refactor!: remove the builtin actions (#1407)

Removes `builtin:checkout`, `builtin:upload-artifact` and `builtin:download-artifact`, along with the container helpers only they used.

Builtin actions are tied to the runner version, so users cannot pin them, and they diverge from the shareable actions ecosystem that tools like zizmor build on. Workflows should use `actions/checkout`, `actions/upload-artifact` and `actions/download-artifact`, or lightweight third-party actions such as https://github.com/taiki-e/checkout-action.

**Breaking:** steps with `uses: builtin:checkout`, released in v4.0.0, now fail and need to switch to one of the actions above. The artifact actions were never released.

Docs: https://gitea.com/gitea/docs/pulls/643
Fixes: https://gitea.com/gitea/runner/issues/1405
Co-authored-by: silverwind <[email protected]>
Reviewed-on: https://gitea.com/gitea/runner/pulls/1407
Reviewed-by: silverwind <[email protected]>
Co-authored-by: bircni <[email protected]>
This commit is contained in:
bircniandsilverwind authored and silverwind committed 2026-11-10 11:05:38 +00:00
1 parent 85d007c47f
commit c59caa9689
54 files changed
+18 -5751

No files matched your search

-5
View File
@@ -51,11 +51,6 @@ fields.
- Tests read what was logged with `logtest.NewLogger()`, or `logtest.SetDefault(t)` for the
package functions.
## Built-in actions
Each lives in `internal/pkg/action/<name>` and is registered in `builtinActions` in
`act/runner/step_action_builtin.go`.
## End-to-end compatibility tests
`make test-e2e` runs the runner against `E2E_GITEA_IMAGE`. It defaults to the nightly image.
-7
View File
@@ -14,9 +14,6 @@ In the job image, or on the host for host jobs:
- `bash` or `sh`, or `pwsh` or `powershell` on Windows.
- `node` for JavaScript actions and `hashFiles()`.
- `git` 2.34.1 or newer for [`builtin:checkout`](docs/builtin-actions.md).
- `git-lfs` for `builtin:checkout` with `lfs: true`.
- `ssh` for `builtin:checkout` with `ssh-key`.
Kubernetes mode needs [a few more tools](docs/kubernetes.md) in job images.
@@ -245,10 +242,6 @@ volumes:
Set `container.sweep: true` to remove the containers, networks and volumes most Linux container jobs create when they end, `docker compose` services included. Leave it off if jobs deploy services to the runner's Docker daemon.
### Built-in actions (`uses: builtin:<name>`)
`uses: builtin:checkout`, `builtin:upload-artifact` and `builtin:download-artifact` replace their `actions/` counterparts without an action download or Node in the job image, see [docs/builtin-actions.md](docs/builtin-actions.md).
### Caching (`actions/cache`)
Each runner runs its own cache server. As on GitHub, a job restores caches of its own ref, its pull request's base branch and the default branch.
+1 -1
View File
@@ -218,7 +218,7 @@ func Serve(ctx context.Context, artifactPath, addr, port string) context.CancelF
logger.Debugf("Artifacts base path '%s'", artifactPath)
uploads(router, artifactPath)
downloads(router, artifactPath)
RegisterV4(router, artifactPath)
registerV4(router, artifactPath)
server := &http.Server{
Addr: net.JoinHostPort(addr, port),
+2 -2
View File
@@ -28,7 +28,7 @@ func TestArtifactFlow(t *testing.T) {
router := http.NewServeMux()
uploads(router, artifactPath)
downloads(router, artifactPath)
RegisterV4(router, artifactPath)
registerV4(router, artifactPath)
server := httptest.NewServer(router)
defer server.Close()
@@ -256,7 +256,7 @@ func TestArtifactFlow(t *testing.T) {
require.Equal(t, "attachment; filename*=UTF-8''50%25%20art%40v1", header.Get("Content-Disposition"))
rerun := http.NewServeMux()
RegisterV4(rerun, artifactPath)
registerV4(rerun, artifactPath)
recorder := httptest.NewRecorder()
rerun.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, artifactServicePath+"/CreateArtifact", strings.NewReader("{"+artifactRef+"}")))
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
+1 -1
View File
@@ -35,7 +35,7 @@ const (
maxTwirpBytes = 1 << 20
)
func RegisterV4(router *http.ServeMux, baseDir string) {
func registerV4(router *http.ServeMux, baseDir string) {
server := &serverV4{dir: filepath.Join(baseDir, "v4"), lastID: time.Now().UnixMilli(), created: map[string]bool{}} // IDs stay unique across invocations sharing baseDir
router.HandleFunc("POST "+artifactServicePath+"/CreateArtifact", twirp(server.createArtifact))
router.HandleFunc("POST "+artifactServicePath+"/FinalizeArtifact", twirp(server.finalizeArtifact))
-35
View File
@@ -5,7 +5,6 @@
package container
import (
"bytes"
"context"
"errors"
"fmt"
@@ -35,38 +34,6 @@ func (e ExitCodeError) Error() string {
return fmt.Sprintf("Process completed with exit code %d.", int(e))
}
type commandOutput struct {
*io.PipeReader
cancel context.CancelFunc
done chan struct{}
err error
}
func (output *commandOutput) Close() error {
_, _ = io.Copy(io.Discard, output.PipeReader)
output.PipeReader.Close()
output.cancel()
<-output.done
return output.err
}
func streamOutput(ctx context.Context, run func(context.Context, io.Writer, io.Writer) error) io.ReadCloser {
ctx, cancel := context.WithCancel(ctx)
reader, writer := io.Pipe()
output := &commandOutput{PipeReader: reader, cancel: cancel, done: make(chan struct{})}
go func() {
defer close(output.done)
defer cancel()
var stderr bytes.Buffer
output.err = run(ctx, writer, &stderr)
if output.err != nil && strings.TrimSpace(stderr.String()) != "" {
output.err = fmt.Errorf("%w: %s", output.err, strings.TrimSpace(stderr.String()))
}
writer.CloseWithError(output.err)
}()
return output
}
// NewContainerInput the input for the New function
type NewContainerInput struct {
Image string
@@ -167,9 +134,7 @@ type Container interface {
Create(capAdd, capDrop []string) common.Executor
Copy(destPath string, files ...*FileEntry) common.Executor
CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor
ExecOutput(ctx context.Context, command []string) (io.ReadCloser, error)
GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error)
CopyTarStream(ctx context.Context, destPath string, write func(*TarWriter) error) error
Inspect(ctx context.Context) (*Info, error)
DumpLogs(ctx context.Context) error
Pull(forcePull bool) common.Executor
-72
View File
@@ -139,47 +139,6 @@ func (cr *containerReference) CopyDir(destPath, srcPath string, useGitIgnore, sk
).IfNot(common.Dryrun)
}
func (cr *containerReference) ExecOutput(ctx context.Context, command []string) (io.ReadCloser, error) {
if common.Dryrun(ctx) {
return nil, errors.New("DRYRUN is not supported in ExecOutput")
}
if err := cr.connect()(ctx); err != nil {
return nil, err
}
if err := cr.find()(ctx); err != nil {
return nil, err
}
if cr.id == "" {
return nil, cr.missingContainerError("exec %v", command)
}
return streamOutput(ctx, func(ctx context.Context, stdout, stderr io.Writer) error {
created, err := cr.cli.ExecCreate(ctx, cr.id, client.ExecCreateOptions{
Cmd: command, AttachStdout: true, AttachStderr: true,
})
if err != nil {
return err
}
attached, err := cr.cli.ExecAttach(ctx, created.ID, client.ExecAttachOptions{})
if err != nil {
return err
}
defer attached.Close()
stop := context.AfterFunc(ctx, func() { attached.Close() })
defer stop()
if _, err := stdcopy.StdCopy(stdout, stderr, attached.Reader); err != nil {
return err
}
inspected, err := cr.cli.ExecInspect(ctx, created.ID, client.ExecInspectOptions{})
if err != nil {
return err
}
if inspected.ExitCode != 0 {
return ExitCodeError(inspected.ExitCode)
}
return nil
}), nil
}
func (cr *containerReference) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
if common.Dryrun(ctx) {
return nil, errors.New("DRYRUN is not supported in GetContainerArchive")
@@ -993,37 +952,6 @@ func (cr *containerReference) extractionRoot(dstPath string) string {
return "/"
}
func (cr *containerReference) CopyTarStream(ctx context.Context, destPath string, write func(*TarWriter) error) error {
if common.Dryrun(ctx) {
return nil
}
if err := cr.connect()(ctx); err != nil {
return err
}
if err := cr.find()(ctx); err != nil {
return err
}
if cr.id == "" {
return cr.missingContainerError("copy to %s", destPath)
}
destPath = path.Clean(destPath)
root := cr.extractionRoot(destPath)
rel := func(fullPath string) string { return strings.TrimPrefix(strings.TrimPrefix(fullPath, root), "/") }
var parents []string // sent as entries so they belong to the job user, the daemon creates missing ones as root
for dir := destPath; dir != root && dir != "/" && dir != "."; dir = path.Dir(dir) {
if _, err := cr.cli.ContainerStatPath(ctx, cr.id, client.ContainerStatPathOptions{Path: dir}); err == nil {
break
} else if !cerrdefs.IsNotFound(err) {
return fmt.Errorf("stat %s: %w", dir, err)
}
parents = append(parents, rel(dir))
}
slices.Reverse(parents)
content := pipeTar(cr.UID, cr.GID, rel(destPath), parents, write)
defer content.Close()
return cr.upload(ctx, root, content)
}
func (cr *containerReference) copyContent(dstPath string, files ...*FileEntry) common.Executor {
return func(ctx context.Context) error {
if cr.id == "" {
-64
View File
@@ -260,28 +260,6 @@ func TestDockerExecFailure(t *testing.T) {
assert.Equal(t, ExitCodeError(1), exitErr)
assert.Equal(t, "Process completed with exit code 1.", err.Error())
client.On("ContainerInspect", ctx, "123", mobyclient.ContainerInspectOptions{}).
Return(mobyclient.ContainerInspectResult{}, nil)
client.On("ExecCreate", mock.Anything, "123", mobyclient.ExecCreateOptions{
Cmd: []string{"printf", `a\b`}, AttachStdout: true, AttachStderr: true,
}).Return(mobyclient.ExecCreateResult{ID: "output"}, nil)
client.On("ExecAttach", mock.Anything, "output", mobyclient.ExecAttachOptions{}).
Return(mobyclient.ExecAttachResult{
Conn: &mockConn{},
Reader: bufio.NewReader(bytes.NewReader(append(stdcopyFrame(stdcopy.Stdout, "a\x00b"), stdcopyFrame(stdcopy.Stderr, " failed \n")...))),
}, nil)
client.On("ExecInspect", mock.Anything, "output", mobyclient.ExecInspectOptions{}).
Return(mobyclient.ExecInspectResult{ExitCode: 3}, nil)
output, err := cr.ExecOutput(ctx, []string{"printf", `a\b`})
require.NoError(t, err)
content, err := io.ReadAll(output)
require.ErrorAs(t, err, &exitErr)
assert.Equal(t, ExitCodeError(3), exitErr)
assert.Equal(t, "Process completed with exit code 3.: failed", err.Error())
assert.Equal(t, "a\x00b", string(content))
require.ErrorAs(t, output.Close(), &exitErr)
assert.Equal(t, ExitCodeError(3), exitErr)
client.AssertExpectations(t)
}
@@ -570,8 +548,6 @@ func TestRejectsMissingContainer(t *testing.T) {
check("exec", cr.exec([]string{"echo"}, nil, "", "")(ctx))
_, err := cr.GetContainerArchive(ctx, "/var/run/act/x")
check("GetContainerArchive", err)
_, err = cr.ExecOutput(ctx, []string{"true"})
check("ExecOutput", err)
_, err = cr.Inspect(ctx)
check("Inspect", err)
@@ -583,46 +559,6 @@ func TestRejectsMissingContainer(t *testing.T) {
check("Inspect after removal", err)
}
func TestCopyTarStreamOwnsMissingParentsAndRejectsEscapes(t *testing.T) {
ctx := t.Context()
client := &mockDockerClient{}
client.On("ContainerInspect", ctx, "job", mobyclient.ContainerInspectOptions{}).
Return(mobyclient.ContainerInspectResult{Container: container.InspectResponse{ID: "job", Name: "/job"}}, nil)
stat := func(p string, err error) {
client.On("ContainerStatPath", ctx, "job", mobyclient.ContainerStatPathOptions{Path: p}).
Return(mobyclient.ContainerStatPathResult{}, err).Once()
}
stat("/w/out/a", cerrdefs.ErrNotFound)
stat("/w/out", cerrdefs.ErrNotFound)
stat("/w", nil)
var entries []string
client.On("CopyToContainer", ctx, "job", mock.Anything).Run(func(args mock.Arguments) {
opts := args.Get(2).(mobyclient.CopyToContainerOptions)
assert.Equal(t, "/", opts.DestinationPath)
reader := tar.NewReader(opts.Content)
for {
header, err := reader.Next()
if errors.Is(err, io.EOF) {
return
}
require.NoError(t, err)
assert.Equal(t, []any{1001, 1002, ""}, []any{header.Uid, header.Gid, header.Uname}, header.Name)
entries = append(entries, header.Name)
}
}).Return(mobyclient.CopyToContainerResult{}, nil).Once()
cr := &containerReference{id: "job", cli: client, input: &NewContainerInput{Name: "job"}, UID: 1001, GID: 1002}
require.NoError(t, cr.CopyTarStream(ctx, "/w/out/a/", func(tw *TarWriter) error {
return tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: "dir/f.txt", Mode: 0o644, Uname: "nobody"})
}))
assert.Equal(t, []string{"w/out/", "w/out/a/", "w/out/a/dir/", "w/out/a/dir/f.txt"}, entries)
client.AssertExpectations(t)
require.ErrorContains(t, writeTarStream(io.Discard, 0, 0, "w/out/a", nil, func(tw *TarWriter) error {
return tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: "../../../etc/passwd"})
}), "escapes")
}
func TestPublicCopyPipelineHandlesStaleID(t *testing.T) {
source := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(source, "x"), nil, 0o644))
-67
View File
@@ -16,7 +16,6 @@ import (
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"sync/atomic"
@@ -116,20 +115,6 @@ func (e *HostEnvironment) Inspect(_ context.Context) (*Info, error) {
return &Info{Health: HealthNone, Ports: map[string]string{}}, nil
}
func (e *HostEnvironment) ExecOutput(ctx context.Context, command []string) (io.ReadCloser, error) {
return streamOutput(ctx, func(ctx context.Context, stdout, stderr io.Writer) error {
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
cmd.Dir, cmd.Stdout, cmd.Stderr = e.Workdir, stdout, stderr
if err := cmd.Run(); err != nil {
if exit, ok := errors.AsType[*exec.ExitError](err); ok {
return ExitCodeError(exit.ExitCode())
}
return err
}
return nil
}), nil
}
func (e *HostEnvironment) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
srcPath = filepath.Clean(srcPath)
fi, err := os.Lstat(srcPath)
@@ -177,58 +162,6 @@ func writeHostArchive(ctx context.Context, tc *filecollector.TarCollector, srcPa
return tc.WriteFile(fi.Name(), fi, linkname, f)
}
func (e *HostEnvironment) CopyTarStream(ctx context.Context, destPath string, write func(*TarWriter) error) error {
if err := os.MkdirAll(destPath, 0o777); err != nil {
return err
}
root, err := os.OpenRoot(destPath)
if err != nil {
return err
}
defer root.Close()
content := pipeTar(0, 0, "", nil, write)
defer content.Close()
tr := tar.NewReader(content)
var dirs []*tar.Header
for {
if err := ctx.Err(); err != nil {
return err
}
hdr, err := tr.Next()
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return err
}
hdr.Name = filepath.FromSlash(strings.TrimSuffix(hdr.Name, "/"))
if hdr.Typeflag == tar.TypeDir {
err = root.MkdirAll(hdr.Name, 0o777) // modes apply after the contents, so read-only directories can be filled
dirs = append(dirs, hdr)
} else {
err = writeRootFile(root, hdr.Name, hdr.FileInfo().Mode().Perm(), tr)
}
if err != nil {
return err
}
}
for _, dir := range slices.Backward(dirs) {
if err := root.Chmod(dir.Name, dir.FileInfo().Mode().Perm()); err != nil {
return err
}
}
return nil
}
func writeRootFile(root *os.Root, name string, mode fs.FileMode, body io.Reader) error {
_ = root.Remove(name) // replaces read-only files and applies mode, as the daemon and tar do
file, err := root.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
if err != nil {
return err
}
_, err = io.Copy(file, body)
return errors.Join(err, file.Close())
}
func (e *HostEnvironment) Pull(_ bool) common.Executor {
return common.NewPipelineExecutor()
}
-59
View File
@@ -8,7 +8,6 @@ import (
"archive/tar"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
@@ -84,69 +83,11 @@ func TestGetContainerArchive(t *testing.T) {
assert.ErrorIs(t, err, os.ErrNotExist)
}
func TestHostCopyTarStream(t *testing.T) {
dest := filepath.Join(t.TempDir(), "out")
write := func(name string, mode int64, body string) func(*TarWriter) error {
return func(tw *TarWriter) error {
if err := tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: name, Mode: mode, Size: int64(len(body))}); err != nil {
return err
}
_, err := tw.Write([]byte(body))
return err
}
}
e := &HostEnvironment{}
require.NoError(t, e.CopyTarStream(t.Context(), dest, write("dir/run.sh", 0o755, "#!/bin/sh\n")))
content, err := os.ReadFile(filepath.Join(dest, "dir", "run.sh"))
require.NoError(t, err)
assert.Equal(t, "#!/bin/sh\n", string(content))
if runtime.GOOS != "windows" {
require.NoError(t, os.Chmod(filepath.Join(dest, "dir", "run.sh"), 0o444))
require.NoError(t, e.CopyTarStream(t.Context(), dest, func(tw *TarWriter) error {
if err := tw.WriteHeader(&tar.Header{Typeflag: tar.TypeDir, Name: "dir/", Mode: 0o555}); err != nil {
return err
}
return write("dir/run.sh", 0o755, "")(tw)
}))
t.Cleanup(func() { require.NoError(t, os.Chmod(filepath.Join(dest, "dir"), 0o755)) })
for name, mode := range map[string]os.FileMode{"dir": 0o555, filepath.Join("dir", "run.sh"): 0o755} {
info, err := os.Stat(filepath.Join(dest, name))
require.NoError(t, err)
assert.Equal(t, mode, info.Mode().Perm(), name)
}
require.NoError(t, os.Symlink(t.TempDir(), filepath.Join(dest, "link")))
require.ErrorContains(t, e.CopyTarStream(t.Context(), dest, write("link/x", 0o644, "x")), "escapes")
}
require.ErrorContains(t, e.CopyTarStream(t.Context(), dest, write("../escape", 0o644, "x")), "escapes")
assert.NoFileExists(t, filepath.Join(filepath.Dir(dest), "escape"))
require.Error(t, e.CopyTarStream(t.Context(), dest, func(_tw *TarWriter) error { return fmt.Errorf("read body: %w", io.EOF) }))
canceled, cancel := context.WithCancel(t.Context())
cancel()
require.ErrorIs(t, e.CopyTarStream(canceled, dest, write("late", 0o644, "x")), context.Canceled)
assert.NoFileExists(t, filepath.Join(dest, "late"))
}
func TestHostEnvironmentExecExitCode(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("uses POSIX shell")
}
for _, read := range []bool{true, false} {
output, err := (&HostEnvironment{AllocatePTY: true}).ExecOutput(t.Context(), []string{"sh", "-c", `test ! -t 1; printf 'out\000'; printf ' failed \n' >&2; exit 3`})
require.NoError(t, err)
if read {
content, err := io.ReadAll(output)
var exit ExitCodeError
require.ErrorAs(t, err, &exit)
assert.Equal(t, ExitCodeError(3), exit)
assert.Equal(t, "out\x00", string(content))
assert.Equal(t, "Process completed with exit code 3.: failed", err.Error())
}
var exit ExitCodeError
require.ErrorAs(t, output.Close(), &exit)
assert.Equal(t, ExitCodeError(3), exit)
}
for name, allocatePTY := range map[string]bool{"without PTY": false, "with PTY": true} {
t.Run(name, func(t *testing.T) {
t.Parallel()
+10 -14
View File
@@ -553,10 +553,6 @@ func (c *kubernetesContainer) Copy(destPath string, files ...*FileEntry) common.
}
}
func (c *kubernetesContainer) CopyTarStream(ctx context.Context, destPath string, write func(*TarWriter) error) error {
return c.extract(ctx, destPath, true, func(writer io.Writer) error { return writeTarStream(writer, 0, 0, "", nil, write) }) // streams carry large content like artifacts
}
func (c *kubernetesContainer) CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
return func(ctx context.Context) error {
return c.extract(ctx, destPath, true, func(writer io.Writer) error { // directories are actions and workspaces, megabytes of compressible sources
@@ -565,17 +561,17 @@ func (c *kubernetesContainer) CopyDir(destPath, srcPath string, useGitIgnore, sk
}
}
func (c *kubernetesContainer) ExecOutput(ctx context.Context, command []string) (io.ReadCloser, error) {
return streamOutput(ctx, func(ctx context.Context, stdout, stderr io.Writer) error {
return c.pod.client.exec(ctx, c.pod.name, c.name, command, nil, stdout, stderr)
}), nil
}
// GetContainerArchive streams the archive, checking the path first as tar writes an empty archive for a missing one.
func (c *kubernetesContainer) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
reader, err := c.ExecOutput(ctx, []string{"sh", "-c", `test -e "$1" -o -L "$1" && exec tar -cf - -C "$2" "$3"`, "sh", srcPath, path.Dir(srcPath), path.Base(srcPath)})
if err != nil {
return nil, err
}
reader, writer := io.Pipe()
go func() {
var stderr bytes.Buffer
err := c.pod.client.exec(ctx, c.pod.name, c.name, []string{"sh", "-c", `test -e "$1" -o -L "$1" && exec tar -cf - -C "$2" "$3"`, "sh", srcPath, path.Dir(srcPath), path.Base(srcPath)}, nil, writer, &stderr)
if err != nil {
err = fmt.Errorf("archive %s: %w: %s", srcPath, err, strings.TrimSpace(stderr.String()))
}
writer.CloseWithError(err)
}()
return startedArchive(reader)
}
+1 -24
View File
@@ -273,17 +273,6 @@ func TestKubernetesPodRunsJobThroughAPI(t *testing.T) {
assert.Equal(t, "hunter2\nit's\nme\n5\n"+workdir+"\n", jobLog.String())
assert.Equal(t, ExitCodeError(3), job.Exec([]string{"sh", "-c", "echo failing >&2; exit 3"}, nil, "", "")(ctx))
assert.Contains(t, jobLog.String(), "failing\n")
output, err := job.ExecOutput(ctx, []string{"sh", "-c", `printf 'out\000'; printf ' failed \n' >&2; exit 3`})
require.NoError(t, err)
content, err := io.ReadAll(output)
var exit ExitCodeError
require.ErrorAs(t, err, &exit)
assert.Equal(t, ExitCodeError(3), exit)
assert.Contains(t, err.Error(), ": failed")
assert.Equal(t, "out\x00", string(content))
require.ErrorAs(t, output.Close(), &exit)
assert.Equal(t, ExitCodeError(3), exit)
for _, query := range cluster.requests["exec"] {
assert.NotContains(t, query, "hunter2")
}
@@ -296,7 +285,7 @@ func TestKubernetesPodRunsJobThroughAPI(t *testing.T) {
reader := tar.NewReader(archive)
header, err := reader.Next()
require.NoError(t, err)
content, err = io.ReadAll(reader)
content, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, "event.json", header.Name)
assert.JSONEq(t, `{"ref":"main"}`, string(content))
@@ -320,18 +309,6 @@ func TestKubernetesPodRunsJobThroughAPI(t *testing.T) {
assert.Contains(t, lastExec(), "command="+url.QueryEscape(workdir+"/act/actions/sha/"))
assert.Contains(t, lastExec(), url.QueryEscape("gzip -dc |"))
require.NoError(t, job.CopyTarStream(ctx, workdir+"/download/new", func(tw *TarWriter) error {
if err := tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: "dir/data.txt", Mode: 0o644, Size: 7}); err != nil {
return err
}
_, err := tw.Write([]byte("payload"))
return err
}))
downloaded, err := os.ReadFile(workdir + "/download/new/dir/data.txt")
require.NoError(t, err)
assert.Equal(t, "payload", string(downloaded))
assert.Contains(t, lastExec(), url.QueryEscape("gzip -dc |"))
pathEnv := map[string]string{}
require.NoError(t, job.UpdateFromImageEnv(&pathEnv)(ctx))
assert.Equal(t, path, pathEnv["PATH"])
+1 -70
View File
@@ -8,11 +8,7 @@ import (
"archive/tar"
"bufio"
"context"
"errors"
"fmt"
"io"
"io/fs"
"path"
"path/filepath"
"strings"
@@ -20,73 +16,8 @@ import (
"gitea.com/gitea/runner/act/filecollector"
)
// TarWriter takes directories and files named relative to the destination, owned by the job user.
type TarWriter struct {
writer *tar.Writer
uid, gid int
prefix string
dirs map[string]bool
}
func (w *TarWriter) Write(data []byte) (int, error) {
return w.writer.Write(data)
}
func (w *TarWriter) WriteHeader(hdr *tar.Header) error {
name := strings.TrimSuffix(hdr.Name, "/")
if !fs.ValidPath(name) {
return fmt.Errorf("tar entry %q escapes the destination", hdr.Name)
}
if hdr.Typeflag != tar.TypeDir && hdr.Typeflag != tar.TypeReg {
return fmt.Errorf("tar entry %q: unsupported type %q", hdr.Name, hdr.Typeflag)
}
for index := range len(name) {
if dir := name[:index]; name[index] == '/' && !w.dirs[dir] {
if err := w.write(&tar.Header{Typeflag: tar.TypeDir, Name: path.Join(w.prefix, dir), Mode: 0o755}); err != nil {
return err
}
w.dirs[dir] = true
}
}
if hdr.Typeflag == tar.TypeDir {
w.dirs[name] = true
}
entry := *hdr
entry.Name = path.Join(w.prefix, name)
return w.write(&entry)
}
func (w *TarWriter) write(hdr *tar.Header) error {
hdr.Uid, hdr.Gid, hdr.Uname, hdr.Gname = w.uid, w.gid, "", "" // tar running as root prefers names over ids
if hdr.Typeflag == tar.TypeDir {
hdr.Name += "/"
}
return w.writer.WriteHeader(hdr)
}
func writeTarStream(dst io.Writer, uid, gid int, prefix string, parents []string, write func(*TarWriter) error) error {
tw := &TarWriter{writer: tar.NewWriter(dst), uid: uid, gid: gid, prefix: prefix, dirs: map[string]bool{}}
for _, name := range parents {
if err := tw.write(&tar.Header{Typeflag: tar.TypeDir, Name: name, Mode: 0o755}); err != nil {
return err
}
}
if err := write(tw); errors.Is(err, io.EOF) {
return fmt.Errorf("tar stream: %v", err) // %v, as a wrapped io.EOF reads as the archive's end
} else if err != nil {
return err
}
return tw.writer.Close()
}
func pipeTar(uid, gid int, prefix string, parents []string, write func(*TarWriter) error) *io.PipeReader {
reader, writer := io.Pipe()
go func() { writer.CloseWithError(writeTarStream(writer, uid, gid, prefix, parents, write)) }()
return reader
}
// startedArchive returns reader once its first byte arrives, so failing to start archiving errors here, not on read.
func startedArchive(reader io.ReadCloser) (io.ReadCloser, error) {
func startedArchive(reader *io.PipeReader) (io.ReadCloser, error) {
buffered := bufio.NewReader(reader)
if _, err := buffered.Peek(1); err != nil {
reader.Close()
-20
View File
@@ -11,8 +11,6 @@ import (
"gitea.com/gitea/runner/act/common/git"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/act/common/logging/logtest"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.dev/actionslib/pkg/model"
"github.com/stretchr/testify/assert"
@@ -184,21 +182,3 @@ func newTestCompositeRunContext(t *testing.T, parent *RunContext) *RunContext {
require.NoError(t, err)
return composite
}
func TestBuiltinActionGetsLowercaseInputsAndTheJobTokenInComposites(t *testing.T) {
job := makeTestRC(t, "runs-on: ubuntu-latest")
job.Config.Secrets = map[string]string{"ACTIONS_RUNTIME_TOKEN": "daemon-token"}
job.JobContainer = &container.HostEnvironment{Path: t.TempDir(), ActPath: t.TempDir(), Workdir: t.TempDir()}
composite := newTestCompositeRunContext(t, job)
composite.JobContainer = job.JobContainer
for _, rc := range []*RunContext{job, composite} {
var got *action.Context
sab := &stepActionBuiltin{Step: &model.Step{ID: "x", With: map[string]string{"Name": "x"}}, RunContext: rc, run: func(_ctx context.Context, c *action.Context) error {
got = c
return nil
}}
require.NoError(t, sab.main()(t.Context()))
assert.Equal(t, "daemon-token", got.RuntimeToken)
assert.Equal(t, map[string]string{"name": "x"}, got.Inputs)
}
}
-10
View File
@@ -66,12 +66,6 @@ func (cm *containerMock) Exec(command []string, env map[string]string, user, wor
return cm.Called(command, env, user, workdir).Get(0).(func(context.Context) error)
}
func (cm *containerMock) ExecOutput(ctx context.Context, command []string) (io.ReadCloser, error) {
args := cm.Called(ctx, command)
output, _ := args.Get(0).(io.ReadCloser)
return output, args.Error(1)
}
func (cm *containerMock) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
args := cm.Called(ctx, srcPath)
err, _ := args.Get(1).(error)
@@ -89,10 +83,6 @@ func (cm *containerMock) Inspect(ctx context.Context) (*container.Info, error) {
return info, err
}
func (cm *containerMock) CopyTarStream(ctx context.Context, destPath string, write func(*container.TarWriter) error) error {
return cm.Called(ctx, destPath, write).Error(0)
}
func (cm *containerMock) ReplaceLogWriter(stdout, stderr io.Writer) (io.Writer, io.Writer) {
args := cm.Called(stdout, stderr)
return args.Get(0).(io.Writer), args.Get(1).(io.Writer)
-5
View File
@@ -71,11 +71,6 @@ func (c *hookContainer) UpdateFromEnv(_ string, env *map[string]string) common.E
}
}
func (c *hookContainer) ExecOutput(_ctx context.Context, command []string) (io.ReadCloser, error) {
c.cmd = command
return io.NopCloser(bytes.NewBufferString(c.output)), c.err
}
func (c *hookContainer) GetContainerArchive(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(c.pathTar)), nil
}
-1
View File
@@ -81,7 +81,6 @@ type Config struct {
PlatformPicker func(labels []string) string
KubernetesPicker func(labels []string) container.KubernetesOptions
InstanceTransport http.RoundTripper
ResultsURL string // the results service as the runner reaches it, never the job's ACTIONS_RESULTS_URL, which a step can rewrite
JobLoggerLevel *logging.Level // the level of job logger
ValidVolumes []string // only volumes (and bind mounts) in this slice can be mounted on the job container or service containers
ContainerVolumes []string // mounted into every job, service and docker action container
-1
View File
@@ -455,7 +455,6 @@ func TestRunEventHostEnvironment(t *testing.T) {
{workdir, "nix-prepend-path", "push", "", platforms, secrets},
{workdir, "uses-docker-url", "push", "", platforms, secrets},
{workdir, "local-action-dockerfile", "push", "", platforms, secrets},
{workdir, "builtin-checkout", "push", "", platforms, secrets},
{workdir, "inputs-via-env-context", "push", "", platforms, secrets},
{workdir, "do-not-leak-step-env-in-composite", "push", "", platforms, secrets},
{workdir, "set-env-step-env-override", "push", "", platforms, secrets},
-87
View File
@@ -1,87 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package runner
import (
"cmp"
"context"
"fmt"
"strings"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.com/gitea/runner/internal/pkg/action/checkout"
"gitea.com/gitea/runner/internal/pkg/action/downloadartifact"
"gitea.com/gitea/runner/internal/pkg/action/uploadartifact"
"gitea.dev/actionslib/pkg/model"
)
var builtinActions = map[string]func(context.Context, *action.Context) error{
"checkout": checkout.Main,
"download-artifact": downloadartifact.Main,
"upload-artifact": uploadartifact.Main,
}
type stepActionBuiltin struct {
Step *model.Step
RunContext *RunContext
run func(context.Context, *action.Context) error
env map[string]string
}
func (sab *stepActionBuiltin) pre() common.Executor { return common.NewPipelineExecutor() }
func (sab *stepActionBuiltin) main() common.Executor {
sab.env = map[string]string{}
return runStepExecutor(sab, stepStageMain, func(ctx context.Context) error {
if common.Dryrun(ctx) {
return nil
}
printRunActionHeader(ctx, sab.Step, nil, sab.env, sab.RunContext)
rawLogger := common.Logger(ctx).With(rawOutputField, true)
rc := sab.RunContext
rc.ApplyExtraPath(ctx, &sab.env)
inputs := make(map[string]string, len(sab.Step.With))
for name, value := range sab.Step.With {
inputs[strings.ToLower(name)] = value // input names are case-insensitive on GitHub
}
return sab.run(ctx, &action.Context{
Container: rc.JobContainer,
Github: getStepGithubContext(ctx, sab),
Inputs: inputs,
HostWorkdir: rc.Config.Workdir,
Workspace: rc.JobContainer.ToContainerPath(rc.Config.Workdir),
BindWorkdir: rc.Config.BindWorkdir,
NoSkipCheckout: rc.Config.NoSkipCheckout,
UseGitIgnore: rc.Config.UseGitIgnore,
InsecureSkipTLS: rc.Config.InsecureSkipTLS,
ClientCertFile: rc.Config.ClientCertFile,
ClientKeyFile: rc.Config.ClientKeyFile,
CAFile: rc.jobCAFile(),
Env: sab.env,
ResultsURL: rc.Config.ResultsURL,
RuntimeToken: cmp.Or(rc.runtimeToken, rc.topLevelRunContext().Config.Secrets["ACTIONS_RUNTIME_TOKEN"]), // composite contexts have no secrets
Transport: rc.Config.InstanceTransport,
Infof: rawLogger.Infof,
Warning: func(format string, args ...any) {
rawLogger.Infof("%s", formatAnnotation("warning", nil, fmt.Sprintf(format, args...)))
},
})
})
}
func (sab *stepActionBuiltin) post() common.Executor { return common.NewPipelineExecutor() }
func (sab *stepActionBuiltin) getRunContext() *RunContext { return sab.RunContext }
func (sab *stepActionBuiltin) getStepModel() *model.Step { return sab.Step }
func (sab *stepActionBuiltin) getEnv() *map[string]string { return &sab.env }
func (sab *stepActionBuiltin) getIfExpression(_ context.Context, _ stepStage) string {
return sab.Step.If.Value
}
-15
View File
@@ -6,9 +6,6 @@ package runner
import (
"fmt"
"maps"
"slices"
"strings"
"gitea.dev/actionslib/pkg/model"
)
@@ -36,18 +33,6 @@ func (sf *stepFactoryImpl) newStep(stepModel *model.Step, rc *RunContext) (step,
runAction: runActionImpl,
}, nil
case model.StepTypeUsesActionRemote:
if name, ok := strings.CutPrefix(stepModel.Uses, "builtin:"); ok {
run, ok := builtinActions[name]
if !ok {
return nil, fmt.Errorf("unknown built-in action %q (known: %v) for job:%s step:%+v",
name, slices.Sorted(maps.Keys(builtinActions)), rc.Name, stepModel)
}
return &stepActionBuiltin{
Step: stepModel,
RunContext: rc,
run: run,
}, nil
}
return &stepActionRemote{
Step: stepModel,
RunContext: rc,
-2
View File
@@ -22,7 +22,6 @@ func TestStepFactoryNewStep(t *testing.T) {
{"StepLocalAction", &model.Step{Uses: "./action@v1"}, &stepActionLocal{}},
{"StepDocker", &model.Step{Uses: "docker://image:tag"}, &stepDocker{}},
{"StepRun", &model.Step{Run: "cmd"}, &stepRun{}},
{"StepBuiltinAction", &model.Step{Uses: "builtin:checkout"}, &stepActionBuiltin{}},
} {
t.Run(test.name, func(t *testing.T) {
step, err := (&stepFactoryImpl{}).newStep(test.model, &RunContext{})
@@ -35,7 +34,6 @@ func TestStepFactoryNewStep(t *testing.T) {
func TestStepFactoryInvalidStep(t *testing.T) {
for _, stepModel := range []*model.Step{
{Uses: "remote/action@v1", Run: "cmd"},
{Uses: "builtin:unknown"},
} {
_, err := (&stepFactoryImpl{}).newStep(stepModel, &RunContext{Name: "build"})
assert.ErrorContains(t, err, "job:build ", stepModel.Uses)
-10
View File
@@ -1,10 +0,0 @@
name: builtin-checkout
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: builtin:checkout
with:
path: ${{ 'sub' }}
- run: test -f sub/builtin-checkout/push.yml
-85
View File
@@ -1,85 +0,0 @@
# Built-in actions
Built-in actions ship with the runner, so a job needs no action download and no Node in its image.
```yaml
- uses: builtin:checkout
- uses: builtin:upload-artifact
- uses: builtin:download-artifact
```
## checkout
Works like `actions/checkout` with these inputs. Any other input fails the step. It runs `git` where the job runs, see the [prerequisites](../README.md#prerequisites).
| Input | Default |
| --- | --- |
| `repository` | `github.repository` |
| `ref` | the triggering ref and commit, or the default branch of another repository |
| `token` | `github.token` |
| `ssh-key` | empty, a private key fetches over SSH instead |
| `ssh-known-hosts` | empty, host keys trusted besides `~/.ssh/known_hosts` |
| `ssh-strict` | `true`, rejects unknown host keys |
| `ssh-user` | the user of the repository's SSH URL, else `git` |
| `persist-credentials` | `true`, later steps of the job can fetch and push with `token` or `ssh-key` |
| `path` | workspace root |
| `clean` | `true`, removes untracked files, also in submodules |
| `filter` | empty, a partial clone filter such as `blob:none` |
| `sparse-checkout` | empty, the paths to check out, one per line |
| `sparse-checkout-cone-mode` | `true`, `false` reads `sparse-checkout` as patterns |
| `fetch-depth` | `1`, `0` for the full history of every branch and tag |
| `fetch-tags` | `false`, `true` fetches every tag |
| `show-progress` | `true`, shows the fetch progress |
| `lfs` | `false`, `true` downloads Git LFS files |
| `submodules` | `false`, `true` checks out submodules, `recursive` also theirs |
| `set-safe-directory` | `true`, lets checkout's `git` work in a directory another user owns |
A branch is checked out as a local branch tracking `origin`, a tag or commit as a detached `HEAD`. A triggering tag that moved since the event fails the step. The step outputs `ref` and `commit` like `actions/checkout`.
Persisted credentials end with the job. `token` is only sent to `github.server_url`, while `ssh-key` is offered to any SSH host, as with `actions/checkout`. The runner's `client_cert_file` is only offered to `github.server_url` and only during the step, so later steps do not get it. Its `ca_file` replaces the job image's CA bundle for `github.server_url`, in later steps too when credentials persist. Without `ssh-key`, submodule URLs of the form `git@<server host>:` are fetched from `github.server_url` with `token`. With `ssh-key`, the repository is fetched from the SSH URL in the event's `repository.ssh_url`, or from the server's host on port 22.
With `gitea-runner exec`, checking out the workflow's own repository copies your local working directory, unless `--no-skip-checkout` or `ssh-key` is set.
## upload-artifact
Works like `actions/upload-artifact` v7 with these inputs. Any other input logs a warning, as on GitHub. It needs Gitea 1.22.4 or later, and 1.26 for `archive: false`.
| Input | Default |
| --- | --- |
| `name` | `artifact`, ignored with `archive: false`, which names the artifact after the file |
| `path` | required, files, directories or patterns, one per line, `!` excludes |
| `if-no-files-found` | `warn`, also `error` or `ignore` |
| `retention-days` | the server's default, at most the repository's retention limit |
| `compression-level` | `6`, from `0` for none to `9` |
| `overwrite` | `false`, `true` deletes an artifact of the same name first |
| `include-hidden-files` | `false`, `true` uploads files and directories whose name starts with `.` |
| `archive` | `true`, `false` uploads a single file as is |
Patterns, symlinks and the artifact's root directory follow `actions/upload-artifact`. `ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY` sets upload concurrency (default `5`), and `ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS` sets the upload stall timeout (default `300000`). The step outputs `artifact-id`, `artifact-digest` and `artifact-url`. On Gitea 1.26 and later, the `artifact-url` is the artifact's link on the run page for this attempt, where `actions/upload-artifact` gives a link only GitHub serves.
Container jobs list the search paths in the job container and transfer only the selected files, gzipped when the image has gzip, requiring `sh`, `find` and `tar` in the image. On Kubernetes these files still pass through the API server, unlike `actions/upload-artifact`, which uploads from the pod.
## download-artifact
Works like `actions/download-artifact` v8 with these inputs. Any other input logs a warning, as on GitHub.
| Input | Default |
| --- | --- |
| `name` | empty, every artifact of the run |
| `artifact-ids` | empty, comma-separated IDs instead of `name` |
| `path` | workspace root, `~` is the job user's home |
| `pattern` | empty, a glob the artifact names must match, without the extglobs and brace ranges of minimatch, ignored with `name` or `artifact-ids` |
| `merge-multiple` | `false`, several artifacts go to `path/<name>`, `true` puts them all in `path` |
| `github-token` | empty, a token to download from another run or repository |
| `repository` | `github.repository`, with `github-token` |
| `run-id` | `github.run_id`, with `github-token` |
| `skip-decompress` | `false`, `true` keeps a zipped artifact as `<name>.zip` |
| `digest-mismatch` | `error`, also `ignore`, `info` or `warn` |
ZIP entries become regular files with current modification times, so files lose their executable bit and symlinks become files containing their targets. `digest-mismatch` only applies when the server reports a digest, which Gitea does not. The step outputs `download-path`.
The runner downloads each artifact to a temporary file on the runner because the zip is read out of order, then streams the files into the job container. On Kubernetes, the stream goes through the API server, gzipped when the image has gzip, or over the pod network with `kubernetes.transfer.mode` set to `auto` or `direct`, while `actions/download-artifact` downloads from the pod directly.
`github-token` needs Gitea 1.24 or later and is only sent to the instance the runner is registered with. Downloads from another run paginate through its artifacts and skip expired ones, where `actions/download-artifact` sees only Gitea's first 30 and fails on an expired newest copy. `run-id` must be positive, since Gitea treats nonpositive IDs as a request for artifacts from every run. Artifact names and ZIP entries that would leave the destination are rejected.
With `gitea-runner exec`, both actions use the local artifact server of `--artifact-server-path`, which serves no other runs for `github-token`.
-22
View File
@@ -1,22 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build e2e
package e2e
import "testing"
func testBuiltinCheckout(t *testing.T) {
t.Parallel()
api, repo := newScenario(t)
pushWorkflow(t, api, repo, "checkout.yml")
branchRun := waitForRun(t, api, repo)
if err := api.CreateTag(t.Context(), repo, "v1"); err != nil {
t.Fatalf("create tag: %v", err)
}
tagRun := waitForRunAfter(t, api, repo, branchRun.ID)
requireSuccess(t, api, repo, branchRun.ID)
requireSuccess(t, api, repo, tagRun.ID)
}
-1
View File
@@ -29,7 +29,6 @@ func TestCompatibility(t *testing.T) {
t.Run("cache_and_artifacts", testCacheAndArtifactRoundTrips)
t.Run("cancellation_and_log_streaming", testRunCancellation)
t.Run("dispatch", inAllModes(testWorkflowDispatch))
t.Run("builtin_checkout", testBuiltinCheckout)
t.Run("exec_artifacts", testExecArtifacts)
t.Run("moving_action_ref", testMovingActionRef)
t.Run("ephemeral", testEphemeralRunner)
-6
View File
@@ -65,12 +65,6 @@ func (a *GiteaAPI) CreateFiles(ctx context.Context, repo string, files map[strin
return a.doJSON(ctx, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/contents", giteaAdminUser, repo), body, nil)
}
func (a *GiteaAPI) CreateTag(ctx context.Context, repo, name string) error {
body := map[string]any{"tag_name": name}
url := fmt.Sprintf("/api/v1/repos/%s/%s/tags", giteaAdminUser, repo)
return a.doJSON(ctx, http.MethodPost, url, body, nil)
}
func (a *GiteaAPI) CreateSecret(ctx context.Context, repo, name, value string) error {
body := map[string]any{"data": value}
url := fmt.Sprintf("/api/v1/repos/%s/%s/actions/secrets/%s", giteaAdminUser, repo, name)
-1
View File
@@ -111,7 +111,6 @@ func StartGitea(ctx context.Context, cli mobyclient.APIClient) (_ *GiteaFixture,
"GITEA__security__INSTALL_LOCK=true",
"GITEA__database__DB_TYPE=sqlite3",
"GITEA__actions__ENABLED=true",
"GITEA__server__LFS_START_SERVER=true",
"GITEA__server__ROOT_URL=" + baseURL + "/",
},
},
-49
View File
@@ -26,52 +26,3 @@ jobs:
name: e2e-artifact-${{ github.run_id }}
path: got
- run: grep -q artifact-payload got/data.txt
builtin-upload:
runs-on: e2e-artifact
steps:
- run: |
mkdir -p out/sub
echo "builtin-payload" > out/data.txt
echo "nested" > out/sub/nested.txt
echo "hidden" > out/.hidden
echo "raw" > report.txt
- id: zipped
uses: builtin:upload-artifact
with:
name: e2e-builtin-${{ github.run_id }}
path: out
- run: test -n "${{ steps.zipped.outputs.artifact-id }}" && test -n "${{ steps.zipped.outputs.artifact-digest }}"
- uses: builtin:upload-artifact
with:
path: report.txt
archive: false
js-downloads-builtin:
needs: builtin-upload
runs-on: e2e-artifact
steps:
- uses: actions/download-artifact@v8
with:
name: e2e-builtin-${{ github.run_id }}
path: got
- run: grep -q builtin-payload got/data.txt && grep -q nested got/sub/nested.txt && test ! -e got/.hidden
- uses: actions/download-artifact@v8
with:
name: report.txt
- run: grep -q raw report.txt
builtin-downloads-js:
needs: upload
runs-on: e2e-artifact
steps:
- id: own
uses: builtin:download-artifact
with:
name: e2e-artifact-${{ github.run_id }}
path: got
- run: grep -q artifact-payload got/data.txt && test "${{ steps.own.outputs.download-path }}" = "$GITHUB_WORKSPACE/got"
- uses: builtin:download-artifact
with:
name: e2e-artifact-${{ github.run_id }}
path: rest
github-token: ${{ github.token }}
run-id: ${{ github.run_id }}
- run: grep -q artifact-payload rest/data.txt
-61
View File
@@ -1,61 +0,0 @@
name: checkout
on: push
jobs:
checkout:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- id: checkout
uses: builtin:checkout
- uses: builtin:checkout
with:
ref: ${{ github.ref_name }}
path: short
- run: test "$(git -C short rev-parse HEAD)" = "$GITHUB_SHA"
- if: github.ref_type == 'branch'
run: |
test "$(git symbolic-ref HEAD)" = "$GITHUB_REF"
test "${{ steps.checkout.outputs.ref }}" = "$GITHUB_REF"
test "${{ steps.checkout.outputs.commit }}" = "$GITHUB_SHA"
git -c user.name=e2e -c [email protected] commit --allow-empty -m pushed
git push
git tag moved
git push --force origin moved
git switch --orphan child
echo child > child.txt
git add child.txt
git -c user.name=e2e -c [email protected] commit -m child
git push origin child
git switch -c content main
git submodule add -b child "../${{ github.event.repository.name }}.git" sub
git lfs install --local
git lfs track '*.bin'
mkdir keep drop
echo big > keep/big.bin
echo big > drop/big.bin
git add .gitattributes keep drop
git -c user.name=e2e -c [email protected] commit -m content
git push origin content
- if: github.ref_type == 'branch'
uses: builtin:checkout
with:
ref: content
path: full
submodules: true
lfs: true
- if: github.ref_type == 'branch'
uses: builtin:checkout
with:
ref: content
path: sparse
sparse-checkout: keep
lfs: true
- if: github.ref_type == 'branch'
run: |
test "$(cat full/sub/child.txt)" = child
test "$(cat full/keep/big.bin)" = big
test "$(cat sparse/keep/big.bin)" = big
test ! -e sparse/drop
- if: github.ref_type == 'tag'
run: test "$(git describe --tags)" = "$GITHUB_REF_NAME"
+1 -6
View File
@@ -213,10 +213,6 @@ func parseKVAndFile(rawKVs []string, filePath string) map[string]string {
return result
}
func (i *executeArgs) artifactServerURL() string {
return "http://" + net.JoinHostPort(i.artifactServerAddr, i.artifactServerPort)
}
// Workdir returns path to workdir
func (i *executeArgs) Workdir() string {
return i.resolve(".")
@@ -390,7 +386,6 @@ func (i *executeArgs) runnerConfig(eventName string, env, proxyEnv map[string]st
ArtifactServerPath: i.artifactServerPath,
ArtifactServerPort: i.artifactServerPort,
ArtifactServerAddr: i.artifactServerAddr,
ResultsURL: i.artifactServerURL(),
NoSkipCheckout: i.noSkipCheckout,
EventName: eventName,
EventJSON: eventJSON,
@@ -522,7 +517,7 @@ func runExec(ctx context.Context, execArgs *executeArgs) func(cmd *cobra.Command
token := cmp.Or(inheritedToken, artifacts.LocalRuntimeToken(workflowRun, maxLifetime))
config.RuntimeTokens[run.Workflow] = token
config.ExtraMasks = append(config.ExtraMasks, token)
handler.RegisterJob(token, artifactcache.JobCredential{Repo: "__local/__exec", Results: execArgs.artifactServerURL()})
handler.RegisterJob(token, artifactcache.JobCredential{Repo: "__local/__exec", Results: "http://" + net.JoinHostPort(execArgs.artifactServerAddr, execArgs.artifactServerPort)})
}
}
-1
View File
@@ -628,7 +628,6 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
ClientKeyFile: r.cfg.Runner.ClientKeyFile,
CAFile: r.cfg.Runner.CAFile,
InstanceTransport: r.instanceTransport,
ResultsURL: strings.TrimSuffix(r.client.Address(), "/"),
RunnerName: r.name,
KubernetesPicker: r.kubernetesOptions,
}
-174
View File
@@ -1,174 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// Package action holds the native actions run by `uses: builtin:<name>`.
package action
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"unicode"
"gitea.com/gitea/runner/act/container"
"gitea.dev/actionslib/pkg/model"
)
type Context struct {
Container container.ExecutionsEnvironment
Github *model.GithubContext
Inputs map[string]string
HostWorkdir string
Workspace string // HostWorkdir as seen inside Container
BindWorkdir bool
NoSkipCheckout bool
UseGitIgnore bool
InsecureSkipTLS bool
ClientCertFile string
ClientKeyFile string
CAFile string // the runner CA as seen inside Container
Env map[string]string
ResultsURL string // the results service as the runner reaches it
RuntimeToken string
Transport http.RoundTripper // carries the instance's TLS settings, nil for the default
Infof func(format string, args ...any)
Warning func(format string, args ...any)
}
func (c *Context) ApplyDefaults(pairs ...string) {
var valid, unexpected []string
for i := 0; i+1 < len(pairs); i += 2 {
valid = append(valid, pairs[i])
if _, set := c.Inputs[pairs[i]]; !set && pairs[i+1] != "" {
c.Inputs[pairs[i]] = pairs[i+1]
}
}
for name := range c.Inputs {
if !slices.Contains(valid, name) {
unexpected = append(unexpected, name)
}
}
if len(unexpected) > 0 {
slices.Sort(unexpected)
c.Warning("Unexpected input(s) '%s', valid inputs are ['%s']", strings.Join(unexpected, "', '"), strings.Join(valid, "', '"))
}
}
// Input is the trimmed input, as @actions/core getInput returns it.
func (c *Context) Input(name string) string {
return strings.TrimSpace(c.Inputs[name])
}
// BoolInput accepts what @actions/core getBooleanInput does.
func (c *Context) BoolInput(name string) (bool, error) {
switch c.Input(name) {
case "true", "True", "TRUE":
return true, nil
case "false", "False", "FALSE":
return false, nil
}
return false, Failf("Input does not meet YAML 1.2 \"Core Schema\" specification: %s\nSupport boolean input list: `true | True | TRUE | false | False | FALSE`", name)
}
func (c *Context) SetOutputs(ctx context.Context, pairs ...string) error {
output := c.Env["GITHUB_OUTPUT"]
if output == "" {
return nil
}
var body strings.Builder
for i := 0; i+1 < len(pairs); i += 2 {
if strings.ContainsAny(pairs[i+1], "\r\n") {
return fmt.Errorf("output %s spans several lines", pairs[i])
}
body.WriteString(pairs[i] + "=" + pairs[i+1] + "\n")
}
return c.Container.Copy(c.Dir(output), &container.FileEntry{Name: c.Base(output), Mode: 0o666, Body: body.String()})(ctx)
}
func (c *Context) Host() bool {
_, host := c.Container.(*container.HostEnvironment)
return host
}
func (c *Context) Windows() bool {
return c.Host() && runtime.GOOS == "windows"
}
func (c *Context) Join(elem ...string) string {
if c.Windows() {
return filepath.Join(elem...)
}
return path.Join(elem...)
}
func (c *Context) Dir(p string) string {
if c.Windows() {
return filepath.Dir(p)
}
return path.Dir(p)
}
func (c *Context) Base(p string) string {
if c.Windows() {
return filepath.Base(p)
}
return path.Base(p)
}
func (c *Context) Resolve(p string) string {
if c.Windows() && filepath.IsAbs(p) || !c.Windows() && path.IsAbs(p) {
return c.Join(p)
}
return c.Join(c.Workspace, p)
}
// Home is the job user's home directory, what os.homedir() returns to a JavaScript action.
func (c *Context) Home(ctx context.Context) (string, error) {
if home := c.Env["HOME"]; home != "" {
return home, nil
}
if home := c.Env["USERPROFILE"]; c.Windows() && home != "" {
return home, nil
}
if c.Host() {
return os.UserHomeDir()
}
var out strings.Builder
stdout, stderr := c.Container.ReplaceLogWriter(&out, &out)
err := c.Container.Exec([]string{"sh", "-c", `printf %s "$HOME"`}, nil, "", "")(ctx)
c.Container.ReplaceLogWriter(stdout, stderr)
if err != nil {
return "", fmt.Errorf("cannot expand ~ without HOME: %w", err)
}
if out.Len() == 0 {
return "", errors.New("cannot expand ~, the job user has no HOME")
}
return out.String(), nil
}
// Failf is fmt.Errorf for messages worded as the JavaScript action words them, which the error string lint rejects.
func Failf(format string, args ...any) error {
return fmt.Errorf(format, args...)
}
// ParseInt reads a leading integer the way JavaScript's parseInt does.
func ParseInt(s string) (int, error) {
s = strings.TrimLeftFunc(s, unicode.IsSpace)
end := 0
if end < len(s) && (s[end] == '-' || s[end] == '+') {
end++
}
for end < len(s) && s[end] >= '0' && s[end] <= '9' {
end++
}
return strconv.Atoi(s[:end])
}
-184
View File
@@ -1,184 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package artifact
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
)
// BlockSize is the toolkit's upload chunk.
const BlockSize = 8 << 20
type Uploaded struct {
Size int64
Digest string // sha256:<hex> for Finalize
}
// Upload puts body to a signed URL as parallel Azure blocks, failing when upload progress stalls for stall.
func (c *Client) Upload(ctx context.Context, signedURL, contentType string, body io.Reader, concurrency int, stall time.Duration) (result Uploaded, err error) {
ctx, cancel := context.WithCancelCause(ctx)
defer func() {
if ctx.Err() != nil {
err = context.Cause(ctx)
}
cancel(nil)
}()
stall = max(stall, time.Millisecond)
timer := time.AfterFunc(stall, func() { cancel(errors.New("upload progress stalled")) })
defer timer.Stop()
hash := sha256.New()
reader := io.TeeReader(body, hash)
group, blockCtx := errgroup.WithContext(ctx)
if closer, ok := body.(io.ReadCloser); ok {
stop := context.AfterFunc(blockCtx, func() { closer.Close() })
defer stop()
}
buffers := make(chan []byte, concurrency)
prefix := rand.Text()
var ids []string
var uploaded atomic.Int64
for index := 0; ; index++ {
var buf []byte
if index < concurrency {
buf = make([]byte, BlockSize)
} else {
select {
case buf = <-buffers:
case <-blockCtx.Done():
return Uploaded{}, group.Wait()
}
}
n, readErr := io.ReadFull(reader, buf)
if errors.Is(readErr, io.EOF) {
break
} else if readErr != nil && !errors.Is(readErr, io.ErrUnexpectedEOF) {
if blockCtx.Err() == nil {
cancel(readErr)
}
if err := group.Wait(); err != nil {
return Uploaded{}, err
}
return Uploaded{}, readErr
}
id := base64.StdEncoding.EncodeToString(fmt.Appendf(nil, "%s-%08d", prefix, index)) // fixed width as Azure needs, unique as Gitea before 1.25.5 shares a run's blocks
ids = append(ids, id)
group.Go(func() error {
defer func() { buffers <- buf }()
if err := c.put(blockCtx, signedURL+"&comp=block&blockid="+url.QueryEscape(id), "x-ms-blob-type", "BlockBlob", buf[:n]); err != nil {
return err
}
timer.Reset(stall)
c.Logf("Uploaded bytes %d", uploaded.Add(int64(n)))
return nil
})
if readErr != nil {
break
}
}
if err := group.Wait(); err != nil {
return Uploaded{}, err
}
var list strings.Builder
list.WriteString("<BlockList>")
for _, id := range ids {
list.WriteString("<Latest>" + id + "</Latest>")
}
list.WriteString("</BlockList>")
if err := c.put(ctx, signedURL+"&comp=blocklist", "x-ms-blob-content-type", contentType, []byte(list.String())); err != nil {
return Uploaded{}, err
}
return Uploaded{Size: uploaded.Load(), Digest: "sha256:" + hex.EncodeToString(hash.Sum(nil))}, nil
}
func (c *Client) put(ctx context.Context, signedURL, header, value string, body []byte) error {
resp, err := c.Retry.do(ctx, c.Logf, "blob upload", func() (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPut, signedURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set(header, value)
resp, err := c.blob.Do(req)
return resp, scrub(err)
})
if err != nil {
return err
}
return resp.Body.Close()
}
// Download GETs a signed URL, a read failing when nothing arrives for stall.
func (c *Client) Download(ctx context.Context, signedURL string, stall time.Duration) (*http.Response, error) {
ctx, cancel := context.WithCancelCause(ctx)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, signedURL, nil)
if err != nil {
cancel(nil)
return nil, err
}
resp, err := c.blob.Do(req)
if err != nil {
cancel(nil)
return nil, scrub(err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
cancel(nil)
return nil, fmt.Errorf("unexpected HTTP response from blob storage: %d %s", resp.StatusCode, http.StatusText(resp.StatusCode))
}
resp.Body = &stallReader{body: resp.Body, timer: time.AfterFunc(stall, func() {
cancel(fmt.Errorf("blob storage chunk did not respond in %s", stall))
}), stall: stall, cancel: cancel, ctx: ctx}
return resp, nil
}
func scrub(err error) error { // the signature of a signed URL is a credential
if urlErr, ok := errors.AsType[*url.Error](err); ok {
if parsed, parseErr := url.Parse(urlErr.URL); parseErr == nil {
parsed.RawQuery = ""
urlErr.URL = parsed.String()
} else {
urlErr.URL = "<unparsable URL>"
}
}
return err
}
type stallReader struct {
body io.ReadCloser
timer *time.Timer
stall time.Duration
cancel context.CancelCauseFunc
ctx context.Context
}
func (r *stallReader) Read(p []byte) (int, error) {
n, err := r.body.Read(p)
if n > 0 {
r.timer.Reset(r.stall)
}
if err != nil && !errors.Is(err, io.EOF) && context.Cause(r.ctx) != nil {
err = context.Cause(r.ctx)
}
return n, err
}
func (r *stallReader) Close() error {
r.timer.Stop()
r.cancel(nil)
return r.body.Close()
}
-264
View File
@@ -1,264 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// Package artifact talks to the v4 results service of the job's run.
package artifact
import (
"bytes"
"cmp"
"context"
"encoding/base64"
"encoding/json/v2"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type Artifact struct {
ID int64 `json:"databaseId,string"`
Name string `json:"name"`
Size int64 `json:"size,string"`
Digest string `json:"digest"`
}
type Retry struct {
Attempts int
Base time.Duration
Multiplier float64
MaxWait time.Duration
}
var DefaultRetry = Retry{Attempts: 5, Base: 8 * time.Second, Multiplier: 1.5, MaxWait: 2 * time.Minute}
type Client struct {
base *url.URL
token string
ids backendIDsMessage
api, blob *http.Client
Retry Retry
Logf func(format string, args ...any)
}
// New reaches base through transport, which carries the instance's TLS settings, and signed URLs elsewhere directly.
func New(base, token string, transport http.RoundTripper) (*Client, error) {
if base == "" {
return nil, errors.New("no artifact service is configured for this runner")
}
parsed, err := url.Parse(base)
if err != nil {
return nil, err
}
if token == "" {
return nil, errors.New("ACTIONS_RUNTIME_TOKEN is not set")
}
ids, err := backendIDs(token)
if err != nil {
return nil, err
}
return &Client{
base: parsed, token: token, ids: ids,
api: &http.Client{Transport: transport, Timeout: 3 * time.Minute},
blob: &http.Client{Transport: blobTransport{instance: parsed.Host, transport: transport}},
Retry: DefaultRetry,
Logf: func(string, ...any) {},
}, nil
}
// backendIDs reads the unverified scp claim of a runtime token, as the toolkit does.
func backendIDs(token string) (backendIDsMessage, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return backendIDsMessage{}, errors.New("the runtime token is not a JWT, artifacts v4 need Gitea 1.22 or later")
}
payload, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(parts[1], "="))
if err != nil {
return backendIDsMessage{}, err
}
var claims struct {
Scp string `json:"scp"`
}
if err := json.Unmarshal(payload, &claims); err != nil {
return backendIDsMessage{}, err
}
for scope := range strings.FieldsSeq(claims.Scp) {
if fields := strings.Split(scope, ":"); fields[0] == "Actions.Results" && len(fields) == 3 {
return backendIDsMessage{fields[1], fields[2]}, nil
}
}
return backendIDsMessage{}, errors.New("the runtime token has no Actions.Results scope")
}
type blobTransport struct { // the instance's TLS settings only for the instance, as a signed URL can point at object storage
instance string
transport http.RoundTripper
}
func (t blobTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL.Host == t.instance && t.transport != nil {
return t.transport.RoundTrip(req)
}
return http.DefaultTransport.RoundTrip(req)
}
type StatusError struct {
Status int
Msg string
}
func (e *StatusError) Error() string {
if e.Msg == "" {
return fmt.Sprintf("(%d) %s", e.Status, http.StatusText(e.Status))
}
return fmt.Sprintf("(%d) %s: %s", e.Status, http.StatusText(e.Status), e.Msg)
}
func IsNotFound(err error) bool {
var status *StatusError
return errors.As(err, &status) && status.Status == http.StatusNotFound
}
func (r Retry) do(ctx context.Context, logf func(string, ...any), what string, send func() (*http.Response, error)) (*http.Response, error) {
var waited time.Duration
for attempt := 0; ; attempt++ {
resp, err := send()
var wait time.Duration
if err == nil {
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
return resp, nil
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
resp.Body.Close()
err = &StatusError{Status: resp.StatusCode, Msg: twirpMessage(body)}
switch resp.StatusCode {
case http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
default:
return nil, err
}
if seconds, parseErr := strconv.Atoi(resp.Header.Get("Retry-After")); parseErr == nil && seconds > 0 && resp.StatusCode == http.StatusTooManyRequests {
wait = time.Duration(seconds) * time.Second
}
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
if attempt+1 >= r.Attempts {
return nil, fmt.Errorf("%s failed after %d attempts: %w", what, r.Attempts, err)
}
if wait == 0 {
wait = time.Duration(float64(r.Base) * math.Pow(r.Multiplier, float64(attempt)))
}
if waited+wait > r.MaxWait {
return nil, fmt.Errorf("%s: a retry wait of %s would exceed %s: %w", what, wait, r.MaxWait, err)
}
logf("Attempt %d of %d failed with error: %v. Retrying request in %d ms...", attempt+1, r.Attempts, err, wait.Milliseconds())
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(wait):
}
waited += wait
}
}
// twirpMessage is the msg of a twirp error, the message of a Gitea API one, or the body Gitea answers in plain text.
func twirpMessage(body []byte) string {
var twirpErr struct {
Msg string `json:"msg"`
Message string `json:"message"`
}
if json.Unmarshal(body, &twirpErr) == nil && cmp.Or(twirpErr.Msg, twirpErr.Message) != "" {
return cmp.Or(twirpErr.Msg, twirpErr.Message)
}
return strings.TrimSpace(string(body))
}
type ( // the ArtifactService messages in the protobuf JSON mapping, requests with the proto names the toolkit sends
backendIDsMessage struct {
WorkflowRunBackendID string `json:"workflow_run_backend_id"`
WorkflowJobRunBackendID string `json:"workflow_job_run_backend_id"`
}
namedRequest struct {
backendIDsMessage
Name string `json:"name"`
}
createRequest struct {
namedRequest
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Version int32 `json:"version"`
MimeType string `json:"mime_type,omitempty"` // Gitea before 1.26 rejects the field
}
finalizeRequest struct {
namedRequest
Size int64 `json:"size,string"`
Hash string `json:"hash"`
}
listRequest struct {
backendIDsMessage
NameFilter string `json:"name_filter,omitempty"`
}
idResponse struct {
ArtifactID int64 `json:"artifactId,string"`
}
)
func call[Resp any](ctx context.Context, c *Client, method string, req any) (Resp, error) {
var resp Resp
body, err := json.Marshal(req)
if err != nil {
return resp, err
}
endpoint := c.base.JoinPath("/twirp/github.actions.results.api.v1.ArtifactService", method).String()
httpResp, err := c.Retry.do(ctx, c.Logf, method, func() (*http.Response, error) {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+c.token)
return c.api.Do(httpReq)
})
if err != nil {
return resp, fmt.Errorf("failed to %s: %w", method, err)
}
defer httpResp.Body.Close()
err = json.UnmarshalRead(httpResp.Body, &resp)
return resp, err
}
func (c *Client) Create(ctx context.Context, name, mimeType string, expiresAt *time.Time) (string, error) {
resp, err := call[struct {
SignedUploadURL string `json:"signedUploadUrl"`
}](ctx, c, "CreateArtifact", createRequest{namedRequest{c.ids, name}, expiresAt, 7, mimeType})
return resp.SignedUploadURL, err
}
func (c *Client) Finalize(ctx context.Context, name string, size int64, digest string) (int64, error) {
resp, err := call[idResponse](ctx, c, "FinalizeArtifact", finalizeRequest{namedRequest{c.ids, name}, size, digest})
return resp.ArtifactID, err
}
func (c *Client) List(ctx context.Context, name string) ([]Artifact, error) {
resp, err := call[struct {
Artifacts []Artifact `json:"artifacts"`
}](ctx, c, "ListArtifacts", listRequest{c.ids, name})
return resp.Artifacts, err
}
func (c *Client) SignedURL(ctx context.Context, name string) (string, error) {
resp, err := call[struct {
SignedURL string `json:"signedUrl"`
}](ctx, c, "GetSignedArtifactURL", namedRequest{c.ids, name})
return resp.SignedURL, err
}
func (c *Client) Delete(ctx context.Context, name string) (int64, error) {
resp, err := call[idResponse](ctx, c, "DeleteArtifact", namedRequest{c.ids, name})
return resp.ArtifactID, err
}
-182
View File
@@ -1,182 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package artifact
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"gitea.com/gitea/runner/act/artifacts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClientRoundTrip(t *testing.T) {
router := http.NewServeMux()
artifacts.RegisterV4(router, t.TempDir())
var blocks atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.URL.Query().Get("comp") == "block" {
blocks.Add(1)
}
router.ServeHTTP(writer, request)
}))
defer server.Close()
client, err := New(server.URL, artifacts.LocalRuntimeToken("7", time.Hour), nil)
require.NoError(t, err)
for _, content := range [][]byte{nil, bytes.Repeat([]byte("payload"), 2*BlockSize/7+123)} {
sum := sha256.Sum256(content)
uploadURL, err := client.Create(t.Context(), "art", "text/plain", nil)
require.NoError(t, err)
uploaded, err := client.Upload(t.Context(), uploadURL, "text/plain", bytes.NewReader(content), 2, time.Minute)
require.NoError(t, err)
assert.Equal(t, int32((len(content)+BlockSize-1)/BlockSize), blocks.Swap(0))
assert.Equal(t, Uploaded{Size: int64(len(content)), Digest: "sha256:" + hex.EncodeToString(sum[:])}, uploaded)
id, err := client.Finalize(t.Context(), "art", uploaded.Size, uploaded.Digest)
require.NoError(t, err)
listed, err := client.List(t.Context(), "art")
require.NoError(t, err)
assert.Equal(t, []Artifact{{ID: id, Name: "art", Size: int64(len(content)), Digest: uploaded.Digest}}, listed)
signed, err := client.SignedURL(t.Context(), "art")
require.NoError(t, err)
resp, err := client.Download(t.Context(), signed, time.Minute)
require.NoError(t, err)
got, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.True(t, bytes.Equal(content, got))
deleted, err := client.Delete(t.Context(), "art")
require.NoError(t, err)
assert.Equal(t, id, deleted)
_, err = client.SignedURL(t.Context(), "art")
assert.True(t, IsNotFound(err), err)
}
}
func TestClientRetries(t *testing.T) {
var calls atomic.Int32
var blockIDs []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPut {
blockIDs = append(blockIDs, r.URL.Query().Get("blockid"))
w.WriteHeader(http.StatusCreated)
return
}
body, _ := io.ReadAll(r.Body)
assert.NotContains(t, string(body), "mime_type", "older Gitea rejects the field")
assert.True(t, strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ey"), "the runtime token is the bearer")
switch calls.Add(1) {
case 1:
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
case 2:
http.Error(w, "Error create or get artifact", http.StatusInternalServerError)
case 3:
w.WriteHeader(http.StatusFound)
_, _ = io.WriteString(w, `{"ok":true,"signedUploadUrl":"http://blob/u?sig=x"}`)
default:
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"code":"invalid_argument","msg":"bad name"}`)
}
}))
defer server.Close()
client, err := New(server.URL, artifacts.LocalRuntimeToken("7", time.Hour), nil)
require.NoError(t, err)
client.Retry = Retry{Attempts: 3}
var logged []string
client.Logf = func(format string, args ...any) { logged = append(logged, fmt.Sprintf(format, args...)) }
uploadURL, err := client.Create(t.Context(), "art", "", nil)
require.NoError(t, err)
assert.Equal(t, "http://blob/u?sig=x", uploadURL)
assert.Contains(t, logged[1], "Error create or get artifact")
_, err = client.Create(t.Context(), "art", "", nil)
require.ErrorContains(t, err, "(400) Bad Request: bad name")
assert.Equal(t, int32(4), calls.Load(), "a 400 is not retried")
for range 2 {
_, err = client.Upload(t.Context(), server.URL+"/u?sig=secret", "application/zip", strings.NewReader("x"), 1, time.Minute)
require.NoError(t, err)
}
assert.NotEqual(t, blockIDs[0], blockIDs[2], "each upload names its blocks anew")
server.Close()
_, err = client.Upload(t.Context(), server.URL+"/u?sig=secret", "application/zip", strings.NewReader("x"), 1, time.Minute)
require.Error(t, err)
assert.NotContains(t, err.Error()+strings.Join(logged, ""), "secret")
}
func TestTransferStalls(t *testing.T) {
for _, test := range []struct{ name, want string }{
{"api", "Client.Timeout"},
{"failed upload", "(400) Bad Request"},
{"source", "upload progress stalled"},
{"commit", "upload progress stalled"},
{"download", "did not respond"},
} {
t.Run(test.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
_, _ = io.Copy(io.Discard, request.Body)
if test.name == "failed upload" {
writer.WriteHeader(http.StatusBadRequest)
return
}
if test.name == "download" {
_, _ = io.WriteString(writer, "partial")
writer.(http.Flusher).Flush()
}
<-request.Context().Done()
}))
defer server.Close()
client, err := New(server.URL, artifacts.LocalRuntimeToken("7", time.Hour), nil)
require.NoError(t, err)
client.Retry = Retry{Attempts: 1}
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
switch test.name {
case "api":
assert.Equal(t, 3*time.Minute, client.api.Timeout)
client.api.Timeout = time.Millisecond
_, err = client.Create(ctx, "art", "", nil)
case "download":
var resp *http.Response
resp, err = client.Download(ctx, server.URL, time.Millisecond)
require.NoError(t, err)
defer resp.Body.Close()
_, err = io.ReadAll(resp.Body)
case "commit":
_, err = client.Upload(ctx, server.URL+"?sig=x", "text/plain", strings.NewReader(""), 1, time.Millisecond)
default:
reader, writer := io.Pipe()
defer reader.Close()
defer writer.Close()
done := make(chan error, 1)
stall := time.Millisecond
if test.name == "failed upload" {
stall = time.Minute
go func() {
_, err := writer.Write(make([]byte, BlockSize))
done <- err
}()
}
_, err = client.Upload(ctx, server.URL+"?sig=x", "text/plain", reader, 2, stall)
if test.name == "failed upload" {
require.NoError(t, <-done)
}
}
require.ErrorContains(t, err, test.want)
})
}
}
-117
View File
@@ -1,117 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package artifact
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
)
type REST struct {
base *url.URL
token string
api *http.Client
blob *http.Client
Retry Retry
Logf func(format string, args ...any)
}
// NewREST takes the instance as the runner reaches it, never the job's GITHUB_API_URL, so the token only goes there.
func NewREST(instance, token string, transport http.RoundTripper) (*REST, error) {
parsed, err := url.Parse(instance)
if err != nil {
return nil, err
}
return &REST{
base: parsed.JoinPath("api", "v1"),
token: token,
api: &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse // the redirect target is signed and must not get the token
}},
blob: &http.Client{Transport: blobTransport{instance: parsed.Host, transport: transport}},
Retry: DefaultRetry,
Logf: func(string, ...any) {},
}, nil
}
func (r *REST) get(ctx context.Context, what string, endpoint *url.URL) (*http.Response, error) {
return r.Retry.do(ctx, r.Logf, what, func() (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "token "+r.token)
req.Header.Set("Accept", "application/json")
return r.api.Do(req)
})
}
func (r *REST) List(ctx context.Context, owner, repo string, runID int64, name string) ([]Artifact, error) {
if name == "" {
r.Logf("Fetching artifact list for workflow run %d in repository %s/%s", runID, owner, repo)
}
var list []Artifact
seen := 0
for page := 1; ; page++ {
endpoint := r.base.JoinPath("repos", owner, repo, "actions", "runs", strconv.FormatInt(runID, 10), "artifacts")
query := url.Values{"page": {strconv.Itoa(page)}, "limit": {"50"}}
if name != "" {
query.Set("name", name)
}
endpoint.RawQuery = query.Encode()
resp, err := r.get(ctx, "list artifacts", endpoint)
if err != nil {
return nil, err
}
var body struct {
TotalCount int `json:"total_count"`
Artifacts []struct {
ID int64 `json:"id"`
Name string `json:"name"`
SizeInBytes int64 `json:"size_in_bytes"`
Expired bool `json:"expired"`
Digest string `json:"digest"`
} `json:"artifacts"`
}
err = json.UnmarshalRead(resp.Body, &body)
resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("list artifacts: %w", err)
}
for _, listed := range body.Artifacts {
if !listed.Expired {
list = append(list, Artifact{ID: listed.ID, Name: listed.Name, Size: listed.SizeInBytes, Digest: listed.Digest})
}
}
if seen += len(body.Artifacts); len(body.Artifacts) == 0 || seen >= body.TotalCount {
return list, nil
}
}
}
func (r *REST) DownloadURL(ctx context.Context, owner, repo string, id int64) (string, error) {
resp, err := r.get(ctx, "download artifact", r.base.JoinPath("repos", owner, repo, "actions", "artifacts", strconv.FormatInt(id, 10), "zip"))
if err != nil {
return "", fmt.Errorf("unable to download artifact: %w", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusFound {
return "", fmt.Errorf("unable to download artifact. Unexpected status: %d", resp.StatusCode)
}
location, err := resp.Location()
if err != nil {
return "", errors.New("unable to redirect to artifact download url")
}
return location.String(), nil
}
func (r *REST) Download(ctx context.Context, signedURL string, stall time.Duration) (*http.Response, error) {
return (&Client{blob: r.blob}).Download(ctx, signedURL, stall)
}
-42
View File
@@ -1,42 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package artifact
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRESTListsEveryPageAndSkipsExpired(t *testing.T) {
var pages []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/repos/own%20er/repo/actions/runs/12/artifacts", r.URL.EscapedPath())
assert.Equal(t, "token secret", r.Header.Get("Authorization"))
assert.Empty(t, r.URL.Query().Get("per_page"))
pages = append(pages, r.URL.Query().Get("page")+"/"+r.URL.Query().Get("limit"))
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
const maxResponseItems = 20
var entries []string
for id := (page-1)*maxResponseItems + 1; id <= min(page*maxResponseItems, 53); id++ {
entries = append(entries, fmt.Sprintf(`{"id":%d,"name":"a%d","size_in_bytes":%d,"expired":%t}`, id, id, id, id == 2))
}
_, _ = io.WriteString(w, `{"total_count":53,"artifacts":[`+strings.Join(entries, ",")+`]}`)
}))
defer server.Close()
rest, err := NewREST(server.URL, "secret", nil)
require.NoError(t, err)
list, err := rest.List(t.Context(), "own er", "repo", 12, "")
require.NoError(t, err)
assert.Equal(t, []string{"1/50", "2/50", "3/50"}, pages)
assert.Len(t, list, 52)
assert.Equal(t, Artifact{ID: 3, Name: "a3", Size: 3}, list[1])
}
-483
View File
@@ -1,483 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package checkout
import (
"cmp"
"context"
"crypto/sha256"
"errors"
"fmt"
"maps"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
"gitea.com/gitea/runner/act/common/git"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.dev/actionslib/pkg/model"
"github.com/kballard/go-shellquote"
)
var inputNames = []string{
"repository", "ref", "token", "ssh-key", "ssh-known-hosts", "ssh-strict", "ssh-user", "persist-credentials", "path", "clean",
"filter", "sparse-checkout", "sparse-checkout-cone-mode", "fetch-depth", "fetch-tags", "show-progress", "lfs", "submodules",
"set-safe-directory",
}
const credentialsInclude = "includeIf.gitdir:**.path" // the form actions/checkout removes from a repository it checks out again
func Main(ctx context.Context, c *action.Context) (err error) {
for name := range c.Inputs {
if !slices.Contains(inputNames, name) {
return fmt.Errorf("checkout: unsupported input %q", name)
}
}
runnerContext := c.Container.GetRunnerContext(ctx)
executionOS, _ := runnerContext["os"].(string)
windows := strings.EqualFold(executionOS, "windows")
dst, err := workspaceDestination(c.Workspace, c.Inputs["path"], windows)
if err != nil {
return err
}
depth, err := fetchDepth(c.Inputs["fetch-depth"])
if err != nil {
return err
}
ghc := c.Github
repository := cmp.Or(c.Inputs["repository"], ghc.Repository)
ref := c.Inputs["ref"]
sshKey := strings.TrimSpace(c.Inputs["ssh-key"])
isWorkflowRepo := strings.EqualFold(repository, ghc.Repository)
local := isWorkflowRepo && slices.Contains([]string{"", strings.TrimPrefix(ghc.Ref, "refs/heads/"), ghc.Sha}, strings.TrimPrefix(ref, "refs/heads/")) && !c.NoSkipCheckout && sshKey == ""
if local && (!c.BindWorkdir || dst == c.Workspace) {
if !c.BindWorkdir {
if err := c.Container.CopyDir(dst, c.HostWorkdir+string(filepath.Separator)+".", c.UseGitIgnore, false)(ctx); err != nil {
return err
}
}
if output := filepath.ToSlash(c.Env["GITHUB_OUTPUT"]); output != "" {
return c.Container.Copy(container.JoinPath(output, ".."), &container.FileEntry{Name: path.Base(output), Mode: 0o666, Body: fmt.Sprintf("ref=%s\ncommit=%s\n", ghc.Ref, ghc.Sha)})(ctx)
}
return nil
}
co := &checkout{
url: strings.TrimSuffix(ghc.ServerURL, "/") + "/" + repository,
dst: dst,
windows: windows,
ref: ref,
depth: depth,
fetchTags: boolInput(c.Inputs, "fetch-tags", false),
clean: boolInput(c.Inputs, "clean", true),
lfs: boolInput(c.Inputs, "lfs", false),
progress: boolInput(c.Inputs, "show-progress", true),
cone: boolInput(c.Inputs, "sparse-checkout-cone-mode", true),
filter: strings.TrimSpace(c.Inputs["filter"]),
output: c.Env["GITHUB_OUTPUT"],
}
for pattern := range strings.Lines(c.Inputs["sparse-checkout"]) {
if pattern = strings.TrimSpace(pattern); pattern != "" {
co.sparse = append(co.sparse, pattern)
}
}
if len(co.sparse) > 0 {
co.filter = cmp.Or(co.filter, "blob:none")
}
if submodules := strings.ToLower(strings.TrimSpace(c.Inputs["submodules"])); submodules == "true" || submodules == "recursive" {
co.submodules = submodules
}
if sshKey != "" {
if co.url, err = sshURL(ghc, repository, strings.TrimSpace(c.Inputs["ssh-user"])); err != nil {
return err
}
}
co.objectFormat = git.ObjectFormat(ref)
switch {
case co.objectFormat != "":
co.sha, co.ref = ref, ""
case ref == "" && isWorkflowRepo && strings.HasPrefix(ghc.Ref, "refs/"):
co.sha, co.ref = ghc.Sha, ghc.Ref
case ref == "" && isWorkflowRepo: // a merged pull request's ref is its merge commit
co.sha = ghc.Sha
case ref == "HEAD":
co.ref = ""
}
if isWorkflowRepo {
co.objectFormat = cmp.Or(co.objectFormat, git.ObjectFormat(ghc.Sha))
}
// named like actions/checkout's, which create-pull-request knows to hide, and gone with the job
runnerTemp, _ := runnerContext["temp"].(string)
runnerTemp = filepath.ToSlash(runnerTemp)
digest := sha256.Sum256([]byte(dst))
credentials := fmt.Sprintf("git-credentials-%x.config", digest[:8])
co.credentials = container.JoinPath(runnerTemp, credentials)
persist := boolInput(c.Inputs, "persist-credentials", true)
config, remoteConfig := serverConfig(ghc.ServerURL, append(git.RemoteConfig(cmp.Or(c.Inputs["token"], ghc.Token), c.InsecureSkipTLS), git.SSLConfig("http.", "", "", c.CAFile, executionOS)...), co.submodules != "" && sshKey == "")
if boolInput(c.Inputs, "set-safe-directory", true) {
remoteConfig = append(remoteConfig, "safe.directory=*") // a bound workdir belongs to the host user
}
if c.ClientCertFile != "" { // only for this step, later steps never get the runner's key
var certPEM, keyPEM []byte
if certPEM, err = os.ReadFile(c.ClientCertFile); err != nil {
return err
}
if keyPEM, err = os.ReadFile(c.ClientKeyFile); err != nil {
return err
}
cert, key := fmt.Sprintf("git-client-cert-%x.pem", digest[:8]), fmt.Sprintf("git-client-key-%x.pem", digest[:8])
defer func() {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute)
defer cancel()
err = errors.Join(err, c.Container.Copy(runnerTemp, &container.FileEntry{Name: key, Mode: 0o600})(cleanupCtx))
}()
if err := c.Container.Copy(runnerTemp, &container.FileEntry{Name: cert, Mode: 0o600, Body: string(certPEM)}, &container.FileEntry{Name: key, Mode: 0o600, Body: string(keyPEM)})(ctx); err != nil {
return err
}
remoteConfig = append(remoteConfig, git.SSLConfig("http."+strings.TrimSuffix(ghc.ServerURL, "/")+"/.", container.JoinPath(runnerTemp, cert), container.JoinPath(runnerTemp, key), "", executionOS)...)
}
env := gitEnv(c, remoteConfig)
env["GIT_LFS_SKIP_SMUDGE"] = strconv.FormatBool(!co.lfs || len(co.sparse) == 0) // lfs pull fetches the objects of a full checkout in one go
if sshKey != "" {
key := fmt.Sprintf("git-ssh-key-%x", digest[:8])
files := []*container.FileEntry{{Name: key, Mode: 0o600, Body: sshKey + "\n"}}
ssh := []string{"ssh", "-i", container.JoinPath(runnerTemp, key)}
if boolInput(c.Inputs, "ssh-strict", true) {
ssh = append(ssh, "-o", "StrictHostKeyChecking=yes", "-o", "CheckHostIP=no")
}
if knownHosts := strings.TrimSpace(c.Inputs["ssh-known-hosts"]); knownHosts != "" {
name := fmt.Sprintf("git-ssh-known-hosts-%x", digest[:8])
files = append(files, &container.FileEntry{Name: name, Mode: 0o600, Body: knownHosts + "\n"})
ssh = append(ssh, "-o", "UserKnownHostsFile=~/.ssh/known_hosts "+strconv.Quote(container.JoinPath(runnerTemp, name)))
}
if !persist {
defer func() {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute)
defer cancel()
err = errors.Join(err, c.Container.Copy(runnerTemp, &container.FileEntry{Name: key, Mode: 0o600})(cleanupCtx))
}()
}
if err := c.Container.Copy(runnerTemp, files...)(ctx); err != nil {
return err
}
env["GIT_SSH_COMMAND"] = shellquote.Join(ssh...)
config += "[core]\n\tsshCommand = " + strconv.Quote(env["GIT_SSH_COMMAND"]) + "\n"
}
if co.objectFormat == "" || co.sha == "" && !strings.HasPrefix(co.ref, "refs/") {
advertised, err := lsRemote(ctx, c, env, co.url, co.ref)
if err != nil {
return fmt.Errorf("checkout: %s@%s: %w", repository, ref, err)
}
if co.resolve(advertised); co.ref == "" && co.sha == "" {
return fmt.Errorf("checkout: %s has no ref %q", repository, ref)
}
}
co.outputRef = co.ref
if ref != co.sha {
co.outputRef = cmp.Or(ref, co.ref) // as given, like actions/checkout
}
if err := c.Container.Copy(runnerTemp, &container.FileEntry{Name: credentials, Mode: 0o600})(ctx); err != nil {
return err
}
clone := func(commands [][]string) error {
if err := run(ctx, c, env, commands); err != nil {
return fmt.Errorf("checkout: clone %s@%s: %w", repository, cmp.Or(co.ref, co.sha), err)
}
return nil
}
commands, fetched := co.commands()
if co.sha != "" && strings.HasPrefix(co.ref, "refs/tags/") {
if err := clone(commands[:fetched]); err != nil {
return err
}
tagged, err := output(ctx, c, env, "git", "-C", dst, "rev-parse", "--verify", "--quiet", co.ref+"^{commit}")
if err != nil {
return fmt.Errorf("checkout: %s: %w", co.ref, err)
}
if !strings.EqualFold(strings.TrimSpace(tagged), co.sha) {
return fmt.Errorf("checkout: %s does not point to the expected commit %s, it may have been moved after the workflow was triggered", co.ref, co.sha)
}
commands = commands[fetched:]
}
if err := clone(commands); err != nil || !persist {
return err
}
return c.Container.Copy(runnerTemp, &container.FileEntry{Name: credentials, Mode: 0o600, Body: config})(ctx) // for later steps, the step itself authenticates through env
}
func gitEnv(c *action.Context, config []string) map[string]string {
env := map[string]string{"GIT_TERMINAL_PROMPT": "0"}
maps.Copy(env, c.Env)
maps.DeleteFunc(env, func(name, _ string) bool { return slices.Contains(git.LocalEnvVars, name) })
maps.Copy(env, git.ConfigEnv(append([]string{"protocol.version=2", "init.defaultBranch=main", "advice.detachedHead=false", "maintenance.auto=false", "core.longpaths=true"}, config...)...))
return env
}
func run(ctx context.Context, c *action.Context, env map[string]string, commands [][]string) error {
if _, host := c.Container.(*container.HostEnvironment); !host || runtime.GOOS != "windows" {
script := []string{"set -e", `command -v git >/dev/null || { echo "builtin:checkout needs git on PATH" >&2; exit 127; }`}
for _, command := range commands {
script = append(script, shellquote.Join(command...))
}
return c.Container.Exec([]string{"sh", "-c", strings.Join(script, "\n")}, env, "", "")(ctx)
}
for _, command := range commands {
if err := c.Container.Exec(command, env, "", "")(ctx); err != nil {
return err
}
}
return nil
}
// output runs where the job runs, so the job's network and git config apply as for the fetch.
func output(ctx context.Context, c *action.Context, env map[string]string, command ...string) (string, error) {
var out strings.Builder
stdout, stderr := c.Container.ReplaceLogWriter(&out, &out)
defer c.Container.ReplaceLogWriter(stdout, stderr)
if err := c.Container.Exec(command, env, "", "")(ctx); err != nil {
return "", fmt.Errorf("%w: %s", err, strings.TrimSpace(out.String()))
}
return out.String(), nil
}
func lsRemote(ctx context.Context, c *action.Context, env map[string]string, url, ref string) (string, error) {
patterns := []string{ref}
switch {
case ref == "":
patterns = []string{"HEAD"}
case !strings.HasPrefix(ref, "refs/"):
patterns = []string{"refs/heads/" + ref, "refs/tags/" + ref}
}
return output(ctx, c, env, append([]string{"git", "ls-remote", "--symref", url}, patterns...)...)
}
// serverConfig scopes the token to the server, so no other host like a repository's LFS endpoint gets it.
func serverConfig(serverURL string, settings []string, rewriteSSH bool) (file string, env []string) {
scope := strings.TrimSuffix(serverURL, "/") + "/"
file = fmt.Sprintf("[http %q]\n", scope)
for _, entry := range settings {
setting := strings.TrimPrefix(entry, "http.")
key, value, _ := strings.Cut(setting, "=")
file += "\t" + key + " = " + strconv.Quote(value) + "\n"
env = append(env, "http."+scope+"."+setting)
}
if server, err := url.Parse(serverURL); rewriteSSH && err == nil && server.Hostname() != "" { // submodules on the server fetch over HTTP with the token
file += fmt.Sprintf("[url %q]\n\tinsteadOf = git@%s:\n", scope, server.Hostname())
env = append(env, "url."+scope+".insteadOf=git@"+server.Hostname()+":")
}
return file, env
}
func sshURL(ghc *model.GithubContext, repository, user string) (string, error) {
endpoint := &url.URL{Scheme: "ssh"}
if advertised, _ := model.NestedMapLookup(ghc.Event, "repository", "ssh_url").(string); advertised != "" {
if colon := strings.LastIndex(advertised, ":"); !strings.HasPrefix(advertised, "ssh://") && colon >= 0 {
advertised = "ssh://" + advertised[:colon] + "/" + advertised[colon+1:] // scp-like git@host:owner/repo.git
}
var err error
if endpoint, err = url.Parse(advertised); err != nil {
return "", fmt.Errorf("checkout: parse the event's ssh_url: %w", err)
}
} else if server, err := url.Parse(ghc.ServerURL); err == nil {
endpoint.Host = server.Hostname()
}
endpoint.User = url.User(cmp.Or(user, endpoint.User.Username(), "git"))
endpoint.Path = "/" + repository + ".git"
return endpoint.String(), nil
}
type checkout struct {
url, dst, objectFormat, credentials, output, outputRef string
ref, sha string // ref is fully qualified or empty, sha pins it when known
filter, submodules string
sparse []string
depth int
fetchTags, clean, lfs, progress, cone, windows bool
}
const fullDepth = "2147483647" // git's INFINITE_DEPTH, also deepens a shallow dst
// commands checks out co.dst, the first `fetched` of them fetch so a fetched tag can be verified before the rest.
func (co *checkout) commands() (commands [][]string, fetched int) {
repo := func(args ...string) []string { return append([]string{"git", "-C", co.dst}, args...) }
commands = [][]string{
{"git", "init", "--quiet", "--object-format=" + co.objectFormat, co.dst},
repo("config", "remote.origin.url", co.url), // `remote add` fails on a repeated checkout
repo("config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"),
repo("config", "--replace-all", "--fixed-value", credentialsInclude, co.credentials, co.credentials),
}
if co.windows {
commands = append(commands, repo("config", "core.longpaths", "true")) // later steps run git on the checkout too
}
if co.lfs {
commands = append(commands, repo("lfs", "install", "--local"))
}
depth := strconv.Itoa(co.depth)
var refSpecs []string
if co.depth == 0 {
depth = fullDepth
refSpecs = append(refSpecs, "+refs/heads/*:refs/remotes/origin/*")
}
fetch := []string{"fetch", "--force", "--no-tags", "--no-recurse-submodules", "--depth", depth}
if co.progress {
fetch = append(fetch, "--progress")
} else {
fetch = append(fetch, "--no-progress")
}
if co.filter != "" {
fetch = append(fetch, "--filter="+co.filter)
}
if co.fetchTags || co.depth == 0 {
refSpecs = append(refSpecs, "+refs/tags/*:refs/tags/*")
}
tag := strings.HasPrefix(co.ref, "refs/tags/") // fetched itself, which keeps an annotated tag's object
pinned := co.sha != "" && co.ref != "" && !tag
if co.ref != "" && !pinned {
refSpecs = append(refSpecs, "+"+co.ref+":"+trackingRef(co.ref))
}
if co.sha != "" && !tag {
refSpecs = append(refSpecs, co.sha)
}
commands = append(commands, repo(append(append(fetch, "origin"), refSpecs...)...))
if pinned {
commands = append(commands, repo("update-ref", trackingRef(co.ref), co.sha))
}
fetched = len(commands)
if len(co.sparse) > 0 {
mode := "--cone"
if !co.cone {
mode = "--no-cone"
}
commands = append(commands, repo("sparse-checkout", "init", mode), repo(append([]string{"sparse-checkout", "set", "--"}, co.sparse...)...))
}
if branch, ok := strings.CutPrefix(co.ref, "refs/heads/"); ok {
commands = append(commands, repo("checkout", "--force", "--ignore-other-worktrees", "-B", branch, "--track", trackingRef(co.ref)))
} else {
commands = append(commands, repo("checkout", "--force", cmp.Or(co.sha, trackingRef(co.ref))))
}
if len(co.sparse) == 0 { // after the checkout, so a sparse dst of another repository needs nothing of it
commands = append(commands, repo("sparse-checkout", "disable"), repo("config", "--local", "--unset-all", "extensions.worktreeConfig"))
}
if co.lfs && len(co.sparse) == 0 {
commands = append(commands, repo("lfs", "pull", "origin"))
}
if co.clean {
commands = append(commands, repo("clean", "-ffdx"))
}
if co.submodules != "" {
commands = append(commands, co.submoduleCommands(repo)...)
}
if co.output != "" {
commands = append(commands, repo("log", "-1", "--format=commit=%H%nref="+strings.ReplaceAll(co.outputRef, "%", "%%"), "--output="+co.output))
}
return commands, fetched
}
func (co *checkout) submoduleCommands(repo func(args ...string) []string) [][]string {
var recursive []string
if co.submodules == "recursive" {
recursive = []string{"--recursive"}
}
foreach := func(commands ...[]string) []string {
joined := make([]string, len(commands))
for i, command := range commands {
joined[i] = shellquote.Join(command...)
}
return repo(append(append([]string{"submodule", "foreach"}, recursive...), strings.Join(joined, " && "))...)
}
commands := [][]string{repo(append([]string{"submodule", "sync"}, recursive...)...)}
if co.clean {
commands = append(commands, foreach([]string{"git", "clean", "-ffdx"}))
}
update := append([]string{"submodule", "update", "--init", "--force"}, recursive...)
if co.depth > 0 {
update = append(update, "--depth="+strconv.Itoa(co.depth))
}
include := []string{"git", "config", "--replace-all", "--fixed-value", credentialsInclude, co.credentials, co.credentials}
if co.lfs {
return append(commands, repo(update...), foreach([]string{"git", "lfs", "install", "--local"}, []string{"git", "lfs", "pull", "origin"}, include))
}
return append(commands, repo(update...), foreach(include))
}
func (co *checkout) resolve(advertised string) {
ref := co.ref
if !strings.HasPrefix(ref, "refs/") {
co.ref = ""
}
for line := range strings.Lines(advertised) {
value, name, _ := strings.Cut(strings.TrimSpace(line), "\t")
if target, ok := strings.CutPrefix(value, "ref: "); ok {
if name == "HEAD" {
co.ref = target
}
continue
}
co.objectFormat = cmp.Or(co.objectFormat, git.ObjectFormat(value))
switch name {
case "HEAD":
if co.ref == "" {
co.sha = value
}
case "refs/heads/" + ref:
co.ref = name
case "refs/tags/" + ref:
co.ref = cmp.Or(co.ref, name)
}
}
co.objectFormat = cmp.Or(co.objectFormat, "sha1")
}
func trackingRef(ref string) string {
if branch, ok := strings.CutPrefix(ref, "refs/heads/"); ok {
return "refs/remotes/origin/" + branch
}
if pull, ok := strings.CutPrefix(ref, "refs/pull/"); ok {
return "refs/remotes/pull/" + pull
}
return ref
}
func boolInput(inputs map[string]string, name string, fallback bool) bool {
value := strings.TrimSpace(inputs[name])
return strings.EqualFold(value, "true") || value == "" && fallback
}
func workspaceDestination(workspace, checkoutPath string, windows bool) (string, error) {
cleanPath := strings.TrimSpace(checkoutPath)
if windows {
cleanPath = strings.ReplaceAll(cleanPath, `\`, "/")
}
cleanPath = path.Clean(cleanPath)
if path.IsAbs(cleanPath) || cleanPath == ".." || strings.HasPrefix(cleanPath, "../") || windows && len(cleanPath) > 1 && cleanPath[1] == ':' {
return "", fmt.Errorf("checkout: path %q must be relative to the workspace", checkoutPath)
}
return path.Join(workspace, cleanPath), nil
}
func fetchDepth(input string) (int, error) {
input = strings.TrimSpace(input)
if input == "" {
return 1, nil
}
depth, err := strconv.Atoi(input)
if err != nil || depth < 0 {
return 0, fmt.Errorf("checkout: fetch-depth %q must be a non-negative integer", input)
}
return depth, nil
}
@@ -1,416 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package checkout
import (
"cmp"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.dev/actionslib/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func runGit(t *testing.T, args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=test", "[email protected]",
"GIT_COMMITTER_NAME=test", "[email protected]",
"GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null",
)
out, err := cmd.CombinedOutput()
require.NoError(t, err, string(out))
return strings.TrimSpace(string(out))
}
func gitLog(dir string) []string {
out, err := exec.Command("git", "--git-dir", filepath.Join(dir, ".git"), "log", "--format=%s").Output()
if err != nil {
return nil
}
return strings.Fields(string(out))
}
func TestCheckout(t *testing.T) {
server := t.TempDir()
serverURL := (&url.URL{Scheme: "file", Path: "/" + strings.TrimPrefix(filepath.ToSlash(server), "/")}).String()
var sha string
lfsPath, lfsErr := exec.LookPath("git-lfs")
require.True(t, t.Run("fixtures", func(t *testing.T) {
t.Run("history", func(t *testing.T) {
t.Parallel()
work := t.TempDir()
runGit(t, "init", "--template=", "--initial-branch=main", work)
runGit(t, "-C", work, "commit", "--allow-empty", "-m", "c1")
sha = runGit(t, "-C", work, "rev-parse", "HEAD")
runGit(t, "-C", work, "tag", "v1")
runGit(t, "-C", work, "commit", "--allow-empty", "-m", "c2")
runGit(t, "-C", work, "checkout", "-b", "feature")
runGit(t, "-C", work, "commit", "--allow-empty", "-m", "f1")
runGit(t, "-C", work, "checkout", "--orphan", "trunk")
runGit(t, "-C", work, "commit", "--allow-empty", "-m", "t1")
runGit(t, "-C", work, "commit", "--allow-empty", "-m", "t2")
runGit(t, "-C", work, "tag", "trunk", "main")
runGit(t, "clone", "--bare", "--branch", "main", work, filepath.Join(server, "org", "repo"))
runGit(t, "clone", "--bare", "--branch", "trunk", work, filepath.Join(server, "other", "repo"))
runGit(t, "-C", filepath.Join(server, "other", "repo"), "symbolic-ref", "refs/remotes/origin/HEAD", "refs/heads/main")
})
t.Run("sha256", func(t *testing.T) {
t.Parallel()
sha256Repo := filepath.Join(server, "org", "sha256")
runGit(t, "init", "--template=", "--object-format=sha256", "--initial-branch=main", sha256Repo)
runGit(t, "-C", sha256Repo, "commit", "--allow-empty", "-m", "s1")
runGit(t, "-C", sha256Repo, "checkout", "--detach")
})
t.Run("submodules", func(t *testing.T) {
t.Parallel()
publish(t, server, "org/nested", map[string]string{"nested.txt": "nested"}, nil)
publish(t, server, "org/child", map[string]string{"child.txt": "child"}, map[string]string{"nested": "../nested"})
publish(t, server, "org/content", map[string]string{"root.txt": "root", "a/a.txt": "a", "b/b.txt": "b"}, map[string]string{"sub": "../child"})
runGit(t, "-C", filepath.Join(server, "org", "content"), "config", "uploadpack.allowFilter", "true")
})
t.Run("lfs", func(t *testing.T) {
t.Parallel()
oid := fmt.Sprintf("%x", sha256.Sum256([]byte("big")))
pointer := "version https://git-lfs.github.com/spec/v1\noid sha256:" + oid + "\nsize 3\n"
publish(t, server, "org/lfs", map[string]string{".gitattributes": "*.bin filter=lfs diff=lfs merge=lfs -text\n", "keep/big.bin": pointer, "drop/big.bin": pointer}, nil)
object := filepath.Join(server, "org", "lfs", "lfs", "objects", oid[:2], oid[2:4], oid)
require.NoError(t, os.MkdirAll(filepath.Dir(object), 0o755))
require.NoError(t, os.WriteFile(object, []byte("big"), 0o644))
})
}))
host := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(host, "marker"), []byte("marker"), 0o644))
tools := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(tools, "ssh"), []byte(`#!/bin/sh
test -s "$2" || exit 1
printf '%s\n' "$@" > "$SSH_ARGS"
for last; do :; done
exec sh -c "$(printf '%s' "$last" | sed "s#git-upload-pack '/\(.*\)\.git'#git upload-pack '$SSH_SERVER/\1'#")"
`), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(tools, "git-lfs"), []byte(`#!/bin/sh
git config --get-regexp extraheader > "$LFS_HEADERS"
exec "$LFS" "$@"
`), 0o755))
globalConfig := filepath.Join(t.TempDir(), "gitconfig")
require.NoError(t, os.WriteFile(globalConfig, []byte("[protocol \"file\"]\n\tallow = always\n"), 0o644))
sshEvent := func(url string) map[string]any { return map[string]any{"repository": map[string]any{"ssh_url": url}} }
for _, tc := range []struct {
name string
bind, noSkip bool
eventRef string
event map[string]any
before, inputs map[string]string
dst, head, err string
log, refs []string
files, config map[string]string
}{
{name: "bound workspace is skipped", bind: true},
{name: "workflow ref copies host workdir", inputs: map[string]string{"ref": "main", "path": "a/../src"}, dst: "src", files: map[string]string{"marker": "marker"}},
{name: "bound path checks out the event branch", bind: true, inputs: map[string]string{"path": "src"}, dst: "src", head: "main", log: []string{"c1"}},
{name: "no-skip checks out the event branch", noSkip: true, head: "main", log: []string{"c1"}, refs: []string{"refs/remotes/origin/main"}},
{name: "event tag is kept", noSkip: true, eventRef: "refs/tags/v1", log: []string{"c1"}, refs: []string{"refs/tags/v1"}},
{name: "moved event tag fails", noSkip: true, eventRef: "refs/tags/trunk", err: "does not point to the expected commit " + sha},
{name: "deleted event tag fails", noSkip: true, eventRef: "refs/tags/deleted", err: "checkout: clone"},
{
name: "sha input removes previously persisted credentials without clean", noSkip: true, before: map[string]string{"ref": sha},
inputs: map[string]string{"ref": sha, "persist-credentials": "false", "clean": "false"},
log: []string{"c1"},
},
{name: "ref clones shallow", inputs: map[string]string{"ref": "refs/heads/feature"}, head: "feature", log: []string{"f1"}},
{name: "tag ref wins over same-named branch and is kept", inputs: map[string]string{"ref": "refs/tags/trunk"}, log: []string{"c2"}, refs: []string{"refs/tags/trunk"}},
{name: "branch ref wins over same-named tag", inputs: map[string]string{"ref": "refs/heads/trunk"}, head: "trunk", log: []string{"t2"}},
{
name: "short branch wins over same-named tag and fetch-tags fetches every tag", inputs: map[string]string{"ref": "trunk", "fetch-tags": "true"},
head: "trunk", log: []string{"t2"}, refs: []string{"refs/tags/trunk", "refs/tags/v1"},
},
{name: "short tag", inputs: map[string]string{"ref": "v1"}, log: []string{"c1"}, refs: []string{"refs/tags/v1"}},
{
name: "fetch-depth 0 deepens a shallow checkout to every branch and tag", before: map[string]string{"ref": "feature"},
inputs: map[string]string{"ref": "refs/heads/feature", "fetch-depth": "0"}, head: "feature", log: []string{"f1", "c2", "c1"},
refs: []string{"refs/remotes/origin/feature", "refs/remotes/origin/main", "refs/remotes/origin/trunk", "refs/tags/trunk", "refs/tags/v1"},
},
{name: "other repository defaults to its default branch", inputs: map[string]string{"repository": "other/repo"}, head: "trunk", log: []string{"t2"}},
{name: "explicit HEAD checks out the default branch", inputs: map[string]string{"repository": "other/repo", "ref": "HEAD"}, head: "trunk", log: []string{"t2"}},
{name: "detached sha256 HEAD is checked out", inputs: map[string]string{"repository": "org/sha256"}, log: []string{"s1"}},
{
name: "ssh key with the advertised endpoint persists", event: sshEvent("ssh://[email protected]:2222/org/repo.git"),
inputs: map[string]string{"ssh-key": "KEY", "ssh-user": "me", "ssh-known-hosts": "ssh.example ssh-ed25519 AAAA"},
head: "main", log: []string{"c1"}, config: map[string]string{"remote.origin.url": "ssh://[email protected]:2222/org/repo.git"},
},
{
name: "ssh key without persisting is emptied", event: sshEvent("[email protected]:org/repo.git"),
inputs: map[string]string{"ssh-key": "KEY", "persist-credentials": "false"},
head: "main", log: []string{"c1"}, config: map[string]string{"remote.origin.url": "ssh://[email protected]/org/repo.git"},
},
{
name: "sparse cone checkout filters blobs", inputs: map[string]string{"repository": "org/content", "sparse-checkout": "a\n", "show-progress": "false"},
head: "main", log: []string{"content"}, files: map[string]string{"root.txt": "root", "a/a.txt": "a", "b/b.txt": ""},
config: map[string]string{"remote.origin.partialclonefilter": "blob:none"},
},
{
name: "non-cone sparse checkout with an explicit filter", head: "main", log: []string{"content"},
inputs: map[string]string{"repository": "org/content", "sparse-checkout": "b/b.txt", "sparse-checkout-cone-mode": "false", "filter": "blob:limit=1024"},
files: map[string]string{"root.txt": "", "a/a.txt": "", "b/b.txt": "b"}, config: map[string]string{"remote.origin.partialclonefilter": "blob:limit=1024"},
},
{
name: "full checkout after a sparse one restores every file", before: map[string]string{"repository": "org/content", "sparse-checkout": "a"},
inputs: map[string]string{"repository": "org/content", "set-safe-directory": "false"}, head: "main", log: []string{"content"},
files: map[string]string{"root.txt": "root", "a/a.txt": "a", "b/b.txt": "b", "sub/child.txt": ""},
},
{
name: "recursive submodules after plain ones", before: map[string]string{"repository": "org/content", "submodules": "true"},
inputs: map[string]string{"repository": "org/content", "submodules": "Recursive"}, head: "main", log: []string{"content"},
files: map[string]string{"sub/child.txt": "child", "sub/nested/nested.txt": "nested"},
},
{
name: "lfs content stays when narrowing a full checkout to a sparse one", before: map[string]string{"repository": "org/lfs", "lfs": "true"},
inputs: map[string]string{"repository": "org/lfs", "lfs": "true", "sparse-checkout": "keep"}, head: "main", log: []string{"content"},
files: map[string]string{"keep/big.bin": "big", "drop/big.bin": ""},
},
{name: "unknown ref", inputs: map[string]string{"ref": "missing"}, err: "has no ref"},
{name: "unsupported input", inputs: map[string]string{"github-server-url": "https://example.com"}, err: "unsupported input"},
{name: "relative path escaping workspace", inputs: map[string]string{"path": "../x"}, err: "must be relative"},
{name: "absolute path", inputs: map[string]string{"path": "/x"}, err: "must be relative"},
{name: "negative fetch-depth", inputs: map[string]string{"fetch-depth": "-1"}, err: "non-negative"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if tc.inputs["lfs"] == "true" && lfsErr != nil {
t.Skip("needs git-lfs")
}
if tc.inputs["ssh-key"] != "" && runtime.GOOS == "windows" {
t.Skip("Git for Windows puts its own ssh ahead of the fake one on PATH")
}
workspace, runnerTemp := t.TempDir(), t.TempDir()
output := filepath.Join(runnerTemp, "output")
checkout := func(inputs map[string]string) error {
return Main(t.Context(), &action.Context{
Container: &container.HostEnvironment{Path: workspace, TmpDir: runnerTemp, StdOut: io.Discard},
Github: &model.GithubContext{
Repository: "org/repo", Ref: cmp.Or(tc.eventRef, "refs/heads/main"), Sha: sha, ServerURL: serverURL, Token: "tok", Event: tc.event,
},
Inputs: inputs,
HostWorkdir: host,
Workspace: workspace,
BindWorkdir: tc.bind,
NoSkipCheckout: tc.noSkip,
CAFile: "ca.crt",
Env: map[string]string{
"PATH": tools + string(os.PathListSeparator) + os.Getenv("PATH"), "GIT_CONFIG_GLOBAL": globalConfig, "GIT_CONFIG_NOSYSTEM": "1",
"GIT_DIR": host, "GITHUB_OUTPUT": output, "SSH_SERVER": filepath.ToSlash(server), "SSH_ARGS": filepath.Join(runnerTemp, "ssh-args"),
"LFS": lfsPath, "LFS_HEADERS": filepath.Join(runnerTemp, "lfs-headers"),
},
})
}
dst := filepath.Join(workspace, tc.dst)
if tc.err != "" {
require.ErrorContains(t, checkout(tc.inputs), tc.err)
if tc.eventRef == "" {
entries, _ := os.ReadDir(workspace)
assert.Empty(t, entries)
} else {
assert.Nil(t, gitLog(dst))
}
return
}
first := tc.before
if first == nil {
first = tc.inputs
}
require.NoError(t, checkout(first))
repos := []string{dst}
if fileExists(filepath.Join(dst, "sub", ".git")) {
repos = append(repos, filepath.Join(dst, "sub"))
}
for _, repo := range repos {
require.NoError(t, os.WriteFile(filepath.Join(repo, "untracked"), nil, 0o644))
}
require.NoError(t, checkout(tc.inputs))
outputs, err := os.ReadFile(output)
require.NoError(t, err)
assert.Equal(t, tc.log, gitLog(dst))
for name, content := range tc.files {
body, err := os.ReadFile(filepath.Join(dst, name))
assert.Equal(t, content, strings.TrimSpace(string(body)), name)
assert.Equal(t, content == "", os.IsNotExist(err), name)
}
assert.Equal(t, tc.files["marker"] != "", fileExists(filepath.Join(dst, "marker")))
for key, value := range tc.config {
assert.Equal(t, value, gitOutput(dst, "config", key), key)
}
if tc.refs != nil {
assert.Subset(t, strings.Fields(runGit(t, "-C", dst, "for-each-ref", "--format=%(refname)")), tc.refs)
}
if tc.log == nil {
assert.Contains(t, string(outputs), "commit="+sha+"\n")
assert.Contains(t, string(outputs), "ref="+cmp.Or(tc.eventRef, "refs/heads/main")+"\n")
return
}
headArgs := []string{"-C", dst, "rev-parse", "HEAD", "--symbolic-full-name", "HEAD"}
if tc.head != "" {
headArgs = append(headArgs, "--abbrev-ref", "@{u}")
}
head := strings.Fields(runGit(t, headArgs...))
if tc.head == "" {
require.Len(t, head, 2)
assert.Equal(t, "HEAD", head[1])
} else {
require.Len(t, head, 3)
assert.Equal(t, "refs/heads/"+tc.head, head[1])
assert.Equal(t, "origin/"+tc.head, head[2])
}
assert.Contains(t, string(outputs), "commit="+head[0]+"\n")
if inputRef := tc.inputs["ref"]; inputRef != "" && inputRef != sha {
assert.Contains(t, string(outputs), "ref="+inputRef+"\n")
}
persisted := tc.inputs["persist-credentials"] != "false"
for _, repo := range repos {
var credentialIncludes []string
var worktreeConfig string
for entry := range strings.SplitSeq(runGit(t, "-C", repo, "config", "--local", "--no-includes", "--null", "--list"), "\x00") {
key, value, _ := strings.Cut(entry, "\n")
switch key {
case "extensions.worktreeconfig":
worktreeConfig = value
case strings.ToLower(credentialsInclude):
credentialIncludes = append(credentialIncludes, value)
}
}
if repo == dst {
assert.Equal(t, tc.inputs["sparse-checkout"] != "", strings.TrimSpace(worktreeConfig) == "true")
}
assert.Equal(t, tc.inputs["clean"] == "false", fileExists(filepath.Join(repo, "untracked")), repo)
assert.Len(t, strings.Fields(strings.Join(credentialIncludes, "\n")), 1, repo)
headers, _ := exec.Command("git", "-C", repo, "config", "--get-all", "http."+serverURL+"/.extraheader").Output()
assert.Equal(t, persisted, string(headers) == "\nAuthorization: Basic dG9rZW46dG9r\n", repo)
assert.Equal(t, persisted, gitOutput(repo, "config", "http."+serverURL+"/.sslcainfo") != "", repo)
}
if tc.inputs["lfs"] == "true" && runtime.GOOS != "windows" {
headers, _ := os.ReadFile(filepath.Join(runnerTemp, "lfs-headers"))
assert.Equal(t, 1, strings.Count(string(headers), "Authorization"), string(headers))
}
if tc.inputs["ssh-key"] != "" {
keys, _ := filepath.Glob(filepath.Join(runnerTemp, "git-ssh-key-*"))
require.Len(t, keys, 1)
key, _ := os.ReadFile(keys[0])
if persisted {
assert.Equal(t, "KEY\n", string(key))
} else {
assert.Empty(t, key)
}
args, _ := os.ReadFile(filepath.Join(runnerTemp, "ssh-args"))
assert.Contains(t, string(args), "StrictHostKeyChecking=yes")
assert.Equal(t, tc.inputs["ssh-known-hosts"] != "", strings.Contains(string(args), "UserKnownHostsFile="))
assert.Equal(t, persisted, gitOutput(dst, "config", "core.sshCommand") != "")
}
})
}
}
func TestCheckoutTrustsTheRunnerCAAndOffersClientCertOnlyDuringTheStep(t *testing.T) {
var gotCert bool
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotCert = len(r.TLS.PeerCertificates) > 0
w.WriteHeader(http.StatusNotFound)
}))
server.TLS = &tls.Config{ClientAuth: tls.RequireAnyClientCert}
server.StartTLS()
defer server.Close()
pair := server.TLS.Certificates[0]
keyDER, err := x509.MarshalPKCS8PrivateKey(pair.PrivateKey)
require.NoError(t, err)
dir, workspace, runnerTemp := t.TempDir(), t.TempDir(), t.TempDir()
certFile, keyFile := filepath.Join(dir, "client.crt"), filepath.Join(dir, "client.key")
require.NoError(t, os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pair.Certificate[0]}), 0o600))
require.NoError(t, os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0o600))
require.ErrorContains(t, Main(t.Context(), &action.Context{
Container: &container.HostEnvironment{Path: workspace, TmpDir: runnerTemp, StdOut: io.Discard},
Github: &model.GithubContext{Repository: "org/repo", Ref: "refs/heads/main", ServerURL: server.URL},
Inputs: map[string]string{"repository": "other/repo"},
Workspace: workspace,
ClientCertFile: certFile,
ClientKeyFile: keyFile,
CAFile: certFile,
Env: map[string]string{"PATH": os.Getenv("PATH"), "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_NOSYSTEM": "1"},
}), "checkout: other/repo@")
require.True(t, gotCert)
keys, _ := filepath.Glob(filepath.Join(runnerTemp, "git-client-key-*"))
require.Len(t, keys, 1)
key, err := os.ReadFile(keys[0])
require.NoError(t, err)
require.Empty(t, key)
}
func publish(t *testing.T, server, name string, files, submodules map[string]string) {
work := t.TempDir()
runGit(t, "init", "--template=", "--initial-branch=main", work)
for file, content := range files {
require.NoError(t, os.MkdirAll(filepath.Dir(filepath.Join(work, file)), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(work, file), []byte(content), 0o644))
}
runGit(t, "-C", work, "add", ".")
var moduleConfig []byte
for path, url := range submodules {
moduleConfig = fmt.Appendf(moduleConfig, "[submodule %q]\n\tpath = %q\n\turl = %q\n", path, path, url)
require.NoError(t, os.WriteFile(filepath.Join(work, ".gitmodules"), moduleConfig, 0o644))
commit := runGit(t, "--git-dir", filepath.Join(server, name, url), "rev-parse", "main")
runGit(t, "-C", work, "update-index", "--add", "--cacheinfo", "160000,"+commit+","+path)
runGit(t, "-C", work, "add", ".gitmodules")
}
runGit(t, "-C", work, "commit", "-m", "content")
runGit(t, "clone", "--bare", "--quiet", work, filepath.Join(server, name))
}
func gitOutput(dir string, args ...string) string {
out, _ := exec.Command("git", append([]string{"-C", dir}, args...)...).Output()
return strings.TrimSpace(string(out))
}
func fileExists(name string) bool {
_, err := os.Stat(name)
return err == nil
}
func TestWorkspaceDestination(t *testing.T) {
for _, tc := range []struct {
path string
windows bool
want string
}{
{`..\x`, true, ""},
{`C:x`, true, ""},
{`a\b`, true, "/w/a/b"},
{`..\x`, false, `/w/..\x`},
{`a:b`, false, "/w/a:b"},
} {
got, err := workspaceDestination("/w", tc.path, tc.windows)
if tc.want == "" {
assert.ErrorContains(t, err, "must be relative", tc.path)
} else {
require.NoError(t, err, tc.path)
assert.Equal(t, tc.want, got, tc.path)
}
}
}
@@ -1,174 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// Package downloadartifact works like actions/download-artifact v8.
package downloadartifact
import (
"cmp"
"context"
"fmt"
"path/filepath"
"slices"
"strings"
"time"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.com/gitea/runner/internal/pkg/action/artifact"
"golang.org/x/sync/errgroup"
)
var digestBehaviors = []string{"ignore", "info", "warn", "error"}
const downloadAttempts = 5
func Main(ctx context.Context, c *action.Context) error {
if err := run(ctx, c); err != nil {
return action.Failf("Unable to download artifact(s): %w", err)
}
return nil
}
func run(ctx context.Context, c *action.Context) error {
c.ApplyDefaults("name", "", "artifact-ids", "", "path", "", "pattern", "", "merge-multiple", "false", "github-token", "",
"repository", c.Github.Repository, "run-id", c.Github.RunID, "skip-decompress", "false", "digest-mismatch", "error")
name, ids, pattern, token := c.Input("name"), c.Input("artifact-ids"), c.Input("pattern"), c.Input("github-token")
mergeMultiple, err := c.BoolInput("merge-multiple")
if err != nil {
return err
}
skipDecompress, err := c.BoolInput("skip-decompress")
if err != nil {
return err
}
digestMismatch := cmp.Or(c.Input("digest-mismatch"), "error")
if !slices.Contains(digestBehaviors, digestMismatch) {
return action.Failf("Invalid value for 'digest-mismatch': '%s'. Valid options are: %s", digestMismatch, strings.Join(digestBehaviors, ", "))
}
dest := cmp.Or(c.Input("path"), c.Env["GITHUB_WORKSPACE"], c.Workspace)
if strings.HasPrefix(dest, "~") {
home, err := c.Home(ctx)
if err != nil {
return err
}
dest = home + dest[1:]
}
dest = c.Resolve(dest)
if name != "" && ids != "" {
return action.Failf("Inputs 'name' and 'artifact-ids' cannot be used together. Please specify only one.")
}
src, err := newSource(c, token)
if err != nil {
return err
}
artifacts, err := src.list(ctx, name)
if err != nil {
return err
}
slices.SortStableFunc(artifacts, func(a, b artifact.Artifact) int { return cmp.Compare(b.ID, a.ID) })
seen := map[string]bool{}
artifacts = slices.DeleteFunc(artifacts, func(a artifact.Artifact) bool {
duplicate := seen[a.Name]
seen[a.Name] = true
return duplicate
})
if name == "" {
c.Infof("Found %d artifact(s)", len(artifacts))
}
switch {
case name != "":
if len(artifacts) == 0 {
return action.Failf("Artifact not found for name: %s\nPlease ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.", name)
}
artifacts = artifacts[:1]
case ids != "":
var wanted []int64
for id := range strings.SplitSeq(ids, ",") {
if id = strings.TrimSpace(id); id == "" {
continue
}
parsed, err := action.ParseInt(id)
if err != nil {
return action.Failf("Invalid artifact ID: '%s'. Must be a number.", id)
}
wanted = append(wanted, int64(parsed))
}
if len(wanted) == 0 {
return action.Failf("No valid artifact IDs provided in 'artifact-ids' input")
}
artifacts = slices.DeleteFunc(artifacts, func(a artifact.Artifact) bool { return !slices.Contains(wanted, a.ID) })
if len(artifacts) == 0 {
return action.Failf("None of the provided artifact IDs were found")
}
case pattern != "":
artifacts = slices.DeleteFunc(artifacts, func(a artifact.Artifact) bool { return !matchName(pattern, a.Name) })
}
for _, art := range artifacts {
if art.Name == "" || art.Name == "." || art.Name == ".." || strings.ContainsAny(art.Name, `/\`) || c.Windows() && !filepath.IsLocal(art.Name) {
return action.Failf("Artifact name is not valid: %s", art.Name)
}
}
mismatches := make([]string, len(artifacts))
group, groupCtx := errgroup.WithContext(ctx)
group.SetLimit(5)
for i, art := range artifacts {
target := dest
if name == "" && !mergeMultiple && len(artifacts) > 1 {
target = c.Join(dest, art.Name)
}
group.Go(func() error {
mismatch, err := fetch(groupCtx, c, src, art, target, skipDecompress)
if err != nil {
return err
}
if mismatch {
mismatches[i] = art.Name
message := fmt.Sprintf("Artifact '%s' digest validation failed. Please verify the integrity of the artifact.", art.Name)
switch digestMismatch {
case "info":
c.Infof("%s", message)
case "warn":
c.Warning("%s", message)
}
}
return nil
})
}
if err := group.Wait(); err != nil {
return err
}
mismatches = slices.DeleteFunc(mismatches, func(name string) bool { return name == "" })
if len(mismatches) > 0 && digestMismatch == "error" {
return action.Failf("Digest validation failed for artifact(s): %s. Use 'digest-mismatch: warn' to continue on mismatch.", strings.Join(mismatches, ", "))
}
c.Infof("Total of %d artifact(s) downloaded", len(artifacts))
return c.SetOutputs(ctx, "download-path", dest)
}
func fetch(ctx context.Context, c *action.Context, src *source, art artifact.Artifact, target string, skipDecompress bool) (bool, error) {
if err := c.Container.CopyTarStream(ctx, target, func(*container.TarWriter) error { return nil }); err != nil {
return false, err
}
signed, err := src.signedURL(ctx, art)
if err != nil {
return false, err
}
for attempt := 1; attempt <= downloadAttempts; attempt++ {
digest, err := fetchOnce(ctx, c, src, signed, target, skipDecompress)
if err == nil {
return art.Digest != "" && art.Digest != digest, nil
}
common.Logger(ctx).Debugf("Failed to download artifact after %d retries due to %v. Retrying in 5 seconds...", attempt, err)
select {
case <-ctx.Done():
return false, ctx.Err()
case <-time.After(5 * time.Second):
}
}
return false, action.Failf("Unable to download and extract artifact: Artifact download failed after %d retries.", downloadAttempts)
}
@@ -1,316 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package downloadartifact
import (
"archive/zip"
"bytes"
"context"
"errors"
"fmt"
"io"
"maps"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
"gitea.com/gitea/runner/act/artifacts"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.com/gitea/runner/internal/pkg/action/artifact"
"gitea.dev/actionslib/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type zipEntry struct {
name, body string
mode os.FileMode
}
func zipOf(t *testing.T, entries ...zipEntry) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, e := range entries {
header := &zip.FileHeader{Name: e.name, Method: zip.Deflate}
header.SetMode(e.mode)
w, err := zw.CreateHeader(header)
require.NoError(t, err)
_, err = io.WriteString(w, e.body)
require.NoError(t, err)
}
require.NoError(t, zw.Close())
return buf.Bytes()
}
type harness struct {
t *testing.T
server, store string
client *artifact.Client
workspace string
env map[string]string
mu sync.Mutex
logs, annotation []string
}
func newHarness(t *testing.T) *harness {
t.Helper()
store := t.TempDir()
router := http.NewServeMux()
artifacts.RegisterV4(router, store)
server := httptest.NewServer(router)
t.Cleanup(server.Close)
client, err := artifact.New(server.URL, artifacts.LocalRuntimeToken("7", time.Hour), nil)
require.NoError(t, err)
return &harness{t: t, server: server.URL, store: store, client: client, workspace: t.TempDir()}
}
func (h *harness) upload(name, mimeType string, content []byte) int64 {
h.t.Helper()
ctx := h.t.Context()
signed, err := h.client.Create(ctx, name, mimeType, nil)
require.NoError(h.t, err)
uploaded, err := h.client.Upload(ctx, signed, mimeType, bytes.NewReader(content), 2, time.Minute)
require.NoError(h.t, err)
id, err := h.client.Finalize(ctx, name, uploaded.Size, uploaded.Digest)
require.NoError(h.t, err)
return id
}
func (h *harness) run(inputs map[string]string) error {
h.logs, h.annotation = nil, nil
env := map[string]string{"GITHUB_OUTPUT": filepath.Join(h.workspace, "output")}
maps.Copy(env, h.env)
return Main(h.t.Context(), &action.Context{
Container: &container.HostEnvironment{},
Github: &model.GithubContext{Repository: "owner/repo", RunID: "7"},
Inputs: inputs,
Workspace: h.workspace,
Env: env,
ResultsURL: h.server,
RuntimeToken: artifacts.LocalRuntimeToken("7", time.Hour),
Infof: func(format string, args ...any) {
h.mu.Lock()
defer h.mu.Unlock()
h.logs = append(h.logs, fmt.Sprintf(format, args...))
},
Warning: func(format string, args ...any) {
h.mu.Lock()
defer h.mu.Unlock()
h.annotation = append(h.annotation, "warning: "+fmt.Sprintf(format, args...))
},
})
}
func (h *harness) read(rel string) string {
h.t.Helper()
content, err := os.ReadFile(filepath.Join(h.workspace, filepath.FromSlash(rel)))
require.NoError(h.t, err)
return string(content)
}
func TestDownload(t *testing.T) {
h := newHarness(t)
first := h.upload("alpha", "", zipOf(t, zipEntry{name: "a.txt", body: "a1"}))
_, err := h.client.Delete(t.Context(), "alpha")
require.NoError(t, err)
archive := zipOf(t,
zipEntry{name: "run.sh", body: "#!/bin/sh\n", mode: 0o755},
zipEntry{name: "empty/", mode: os.ModeDir | 0o755},
zipEntry{name: "nested/../a.txt", body: "a2"},
zipEntry{name: "empty.txt"},
)
second := h.upload("alpha", "", archive)
h.upload("beta ü.txt", "text/plain", []byte("plain text"))
h.upload(".hidden", "", zipOf(t, zipEntry{name: "h.txt", body: "h"}))
for _, test := range []struct {
inputs map[string]string
files map[string]string
}{
{map[string]string{"name": "alpha", "path": "named"}, map[string]string{"named/a.txt": "a2", "named/run.sh": "#!/bin/sh\n", "named/empty.txt": ""}},
{map[string]string{"path": "all"}, map[string]string{"all/alpha/a.txt": "a2", "all/beta ü.txt/beta ü.txt": "plain text", "all/.hidden/h.txt": "h"}},
{map[string]string{"path": "merged", "merge-multiple": "true"}, map[string]string{"merged/a.txt": "a2", "merged/beta ü.txt": "plain text", "merged/h.txt": "h"}},
{map[string]string{"path": "pattern", "pattern": "*"}, map[string]string{"pattern/alpha/a.txt": "a2", "pattern/beta ü.txt/beta ü.txt": "plain text"}},
{map[string]string{"path": "ids", "artifact-ids": fmt.Sprintf("%dtrailing, %d", second, first), "pattern": "ignored"}, map[string]string{"ids/a.txt": "a2"}},
{map[string]string{"name": "alpha", "path": "kept", "skip-decompress": "true"}, map[string]string{"kept/alpha.zip": string(archive)}},
{map[string]string{"path": "none", "pattern": "nope-*", "repository": "ignored", "run-id": "invalid"}, nil},
} {
require.NoError(t, h.run(test.inputs))
assert.Contains(t, h.read("output"), "download-path="+filepath.Join(h.workspace, test.inputs["path"])+"\n")
for name, body := range test.files {
assert.Equal(t, body, h.read(name))
}
}
assert.Contains(t, h.logs, "Total of 0 artifact(s) downloaded")
assert.NoDirExists(t, filepath.Join(h.workspace, "pattern", ".hidden"))
assert.DirExists(t, filepath.Join(h.workspace, "named", "empty"))
if runtime.GOOS != "windows" {
info, err := os.Stat(filepath.Join(h.workspace, "named", "run.sh"))
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o644), info.Mode())
assert.WithinDuration(t, time.Now(), info.ModTime(), time.Minute)
}
for _, test := range []struct {
inputs map[string]string
error string
}{
{map[string]string{"artifact-ids": strconv.FormatInt(first, 10)}, "None of the provided artifact IDs were found"},
{map[string]string{"name": "gone"}, "Artifact not found for name: gone"},
{map[string]string{"name": "alpha", "artifact-ids": "1"}, "cannot be used together"},
{map[string]string{"artifact-ids": "x"}, "Invalid artifact ID: 'x'"},
{map[string]string{"artifact-ids": " , "}, "No valid artifact IDs provided"},
{map[string]string{"digest-mismatch": "loud"}, "Valid options are: ignore, info, warn, error"},
{map[string]string{"merge-multiple": "yes"}, "Core Schema"},
} {
require.ErrorContains(t, h.run(test.inputs), test.error)
}
h.env = map[string]string{"GITHUB_WORKSPACE": filepath.Join(h.workspace, "overridden")}
require.NoError(t, h.run(map[string]string{"name": "beta ü.txt"}))
assert.Equal(t, "plain text", h.read("overridden/beta ü.txt"))
h.env = map[string]string{"HOME": filepath.Join(h.workspace, "home")}
require.NoError(t, h.run(map[string]string{"name": "beta ü.txt", "path": "~/tilde", "retention-days": "1"}))
assert.Equal(t, "plain text", h.read("home/tilde/beta ü.txt"))
assert.Equal(t, []string{"warning: Unexpected input(s) 'retention-days', valid inputs are ['name', 'artifact-ids', 'path', 'pattern', 'merge-multiple', 'github-token', 'repository', 'run-id', 'skip-decompress', 'digest-mismatch']"}, h.annotation)
h.upload("..", "", archive)
require.ErrorContains(t, h.run(map[string]string{}), "Artifact name is not valid: ..")
}
func TestDownloadFormats(t *testing.T) {
for _, test := range []struct {
contentType, url string
zip bool
}{
{"application/zip", "raw", true},
{"Application/X-Zip-Compressed; charset=binary", "raw", true},
{"application/zip-compressed", "raw", true},
{"", "FILE.ZIP?sig=x", true},
{"", "raw?name=file.zip", false},
} {
assert.Equal(t, test.zip, isZip(&http.Response{Header: http.Header{"Content-Type": {test.contentType}}}, "https://example.test/"+test.url))
}
for _, test := range []struct {
pattern, name string
want bool
}{
{"a*", "alpha", true},
{"*", ".hidden", false},
{"!alpha", "beta", true},
{"#alpha", "alpha", false},
} {
assert.Equal(t, test.want, matchName(test.pattern, test.name))
}
}
func TestDownloadDigestMismatch(t *testing.T) {
h := newHarness(t)
h.upload("art", "", zipOf(t, zipEntry{name: "f.txt", body: "original"}))
blobs, err := filepath.Glob(filepath.Join(h.store, "v4", "*", "*", "blob"))
require.NoError(t, err)
require.Len(t, blobs, 1)
tampered := zipOf(t, zipEntry{name: "f.txt", body: "tampered"})
require.NoError(t, os.WriteFile(blobs[0], tampered, 0o644))
for _, behavior := range []string{"", "ignore", "info", "warn", "error"} {
err = h.run(map[string]string{"name": "art", "path": "digest", "digest-mismatch": behavior})
if behavior == "" || behavior == "error" {
require.ErrorContains(t, err, "Digest validation failed for artifact(s): art. Use 'digest-mismatch: warn' to continue on mismatch.")
} else {
require.NoError(t, err)
}
assert.Equal(t, "tampered", h.read("digest/f.txt"))
if behavior == "warn" {
assert.Equal(t, []string{"warning: Artifact 'art' digest validation failed. Please verify the integrity of the artifact."}, h.annotation)
} else {
assert.Empty(t, h.annotation)
}
if behavior == "info" {
assert.Contains(t, h.logs, "Artifact 'art' digest validation failed. Please verify the integrity of the artifact.")
}
}
}
func TestDownloadFromAnotherRun(t *testing.T) {
h := &harness{t: t, workspace: t.TempDir()}
archive := zipOf(t, zipEntry{name: "other.txt", body: "from run 12"})
var expired atomic.Bool
var zipCalls atomic.Int32
blob := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Empty(t, r.Header.Get("Authorization"))
w.Header().Set("Content-Type", "application/zip")
_, _ = w.Write(archive)
}))
defer blob.Close()
gitea := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/repos/someone/else/actions/runs/12/artifacts":
assert.Equal(t, "token pat", r.Header.Get("Authorization"))
_, _ = io.WriteString(w, `{"total_count":3,"artifacts":[
{"id":10,"name":"dist","size_in_bytes":1,"expired":false},
{"id":30,"name":"dist","size_in_bytes":1,"expired":true},
{"id":20,"name":"dist","size_in_bytes":1,"expired":false}]}`)
case "/api/v1/repos/someone/else/actions/artifacts/20/zip":
zipCalls.Add(1)
if expired.Load() {
http.Error(w, "Artifact has expired", http.StatusNotFound)
return
}
http.Redirect(w, r, blob.URL+"/raw/20?sig=abc", http.StatusFound)
default:
http.NotFound(w, r)
}
}))
defer gitea.Close()
h.server = gitea.URL
inputs := map[string]string{"github-token": "pat", "repository": "someone/else/ignored", "run-id": "12", "path": "other"}
require.NoError(t, h.run(inputs))
assert.Equal(t, "from run 12", h.read("other/other.txt"))
assert.Contains(t, h.logs, "Found 1 artifact(s)")
expired.Store(true)
require.ErrorContains(t, h.run(inputs), "Artifact has expired")
assert.Equal(t, int32(2), zipCalls.Load(), "an API error is not retried")
require.ErrorContains(t, h.run(map[string]string{"github-token": "pat", "repository": "nobody"}), "Invalid repository: 'nobody'. Must be in format owner/repo")
require.ErrorContains(t, h.run(map[string]string{"github-token": "pat", "run-id": "0"}), "Invalid run-id: '0'")
}
func TestDownloadRetries(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
attempts := 0
target := filepath.Join(t.TempDir(), "download")
started := time.Now()
_, err := fetch(t.Context(), &action.Context{Container: &container.HostEnvironment{}}, &source{
signedURL: func(context.Context, artifact.Artifact) (string, error) {
assert.DirExists(t, target)
return "https://example.test/artifact.zip", nil
},
download: func(context.Context, string, time.Duration) (*http.Response, error) {
attempts++
return nil, errors.New("connection failed")
},
}, artifact.Artifact{}, target, false)
require.EqualError(t, err, "Unable to download and extract artifact: Artifact download failed after 5 retries.")
assert.Equal(t, 5, attempts)
assert.Equal(t, 25*time.Second, time.Since(started))
})
}
func TestDownloadRejectsEscapingZipPaths(t *testing.T) {
for _, name := range []string{"../escape.txt", "a/../../escape.txt", "/absolute.txt", `..\escape.txt`} {
t.Run(name, func(t *testing.T) {
archive := zipOf(t, zipEntry{name: name, body: "escape"})
require.ErrorContains(t, extractZip(t.Context(), &action.Context{Container: &container.HostEnvironment{}}, bytes.NewReader(archive), int64(len(archive)), t.TempDir()), "Artifact entry path is not valid")
})
}
}
@@ -1,142 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package downloadartifact
import (
"archive/tar"
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"slices"
"strings"
"time"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"github.com/bmatcuk/doublestar/v4"
)
func fetchOnce(ctx context.Context, c *action.Context, src *source, signed, target string, skipDecompress bool) (string, error) {
resp, err := src.download(ctx, signed, 30*time.Second)
if err != nil {
return "", err
}
defer resp.Body.Close()
file, err := os.CreateTemp("", "artifact-*")
if err != nil {
return "", err
}
defer os.Remove(file.Name())
defer file.Close()
hash := sha256.New()
size, err := io.Copy(io.MultiWriter(file, hash), resp.Body)
if err != nil {
return "", err
}
digest := "sha256:" + hex.EncodeToString(hash.Sum(nil))
if isZip(resp, signed) && !skipDecompress {
return digest, extractZip(ctx, c, file, size, target)
}
fileName := rawFileName(resp.Header.Get("Content-Disposition"))
if fileName == ".." || strings.ContainsAny(fileName, `/\`) || c.Windows() && !filepath.IsLocal(fileName) {
return "", action.Failf("Artifact filename is not valid: %s", fileName)
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return digest, err
}
return digest, c.Container.CopyTarStream(ctx, target, func(tw *container.TarWriter) error {
if err := tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: fileName, Mode: 0o644, Size: size, ModTime: time.Now()}); err != nil {
return err
}
_, err := io.Copy(tw, file)
return err
})
}
var zipTypes = []string{"application/zip", "application/x-zip-compressed", "application/zip-compressed"}
func isZip(resp *http.Response, signed string) bool {
mediaType, _, _ := strings.Cut(resp.Header.Get("Content-Type"), ";")
mediaType = strings.ToLower(strings.TrimSpace(mediaType))
signedURL, _ := url.Parse(signed)
return slices.Contains(zipTypes, mediaType) || signedURL != nil && strings.HasSuffix(strings.ToLower(signedURL.Path), ".zip")
}
func rawFileName(disposition string) string {
_, params, err := mime.ParseMediaType(disposition)
name := params["filename"] // filename* arrives decoded in here
if err != nil || name == "" {
return "artifact"
}
if unescaped, err := url.PathUnescape(name); err == nil && !strings.Contains(strings.ToLower(disposition), "filename*") {
name = unescaped
}
if name = path.Base(name); name == "/" || name == "." {
return "artifact"
}
return name
}
func extractZip(ctx context.Context, c *action.Context, file io.ReaderAt, size int64, target string) error {
reader, err := zip.NewReader(file, size)
if err != nil {
return err
}
now := time.Now()
return c.Container.CopyTarStream(ctx, target, func(tw *container.TarWriter) error {
for _, entry := range reader.File {
name := path.Clean(strings.ReplaceAll(entry.Name, `\`, "/"))
if name == "." {
continue
}
if path.IsAbs(name) || name == ".." || strings.HasPrefix(name, "../") || c.Windows() && !filepath.IsLocal(name) {
return action.Failf("Artifact entry path is not valid: %s", entry.Name)
}
header := &tar.Header{Typeflag: tar.TypeReg, Name: name, Mode: 0o644, Size: int64(entry.UncompressedSize64), ModTime: now}
if entry.FileInfo().IsDir() {
header.Typeflag, header.Name, header.Mode, header.Size = tar.TypeDir, name+"/", 0o755, 0
}
if err := tw.WriteHeader(header); err != nil {
return err
}
body, err := entry.Open()
if err != nil {
return err
}
_, err = io.Copy(tw, body)
if err := errors.Join(err, body.Close()); err != nil {
return err
}
}
return nil
})
}
func matchName(pattern, name string) bool {
if strings.HasPrefix(pattern, "#") {
return false
}
negate := false
for strings.HasPrefix(pattern, "!") {
negate, pattern = !negate, pattern[1:]
}
matched, err := doublestar.Match(pattern, name)
if err != nil {
matched = pattern == name
}
if strings.HasPrefix(name, ".") && !strings.HasPrefix(pattern, ".") {
matched = false
}
return matched != negate
}
@@ -1,60 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package downloadartifact
import (
"context"
"net/http"
"strings"
"time"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.com/gitea/runner/internal/pkg/action/artifact"
)
type source struct {
list func(context.Context, string) ([]artifact.Artifact, error)
signedURL func(context.Context, artifact.Artifact) (string, error)
download func(context.Context, string, time.Duration) (*http.Response, error)
}
func newSource(c *action.Context, token string) (*source, error) {
if token == "" {
client, err := artifact.New(c.ResultsURL, c.RuntimeToken, c.Transport)
if err != nil {
return nil, err
}
client.Logf = c.Infof
return &source{
list: client.List,
signedURL: func(ctx context.Context, art artifact.Artifact) (string, error) {
return client.SignedURL(ctx, art.Name)
},
download: client.Download,
}, nil
}
parts := append(strings.Split(c.Input("repository"), "/"), "")
owner, repo := parts[0], parts[1]
if owner == "" || repo == "" {
return nil, action.Failf("Invalid repository: '%s'. Must be in format owner/repo", c.Input("repository"))
}
runID, err := action.ParseInt(c.Input("run-id"))
if err != nil || runID <= 0 { // Gitea lists the artifacts of every run for those
return nil, action.Failf("Invalid run-id: '%s'. Must be a number.", c.Input("run-id"))
}
rest, err := artifact.NewREST(c.ResultsURL, token, c.Transport)
if err != nil {
return nil, err
}
rest.Logf = c.Infof
return &source{
list: func(ctx context.Context, name string) ([]artifact.Artifact, error) {
return rest.List(ctx, owner, repo, int64(runID), name)
},
signedURL: func(ctx context.Context, art artifact.Artifact) (string, error) {
return rest.DownloadURL(ctx, owner, repo, art.ID)
},
download: rest.Download,
}, nil
}
-239
View File
@@ -1,239 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// Package glob ports the pattern semantics of the JavaScript @actions/glob 0.6.1 package, as
// bundled in actions/upload-artifact, without walking a filesystem. Malformed bracket expressions
// and some non-ASCII case folding on Windows can match differently.
package glob
import (
"fmt"
"path"
"strings"
"sync"
)
type Options struct {
Workdir string // absolute; relative patterns resolve against it
Home func() (string, error) // replaces ~, called once and only when a pattern uses it
Windows bool // Windows path flavour
ImplicitDescendants bool
}
type MatchKind int
const (
MatchNone MatchKind = 0
MatchDirectory MatchKind = 1
MatchFile MatchKind = 2
MatchAll = MatchDirectory | MatchFile
)
type Globber struct {
patterns []*pattern
searchPaths []string
}
// Parse parses newline separated patterns like DefaultGlobber.create.
func Parse(patterns string, o Options) (*Globber, error) {
w := flavour{o.Windows}
env := parseEnv{w: w, cwd: w.normalizeSeparators(o.Workdir)}
if o.Home != nil {
env.home = sync.OnceValues(o.Home)
}
if env.cwd == "" || !w.hasAbsoluteRoot(env.cwd) {
return nil, fmt.Errorf("workdir '%s' is not an absolute path", o.Workdir)
}
if o.Windows {
patterns = strings.ReplaceAll(patterns, "\r\n", "\n")
patterns = strings.ReplaceAll(patterns, "\r", "\n")
}
var parsed []*pattern
for line := range strings.SplitSeq(patterns, "\n") {
line = jsTrim(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
p, err := newPattern(line, false, env)
if err != nil {
return nil, err
}
parsed = append(parsed, p)
}
g := &Globber{searchPaths: searchPaths(parsed, w)}
for _, p := range parsed {
g.patterns = append(g.patterns, p)
if o.ImplicitDescendants && (p.trailingSeparator || p.segments[len(p.segments)-1] != "**") {
s := jsTrim(w.joinSegments(append(append([]string(nil), p.segments...), "**")))
if p.negate {
s = "!" + s
}
implicit, err := newPattern(s, true, env)
if err != nil {
return nil, err
}
g.patterns = append(g.patterns, implicit)
}
}
return g, nil
}
// SearchPaths returns the literal prefix of each include pattern, without duplicates and
// paths nested under another search path.
func (g *Globber) SearchPaths() []string {
return append([]string(nil), g.searchPaths...)
}
// Match ORs in each include pattern and masks out each exclude pattern, in order.
func (g *Globber) Match(p string) MatchKind {
result := MatchNone
for _, pat := range g.patterns {
if pat.negate {
result &^= pat.match(p)
} else {
result |= pat.match(p)
}
}
return result
}
// PartialMatch reports whether an include pattern may match descendants of p.
func (g *Globber) PartialMatch(p string) bool {
for _, pat := range g.patterns {
if !pat.negate && pat.partialMatch(p) {
return true
}
}
return false
}
func searchPaths(patterns []*pattern, w flavour) []string {
key := func(p *pattern) string {
if w.windows {
return strings.ToUpper(p.searchPath)
}
return p.searchPath
}
const candidate, included = 1, 2
seen := map[string]int{}
for _, p := range patterns {
if !p.negate {
seen[key(p)] = candidate
}
}
var result []string
for _, p := range patterns {
if p.negate {
continue
}
k := key(p)
if seen[k] == included {
continue
}
foundAncestor := false
for temp, parent := k, w.dirname(k); parent != temp; temp, parent = parent, w.dirname(parent) {
if seen[parent] != 0 {
foundAncestor = true
break
}
}
if !foundAncestor {
result = append(result, p.searchPath)
seen[k] = included
}
}
return result
}
// LeastCommonAncestor ports getMultiPathLCA from upload-artifact's search.ts, which becomes the
// artifact root when there are several search paths. Segments compare case-sensitively there,
// even on Windows.
func LeastCommonAncestor(paths []string, windows bool) string {
switch len(paths) {
case 0:
return ""
case 1:
return paths[0]
}
w := flavour{windows}
sep := w.sep()
split := make([][]string, len(paths))
smallest := -1
for i, p := range paths {
if w.windows {
p = w.normalizeSeparators(p)
} else {
p = path.Clean(p)
}
split[i] = strings.Split(p, sep)
if smallest < 0 || len(split[i]) < smallest {
smallest = len(split[i])
}
}
var common []string
if strings.HasPrefix(paths[0], sep) {
common = append(common, sep)
}
for i := 0; i < smallest; i++ {
same := true
for _, s := range split[1:] {
if s[i] != split[0][i] {
same = false
break
}
}
if !same {
break
}
common = append(common, split[0][i])
}
return w.nodeJoin(common)
}
// nodeJoin ports Node's path.join for the already normalized segments LeastCommonAncestor produces.
func (w flavour) nodeJoin(parts []string) string {
var nonEmpty []string
for _, p := range parts {
if p != "" {
nonEmpty = append(nonEmpty, p)
}
}
if len(nonEmpty) == 0 {
return "."
}
joined := strings.Join(nonEmpty, w.sep())
if !w.windows {
return path.Clean(joined)
}
first := nonEmpty[0]
needsReplace, slashCount := true, 0
if w.isSep(first[0]) {
slashCount++
if len(first) > 1 && w.isSep(first[1]) {
slashCount++
if len(first) > 2 {
if w.isSep(first[2]) {
slashCount++
} else {
needsReplace = false
}
}
}
}
if needsReplace {
for slashCount < len(joined) && w.isSep(joined[slashCount]) {
slashCount++
}
if slashCount >= 2 {
joined = `\` + joined[slashCount:]
}
}
// path.win32.normalize turns a bare drive into the drive relative "C:.".
if reDriveOnly.MatchString(joined) {
return joined + "."
}
return joined
}
-216
View File
@@ -1,216 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package glob
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
posix = Options{Workdir: "/work/cwd-with-[and]", Home: home("/home/home-with-[and]")}
windows = Options{Workdir: `C:\work\cwd-with-[and]`, Home: home(`C:\Users\home-with-[and]`), Windows: true}
)
func home(dir string) func() (string, error) {
return func() (string, error) { return dir, nil }
}
func implicit(o Options) Options {
o.ImplicitDescendants = true
return o
}
func TestHomeResolvedLazilyOnce(t *testing.T) {
calls := 0
o := Options{Workdir: "/w", Home: func() (string, error) { calls++; return "/h", nil }}
_, err := Parse("~/a\n! ~/b", o)
require.NoError(t, err)
_, err = Parse("/a", o)
require.NoError(t, err)
assert.Equal(t, 1, calls)
}
func TestMatch(t *testing.T) {
tests := []struct {
name string
patterns string
opts Options
want map[string]MatchKind
}{
{"negate markers toggle", "/a/*.txt\n!!/a/two.txt\n!/a/one.txt\n!!!/a/three.txt", posix, map[string]MatchKind{
"/a/two.txt": MatchAll, "/a/one.txt": MatchNone, "/a/three.txt": MatchNone, "/a/x.txt": MatchAll,
}},
{"home is escaped", "~/m*", posix, map[string]MatchKind{
"/home/home-with-[and]/match": MatchAll, "/home/home-with-[and]/not-match": MatchNone, "/home/home-with-a/match": MatchNone,
}},
{"workdir is escaped", "m*", posix, map[string]MatchKind{
"/work/cwd-with-[and]/match": MatchAll, "/work/cwd-with-[and]/not-match": MatchNone,
}},
{"workdir is escaped on windows", "m*\nC:n*\n" + `\work\cwd-with-[[]and]\o*`, windows, map[string]MatchKind{
`C:\work\cwd-with-[and]\match`: MatchAll, `C:\work\cwd-with-[and]\nope`: MatchAll, `C:\work\cwd-with-[and]\ok`: MatchAll, `C:\work\cwd-with-[and]\x`: MatchNone,
}},
{"globstar matches the directory before it", "/foo/bar/**", posix, map[string]MatchKind{
"/": MatchNone, "/foo": MatchNone, "/foo/bar": MatchAll, "/foo/bar/baz": MatchAll,
}},
{"globstar matches root", "/**", posix, map[string]MatchKind{"/": MatchAll}},
{"globstar matches root on windows", `C:\**`, windows, map[string]MatchKind{`C:\`: MatchAll}},
{"case sensitive on posix", "/Foo/**/Baz", posix, map[string]MatchKind{
"/Foo/Baz": MatchAll, "/Foo/bAZ": MatchNone, "/fOO/bar/Baz": MatchNone,
}},
{"case insensitive on windows", "C:/Foo/**/Baz", windows, map[string]MatchKind{
`C:\Foo\Baz`: MatchAll, `c:\Foo\bAZ`: MatchAll, "C:/fOO/bar/bAZ": MatchAll, `C:\Foo\Bar`: MatchNone,
}},
{"leading dot segment", ".\n./foo\n.bar", posix, map[string]MatchKind{
"/work/cwd-with-[and]": MatchAll, "/work/cwd-with-[and]/foo": MatchAll, "/work/cwd-with-[and]/.bar": MatchAll,
"/work/cwd-with-[and]/bar": MatchNone, "/work/cwd-with-[and]bar": MatchNone,
}},
{"leading tilde segment", "~\n~/foo\n~bar", posix, map[string]MatchKind{
"/home/home-with-[and]": MatchAll, "/home/home-with-[and]/foo": MatchAll, "/work/cwd-with-[and]/~bar": MatchAll,
"/home/home-with-[and]/bar": MatchNone, "/home/home-with-[and]bar": MatchNone,
}},
{"windows relative roots", "C:\nC:foo\nD:\nD:bar\n" + `\work\cwd-with-[[]and]\baz`, windows, map[string]MatchKind{
`C:\work\cwd-with-[and]`: MatchAll, `C:\work\cwd-with-[and]\foo`: MatchAll, `C:\foo`: MatchNone,
`D:\`: MatchDirectory, `D:\bar`: MatchAll, `D:\foo`: MatchNone, `C:\work\cwd-with-[and]\baz`: MatchAll,
}},
{"windows unc", `\\srv\share\a\*`, windows, map[string]MatchKind{`\\srv\share\a\b`: MatchAll, `//SRV/share/a/b`: MatchAll, `\\srv\other\a\b`: MatchNone}},
{"trailing separator matches directories only", "/foo/**/", posix, map[string]MatchKind{
"/": MatchNone, "/foo/": MatchDirectory, "/foo/bar": MatchDirectory, "/foo/bar/baz": MatchDirectory,
}},
{"backslash is a separator on windows", `C:\foo\`, windows, map[string]MatchKind{`C:\foo`: MatchDirectory}},
{"backslash escapes on posix", `/foo\*/b\[a]r`, posix, map[string]MatchKind{"/foo*/b[a]r": MatchAll, "/fooo/bar": MatchNone}},
{"interleaved excludes", "/**/*.proj\n/**/README.txt\n!/**/solution2/**\n/**/*.sln\n!/**/proj2/README.txt", posix, map[string]MatchKind{
"/solution1/proj1/proj1.proj": MatchAll, "/solution1/proj1/README.txt": MatchAll, "/solution1/proj2/README.txt": MatchNone,
"/solution1/solution1.sln": MatchAll, "/solution2/proj1/proj1.proj": MatchNone, "/solution2/solution2.sln": MatchAll,
}},
{"exclude directories", "C:/foo/**\n!C:/foo/**/", windows, map[string]MatchKind{
`C:\`: MatchNone, `C:\foo`: MatchFile, `C:\foo\bar`: MatchFile,
}},
{"dot is on, brace and extglob are off", "/a/*\n/b/{x,y}\n/c/+(x)\n/d/#e", posix, map[string]MatchKind{
"/a/.hidden": MatchAll, "/a/.": MatchNone, "/b/{x,y}": MatchAll, "/b/x": MatchNone, "/c/+(x)": MatchAll, "/c/x": MatchNone, "/d/#e": MatchAll,
}},
{"character classes", "/a/[!x]\n/b/[a-c]z\n/c/[z-a]\n/d/[]]", posix, map[string]MatchKind{
"/a/y": MatchAll, "/a/x": MatchNone, "/b/bz": MatchAll, "/b/dz": MatchNone, "/c/[z-a]": MatchAll, "/c/z": MatchNone, "/d/]": MatchAll,
}},
{"unclosed class splices undefined like minimatch 3", "C:/foo/b[\\!]r/b*", windows, map[string]MatchKind{
"C:/foo/b[undefined/!]r/baz": MatchAll,
}},
{"implicit descendants", "/foo\n/bar/**\n/dir/\n!/foo/skip", implicit(posix), map[string]MatchKind{
"/foo": MatchAll, "/foo/a/b": MatchAll, "/foo/skip": MatchNone, "/foo/skip/x": MatchNone,
"/bar": MatchAll, "/dir": MatchDirectory, "/dir/file": MatchAll,
}},
{"no implicit descendants", "/foo", posix, map[string]MatchKind{"/foo": MatchAll, "/foo/a": MatchNone}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g, err := Parse(tt.patterns, tt.opts)
require.NoError(t, err)
for p, want := range tt.want {
assert.Equal(t, want, g.Match(p), p)
}
})
}
}
func TestPartialMatch(t *testing.T) {
tests := []struct {
name string
patterns string
opts Options
want map[string]bool
}{
{"skips excludes", "/search1/foo/**\n/search2/bar/**\n!/search2/bar/**\n!/search3/baz/**", posix, map[string]bool{
"/search1": true, "/search1/foo": true, "/search2": true, "/search2/bar": true, "/search3": false, "/search3/bar": false,
}},
{"root", "/foo/**", posix, map[string]bool{"/": true}},
{"root on windows", "C:\\foo\\**\nd:\\foo\\**", windows, map[string]bool{`c:\`: true, `D:\`: true, `E:\`: false}},
{"case", "/Foo/Bar/**/Baz", posix, map[string]bool{"/Foo": true, "/fOO": false}},
{"case on windows", "C:/Foo/Bar/**/Baz", windows, map[string]bool{`C:\Foo`: true, `C:\fOO`: true, `C:\Other`: false}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g, err := Parse(tt.patterns, tt.opts)
require.NoError(t, err)
for p, want := range tt.want {
assert.Equal(t, want, g.PartialMatch(p), p)
}
})
}
}
func TestSearchPaths(t *testing.T) {
tests := []struct {
name string
patterns string
opts Options
want []string
}{
{"omits excludes", "/search1/foo/**\n/search2/bar/**\n!/search3/baz/**", posix, []string{"/search1/foo", "/search2/bar"}},
{
"omits descendants", "/search1/foo/**\n/search1/foo/bar/**\n/search2/foo/bar\n/search2/**\n/search3/foo/bar/**\n/search3/foo/bar/**", posix,
[]string{"/search1/foo", "/search2", "/search3/foo/bar"},
},
{
"omits descendants on windows", "C:\\Search1\\Foo\\**\nC:\\sEARCH1\\fOO\\bar\\**\nC:\\sEARCH1\\foo\\bar\nC:\\Search2\\**\nC:\\Search3\\Foo\\Bar\\**\nC:\\sEARCH3\\fOO\\bAR\\**", windows,
[]string{`C:\Search1\Foo`, `C:\Search2`, `C:\Search3\Foo\Bar`},
},
{"skips comments and blank lines", "# /nope\n\n /a/* \n", posix, []string{"/a"}},
{"splits carriage returns on windows", "C:/a/*\r\nC:/b/*\rC:/c/*", windows, []string{`C:\a`, `C:\b`, `C:\c`}},
{
"unescapes literal segments", "/foo/b[a]r/b*\n/x/b[*]r/b*\n/y/b[!]r/b*\n/z/b[]r/b*\n/q/b[aA]r/b*\n/e/b\\[a]r/b*\n/f/b[\\]]r/b*", posix,
[]string{"/foo/bar", "/x/b*r", "/y/b!r", "/z/b[]r", "/q", "/e/b[a]r", "/f/b]r"},
},
{"unescapes literal segments on windows", "C:/foo/b\\[a]r/b*\nC:/x/b[?]r/b*", windows, []string{`C:\foo\b\ar`, `C:\x\b?r`}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g, err := Parse(tt.patterns, tt.opts)
require.NoError(t, err)
assert.Equal(t, tt.want, g.SearchPaths())
})
}
}
func TestParseErrors(t *testing.T) {
tests := []struct {
name string
patterns string
opts Options
}{
{"empty after negation", "!", posix},
{"dot segment", "/a/./b", posix},
{"dot dot segment", "a/../b", posix},
{"glob in unc root", `\\srv\sh*re\a`, windows},
{"tilde without home", "~/a", Options{Workdir: "/w"}},
{"relative workdir", "a", Options{Workdir: "w"}},
{"drive relative with unc workdir", "C:a", Options{Workdir: `\\srv\share`, Windows: true}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := Parse(tt.patterns, tt.opts)
assert.Error(t, err)
})
}
}
func TestLeastCommonAncestor(t *testing.T) {
tests := []struct {
paths []string
windows bool
want string
}{
{[]string{"/a/b/c", "/a/b/d", "/a/b"}, false, "/a/b"},
{[]string{"/foo", "/bar"}, false, "/"},
{[]string{"/a"}, false, "/a"},
{[]string{`C:\a\b`, `C:\a\c`}, true, `C:\a`},
{[]string{`C:\a`, `c:\a\b`}, true, "."},
{[]string{`C:\a`, `C:\b`}, true, "C:."},
{[]string{`\\srv\share\a`, `\\srv\share\b`}, true, `\srv\share`},
}
for _, tt := range tests {
assert.Equal(t, tt.want, LeastCommonAncestor(tt.paths, tt.windows), tt.paths)
}
}
-534
View File
@@ -1,534 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package glob
import (
"errors"
"slices"
"unicode"
"unicode/utf16"
)
// This ports the subset of minimatch 3.1.5 that @actions/glob 0.6.1 uses: options dot, nobrace,
// noext, nocomment and nonegate, with nocase on Windows. Like JS regexps without the u flag it
// works on UTF-16 code units.
const maxGlobstarRecursion = 200
type tokKind uint8
const (
tokLit tokKind = iota
tokAny // [^/]
tokStar // [^/]*?
tokClass // [...]
tokNonEmpty // (?=.)
tokNotDot // (?!(?:^|\/)\.{1,2}(?:$|\/))
)
type unitRange struct{ lo, hi uint16 }
type tok struct {
kind tokKind
ch uint16
neg bool
ranges []unitRange
}
type mmSegment struct {
globstar bool
magic bool
nocase bool
literal string
toks []tok
}
type classItem struct {
ch uint16
escaped bool
}
func isReSpecial(c uint16) bool {
switch c {
case '(', ')', '.', '*', '{', '}', '+', '?', '[', ']', '^', '$', '\\', '!':
return true
}
return false
}
func compileMinimatch(pattern string, nocase bool) ([]mmSegment, error) {
if len(utf16.Encode([]rune(pattern))) > 64*1024 {
return nil, errors.New("pattern is too long")
}
parts := splitRuns(jsTrim(pattern), '/')
segs := make([]mmSegment, len(parts))
for i, part := range parts {
segs[i] = compileSegment(part, nocase)
}
return segs, nil
}
func compileSegment(s string, nocase bool) mmSegment {
if s == "**" {
return mmSegment{globstar: true}
}
if s == "" {
return mmSegment{}
}
p := utf16.Encode([]rune(s))
toks, magic := parseSegment(p, nocase)
if !magic {
return mmSegment{literal: globUnescape(s)}
}
return mmSegment{magic: true, nocase: nocase, toks: toks}
}
// globUnescape replaces \x with x like s.replace(/\\(.)/g, '$1'); JS . excludes line terminators.
func globUnescape(s string) string {
u := utf16.Encode([]rune(s))
out := make([]uint16, 0, len(u))
for i := 0; i < len(u); i++ {
if u[i] == '\\' && i+1 < len(u) && !isLineTerminator(u[i+1]) {
i++
}
out = append(out, u[i])
}
return string(utf16.Decode(out))
}
// parseSegment ports minimatch's parse(), emitting tokens instead of a regexp source.
func parseSegment(p []uint16, nocase bool) (toks []tok, hasMagic bool) {
hasMagic = nocase
escaping := false
var stateChar uint16
inClass := false
classStart := -1
var class []classItem
lit := func(c uint16) { toks = append(toks, tok{kind: tokLit, ch: c}) }
clearStateChar := func() {
switch stateChar {
case 0:
return
case '*':
toks = append(toks, tok{kind: tokStar})
hasMagic = true
case '?':
toks = append(toks, tok{kind: tokAny})
hasMagic = true
default:
lit(stateChar)
}
stateChar = 0
}
fallback := func(cs []uint16, closing bool) {
lit('[')
// parse() returns a non-array for "" and "**", so minimatch splices in the text "undefined".
if len(cs) == 0 || (len(cs) == 2 && cs[0] == '*' && cs[1] == '*') {
for _, c := range "undefined" {
lit(uint16(c))
}
if closing {
lit(']')
}
inClass = false
return
}
subToks, subMagic := parseSegment(cs, nocase)
toks = append(toks, subToks...)
if closing {
lit(']')
}
hasMagic = hasMagic || subMagic
inClass = false
}
for i := range p {
c := p[i]
if escaping && isReSpecial(c) {
if inClass {
class = append(class, classItem{c, true})
} else {
lit(c)
}
escaping = false
continue
}
switch c {
case '\\':
clearStateChar()
escaping = true
case '?', '*', '+', '@', '!':
if inClass {
if c == '!' && i == classStart+1 {
c = '^'
}
class = append(class, classItem{c, false})
continue
}
clearStateChar()
stateChar = c
clearStateChar() // noext
case '(':
if inClass {
class = append(class, classItem{c, false})
} else {
lit(c)
}
case ')':
if inClass {
class = append(class, classItem{c, true})
} else {
lit(c)
}
case '|':
if inClass {
class = append(class, classItem{c, true})
} else {
lit(c)
}
escaping = false
case '[':
clearStateChar()
if inClass {
class = append(class, classItem{c, true})
continue
}
inClass = true
classStart = i
class = class[:0]
case ']':
if i == classStart+1 || !inClass {
if inClass {
class = append(class, classItem{c, true})
} else {
lit(c)
}
escaping = false
continue
}
t, ok := buildClass(class)
if !ok {
fallback(p[classStart+1:i], true)
continue
}
toks = append(toks, t)
hasMagic = true
inClass = false
default:
clearStateChar()
if inClass {
class = append(class, classItem{c, !escaping && isReSpecial(c) && c != '^'})
} else {
lit(c)
}
escaping = false
}
}
if inClass {
fallback(p[classStart+1:], false)
}
clearStateChar()
if escaping {
lit('\\')
}
addPatternStart := len(toks) > 0 && (toks[0].kind == tokStar || toks[0].kind == tokAny || toks[0].kind == tokClass)
if len(toks) > 0 && hasMagic {
toks = append([]tok{{kind: tokNonEmpty}}, toks...)
}
if addPatternStart && p[0] != '.' {
toks = append([]tok{{kind: tokNotDot}}, toks...)
}
return toks, hasMagic
}
// buildClass turns the class body minimatch emits into ranges, ok is false for an out of order range like [z-a], which matches literally.
func buildClass(items []classItem) (tok, bool) {
t := tok{kind: tokClass}
if len(items) > 0 && items[0].ch == '^' && !items[0].escaped {
t.neg = true
items = items[1:]
}
for i := 0; i < len(items); {
lo := items[i].ch
if i+2 < len(items) && items[i+1].ch == '-' && !items[i+1].escaped {
hi := items[i+2].ch
if lo > hi {
return t, false
}
t.ranges = append(t.ranges, unitRange{lo, hi})
i += 3
continue
}
t.ranges = append(t.ranges, unitRange{lo, lo})
i++
}
return t, true
}
func isLineTerminator(c uint16) bool {
return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029
}
// canonicalize ports the ES Canonicalize() used by non-unicode case-insensitive regexps.
func canonicalize(c uint16) uint16 {
if utf16.IsSurrogate(rune(c)) {
return c
}
up := unicode.ToUpper(rune(c))
if up > 0xffff || (c >= 128 && up < 128) {
return c
}
return uint16(up)
}
func (t *tok) classMatch(c uint16, nocase bool) bool {
in := func(v uint16) bool {
for _, r := range t.ranges {
if v >= r.lo && v <= r.hi {
return true
}
}
return false
}
hit := in(c)
if !hit && nocase && !utf16.IsSurrogate(rune(c)) {
want := canonicalize(c)
for f := unicode.SimpleFold(rune(c)); f != rune(c); f = unicode.SimpleFold(f) {
if f <= 0xffff && canonicalize(uint16(f)) == want && in(uint16(f)) {
hit = true
break
}
}
}
return hit != t.neg
}
func (s *mmSegment) match(f string) bool {
if !s.magic {
return f == s.literal
}
u := utf16.Encode([]rune(f))
n := len(u) + 1
memo := make([]int8, (len(s.toks)+1)*n)
var rec func(ti, pos int) bool
rec = func(ti, pos int) bool {
if ti == len(s.toks) {
return pos == len(u)
}
key := ti*n + pos
if memo[key] != 0 {
return memo[key] > 0
}
t := &s.toks[ti]
hit := false
switch t.kind {
case tokLit:
hit = pos < len(u) && (u[pos] == t.ch || (s.nocase && canonicalize(u[pos]) == canonicalize(t.ch))) && rec(ti+1, pos+1)
case tokAny:
hit = pos < len(u) && u[pos] != '/' && rec(ti+1, pos+1)
case tokClass:
hit = pos < len(u) && t.classMatch(u[pos], s.nocase) && rec(ti+1, pos+1)
case tokStar:
for j := pos; !hit; j++ {
hit = rec(ti+1, j)
if j == len(u) || u[j] == '/' {
break
}
}
case tokNonEmpty:
hit = pos < len(u) && !isLineTerminator(u[pos]) && rec(ti+1, pos)
case tokNotDot:
hit = !dotSegmentAhead(u, pos) && rec(ti+1, pos)
}
memo[key] = -1
if hit {
memo[key] = 1
}
return hit
}
return rec(0, 0)
}
// dotSegmentAhead evaluates (?:^|\/)\.{1,2}(?:$|\/) at pos.
func dotSegmentAhead(u []uint16, pos int) bool {
i := pos
if pos != 0 {
if i >= len(u) || u[i] != '/' {
return false
}
i++
}
for dots := 0; dots < 2 && i < len(u) && u[i] == '.'; dots++ {
i++
if i == len(u) || u[i] == '/' {
return true
}
}
return false
}
// matchOne ports Minimatch.prototype.matchOne for the single pattern set nobrace produces.
func matchOne(file []string, pattern []mmSegment, partial bool) bool {
for i := range pattern {
if pattern[i].globstar {
return matchGlobstar(file, pattern, partial, 0, 0)
}
}
return matchOneFrom(file, pattern, partial, 0)
}
func clampSlice(s []string, from, to int) []string {
to = min(to, len(s))
from = min(from, to)
return s[from:to]
}
func matchOneFrom(file []string, pattern []mmSegment, partial bool, fi int) bool {
fl, pl, pi := len(file), len(pattern), 0
for ; fi < fl && pi < pl; fi, pi = fi+1, pi+1 {
if pattern[pi].globstar || !pattern[pi].match(file[fi]) {
return false
}
}
switch {
case fi == fl && pi == pl:
return true
case fi == fl:
return partial
case pi == pl:
return fi == fl-1 && file[fi] == ""
}
return false
}
func isDotOrDotDot(f string) bool {
return f == "." || f == ".."
}
func matchGlobstar(file []string, pattern []mmSegment, partial bool, fileIndex, patternIndex int) bool {
firstgs, lastgs := -1, -1
for i := patternIndex; i < len(pattern); i++ {
if pattern[i].globstar {
firstgs = i
break
}
}
for i, seg := range slices.Backward(pattern) {
if seg.globstar {
lastgs = i
break
}
}
head := pattern[patternIndex:firstgs]
var body, tail []mmSegment
if partial {
body = pattern[firstgs+1:]
} else {
body = pattern[firstgs+1 : max(lastgs, firstgs+1)]
tail = pattern[lastgs+1:]
}
if len(head) > 0 {
if !matchOneFrom(clampSlice(file, fileIndex, fileIndex+len(head)), head, partial, 0) {
return false
}
fileIndex += len(head)
}
fileTailMatch := 0
if len(tail) > 0 {
if len(tail)+fileIndex > len(file) {
return false
}
tailStart := len(file) - len(tail)
if matchOneFrom(file, tail, partial, tailStart) {
fileTailMatch = len(tail)
} else {
// a/**/* matching a/b/
if file[len(file)-1] != "" || fileIndex+len(tail) == len(file) {
return false
}
tailStart--
if !matchOneFrom(file, tail, partial, tailStart) {
return false
}
fileTailMatch = len(tail) + 1
}
}
if len(body) == 0 {
sawSome := fileTailMatch > 0
for i := fileIndex; i < len(file)-fileTailMatch; i++ {
sawSome = true
if isDotOrDotDot(file[i]) {
return false
}
}
return partial || sawSome
}
type section struct {
body []mmSegment
after int
}
sections := []section{{}}
nonGsParts := 0
nonGsPartsSums := []int{0}
for _, b := range body {
if b.globstar {
nonGsPartsSums = append(nonGsPartsSums, nonGsParts)
sections = append(sections, section{})
} else {
sections[len(sections)-1].body = append(sections[len(sections)-1].body, b)
nonGsParts++
}
}
idx := len(sections) - 1
fileLength := len(file) - fileTailMatch
for si := range sections {
sections[si].after = fileLength - (nonGsPartsSums[idx] + len(sections[si].body))
idx--
}
// minimatch returns false (no match), null (no match, stop trying) or true.
const (
triFalse = iota
triNull
triTrue
)
var bodySections func(fileIndex, bodyIndex, depth int, sawTail bool) int
bodySections = func(fileIndex, bodyIndex, depth int, sawTail bool) int {
if bodyIndex >= len(sections) {
for i := fileIndex; i < len(file); i++ {
sawTail = true
if isDotOrDotDot(file[i]) {
return triFalse
}
}
if sawTail {
return triTrue
}
return triFalse
}
bs := sections[bodyIndex]
for ; fileIndex <= bs.after; fileIndex++ {
m := matchOneFrom(clampSlice(file, 0, fileIndex+len(bs.body)), bs.body, partial, fileIndex)
if m && depth < maxGlobstarRecursion {
if sub := bodySections(fileIndex+len(bs.body), bodyIndex+1, depth+1, sawTail); sub != triFalse {
return sub
}
}
if fileIndex < len(file) && isDotOrDotDot(file[fileIndex]) {
return triFalse
}
}
if partial {
return triTrue
}
return triNull
}
return bodySections(fileIndex, 0, 0, fileTailMatch > 0) == triTrue
}
-284
View File
@@ -1,284 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package glob
import (
"errors"
"regexp"
"strings"
)
// flavour selects Windows or POSIX path semantics; the helpers port @actions/glob internal-path-helper.ts.
type flavour struct{ windows bool }
var (
reUNCPrefix = regexp.MustCompile(`^\\\\+[^\\]`)
reBackslashRun = regexp.MustCompile(`\\\\+`)
reSlashRun = regexp.MustCompile(`//+`)
reDriveRoot = regexp.MustCompile(`^[A-Za-z]:\\$`)
reDriveAbs = regexp.MustCompile(`^[A-Za-z]:\\`)
reDrive = regexp.MustCompile(`^[A-Za-z]:`)
reDriveOnly = regexp.MustCompile(`^[A-Za-z]:$`)
reDriveRel = regexp.MustCompile(`^[A-Za-z]:[^\\/]|^[A-Za-z]:$`)
reRelRoot = regexp.MustCompile(`^\\$|^\\[^\\]`)
reRelRootOnly = regexp.MustCompile(`^\\[^\\]`)
reDriveNoSep = regexp.MustCompile(`^[A-Za-z]:[^\\]`)
reUNCRoot = regexp.MustCompile(`^\\\\[^\\]+(\\[^\\]+)?$`)
reUNCRootSlash = regexp.MustCompile(`^\\\\[^\\]+\\[^\\]+\\$`)
)
func (w flavour) sep() string {
if w.windows {
return `\`
}
return "/"
}
func (w flavour) isSep(c byte) bool {
return c == '/' || (w.windows && c == '\\')
}
func (w flavour) normalizeSeparators(p string) string {
if w.windows {
p = strings.ReplaceAll(p, "/", `\`)
prefix := ""
if reUNCPrefix.MatchString(p) {
prefix = `\`
}
return prefix + reBackslashRun.ReplaceAllLiteralString(p, `\`)
}
return reSlashRun.ReplaceAllLiteralString(p, "/")
}
func (w flavour) safeTrimTrailingSeparator(p string) string {
if p == "" {
return ""
}
p = w.normalizeSeparators(p)
if !strings.HasSuffix(p, w.sep()) || p == w.sep() || (w.windows && reDriveRoot.MatchString(p)) {
return p
}
return p[:len(p)-1]
}
func (w flavour) hasAbsoluteRoot(p string) bool {
p = w.normalizeSeparators(p)
if w.windows {
return strings.HasPrefix(p, `\\`) || reDriveAbs.MatchString(p)
}
return strings.HasPrefix(p, "/")
}
func (w flavour) hasRoot(p string) bool {
p = w.normalizeSeparators(p)
if w.windows {
return strings.HasPrefix(p, `\`) || reDrive.MatchString(p)
}
return strings.HasPrefix(p, "/")
}
func (w flavour) dirname(p string) string {
p = w.safeTrimTrailingSeparator(p)
if w.windows && reUNCRoot.MatchString(p) {
return p
}
result := w.nodeDirname(p)
if w.windows && reUNCRootSlash.MatchString(result) {
result = w.safeTrimTrailingSeparator(result)
}
return result
}
// ensureAbsoluteRoot resolves Windows drive and root relative paths against cwd like process.cwd().
func (w flavour) ensureAbsoluteRoot(root, itemPath, cwd string) (string, error) {
if root == "" || itemPath == "" {
return "", errors.New("ensureAbsoluteRoot parameters must not be empty")
}
if w.hasAbsoluteRoot(itemPath) {
return itemPath, nil
}
if w.windows {
if reDriveRel.MatchString(itemPath) {
if !reDriveAbs.MatchString(cwd) {
return "", errors.New("expected current directory to start with an absolute drive root, actual '" + cwd + "'")
}
if strings.EqualFold(itemPath[:1], cwd[:1]) {
if len(itemPath) == 2 {
return itemPath[:1] + `:\` + cwd[3:], nil
}
if !strings.HasSuffix(cwd, `\`) {
cwd += `\`
}
return itemPath[:1] + `:\` + cwd[3:] + itemPath[2:], nil
}
return itemPath[:1] + `:\` + itemPath[2:], nil
} else if reRelRoot.MatchString(w.normalizeSeparators(itemPath)) {
if !reDriveAbs.MatchString(cwd) {
return "", errors.New("expected current directory to start with an absolute drive root, actual '" + cwd + "'")
}
return cwd[:1] + `:\` + itemPath[1:], nil
}
}
if !w.hasAbsoluteRoot(root) {
return "", errors.New("ensureAbsoluteRoot parameter 'root' must have an absolute root")
}
if !strings.HasSuffix(root, "/") && (!w.windows || !strings.HasSuffix(root, `\`)) {
root += w.sep()
}
return root + itemPath, nil
}
// splitPath ports internal-path.ts Path(string).segments.
func (w flavour) splitPath(p string) []string {
p = w.safeTrimTrailingSeparator(p)
if !w.hasRoot(p) {
return strings.Split(p, w.sep())
}
var segments []string
remaining := p
for dir := w.dirname(remaining); dir != remaining; dir = w.dirname(remaining) {
segments = append([]string{w.nodeBasename(remaining)}, segments...)
remaining = dir
}
return append([]string{remaining}, segments...)
}
// joinSegments ports internal-path.ts Path(string[]).toString().
func (w flavour) joinSegments(segments []string) string {
result := w.normalizeSeparators(segments[0])
if w.hasRoot(result) {
result = w.safeTrimTrailingSeparator(result)
}
skipSlash := strings.HasSuffix(result, w.sep()) || (w.windows && reDriveOnly.MatchString(result))
for _, s := range segments[1:] {
if skipSlash {
skipSlash = false
} else {
result += w.sep()
}
result += w.normalizeSeparators(s)
}
return result
}
func isDeviceRoot(c byte) bool {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
}
// nodeDirname ports Node's path.posix.dirname and path.win32.dirname.
func (w flavour) nodeDirname(p string) string {
n := len(p)
if n == 0 {
return "."
}
if !w.windows {
hasRoot := p[0] == '/'
end := -1
matchedSlash := true
for i := n - 1; i >= 1; i-- {
if p[i] == '/' {
if !matchedSlash {
end = i
break
}
} else {
matchedSlash = false
}
}
switch {
case end == -1 && hasRoot:
return "/"
case end == -1:
return "."
case hasRoot && end == 1:
return "//"
}
return p[:end]
}
if n == 1 {
if w.isSep(p[0]) {
return p
}
return "."
}
rootEnd, offset := -1, 0
if w.isSep(p[0]) {
rootEnd, offset = 1, 1
if w.isSep(p[1]) {
j := 2
last := j
for j < n && !w.isSep(p[j]) {
j++
}
if j < n && j != last {
last = j
for j < n && w.isSep(p[j]) {
j++
}
if j < n && j != last {
last = j
for j < n && !w.isSep(p[j]) {
j++
}
if j == n {
return p
}
if j != last {
rootEnd, offset = j+1, j+1
}
}
}
}
} else if isDeviceRoot(p[0]) && p[1] == ':' {
rootEnd = 2
if n > 2 && w.isSep(p[2]) {
rootEnd = 3
}
offset = rootEnd
}
end := -1
matchedSlash := true
for i := n - 1; i >= offset; i-- {
if w.isSep(p[i]) {
if !matchedSlash {
end = i
break
}
} else {
matchedSlash = false
}
}
if end == -1 {
if rootEnd == -1 {
return "."
}
end = rootEnd
}
return p[:end]
}
// nodeBasename ports Node's path.posix.basename and path.win32.basename without the ext argument.
func (w flavour) nodeBasename(p string) string {
start := 0
if w.windows && len(p) >= 2 && isDeviceRoot(p[0]) && p[1] == ':' {
start = 2
}
from, end := start, -1
matchedSlash := true
for i := len(p) - 1; i >= start; i-- {
if w.isSep(p[i]) {
if !matchedSlash {
from = i + 1
break
}
} else if end == -1 {
matchedSlash = false
end = i + 1
}
}
if end == -1 {
return ""
}
return p[from:end]
}
-269
View File
@@ -1,269 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package glob
import (
"errors"
"fmt"
"strings"
"unicode/utf16"
)
// pattern ports @actions/glob internal-pattern.ts.
type pattern struct {
negate bool
searchPath string
segments []string
trailingSeparator bool
implicit bool
rootLiteral string
mm []mmSegment
w flavour
}
type parseEnv struct {
w flavour
cwd string
home func() (string, error)
}
func newPattern(s string, implicit bool, env parseEnv) (*pattern, error) {
w := env.w
p := &pattern{implicit: implicit, w: w}
s = jsTrim(s)
for strings.HasPrefix(s, "!") {
p.negate = !p.negate
s = jsTrim(s[1:])
}
s, err := fixupPattern(s, env)
if err != nil {
return nil, err
}
p.segments = w.splitPath(s)
p.trailingSeparator = strings.HasSuffix(w.normalizeSeparators(s), w.sep())
s = w.safeTrimTrailingSeparator(s)
var searchSegments []string
for _, seg := range p.segments {
lit := getLiteral(seg, w)
if lit == "" {
break
}
searchSegments = append(searchSegments, lit)
}
p.searchPath = w.joinSegments(searchSegments)
p.rootLiteral = searchSegments[0]
if w.windows {
s = strings.ReplaceAll(s, `\`, "/")
}
p.mm, err = compileMinimatch(s, w.windows)
if err != nil {
return nil, err
}
return p, nil
}
func fixupPattern(s string, env parseEnv) (string, error) {
w := env.w
if s == "" {
return "", errors.New("pattern cannot be empty")
}
segments := w.splitPath(s)
for i, seg := range segments {
if lit := getLiteral(seg, w); (lit == "." && i != 0) || lit == ".." {
return "", fmt.Errorf("invalid pattern '%s': relative pathing '.' and '..' is not allowed", s)
}
}
if w.hasRoot(s) && getLiteral(segments[0], w) == "" {
return "", fmt.Errorf("invalid pattern '%s': root segment must not contain globs", s)
}
s = w.normalizeSeparators(s)
sep := w.sep()
var root string
var err error
switch {
case s == "." || strings.HasPrefix(s, "."+sep):
s = globEscape(env.cwd, w) + s[1:]
case s == "~" || strings.HasPrefix(s, "~"+sep):
var home string
if env.home != nil {
if home, err = env.home(); err != nil {
return "", err
}
}
if home == "" {
return "", errors.New("unable to determine HOME directory")
}
if home = w.normalizeSeparators(home); !w.hasAbsoluteRoot(home) {
return "", fmt.Errorf("expected HOME directory to be a rooted path, actual '%s'", home)
}
s = globEscape(home, w) + s[1:]
case w.windows && (reDriveOnly.MatchString(s) || reDriveNoSep.MatchString(s)):
if root, err = w.ensureAbsoluteRoot(`C:\dummy-root`, s[:2], env.cwd); err != nil {
return "", err
}
if len(s) > 2 && !strings.HasSuffix(root, `\`) {
root += `\`
}
s = globEscape(root, w) + s[2:]
case w.windows && (s == `\` || reRelRootOnly.MatchString(s)):
if root, err = w.ensureAbsoluteRoot(`C:\dummy-root`, `\`, env.cwd); err != nil {
return "", err
}
if !strings.HasSuffix(root, `\`) {
root += `\`
}
s = globEscape(root, w) + s[1:]
default:
if s, err = w.ensureAbsoluteRoot(globEscape(env.cwd, w), s, env.cwd); err != nil {
return "", err
}
}
return w.normalizeSeparators(s), nil
}
func (p *pattern) match(itemPath string) MatchKind {
w := p.w
if p.segments[len(p.segments)-1] == "**" {
itemPath = w.normalizeSeparators(itemPath)
// Without the trailing separator minimatch would not match the directory preceding the globstar.
if !strings.HasSuffix(itemPath, w.sep()) && !p.implicit {
itemPath += w.sep()
}
} else {
itemPath = w.safeTrimTrailingSeparator(itemPath)
}
if w.windows {
itemPath = strings.ReplaceAll(itemPath, `\`, "/")
}
if !matchOne(splitRuns(itemPath, '/'), p.mm, false) {
return MatchNone
}
if p.trailingSeparator {
return MatchDirectory
}
return MatchAll
}
func (p *pattern) partialMatch(itemPath string) bool {
w := p.w
itemPath = w.safeTrimTrailingSeparator(itemPath)
// The toolkit tests roots with an unanchored regexp because minimatch mishandles them.
if w.dirname(itemPath) == itemPath {
if w.windows {
return strings.Contains(strings.ToUpper(itemPath), strings.ToUpper(p.rootLiteral))
}
return strings.Contains(itemPath, p.rootLiteral)
}
sep := byte('/')
if w.windows {
sep = '\\'
}
return matchOne(splitRuns(itemPath, sep), p.mm, true)
}
// globEscape ports Pattern.globEscape.
func globEscape(s string, w flavour) string {
if !w.windows {
s = strings.ReplaceAll(s, `\`, `\\`)
}
var b strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '[' && closesBeforeSlash(s[i+1:]) {
b.WriteString("[[]")
continue
}
b.WriteByte(s[i])
}
s = strings.ReplaceAll(b.String(), "?", "[?]")
return strings.ReplaceAll(s, "*", "[*]")
}
// closesBeforeSlash reports whether s matches the lookahead `[^/]+\]`.
func closesBeforeSlash(s string) bool {
for i := 0; i < len(s) && s[i] != '/'; i++ {
if s[i] == ']' && i > 0 {
return true
}
}
return false
}
// getLiteral ports Pattern.getLiteral, returning "" when the segment contains a glob.
func getLiteral(segment string, w flavour) string {
seg := utf16.Encode([]rune(segment))
var lit []uint16
for i := 0; i < len(seg); i++ {
c := seg[i]
switch {
case c == '\\' && !w.windows && i+1 < len(seg):
i++
lit = append(lit, seg[i])
continue
case c == '*' || c == '?':
return ""
case c == '[' && i+1 < len(seg):
var set []uint16
closed := -1
for i2 := i + 1; i2 < len(seg); i2++ {
c2 := seg[i2]
if c2 == '\\' && !w.windows && i2+1 < len(seg) {
i2++
set = append(set, seg[i2])
continue
} else if c2 == ']' {
closed = i2
break
}
set = append(set, c2)
}
if closed >= 0 {
if len(set) > 1 {
return ""
}
if len(set) == 1 {
lit = append(lit, set...)
i = closed
continue
}
}
}
lit = append(lit, c)
}
return string(utf16.Decode(lit))
}
func isJSWhitespace(r rune) bool {
switch r {
case '\t', '\n', '\v', '\f', '\r', ' ', 0xa0, 0x1680, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff:
return true
}
return r >= 0x2000 && r <= 0x200a
}
// jsTrim matches String.prototype.trim, which differs from strings.TrimSpace on U+0085 and U+FEFF.
func jsTrim(s string) string {
return strings.TrimFunc(s, isJSWhitespace)
}
// splitRuns splits like JS s.split(/c+/).
func splitRuns(s string, c byte) []string {
parts := []string{}
start := 0
for i := 0; i < len(s); {
if s[i] != c {
i++
continue
}
parts = append(parts, s[start:i])
for i < len(s) && s[i] == c {
i++
}
start = i
}
return append(parts, s[start:])
}
@@ -1,120 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package uploadartifact
import (
"archive/tar"
"bufio"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"gitea.com/gitea/runner/internal/pkg/action"
)
const fetchScript = `cd / && if command -v gzip >/dev/null 2>&1; then exec tar -czhf - -- "$@"; fi; exec tar -chf - -- "$@"`
func readFiles(ctx context.Context, c *action.Context, files []found, visit func(found) error) error {
if c.Host() {
for _, file := range files {
body, err := os.Open(file.source)
if err != nil {
return err
}
info, err := body.Stat()
if err == nil {
file.body, file.mode, file.mtime = body, info.Mode(), info.ModTime()
err = visit(file)
}
body.Close()
if err != nil {
return err
}
}
return nil
}
for len(files) > 0 {
command := []string{"sh", "-c", fetchScript, "sh"}
selected := map[string][]found{}
size, count := 0, 0
for _, file := range files {
name := "./" + strings.TrimPrefix(file.source, "/")
if size+len(name)+1 >= 32*1024 {
if count == 0 {
return fmt.Errorf("artifact path exceeds container command limit: %s", file.path)
}
break
}
count++
if _, exists := selected[path.Clean(name)]; !exists {
command = append(command, name)
size += len(name) + 1
}
selected[path.Clean(name)] = append(selected[path.Clean(name)], file)
}
output, err := c.Container.ExecOutput(ctx, command)
if err != nil {
return err
}
retry, err := readArchive(output, selected, visit)
closeErr := output.Close()
if err != nil {
return err
} else if closeErr != nil {
return closeErr
}
files = append(retry, files[count:]...)
}
return nil
}
func readArchive(output io.Reader, selected map[string][]found, visit func(found) error) ([]found, error) {
buffered := bufio.NewReader(output)
var content io.Reader = buffered
if magic, _ := buffered.Peek(2); len(magic) == 2 && magic[0] == 0x1f && magic[1] == 0x8b {
compressed, err := gzip.NewReader(buffered)
if err != nil {
return nil, err
}
defer compressed.Close()
compressed.Multistream(false) // bsdtar pads its gzip output with zeros to the block size
content = compressed
}
reader := tar.NewReader(content)
var retry []found
for {
header, err := reader.Next()
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
name := path.Clean(header.Name)
files := selected[name]
delete(selected, name)
if header.Typeflag == tar.TypeLink {
retry = append(retry, files...)
continue
}
if len(files) == 0 {
continue
}
retry = append(retry, files[1:]...)
file := files[0]
file.body, file.mode, file.mtime = reader, header.FileInfo().Mode(), header.ModTime
if err := visit(file); err != nil {
return nil, err
}
}
_, err := io.Copy(io.Discard, content)
if err == nil {
_, err = io.Copy(io.Discard, buffered)
}
return retry, err
}
@@ -1,14 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package uploadartifact
import (
"cmp"
"mime"
"path"
)
func mimeTypeOf(name string) string {
return cmp.Or(mime.TypeByExtension(path.Ext(name)), "application/octet-stream")
}
@@ -1,258 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// Package uploadartifact works like actions/upload-artifact v7.
package uploadartifact
import (
"archive/zip"
"cmp"
"compress/flate"
"context"
"fmt"
"io"
"io/fs"
"net/url"
"strconv"
"strings"
"time"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.com/gitea/runner/internal/pkg/action/artifact"
"gitea.com/gitea/runner/internal/pkg/action/glob"
)
type inputs struct {
name, path, ifNoFilesFound string
retentionDays, compressionLevel int
overwrite, includeHidden, archiveIt bool
}
func Main(ctx context.Context, c *action.Context) error {
c.ApplyDefaults("name", "artifact", "path", "", "if-no-files-found", "warn", "retention-days", "", "compression-level", "6",
"overwrite", "false", "include-hidden-files", "false", "archive", "true")
in, err := readInputs(c)
if err != nil {
return err
}
g, err := glob.Parse(in.path, glob.Options{
Workdir: c.Workspace,
Home: func() (string, error) { return c.Home(ctx) },
Windows: c.Windows(),
ImplicitDescendants: true,
})
if err != nil {
return err
}
files, err := selectFiles(ctx, c, g, in.includeHidden)
if err != nil {
return err
}
collected := &collected{files: files, root: glob.LeastCommonAncestor(g.SearchPaths(), c.Windows())}
if len(files) == 1 && files[0].path == collected.root {
collected.root = c.Dir(collected.root)
}
if len(collected.files) == 0 {
message := fmt.Sprintf("No files were found with the provided path: %s. No artifacts will be uploaded.", in.path)
switch in.ifNoFilesFound {
case "warn":
c.Warning("%s", message)
case "error":
return action.Failf("%s", message)
default:
c.Infof("%s", message)
}
return nil
}
if !in.archiveIt && len(collected.files) > 1 {
return action.Failf("When 'archive' is set to false, only a single file can be uploaded. Found %d files to upload.", len(collected.files))
}
return upload(ctx, c, in, collected)
}
func readInputs(c *action.Context) (*inputs, error) {
in := &inputs{name: c.Input("name"), path: c.Input("path"), ifNoFilesFound: c.Input("if-no-files-found"), compressionLevel: 6}
if in.path == "" {
return nil, action.Failf("Input required and not supplied: path")
}
var err error
if in.overwrite, err = c.BoolInput("overwrite"); err != nil {
return nil, err
}
if in.includeHidden, err = c.BoolInput("include-hidden-files"); err != nil {
return nil, err
}
if in.archiveIt, err = c.BoolInput("archive"); err != nil {
return nil, err
}
if in.ifNoFilesFound != "warn" && in.ifNoFilesFound != "error" && in.ifNoFilesFound != "ignore" {
return nil, action.Failf("Unrecognized if-no-files-found input. Provided: %s. Available options: warn,error,ignore", in.ifNoFilesFound)
}
if days := c.Input("retention-days"); days != "" {
if in.retentionDays, err = action.ParseInt(days); err != nil {
return nil, action.Failf("Invalid retention-days")
}
}
if level := c.Input("compression-level"); level != "" {
if in.compressionLevel, err = action.ParseInt(level); err != nil {
return nil, action.Failf("Invalid compression-level")
}
if in.compressionLevel < 0 || in.compressionLevel > 9 {
return nil, action.Failf("Invalid compression-level. Valid values are 0-9")
}
}
return in, nil
}
type collected struct {
files []found
root string
}
func (got *collected) write(ctx context.Context, c *action.Context, in *inputs, output io.Writer) error {
if !in.archiveIt {
return readFiles(ctx, c, got.files, func(file found) error {
_, err := io.Copy(output, file.body)
return err
})
}
deflater, err := flate.NewWriter(nil, in.compressionLevel)
if err != nil {
return err
}
writer := zip.NewWriter(output)
writer.RegisterCompressor(zip.Deflate, func(output io.Writer) (io.WriteCloser, error) {
deflater.Reset(output)
return deflater, nil
})
if err := readFiles(ctx, c, got.files, func(file found) error {
header := &zip.FileHeader{
Name: strings.TrimLeft(strings.ReplaceAll(strings.TrimPrefix(file.path, got.root), `\`, "/"), "/"),
Method: zip.Deflate, Modified: file.mtime.UTC(),
}
if in.compressionLevel == 0 {
header.Method = zip.Store
}
header.SetMode(file.mode & (fs.ModePerm | fs.ModeSetuid | fs.ModeSetgid | fs.ModeSticky))
entry, err := writer.CreateHeader(header)
if err != nil {
return err
}
_, err = io.Copy(entry, file.body)
return err
}); err != nil {
return err
}
return writer.Close()
}
const invalidPathChars = "\":<>|*?\r\n"
func upload(ctx context.Context, c *action.Context, in *inputs, got *collected) error {
client, err := artifact.New(c.ResultsURL, c.RuntimeToken, c.Transport)
if err != nil {
return err
}
client.Logf = c.Infof
if in.overwrite {
if id, err := client.Delete(ctx, in.name); err == nil {
c.Infof("Artifact '%s' (ID: %d) deleted", in.name, id)
} else if !artifact.IsNotFound(err) {
c.Infof("Unable to delete artifact: %v", err) // best effort, as the JavaScript action
}
}
name, fileName, mimeType := in.name, in.name+".zip", ""
if !in.archiveIt {
name, fileName, mimeType = c.Base(got.files[0].path), c.Base(got.files[0].path), mimeTypeOf(got.files[0].path)
}
if name == "" {
return action.Failf("Provided artifact name input during validation is empty")
}
if strings.ContainsAny(name, invalidPathChars+`\/`) {
return action.Failf("The artifact name is not valid: %s", name)
}
if in.archiveIt {
for _, file := range got.files {
if rel := strings.TrimPrefix(file.path, got.root); strings.ContainsAny(rel, invalidPathChars) {
return action.Failf("The path for one of the files in artifact is not valid: %s", rel)
}
}
}
signed, err := client.Create(ctx, name, mimeType, expiresAt(c, in.retentionDays))
if err != nil {
return err
}
concurrency, err := uploadConcurrency(c)
if err != nil {
return err
}
stall, err := uploadTimeout(c)
if err != nil {
return err
}
c.Infof("Uploading artifact: %s", fileName)
reader, writer := io.Pipe()
defer reader.Close()
streamCtx, cancel := context.WithCancel(ctx)
defer cancel()
done := make(chan struct{})
go func() {
defer close(done)
writer.CloseWithError(got.write(streamCtx, c, in, writer))
}()
uploaded, err := client.Upload(ctx, signed, cmp.Or(mimeType, "application/zip"), reader, concurrency, stall)
reader.CloseWithError(err)
cancel()
<-done
if err != nil {
return err
}
id, err := client.Finalize(ctx, name, uploaded.Size, uploaded.Digest)
if err != nil {
return err
}
c.Infof("Artifact %s has been successfully uploaded! Final size is %d bytes. Artifact ID is %d", in.name, uploaded.Size, id)
ghc := c.Github
link := strings.TrimSuffix(ghc.ServerURL, "/") + "/" + ghc.Repository + "/actions/runs/" + ghc.RunID + "/artifacts/" + url.PathEscape(name)
if ghc.RunAttempt != "" {
link += "?attempt=" + url.QueryEscape(ghc.RunAttempt)
}
c.Infof("Artifact download URL: %s", link)
return c.SetOutputs(ctx, "artifact-id", strconv.FormatInt(id, 10), "artifact-digest", strings.TrimPrefix(uploaded.Digest, "sha256:"), "artifact-url", link)
}
func expiresAt(c *action.Context, days int) *time.Time {
if days == 0 {
return nil
}
if limit, err := action.ParseInt(c.Github.RetentionDays); err == nil && limit != 0 && limit < days {
c.Warning("Retention days cannot be greater than the maximum allowed retention set within the repository. Using %d instead.", limit)
days = limit
}
expires := time.Now().AddDate(0, 0, days)
return &expires
}
func uploadConcurrency(c *action.Context) (int, error) {
override := c.Env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"]
if override == "" {
return 5, nil
}
concurrency, err := action.ParseInt(override)
if err != nil || concurrency < 1 {
return 0, action.Failf("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable")
}
return concurrency, nil
}
func uploadTimeout(c *action.Context) (time.Duration, error) {
value := c.Env["ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS"]
if value == "" {
return 5 * time.Minute, nil
}
ms, err := action.ParseInt(value)
if err != nil {
return 0, action.Failf("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS env variable")
}
return time.Duration(ms) * time.Millisecond, nil
}
@@ -1,280 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package uploadartifact
import (
"archive/zip"
"bytes"
"context"
"fmt"
"io"
"maps"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"gitea.com/gitea/runner/act/artifacts"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.com/gitea/runner/internal/pkg/action/artifact"
"gitea.dev/actionslib/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type localContainer struct {
*container.HostEnvironment
bin string
}
func (c localContainer) ExecOutput(ctx context.Context, command []string) (io.ReadCloser, error) {
if c.bin != "" {
command = append([]string{"env", "PATH=" + c.bin}, command...)
}
return c.HostEnvironment.ExecOutput(ctx, command)
}
type harness struct {
t *testing.T
server string
client *artifact.Client
workspace string
env container.ExecutionsEnvironment
logs, annotation []string
retentionDays string
variables map[string]string
output string
}
func newHarness(t *testing.T, env container.ExecutionsEnvironment) *harness {
t.Helper()
router := http.NewServeMux()
artifacts.RegisterV4(router, t.TempDir())
server := httptest.NewServer(router)
t.Cleanup(server.Close)
client, err := artifact.New(server.URL, artifacts.LocalRuntimeToken("7", time.Hour), nil)
require.NoError(t, err)
workspace, err := filepath.EvalSymlinks(t.TempDir())
require.NoError(t, err)
return &harness{t: t, server: server.URL, client: client, workspace: workspace, env: env}
}
func (h *harness) write(rel, content string, mode os.FileMode) {
h.t.Helper()
p := filepath.Join(h.workspace, filepath.FromSlash(rel))
require.NoError(h.t, os.MkdirAll(filepath.Dir(p), 0o755))
require.NoError(h.t, os.WriteFile(p, []byte(content), mode))
}
func (h *harness) run(inputs map[string]string) error {
h.logs, h.annotation = nil, nil
h.output = filepath.Join(h.t.TempDir(), "output")
variables := map[string]string{"GITHUB_OUTPUT": h.output}
maps.Copy(variables, h.variables)
return Main(h.t.Context(), &action.Context{
Container: h.env,
Github: &model.GithubContext{ServerURL: "https://gitea.example", Repository: "owner/repo", RunID: "7", RunAttempt: "2", RetentionDays: h.retentionDays},
Inputs: inputs,
Workspace: h.workspace,
Env: variables,
ResultsURL: h.server,
RuntimeToken: artifacts.LocalRuntimeToken("7", time.Hour),
Infof: func(format string, args ...any) { h.logs = append(h.logs, fmt.Sprintf(format, args...)) },
Warning: func(format string, args ...any) {
h.annotation = append(h.annotation, "warning: "+fmt.Sprintf(format, args...))
},
})
}
func (h *harness) fetch(name string) ([]byte, map[string]string) {
h.t.Helper()
signed, err := h.client.SignedURL(h.t.Context(), name)
require.NoError(h.t, err)
resp, err := h.client.Download(h.t.Context(), signed, time.Minute)
require.NoError(h.t, err)
defer resp.Body.Close()
content, err := io.ReadAll(resp.Body)
require.NoError(h.t, err)
reader, err := zip.NewReader(bytes.NewReader(content), int64(len(content)))
if err != nil {
return content, nil
}
entries := map[string]string{}
for _, f := range reader.File {
body, err := f.Open()
require.NoError(h.t, err)
data, err := io.ReadAll(body)
require.NoError(h.t, err)
require.NoError(h.t, body.Close())
entries[f.Name] = string(data)
}
return content, entries
}
func TestUploadSelectsWhatTheToolkitSelects(t *testing.T) {
envs := map[string]container.ExecutionsEnvironment{"host": &container.HostEnvironment{}}
if runtime.GOOS != "windows" {
envs["container gzip"] = localContainer{HostEnvironment: &container.HostEnvironment{}}
bin := t.TempDir()
for _, name := range []string{"sh", "find", "readlink", "tar"} {
binary, err := exec.LookPath(name)
require.NoError(t, err)
require.NoError(t, os.Symlink(binary, filepath.Join(bin, name)))
}
envs["container plain"] = localContainer{HostEnvironment: &container.HostEnvironment{}, bin: bin}
}
for envName, env := range envs {
t.Run(envName, func(t *testing.T) {
h := newHarness(t, env)
h.write("dist/a.txt", "a", 0o644)
h.write("dist/run.sh", "#!/bin/sh\n", 0o755)
h.write("dist/sub/b.txt", "b", 0o644)
h.write("dist/empty", "", 0o644)
require.NoError(t, os.Mkdir(filepath.Join(h.workspace, "dist", "emptydir"), 0o755))
h.write("dist/.hidden", "h", 0o644)
h.write("dist/.git/config", "c", 0o644)
h.write("logs/x.log", "x", 0o644)
h.write(".store/target.txt", "hidden target", 0o644)
if runtime.GOOS != "windows" {
require.NoError(t, os.Symlink("a.txt", filepath.Join(h.workspace, "dist", "link.txt")))
require.NoError(t, os.Symlink("sub", filepath.Join(h.workspace, "dist", "linkdir")))
require.NoError(t, os.Symlink("../.store", filepath.Join(h.workspace, "dist", "alias")))
require.NoError(t, os.Symlink("missing", filepath.Join(h.workspace, "dist", "broken")))
require.NoError(t, os.Symlink("..", filepath.Join(h.workspace, "dist", "loop")))
require.NoError(t, os.Link(filepath.Join(h.workspace, "dist", "a.txt"), filepath.Join(h.workspace, "dist", "hard.txt")))
}
for _, test := range []struct {
name string
inputs map[string]string
expected map[string]string
links map[string]string
}{
{
name: "a directory",
inputs: map[string]string{"path": "dist"},
expected: map[string]string{"a.txt": "a", "run.sh": "#!/bin/sh\n", "sub/b.txt": "b", "empty": ""},
links: map[string]string{"link.txt": "a", "hard.txt": "a", "linkdir/b.txt": "b", "loop/logs/x.log": "x", "alias/target.txt": "hidden target"},
},
{
name: "hidden files included",
inputs: map[string]string{"path": "dist/", "include-hidden-files": "true"},
expected: map[string]string{"a.txt": "a", "run.sh": "#!/bin/sh\n", "sub/b.txt": "b", ".hidden": "h", ".git/config": "c", "empty": ""},
links: map[string]string{"link.txt": "a", "hard.txt": "a", "linkdir/b.txt": "b", "loop/logs/x.log": "x", "loop/.store/target.txt": "hidden target", "alias/target.txt": "hidden target"},
},
{
name: "only exclusions and comments",
inputs: map[string]string{"path": "!dist\n# dist"},
expected: map[string]string{},
},
{
name: "several patterns share their common ancestor as root",
inputs: map[string]string{"path": "dist/**/*.txt\n!dist/sub/**\n# a comment\nlogs/x.log"},
expected: map[string]string{"dist/a.txt": "a", "logs/x.log": "x"},
links: map[string]string{"dist/link.txt": "a", "dist/hard.txt": "a", "dist/linkdir/b.txt": "b", "dist/alias/target.txt": "hidden target"},
},
{
name: "hidden root skipped",
inputs: map[string]string{"path": ".store"},
expected: map[string]string{},
},
{
name: "a single file keeps no directory",
inputs: map[string]string{"path": h.workspace + "/dist/sub/b.txt"},
expected: map[string]string{"b.txt": "b"},
},
} {
t.Run(test.name, func(t *testing.T) {
inputs := map[string]string{"name": "art", "overwrite": "true"}
maps.Copy(inputs, test.inputs)
require.NoError(t, h.run(inputs))
expected := test.expected
if runtime.GOOS != "windows" {
maps.Copy(expected, test.links)
}
if len(expected) == 0 {
assert.Contains(t, h.annotation, "warning: No files were found with the provided path: "+test.inputs["path"]+". No artifacts will be uploaded.")
return
}
_, entries := h.fetch("art")
assert.Equal(t, expected, entries)
})
}
})
}
}
func TestUploadOptions(t *testing.T) {
h := newHarness(t, &container.HostEnvironment{})
h.write("out/run.sh", "#!/bin/sh\n", 0o755)
h.write("out/data.txt", strings.Repeat("data", 1000), 0o644)
h.variables = map[string]string{"ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY": " 2 workers", "ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS": " 60000ms"}
h.retentionDays = "5"
require.NoError(t, h.run(map[string]string{"name": "packed", "path": "out", "compression-level": "0", "retention-days": "10 days"}))
assert.Equal(t, []string{"warning: Retention days cannot be greater than the maximum allowed retention set within the repository. Using 5 instead."}, h.annotation)
content, _ := h.fetch("packed")
reader, err := zip.NewReader(bytes.NewReader(content), int64(len(content)))
require.NoError(t, err)
for _, f := range reader.File {
assert.Equal(t, zip.Store, f.Method, f.Name)
if runtime.GOOS != "windows" && f.Name == "run.sh" {
assert.Equal(t, os.FileMode(0o755), f.Mode().Perm())
}
}
list, err := h.client.List(t.Context(), "")
require.NoError(t, err)
require.Len(t, list, 1)
outputs, err := os.ReadFile(h.output)
require.NoError(t, err)
assert.Equal(t, fmt.Sprintf("artifact-id=%d\nartifact-digest=%s\nartifact-url=https://gitea.example/owner/repo/actions/runs/7/artifacts/packed?attempt=2\n", list[0].ID, strings.TrimPrefix(list[0].Digest, "sha256:")), string(outputs))
h.write("report.html", "<html></html>", 0o644)
require.NoError(t, h.run(map[string]string{"name": "packed", "path": "report.html", "archive": "false", "overwrite": "true"}))
list, err = h.client.List(t.Context(), "packed")
require.NoError(t, err)
assert.Empty(t, list)
content, entries := h.fetch("report.html")
assert.Nil(t, entries)
assert.Equal(t, "<html></html>", string(content))
assert.Contains(t, h.logs, "Uploading artifact: report.html")
assert.Contains(t, strings.Join(h.logs, "\n"), "Artifact packed has been successfully uploaded!")
require.ErrorContains(t, h.run(map[string]string{"path": "out", "archive": "false"}), "When 'archive' is set to false, only a single file can be uploaded. Found 2 files to upload.")
require.NoError(t, h.run(map[string]string{"path": "nothing/here"}))
assert.Equal(t, []string{"warning: No files were found with the provided path: nothing/here. No artifacts will be uploaded."}, h.annotation)
require.NoError(t, h.run(map[string]string{"path": "nothing", "if-no-files-found": "ignore"}))
assert.Contains(t, h.logs, "No files were found with the provided path: nothing. No artifacts will be uploaded.")
require.ErrorContains(t, h.run(map[string]string{"path": "nothing", "if-no-files-found": "error"}), "No files were found")
for _, test := range []struct {
inputs map[string]string
want string
}{
{map[string]string{"name": "a/b", "path": "out/data.txt"}, "The artifact name is not valid: a/b"},
{map[string]string{}, "Input required and not supplied: path"},
{map[string]string{"name": "", "path": "out/data.txt"}, "Provided artifact name input during validation is empty"},
{map[string]string{"path": "out/data.txt", "overwrite": ""}, "Core Schema"},
{map[string]string{"path": "out/data.txt", "compression-level": "10"}, "Invalid compression-level. Valid values are 0-9"},
{map[string]string{"path": "out/data.txt", "compression-level": "+-1"}, "Invalid compression-level"},
{map[string]string{"path": "out/data.txt", "if-no-files-found": "fail"}, "Unrecognized if-no-files-found input"},
} {
require.ErrorContains(t, h.run(test.inputs), test.want)
}
require.NoError(t, h.run(map[string]string{"path": "out/data.txt", "retention": "1", "overwrite": "true"}))
assert.Equal(t, []string{"warning: Unexpected input(s) 'retention', valid inputs are ['name', 'path', 'if-no-files-found', 'retention-days', 'compression-level', 'overwrite', 'include-hidden-files', 'archive']"}, h.annotation)
if runtime.GOOS != "windows" {
h.write("bad/a:b.txt", "x", 0o644)
require.ErrorContains(t, h.run(map[string]string{"path": "bad"}), "The path for one of the files in artifact is not valid: /a:b.txt")
}
}
-178
View File
@@ -1,178 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package uploadartifact
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"slices"
"strings"
"time"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/action"
"gitea.com/gitea/runner/internal/pkg/action/glob"
)
type found struct {
path, source string
mode fs.FileMode
mtime time.Time
body io.Reader
}
type treeEntry struct {
name, target string
dir bool
}
type tree struct {
real string
entries map[string][]treeEntry
}
const listScript = `test -e "$1" || exit 1
[ -d "$1" ] || { printf 'f\0'; exit 0; }
cd "$1" || exit 2
shift
pwd -P; printf '\0'
find . "$@" -type d ! -name . -print0; printf '\0'
find . "$@" -type l -exec sh -c 'for l; do printf "%s\0" "$l"; readlink "$l"; printf "\0"; done' sh {} +; printf '\0'
find . "$@" ! -type d ! -type l -print0`
func list(ctx context.Context, c *action.Context, source string, includeHidden bool) (*tree, error) {
if c.Host() {
info, err := os.Stat(source)
if err != nil {
return nil, err
}
resolved, err := filepath.EvalSymlinks(source)
if err != nil || !info.IsDir() {
return &tree{real: resolved}, err
}
entries, err := os.ReadDir(resolved)
result := &tree{real: resolved, entries: map[string][]treeEntry{".": nil}}
for _, entry := range entries {
result.entries["."] = append(result.entries["."], treeEntry{name: entry.Name(), dir: entry.IsDir()})
}
return result, err
}
command := []string{"sh", "-c", listScript, "sh", source}
if !includeHidden {
command = append(command, "!", "-name", ".", "-name", ".*", "-prune", "-o")
}
output, err := c.Container.ExecOutput(ctx, command)
if err != nil {
return nil, err
}
defer output.Close()
data, err := io.ReadAll(output)
if err != nil {
return nil, err
}
if err := output.Close(); err != nil {
return nil, err
}
if string(data) == "f\x00" {
return &tree{real: source}, nil
}
fields := strings.Split(string(data), "\x00")
if len(fields) < 4 {
return nil, fmt.Errorf("invalid directory listing for %s", source)
}
result := &tree{real: strings.TrimSuffix(fields[0], "\n"), entries: map[string][]treeEntry{".": nil}}
section := 0
for index := 1; index < len(fields)-1; index++ {
name := fields[index]
if name == "" {
section++
continue
}
entry := treeEntry{name: path.Base(name), dir: section == 0}
switch section {
case 0:
result.entries[path.Clean(name)] = nil
case 1:
index++
if index >= len(fields)-1 {
return nil, fmt.Errorf("invalid symlink listing for %s", source)
}
entry.target = strings.TrimSuffix(fields[index], "\n")
}
result.entries[path.Dir(name)] = append(result.entries[path.Dir(name)], entry)
}
for _, entries := range result.entries {
slices.SortFunc(entries, func(left, right treeEntry) int { return strings.Compare(left.name, right.name) })
}
return result, nil
}
func selectFiles(ctx context.Context, c *action.Context, globber *glob.Globber, includeHidden bool) ([]found, error) {
var files []found
join := path.Join
if c.Windows() {
join = filepath.Join
}
var walk func(string, string, []string, *tree, string) error
walk = func(virtual, source string, chain []string, listed *tree, relative string) error {
match := globber.Match(virtual)
if match == glob.MatchNone && !globber.PartialMatch(virtual) || !includeHidden && strings.HasPrefix(c.Base(virtual), ".") {
return nil
}
if listed == nil {
var err error
listed, err = list(ctx, c, source, includeHidden)
var exit container.ExitCodeError
if errors.Is(err, fs.ErrNotExist) || errors.As(err, &exit) && exit == 1 {
return nil
} else if err != nil {
return err
}
relative = "."
}
if listed.entries == nil {
if match&glob.MatchFile != 0 {
files = append(files, found{path: virtual, source: listed.real})
}
return nil
}
resolved := join(listed.real, relative)
if slices.Contains(chain, resolved) {
return nil
}
chain = append(slices.Clip(chain), resolved)
for _, entry := range listed.entries[relative] {
child := join(virtual, entry.name)
source := join(resolved, entry.name)
var subtree *tree
switch {
case entry.target != "":
source = entry.target
if !path.IsAbs(source) {
source = path.Join(resolved, source)
}
case entry.dir && !c.Host():
subtree = listed
case !entry.dir && !c.Host():
subtree = &tree{real: source}
}
if err := walk(child, source, chain, subtree, path.Join(relative, entry.name)); err != nil {
return err
}
}
return nil
}
for _, root := range globber.SearchPaths() {
if err := walk(root, root, nil, nil, "."); err != nil {
return nil, err
}
}
return files, nil
}
+1 -1
View File
@@ -45,7 +45,7 @@ runner:
#client_cert_file: /etc/gitea-runner/client.crt
#client_key_file: /etc/gitea-runner/client.key
# PEM CA certificates of a Gitea instance with a private CA, trusted besides the system's.
# Runner-side git and builtin:checkout use it instead of the system's bundle for the instance.
# Runner-side git uses it instead of the system's bundle for the instance.
# Jobs get it at /var/run/act/ca.crt, or in their act directory on the host, with NODE_EXTRA_CA_CERTS
# pointing there unless the job, or on Docker its image, sets it. Other tools in jobs, such as the
# git that actions/checkout runs, need the CA in the image's bundle, for example via container.volumes.