mirror of
https://gitea.com/gitea/act_runner.git
synced 2026-06-22 09:44:24 +02:00
Compare commits
19 Commits
5873b8b054
...
lunny/remo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5d0457615 | ||
|
|
273f6b4247 | ||
|
|
47ee45412a | ||
|
|
38b69bb214 | ||
|
|
1c62c0635f | ||
|
|
0e0c54b272 | ||
|
|
d6fbe75721 | ||
|
|
b30204aa94 | ||
|
|
7b5ebe9618 | ||
|
|
4317662a38 | ||
|
|
2208e7ec63 | ||
|
|
3815aad750 | ||
|
|
fab9714f9a | ||
|
|
10475db58a | ||
|
|
9e738c203c | ||
|
|
6023928876 | ||
|
|
014ce438c1 | ||
|
|
cf7e29c10d | ||
|
|
8a99506fed |
27
.gitea/workflows/pull-pr-title.yml
Normal file
27
.gitea/workflows/pull-pr-title.yml
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
name: pr-title
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- edited
|
||||||
|
- reopened
|
||||||
|
- synchronize
|
||||||
|
- ready_for_review
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint-pr-title:
|
||||||
|
if: github.event.pull_request.draft == false
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 5
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
- run: make lint-pr-title
|
||||||
|
env:
|
||||||
|
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||||
@@ -71,6 +71,11 @@ jobs:
|
|||||||
- name: Echo the tag
|
- name: Echo the tag
|
||||||
run: echo "${{ env.DOCKER_ORG }}/runner:nightly${{ matrix.variant.tag_suffix }}"
|
run: echo "${{ env.DOCKER_ORG }}/runner:nightly${{ matrix.variant.tag_suffix }}"
|
||||||
|
|
||||||
|
- name: Get Meta
|
||||||
|
id: meta
|
||||||
|
run: |
|
||||||
|
echo REPO_VERSION=$(git describe --tags --always | sed 's/-/+/' | sed 's/^v//') >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@v7
|
uses: docker/build-push-action@v7
|
||||||
with:
|
with:
|
||||||
@@ -83,3 +88,5 @@ jobs:
|
|||||||
push: true
|
push: true
|
||||||
tags: |
|
tags: |
|
||||||
${{ env.DOCKER_ORG }}/runner:nightly${{ matrix.variant.tag_suffix }}
|
${{ env.DOCKER_ORG }}/runner:nightly${{ matrix.variant.tag_suffix }}
|
||||||
|
build-args: |
|
||||||
|
VERSION=${{ steps.meta.outputs.REPO_VERSION }}
|
||||||
|
|||||||
@@ -96,3 +96,5 @@ jobs:
|
|||||||
linux/arm64
|
linux/arm64
|
||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.docker_meta.outputs.tags }}
|
tags: ${{ steps.docker_meta.outputs.tags }}
|
||||||
|
build-args: |
|
||||||
|
VERSION=${{ steps.docker_meta.outputs.version }}
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,5 +1,6 @@
|
|||||||
/gitea-runner
|
/gitea-runner
|
||||||
.env
|
.env
|
||||||
|
!/act/runner/testdata/secrets/.env
|
||||||
.runner
|
.runner
|
||||||
coverage.txt
|
coverage.txt
|
||||||
/config.yaml
|
/config.yaml
|
||||||
@@ -10,4 +11,4 @@ coverage.txt
|
|||||||
.vscode
|
.vscode
|
||||||
__debug_bin
|
__debug_bin
|
||||||
# gorelease binary folder
|
# gorelease binary folder
|
||||||
dist
|
/dist
|
||||||
|
|||||||
24
Dockerfile
24
Dockerfile
@@ -1,7 +1,7 @@
|
|||||||
### BUILDER STAGE
|
### BUILDER STAGE
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
FROM golang:1.26-alpine AS builder
|
FROM golang:1.26-alpine3.23 AS builder
|
||||||
|
|
||||||
# Do not remove `git` here, it is required for getting runner version when executing `make build`
|
# Do not remove `git` here, it is required for getting runner version when executing `make build`
|
||||||
RUN apk add --no-cache make git
|
RUN apk add --no-cache make git
|
||||||
@@ -17,7 +17,12 @@ RUN make clean && make build
|
|||||||
### DIND VARIANT
|
### DIND VARIANT
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
FROM docker:29-dind AS dind
|
FROM docker:29.5.2-dind AS dind
|
||||||
|
|
||||||
|
ARG VERSION=dev
|
||||||
|
|
||||||
|
LABEL org.opencontainers.image.source="https://gitea.com/gitea/runner"
|
||||||
|
LABEL org.opencontainers.image.version="${VERSION}"
|
||||||
|
|
||||||
RUN apk add --no-cache s6 bash git tzdata
|
RUN apk add --no-cache s6 bash git tzdata
|
||||||
|
|
||||||
@@ -32,7 +37,12 @@ ENTRYPOINT ["s6-svscan","/etc/s6"]
|
|||||||
### DIND-ROOTLESS VARIANT
|
### DIND-ROOTLESS VARIANT
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
FROM docker:29-dind-rootless AS dind-rootless
|
FROM docker:29.5.2-dind-rootless AS dind-rootless
|
||||||
|
|
||||||
|
ARG VERSION=dev
|
||||||
|
|
||||||
|
LABEL org.opencontainers.image.source="https://gitea.com/gitea/runner"
|
||||||
|
LABEL org.opencontainers.image.version="${VERSION}"
|
||||||
|
|
||||||
USER root
|
USER root
|
||||||
RUN apk add --no-cache s6 bash git tzdata
|
RUN apk add --no-cache s6 bash git tzdata
|
||||||
@@ -53,7 +63,13 @@ ENTRYPOINT ["s6-svscan","/etc/s6"]
|
|||||||
### BASIC VARIANT
|
### BASIC VARIANT
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
FROM alpine AS basic
|
FROM alpine:3.23 AS basic
|
||||||
|
|
||||||
|
ARG VERSION=dev
|
||||||
|
|
||||||
|
LABEL org.opencontainers.image.source="https://gitea.com/gitea/runner"
|
||||||
|
LABEL org.opencontainers.image.version="${VERSION}"
|
||||||
|
|
||||||
RUN apk add --no-cache tini bash git tzdata
|
RUN apk add --no-cache tini bash git tzdata
|
||||||
|
|
||||||
COPY --from=builder /opt/src/runner/gitea-runner /usr/local/bin/gitea-runner
|
COPY --from=builder /opt/src/runner/gitea-runner /usr/local/bin/gitea-runner
|
||||||
|
|||||||
4
Makefile
4
Makefile
@@ -118,6 +118,10 @@ lint-go: ## lint go files
|
|||||||
lint-go-fix: ## lint go files and fix issues
|
lint-go-fix: ## lint go files and fix issues
|
||||||
$(GO) run $(GOLANGCI_LINT_PACKAGE) run --fix
|
$(GO) run $(GOLANGCI_LINT_PACKAGE) run --fix
|
||||||
|
|
||||||
|
.PHONY: lint-pr-title
|
||||||
|
lint-pr-title: ## lint PR title against Conventional Commits (set PR_TITLE=...)
|
||||||
|
@node ./tools/lint-pr-title.ts
|
||||||
|
|
||||||
.PHONY: security-check
|
.PHONY: security-check
|
||||||
security-check: deps-tools
|
security-check: deps-tools
|
||||||
GOEXPERIMENT= $(GO) run $(GOVULNCHECK_PACKAGE) -show color ./... || true
|
GOEXPERIMENT= $(GO) run $(GOVULNCHECK_PACKAGE) -show color ./... || true
|
||||||
|
|||||||
@@ -431,6 +431,7 @@ func (h *Handler) upload(w http.ResponseWriter, r *http.Request, params httprout
|
|||||||
}
|
}
|
||||||
if err := h.storage.Write(cache.ID, start, r.Body); err != nil {
|
if err := h.storage.Write(cache.ID, start, r.Body); err != nil {
|
||||||
h.responseJSON(w, r, 500, err)
|
h.responseJSON(w, r, 500, err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
h.useCache(id)
|
h.useCache(id)
|
||||||
h.responseJSON(w, r, 200)
|
h.responseJSON(w, r, 200)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -338,6 +339,54 @@ func TestHandler(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("upload write failure returns only error", func(t *testing.T) {
|
||||||
|
key := strings.ToLower(t.Name())
|
||||||
|
version := "c19da02a2bd7e77277f1ac29ab45c09b7d46a4ee758284e26bb3045ad11d9d20"
|
||||||
|
var id uint64
|
||||||
|
{
|
||||||
|
body, err := json.Marshal(&Request{
|
||||||
|
Key: key,
|
||||||
|
Version: version,
|
||||||
|
Size: 100,
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
resp, err := testClient.Post(base+"/caches", "application/json", bytes.NewReader(body))
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer resp.Body.Close()
|
||||||
|
require.Equal(t, 200, resp.StatusCode)
|
||||||
|
|
||||||
|
got := struct {
|
||||||
|
CacheID uint64 `json:"cacheId"`
|
||||||
|
}{}
|
||||||
|
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
|
||||||
|
id = got.CacheID
|
||||||
|
}
|
||||||
|
|
||||||
|
storageFile := filepath.Join(dir, "not-a-directory")
|
||||||
|
require.NoError(t, os.WriteFile(storageFile, []byte("blocked"), 0o600))
|
||||||
|
originalStorage := handler.storage
|
||||||
|
handler.storage = &Storage{rootDir: storageFile}
|
||||||
|
defer func() {
|
||||||
|
handler.storage = originalStorage
|
||||||
|
}()
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodPatch,
|
||||||
|
fmt.Sprintf("%s/caches/%d", base, id), bytes.NewReader(make([]byte, 100)))
|
||||||
|
require.NoError(t, err)
|
||||||
|
req.Header.Set("Content-Type", "application/octet-stream")
|
||||||
|
req.Header.Set("Content-Range", "bytes 0-99/*")
|
||||||
|
resp, err := testClient.Do(req)
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer resp.Body.Close()
|
||||||
|
require.Equal(t, 500, resp.StatusCode)
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
require.NoError(t, err)
|
||||||
|
var got map[string]string
|
||||||
|
require.NoError(t, json.Unmarshal(body, &got))
|
||||||
|
assert.NotEmpty(t, got["error"])
|
||||||
|
})
|
||||||
|
|
||||||
t.Run("commit early", func(t *testing.T) {
|
t.Run("commit early", func(t *testing.T) {
|
||||||
key := strings.ToLower(t.Name())
|
key := strings.ToLower(t.Name())
|
||||||
version := "c19da02a2bd7e77277f1ac29ab45c09b7d46a4ee758284e26bb3045ad11d9d20"
|
version := "c19da02a2bd7e77277f1ac29ab45c09b7d46a4ee758284e26bb3045ad11d9d20"
|
||||||
|
|||||||
@@ -243,10 +243,14 @@ type NewGitCloneExecutorInput struct {
|
|||||||
InsecureSkipTLS bool
|
InsecureSkipTLS bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// CloneIfRequired ...
|
// CloneIfRequired returns the repository and a boolean indicating whether an existing local clone was reused.
|
||||||
func CloneIfRequired(ctx context.Context, refName plumbing.ReferenceName, input NewGitCloneExecutorInput, logger log.FieldLogger) (*git.Repository, error) {
|
func CloneIfRequired(ctx context.Context, refName plumbing.ReferenceName, input NewGitCloneExecutorInput, logger log.FieldLogger) (*git.Repository, bool, error) {
|
||||||
r, err := git.PlainOpen(input.Dir)
|
r, err := git.PlainOpen(input.Dir)
|
||||||
if err != nil {
|
if err == nil {
|
||||||
|
// Reuse existing clone
|
||||||
|
return r, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
var progressWriter io.Writer
|
var progressWriter io.Writer
|
||||||
if isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) {
|
if isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) {
|
||||||
if entry, ok := logger.(*log.Entry); ok {
|
if entry, ok := logger.(*log.Entry); ok {
|
||||||
@@ -275,15 +279,14 @@ func CloneIfRequired(ctx context.Context, refName plumbing.ReferenceName, input
|
|||||||
r, err = git.PlainCloneContext(ctx, input.Dir, false, &cloneOptions)
|
r, err = git.PlainCloneContext(ctx, input.Dir, false, &cloneOptions)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf("Unable to clone %v %s: %v", input.URL, refName, err)
|
logger.Errorf("Unable to clone %v %s: %v", input.URL, refName, err)
|
||||||
return nil, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = os.Chmod(input.Dir, 0o755); err != nil {
|
if err = os.Chmod(input.Dir, 0o755); err != nil {
|
||||||
return nil, err
|
return nil, false, err
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return r, nil
|
return r, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func gitOptions(token string) (fetchOptions git.FetchOptions, pullOptions git.PullOptions) {
|
func gitOptions(token string) (fetchOptions git.FetchOptions, pullOptions git.PullOptions) {
|
||||||
@@ -313,7 +316,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
|||||||
defer AcquireCloneLock(input.Dir)()
|
defer AcquireCloneLock(input.Dir)()
|
||||||
|
|
||||||
refName := plumbing.ReferenceName("refs/heads/" + input.Ref)
|
refName := plumbing.ReferenceName("refs/heads/" + input.Ref)
|
||||||
r, err := CloneIfRequired(ctx, refName, input, logger)
|
r, reused, err := CloneIfRequired(ctx, refName, input, logger)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -338,10 +341,10 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
|||||||
var hash *plumbing.Hash
|
var hash *plumbing.Hash
|
||||||
rev := plumbing.Revision(input.Ref)
|
rev := plumbing.Revision(input.Ref)
|
||||||
if hash, err = r.ResolveRevision(rev); err != nil {
|
if hash, err = r.ResolveRevision(rev); err != nil {
|
||||||
|
// ResolveRevision returns a nil hash on error, and a branch ref legitimately fails
|
||||||
|
// here (no local refs/heads/<ref>); the duck-typing below resolves it.
|
||||||
logger.Errorf("Unable to resolve %s: %v", input.Ref, err)
|
logger.Errorf("Unable to resolve %s: %v", input.Ref, err)
|
||||||
}
|
} else if hash.String() != input.Ref && strings.HasPrefix(hash.String(), input.Ref) {
|
||||||
|
|
||||||
if hash.String() != input.Ref && strings.HasPrefix(hash.String(), input.Ref) {
|
|
||||||
return &Error{
|
return &Error{
|
||||||
err: ErrShortRef,
|
err: ErrShortRef,
|
||||||
commit: hash.String(),
|
commit: hash.String(),
|
||||||
@@ -392,12 +395,18 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
reusedMsg := ""
|
||||||
|
|
||||||
if !isOfflineMode {
|
if !isOfflineMode {
|
||||||
if err = w.Pull(&pullOptions); err != nil && err != git.NoErrAlreadyUpToDate {
|
if err = w.Pull(&pullOptions); err != nil && err != git.NoErrAlreadyUpToDate {
|
||||||
logger.Debugf("Unable to pull %s: %v", refName, err)
|
logger.Debugf("Unable to pull %s: %v", refName, err)
|
||||||
}
|
}
|
||||||
|
} else if reused {
|
||||||
|
reusedMsg = " (reused in offline mode)"
|
||||||
}
|
}
|
||||||
logger.Debugf("Cloned %s to %s", input.URL, input.Dir)
|
|
||||||
|
logger.Debugf("Cloned %s to %s%s", input.URL, input.Dir, reusedMsg)
|
||||||
|
|
||||||
if hash.String() != input.Ref && refType == "branch" {
|
if hash.String() != input.Ref && refType == "branch" {
|
||||||
logger.Debugf("Provided ref is not a sha. Updating branch ref after pull")
|
logger.Debugf("Provided ref is not a sha. Updating branch ref after pull")
|
||||||
|
|||||||
@@ -279,6 +279,54 @@ func TestGitCloneExecutorNonFastForwardRef(t *testing.T) {
|
|||||||
assert.Equal(t, "second", strings.TrimSpace(string(out)), "working tree should be at the latest commit")
|
assert.Equal(t, "second", strings.TrimSpace(string(out)), "working tree should be at the latest commit")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGitCloneExecutorOfflineMode(t *testing.T) {
|
||||||
|
gitConfig()
|
||||||
|
|
||||||
|
// Build a local "remote" with a single commit on main.
|
||||||
|
remoteDir := t.TempDir()
|
||||||
|
require.NoError(t, gitCmd("init", "--bare", "--initial-branch=main", remoteDir))
|
||||||
|
workDir := t.TempDir()
|
||||||
|
require.NoError(t, gitCmd("clone", remoteDir, workDir))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "checkout", "-b", "main"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "commit", "--allow-empty", "-m", "initial"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "push", "-u", "origin", "main"))
|
||||||
|
|
||||||
|
// Prime the cache with an online clone of main.
|
||||||
|
cacheDir := t.TempDir()
|
||||||
|
require.NoError(t, NewGitCloneExecutor(NewGitCloneExecutorInput{
|
||||||
|
URL: remoteDir,
|
||||||
|
Ref: "main",
|
||||||
|
Dir: cacheDir,
|
||||||
|
})(context.Background()))
|
||||||
|
|
||||||
|
t.Run("cached branch resolves without fetching", func(t *testing.T) {
|
||||||
|
// Offline reuse of a cached branch must succeed even though ResolveRevision(input.Ref)
|
||||||
|
// finds no local refs/heads/<ref>.
|
||||||
|
err := NewGitCloneExecutor(NewGitCloneExecutorInput{
|
||||||
|
URL: remoteDir,
|
||||||
|
Ref: "main",
|
||||||
|
Dir: cacheDir,
|
||||||
|
OfflineMode: true,
|
||||||
|
})(context.Background())
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
out, err := exec.Command("git", "-C", cacheDir, "log", "--oneline", "-1", "--format=%s").Output()
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "initial", strings.TrimSpace(string(out)))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("unresolvable cached ref returns error", func(t *testing.T) {
|
||||||
|
// The ref was never cached; offline mode cannot resolve it and must return an error.
|
||||||
|
err := NewGitCloneExecutor(NewGitCloneExecutorInput{
|
||||||
|
URL: remoteDir,
|
||||||
|
Ref: "never-fetched",
|
||||||
|
Dir: cacheDir,
|
||||||
|
OfflineMode: true,
|
||||||
|
})(context.Background())
|
||||||
|
require.Error(t, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func gitConfig() {
|
func gitConfig() {
|
||||||
if os.Getenv("GITHUB_ACTIONS") == "true" {
|
if os.Getenv("GITHUB_ACTIONS") == "true" {
|
||||||
var err error
|
var err error
|
||||||
|
|||||||
@@ -8,12 +8,24 @@ package container
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
"gitea.com/gitea/runner/act/common"
|
"gitea.com/gitea/runner/act/common"
|
||||||
|
|
||||||
"github.com/moby/moby/client"
|
"github.com/moby/moby/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
dockerNetworkRemoveRetryInterval = 200 * time.Millisecond
|
||||||
|
dockerNetworkRemoveTimeout = 10 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
type dockerNetworkClient interface {
|
||||||
|
NetworkList(ctx context.Context, options client.NetworkListOptions) (client.NetworkListResult, error)
|
||||||
|
NetworkInspect(ctx context.Context, networkID string, options client.NetworkInspectOptions) (client.NetworkInspectResult, error)
|
||||||
|
NetworkRemove(ctx context.Context, networkID string, options client.NetworkRemoveOptions) (client.NetworkRemoveResult, error)
|
||||||
|
}
|
||||||
|
|
||||||
func NewDockerNetworkCreateExecutor(name string) common.Executor {
|
func NewDockerNetworkCreateExecutor(name string) common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
cli, err := GetDockerClient(ctx)
|
cli, err := GetDockerClient(ctx)
|
||||||
@@ -56,31 +68,64 @@ func NewDockerNetworkRemoveExecutor(name string) common.Executor {
|
|||||||
}
|
}
|
||||||
defer cli.Close()
|
defer cli.Close()
|
||||||
|
|
||||||
// Make sure that all network of the specified name are removed
|
return removeDockerNetworks(ctx, cli, name)
|
||||||
// cli.NetworkRemove refuses to remove a network if there are duplicates
|
}
|
||||||
networks, err := cli.NetworkList(ctx, client.NetworkListOptions{})
|
}
|
||||||
|
|
||||||
|
func removeDockerNetworks(ctx context.Context, cli dockerNetworkClient, name string) error {
|
||||||
|
cleanupCtx, cancel := context.WithTimeout(ctx, dockerNetworkRemoveTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
for {
|
||||||
|
pendingRemoval, err := removeDockerNetworksOnce(cleanupCtx, cli, name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if !pendingRemoval {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-cleanupCtx.Done():
|
||||||
|
common.Logger(ctx).Warnf("Timed out waiting for Docker network %v endpoints to detach; leaving network behind", name)
|
||||||
|
return nil
|
||||||
|
case <-time.After(dockerNetworkRemoveRetryInterval):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeDockerNetworksOnce(ctx context.Context, cli dockerNetworkClient, name string) (bool, error) {
|
||||||
|
// Make sure that all network of the specified name are removed.
|
||||||
|
// cli.NetworkRemove refuses to remove a network if there are duplicates.
|
||||||
|
networks, err := cli.NetworkList(ctx, client.NetworkListOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
// For Gitea, reduce log noise
|
// For Gitea, reduce log noise
|
||||||
// common.Logger(ctx).Debugf("%v", networks)
|
// common.Logger(ctx).Debugf("%v", networks)
|
||||||
|
|
||||||
|
pendingRemoval := false
|
||||||
for _, n := range networks.Items {
|
for _, n := range networks.Items {
|
||||||
if n.Name == name {
|
if n.Name != name {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
result, err := cli.NetworkInspect(ctx, n.ID, client.NetworkInspectOptions{})
|
result, err := cli.NetworkInspect(ctx, n.ID, client.NetworkInspectOptions{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(result.Network.Containers) != 0 {
|
||||||
|
pendingRemoval = true
|
||||||
|
common.Logger(ctx).Debugf("Waiting to remove network %v because it still has active endpoints", name)
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(result.Network.Containers) == 0 {
|
|
||||||
if _, err = cli.NetworkRemove(ctx, n.ID, client.NetworkRemoveOptions{}); err != nil {
|
if _, err = cli.NetworkRemove(ctx, n.ID, client.NetworkRemoveOptions{}); err != nil {
|
||||||
common.Logger(ctx).Debugf("%v", err)
|
pendingRemoval = true
|
||||||
}
|
common.Logger(ctx).Debugf("Retrying Docker network removal for %v: %v", name, err)
|
||||||
} else {
|
|
||||||
common.Logger(ctx).Debugf("Refusing to remove network %v because it still has active endpoints", name)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return err
|
return pendingRemoval, nil
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
115
act/container/docker_network_test.go
Normal file
115
act/container/docker_network_test.go
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||||
|
// Copyright 2026 The nektos/act Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
//go:build !(WITHOUT_DOCKER || !(linux || darwin || windows || netbsd))
|
||||||
|
|
||||||
|
package container
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
containernetwork "github.com/moby/moby/api/types/network"
|
||||||
|
"github.com/moby/moby/client"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeDockerNetworkClient struct {
|
||||||
|
listResult client.NetworkListResult
|
||||||
|
inspectByID map[string][]client.NetworkInspectResult
|
||||||
|
inspectCalls map[string]int
|
||||||
|
removeCalls []string
|
||||||
|
removeErrs map[string][]error
|
||||||
|
removeIdx map[string]int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeDockerNetworkClient) NetworkList(context.Context, client.NetworkListOptions) (client.NetworkListResult, error) {
|
||||||
|
return f.listResult, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeDockerNetworkClient) NetworkInspect(_ context.Context, networkID string, _ client.NetworkInspectOptions) (client.NetworkInspectResult, error) {
|
||||||
|
idx := f.inspectCalls[networkID]
|
||||||
|
f.inspectCalls[networkID] = idx + 1
|
||||||
|
results := f.inspectByID[networkID]
|
||||||
|
if len(results) == 0 {
|
||||||
|
return client.NetworkInspectResult{}, nil
|
||||||
|
}
|
||||||
|
if idx >= len(results) {
|
||||||
|
return results[len(results)-1], nil
|
||||||
|
}
|
||||||
|
return results[idx], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeDockerNetworkClient) NetworkRemove(_ context.Context, networkID string, _ client.NetworkRemoveOptions) (client.NetworkRemoveResult, error) {
|
||||||
|
f.removeCalls = append(f.removeCalls, networkID)
|
||||||
|
idx := f.removeIdx[networkID]
|
||||||
|
f.removeIdx[networkID] = idx + 1
|
||||||
|
if errs := f.removeErrs[networkID]; idx < len(errs) {
|
||||||
|
return client.NetworkRemoveResult{}, errs[idx]
|
||||||
|
}
|
||||||
|
return client.NetworkRemoveResult{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRemoveDockerNetworksRetriesUntilEndpointsDetach(t *testing.T) {
|
||||||
|
originalInterval := dockerNetworkRemoveRetryInterval
|
||||||
|
originalTimeout := dockerNetworkRemoveTimeout
|
||||||
|
dockerNetworkRemoveRetryInterval = time.Millisecond
|
||||||
|
dockerNetworkRemoveTimeout = 50 * time.Millisecond
|
||||||
|
t.Cleanup(func() {
|
||||||
|
dockerNetworkRemoveRetryInterval = originalInterval
|
||||||
|
dockerNetworkRemoveTimeout = originalTimeout
|
||||||
|
})
|
||||||
|
|
||||||
|
cli := &fakeDockerNetworkClient{
|
||||||
|
listResult: client.NetworkListResult{
|
||||||
|
Items: []containernetwork.Summary{{Network: containernetwork.Network{ID: "n1", Name: "test"}}},
|
||||||
|
},
|
||||||
|
inspectByID: map[string][]client.NetworkInspectResult{
|
||||||
|
"n1": {
|
||||||
|
{Network: containernetwork.Inspect{Containers: map[string]containernetwork.EndpointResource{"c1": {}}}},
|
||||||
|
{Network: containernetwork.Inspect{Containers: map[string]containernetwork.EndpointResource{}}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
inspectCalls: map[string]int{},
|
||||||
|
removeErrs: map[string][]error{},
|
||||||
|
removeIdx: map[string]int{},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := removeDockerNetworks(context.Background(), cli, "test")
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, []string{"n1"}, cli.removeCalls)
|
||||||
|
assert.GreaterOrEqual(t, cli.inspectCalls["n1"], 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRemoveDockerNetworksStopsRetryingAfterTimeout(t *testing.T) {
|
||||||
|
originalInterval := dockerNetworkRemoveRetryInterval
|
||||||
|
originalTimeout := dockerNetworkRemoveTimeout
|
||||||
|
dockerNetworkRemoveRetryInterval = time.Millisecond
|
||||||
|
dockerNetworkRemoveTimeout = 5 * time.Millisecond
|
||||||
|
t.Cleanup(func() {
|
||||||
|
dockerNetworkRemoveRetryInterval = originalInterval
|
||||||
|
dockerNetworkRemoveTimeout = originalTimeout
|
||||||
|
})
|
||||||
|
|
||||||
|
cli := &fakeDockerNetworkClient{
|
||||||
|
listResult: client.NetworkListResult{
|
||||||
|
Items: []containernetwork.Summary{{Network: containernetwork.Network{ID: "n1", Name: "test"}}},
|
||||||
|
},
|
||||||
|
inspectByID: map[string][]client.NetworkInspectResult{
|
||||||
|
"n1": {
|
||||||
|
{Network: containernetwork.Inspect{Containers: map[string]containernetwork.EndpointResource{"c1": {}}}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
inspectCalls: map[string]int{},
|
||||||
|
removeErrs: map[string][]error{},
|
||||||
|
removeIdx: map[string]int{},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := removeDockerNetworks(context.Background(), cli, "test")
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, cli.removeCalls)
|
||||||
|
assert.Positive(t, cli.inspectCalls["n1"])
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -968,22 +969,7 @@ func (cr *containerReference) sanitizeConfig(ctx context.Context, config *contai
|
|||||||
logger := common.Logger(ctx)
|
logger := common.Logger(ctx)
|
||||||
|
|
||||||
if len(cr.input.ValidVolumes) > 0 {
|
if len(cr.input.ValidVolumes) > 0 {
|
||||||
globs := make([]glob.Glob, 0, len(cr.input.ValidVolumes))
|
matcher := newValidVolumeMatcher(ctx, cr.input.ValidVolumes)
|
||||||
for _, v := range cr.input.ValidVolumes {
|
|
||||||
if g, err := glob.Compile(v); err != nil {
|
|
||||||
logger.Errorf("create glob from %s error: %v", v, err)
|
|
||||||
} else {
|
|
||||||
globs = append(globs, g)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
isValid := func(v string) bool {
|
|
||||||
for _, g := range globs {
|
|
||||||
if g.Match(v) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
// sanitize binds
|
// sanitize binds
|
||||||
sanitizedBinds := make([]string, 0, len(hostConfig.Binds))
|
sanitizedBinds := make([]string, 0, len(hostConfig.Binds))
|
||||||
for _, bind := range hostConfig.Binds {
|
for _, bind := range hostConfig.Binds {
|
||||||
@@ -997,7 +983,7 @@ func (cr *containerReference) sanitizeConfig(ctx context.Context, config *contai
|
|||||||
sanitizedBinds = append(sanitizedBinds, bind)
|
sanitizedBinds = append(sanitizedBinds, bind)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if isValid(parsed.Source) {
|
if matcher.isValid(parsed.Source, mount.Type(parsed.Type)) {
|
||||||
sanitizedBinds = append(sanitizedBinds, bind)
|
sanitizedBinds = append(sanitizedBinds, bind)
|
||||||
} else {
|
} else {
|
||||||
logger.Warnf("[%s] is not a valid volume, will be ignored", parsed.Source)
|
logger.Warnf("[%s] is not a valid volume, will be ignored", parsed.Source)
|
||||||
@@ -1007,7 +993,7 @@ func (cr *containerReference) sanitizeConfig(ctx context.Context, config *contai
|
|||||||
// sanitize mounts
|
// sanitize mounts
|
||||||
sanitizedMounts := make([]mount.Mount, 0, len(hostConfig.Mounts))
|
sanitizedMounts := make([]mount.Mount, 0, len(hostConfig.Mounts))
|
||||||
for _, mt := range hostConfig.Mounts {
|
for _, mt := range hostConfig.Mounts {
|
||||||
if isValid(mt.Source) {
|
if matcher.isValid(mt.Source, mt.Type) {
|
||||||
sanitizedMounts = append(sanitizedMounts, mt)
|
sanitizedMounts = append(sanitizedMounts, mt)
|
||||||
} else {
|
} else {
|
||||||
logger.Warnf("[%s] is not a valid volume, will be ignored", mt.Source)
|
logger.Warnf("[%s] is not a valid volume, will be ignored", mt.Source)
|
||||||
@@ -1021,3 +1007,129 @@ func (cr *containerReference) sanitizeConfig(ctx context.Context, config *contai
|
|||||||
|
|
||||||
return config, hostConfig
|
return config, hostConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type validVolumeMatcher struct {
|
||||||
|
allowAll bool
|
||||||
|
named []glob.Glob
|
||||||
|
host []glob.Glob
|
||||||
|
}
|
||||||
|
|
||||||
|
func newValidVolumeMatcher(ctx context.Context, validVolumes []string) validVolumeMatcher {
|
||||||
|
logger := common.Logger(ctx)
|
||||||
|
ret := validVolumeMatcher{
|
||||||
|
named: make([]glob.Glob, 0, len(validVolumes)),
|
||||||
|
host: make([]glob.Glob, 0, len(validVolumes)),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, v := range validVolumes {
|
||||||
|
if v == "**" {
|
||||||
|
ret.allowAll = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !isHostVolumePattern(v) {
|
||||||
|
if g, err := glob.Compile(v); err != nil {
|
||||||
|
logger.Errorf("create glob from %s error: %v", v, err)
|
||||||
|
} else {
|
||||||
|
ret.named = append(ret.named, g)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
normalized, err := normalizeHostVolumePath(v)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorf("normalize volume pattern %s error: %v", v, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if g, err := glob.Compile(normalized); err != nil {
|
||||||
|
logger.Errorf("create glob from %s error: %v", normalized, err)
|
||||||
|
} else {
|
||||||
|
ret.host = append(ret.host, g)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m validVolumeMatcher) isValid(source string, sourceType mount.Type) bool {
|
||||||
|
if m.allowAll {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if isHostVolumeSource(source, sourceType) {
|
||||||
|
normalized, err := normalizeHostVolumePath(source)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, g := range m.host {
|
||||||
|
if g.Match(normalized) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, g := range m.named {
|
||||||
|
if g.Match(source) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isHostVolumePattern(pattern string) bool {
|
||||||
|
return filepath.IsAbs(pattern) ||
|
||||||
|
strings.HasPrefix(pattern, "."+string(filepath.Separator)) ||
|
||||||
|
strings.HasPrefix(pattern, ".."+string(filepath.Separator)) ||
|
||||||
|
strings.Contains(pattern, "/") ||
|
||||||
|
strings.Contains(pattern, `\`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isHostVolumeSource(source string, sourceType mount.Type) bool {
|
||||||
|
if sourceType == mount.TypeBind {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if sourceType == mount.TypeVolume {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return isHostVolumePattern(source)
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeHostVolumePath(path string) (string, error) {
|
||||||
|
abs, err := filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return evalSymlinksExistingPrefix(abs)
|
||||||
|
}
|
||||||
|
|
||||||
|
func evalSymlinksExistingPrefix(path string) (string, error) {
|
||||||
|
resolved, err := filepath.EvalSymlinks(path)
|
||||||
|
if err == nil {
|
||||||
|
return filepath.Clean(resolved), nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
current := path
|
||||||
|
var missing []string
|
||||||
|
for {
|
||||||
|
_, err := os.Lstat(current)
|
||||||
|
if err == nil {
|
||||||
|
resolved, err := filepath.EvalSymlinks(current)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
for _, name := range slices.Backward(missing) {
|
||||||
|
resolved = filepath.Join(resolved, name)
|
||||||
|
}
|
||||||
|
return filepath.Clean(resolved), nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
parent := filepath.Dir(current)
|
||||||
|
if parent == current {
|
||||||
|
return filepath.Clean(path), nil
|
||||||
|
}
|
||||||
|
missing = append(missing, filepath.Base(current))
|
||||||
|
current = parent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -375,3 +377,40 @@ func TestCheckVolumes(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCheckVolumesRejectsEscapingHostPaths(t *testing.T) {
|
||||||
|
logger, _ := test.NewNullLogger()
|
||||||
|
ctx := common.WithLogger(context.Background(), logger)
|
||||||
|
|
||||||
|
base := t.TempDir()
|
||||||
|
allowed := filepath.Join(base, "allowed")
|
||||||
|
denied := filepath.Join(base, "denied")
|
||||||
|
require.NoError(t, os.MkdirAll(allowed, 0o700))
|
||||||
|
require.NoError(t, os.MkdirAll(denied, 0o700))
|
||||||
|
|
||||||
|
cr := &containerReference{
|
||||||
|
input: &NewContainerInput{
|
||||||
|
ValidVolumes: []string{filepath.Join(allowed, "**")},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
escapingPath := allowed + string(filepath.Separator) + ".." + string(filepath.Separator) + "denied"
|
||||||
|
_, hostConf := cr.sanitizeConfig(ctx, &container.Config{}, &container.HostConfig{
|
||||||
|
Binds: []string{escapingPath + ":/mnt"},
|
||||||
|
})
|
||||||
|
assert.Empty(t, hostConf.Binds)
|
||||||
|
|
||||||
|
linkPath := filepath.Join(allowed, "link")
|
||||||
|
if err := os.Symlink(denied, linkPath); err != nil {
|
||||||
|
t.Skipf("cannot create symlink: %v", err)
|
||||||
|
}
|
||||||
|
_, hostConf = cr.sanitizeConfig(ctx, &container.Config{}, &container.HostConfig{
|
||||||
|
Binds: []string{linkPath + ":/mnt"},
|
||||||
|
})
|
||||||
|
assert.Empty(t, hostConf.Binds)
|
||||||
|
|
||||||
|
_, hostConf = cr.sanitizeConfig(ctx, &container.Config{}, &container.HostConfig{
|
||||||
|
Binds: []string{filepath.Join(linkPath, "missing") + ":/mnt"},
|
||||||
|
})
|
||||||
|
assert.Empty(t, hostConf.Binds)
|
||||||
|
}
|
||||||
|
|||||||
@@ -37,9 +37,9 @@ type HostEnvironment struct {
|
|||||||
TmpDir string
|
TmpDir string
|
||||||
ToolCache string
|
ToolCache string
|
||||||
Workdir string
|
Workdir string
|
||||||
// BindWorkdir is true when the app runner mounts the workspace on the host and
|
// CleanWorkdir means teardown owns Workdir and may delete it. Leave false
|
||||||
// deletes the task directory after the job; host teardown must not remove Workdir.
|
// when Workdir points at a caller-owned checkout (e.g. `act` local mode).
|
||||||
BindWorkdir bool
|
CleanWorkdir bool
|
||||||
ActPath string
|
ActPath string
|
||||||
CleanUp func()
|
CleanUp func()
|
||||||
StdOut io.Writer
|
StdOut io.Writer
|
||||||
@@ -483,7 +483,7 @@ func (e *HostEnvironment) Remove() common.Executor {
|
|||||||
logger.Warnf("failed to remove host misc state %s: %v", e.Path, err)
|
logger.Warnf("failed to remove host misc state %s: %v", e.Path, err)
|
||||||
errs = append(errs, err)
|
errs = append(errs, err)
|
||||||
}
|
}
|
||||||
if !e.BindWorkdir && e.Workdir != "" {
|
if e.CleanWorkdir {
|
||||||
if err := removePathWithRetry(ctx, e.Workdir); err != nil {
|
if err := removePathWithRetry(ctx, e.Workdir); err != nil {
|
||||||
logger.Warnf("failed to remove host workspace %s: %v", e.Workdir, err)
|
logger.Warnf("failed to remove host workspace %s: %v", e.Workdir, err)
|
||||||
errs = append(errs, err)
|
errs = append(errs, err)
|
||||||
|
|||||||
@@ -141,7 +141,7 @@ func TestHostEnvironmentAllocatePTY(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHostEnvironmentRemoveCleansWorkdir(t *testing.T) {
|
func TestHostEnvironmentRemovePreservesWorkdirByDefault(t *testing.T) {
|
||||||
logger := logrus.New()
|
logger := logrus.New()
|
||||||
ctx := common.WithLogger(context.Background(), logrus.NewEntry(logger))
|
ctx := common.WithLogger(context.Background(), logrus.NewEntry(logger))
|
||||||
base := t.TempDir()
|
base := t.TempDir()
|
||||||
@@ -154,7 +154,6 @@ func TestHostEnvironmentRemoveCleansWorkdir(t *testing.T) {
|
|||||||
e := &HostEnvironment{
|
e := &HostEnvironment{
|
||||||
Path: path,
|
Path: path,
|
||||||
Workdir: workdir,
|
Workdir: workdir,
|
||||||
BindWorkdir: false,
|
|
||||||
CleanUp: func() {
|
CleanUp: func() {
|
||||||
_ = os.RemoveAll(miscRoot)
|
_ = os.RemoveAll(miscRoot)
|
||||||
},
|
},
|
||||||
@@ -162,10 +161,10 @@ func TestHostEnvironmentRemoveCleansWorkdir(t *testing.T) {
|
|||||||
}
|
}
|
||||||
require.NoError(t, e.Remove()(ctx))
|
require.NoError(t, e.Remove()(ctx))
|
||||||
_, err := os.Stat(workdir)
|
_, err := os.Stat(workdir)
|
||||||
assert.ErrorIs(t, err, os.ErrNotExist)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHostEnvironmentRemoveSkipsWorkdirWhenBindWorkdir(t *testing.T) {
|
func TestHostEnvironmentRemoveCleansWorkdirWhenOwned(t *testing.T) {
|
||||||
logger := logrus.New()
|
logger := logrus.New()
|
||||||
ctx := common.WithLogger(context.Background(), logrus.NewEntry(logger))
|
ctx := common.WithLogger(context.Background(), logrus.NewEntry(logger))
|
||||||
base := t.TempDir()
|
base := t.TempDir()
|
||||||
@@ -178,7 +177,7 @@ func TestHostEnvironmentRemoveSkipsWorkdirWhenBindWorkdir(t *testing.T) {
|
|||||||
e := &HostEnvironment{
|
e := &HostEnvironment{
|
||||||
Path: path,
|
Path: path,
|
||||||
Workdir: workdir,
|
Workdir: workdir,
|
||||||
BindWorkdir: true,
|
CleanWorkdir: true,
|
||||||
CleanUp: func() {
|
CleanUp: func() {
|
||||||
_ = os.RemoveAll(miscRoot)
|
_ = os.RemoveAll(miscRoot)
|
||||||
},
|
},
|
||||||
@@ -186,5 +185,5 @@ func TestHostEnvironmentRemoveSkipsWorkdirWhenBindWorkdir(t *testing.T) {
|
|||||||
}
|
}
|
||||||
require.NoError(t, e.Remove()(ctx))
|
require.NoError(t, e.Remove()(ctx))
|
||||||
_, err := os.Stat(workdir)
|
_, err := os.Stat(workdir)
|
||||||
require.NoError(t, err)
|
assert.ErrorIs(t, err, os.ErrNotExist)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ func parseEnvFile(e Container, srcPath string, env *map[string]string) common.Ex
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
s := bufio.NewScanner(reader)
|
s := bufio.NewScanner(reader)
|
||||||
|
// Default 64 KiB max token size is too small for realistic env-file lines; allow up to 16 MiB.
|
||||||
|
s.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
|
||||||
for s.Scan() {
|
for s.Scan() {
|
||||||
line := s.Text()
|
line := s.Text()
|
||||||
singleLineEnv := strings.Index(line, "=")
|
singleLineEnv := strings.Index(line, "=")
|
||||||
@@ -50,6 +52,9 @@ func parseEnvFile(e Container, srcPath string, env *map[string]string) common.Ex
|
|||||||
}
|
}
|
||||||
multiLineEnvContent += content
|
multiLineEnvContent += content
|
||||||
}
|
}
|
||||||
|
if err := s.Err(); err != nil {
|
||||||
|
return fmt.Errorf("reading env file: %w", err)
|
||||||
|
}
|
||||||
if !delimiterFound {
|
if !delimiterFound {
|
||||||
return fmt.Errorf("invalid format delimiter '%v' not found before end of file", multiLineEnvDelimiter)
|
return fmt.Errorf("invalid format delimiter '%v' not found before end of file", multiLineEnvDelimiter)
|
||||||
}
|
}
|
||||||
@@ -58,6 +63,9 @@ func parseEnvFile(e Container, srcPath string, env *map[string]string) common.Ex
|
|||||||
return fmt.Errorf("invalid format '%v', expected a line with '=' or '<<'", line)
|
return fmt.Errorf("invalid format '%v', expected a line with '=' or '<<'", line)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if err := s.Err(); err != nil {
|
||||||
|
return fmt.Errorf("reading env file: %w", err)
|
||||||
|
}
|
||||||
env = &localEnv
|
env = &localEnv
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
75
act/container/parse_env_file_test.go
Normal file
75
act/container/parse_env_file_test.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package container
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newTestHostEnv(t *testing.T) (*HostEnvironment, string) {
|
||||||
|
t.Helper()
|
||||||
|
e := &HostEnvironment{Path: t.TempDir()}
|
||||||
|
return e, filepath.Join(e.Path, "envfile")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseEnvFileSingleLine(t *testing.T) {
|
||||||
|
e, envPath := newTestHostEnv(t)
|
||||||
|
require.NoError(t, os.WriteFile(envPath, []byte("FOO=bar\nBAZ=qux\n"), 0o600))
|
||||||
|
|
||||||
|
env := map[string]string{}
|
||||||
|
require.NoError(t, parseEnvFile(e, envPath, &env)(context.Background()))
|
||||||
|
assert.Equal(t, "bar", env["FOO"])
|
||||||
|
assert.Equal(t, "qux", env["BAZ"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseEnvFileMultiLine(t *testing.T) {
|
||||||
|
e, envPath := newTestHostEnv(t)
|
||||||
|
content := "FOO<<EOF\nline1\nline2\nEOF\n"
|
||||||
|
require.NoError(t, os.WriteFile(envPath, []byte(content), 0o600))
|
||||||
|
|
||||||
|
env := map[string]string{}
|
||||||
|
require.NoError(t, parseEnvFile(e, envPath, &env)(context.Background()))
|
||||||
|
assert.Equal(t, "line1\nline2", env["FOO"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseEnvFileLargeValueWithinLimit(t *testing.T) {
|
||||||
|
e, envPath := newTestHostEnv(t)
|
||||||
|
big := strings.Repeat("x", 2*1024*1024)
|
||||||
|
content := "FOO<<EOF\n" + big + "\nEOF\n"
|
||||||
|
require.NoError(t, os.WriteFile(envPath, []byte(content), 0o600))
|
||||||
|
|
||||||
|
env := map[string]string{}
|
||||||
|
require.NoError(t, parseEnvFile(e, envPath, &env)(context.Background()))
|
||||||
|
assert.Equal(t, big, env["FOO"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseEnvFileLineExceedsBufferReportsScannerError(t *testing.T) {
|
||||||
|
e, envPath := newTestHostEnv(t)
|
||||||
|
tooBig := strings.Repeat("x", 17*1024*1024) // over the 16 MiB cap
|
||||||
|
content := "FOO<<EOF\n" + tooBig + "\nEOF\n"
|
||||||
|
require.NoError(t, os.WriteFile(envPath, []byte(content), 0o600))
|
||||||
|
|
||||||
|
env := map[string]string{}
|
||||||
|
err := parseEnvFile(e, envPath, &env)(context.Background())
|
||||||
|
require.ErrorIs(t, err, bufio.ErrTooLong)
|
||||||
|
assert.Contains(t, err.Error(), "reading env file")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseEnvFileMissingDelimiter(t *testing.T) {
|
||||||
|
e, envPath := newTestHostEnv(t)
|
||||||
|
require.NoError(t, os.WriteFile(envPath, []byte("FOO<<EOF\nline1\nline2\n"), 0o600))
|
||||||
|
|
||||||
|
env := map[string]string{}
|
||||||
|
err := parseEnvFile(e, envPath, &env)(context.Background())
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Contains(t, err.Error(), "delimiter")
|
||||||
|
}
|
||||||
@@ -35,6 +35,7 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
|
|||||||
steps := make([]common.Executor, 0)
|
steps := make([]common.Executor, 0)
|
||||||
preSteps := make([]common.Executor, 0)
|
preSteps := make([]common.Executor, 0)
|
||||||
var postExecutor common.Executor
|
var postExecutor common.Executor
|
||||||
|
var startErr error
|
||||||
|
|
||||||
steps = append(steps, func(ctx context.Context) error {
|
steps = append(steps, func(ctx context.Context) error {
|
||||||
logger := common.Logger(ctx)
|
logger := common.Logger(ctx)
|
||||||
@@ -165,7 +166,12 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
|
|||||||
pipeline = append(pipeline, preSteps...)
|
pipeline = append(pipeline, preSteps...)
|
||||||
pipeline = append(pipeline, steps...)
|
pipeline = append(pipeline, steps...)
|
||||||
|
|
||||||
return common.NewPipelineExecutor(info.startContainer(), common.NewPipelineExecutor(pipeline...).
|
startContainer := func(ctx context.Context) error {
|
||||||
|
startErr = info.startContainer()(ctx)
|
||||||
|
return startErr
|
||||||
|
}
|
||||||
|
|
||||||
|
return common.NewPipelineExecutor(startContainer, common.NewPipelineExecutor(pipeline...).
|
||||||
Finally(func(ctx context.Context) error {
|
Finally(func(ctx context.Context) error {
|
||||||
var cancel context.CancelFunc
|
var cancel context.CancelFunc
|
||||||
if ctx.Err() == context.Canceled {
|
if ctx.Err() == context.Canceled {
|
||||||
@@ -176,8 +182,23 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
|
|||||||
}
|
}
|
||||||
return postExecutor(ctx)
|
return postExecutor(ctx)
|
||||||
}).
|
}).
|
||||||
Finally(info.interpolateOutputs()).
|
Finally(info.interpolateOutputs())).
|
||||||
Finally(info.closeContainer()))
|
Finally(func(ctx context.Context) error {
|
||||||
|
if startErr == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanupCtx, cancel := context.WithTimeout(common.WithLogger(context.Background(), common.Logger(ctx)), time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
logger := common.Logger(cleanupCtx)
|
||||||
|
logger.Infof("Cleaning up container for failed startup of job %s", rc.JobName)
|
||||||
|
if err := info.stopContainer()(cleanupCtx); err != nil {
|
||||||
|
logger.Errorf("Error while cleaning up failed job startup: %v", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}).
|
||||||
|
Finally(info.closeContainer())
|
||||||
}
|
}
|
||||||
|
|
||||||
func setJobResult(ctx context.Context, info jobInfo, rc *RunContext, success bool) {
|
func setJobResult(ctx context.Context, info jobInfo, rc *RunContext, success bool) {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import (
|
|||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/mock"
|
"github.com/stretchr/testify/mock"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestJobExecutor(t *testing.T) {
|
func TestJobExecutor(t *testing.T) {
|
||||||
@@ -341,3 +342,64 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestNewJobExecutorCleansUpAfterStartContainerFailure(t *testing.T) {
|
||||||
|
ctx := common.WithJobErrorContainer(context.Background())
|
||||||
|
jim := &jobInfoMock{}
|
||||||
|
sfm := &stepFactoryMock{}
|
||||||
|
rc := &RunContext{
|
||||||
|
JobName: "test",
|
||||||
|
JobContainer: &jobContainerMock{},
|
||||||
|
Run: &model.Run{
|
||||||
|
JobID: "test",
|
||||||
|
Workflow: &model.Workflow{
|
||||||
|
Jobs: map[string]*model.Job{
|
||||||
|
"test": {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Config: &Config{},
|
||||||
|
}
|
||||||
|
rc.ExprEval = rc.NewExpressionEvaluator(ctx)
|
||||||
|
|
||||||
|
executorOrder := make([]string, 0)
|
||||||
|
startErr := errors.New("failed to start container")
|
||||||
|
stepModel := &model.Step{ID: "1"}
|
||||||
|
sm := &stepMock{}
|
||||||
|
|
||||||
|
jim.On("steps").Return([]*model.Step{stepModel})
|
||||||
|
jim.On("startContainer").Return(func(ctx context.Context) error {
|
||||||
|
executorOrder = append(executorOrder, "startContainer")
|
||||||
|
return startErr
|
||||||
|
})
|
||||||
|
jim.On("stopContainer").Return(func(ctx context.Context) error {
|
||||||
|
executorOrder = append(executorOrder, "stopContainer")
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
jim.On("closeContainer").Return(func(ctx context.Context) error {
|
||||||
|
executorOrder = append(executorOrder, "closeContainer")
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
jim.On("interpolateOutputs").Return(func(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
sfm.On("newStep", stepModel, rc).Return(sm, nil)
|
||||||
|
sm.On("pre").Return(func(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
sm.On("main").Return(func(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
sm.On("post").Return(func(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
executor := newJobExecutor(jim, sfm, rc)
|
||||||
|
err := executor(ctx)
|
||||||
|
require.ErrorIs(t, err, startErr)
|
||||||
|
assert.Equal(t, []string{"startContainer", "stopContainer", "closeContainer"}, executorOrder)
|
||||||
|
|
||||||
|
jim.AssertExpectations(t)
|
||||||
|
sfm.AssertExpectations(t)
|
||||||
|
sm.AssertExpectations(t)
|
||||||
|
}
|
||||||
|
|||||||
@@ -308,6 +308,11 @@ func getGitCloneToken(conf *Config, cloneURL string) string {
|
|||||||
// 1. cloneURL is from the same Gitea instance that the runner is registered to
|
// 1. cloneURL is from the same Gitea instance that the runner is registered to
|
||||||
// 2. the cloneURL does not have basic auth embedded
|
// 2. the cloneURL does not have basic auth embedded
|
||||||
func shouldCloneURLUseToken(instanceURL, cloneURL string) bool {
|
func shouldCloneURLUseToken(instanceURL, cloneURL string) bool {
|
||||||
|
if !strings.HasPrefix(instanceURL, "http://") &&
|
||||||
|
!strings.HasPrefix(instanceURL, "https://") {
|
||||||
|
instanceURL = "https://" + instanceURL
|
||||||
|
}
|
||||||
|
|
||||||
u1, err1 := url.Parse(instanceURL)
|
u1, err1 := url.Parse(instanceURL)
|
||||||
u2, err2 := url.Parse(cloneURL)
|
u2, err2 := url.Parse(cloneURL)
|
||||||
if err1 != nil || err2 != nil {
|
if err1 != nil || err2 != nil {
|
||||||
|
|||||||
@@ -123,6 +123,65 @@ func TestNewReusableWorkflowExecutorHoldsCloneLock(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetGitCloneTokenWithSchemalessGiteaInstance(t *testing.T) {
|
||||||
|
conf := &Config{
|
||||||
|
GitHubInstance: "gitea.example.net",
|
||||||
|
Secrets: map[string]string{
|
||||||
|
"GITEA_TOKEN": "token-value",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
token := getGitCloneToken(conf, "https://gitea.example.net/actions/tools")
|
||||||
|
|
||||||
|
require.Equal(t, "token-value", token)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShouldCloneURLUseToken(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
instanceURL string
|
||||||
|
cloneURL string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "same host with schemaless instance",
|
||||||
|
instanceURL: "gitea.example.net",
|
||||||
|
cloneURL: "https://gitea.example.net/actions/tools",
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "same host with schemaless instance and port",
|
||||||
|
instanceURL: "gitea.example.net:3000",
|
||||||
|
cloneURL: "https://gitea.example.net:3000/actions/tools",
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "different host",
|
||||||
|
instanceURL: "gitea.example.net",
|
||||||
|
cloneURL: "https://github.com/actions/tools",
|
||||||
|
want: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "embedded basic auth",
|
||||||
|
instanceURL: "gitea.example.net",
|
||||||
|
cloneURL: "https://user:pass@gitea.example.net/actions/tools",
|
||||||
|
want: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid clone URL",
|
||||||
|
instanceURL: "gitea.example.net",
|
||||||
|
cloneURL: "://gitea.example.net/actions/tools",
|
||||||
|
want: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
require.Equal(t, tt.want, shouldCloneURLUseToken(tt.instanceURL, tt.cloneURL))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func gitMust(t *testing.T, dir string, args ...string) {
|
func gitMust(t *testing.T, dir string, args ...string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
cmd := exec.Command("git", args...)
|
cmd := exec.Command("git", args...)
|
||||||
|
|||||||
@@ -224,7 +224,7 @@ func (rc *RunContext) startHostEnvironment() common.Executor {
|
|||||||
TmpDir: runnerTmp,
|
TmpDir: runnerTmp,
|
||||||
ToolCache: toolCache,
|
ToolCache: toolCache,
|
||||||
Workdir: rc.Config.Workdir,
|
Workdir: rc.Config.Workdir,
|
||||||
BindWorkdir: rc.Config.BindWorkdir,
|
CleanWorkdir: rc.Config.CleanWorkdir,
|
||||||
ActPath: actPath,
|
ActPath: actPath,
|
||||||
CleanUp: func() {
|
CleanUp: func() {
|
||||||
os.RemoveAll(miscpath)
|
os.RemoveAll(miscpath)
|
||||||
@@ -601,10 +601,34 @@ func (rc *RunContext) interpolateOutputs() common.Executor {
|
|||||||
|
|
||||||
func (rc *RunContext) startContainer() common.Executor {
|
func (rc *RunContext) startContainer() common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
|
var err error
|
||||||
if rc.IsHostEnv(ctx) {
|
if rc.IsHostEnv(ctx) {
|
||||||
return rc.startHostEnvironment()(ctx)
|
err = rc.startHostEnvironment()(ctx)
|
||||||
|
} else {
|
||||||
|
err = rc.startJobContainer()(ctx)
|
||||||
}
|
}
|
||||||
return rc.startJobContainer()(ctx)
|
if err != nil {
|
||||||
|
// The job executor's teardown only runs after a successful start, so a failed
|
||||||
|
// start would otherwise leak the per-job network and container.
|
||||||
|
rc.cleanupFailedStart(ctx)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rc *RunContext) cleanupFailedStart(ctx context.Context) {
|
||||||
|
if rc.cleanUpJobContainer == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cleanCtx := ctx
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
// the start likely failed because ctx was cancelled, detach so teardown still runs
|
||||||
|
var cancel context.CancelFunc
|
||||||
|
cleanCtx, cancel = context.WithTimeout(common.WithLogger(context.Background(), common.Logger(ctx)), time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
}
|
||||||
|
if err := rc.cleanUpJobContainer(cleanCtx); err != nil {
|
||||||
|
common.Logger(ctx).Errorf("Error while cleaning up after failed container start for job %s: %v", rc.JobName, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import (
|
|||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
assert "github.com/stretchr/testify/assert"
|
assert "github.com/stretchr/testify/assert"
|
||||||
|
require "github.com/stretchr/testify/require"
|
||||||
yaml "go.yaml.in/yaml/v4"
|
yaml "go.yaml.in/yaml/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -659,3 +660,53 @@ func TestPrintStartJobContainerGroupGolden(t *testing.T) {
|
|||||||
}, "\n")
|
}, "\n")
|
||||||
assert.Equal(t, want, buf.String())
|
assert.Equal(t, want, buf.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRunContext_cleanupFailedStart(t *testing.T) {
|
||||||
|
type ctxKey string
|
||||||
|
const sentinel = ctxKey("sentinel")
|
||||||
|
|
||||||
|
// the fresh context is cancelled via defer on return, so capture state inside the stub
|
||||||
|
type capture struct {
|
||||||
|
calls int
|
||||||
|
err error
|
||||||
|
sentinel any
|
||||||
|
}
|
||||||
|
newRC := func(c *capture) *RunContext {
|
||||||
|
return &RunContext{
|
||||||
|
JobName: "job",
|
||||||
|
cleanUpJobContainer: func(ctx context.Context) error {
|
||||||
|
c.calls++
|
||||||
|
c.err = ctx.Err()
|
||||||
|
c.sentinel = ctx.Value(sentinel)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("runs teardown on the live context", func(t *testing.T) {
|
||||||
|
var c capture
|
||||||
|
ctx := context.WithValue(context.Background(), sentinel, "v")
|
||||||
|
|
||||||
|
newRC(&c).cleanupFailedStart(ctx)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, c.calls)
|
||||||
|
require.NoError(t, c.err)
|
||||||
|
assert.Equal(t, "v", c.sentinel)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("falls back to a fresh context when the input is done", func(t *testing.T) {
|
||||||
|
var c capture
|
||||||
|
ctx, cancel := context.WithCancel(context.WithValue(context.Background(), sentinel, "v"))
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
newRC(&c).cleanupFailedStart(ctx)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, c.calls)
|
||||||
|
require.NoError(t, c.err)
|
||||||
|
assert.Nil(t, c.sentinel)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("no-op when there is nothing to clean up", func(t *testing.T) {
|
||||||
|
assert.NotPanics(t, func() { (&RunContext{}).cleanupFailedStart(context.Background()) })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ type Config struct {
|
|||||||
Actor string // the user that triggered the event
|
Actor string // the user that triggered the event
|
||||||
Workdir string // path to working directory
|
Workdir string // path to working directory
|
||||||
ActionCacheDir string // path used for caching action contents
|
ActionCacheDir string // path used for caching action contents
|
||||||
ActionOfflineMode bool // when offline, use caching action contents
|
ActionOfflineMode bool // when offline, use cached action contents
|
||||||
BindWorkdir bool // bind the workdir to the job container
|
BindWorkdir bool // bind the workdir to the job container
|
||||||
EventName string // name of event to run
|
EventName string // name of event to run
|
||||||
EventPath string // path to JSON file to use for event.json in containers
|
EventPath string // path to JSON file to use for event.json in containers
|
||||||
@@ -73,6 +73,7 @@ type Config struct {
|
|||||||
EventJSON string // the content of JSON file to use for event.json in containers, overrides EventPath
|
EventJSON string // the content of JSON file to use for event.json in containers, overrides EventPath
|
||||||
ContainerNamePrefix string // the prefix of container name
|
ContainerNamePrefix string // the prefix of container name
|
||||||
ContainerMaxLifetime time.Duration // the max lifetime of job containers
|
ContainerMaxLifetime time.Duration // the max lifetime of job containers
|
||||||
|
CleanWorkdir bool // remove host executor workdir on teardown
|
||||||
DefaultActionInstance string // the default actions web site
|
DefaultActionInstance string // the default actions web site
|
||||||
PlatformPicker func(labels []string) string // platform picker, it will take precedence over Platforms if isn't nil
|
PlatformPicker func(labels []string) string // platform picker, it will take precedence over Platforms if isn't nil
|
||||||
JobLoggerLevel *log.Level // the level of job logger
|
JobLoggerLevel *log.Level // the level of job logger
|
||||||
@@ -91,6 +92,17 @@ func (c Config) GetToken() string {
|
|||||||
return token
|
return token
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DefaultActionURL returns the host used for implicit remote actions.
|
||||||
|
func (c Config) DefaultActionURL() string {
|
||||||
|
if c.DefaultActionInstance != "" {
|
||||||
|
return c.DefaultActionInstance
|
||||||
|
}
|
||||||
|
if c.GitHubInstance != "" {
|
||||||
|
return c.GitHubInstance
|
||||||
|
}
|
||||||
|
return "github.com"
|
||||||
|
}
|
||||||
|
|
||||||
type caller struct {
|
type caller struct {
|
||||||
runContext *RunContext
|
runContext *RunContext
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"gitea.com/gitea/runner/act/common"
|
"gitea.com/gitea/runner/act/common"
|
||||||
"gitea.com/gitea/runner/act/model"
|
"gitea.com/gitea/runner/act/model"
|
||||||
@@ -192,6 +193,7 @@ func (j *TestJobFileInfo) runTest(ctx context.Context, t *testing.T, cfg *Config
|
|||||||
Inputs: cfg.Inputs,
|
Inputs: cfg.Inputs,
|
||||||
GitHubInstance: "github.com",
|
GitHubInstance: "github.com",
|
||||||
ContainerArchitecture: cfg.ContainerArchitecture,
|
ContainerArchitecture: cfg.ContainerArchitecture,
|
||||||
|
ContainerMaxLifetime: time.Hour,
|
||||||
Matrix: cfg.Matrix,
|
Matrix: cfg.Matrix,
|
||||||
ActionCache: cfg.ActionCache,
|
ActionCache: cfg.ActionCache,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,9 +113,10 @@ func (sar *stepActionRemote) prepareActionExecutor() common.Executor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
actionDir := fmt.Sprintf("%s/%s", sar.RunContext.ActionCacheDir(), sar.Step.UsesHash())
|
actionDir := fmt.Sprintf("%s/%s", sar.RunContext.ActionCacheDir(), sar.Step.UsesHash())
|
||||||
token := getGitCloneToken(sar.getRunContext().Config, sar.remoteAction.CloneURL(sar.RunContext.Config.DefaultActionInstance))
|
defaultActionURL := sar.RunContext.Config.DefaultActionURL()
|
||||||
|
token := getGitCloneToken(sar.getRunContext().Config, sar.remoteAction.CloneURL(defaultActionURL))
|
||||||
gitClone := stepActionRemoteNewCloneExecutor(git.NewGitCloneExecutorInput{
|
gitClone := stepActionRemoteNewCloneExecutor(git.NewGitCloneExecutorInput{
|
||||||
URL: sar.remoteAction.CloneURL(sar.RunContext.Config.DefaultActionInstance),
|
URL: sar.remoteAction.CloneURL(defaultActionURL),
|
||||||
Ref: sar.remoteAction.Ref,
|
Ref: sar.remoteAction.Ref,
|
||||||
Dir: actionDir,
|
Dir: actionDir,
|
||||||
Token: token,
|
Token: token,
|
||||||
@@ -274,7 +275,7 @@ func (sar *stepActionRemote) cloneSkipTLS() bool {
|
|||||||
if sar.remoteAction.URL == "" {
|
if sar.remoteAction.URL == "" {
|
||||||
// Empty URL means the default action instance should be used
|
// Empty URL means the default action instance should be used
|
||||||
// Return true if the URL of the Gitea instance is the same as the URL of the default action instance
|
// Return true if the URL of the Gitea instance is the same as the URL of the default action instance
|
||||||
return sar.RunContext.Config.DefaultActionInstance == sar.RunContext.Config.GitHubInstance
|
return sar.RunContext.Config.DefaultActionURL() == sar.RunContext.Config.GitHubInstance
|
||||||
}
|
}
|
||||||
// Return true if the URL of the remote action is the same as the URL of the Gitea instance
|
// Return true if the URL of the remote action is the same as the URL of the Gitea instance
|
||||||
return sar.remoteAction.URL == sar.RunContext.Config.GitHubInstance
|
return sar.remoteAction.URL == sar.RunContext.Config.GitHubInstance
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/mock"
|
"github.com/stretchr/testify/mock"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
"go.yaml.in/yaml/v4"
|
"go.yaml.in/yaml/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -434,6 +435,57 @@ func TestStepActionRemotePreThroughActionToken(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStepActionRemoteUsesGitHubInstanceWhenDefaultActionInstanceEmpty(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
var actualURL string
|
||||||
|
sarm := &stepActionRemoteMocks{}
|
||||||
|
|
||||||
|
origStepAtionRemoteNewCloneExecutor := stepActionRemoteNewCloneExecutor
|
||||||
|
stepActionRemoteNewCloneExecutor = func(input git.NewGitCloneExecutorInput) common.Executor {
|
||||||
|
return func(ctx context.Context) error {
|
||||||
|
actualURL = input.URL
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
stepActionRemoteNewCloneExecutor = origStepAtionRemoteNewCloneExecutor
|
||||||
|
}()
|
||||||
|
|
||||||
|
sar := &stepActionRemote{
|
||||||
|
Step: &model.Step{
|
||||||
|
Uses: "actions/setup-go@v4",
|
||||||
|
},
|
||||||
|
RunContext: &RunContext{
|
||||||
|
Config: &Config{
|
||||||
|
GitHubInstance: "gitea.example",
|
||||||
|
DefaultActionInstance: "",
|
||||||
|
ActionCacheDir: t.TempDir(),
|
||||||
|
},
|
||||||
|
Run: &model.Run{
|
||||||
|
JobID: "1",
|
||||||
|
Workflow: &model.Workflow{
|
||||||
|
Jobs: map[string]*model.Job{
|
||||||
|
"1": {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
readAction: sarm.readAction,
|
||||||
|
}
|
||||||
|
|
||||||
|
suffixMatcher := func(suffix string) any {
|
||||||
|
return mock.MatchedBy(func(actionDir string) bool {
|
||||||
|
return strings.HasSuffix(actionDir, suffix)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
sarm.On("readAction", sar.Step, suffixMatcher(sar.Step.UsesHash()), "", mock.Anything, mock.Anything).Return(&model.Action{}, nil)
|
||||||
|
|
||||||
|
require.NoError(t, sar.prepareActionExecutor()(ctx))
|
||||||
|
assert.Equal(t, "https://gitea.example/actions/setup-go", actualURL)
|
||||||
|
sarm.AssertExpectations(t)
|
||||||
|
}
|
||||||
|
|
||||||
func TestStepActionRemotePost(t *testing.T) {
|
func TestStepActionRemotePost(t *testing.T) {
|
||||||
table := []struct {
|
table := []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM alpine:3
|
FROM alpine:3.23
|
||||||
|
|
||||||
COPY entrypoint.sh /entrypoint.sh
|
COPY entrypoint.sh /entrypoint.sh
|
||||||
|
|
||||||
|
|||||||
@@ -10,4 +10,4 @@ outputs:
|
|||||||
description: 'The time we greeted you'
|
description: 'The time we greeted you'
|
||||||
runs:
|
runs:
|
||||||
using: 'node24'
|
using: 'node24'
|
||||||
main: 'dist/index.js'
|
main: 'index.js'
|
||||||
|
|||||||
19
act/runner/testdata/actions/node24/index.js
vendored
19
act/runner/testdata/actions/node24/index.js
vendored
@@ -1,11 +1,14 @@
|
|||||||
import {getInput, setOutput, setFailed} from '@actions/core';
|
import {appendFileSync, readFileSync} from 'node:fs';
|
||||||
import {context} from '@actions/github';
|
|
||||||
|
|
||||||
try {
|
const nameToGreet = process.env['INPUT_WHO-TO-GREET'] || 'World';
|
||||||
const nameToGreet = getInput('who-to-greet');
|
|
||||||
console.log(`Hello ${nameToGreet}!`);
|
console.log(`Hello ${nameToGreet}!`);
|
||||||
setOutput('time', (new Date()).toTimeString());
|
|
||||||
console.log(`The event payload: ${JSON.stringify(context.payload, undefined, 2)}`);
|
if (process.env.GITHUB_OUTPUT) {
|
||||||
} catch (error) {
|
appendFileSync(process.env.GITHUB_OUTPUT, `time=${new Date().toTimeString()}\n`);
|
||||||
setFailed(error.message);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let payload = {};
|
||||||
|
if (process.env.GITHUB_EVENT_PATH) {
|
||||||
|
payload = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'));
|
||||||
|
}
|
||||||
|
console.log(`The event payload: ${JSON.stringify(payload, undefined, 2)}`);
|
||||||
|
|||||||
20
act/runner/testdata/actions/node24/package.json
vendored
20
act/runner/testdata/actions/node24/package.json
vendored
@@ -1,21 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "node24",
|
"name": "node24",
|
||||||
"version": "1.0.0",
|
"private": true,
|
||||||
"description": "",
|
"type": "module"
|
||||||
"main": "index.js",
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"build": "ncc build index.js"
|
|
||||||
},
|
|
||||||
"license": "ISC",
|
|
||||||
"dependencies": {
|
|
||||||
"@actions/core": "^3.0.1",
|
|
||||||
"@actions/github": "^9.1.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@vercel/ncc": "^0.38.4"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=24"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
2
act/runner/testdata/secrets/.env
vendored
Normal file
2
act/runner/testdata/secrets/.env
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
HELLO=WORLD
|
||||||
|
MULTILINE_ENV="foo\nbar\nbaz"
|
||||||
8
go.mod
8
go.mod
@@ -4,17 +4,17 @@ go 1.26.0
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
code.gitea.io/actions-proto-go v0.4.1
|
code.gitea.io/actions-proto-go v0.4.1
|
||||||
connectrpc.com/connect v1.19.2
|
connectrpc.com/connect v1.20.0
|
||||||
dario.cat/mergo v1.0.2
|
dario.cat/mergo v1.0.2
|
||||||
github.com/Masterminds/semver v1.5.0
|
github.com/Masterminds/semver v1.5.0
|
||||||
github.com/avast/retry-go/v5 v5.0.0
|
github.com/avast/retry-go/v5 v5.0.0
|
||||||
github.com/containerd/errdefs v1.0.0
|
github.com/containerd/errdefs v1.0.0
|
||||||
github.com/creack/pty v1.1.24
|
github.com/creack/pty v1.1.24
|
||||||
github.com/distribution/reference v0.6.0
|
github.com/distribution/reference v0.6.0
|
||||||
github.com/docker/cli v29.5.0+incompatible
|
github.com/docker/cli v29.5.2+incompatible
|
||||||
github.com/docker/go-connections v0.7.0
|
github.com/docker/go-connections v0.7.0
|
||||||
github.com/go-git/go-billy/v5 v5.9.0
|
github.com/go-git/go-billy/v5 v5.9.0
|
||||||
github.com/go-git/go-git/v5 v5.19.0
|
github.com/go-git/go-git/v5 v5.19.1
|
||||||
github.com/gobwas/glob v0.2.3
|
github.com/gobwas/glob v0.2.3
|
||||||
github.com/google/go-cmp v0.7.0
|
github.com/google/go-cmp v0.7.0
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
@@ -26,7 +26,7 @@ require (
|
|||||||
github.com/moby/moby/client v0.4.1
|
github.com/moby/moby/client v0.4.1
|
||||||
github.com/moby/patternmatcher v0.6.1
|
github.com/moby/patternmatcher v0.6.1
|
||||||
github.com/opencontainers/image-spec v1.1.1
|
github.com/opencontainers/image-spec v1.1.1
|
||||||
github.com/opencontainers/selinux v1.14.1
|
github.com/opencontainers/selinux v1.15.0
|
||||||
github.com/pkg/errors v0.9.1
|
github.com/pkg/errors v0.9.1
|
||||||
github.com/prometheus/client_golang v1.23.2
|
github.com/prometheus/client_golang v1.23.2
|
||||||
github.com/rhysd/actionlint v1.7.12
|
github.com/rhysd/actionlint v1.7.12
|
||||||
|
|||||||
14
go.sum
14
go.sum
@@ -2,6 +2,8 @@ code.gitea.io/actions-proto-go v0.4.1 h1:l0EYhjsgpUe/1VABo2eK7zcoNX2W44WOnb0MSLr
|
|||||||
code.gitea.io/actions-proto-go v0.4.1/go.mod h1:mn7Wkqz6JbnTOHQpot3yDeHx+O5C9EGhMEE+htvHBas=
|
code.gitea.io/actions-proto-go v0.4.1/go.mod h1:mn7Wkqz6JbnTOHQpot3yDeHx+O5C9EGhMEE+htvHBas=
|
||||||
connectrpc.com/connect v1.19.2 h1:McQ83FGdzL+t60peksi0gXC7MQ/iLKgLduAnThbM0mo=
|
connectrpc.com/connect v1.19.2 h1:McQ83FGdzL+t60peksi0gXC7MQ/iLKgLduAnThbM0mo=
|
||||||
connectrpc.com/connect v1.19.2/go.mod h1:tN20fjdGlewnSFeZxLKb0xwIZ6ozc3OQs2hTXy4du9w=
|
connectrpc.com/connect v1.19.2/go.mod h1:tN20fjdGlewnSFeZxLKb0xwIZ6ozc3OQs2hTXy4du9w=
|
||||||
|
connectrpc.com/connect v1.20.0 h1:6TNDAB+WeNd2uolWNlYczB5E0KNNaVMNUEx8JEUsPmQ=
|
||||||
|
connectrpc.com/connect v1.20.0/go.mod h1:A2ygJrukXwWy32vkCAAHNVguZrqZ+jeZ9rGRnGR4dN4=
|
||||||
cyphar.com/go-pathrs v0.2.3 h1:0pH8gep37wB0BgaXrEaN1OtZhUMeS7VvaejSr6i822o=
|
cyphar.com/go-pathrs v0.2.3 h1:0pH8gep37wB0BgaXrEaN1OtZhUMeS7VvaejSr6i822o=
|
||||||
cyphar.com/go-pathrs v0.2.3/go.mod h1:y8f1EMG7r+hCuFf/rXsKqMJrJAUoADZGNh5/vZPKcGc=
|
cyphar.com/go-pathrs v0.2.3/go.mod h1:y8f1EMG7r+hCuFf/rXsKqMJrJAUoADZGNh5/vZPKcGc=
|
||||||
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
||||||
@@ -47,10 +49,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
|||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||||
github.com/docker/cli v29.4.3+incompatible h1:u+UliYm2J/rYrIh2FqHQg32neRG8GjbvNuwQRTzGspU=
|
github.com/docker/cli v29.5.2+incompatible h1:ubykJ1Y8LmNRGJ2BuMQ0kHOt/RO1YzGNswqWMJgivuQ=
|
||||||
github.com/docker/cli v29.4.3+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
|
github.com/docker/cli v29.5.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
|
||||||
github.com/docker/cli v29.5.0+incompatible h1:FPUvKJoKpeP4Njz8NrQdeUN8o247P7ndTiILtaP5/l4=
|
|
||||||
github.com/docker/cli v29.5.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
|
|
||||||
github.com/docker/docker-credential-helpers v0.9.6 h1:cT2PbRPSlnMmNTfT2TDMXRyQ1KMWHG7xoTLBcn1ZNv0=
|
github.com/docker/docker-credential-helpers v0.9.6 h1:cT2PbRPSlnMmNTfT2TDMXRyQ1KMWHG7xoTLBcn1ZNv0=
|
||||||
github.com/docker/docker-credential-helpers v0.9.6/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c=
|
github.com/docker/docker-credential-helpers v0.9.6/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c=
|
||||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||||
@@ -73,8 +73,8 @@ github.com/go-git/go-billy/v5 v5.9.0 h1:jItGXszUDRtR/AlferWPTMN4j38BQ88XnXKbilmm
|
|||||||
github.com/go-git/go-billy/v5 v5.9.0/go.mod h1:jCnQMLj9eUgGU7+ludSTYoZL/GGmii14RxKFj7ROgHw=
|
github.com/go-git/go-billy/v5 v5.9.0/go.mod h1:jCnQMLj9eUgGU7+ludSTYoZL/GGmii14RxKFj7ROgHw=
|
||||||
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
|
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
|
||||||
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
|
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
|
||||||
github.com/go-git/go-git/v5 v5.19.0 h1:+WkVUQZSy/F1Gb13udrMKjIM2PrzsNfDKFSfo5tkMtc=
|
github.com/go-git/go-git/v5 v5.19.1 h1:nX27AnaU43/K5bKktKwgBmR9lawoYVe1Ckg0rgzzN00=
|
||||||
github.com/go-git/go-git/v5 v5.19.0/go.mod h1:Pb1v0c7/g8aGQJwx9Us09W85yGoyvSwuhEGMH7zjDKQ=
|
github.com/go-git/go-git/v5 v5.19.1/go.mod h1:Pb1v0c7/g8aGQJwx9Us09W85yGoyvSwuhEGMH7zjDKQ=
|
||||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
@@ -151,6 +151,8 @@ github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJw
|
|||||||
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
||||||
github.com/opencontainers/selinux v1.14.1 h1:a7XlXV/nN/l5zFP1FWZYoExpClu1QOPMfWUV2CZ8kEQ=
|
github.com/opencontainers/selinux v1.14.1 h1:a7XlXV/nN/l5zFP1FWZYoExpClu1QOPMfWUV2CZ8kEQ=
|
||||||
github.com/opencontainers/selinux v1.14.1/go.mod h1:LenyElirjUHszfxrjuFqC85HIeXZKumHcKMQtnaDlQQ=
|
github.com/opencontainers/selinux v1.14.1/go.mod h1:LenyElirjUHszfxrjuFqC85HIeXZKumHcKMQtnaDlQQ=
|
||||||
|
github.com/opencontainers/selinux v1.15.0 h1:4Gs40e/R2FvM8PC1HPaPncLLaDor8Y2WDfk5gjU9o5M=
|
||||||
|
github.com/opencontainers/selinux v1.15.0/go.mod h1:LenyElirjUHszfxrjuFqC85HIeXZKumHcKMQtnaDlQQ=
|
||||||
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
|
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
|
||||||
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
|
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
|
||||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
|||||||
@@ -132,7 +132,6 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
|
|||||||
cfg.Runner.Insecure,
|
cfg.Runner.Insecure,
|
||||||
reg.UUID,
|
reg.UUID,
|
||||||
reg.Token,
|
reg.Token,
|
||||||
ver.Version(),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
runner := run.NewRunner(cfg, reg, cli)
|
runner := run.NewRunner(cfg, reg, cli)
|
||||||
|
|||||||
@@ -325,7 +325,6 @@ func doRegister(ctx context.Context, cfg *config.Config, inputs *registerInputs)
|
|||||||
cfg.Runner.Insecure,
|
cfg.Runner.Insecure,
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
ver.Version(),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
@@ -369,7 +368,6 @@ func doRegister(ctx context.Context, cfg *config.Config, inputs *registerInputs)
|
|||||||
Name: reg.Name,
|
Name: reg.Name,
|
||||||
Token: reg.Token,
|
Token: reg.Token,
|
||||||
Version: ver.Version(),
|
Version: ver.Version(),
|
||||||
AgentLabels: ls, // Could be removed after Gitea 1.20
|
|
||||||
Labels: ls,
|
Labels: ls,
|
||||||
Ephemeral: reg.Ephemeral,
|
Ephemeral: reg.Ephemeral,
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -348,6 +348,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
|||||||
BindWorkdir: r.cfg.Container.BindWorkdir,
|
BindWorkdir: r.cfg.Container.BindWorkdir,
|
||||||
ActionCacheDir: filepath.FromSlash(r.cfg.Host.WorkdirParent),
|
ActionCacheDir: filepath.FromSlash(r.cfg.Host.WorkdirParent),
|
||||||
AllocatePTY: r.cfg.Runner.AllocatePTY,
|
AllocatePTY: r.cfg.Runner.AllocatePTY,
|
||||||
|
ActionOfflineMode: r.cfg.Cache.OfflineMode,
|
||||||
|
|
||||||
ReuseContainers: false,
|
ReuseContainers: false,
|
||||||
ForcePull: r.cfg.Container.ForcePull,
|
ForcePull: r.cfg.Container.ForcePull,
|
||||||
@@ -363,6 +364,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
|||||||
EventJSON: string(eventJSON),
|
EventJSON: string(eventJSON),
|
||||||
ContainerNamePrefix: fmt.Sprintf("GITEA-ACTIONS-TASK-%d", task.Id),
|
ContainerNamePrefix: fmt.Sprintf("GITEA-ACTIONS-TASK-%d", task.Id),
|
||||||
ContainerMaxLifetime: maxLifetime,
|
ContainerMaxLifetime: maxLifetime,
|
||||||
|
CleanWorkdir: true,
|
||||||
ContainerNetworkMode: container.NetworkMode(r.cfg.Container.Network),
|
ContainerNetworkMode: container.NetworkMode(r.cfg.Container.Network),
|
||||||
ContainerOptions: r.cfg.Container.Options,
|
ContainerOptions: r.cfg.Container.Options,
|
||||||
ContainerDaemonSocket: r.cfg.Container.DockerHost,
|
ContainerDaemonSocket: r.cfg.Container.DockerHost,
|
||||||
|
|||||||
@@ -6,6 +6,4 @@ package client
|
|||||||
const (
|
const (
|
||||||
UUIDHeader = "x-runner-uuid"
|
UUIDHeader = "x-runner-uuid"
|
||||||
TokenHeader = "x-runner-token"
|
TokenHeader = "x-runner-token"
|
||||||
// Deprecated: could be removed after Gitea 1.20 released
|
|
||||||
VersionHeader = "x-runner-version"
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ func getHTTPClient(endpoint string, insecure bool) *http.Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New returns a new runner client.
|
// New returns a new runner client.
|
||||||
func New(endpoint string, insecure bool, uuid, token, version string, opts ...connect.ClientOption) *HTTPClient {
|
func New(endpoint string, insecure bool, uuid, token string, opts ...connect.ClientOption) *HTTPClient {
|
||||||
baseURL := strings.TrimRight(endpoint, "/") + "/api/actions"
|
baseURL := strings.TrimRight(endpoint, "/") + "/api/actions"
|
||||||
|
|
||||||
opts = append(opts, connect.WithInterceptors(connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
|
opts = append(opts, connect.WithInterceptors(connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
|
||||||
@@ -42,10 +42,6 @@ func New(endpoint string, insecure bool, uuid, token, version string, opts ...co
|
|||||||
if token != "" {
|
if token != "" {
|
||||||
req.Header().Set(TokenHeader, token)
|
req.Header().Set(TokenHeader, token)
|
||||||
}
|
}
|
||||||
// TODO: version will be removed from request header after Gitea 1.20 released.
|
|
||||||
if version != "" {
|
|
||||||
req.Header().Set(VersionHeader, version)
|
|
||||||
}
|
|
||||||
return next(ctx, req)
|
return next(ctx, req)
|
||||||
}
|
}
|
||||||
})))
|
})))
|
||||||
|
|||||||
@@ -102,6 +102,9 @@ cache:
|
|||||||
# (or `gitea-runner cache-server`) is in use: the runner pre-registers each job's ACTIONS_RUNTIME_TOKEN with the
|
# (or `gitea-runner cache-server`) is in use: the runner pre-registers each job's ACTIONS_RUNTIME_TOKEN with the
|
||||||
# cache-server, and the cache-server enforces bearer auth + per-repo cache isolation.
|
# cache-server, and the cache-server enforces bearer auth + per-repo cache isolation.
|
||||||
external_secret: ""
|
external_secret: ""
|
||||||
|
# When true, reuse a cached action instead of fetching from the remote on every job. Note: a moved tag
|
||||||
|
# (e.g. a re-tagged "v6") or an updated branch stays at the cached commit until its cache entry is removed.
|
||||||
|
offline_mode: false
|
||||||
|
|
||||||
container:
|
container:
|
||||||
# Specifies the network to which the container will connect.
|
# Specifies the network to which the container will connect.
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ type Cache struct {
|
|||||||
Port uint16 `yaml:"port"` // Port specifies the caching port.
|
Port uint16 `yaml:"port"` // Port specifies the caching port.
|
||||||
ExternalServer string `yaml:"external_server"` // ExternalServer specifies the URL of external cache server
|
ExternalServer string `yaml:"external_server"` // ExternalServer specifies the URL of external cache server
|
||||||
ExternalSecret string `yaml:"external_secret"` // ExternalSecret is a shared secret between this runner and an external gitea-runner cache-server, enabling per-job ACTIONS_RUNTIME_TOKEN authentication and repo scoping over the network. Leave empty to keep the legacy unauthenticated behavior.
|
ExternalSecret string `yaml:"external_secret"` // ExternalSecret is a shared secret between this runner and an external gitea-runner cache-server, enabling per-job ACTIONS_RUNTIME_TOKEN authentication and repo scoping over the network. Leave empty to keep the legacy unauthenticated behavior.
|
||||||
|
OfflineMode bool `yaml:"offline_mode"` // OfflineMode reuses a cached action without fetching from the remote; a moved tag or branch stays at the cached commit until the cache entry is removed.
|
||||||
}
|
}
|
||||||
|
|
||||||
// Container represents the configuration for the container.
|
// Container represents the configuration for the container.
|
||||||
@@ -109,7 +110,6 @@ func LoadDefault(file string) (*Config, error) {
|
|||||||
return nil, fmt.Errorf("parse config file %q for defaults metadata: %w", file, err)
|
return nil, fmt.Errorf("parse config file %q for defaults metadata: %w", file, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
compatibleWithOldEnvs(file != "", cfg)
|
|
||||||
|
|
||||||
if cfg.Runner.EnvFile != "" {
|
if cfg.Runner.EnvFile != "" {
|
||||||
if stat, err := os.Stat(cfg.Runner.EnvFile); err == nil && !stat.IsDir() {
|
if stat, err := os.Stat(cfg.Runner.EnvFile); err == nil && !stat.IsDir() {
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
// Copyright 2023 The Gitea Authors. All rights reserved.
|
|
||||||
// SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Deprecated: could be removed in the future. TODO: remove it when Gitea 1.20.0 is released.
|
|
||||||
// Be compatible with old envs.
|
|
||||||
func compatibleWithOldEnvs(fileUsed bool, cfg *Config) {
|
|
||||||
handleEnv := func(key string) (string, bool) {
|
|
||||||
if v, ok := os.LookupEnv(key); ok {
|
|
||||||
if fileUsed {
|
|
||||||
log.Warnf("env %s has been ignored because config file is used", key)
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
log.Warnf("env %s will be deprecated, please use config file instead", key)
|
|
||||||
return v, true
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
if v, ok := handleEnv("GITEA_DEBUG"); ok {
|
|
||||||
if b, _ := strconv.ParseBool(v); b {
|
|
||||||
cfg.Log.Level = "debug"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if v, ok := handleEnv("GITEA_TRACE"); ok {
|
|
||||||
if b, _ := strconv.ParseBool(v); b {
|
|
||||||
cfg.Log.Level = "trace"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if v, ok := handleEnv("GITEA_RUNNER_CAPACITY"); ok {
|
|
||||||
if i, _ := strconv.Atoi(v); i > 0 {
|
|
||||||
cfg.Runner.Capacity = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if v, ok := handleEnv("GITEA_RUNNER_FILE"); ok {
|
|
||||||
cfg.Runner.File = v
|
|
||||||
}
|
|
||||||
if v, ok := handleEnv("GITEA_RUNNER_ENVIRON"); ok {
|
|
||||||
splits := strings.Split(v, ",")
|
|
||||||
if cfg.Runner.Envs == nil {
|
|
||||||
cfg.Runner.Envs = map[string]string{}
|
|
||||||
}
|
|
||||||
for _, split := range splits {
|
|
||||||
kv := strings.SplitN(split, ":", 2)
|
|
||||||
if len(kv) == 2 && kv[0] != "" {
|
|
||||||
cfg.Runner.Envs[kv[0]] = kv[1]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if v, ok := handleEnv("GITEA_RUNNER_ENV_FILE"); ok {
|
|
||||||
cfg.Runner.EnvFile = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -205,7 +205,7 @@ func (r *Reporter) Fire(entry *log.Entry) error {
|
|||||||
urgentState = true
|
urgentState = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !r.duringSteps() {
|
if r.shouldAppendLogRow(entry) {
|
||||||
r.logRows = appendIfNotNil(r.logRows, r.parseLogRow(entry))
|
r.logRows = appendIfNotNil(r.logRows, r.parseLogRow(entry))
|
||||||
}
|
}
|
||||||
r.unlockAndNotify(urgentState)
|
r.unlockAndNotify(urgentState)
|
||||||
@@ -219,7 +219,7 @@ func (r *Reporter) Fire(entry *log.Entry) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if step == nil {
|
if step == nil {
|
||||||
if !r.duringSteps() {
|
if r.shouldAppendLogRow(entry) {
|
||||||
r.logRows = appendIfNotNil(r.logRows, r.parseLogRow(entry))
|
r.logRows = appendIfNotNil(r.logRows, r.parseLogRow(entry))
|
||||||
}
|
}
|
||||||
r.unlockAndNotify(false)
|
r.unlockAndNotify(false)
|
||||||
@@ -246,7 +246,7 @@ func (r *Reporter) Fire(entry *log.Entry) error {
|
|||||||
r.logRows = append(r.logRows, row)
|
r.logRows = append(r.logRows, row)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if !r.duringSteps() {
|
} else if r.shouldAppendLogRow(entry) {
|
||||||
r.logRows = appendIfNotNil(r.logRows, r.parseLogRow(entry))
|
r.logRows = appendIfNotNil(r.logRows, r.parseLogRow(entry))
|
||||||
}
|
}
|
||||||
if v, ok := entry.Data["stepResult"]; ok && isJobStepEntry(entry) {
|
if v, ok := entry.Data["stepResult"]; ok && isJobStepEntry(entry) {
|
||||||
@@ -576,6 +576,13 @@ func (r *Reporter) duringSteps() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// shouldAppendLogRow reports whether a non-raw_output entry should be written
|
||||||
|
// to the job log: only when we are between steps and the entry's level is
|
||||||
|
// within the globally configured log level.
|
||||||
|
func (r *Reporter) shouldAppendLogRow(entry *log.Entry) bool {
|
||||||
|
return !r.duringSteps() && entry.Level <= log.GetLevel()
|
||||||
|
}
|
||||||
|
|
||||||
var stringToResult = map[string]runnerv1.Result{
|
var stringToResult = map[string]runnerv1.Result{
|
||||||
"success": runnerv1.Result_RESULT_SUCCESS,
|
"success": runnerv1.Result_RESULT_SUCCESS,
|
||||||
"failure": runnerv1.Result_RESULT_FAILURE,
|
"failure": runnerv1.Result_RESULT_FAILURE,
|
||||||
@@ -639,7 +646,7 @@ func (r *Reporter) handleCommand(originalContent, command, value string) *string
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reporter) parseLogRow(entry *log.Entry) *runnerv1.LogRow {
|
func (r *Reporter) parseLogRow(entry *log.Entry) *runnerv1.LogRow {
|
||||||
content := strings.TrimRightFunc(entry.Message, func(r rune) bool { return r == '\r' || r == '\n' })
|
content := strings.TrimRight(entry.Message, "\r\n")
|
||||||
|
|
||||||
matches := cmdRegex.FindStringSubmatch(content)
|
matches := cmdRegex.FindStringSubmatch(content)
|
||||||
if matches != nil {
|
if matches != nil {
|
||||||
|
|||||||
@@ -219,6 +219,59 @@ func TestReporter_Fire(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReporter_LogLevelFiltering(t *testing.T) {
|
||||||
|
// Set global level to Info so Debug entries should be filtered.
|
||||||
|
origLevel := log.GetLevel()
|
||||||
|
log.SetLevel(log.InfoLevel)
|
||||||
|
defer log.SetLevel(origLevel)
|
||||||
|
|
||||||
|
client := mocks.NewClient(t)
|
||||||
|
client.On("UpdateLog", mock.Anything, mock.Anything).Return(func(_ context.Context, req *connect_go.Request[runnerv1.UpdateLogRequest]) (*connect_go.Response[runnerv1.UpdateLogResponse], error) {
|
||||||
|
return connect_go.NewResponse(&runnerv1.UpdateLogResponse{
|
||||||
|
AckIndex: req.Msg.Index + int64(len(req.Msg.Rows)),
|
||||||
|
}), nil
|
||||||
|
})
|
||||||
|
client.On("UpdateTask", mock.Anything, mock.Anything).Return(func(_ context.Context, req *connect_go.Request[runnerv1.UpdateTaskRequest]) (*connect_go.Response[runnerv1.UpdateTaskResponse], error) {
|
||||||
|
return connect_go.NewResponse(&runnerv1.UpdateTaskResponse{}), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
taskCtx, err := structpb.NewStruct(map[string]any{})
|
||||||
|
require.NoError(t, err)
|
||||||
|
cfg, _ := config.LoadDefault("")
|
||||||
|
reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: taskCtx}, cfg)
|
||||||
|
reporter.RunDaemon()
|
||||||
|
defer func() {
|
||||||
|
require.NoError(t, reporter.Close(""))
|
||||||
|
}()
|
||||||
|
reporter.ResetSteps(2)
|
||||||
|
|
||||||
|
dataStep0 := log.Fields{"stage": "Main", "stepNumber": 0, "raw_output": true}
|
||||||
|
dataStep0Internal := log.Fields{"stage": "Main", "stepNumber": 0}
|
||||||
|
|
||||||
|
// raw_output entries always appear in job log regardless of level.
|
||||||
|
require.NoError(t, reporter.Fire(&log.Entry{Message: "step output", Data: dataStep0, Level: log.InfoLevel}))
|
||||||
|
require.NoError(t, reporter.Fire(&log.Entry{Message: "step debug output", Data: dataStep0, Level: log.DebugLevel}))
|
||||||
|
assert.Equal(t, int64(2), reporter.state.Steps[0].LogLength, "raw_output entries must always be forwarded")
|
||||||
|
|
||||||
|
// Non-raw_output entries during steps are not added to logRows regardless of level.
|
||||||
|
require.NoError(t, reporter.Fire(&log.Entry{Message: "internal info", Data: dataStep0Internal, Level: log.InfoLevel}))
|
||||||
|
require.NoError(t, reporter.Fire(&log.Entry{Message: "internal debug", Data: dataStep0Internal, Level: log.DebugLevel}))
|
||||||
|
|
||||||
|
// stepResult at DebugLevel (skipped step) must still update state even when filtered from log.
|
||||||
|
require.NoError(t, reporter.Fire(&log.Entry{
|
||||||
|
Message: "Skipping step",
|
||||||
|
Data: log.Fields{
|
||||||
|
"stage": "Main",
|
||||||
|
"stepNumber": 1,
|
||||||
|
"stepResult": "skipped",
|
||||||
|
},
|
||||||
|
Level: log.DebugLevel,
|
||||||
|
}))
|
||||||
|
assert.Equal(t, runnerv1.Result_RESULT_SKIPPED, reporter.state.Steps[1].Result,
|
||||||
|
"stepResult at DebugLevel must update step state even when log entry is filtered from job log output")
|
||||||
|
}
|
||||||
|
|
||||||
// TestReporter_EphemeralRunnerDeletion reproduces the exact scenario from
|
// TestReporter_EphemeralRunnerDeletion reproduces the exact scenario from
|
||||||
// https://gitea.com/gitea/runner/issues/793:
|
// https://gitea.com/gitea/runner/issues/793:
|
||||||
//
|
//
|
||||||
|
|||||||
19
tools/lint-pr-title.ts
Normal file
19
tools/lint-pr-title.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import {env, exit} from 'node:process';
|
||||||
|
|
||||||
|
const allowedTypes = 'build, chore, ci, docs, enhance, feat, fix, perf, refactor, revert, style, test';
|
||||||
|
const title = env.PR_TITLE;
|
||||||
|
|
||||||
|
if (!title) {
|
||||||
|
console.error('Missing PR_TITLE');
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const validTitlePattern = new RegExp(`^(${allowedTypes.replaceAll(', ', '|')})(\\([\\w.-]+\\))?(!)?: .+$`);
|
||||||
|
|
||||||
|
if (!validTitlePattern.test(title)) {
|
||||||
|
console.error(`Invalid PR title: ${title}`);
|
||||||
|
console.error('Expected format: type(scope): subject');
|
||||||
|
console.error(`Allowed types: ${allowedTypes}`);
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user