From a944f0e4c520fee53c41f0854db607a5ca9bccac Mon Sep 17 00:00:00 2001 From: Teppei Fukuda Date: Fri, 17 May 2024 12:16:52 +0400 Subject: [PATCH] chore: enforce golangci-lint version (#6700) Signed-off-by: knqyf263 --- magefiles/magefile.go | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/magefiles/magefile.go b/magefiles/magefile.go index 15b9759459b6..6fa5e643b300 100644 --- a/magefiles/magefile.go +++ b/magefiles/magefile.go @@ -2,9 +2,11 @@ package main import ( "context" + "encoding/json" "errors" "fmt" "io/fs" + "log/slog" "os" "os/exec" "path/filepath" @@ -13,6 +15,10 @@ import ( "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" "github.com/magefile/mage/target" + + // Trivy packages should not be imported in Mage (see https://github.com/aquasecurity/trivy/pull/4242), + // but this package doesn't have so many dependencies, and Mage is still fast. + "github.com/aquasecurity/trivy/pkg/log" ) var ( @@ -24,6 +30,10 @@ var ( } ) +func init() { + slog.SetDefault(log.New(log.NewHandler(os.Stderr, nil))) // stdout is suppressed in mage +} + func version() (string, error) { if ver, err := sh.Output("git", "describe", "--tags", "--always"); err != nil { return "", err @@ -60,15 +70,38 @@ func (Tool) Wire() error { } // GolangciLint installs golangci-lint -func (Tool) GolangciLint() error { +func (t Tool) GolangciLint() error { const version = "v1.57.2" - if exists(filepath.Join(GOBIN, "golangci-lint")) { + bin := filepath.Join(GOBIN, "golangci-lint") + if exists(bin) && t.matchGolangciLintVersion(bin, version) { return nil } command := fmt.Sprintf("curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b %s %s", GOBIN, version) return sh.Run("bash", "-c", command) } +func (Tool) matchGolangciLintVersion(bin, version string) bool { + out, err := sh.Output(bin, "version", "--format", "json") + if err != nil { + slog.Error("Unable to get golangci-lint version", slog.Any("err", err)) + return false + } + var output struct { + Version string `json:"Version"` + } + if err = json.Unmarshal([]byte(out), &output); err != nil { + slog.Error("Unable to parse golangci-lint version", slog.Any("err", err)) + return false + } + + version = strings.TrimPrefix(version, "v") + if output.Version != version { + slog.Info("golangci-lint version mismatch", slog.String("expected", version), slog.String("actual", output.Version)) + return false + } + return true +} + // Labeler installs labeler func (Tool) Labeler() error { if exists(filepath.Join(GOBIN, "labeler")) {