Skip to content

Commit

Permalink
feat: use logger from context wherever possible
Browse files Browse the repository at this point in the history
Co-authored-by: Markus Wolf <markus.wolf@new-work.se>
  • Loading branch information
2 people authored and github-actions committed May 23, 2022
1 parent 995c71a commit 334d36c
Show file tree
Hide file tree
Showing 29 changed files with 273 additions and 256 deletions.
10 changes: 5 additions & 5 deletions pkg/artifacts/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (

"github.com/julienschmidt/httprouter"
"github.com/nektos/act/pkg/common"
log "github.com/sirupsen/logrus"
)

type FileContainerResourceURL struct {
Expand Down Expand Up @@ -241,14 +240,15 @@ func downloads(router *httprouter.Router, fsys fs.FS) {

func Serve(ctx context.Context, artifactPath string, port string) context.CancelFunc {
serverContext, cancel := context.WithCancel(ctx)
logger := common.Logger(serverContext)

if artifactPath == "" {
return cancel
}

router := httprouter.New()

log.Debugf("Artifacts base path '%s'", artifactPath)
logger.Debugf("Artifacts base path '%s'", artifactPath)
fs := os.DirFS(artifactPath)
uploads(router, MkdirFsImpl{artifactPath, fs})
downloads(router, fs)
Expand All @@ -258,9 +258,9 @@ func Serve(ctx context.Context, artifactPath string, port string) context.Cancel

// run server
go func() {
log.Infof("Start server on http://%s:%s", ip, port)
logger.Infof("Start server on http://%s:%s", ip, port)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
logger.Fatal(err)
}
}()

Expand All @@ -269,7 +269,7 @@ func Serve(ctx context.Context, artifactPath string, port string) context.Cancel
<-serverContext.Done()

if err := server.Shutdown(ctx); err != nil {
log.Errorf("Failed shutdown gracefully - force shutdown: %v", err)
logger.Errorf("Failed shutdown gracefully - force shutdown: %v", err)
server.Close()
}
}()
Expand Down
4 changes: 1 addition & 3 deletions pkg/common/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package common
import (
"context"
"fmt"

log "github.com/sirupsen/logrus"
)

// Warning that implements `error` but safe to ignore
Expand Down Expand Up @@ -132,7 +130,7 @@ func (e Executor) Then(then Executor) Executor {
if err != nil {
switch err.(type) {
case Warning:
log.Warning(err.Error())
Logger(ctx).Warning(err.Error())
default:
return err
}
Expand Down
32 changes: 17 additions & 15 deletions pkg/common/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ var (
)

// FindGitRevision get the current git revision
func FindGitRevision(file string) (shortSha string, sha string, err error) {
func FindGitRevision(ctx context.Context, file string) (shortSha string, sha string, err error) {
logger := Logger(ctx)
gitDir, err := findGitDirectory(file)
if err != nil {
return "", "", err
Expand All @@ -55,24 +56,25 @@ func FindGitRevision(file string) (shortSha string, sha string, err error) {
refBuf = []byte(ref)
}

log.Debugf("Found revision: %s", refBuf)
logger.Debugf("Found revision: %s", refBuf)
return string(refBuf[:7]), strings.TrimSpace(string(refBuf)), nil
}

// FindGitRef get the current git ref
func FindGitRef(file string) (string, error) {
func FindGitRef(ctx context.Context, file string) (string, error) {
logger := Logger(ctx)
gitDir, err := findGitDirectory(file)
if err != nil {
return "", err
}
log.Debugf("Loading revision from git directory '%s'", gitDir)
logger.Debugf("Loading revision from git directory '%s'", gitDir)

_, ref, err := FindGitRevision(file)
_, ref, err := FindGitRevision(ctx, file)
if err != nil {
return "", err
}

log.Debugf("HEAD points to '%s'", ref)
logger.Debugf("HEAD points to '%s'", ref)

// Prefer the git library to iterate over the references and find a matching tag or branch.
var refTag = ""
Expand All @@ -86,7 +88,7 @@ func FindGitRef(file string) (string, error) {
if r == nil || err != nil {
break
}
// log.Debugf("Reference: name=%s sha=%s", r.Name().String(), r.Hash().String())
// logger.Debugf("Reference: name=%s sha=%s", r.Name().String(), r.Hash().String())
if r.Hash().String() == ref {
if r.Name().IsTag() {
refTag = r.Name().String()
Expand All @@ -109,15 +111,15 @@ func FindGitRef(file string) (string, error) {
// If the above doesn't work, fall back to the old way

// try tags first
tag, err := findGitPrettyRef(ref, gitDir, "refs/tags")
tag, err := findGitPrettyRef(ctx, ref, gitDir, "refs/tags")
if err != nil || tag != "" {
return tag, err
}
// and then branches
return findGitPrettyRef(ref, gitDir, "refs/heads")
return findGitPrettyRef(ctx, ref, gitDir, "refs/heads")
}

func findGitPrettyRef(head, root, sub string) (string, error) {
func findGitPrettyRef(ctx context.Context, head, root, sub string) (string, error) {
var name string
var err = filepath.Walk(filepath.Join(root, sub), func(path string, info os.FileInfo, err error) error {
if err != nil {
Expand All @@ -134,33 +136,33 @@ func findGitPrettyRef(head, root, sub string) (string, error) {
if head == pointsTo {
// On Windows paths are separated with backslash character so they should be replaced to provide proper git refs format
name = strings.TrimPrefix(strings.ReplaceAll(strings.Replace(path, root, "", 1), `\`, `/`), "/")
log.Debugf("HEAD matches %s", name)
Logger(ctx).Debugf("HEAD matches %s", name)
}
return nil
})
return name, err
}

// FindGithubRepo get the repo
func FindGithubRepo(file, githubInstance, remoteName string) (string, error) {
func FindGithubRepo(ctx context.Context, file, githubInstance, remoteName string) (string, error) {
if remoteName == "" {
remoteName = "origin"
}

url, err := findGitRemoteURL(file, remoteName)
url, err := findGitRemoteURL(ctx, file, remoteName)
if err != nil {
return "", err
}
_, slug, err := findGitSlug(url, githubInstance)
return slug, err
}

func findGitRemoteURL(file, remoteName string) (string, error) {
func findGitRemoteURL(ctx context.Context, file, remoteName string) (string, error) {
gitDir, err := findGitDirectory(file)
if err != nil {
return "", err
}
log.Debugf("Loading slug from git directory '%s'", gitDir)
Logger(ctx).Debugf("Loading slug from git directory '%s'", gitDir)

gitconfig, err := ini.InsensitiveLoad(fmt.Sprintf("%s/config", gitDir))
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions pkg/common/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func TestFindGitRemoteURL(t *testing.T) {
err = gitCmd("config", "-f", fmt.Sprintf("%s/.git/config", basedir), "--add", "remote.origin.url", remoteURL)
assert.NoError(err)

u, err := findGitRemoteURL(basedir, "origin")
u, err := findGitRemoteURL(context.Background(), basedir, "origin")
assert.NoError(err)
assert.Equal(remoteURL, u)
}
Expand Down Expand Up @@ -165,7 +165,7 @@ func TestGitFindRef(t *testing.T) {
require.NoError(t, gitCmd("-C", dir, "init", "--initial-branch=master"))
require.NoError(t, cleanGitHooks(dir))
tt.Prepare(t, dir)
ref, err := FindGitRef(dir)
ref, err := FindGitRef(context.Background(), dir)
tt.Assert(t, ref, err)
})
}
Expand Down
10 changes: 6 additions & 4 deletions pkg/container/docker_auth.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
package container

import (
"context"
"strings"

"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/credentials"
"github.com/docker/docker/api/types"
log "github.com/sirupsen/logrus"
"github.com/nektos/act/pkg/common"
)

func LoadDockerAuthConfig(image string) (types.AuthConfig, error) {
func LoadDockerAuthConfig(ctx context.Context, image string) (types.AuthConfig, error) {
logger := common.Logger(ctx)
config, err := config.Load(config.Dir())
if err != nil {
log.Warnf("Could not load docker config: %v", err)
logger.Warnf("Could not load docker config: %v", err)
return types.AuthConfig{}, err
}

Expand All @@ -28,7 +30,7 @@ func LoadDockerAuthConfig(image string) (types.AuthConfig, error) {

authConfig, err := config.GetAuthConfig(hostName)
if err != nil {
log.Warnf("Could not get auth config from docker config: %v", err)
logger.Warnf("Could not get auth config from docker config: %v", err)
return types.AuthConfig{}, err
}

Expand Down
7 changes: 3 additions & 4 deletions pkg/container/docker_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

// github.com/docker/docker/builder/dockerignore is deprecated
"github.com/moby/buildkit/frontend/dockerfile/dockerignore"
log "github.com/sirupsen/logrus"

"github.com/nektos/act/pkg/common"
)
Expand Down Expand Up @@ -56,7 +55,7 @@ func NewDockerBuildExecutor(input NewDockerBuildExecutorInput) common.Executor {
if input.Container != nil {
buildContext, err = input.Container.GetContainerArchive(ctx, input.ContextDir+"/.")
} else {
buildContext, err = createBuildContext(input.ContextDir, "Dockerfile")
buildContext, err = createBuildContext(ctx, input.ContextDir, "Dockerfile")
}
if err != nil {
return err
Expand All @@ -74,8 +73,8 @@ func NewDockerBuildExecutor(input NewDockerBuildExecutorInput) common.Executor {
return nil
}
}
func createBuildContext(contextDir string, relDockerfile string) (io.ReadCloser, error) {
log.Debugf("Creating archive for build context dir '%s' with relative dockerfile '%s'", contextDir, relDockerfile)
func createBuildContext(ctx context.Context, contextDir string, relDockerfile string) (io.ReadCloser, error) {
common.Logger(ctx).Debugf("Creating archive for build context dir '%s' with relative dockerfile '%s'", contextDir, relDockerfile)

// And canonicalize dockerfile name to a platform-independent one
relDockerfile = archive.CanonicalTarNameForPath(relDockerfile)
Expand Down
11 changes: 5 additions & 6 deletions pkg/container/docker_pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"

"github.com/nektos/act/pkg/common"
)
Expand All @@ -35,7 +34,7 @@ func NewDockerPullExecutor(input NewDockerPullExecutorInput) common.Executor {
pull := input.ForcePull
if !pull {
imageExists, err := ImageExistsLocally(ctx, input.Image, input.Platform)
log.Debugf("Image exists? %v", imageExists)
logger.Debugf("Image exists? %v", imageExists)
if err != nil {
return errors.WithMessagef(err, "unable to determine if image already exists for image %q (%s)", input.Image, input.Platform)
}
Expand All @@ -49,7 +48,7 @@ func NewDockerPullExecutor(input NewDockerPullExecutorInput) common.Executor {
return nil
}

imageRef := cleanImage(input.Image)
imageRef := cleanImage(ctx, input.Image)
logger.Debugf("pulling image '%v' (%s)", imageRef, input.Platform)

cli, err := GetDockerClient(ctx)
Expand Down Expand Up @@ -94,7 +93,7 @@ func getImagePullOptions(ctx context.Context, input NewDockerPullExecutorInput)

imagePullOptions.RegistryAuth = base64.URLEncoding.EncodeToString(encodedJSON)
} else {
authConfig, err := LoadDockerAuthConfig(input.Image)
authConfig, err := LoadDockerAuthConfig(ctx, input.Image)
if err != nil {
return imagePullOptions, err
}
Expand All @@ -113,10 +112,10 @@ func getImagePullOptions(ctx context.Context, input NewDockerPullExecutorInput)
return imagePullOptions, nil
}

func cleanImage(image string) string {
func cleanImage(ctx context.Context, image string) string {
ref, err := reference.ParseAnyReference(image)
if err != nil {
log.Error(err)
common.Logger(ctx).Error(err)
return ""
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/container/docker_pull_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestCleanImage(t *testing.T) {
}

for _, table := range tables {
imageOut := cleanImage(table.imageIn)
imageOut := cleanImage(context.Background(), table.imageIn)
assert.Equal(t, table.imageOut, imageOut)
}
}
Expand Down
9 changes: 4 additions & 5 deletions pkg/container/docker_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import (

"github.com/Masterminds/semver"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"golang.org/x/term"

"github.com/nektos/act/pkg/common"
Expand Down Expand Up @@ -597,7 +596,7 @@ func (cr *containerReference) copyDir(dstPath string, srcPath string, useGitIgno
if err != nil {
return err
}
log.Debugf("Writing tarball %s from %s", tarFile.Name(), srcPath)
logger.Debugf("Writing tarball %s from %s", tarFile.Name(), srcPath)
defer func(tarFile *os.File) {
name := tarFile.Name()
err := tarFile.Close()
Expand All @@ -615,13 +614,13 @@ func (cr *containerReference) copyDir(dstPath string, srcPath string, useGitIgno
if !strings.HasSuffix(srcPrefix, string(filepath.Separator)) {
srcPrefix += string(filepath.Separator)
}
log.Debugf("Stripping prefix:%s src:%s", srcPrefix, srcPath)
logger.Debugf("Stripping prefix:%s src:%s", srcPrefix, srcPath)

var ignorer gitignore.Matcher
if useGitIgnore {
ps, err := gitignore.ReadPatterns(polyfill.New(osfs.New(srcPath)), nil)
if err != nil {
log.Debugf("Error loading .gitignore: %v", err)
logger.Debugf("Error loading .gitignore: %v", err)
}

ignorer = gitignore.NewMatcher(ps)
Expand Down Expand Up @@ -664,7 +663,7 @@ func (cr *containerReference) copyContent(dstPath string, files ...*FileEntry) c
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
for _, file := range files {
log.Debugf("Writing entry to tarball %s len:%d", file.Name, len(file.Body))
logger.Debugf("Writing entry to tarball %s len:%d", file.Name, len(file.Body))
hdr := &tar.Header{
Name: file.Name,
Mode: file.Mode,
Expand Down
Loading

0 comments on commit 334d36c

Please sign in to comment.