core(deps): bump golang-cilint to v2.0.2 (#83)

This commit is contained in:
ChristopherHX
2025-04-25 21:58:30 +02:00
committed by GitHub
parent 4be22e9b76
commit fba76f10dd
38 changed files with 184 additions and 174 deletions

View File

@@ -1,9 +1,9 @@
FROM alpine:3.17 FROM alpine:3.21
ARG CHOCOVERSION=1.1.0 ARG CHOCOVERSION=1.1.0
RUN apk add --no-cache bash ca-certificates git \ RUN apk add --no-cache bash ca-certificates git \
&& apk --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/edge/testing add mono mono-dev \ && apk --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/edge/community add mono mono-dev \
&& cert-sync /etc/ssl/certs/ca-certificates.crt \ && cert-sync /etc/ssl/certs/ca-certificates.crt \
&& wget "https://github.com/chocolatey/choco/archive/${CHOCOVERSION}.tar.gz" -O- | tar -xzf - \ && wget "https://github.com/chocolatey/choco/archive/${CHOCOVERSION}.tar.gz" -O- | tar -xzf - \
&& cd choco-"${CHOCOVERSION}" \ && cd choco-"${CHOCOVERSION}" \

View File

@@ -22,9 +22,9 @@ jobs:
with: with:
go-version-file: go.mod go-version-file: go.mod
check-latest: true check-latest: true
- uses: golangci/golangci-lint-action@v6.5.0 - uses: golangci/golangci-lint-action@v7.0.0
with: with:
version: v1.64.8 version: v2.0.2
- uses: megalinter/megalinter/flavors/go@v8.4.2 - uses: megalinter/megalinter/flavors/go@v8.4.2
env: env:
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}

View File

@@ -1,56 +1,65 @@
# Minimum golangci-lint version required: v1.46.0 version: "2"
run:
timeout: 3m
issues:
exclude-dirs:
- report # megalinter results+fixes
max-issues-per-linter: 0
max-same-issues: 0
linters-settings:
gocyclo:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 20
gocritic:
disabled-checks:
- ifElseChain
importas:
alias:
- pkg: 'github.com/sirupsen/logrus'
alias: log
- pkg: 'github.com/stretchr/testify/assert'
alias: assert
depguard:
rules:
main:
deny:
- pkg: github.com/pkg/errors
desc: Please use "errors" package from standard library
- pkg: gotest.tools/v3
desc: Please keep tests unified using only github.com/stretchr/testify
- pkg: log
desc: Please keep logging unified using only github.com/sirupsen/logrus
linters: linters:
enable: enable:
- gosimple - contextcheck
- staticcheck - copyloopvar
- unused - depguard
- govet - dupl
- revive - gocritic
- gocyclo - gocyclo
- gosec - gosec
- unconvert
- dupl
- nakedret
- prealloc
- copyloopvar
- gocritic
- goimports
- whitespace
- misspell
- depguard
- importas - importas
- contextcheck - misspell
- nakedret
- nolintlint - nolintlint
- prealloc
- revive - revive
- unconvert
- whitespace
settings:
depguard:
rules:
main:
deny:
- pkg: github.com/pkg/errors
desc: Please use "errors" package from standard library
- pkg: gotest.tools/v3
desc: Please keep tests unified using only github.com/stretchr/testify
- pkg: log
desc: Please keep logging unified using only github.com/sirupsen/logrus
gocritic:
disabled-checks:
- ifElseChain
gocyclo:
min-complexity: 20
importas:
alias:
- pkg: github.com/sirupsen/logrus
alias: log
- pkg: github.com/stretchr/testify/assert
alias: assert
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
paths:
- report
- third_party$
- builtin$
- examples$
issues:
max-issues-per-linter: 0
max-same-issues: 0
formatters:
enable:
- goimports
exclusions:
generated: lax
paths:
- report
- third_party$
- builtin$
- examples$

View File

@@ -33,13 +33,13 @@ func testMain(args []string) (exitCode int) {
func TestMainHelp(t *testing.T) { func TestMainHelp(t *testing.T) {
exitCode := testMain([]string{"cmd", "--help"}) exitCode := testMain([]string{"cmd", "--help"})
if exitCode != 0 { if exitCode != 0 {
t.Errorf("Expected exit code 0, got %d", exitCode) t.Errorf("expected exit code 0, got %d", exitCode)
} }
} }
func TestMainNoArgsError(t *testing.T) { func TestMainNoArgsError(t *testing.T) {
exitCode := testMain([]string{"cmd"}) exitCode := testMain([]string{"cmd"})
if exitCode != 1 { if exitCode != 1 {
t.Errorf("Expected exit code 1, got %d", exitCode) t.Errorf("expected exit code 1, got %d", exitCode)
} }
} }

View File

@@ -280,7 +280,7 @@ func readArgsFile(file string, split bool) []string {
defer func() { defer func() {
err := f.Close() err := f.Close()
if err != nil { if err != nil {
log.Errorf("Failed to close args file: %v", err) log.Errorf("failed to close args file: %v", err)
} }
}() }()
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
@@ -555,7 +555,7 @@ func newRunCommand(ctx context.Context, input *Input) func(*cobra.Command, []str
} }
if plan != nil { if plan != nil {
if len(plan.Stages) == 0 { if len(plan.Stages) == 0 {
plannerErr = fmt.Errorf("Could not find any stages to run. View the valid jobs with `act --list`. Use `act --help` to find how to filter by Job ID/Workflow/Event Name") plannerErr = fmt.Errorf("could not find any stages to run. View the valid jobs with `act --list`. Use `act --help` to find how to filter by Job ID/Workflow/Event Name")
} }
} }
if plan == nil && plannerErr != nil { if plan == nil && plannerErr != nil {

View File

@@ -17,7 +17,7 @@ func newSecrets(secretList []string) secrets {
secretPairParts := strings.SplitN(secretPair, "=", 2) secretPairParts := strings.SplitN(secretPair, "=", 2)
secretPairParts[0] = strings.ToUpper(secretPairParts[0]) secretPairParts[0] = strings.ToUpper(secretPairParts[0])
if strings.ToUpper(s[secretPairParts[0]]) == secretPairParts[0] { if strings.ToUpper(s[secretPairParts[0]]) == secretPairParts[0] {
log.Errorf("Secret %s is already defined (secrets are case insensitive)", secretPairParts[0]) log.Errorf("secret %s is already defined (secrets are case insensitive)", secretPairParts[0])
} }
if len(secretPairParts) == 2 { if len(secretPairParts) == 2 {
s[secretPairParts[0]] = secretPairParts[1] s[secretPairParts[0]] = secretPairParts[1]

View File

@@ -203,7 +203,7 @@ func (r artifactV4Routes) buildSignature(endp, expires, artifactName string, tas
mac.Write([]byte(endp)) mac.Write([]byte(endp))
mac.Write([]byte(expires)) mac.Write([]byte(expires))
mac.Write([]byte(artifactName)) mac.Write([]byte(artifactName))
mac.Write([]byte(fmt.Sprint(taskID))) fmt.Fprint(mac, taskID)
return mac.Sum(nil) return mac.Sum(nil)
} }
@@ -240,13 +240,13 @@ func (r artifactV4Routes) verifySignature(ctx *ArtifactContext, endp string) (in
func (r *artifactV4Routes) parseProtbufBody(ctx *ArtifactContext, req protoreflect.ProtoMessage) bool { func (r *artifactV4Routes) parseProtbufBody(ctx *ArtifactContext, req protoreflect.ProtoMessage) bool {
body, err := io.ReadAll(ctx.Req.Body) body, err := io.ReadAll(ctx.Req.Body)
if err != nil { if err != nil {
log.Errorf("Error decode request body: %v", err) log.Errorf("error decode request body: %v", err)
ctx.Error(http.StatusInternalServerError, "Error decode request body") ctx.Error(http.StatusInternalServerError, "Error decode request body")
return false return false
} }
err = protojson.Unmarshal(body, req) err = protojson.Unmarshal(body, req)
if err != nil { if err != nil {
log.Errorf("Error decode request body: %v", err) log.Errorf("error decode request body: %v", err)
ctx.Error(http.StatusInternalServerError, "Error decode request body") ctx.Error(http.StatusInternalServerError, "Error decode request body")
return false return false
} }
@@ -256,7 +256,7 @@ func (r *artifactV4Routes) parseProtbufBody(ctx *ArtifactContext, req protorefle
func (r *artifactV4Routes) sendProtbufBody(ctx *ArtifactContext, req protoreflect.ProtoMessage) { func (r *artifactV4Routes) sendProtbufBody(ctx *ArtifactContext, req protoreflect.ProtoMessage) {
resp, err := protojson.Marshal(req) resp, err := protojson.Marshal(req)
if err != nil { if err != nil {
log.Errorf("Error encode response body: %v", err) log.Errorf("error encode response body: %v", err)
ctx.Error(http.StatusInternalServerError, "Error encode response body") ctx.Error(http.StatusInternalServerError, "Error encode response body")
return return
} }
@@ -318,11 +318,11 @@ func (r *artifactV4Routes) uploadArtifact(ctx *ArtifactContext) {
writer, ok := file.(io.Writer) writer, ok := file.(io.Writer)
if !ok { if !ok {
panic(errors.New("File is not writable")) panic(errors.New("file is not writable"))
} }
if ctx.Req.Body == nil { if ctx.Req.Body == nil {
panic(errors.New("No body given")) panic(errors.New("no body given"))
} }
_, err = io.Copy(writer, ctx.Req.Body) _, err = io.Copy(writer, ctx.Req.Body)

View File

@@ -135,11 +135,11 @@ func uploads(router *httprouter.Router, baseDir string, fsys WriteFS) {
writer, ok := file.(io.Writer) writer, ok := file.(io.Writer)
if !ok { if !ok {
panic(errors.New("File is not writable")) panic(errors.New("file is not writable"))
} }
if req.Body == nil { if req.Body == nil {
panic(errors.New("No body given")) panic(errors.New("no body given"))
} }
_, err = io.Copy(writer, req.Body) _, err = io.Copy(writer, req.Body)
@@ -310,7 +310,7 @@ func Serve(ctx context.Context, artifactPath string, addr string, port string) c
<-serverContext.Done() <-serverContext.Done()
if err := server.Shutdown(ctx); err != nil { if err := server.Shutdown(ctx); err != nil {
logger.Errorf("Failed shutdown gracefully - force shutdown: %v", err) logger.Errorf("failed shutdown gracefully - force shutdown: %v", err)
server.Close() server.Close()
} }
}() }()

View File

@@ -227,7 +227,7 @@ func (e Executor) Finally(finally Executor) Executor {
defer func() { defer func() {
err2 := finally(ctx) err2 := finally(ctx)
if err2 != nil { if err2 != nil {
err = fmt.Errorf("Error occurred running finally: %v (original error: %v)", err2, err) err = fmt.Errorf("error occurred running finally: %v (original error: %v)", err2, err)
} }
}() }()
err = e(ctx) err = e(ctx)

View File

@@ -74,7 +74,7 @@ func FindGitRevision(ctx context.Context, file string) (shortSha string, sha str
} }
if head.Hash().IsZero() { if head.Hash().IsZero() {
return "", "", fmt.Errorf("HEAD sha1 could not be resolved") return "", "", fmt.Errorf("head sha1 could not be resolved")
} }
hash := head.Hash().String() hash := head.Hash().String()
@@ -261,7 +261,7 @@ func CloneIfRequired(ctx context.Context, refName plumbing.ReferenceName, input
} else if lgr, ok := logger.(*log.Logger); ok { } else if lgr, ok := logger.(*log.Logger); ok {
progressWriter = lgr.WriterLevel(log.DebugLevel) progressWriter = lgr.WriterLevel(log.DebugLevel)
} else { } else {
log.Errorf("Unable to get writer from logger (type=%T)", logger) log.Errorf("unable to get writer from logger (type=%T)", logger)
progressWriter = os.Stdout progressWriter = os.Stdout
} }
} }
@@ -279,7 +279,7 @@ 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, err
} }
@@ -340,7 +340,7 @@ 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 {
logger.Errorf("Unable to resolve %s: %v", input.Ref, err) logger.Errorf("unable to resolve %s: %v", input.Ref, err)
} }
if hash.String() != input.Ref && len(input.Ref) >= 4 && strings.HasPrefix(hash.String(), input.Ref) { if hash.String() != input.Ref && len(input.Ref) >= 4 && strings.HasPrefix(hash.String(), input.Ref) {
@@ -369,7 +369,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
} }
if hash, err = r.ResolveRevision(rev); err != nil { if hash, err = r.ResolveRevision(rev); err != nil {
logger.Errorf("Unable to resolve %s: %v", input.Ref, err) logger.Errorf("unable to resolve %s: %v", input.Ref, err)
return err return err
} }
@@ -390,7 +390,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
Branch: sourceRef, Branch: sourceRef,
Force: true, Force: true,
}); err != nil { }); err != nil {
logger.Errorf("Unable to checkout %s: %v", sourceRef, err) logger.Errorf("unable to checkout %s: %v", sourceRef, err)
return err return err
} }
} }
@@ -404,7 +404,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
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")
if hash, err = r.ResolveRevision(rev); err != nil { if hash, err = r.ResolveRevision(rev); err != nil {
logger.Errorf("Unable to resolve %s: %v", input.Ref, err) logger.Errorf("unable to resolve %s: %v", input.Ref, err)
return err return err
} }
} }
@@ -412,7 +412,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
Hash: *hash, Hash: *hash,
Force: true, Force: true,
}); err != nil { }); err != nil {
logger.Errorf("Unable to checkout %s: %v", *hash, err) logger.Errorf("unable to checkout %s: %v", *hash, err)
return err return err
} }
@@ -420,7 +420,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
Mode: git.HardReset, Mode: git.HardReset,
Commit: *hash, Commit: *hash,
}); err != nil { }); err != nil {
logger.Errorf("Unable to reset to %s: %v", hash.String(), err) logger.Errorf("unable to reset to %s: %v", hash.String(), err)
return err return err
} }

View File

@@ -241,7 +241,7 @@ func gitCmd(args ...string) error {
err := cmd.Run() err := cmd.Run()
if exitError, ok := err.(*exec.ExitError); ok { if exitError, ok := err.(*exec.ExitError); ok {
if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); ok { if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); ok {
return fmt.Errorf("Exit error %d", waitStatus.ExitStatus()) return fmt.Errorf("exit error %d", waitStatus.ExitStatus())
} }
return exitError return exitError
} }

View File

@@ -679,7 +679,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con
} }
if copts.autoRemove && !hostConfig.RestartPolicy.IsNone() { if copts.autoRemove && !hostConfig.RestartPolicy.IsNone() {
return nil, errors.Errorf("Conflicting options: --restart and --rm") return nil, errors.Errorf("conflicting options: --restart and --rm")
} }
// only set this value if the user provided the flag, else it should default to nil // only set this value if the user provided the flag, else it should default to nil
@@ -868,7 +868,7 @@ func parseSecurityOpts(securityOpts []string) ([]string, error) {
if strings.Contains(opt, ":") { if strings.Contains(opt, ":") {
con = strings.SplitN(opt, ":", 2) con = strings.SplitN(opt, ":", 2)
} else { } else {
return securityOpts, errors.Errorf("Invalid --security-opt: %q", opt) return securityOpts, errors.Errorf("invalid --security-opt: %q", opt)
} }
} }
if con[0] == "seccomp" && con[1] != "unconfined" { if con[0] == "seccomp" && con[1] != "unconfined" {

View File

@@ -693,7 +693,7 @@ func TestParseRestartPolicy(t *testing.T) {
} }
func TestParseRestartPolicyAutoRemove(t *testing.T) { func TestParseRestartPolicyAutoRemove(t *testing.T) {
expected := "Conflicting options: --restart and --rm" expected := "conflicting options: --restart and --rm"
_, _, _, err := parseRun([]string{"--rm", "--restart=always", "img", "cmd"}) //nolint:dogsled _, _, _, err := parseRun([]string{"--rm", "--restart=always", "img", "cmd"}) //nolint:dogsled
if err == nil || err.Error() != expected { if err == nil || err.Error() != expected {
t.Fatalf("Expected error %v, but got none", expected) t.Fatalf("Expected error %v, but got none", expected)

View File

@@ -137,7 +137,7 @@ func (cr *containerReference) CopyDir(destPath string, srcPath string, useGitIgn
func (cr *containerReference) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) { func (cr *containerReference) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
if common.Dryrun(ctx) { if common.Dryrun(ctx) {
return nil, fmt.Errorf("DRYRUN is not supported in GetContainerArchive") return nil, fmt.Errorf("dryrun is not supported in GetContainerArchive")
} }
a, _, err := cr.cli.CopyFromContainer(ctx, cr.id, srcPath) a, _, err := cr.cli.CopyFromContainer(ctx, cr.id, srcPath)
return a, err return a, err
@@ -363,30 +363,30 @@ func (cr *containerReference) mergeContainerConfigs(ctx context.Context, config
optionsArgs, err := shellquote.Split(input.Options) optionsArgs, err := shellquote.Split(input.Options)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Cannot split container options: '%s': '%w'", input.Options, err) return nil, nil, fmt.Errorf("cannot split container options: '%s': '%w'", input.Options, err)
} }
err = flags.Parse(optionsArgs) err = flags.Parse(optionsArgs)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Cannot parse container options: '%s': '%w'", input.Options, err) return nil, nil, fmt.Errorf("cannot parse container options: '%s': '%w'", input.Options, err)
} }
if len(copts.netMode.Value()) == 0 { if len(copts.netMode.Value()) == 0 {
if err = copts.netMode.Set(cr.input.NetworkMode); err != nil { if err = copts.netMode.Set(cr.input.NetworkMode); err != nil {
return nil, nil, fmt.Errorf("Cannot parse networkmode=%s. This is an internal error and should not happen: '%w'", cr.input.NetworkMode, err) return nil, nil, fmt.Errorf("cannot parse networkmode=%s. This is an internal error and should not happen: '%w'", cr.input.NetworkMode, err)
} }
} }
containerConfig, err := parse(flags, copts, runtime.GOOS) containerConfig, err := parse(flags, copts, runtime.GOOS)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Cannot process container options: '%s': '%w'", input.Options, err) return nil, nil, fmt.Errorf("cannot process container options: '%s': '%w'", input.Options, err)
} }
logger.Debugf("Custom container.Config from options ==> %+v", containerConfig.Config) logger.Debugf("Custom container.Config from options ==> %+v", containerConfig.Config)
err = mergo.Merge(config, containerConfig.Config, mergo.WithOverride) err = mergo.Merge(config, containerConfig.Config, mergo.WithOverride)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Cannot merge container.Config options: '%s': '%w'", input.Options, err) return nil, nil, fmt.Errorf("cannot merge container.Config options: '%s': '%w'", input.Options, err)
} }
logger.Debugf("Merged container.Config ==> %+v", config) logger.Debugf("Merged container.Config ==> %+v", config)
@@ -398,7 +398,7 @@ func (cr *containerReference) mergeContainerConfigs(ctx context.Context, config
mounts := hostConfig.Mounts mounts := hostConfig.Mounts
err = mergo.Merge(hostConfig, containerConfig.HostConfig, mergo.WithOverride) err = mergo.Merge(hostConfig, containerConfig.HostConfig, mergo.WithOverride)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Cannot merge container.HostConfig options: '%s': '%w'", input.Options, err) return nil, nil, fmt.Errorf("cannot merge container.HostConfig options: '%s': '%w'", input.Options, err)
} }
hostConfig.Binds = binds hostConfig.Binds = binds
hostConfig.Mounts = mounts hostConfig.Mounts = mounts

View File

@@ -200,7 +200,7 @@ func TestDockerCopyTarStreamErrorInCopyFiles(t *testing.T) {
conn := &mockConn{} conn := &mockConn{}
merr := fmt.Errorf("Failure") merr := fmt.Errorf("failure")
client := &mockDockerClient{} client := &mockDockerClient{}
client.On("CopyToContainer", ctx, "123", "/", mock.Anything, mock.AnythingOfType("container.CopyToContainerOptions")).Return(merr) client.On("CopyToContainer", ctx, "123", "/", mock.Anything, mock.AnythingOfType("container.CopyToContainerOptions")).Return(merr)
@@ -225,7 +225,7 @@ func TestDockerCopyTarStreamErrorInMkdir(t *testing.T) {
conn := &mockConn{} conn := &mockConn{}
merr := fmt.Errorf("Failure") merr := fmt.Errorf("failure")
client := &mockDockerClient{} client := &mockDockerClient{}
client.On("CopyToContainer", ctx, "123", "/", mock.Anything, mock.AnythingOfType("container.CopyToContainerOptions")).Return(nil) client.On("CopyToContainer", ctx, "123", "/", mock.Anything, mock.AnythingOfType("container.CopyToContainerOptions")).Return(nil)

View File

@@ -90,7 +90,7 @@ func GetSocketAndHost(containerSocket string) (SocketAndHost, error) {
if !hasDockerHost && socketHost.Socket != "" && !isDockerHostURI(socketHost.Socket) { if !hasDockerHost && socketHost.Socket != "" && !isDockerHostURI(socketHost.Socket) {
// Cases: 1B, 2B // Cases: 1B, 2B
// Should we early-exit here, since there is no host nor socket to talk to? // Should we early-exit here, since there is no host nor socket to talk to?
return SocketAndHost{}, fmt.Errorf("DOCKER_HOST was not set, couldn't be found in the usual locations, and the container daemon socket ('%s') is invalid", socketHost.Socket) return SocketAndHost{}, fmt.Errorf("docker host aka DOCKER_HOST was not set, couldn't be found in the usual locations, and the container daemon socket ('%s') is invalid", socketHost.Socket)
} }
// Default to DOCKER_HOST if set // Default to DOCKER_HOST if set

View File

@@ -83,7 +83,7 @@ func (e *HostEnvironment) CopyTarStream(ctx context.Context, destPath string, ta
continue continue
} }
if ctx.Err() != nil { if ctx.Err() != nil {
return fmt.Errorf("CopyTarStream has been cancelled") return fmt.Errorf("copyTarStream has been cancelled")
} }
if err := cp.WriteFile(ti.Name, ti.FileInfo(), ti.Linkname, tr); err != nil { if err := cp.WriteFile(ti.Name, ti.FileInfo(), ti.Linkname, tr); err != nil {
return err return err
@@ -405,12 +405,14 @@ func (e *HostEnvironment) GetActPath() string {
} }
func (*HostEnvironment) GetPathVariableName() string { func (*HostEnvironment) GetPathVariableName() string {
if runtime.GOOS == "plan9" { switch runtime.GOOS {
case "plan9":
return "path" return "path"
} else if runtime.GOOS == "windows" { case "windows":
return "Path" // Actually we need a case insensitive map return "Path" // Actually we need a case insensitive map
default:
return "PATH"
} }
return "PATH"
} }
func (e *HostEnvironment) DefaultPathVariable() string { func (e *HostEnvironment) DefaultPathVariable() string {

View File

@@ -94,13 +94,13 @@ func (impl *interperterImpl) format(str reflect.Value, replaceValue ...reflect.V
case '}': case '}':
index, err := strconv.ParseInt(replacementIndex, 10, 32) index, err := strconv.ParseInt(replacementIndex, 10, 32)
if err != nil { if err != nil {
return "", fmt.Errorf("The following format string is invalid: '%s'", input) return "", fmt.Errorf("the following format string is invalid: '%s'", input)
} }
replacementIndex = "" replacementIndex = ""
if len(replaceValue) <= int(index) { if len(replaceValue) <= int(index) {
return "", fmt.Errorf("The following format string references more arguments than were supplied: '%s'", input) return "", fmt.Errorf("the following format string references more arguments than were supplied: '%s'", input)
} }
output += impl.coerceToString(replaceValue[index]).String() output += impl.coerceToString(replaceValue[index]).String()
@@ -127,10 +127,10 @@ func (impl *interperterImpl) format(str reflect.Value, replaceValue ...reflect.V
if state != passThrough { if state != passThrough {
switch state { switch state {
case bracketOpen: case bracketOpen:
return "", fmt.Errorf("Unclosed brackets. The following format string is invalid: '%s'", input) return "", fmt.Errorf("unclosed brackets. The following format string is invalid: '%s'", input)
case bracketClose: case bracketClose:
return "", fmt.Errorf("Closing bracket without opening one. The following format string is invalid: '%s'", input) return "", fmt.Errorf("closing bracket without opening one. The following format string is invalid: '%s'", input)
} }
} }
@@ -159,7 +159,7 @@ func (impl *interperterImpl) toJSON(value reflect.Value) (string, error) {
json, err := json.MarshalIndent(value.Interface(), "", " ") json, err := json.MarshalIndent(value.Interface(), "", " ")
if err != nil { if err != nil {
return "", fmt.Errorf("Cannot convert value to JSON. Cause: %v", err) return "", fmt.Errorf("cannot convert value to JSON. Cause: %v", err)
} }
return string(json), nil return string(json), nil
@@ -167,14 +167,14 @@ func (impl *interperterImpl) toJSON(value reflect.Value) (string, error) {
func (impl *interperterImpl) fromJSON(value reflect.Value) (interface{}, error) { func (impl *interperterImpl) fromJSON(value reflect.Value) (interface{}, error) {
if value.Kind() != reflect.String { if value.Kind() != reflect.String {
return nil, fmt.Errorf("Cannot parse non-string type %v as JSON", value.Kind()) return nil, fmt.Errorf("cannot parse non-string type %v as JSON", value.Kind())
} }
var data interface{} var data interface{}
err := json.Unmarshal([]byte(value.String()), &data) err := json.Unmarshal([]byte(value.String()), &data)
if err != nil { if err != nil {
return nil, fmt.Errorf("Invalid JSON: %v", err) return nil, fmt.Errorf("invalid JSON: %v", err)
} }
return data, nil return data, nil
@@ -195,7 +195,7 @@ func (impl *interperterImpl) hashFiles(paths ...reflect.Value) (string, error) {
} }
ps = append(ps, gitignore.ParsePattern(cleanPath, nil)) ps = append(ps, gitignore.ParsePattern(cleanPath, nil))
} else { } else {
return "", fmt.Errorf("Non-string path passed to hashFiles") return "", fmt.Errorf("non-string path passed to hashFiles")
} }
} }
@@ -214,7 +214,7 @@ func (impl *interperterImpl) hashFiles(paths ...reflect.Value) (string, error) {
files = append(files, path) files = append(files, path)
return nil return nil
}); err != nil { }); err != nil {
return "", fmt.Errorf("Unable to filepath.Walk: %v", err) return "", fmt.Errorf("unable to filepath.Walk: %v", err)
} }
if len(files) == 0 { if len(files) == 0 {
@@ -226,15 +226,15 @@ func (impl *interperterImpl) hashFiles(paths ...reflect.Value) (string, error) {
for _, file := range files { for _, file := range files {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return "", fmt.Errorf("Unable to os.Open: %v", err) return "", fmt.Errorf("unable to os.Open: %v", err)
} }
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return "", fmt.Errorf("Unable to io.Copy: %v", err) return "", fmt.Errorf("unable to io.Copy: %v", err)
} }
if err := f.Close(); err != nil { if err := f.Close(); err != nil {
return "", fmt.Errorf("Unable to Close file: %v", err) return "", fmt.Errorf("unable to Close file: %v", err)
} }
} }

View File

@@ -233,10 +233,10 @@ func TestFunctionFormat(t *testing.T) {
{`format('Hello "{0}" {1} {2}', fromJSON('[0, true, "abc"]'), fromJSON('[{"a":1}]'), fromJSON('{"a":{"b":1}}'))`, `Hello "Array" Array Object`, nil, "format-with-complex-types"}, {`format('Hello "{0}" {1} {2}', fromJSON('[0, true, "abc"]'), fromJSON('[{"a":1}]'), fromJSON('{"a":{"b":1}}'))`, `Hello "Array" Array Object`, nil, "format-with-complex-types"},
{"format(true)", "true", nil, "format-with-primitive-args"}, {"format(true)", "true", nil, "format-with-primitive-args"},
{"format('echo Hello {0} ${{Test}}', github.undefined_property)", "echo Hello ${Test}", nil, "format-with-undefined-value"}, {"format('echo Hello {0} ${{Test}}', github.undefined_property)", "echo Hello ${Test}", nil, "format-with-undefined-value"},
{"format('{0}}', '{1}', 'World')", nil, "Closing bracket without opening one. The following format string is invalid: '{0}}'", "format-invalid-format-string"}, {"format('{0}}', '{1}', 'World')", nil, "closing bracket without opening one. The following format string is invalid: '{0}}'", "format-invalid-format-string"},
{"format('{0', '{1}', 'World')", nil, "Unclosed brackets. The following format string is invalid: '{0'", "format-invalid-format-string"}, {"format('{0', '{1}', 'World')", nil, "unclosed brackets. The following format string is invalid: '{0'", "format-invalid-format-string"},
{"format('{2}', '{1}', 'World')", "", "The following format string references more arguments than were supplied: '{2}'", "format-invalid-replacement-reference"}, {"format('{2}', '{1}', 'World')", "", "the following format string references more arguments than were supplied: '{2}'", "format-invalid-replacement-reference"},
{"format('{2147483648}')", "", "The following format string is invalid: '{2147483648}'", "format-invalid-replacement-reference"}, {"format('{2147483648}')", "", "the following format string is invalid: '{2147483648}'", "format-invalid-replacement-reference"},
{"format('{0} {1} {2} {3}', 1.0, 1.1, 1234567890.0, 12345678901234567890.0)", "1 1.1 1234567890 1.23456789012346E+19", nil, "format-floats"}, {"format('{0} {1} {2} {3}', 1.0, 1.1, 1234567890.0, 12345678901234567890.0)", "1 1.1 1234567890 1.23456789012346E+19", nil, "format-floats"},
} }

View File

@@ -86,7 +86,7 @@ func (impl *interperterImpl) Evaluate(input string, defaultStatusCheck DefaultSt
parser := actionlint.NewExprParser() parser := actionlint.NewExprParser()
exprNode, err := parser.Parse(actionlint.NewExprLexer(input + "}}")) exprNode, err := parser.Parse(actionlint.NewExprLexer(input + "}}"))
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to parse: %s", err.Message) return nil, fmt.Errorf("failed to parse: %s", err.Message)
} }
if defaultStatusCheck != DefaultStatusCheckNone { if defaultStatusCheck != DefaultStatusCheckNone {
@@ -146,7 +146,7 @@ func (impl *interperterImpl) evaluateNode(exprNode actionlint.ExprNode) (interfa
case *actionlint.FuncCallNode: case *actionlint.FuncCallNode:
return impl.evaluateFuncCall(node) return impl.evaluateFuncCall(node)
default: default:
return nil, fmt.Errorf("Fatal error! Unknown node type: %s node: %+v", reflect.TypeOf(exprNode), exprNode) return nil, fmt.Errorf("fatal error! Unknown node type: %s node: %+v", reflect.TypeOf(exprNode), exprNode)
} }
} }
@@ -160,7 +160,7 @@ func (impl *interperterImpl) evaluateVariable(variableNode *actionlint.VariableN
return impl.env.Job, nil return impl.env.Job, nil
case "jobs": case "jobs":
if impl.env.Jobs == nil { if impl.env.Jobs == nil {
return nil, fmt.Errorf("Unavailable context: jobs") return nil, fmt.Errorf("unavailable context: jobs")
} }
return impl.env.Jobs, nil return impl.env.Jobs, nil
case "steps": case "steps":
@@ -184,7 +184,7 @@ func (impl *interperterImpl) evaluateVariable(variableNode *actionlint.VariableN
case "nan": case "nan":
return math.NaN(), nil return math.NaN(), nil
default: default:
return nil, fmt.Errorf("Unavailable context: %s", variableNode.Name) return nil, fmt.Errorf("unavailable context: %s", variableNode.Name)
} }
} }
@@ -414,10 +414,10 @@ func (impl *interperterImpl) compareValues(leftValue reflect.Value, rightValue r
} }
// not possible situation - params are converted to the same type in code above // not possible situation - params are converted to the same type in code above
return nil, fmt.Errorf("Compare params of Invalid type: left: %+v, right: %+v", leftValue.Kind(), rightValue.Kind()) return nil, fmt.Errorf("compare params of Invalid type: left: %+v, right: %+v", leftValue.Kind(), rightValue.Kind())
default: default:
return nil, fmt.Errorf("Compare not implemented for types: left: %+v, right: %+v", leftValue.Kind(), rightValue.Kind()) return nil, fmt.Errorf("compare not implemented for types: left: %+v, right: %+v", leftValue.Kind(), rightValue.Kind())
} }
} }
@@ -505,7 +505,7 @@ func (impl *interperterImpl) compareString(left string, right string, kind actio
case actionlint.CompareOpNodeKindNotEq: case actionlint.CompareOpNodeKindNotEq:
return left != right, nil return left != right, nil
default: default:
return false, fmt.Errorf("TODO: not implemented to compare '%+v'", kind) return false, fmt.Errorf("todo: not implemented to compare '%+v'", kind)
} }
} }
@@ -524,7 +524,7 @@ func (impl *interperterImpl) compareNumber(left float64, right float64, kind act
case actionlint.CompareOpNodeKindNotEq: case actionlint.CompareOpNodeKindNotEq:
return left != right, nil return left != right, nil
default: default:
return false, fmt.Errorf("TODO: not implemented to compare '%+v'", kind) return false, fmt.Errorf("todo: not implemented to compare '%+v'", kind)
} }
} }
@@ -604,7 +604,7 @@ func (impl *interperterImpl) evaluateLogicalCompare(compareNode *actionlint.Logi
return impl.getSafeValue(rightValue), nil return impl.getSafeValue(rightValue), nil
} }
return nil, fmt.Errorf("Unable to compare incompatibles types '%s' and '%s'", leftValue.Kind(), rightValue.Kind()) return nil, fmt.Errorf("unable to compare incompatibles types '%s' and '%s'", leftValue.Kind(), rightValue.Kind())
} }
//nolint:gocyclo //nolint:gocyclo
@@ -652,7 +652,7 @@ func (impl *interperterImpl) evaluateFuncCall(funcCallNode *actionlint.FuncCallN
if impl.config.Context == "step" { if impl.config.Context == "step" {
return impl.stepSuccess() return impl.stepSuccess()
} }
return nil, fmt.Errorf("Context '%s' must be one of 'job' or 'step'", impl.config.Context) return nil, fmt.Errorf("context '%s' must be one of 'job' or 'step'", impl.config.Context)
case "failure": case "failure":
if impl.config.Context == "job" { if impl.config.Context == "job" {
return impl.jobFailure() return impl.jobFailure()
@@ -660,10 +660,10 @@ func (impl *interperterImpl) evaluateFuncCall(funcCallNode *actionlint.FuncCallN
if impl.config.Context == "step" { if impl.config.Context == "step" {
return impl.stepFailure() return impl.stepFailure()
} }
return nil, fmt.Errorf("Context '%s' must be one of 'job' or 'step'", impl.config.Context) return nil, fmt.Errorf("context '%s' must be one of 'job' or 'step'", impl.config.Context)
case "cancelled": case "cancelled":
return impl.cancelled() return impl.cancelled()
default: default:
return nil, fmt.Errorf("TODO: '%s' not implemented", funcCallNode.Callee) return nil, fmt.Errorf("todo: '%s' not implemented", funcCallNode.Callee)
} }
} }

View File

@@ -73,7 +73,7 @@ func TestOperators(t *testing.T) {
{"github.event.commits[0].author.username1 != github.event.commits[1].author.username", true, "property-comparison2", ""}, {"github.event.commits[0].author.username1 != github.event.commits[1].author.username", true, "property-comparison2", ""},
{"github.event.commits[0].author.username != github.event.commits[1].author.username1", true, "property-comparison3", ""}, {"github.event.commits[0].author.username != github.event.commits[1].author.username1", true, "property-comparison3", ""},
{"github.event.commits[0].author.username1 != github.event.commits[1].author.username2", true, "property-comparison4", ""}, {"github.event.commits[0].author.username1 != github.event.commits[1].author.username2", true, "property-comparison4", ""},
{"secrets != env", nil, "property-comparison5", "Compare not implemented for types: left: map, right: map"}, {"secrets != env", nil, "property-comparison5", "compare not implemented for types: left: map, right: map"},
} }
env := &EvaluationEnvironment{ env := &EvaluationEnvironment{

View File

@@ -57,7 +57,7 @@ func (mfs *memoryFs) Walk(root string, fn filepath.WalkFunc) error {
} }
func (mfs *memoryFs) OpenGitIndex(path string) (*index.Index, error) { func (mfs *memoryFs) OpenGitIndex(path string) (*index.Index, error) {
f, _ := mfs.Filesystem.Chroot(filepath.Join(path, ".git")) f, _ := mfs.Chroot(filepath.Join(path, ".git"))
storage := filesystem.NewStorage(f, cache.NewObjectLRUDefault()) storage := filesystem.NewStorage(f, cache.NewObjectLRUDefault())
i, err := storage.Index() i, err := storage.Index()
if err != nil { if err != nil {

View File

@@ -24,7 +24,7 @@ func (a *ActionRunsUsing) UnmarshalYAML(unmarshal func(interface{}) error) error
case ActionRunsUsingNode20, ActionRunsUsingNode16, ActionRunsUsingNode12, ActionRunsUsingDocker, ActionRunsUsingComposite: case ActionRunsUsingNode20, ActionRunsUsingNode16, ActionRunsUsingNode12, ActionRunsUsingDocker, ActionRunsUsingComposite:
*a = format *a = format
default: default:
return fmt.Errorf("The runs.using key in action.yml must be one of: %v, got %s", []string{ return fmt.Errorf("the runs.using key in action.yml must be one of: %v, got %s", []string{
ActionRunsUsingComposite, ActionRunsUsingComposite,
ActionRunsUsingDocker, ActionRunsUsingDocker,
ActionRunsUsingNode12, ActionRunsUsingNode12,

View File

@@ -74,7 +74,7 @@ func (w *Workflow) UnmarshalYAML(node *yaml.Node) error {
Definition: "workflow-root", Definition: "workflow-root",
Schema: schema.GetWorkflowSchema(), Schema: schema.GetWorkflowSchema(),
}).UnmarshalYAML(node); err != nil { }).UnmarshalYAML(node); err != nil {
return errors.Join(err, fmt.Errorf("Actions YAML Schema Validation Error detected:\nFor more information, see: https://actions-oss.github.io/act-docs/usage/schema.html")) return errors.Join(err, fmt.Errorf("actions YAML Schema Validation Error detected:\nFor more information, see: https://actions-oss.github.io/act-docs/usage/schema.html"))
} }
type WorkflowDefault Workflow type WorkflowDefault Workflow
return node.Decode((*WorkflowDefault)(w)) return node.Decode((*WorkflowDefault)(w))
@@ -88,7 +88,7 @@ func (w *WorkflowStrict) UnmarshalYAML(node *yaml.Node) error {
Definition: "workflow-root-strict", Definition: "workflow-root-strict",
Schema: schema.GetWorkflowSchema(), Schema: schema.GetWorkflowSchema(),
}).UnmarshalYAML(node); err != nil { }).UnmarshalYAML(node); err != nil {
return errors.Join(err, fmt.Errorf("Actions YAML Strict Schema Validation Error detected:\nFor more information, see: https://nektosact.com/usage/schema.html")) return errors.Join(err, fmt.Errorf("actions YAML Strict Schema Validation Error detected:\nFor more information, see: https://nektosact.com/usage/schema.html"))
} }
type WorkflowDefault Workflow type WorkflowDefault Workflow
return node.Decode((*WorkflowDefault)(w)) return node.Decode((*WorkflowDefault)(w))
@@ -235,7 +235,7 @@ func (s Strategy) GetMaxParallel() int {
if s.MaxParallelString != "" { if s.MaxParallelString != "" {
var err error var err error
if maxParallel, err = strconv.Atoi(s.MaxParallelString); err != nil { if maxParallel, err = strconv.Atoi(s.MaxParallelString); err != nil {
log.Errorf("Failed to parse 'max-parallel' option: %v", err) log.Errorf("failed to parse 'max-parallel' option: %v", err)
} }
} }
return maxParallel return maxParallel
@@ -249,7 +249,7 @@ func (s Strategy) GetFailFast() bool {
if s.FailFastString != "" { if s.FailFastString != "" {
var err error var err error
if failFast, err = strconv.ParseBool(s.FailFastString); err != nil { if failFast, err = strconv.ParseBool(s.FailFastString); err != nil {
log.Errorf("Failed to parse 'fail-fast' option: %v", err) log.Errorf("failed to parse 'fail-fast' option: %v", err)
} }
} }
return failFast return failFast

View File

@@ -190,7 +190,7 @@ func runActionImpl(step actionStep, actionDir string, remoteAction *remoteAction
return execAsComposite(step)(ctx) return execAsComposite(step)(ctx)
default: default:
return fmt.Errorf("The runs.using key must be one of: %v, got %s", []string{ return fmt.Errorf("the runs.using key must be one of: %v, got %s", []string{
model.ActionRunsUsingDocker, model.ActionRunsUsingDocker,
model.ActionRunsUsingNode12, model.ActionRunsUsingNode12,
model.ActionRunsUsingNode16, model.ActionRunsUsingNode16,

View File

@@ -44,11 +44,11 @@ func (c GoGitActionCache) Fetch(ctx context.Context, cacheDir, url, ref, token s
gogitrepo, err = git.PlainOpen(gitPath) gogitrepo, err = git.PlainOpen(gitPath)
} }
if err != nil { if err != nil {
return "", fmt.Errorf("GoGitActionCache failed to open bare git %s with ref %s at %s: %w", url, ref, gitPath, err) return "", fmt.Errorf("goGitActionCache failed to open bare git %s with ref %s at %s: %w", url, ref, gitPath, err)
} }
tmpBranch := make([]byte, 12) tmpBranch := make([]byte, 12)
if _, err := rand.Read(tmpBranch); err != nil { if _, err := rand.Read(tmpBranch); err != nil {
return "", fmt.Errorf("GoGitActionCache failed to generate random tmp branch %s with ref %s at %s: %w", url, ref, gitPath, err) return "", fmt.Errorf("goGitActionCache failed to generate random tmp branch %s with ref %s at %s: %w", url, ref, gitPath, err)
} }
branchName := hex.EncodeToString(tmpBranch) branchName := hex.EncodeToString(tmpBranch)
@@ -66,7 +66,7 @@ func (c GoGitActionCache) Fetch(ctx context.Context, cacheDir, url, ref, token s
}, },
}) })
if err != nil { if err != nil {
return "", fmt.Errorf("GoGitActionCache failed to create remote %s with ref %s at %s: %w", url, ref, gitPath, err) return "", fmt.Errorf("goGitActionCache failed to create remote %s with ref %s at %s: %w", url, ref, gitPath, err)
} }
defer func() { defer func() {
_ = gogitrepo.DeleteBranch(branchName) _ = gogitrepo.DeleteBranch(branchName)
@@ -79,11 +79,11 @@ func (c GoGitActionCache) Fetch(ctx context.Context, cacheDir, url, ref, token s
Force: true, Force: true,
Depth: 1, Depth: 1,
}); err != nil { }); err != nil {
return "", fmt.Errorf("GoGitActionCache failed to fetch %s with ref %s at %s: %w", url, ref, gitPath, err) return "", fmt.Errorf("goGitActionCache failed to fetch %s with ref %s at %s: %w", url, ref, gitPath, err)
} }
hash, err := gogitrepo.ResolveRevision(plumbing.Revision(branchName)) hash, err := gogitrepo.ResolveRevision(plumbing.Revision(branchName))
if err != nil { if err != nil {
return "", fmt.Errorf("GoGitActionCache failed to resolve sha %s with ref %s at %s: %w", url, ref, gitPath, err) return "", fmt.Errorf("goGitActionCache failed to resolve sha %s with ref %s at %s: %w", url, ref, gitPath, err)
} }
logger.Infof("GoGitActionCache fetch %s with ref %s at %s resolved to %s", url, ref, gitPath, hash.String()) logger.Infof("GoGitActionCache fetch %s with ref %s at %s resolved to %s", url, ref, gitPath, hash.String())
return hash.String(), nil return hash.String(), nil
@@ -132,23 +132,23 @@ func (c GoGitActionCache) GetTarArchive(ctx context.Context, cacheDir, sha, incl
gitPath := path.Join(c.Path, safeFilename(cacheDir)+".git") gitPath := path.Join(c.Path, safeFilename(cacheDir)+".git")
logger.Infof("GoGitActionCache get content %s with sha %s subpath %s at %s", cacheDir, sha, includePrefix, gitPath) logger.Infof("goGitActionCache get content %s with sha %s subpath %s at %s", cacheDir, sha, includePrefix, gitPath)
gogitrepo, err := git.PlainOpen(gitPath) gogitrepo, err := git.PlainOpen(gitPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("GoGitActionCache failed to open bare git %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err) return nil, fmt.Errorf("goGitActionCache failed to open bare git %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err)
} }
commit, err := gogitrepo.CommitObject(plumbing.NewHash(sha)) commit, err := gogitrepo.CommitObject(plumbing.NewHash(sha))
if err != nil { if err != nil {
return nil, fmt.Errorf("GoGitActionCache failed to get commit %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err) return nil, fmt.Errorf("goGitActionCache failed to get commit %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err)
} }
t, err := commit.Tree() t, err := commit.Tree()
if err != nil { if err != nil {
return nil, fmt.Errorf("GoGitActionCache failed to open git tree %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err) return nil, fmt.Errorf("goGitActionCache failed to open git tree %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err)
} }
files, err := commit.Files() files, err := commit.Files()
if err != nil { if err != nil {
return nil, fmt.Errorf("GoGitActionCache failed to list files %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err) return nil, fmt.Errorf("goGitActionCache failed to list files %s with sha %s subpath %s at %s: %w", cacheDir, sha, includePrefix, gitPath, err)
} }
rpipe, wpipe := io.Pipe() rpipe, wpipe := io.Pipe()
// Interrupt io.Copy using ctx // Interrupt io.Copy using ctx

View File

@@ -75,7 +75,7 @@ func (cm *containerMock) GetContainerArchive(ctx context.Context, srcPath string
} }
func (cm *containerMock) CopyTarStream(ctx context.Context, destPath string, tarStream io.Reader) error { func (cm *containerMock) CopyTarStream(ctx context.Context, destPath string, tarStream io.Reader) error {
args := cm.Mock.Called(ctx, destPath, tarStream) args := cm.Called(ctx, destPath, tarStream)
err, hasErr := args.Get(0).(error) err, hasErr := args.Get(0).(error)
if !hasErr { if !hasErr {
err = nil err = nil

View File

@@ -186,7 +186,7 @@ func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.
followSymlink = true followSymlink = true
continue continue
} }
return "", fmt.Errorf("Invalid glob option %s, available option: '--follow-symbolic-links'", s) return "", fmt.Errorf("invalid glob option %s, available option: '--follow-symbolic-links'", s)
} }
} }
patterns = append(patterns, s) patterns = append(patterns, s)
@@ -385,7 +385,7 @@ func (ee expressionEvaluator) Interpolate(ctx context.Context, in string) string
expr, _ := rewriteSubExpression(ctx, in, true) expr, _ := rewriteSubExpression(ctx, in, true)
evaluated, err := ee.evaluate(ctx, expr, exprparser.DefaultStatusCheckNone) evaluated, err := ee.evaluate(ctx, expr, exprparser.DefaultStatusCheckNone)
if err != nil { if err != nil {
common.Logger(ctx).Errorf("Unable to interpolate expression '%s': %s", expr, err) common.Logger(ctx).Errorf("unable to interpolate expression '%s': %s", expr, err)
return "" return ""
} }

View File

@@ -112,7 +112,7 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
logger := common.Logger(ctx) logger := common.Logger(ctx)
logger.Infof("Cleaning up container for job %s", rc.JobName) logger.Infof("Cleaning up container for job %s", rc.JobName)
if err = info.stopContainer()(ctx); err != nil { if err = info.stopContainer()(ctx); err != nil {
logger.Errorf("Error while stop job container: %v", err) logger.Errorf("error while stop job container: %v", err)
} }
} }
return err return err

View File

@@ -356,7 +356,7 @@ func (rc *RunContext) startJobContainer() common.Executor {
if len(rc.ServiceContainers) > 0 { if len(rc.ServiceContainers) > 0 {
logger.Infof("Cleaning up services for job %s", rc.JobName) logger.Infof("Cleaning up services for job %s", rc.JobName)
if err := rc.stopServiceContainers()(ctx); err != nil { if err := rc.stopServiceContainers()(ctx); err != nil {
logger.Errorf("Error while cleaning services: %v", err) logger.Errorf("error while cleaning services: %v", err)
} }
if createAndDeleteNetwork { if createAndDeleteNetwork {
// clean network if it has been created by act // clean network if it has been created by act
@@ -365,7 +365,7 @@ func (rc *RunContext) startJobContainer() common.Executor {
// so, we should remove the network at last. // so, we should remove the network at last.
logger.Infof("Cleaning up network for job %s, and network name is: %s", rc.JobName, networkName) logger.Infof("Cleaning up network for job %s, and network name is: %s", rc.JobName, networkName)
if err := container.NewDockerNetworkRemoveExecutor(networkName)(ctx); err != nil { if err := container.NewDockerNetworkRemoveExecutor(networkName)(ctx); err != nil {
logger.Errorf("Error while cleaning network: %v", err) logger.Errorf("error while cleaning network: %v", err)
} }
} }
} }
@@ -403,7 +403,7 @@ func (rc *RunContext) startJobContainer() common.Executor {
Options: rc.options(ctx), Options: rc.options(ctx),
}) })
if rc.JobContainer == nil { if rc.JobContainer == nil {
return errors.New("Failed to create job container") return errors.New("failed to create job container")
} }
return common.NewPipelineExecutor( return common.NewPipelineExecutor(
@@ -774,7 +774,7 @@ func (rc *RunContext) runsOnPlatformNames(ctx context.Context) []string {
} }
if err := rc.ExprEval.EvaluateYamlNode(ctx, &job.RawRunsOn); err != nil { if err := rc.ExprEval.EvaluateYamlNode(ctx, &job.RawRunsOn); err != nil {
common.Logger(ctx).Errorf("Error while evaluating runs-on: %v", err) common.Logger(ctx).Errorf("error while evaluating runs-on: %v", err)
return []string{} return []string{}
} }
@@ -950,7 +950,7 @@ func (rc *RunContext) getGithubContext(ctx context.Context) *model.GithubContext
if rc.EventJSON != "" { if rc.EventJSON != "" {
err := json.Unmarshal([]byte(rc.EventJSON), &ghc.Event) err := json.Unmarshal([]byte(rc.EventJSON), &ghc.Event)
if err != nil { if err != nil {
logger.Errorf("Unable to Unmarshal event '%s': %v", rc.EventJSON, err) logger.Errorf("unable to Unmarshal event '%s': %v", rc.EventJSON, err)
} }
} }

View File

@@ -11,6 +11,6 @@ import (
func (rc *RunContext) startTartEnvironment() common.Executor { func (rc *RunContext) startTartEnvironment() common.Executor {
return func(_ context.Context) error { return func(_ context.Context) error {
return fmt.Errorf("You need macOS for tart") return fmt.Errorf("you need macOS for tart")
} }
} }

View File

@@ -150,13 +150,13 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
strategyRc := runner.newRunContext(ctx, run, nil) strategyRc := runner.newRunContext(ctx, run, nil)
if err := strategyRc.NewExpressionEvaluator(ctx).EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil { if err := strategyRc.NewExpressionEvaluator(ctx).EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil {
log.Errorf("Error while evaluating matrix: %v", err) log.Errorf("error while evaluating matrix: %v", err)
} }
} }
var matrixes []map[string]interface{} var matrixes []map[string]interface{}
if m, err := job.GetMatrixes(); err != nil { if m, err := job.GetMatrixes(); err != nil {
log.Errorf("Error while get job's matrix: %v", err) log.Errorf("error while get job's matrix: %v", err)
} else { } else {
log.Debugf("Job Matrices: %v", m) log.Debugf("Job Matrices: %v", m)
log.Debugf("Runner Matrices: %v", runner.config.Matrix) log.Debugf("Runner Matrices: %v", runner.config.Matrix)
@@ -212,7 +212,7 @@ func handleFailure(plan *model.Plan) common.Executor {
for _, stage := range plan.Stages { for _, stage := range plan.Stages {
for _, run := range stage.Runs { for _, run := range stage.Runs {
if run.Job().Result == "failure" { if run.Job().Result == "failure" {
return fmt.Errorf("Job '%s' failed", run.String()) return fmt.Errorf("job '%s' failed", run.String())
} }
} }
} }

View File

@@ -15,7 +15,6 @@ import (
"testing" "testing"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
assert "github.com/stretchr/testify/assert" assert "github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@@ -364,8 +363,8 @@ type captureJobLoggerFactory struct {
buffer bytes.Buffer buffer bytes.Buffer
} }
func (factory *captureJobLoggerFactory) WithJobLogger() *logrus.Logger { func (factory *captureJobLoggerFactory) WithJobLogger() *log.Logger {
logger := logrus.New() logger := log.New()
logger.SetOutput(&factory.buffer) logger.SetOutput(&factory.buffer)
logger.SetLevel(log.TraceLevel) logger.SetLevel(log.TraceLevel)
logger.SetFormatter(&log.JSONFormatter{}) logger.SetFormatter(&log.JSONFormatter{})
@@ -397,7 +396,7 @@ func TestPullFailureIsJobFailure(t *testing.T) {
path.Clean(path.Join(workdir, "cache")), path.Clean(path.Join(workdir, "cache")),
} }
logger := logrus.New() logger := log.New()
logger.SetOutput(&factory.buffer) logger.SetOutput(&factory.buffer)
logger.SetLevel(log.TraceLevel) logger.SetLevel(log.TraceLevel)
logger.SetFormatter(&log.JSONFormatter{}) logger.SetFormatter(&log.JSONFormatter{})
@@ -467,7 +466,7 @@ func TestFetchFailureIsJobFailure(t *testing.T) {
} }
config.ActionCache = &mockCache{} config.ActionCache = &mockCache{}
logger := logrus.New() logger := log.New()
logger.SetOutput(&factory.buffer) logger.SetOutput(&factory.buffer)
logger.SetLevel(log.TraceLevel) logger.SetLevel(log.TraceLevel)
logger.SetFormatter(&log.JSONFormatter{}) logger.SetFormatter(&log.JSONFormatter{})

View File

@@ -38,7 +38,7 @@ func (sar *stepActionRemote) prepareActionExecutor() common.Executor {
sar.remoteAction = newRemoteAction(sar.Step.Uses) sar.remoteAction = newRemoteAction(sar.Step.Uses)
if sar.remoteAction == nil { if sar.remoteAction == nil {
return fmt.Errorf("Expected format {org}/{repo}[/path]@ref. Actual '%s' Input string was not in a correct format", sar.Step.Uses) return fmt.Errorf("expected format {org}/{repo}[/path]@ref. Actual '%s' Input string was not in a correct format", sar.Step.Uses)
} }
github := sar.getGithubContext(ctx) github := sar.getGithubContext(ctx)

View File

@@ -35,12 +35,12 @@ type TestRepositoryCache struct {
} }
func (l *TestRepositoryCache) Fetch(ctx context.Context, cacheDir, url, ref, token string) (string, error) { func (l *TestRepositoryCache) Fetch(ctx context.Context, cacheDir, url, ref, token string) (string, error) {
args := l.Mock.Called(ctx, cacheDir, url, ref, token) args := l.Called(ctx, cacheDir, url, ref, token)
return args.Get(0).(string), nil return args.Get(0).(string), nil
} }
func (l *TestRepositoryCache) GetTarArchive(ctx context.Context, cacheDir, sha, includePrefix string) (io.ReadCloser, error) { func (l *TestRepositoryCache) GetTarArchive(ctx context.Context, cacheDir, sha, includePrefix string) (io.ReadCloser, error) {
args := l.Mock.Called(ctx, cacheDir, sha, includePrefix) args := l.Called(ctx, cacheDir, sha, includePrefix)
return args.Get(0).(io.ReadCloser), nil return args.Get(0).(io.ReadCloser), nil
} }
@@ -204,7 +204,7 @@ func TestStepActionRemote(t *testing.T) {
sarm.AssertExpectations(t) sarm.AssertExpectations(t)
cm.AssertExpectations(t) cm.AssertExpectations(t)
cacheMock.Mock.AssertExpectations(t) cacheMock.AssertExpectations(t)
}) })
} }
} }
@@ -256,7 +256,7 @@ func TestStepActionRemotePre(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
sarm.AssertExpectations(t) sarm.AssertExpectations(t)
cacheMock.Mock.AssertExpectations(t) cacheMock.AssertExpectations(t)
}) })
} }
} }
@@ -309,7 +309,7 @@ func TestStepActionRemotePreThroughAction(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
sarm.AssertExpectations(t) sarm.AssertExpectations(t)
cacheMock.Mock.AssertExpectations(t) cacheMock.AssertExpectations(t)
}) })
} }
} }
@@ -363,7 +363,7 @@ func TestStepActionRemotePreThroughActionToken(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
sarm.AssertExpectations(t) sarm.AssertExpectations(t)
cacheMock.Mock.AssertExpectations(t) cacheMock.AssertExpectations(t)
}) })
} }
} }

View File

@@ -15,7 +15,7 @@ type stepFactoryImpl struct{}
func (sf *stepFactoryImpl) newStep(stepModel *model.Step, rc *RunContext) (step, error) { func (sf *stepFactoryImpl) newStep(stepModel *model.Step, rc *RunContext) (step, error) {
switch stepModel.Type() { switch stepModel.Type() {
case model.StepTypeInvalid: case model.StepTypeInvalid:
return nil, fmt.Errorf("Invalid run/uses syntax for job:%s step:%+v", rc.Run, stepModel) return nil, fmt.Errorf("invalid run/uses syntax for job:%s step:%+v", rc.Run, stepModel)
case model.StepTypeRun: case model.StepTypeRun:
return &stepRun{ return &stepRun{
Step: stepModel, Step: stepModel,
@@ -42,5 +42,5 @@ func (sf *stepFactoryImpl) newStep(stepModel *model.Step, rc *RunContext) (step,
}, nil }, nil
} }
return nil, fmt.Errorf("Unable to determine how to run job:%s step:%+v", rc.Run, stepModel) return nil, fmt.Errorf("unable to determine how to run job:%s step:%+v", rc.Run, stepModel)
} }

View File

@@ -142,15 +142,15 @@ func (s *Node) checkSingleExpression(exprNode actionlint.ExprNode) error {
for _, v := range *funcs { for _, v := range *funcs {
if strings.EqualFold(funcCallNode.Callee, v.name) { if strings.EqualFold(funcCallNode.Callee, v.name) {
if v.min > len(funcCallNode.Args) { if v.min > len(funcCallNode.Args) {
err = errors.Join(err, fmt.Errorf("Missing parameters for %s expected >= %v got %v", funcCallNode.Callee, v.min, len(funcCallNode.Args))) err = errors.Join(err, fmt.Errorf("missing parameters for %s expected >= %v got %v", funcCallNode.Callee, v.min, len(funcCallNode.Args)))
} }
if v.max < len(funcCallNode.Args) { if v.max < len(funcCallNode.Args) {
err = errors.Join(err, fmt.Errorf("Too many parameters for %s expected <= %v got %v", funcCallNode.Callee, v.max, len(funcCallNode.Args))) err = errors.Join(err, fmt.Errorf("too many parameters for %s expected <= %v got %v", funcCallNode.Callee, v.max, len(funcCallNode.Args)))
} }
return return
} }
} }
err = errors.Join(err, fmt.Errorf("Unknown Function Call %s", funcCallNode.Callee)) err = errors.Join(err, fmt.Errorf("unknown Function Call %s", funcCallNode.Callee))
} }
if varNode, ok := node.(*actionlint.VariableNode); entering && ok { if varNode, ok := node.(*actionlint.VariableNode); entering && ok {
for _, v := range s.Context { for _, v := range s.Context {
@@ -158,7 +158,7 @@ func (s *Node) checkSingleExpression(exprNode actionlint.ExprNode) error {
return return
} }
} }
err = errors.Join(err, fmt.Errorf("Unknown Variable Access %s", varNode.Name)) err = errors.Join(err, fmt.Errorf("unknown Variable Access %s", varNode.Name))
} }
}) })
return err return err

View File

@@ -126,11 +126,11 @@ func (e *Environment) Stop(ctx context.Context) error {
} }
if err := vm.Stop(ctx); err != nil { if err := vm.Stop(ctx); err != nil {
common.Logger(ctx).Errorf("Failed to stop VM: %v", err) common.Logger(ctx).Errorf("failed to stop VM: %v", err)
} }
if err := vm.Delete(ctx); err != nil { if err := vm.Delete(ctx); err != nil {
common.Logger(ctx).Error("Failed to delete VM: %v", err) common.Logger(ctx).Error("failed to delete VM: %v", err)
return err return err
} }