diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 050d128..3a1ac2f 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -27,12 +27,12 @@ jobs: version: v3.12.1 - name: Set Golang - uses: actions/setup-go@v4 + uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 with: - go-version: 1.24.2 + go-version: '^1.25' - name: Set Golangci-lint - run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.64.7 + run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.4.0 - name: Set Shellcheck run: sudo apt-get -qq update && sudo apt-get install -y shellcheck && shellcheck install-binary.sh diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index bc46022..8aed2fb 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -35,7 +35,7 @@ jobs: - name: Set Golang uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 with: - go-version: 1.24.2 + go-version: '^1.25' - name: Build run: make build diff --git a/.golangci.yml b/.golangci.yml index 03b2013..6d0ad56 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,66 +1,52 @@ +version: "2" linters: enable: - bodyclose - dogsled - gocyclo - - gofmt - - goimports - gosec - - gosimple - govet - ineffassign - lll - - megacheck - misspell - nakedret - revive - staticcheck - - typecheck - unconvert - unused - disable: - errcheck - + exclusions: + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - path: '(.+)\.go$' + text: "(Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less)" + - path: '(.+)\.go$' + text: "Potential file inclusion via variable" + - path: '(.+)\.go$' + text: "G306: Expect WriteFile permissions to be 0600 or less" + - path: '(.+)\.go$' + text: "avoid meaningless package names" + settings: + gocyclo: + min-complexity: 18 + govet: + enable: + - shadow + lll: + line-length: 200 +formatters: + enable: + - gofmt + - goimports run: timeout: 5m -linters-settings: - gocyclo: - min-complexity: 18 - govet: - check-shadowing: false - lll: - line-length: 200 - nakedret: - command: nakedret - pattern: ^(?P.*?\\.go):(?P\\d+)\\s*(?P.*)$ - issues: - # The default exclusion rules are a bit too permissive, so copying the relevant ones below - exclude-use-default: false - - exclude: - - parameter .* always receives - - exclude-rules: - # EXC0009 - - text: "(Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less)" - linters: - - gosec - # EXC0010 - - text: "Potential file inclusion via variable" - linters: - - gosec - - path: test # Excludes /test, *_test.go etc. - linters: - - gosec - # Looks like the match in "EXC0009" above doesn't catch this one - # TODO: consider upstreaming this to golangci-lint's default exclusion rules - - text: "G306: Expect WriteFile permissions to be 0600 or less" - linters: - - gosec - # Maximum issues count per one linter. Set to 0 to disable. Default is 50. max-issues-per-linter: 0 diff --git a/cmd/dt/carvelize/carvelize.go b/cmd/dt/carvelize/carvelize.go index cbafa2b..b44eb9e 100644 --- a/cmd/dt/carvelize/carvelize.go +++ b/cmd/dt/carvelize/carvelize.go @@ -101,8 +101,7 @@ func GenerateBundle(chartPath string, opts ...chartutils.Option) error { imgPkgPath := filepath.Join(chartPath, ".imgpkg") if !utils.FileExists(imgPkgPath) { - err := os.Mkdir(imgPkgPath, os.FileMode(0755)) - if err != nil { + if err = os.Mkdir(imgPkgPath, os.FileMode(0755)); err != nil { return fmt.Errorf("failed to create .imgpkg directory: %w", err) } } @@ -126,7 +125,7 @@ func GenerateBundle(chartPath string, opts ...chartutils.Option) error { path := filepath.Join(imgPkgPath, "images.yml") err = carvelImagesLock.WriteToPath(path) if err != nil { - return fmt.Errorf("Could not write image lock: %v", err) + return fmt.Errorf("could not write image lock: %w", err) } l.Infof("Carvel images lock written to %q", path) diff --git a/cmd/dt/dt_test.go b/cmd/dt/dt_test.go index ab6d44b..7779534 100644 --- a/cmd/dt/dt_test.go +++ b/cmd/dt/dt_test.go @@ -56,7 +56,7 @@ func execCommand(args ...string) CmdResult { var buffStdout, buffStderr bytes.Buffer code := 0 - cmd := exec.Command(os.Args[0], args...) + cmd := exec.Command(os.Args[0], args...) //nolint:gosec cmd.Stdout = &buffStdout cmd.Stderr = &buffStderr diff --git a/cmd/dt/lock/lock.go b/cmd/dt/lock/lock.go index 9b14a27..1b5c300 100644 --- a/cmd/dt/lock/lock.go +++ b/cmd/dt/lock/lock.go @@ -42,18 +42,18 @@ func NewCmd(cfg *config.Config) *cobra.Command { chartPath := args[0] - outputFile, err := getOutputFilename(chartPath) + lockFilePath, err := getOutputFilename(chartPath) if err != nil { return fmt.Errorf("failed to obtain Images.lock location: %w", err) } if err := l.ExecuteStep("Generating Images.lock from annotations...", func() error { - return Create(chartPath, outputFile, silent.NewLogger(), imagelock.WithPlatforms(platforms), + return Create(chartPath, lockFilePath, silent.NewLogger(), imagelock.WithPlatforms(platforms), imagelock.WithAnnotationsKey(cfg.AnnotationsKey), imagelock.WithInsecure(cfg.Insecure)) }); err != nil { - return l.Failf("Failed to genereate lock: %w", err) + return l.Failf("Failed to generate lock: %w", err) } - l.Successf("Images.lock file written to %q", outputFile) + l.Successf("Images.lock file written to %q", lockFilePath) return nil }, } diff --git a/cmd/dt/lock_test.go b/cmd/dt/lock_test.go index 14b0c83..6ae8198 100644 --- a/cmd/dt/lock_test.go +++ b/cmd/dt/lock_test.go @@ -77,7 +77,7 @@ func (suite *CmdSuite) TestLockCommand() { args := []string{"images", "lock", "--insecure", chartDir} res := dt(args...) - res.AssertErrorMatch(t, "Failed to genereate lock: failed to write lock") + res.AssertErrorMatch(t, "Failed to generate lock: failed to write lock") }) t.Run("Handles non-existent chart", func(t *testing.T) { args := []string{"images", "lock", sb.TempFile()} diff --git a/cmd/dt/push_test.go b/cmd/dt/push_test.go index 36b2498..d57ba5e 100644 --- a/cmd/dt/push_test.go +++ b/cmd/dt/push_test.go @@ -35,7 +35,6 @@ func (suite *CmdSuite) TestPushCommand() { t.Run("Handle errors", func(t *testing.T) { t.Run("Handle missing Images.lock", func(t *testing.T) { - chartName := "test" scenarioName := "plain-chart" scenarioDir := fmt.Sprintf("../../testdata/scenarios/%s", scenarioName) chartDir := sb.TempFile() @@ -43,7 +42,7 @@ func (suite *CmdSuite) TestPushCommand() { require.NoError(tu.RenderScenario(scenarioDir, chartDir, map[string]interface{}{ "ServerURL": serverURL, "Images": nil, - "Name": chartName, "RepositoryURL": serverURL, + "Name": "test", "RepositoryURL": serverURL, }, )) dt("images", "push", chartDir).AssertErrorMatch(t, regexp.MustCompile(`failed to open Images.lock file:.*no such file or directory`)) @@ -52,7 +51,6 @@ func (suite *CmdSuite) TestPushCommand() { dt("images", "push", sb.TempFile()).AssertErrorMatch(t, regexp.MustCompile(`failed to load Helm chart`)) }) t.Run("Handle malformed Images.lock", func(t *testing.T) { - chartName := "test" scenarioName := "plain-chart" scenarioDir := fmt.Sprintf("../../testdata/scenarios/%s", scenarioName) chartDir := sb.TempFile() @@ -60,23 +58,21 @@ func (suite *CmdSuite) TestPushCommand() { require.NoError(tu.RenderScenario(scenarioDir, chartDir, map[string]interface{}{ "ServerURL": serverURL, "Images": nil, - "Name": chartName, "RepositoryURL": serverURL, + "Name": "test", "RepositoryURL": serverURL, }, )) require.NoError(os.WriteFile(filepath.Join(chartDir, imagelock.DefaultImagesLockFileName), []byte("malformed lock"), 0644)) dt("images", "push", chartDir).AssertErrorMatch(t, regexp.MustCompile(`failed to load Images.lock`)) }) t.Run("Handle failing to push images", func(t *testing.T) { - chartName := "test" scenarioName := "chart1" - serverURL := "example.com" scenarioDir := fmt.Sprintf("../../testdata/scenarios/%s", scenarioName) chartDir := sb.TempFile() require.NoError(tu.RenderScenario(scenarioDir, chartDir, map[string]interface{}{ "ServerURL": serverURL, "Images": nil, - "Name": chartName, "RepositoryURL": serverURL, + "Name": "test", "RepositoryURL": serverURL, }, )) dt("images", "push", chartDir).AssertErrorMatch(t, regexp.MustCompile(`(?i)failed to push images`)) @@ -84,7 +80,6 @@ func (suite *CmdSuite) TestPushCommand() { }) t.Run("Pushing works", func(t *testing.T) { scenarioName := "complete-chart" - chartName := "test" scenarioDir := fmt.Sprintf("../../testdata/scenarios/%s", scenarioName) @@ -107,20 +102,20 @@ func (suite *CmdSuite) TestPushCommand() { require.NoError(tu.RenderScenario(scenarioDir, chartDir, map[string]interface{}{ "ServerURL": serverURL, "Images": images, - "Name": chartName, "RepositoryURL": serverURL, + "Name": "test", "RepositoryURL": serverURL, }, )) imagesDir := filepath.Join(chartDir, "images") require.NoError(os.MkdirAll(imagesDir, 0755)) for _, img := range craneImgs { - d, err := img.Digest() - if err != nil { - t.Fatal(err) + d, digestErr := img.Digest() + if digestErr != nil { + t.Fatal(digestErr) } imgDir := filepath.Join(imagesDir, fmt.Sprintf("%s.layout", d.Hex)) - if err := crane.SaveOCI(img, imgDir); err != nil { - t.Fatal(err) + if ociErr := crane.SaveOCI(img, imgDir); ociErr != nil { + t.Fatal(ociErr) } } diff --git a/cmd/dt/unwrap/unwrap.go b/cmd/dt/unwrap/unwrap.go index 0e98be3..2faaae8 100644 --- a/cmd/dt/unwrap/unwrap.go +++ b/cmd/dt/unwrap/unwrap.go @@ -411,32 +411,37 @@ func normalizeOCIURL(url string) string { } func pushChart(ctx context.Context, wrap wrapping.Wrap, pushChartURL string, cfg *Config) error { - chart := wrap.Chart() - chartPath := chart.RootDir() - tmpDir, err := cfg.GetTemporaryDirectory() + var tmpDir, dir string + var err error + tmpDir, err = cfg.GetTemporaryDirectory() if err != nil { - return err + return fmt.Errorf("failed to get temp dir: %w", err) } - dir, err := os.MkdirTemp(tmpDir, "chart-*") + dir, err = os.MkdirTemp(tmpDir, "chart-*") if err != nil { - return fmt.Errorf("failed to upload Helm chart: failed to create temp directory: %w", err) + return fmt.Errorf("failed to create temp directory: %w", err) } + chart := wrap.Chart() + chartPath := chart.RootDir() tempTarFile := filepath.Join(dir, fmt.Sprintf("%s.tgz", chart.Name())) - if err := utils.Tar(chartPath, tempTarFile, utils.TarConfig{ + if err = utils.Tar(chartPath, tempTarFile, utils.TarConfig{ Prefix: chart.Name(), }); err != nil { return fmt.Errorf("failed to untar filename %q: %w", chartPath, err) } - d, err := cfg.GetTemporaryDirectory() + + tmpDir, err = cfg.GetTemporaryDirectory() if err != nil { return fmt.Errorf("failed to get temp dir: %w", err) } - if err := artifacts.PushChart(tempTarFile, pushChartURL, - artifacts.WithInsecure(cfg.Insecure), artifacts.WithPlainHTTP(cfg.UsePlainHTTP), + + if err = artifacts.PushChart(tempTarFile, pushChartURL, + artifacts.WithInsecure(cfg.Insecure), + artifacts.WithPlainHTTP(cfg.UsePlainHTTP), artifacts.WithRegistryAuth(cfg.Auth.Username, cfg.Auth.Password), - artifacts.WithTempDir(d), + artifacts.WithTempDir(tmpDir), ); err != nil { return err } diff --git a/cmd/dt/unwrap_test.go b/cmd/dt/unwrap_test.go index 7b46a77..2b688fc 100644 --- a/cmd/dt/unwrap_test.go +++ b/cmd/dt/unwrap_test.go @@ -386,8 +386,8 @@ func (suite *CmdSuite) TestEndToEnd() { "metadata.txt": []byte(metdataFileText), } for fileName, data := range metadataArtifacts { - _, err := sb.Write(filepath.Join(metadataDir, fileName), string(data)) - require.NoError(err) + _, writeErr := sb.Write(filepath.Join(metadataDir, fileName), string(data)) + require.NoError(writeErr) } images, err := tu.AddSampleImagesToRegistry(imageName, srcRegistry, tu.WithSignKey(keyFile), tu.WithMetadataDir(metadataDir), tu.WithAuth(contUser, contPass)) diff --git a/cmd/dt/verify/verify.go b/cmd/dt/verify/verify.go index 7c13c00..44995e3 100644 --- a/cmd/dt/verify/verify.go +++ b/cmd/dt/verify/verify.go @@ -29,7 +29,7 @@ type Config struct { // Lock verifies the images in an Images.lock func Lock(chartPath string, lockFile string, cfg Config) error { if !utils.FileExists(chartPath) { - return fmt.Errorf("Helm chart %q does not exist", chartPath) + return fmt.Errorf("chart %q does not exist", chartPath) } fh, err := os.Open(lockFile) if err != nil { @@ -53,7 +53,7 @@ func Lock(chartPath string, lockFile string, cfg Config) error { } if err := calculatedLock.Validate(currentLock.Images); err != nil { - return fmt.Errorf("Images.lock does not validate:\n%v", err) + return fmt.Errorf("validation failed for Images.lock: %w", err) } return nil } @@ -77,7 +77,7 @@ func NewCmd(cfg *config.Config) *cobra.Command { l := cfg.Logger() if !utils.FileExists(chartPath) { - return fmt.Errorf("Helm chart %q does not exist", chartPath) + return fmt.Errorf("chart %q does not exist", chartPath) } if lockFile == "" { diff --git a/cmd/dt/verify_test.go b/cmd/dt/verify_test.go index 1678567..c47c424 100644 --- a/cmd/dt/verify_test.go +++ b/cmd/dt/verify_test.go @@ -40,7 +40,7 @@ func (suite *CmdSuite) TestVerifyCommand() { t.Run("Handle errors", func(t *testing.T) { t.Run("Non-existent Helm chart", func(t *testing.T) { - dt("images", "verify", sb.TempFile()).AssertErrorMatch(t, "Helm chart.*does not exist") + dt("images", "verify", sb.TempFile()).AssertErrorMatch(t, "chart.*does not exist") }) t.Run("Missing Images.lock", func(t *testing.T) { chartName := "test" @@ -89,8 +89,12 @@ func (suite *CmdSuite) TestVerifyCommand() { ) require.NoError(err) require.NoError(os.WriteFile(filepath.Join(chartDir, "Images.lock"), []byte(data), 0644)) - dt("images", "verify", "--insecure", chartDir).AssertErrorMatch(t, fmt.Sprintf(`.*Images.lock does not validate: -.*Helm chart "test": image ".*%s": digests do not match:\s*.*- %s\s*\s*\+ %s.*`, images[0].Image, newDigest, oldDigest)) + dt("images", "verify", "--insecure", chartDir).AssertErrorMatch(t, + fmt.Sprintf( + `.*validation failed for Images.lock:.*chart "test": image ".*%s": digests do not match:\s*.*- %s\s*\s*\+ %s.*`, + images[0].Image, newDigest, oldDigest, + ), + ) }) }) t.Run("Verify Helm chart", func(t *testing.T) { diff --git a/cmd/dt/wrap/wrap.go b/cmd/dt/wrap/wrap.go index c3a8de5..418faec 100644 --- a/cmd/dt/wrap/wrap.go +++ b/cmd/dt/wrap/wrap.go @@ -219,7 +219,6 @@ func Chart(inputPath string, opts ...Option) (string, error) { func ResolveInputChartPath(inputPath string, cfg *Config) (string, error) { l := cfg.GetLogger() var chartPath string - var err error tmpDir, err := cfg.GetTemporaryDirectory() if err != nil { @@ -227,13 +226,13 @@ func ResolveInputChartPath(inputPath string, cfg *Config) (string, error) { } if chartutils.IsRemoteChart(inputPath) { - if err := l.ExecuteStep("Fetching remote Helm chart", func() error { + if err = l.ExecuteStep("Fetching remote Helm chart", func() error { version := cfg.Version - chartPath, err = fetchRemoteChart(inputPath, version, tmpDir, cfg) if err != nil { return err } + return nil }); err != nil { return "", l.Failf("Failed to download Helm chart: %w", err) @@ -374,10 +373,12 @@ func wrapChart(inputPath string, opts ...Option) (string, error) { if err != nil { return "", err } + tmpDir, err := cfg.GetTemporaryDirectory() if err != nil { return "", fmt.Errorf("failed to create temporary directory: %w", err) } + wrap, err := wrapping.Create(chartPath, filepath.Join(tmpDir, "wrap"), chartutils.WithAnnotationsKey(cfg.AnnotationsKey), ) @@ -389,18 +390,17 @@ func wrapChart(inputPath string, opts ...Option) (string, error) { if cfg.ShouldFetchChartArtifacts(inputPath) { chartURL := fmt.Sprintf("%s:%s", inputPath, chart.Version()) - if err := fetchArtifacts(chartURL, filepath.Join(wrap.RootDir(), artifacts.HelmChartArtifactMetadataDir), subCfg); err != nil { + if err = fetchArtifacts(chartURL, filepath.Join(wrap.RootDir(), artifacts.HelmChartArtifactMetadataDir), subCfg); err != nil { return "", err } } chartRoot := chart.RootDir() - if err := validateWrapLock(wrap, subCfg); err != nil { + if err = validateWrapLock(wrap, subCfg); err != nil { return "", err } outputFile := cfg.OutputFile - if outputFile == "" { outputBaseName := fmt.Sprintf("%s-%s.wrap.tgz", chart.Name(), chart.Version()) if outputFile, err = filepath.Abs(outputBaseName); err != nil { @@ -408,6 +408,7 @@ func wrapChart(inputPath string, opts ...Option) (string, error) { outputFile = filepath.Join(filepath.Dir(chartRoot), outputBaseName) } } + if !cfg.SkipPullImages { if err := pullImages(wrap, subCfg); err != nil { return "", err diff --git a/cmd/dt/wrap_test.go b/cmd/dt/wrap_test.go index 25aa05e..f5255dd 100644 --- a/cmd/dt/wrap_test.go +++ b/cmd/dt/wrap_test.go @@ -75,17 +75,17 @@ func verifyChartWrappedArtifacts(t *testing.T, sb *tu.Sandbox, wrapDir string, i imageArtifactDir := filepath.Join(artifactsDir, fmt.Sprintf("images/%s/%s", wrap.Chart().Name(), imgData.Name)) require.DirExists(t, imageArtifactDir) for _, dir := range []string{"sig", "metadata", "metadata.sig"} { - imageArtifactDir := filepath.Join(imageArtifactDir, fmt.Sprintf("%s.%s", imageTag, dir)) - require.DirExists(t, imageArtifactDir) + subDir := filepath.Join(imageArtifactDir, fmt.Sprintf("%s.%s", imageTag, dir)) + require.DirExists(t, subDir) // Basic validation of the oci-layout dir for _, f := range []string{"index.json", "oci-layout"} { - require.FileExists(t, filepath.Join(imageArtifactDir, f)) + require.FileExists(t, filepath.Join(subDir, f)) } - require.DirExists(t, filepath.Join(imageArtifactDir, "blobs")) + require.DirExists(t, filepath.Join(subDir, "blobs")) // For the "metadata" dir, check the bundle assets match what we provided if dir == "metadata" { - verifyArtifactsContents(t, sb, imageArtifactDir, artifactsData) + verifyArtifactsContents(t, sb, subDir, artifactsData) } } } @@ -96,11 +96,11 @@ func testChartWrap(t *testing.T, sb *tu.Sandbox, inputChart string, expectedLock t.Helper() // Setup a working directory to look for the wrap when not providing a output-filename - currentDir, err := os.Getwd() - require.NoError(t, err) + currentDir, wdErr := os.Getwd() + require.NoError(t, wdErr) - workingDir, err := sb.Mkdir(sb.TempFile(), 0755) - require.NoError(t, err) + workingDir, mkdirErr := sb.Mkdir(sb.TempFile(), 0755) + require.NoError(t, mkdirErr) defer os.Chdir(currentDir) require.NoError(t, os.Chdir(workingDir)) @@ -169,8 +169,8 @@ func testChartWrap(t *testing.T, sb *tu.Sandbox, inputChart string, expectedLock assert.FileExists(t, carvelImagesLockFile) } - newData, err := os.ReadFile(lockFile) - require.NoError(t, err) + newData, readErr := os.ReadFile(lockFile) + require.NoError(t, readErr) var newLock map[string]interface{} require.NoError(t, yaml.Unmarshal(newData, &newLock)) // Clear the timestamp @@ -215,15 +215,15 @@ func (suite *CmdSuite) TestWrapCommand() { if tc.auth { useAPI = true - srv, err := repotest.NewTempServerWithCleanup(t, "") - if err != nil { - t.Fatal(err) + srv, srvErr := repotest.NewTempServerWithCleanup(t, "") + if srvErr != nil { + t.Fatal(srvErr) } defer srv.Stop() - ociSrv, err := tu.NewOCIServer(t, srv.Root()) - if err != nil { - t.Fatal(err) + ociSrv, ociErr := tu.NewOCIServer(t, srv.Root()) + if ociErr != nil { + t.Fatal(ociErr) } go ociSrv.ListenAndServe() @@ -236,9 +236,9 @@ func (suite *CmdSuite) TestWrapCommand() { s := httptest.NewServer(registry.New(registry.Logger(silentLog))) defer s.Close() - u, err := url.Parse(s.URL) - if err != nil { - t.Fatal(err) + u, urlErr := url.Parse(s.URL) + if urlErr != nil { + t.Fatal(urlErr) } registryURL = u.Host } @@ -248,28 +248,27 @@ func (suite *CmdSuite) TestWrapCommand() { sb := suite.sb - certDir, err := sb.Mkdir(sb.TempFile(), 0755) - require.NoError(err) - - keyFile, _, err := tu.GenerateCosignCertificateFiles(certDir) - require.NoError(err) + certDir, certDirErr := sb.Mkdir(sb.TempFile(), 0755) + require.NoError(certDirErr) - metadataDir, err := sb.Mkdir(sb.TempFile(), 0755) - require.NoError(err) + keyFile, _, cosignErr := tu.GenerateCosignCertificateFiles(certDir) + require.NoError(cosignErr) - metdataFileText := "this is a sample text" + metadataDir, metadataDirErr := sb.Mkdir(sb.TempFile(), 0755) + require.NoError(metadataDirErr) + metadataFileText := "this is a sample text" metadataArtifacts := map[string][]byte{ - "metadata.txt": []byte(metdataFileText), + "metadata.txt": []byte(metadataFileText), } for fileName, data := range metadataArtifacts { - _, err := sb.Write(filepath.Join(metadataDir, fileName), string(data)) - require.NoError(err) + _, writeErr := sb.Write(filepath.Join(metadataDir, fileName), string(data)) + require.NoError(writeErr) } - images, err := tu.AddSampleImagesToRegistry(imageName, registryURL, tu.WithSignKey(keyFile), tu.WithMetadataDir(metadataDir), tu.WithAuth(username, password)) - if err != nil { - t.Fatal(err) + images, imgErr := tu.AddSampleImagesToRegistry(imageName, registryURL, tu.WithSignKey(keyFile), tu.WithMetadataDir(metadataDir), tu.WithAuth(username, password)) + if imgErr != nil { + t.Fatal(imgErr) } serverURL := registryURL diff --git a/go.mod b/go.mod index b2781c2..353fe98 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/vmware-labs/distribution-tooling-for-helm -go 1.24.2 +go 1.25 require ( github.com/DataDog/go-tuf v1.0.2-0.5.2 diff --git a/internal/testutil/oci.go b/internal/testutil/oci.go index 3f0eae4..217c006 100644 --- a/internal/testutil/oci.go +++ b/internal/testutil/oci.go @@ -152,12 +152,11 @@ func UnpackOCILayout(ctx context.Context, srcLayout string, destDir string) erro // CreateOCILayout creates a oc-layout directory from a source directory containing a set of files func CreateOCILayout(ctx context.Context, srcDir, destDir string) error { - dest, err := oci.New(destDir) - if err != nil { return err } + store, err := file.New("") if err != nil { return err @@ -165,7 +164,6 @@ func CreateOCILayout(ctx context.Context, srcDir, destDir string) error { defer store.Close() packOpts := oras.PackManifestOptions{} - descs, err := loadDir(ctx, store, nil, srcDir) if err != nil { return err @@ -174,12 +172,12 @@ func CreateOCILayout(ctx context.Context, srcDir, destDir string) error { packOpts.Layers = descs pack := func() (ocispec.Descriptor, error) { - root, err := oras.PackManifest(ctx, store, oras.PackManifestVersion1_1, oras.MediaTypeUnknownArtifact, packOpts) - if err != nil { - return ocispec.Descriptor{}, err + root, orasErr := oras.PackManifest(ctx, store, oras.PackManifestVersion1_1, oras.MediaTypeUnknownArtifact, packOpts) + if orasErr != nil { + return ocispec.Descriptor{}, orasErr } - if err = store.Tag(ctx, root, root.Digest.String()); err != nil { - return ocispec.Descriptor{}, err + if orasErr = store.Tag(ctx, root, root.Digest.String()); orasErr != nil { + return ocispec.Descriptor{}, orasErr } return root, nil } @@ -187,12 +185,8 @@ func CreateOCILayout(ctx context.Context, srcDir, destDir string) error { if err != nil { return err } - err = oras.CopyGraph(context.Background(), store, dest, root, oras.CopyGraphOptions{}) - if err != nil { - return err - } - return err + return oras.CopyGraph(context.Background(), store, dest, root, oras.CopyGraphOptions{}) } func pushArtifact(ctx context.Context, image string, dir string, opts ...crane.Option) error { @@ -273,6 +267,7 @@ func NewOCIServer(t *testing.T, dir string) (*repotest.OCIServer, error) { // NewOCIServerWithCustomCreds returns a new OCI server with custom credentials func NewOCIServerWithCustomCreds(t *testing.T, dir string, username, password string) (*repotest.OCIServer, error) { + //nolint:gosec testHtpasswdFileBasename := "authtest.htpasswd" testUsername, testPassword := username, password diff --git a/internal/testutil/sandbox.go b/internal/testutil/sandbox.go index e4c5263..afcc8fe 100644 --- a/internal/testutil/sandbox.go +++ b/internal/testutil/sandbox.go @@ -67,7 +67,7 @@ func (sb *Sandbox) TempFile(args ...string) string { if len(args) > 0 { tail = args[0] } else { - tail = strconv.Itoa(rand.Int()) + tail = strconv.Itoa(rand.Int()) //nolint:gosec // Too long paths in osx result in errors creating sockets (make the daemon tests break) // https://github.com/golang/go/issues/6895 if len(tail) > 10 { diff --git a/internal/testutil/server.go b/internal/testutil/server.go index 42b60b5..5b59e5a 100644 --- a/internal/testutil/server.go +++ b/internal/testutil/server.go @@ -91,8 +91,7 @@ func NewTestServer() (*TestServer, error) { resp, ok := testServer.responsesMap[r.URL.Path] if !ok { w.WriteHeader(404) - _, err := w.Write([]byte(fmt.Sprintf("cannot find image %q", r.URL.Path))) - if err != nil { + if _, err := fmt.Fprintf(w, "cannot find image %q", r.URL.Path); err != nil { log.Fatal(err) } return diff --git a/pkg/artifacts/helm.go b/pkg/artifacts/helm.go index 7f15c47..fde7d19 100644 --- a/pkg/artifacts/helm.go +++ b/pkg/artifacts/helm.go @@ -151,7 +151,7 @@ func PullChart(chartURL, version string, destDir string, opts ...RegistryClientO } cfg.RegistryClient = reg.client if cc.Auth.Username != "" && cc.Auth.Password != "" && reg.credentialsFile != "" { - if err := reg.client.Login(u.Host, registry.LoginOptBasicAuth(cc.Auth.Username, cc.Auth.Password)); err != nil { + if err = reg.client.Login(u.Host, registry.LoginOptBasicAuth(cc.Auth.Username, cc.Auth.Password)); err != nil { return "", fmt.Errorf("error logging in to %s: %w", u.Host, err) } defer func() { @@ -169,8 +169,7 @@ func PullChart(chartURL, version string, destDir string, opts ...RegistryClientO client.DestDir = dir client.Untar = true client.Version = version - _, err = client.Run(chartURL) - if err != nil { + if _, err = client.Run(chartURL); err != nil { return "", fmt.Errorf("failed to pull Helm chart: %w", err) } @@ -212,11 +211,11 @@ func showRemoteHelmChart(chartURL string, version string, cfg *RegistryClientCon } client.SetRegistryClient(reg.client) client.Version = version - cp, err := client.ChartPathOptions.LocateChart(chartURL, cli.New()) - + cp, err := client.LocateChart(chartURL, cli.New()) if err != nil { return "", err } + return client.Run(cp) } diff --git a/pkg/chartutils/chart.go b/pkg/chartutils/chart.go index a95e998..bf4d092 100644 --- a/pkg/chartutils/chart.go +++ b/pkg/chartutils/chart.go @@ -55,7 +55,7 @@ func (c *Chart) ChartDir() string { func (c *Chart) VerifyLock(opts ...imagelock.Option) error { chartPath := c.ChartDir() if !utils.FileExists(chartPath) { - return fmt.Errorf("Helm chart %q does not exist", chartPath) + return fmt.Errorf("chart %q does not exist", chartPath) } currentLock, err := c.GetImagesLock() @@ -71,7 +71,7 @@ func (c *Chart) VerifyLock(opts ...imagelock.Option) error { } if err := calculatedLock.Validate(currentLock.Images); err != nil { - return fmt.Errorf("Images.lock does not validate:\n%v", err) + return fmt.Errorf("validation failed for Images.lock:\n%v", err) } return nil } diff --git a/pkg/chartutils/chartutils.go b/pkg/chartutils/chartutils.go index 70e51ee..dbfa8e0 100644 --- a/pkg/chartutils/chartutils.go +++ b/pkg/chartutils/chartutils.go @@ -159,16 +159,16 @@ func IsRemoteChart(path string) bool { // ReadLockFromChart reads the Images.lock file from the chart func ReadLockFromChart(chartPath string) (*imagelock.ImagesLock, error) { var lock *imagelock.ImagesLock - var err error if isTar, _ := utils.IsTarFile(chartPath); isTar { if err := utils.FindFileInTar(context.Background(), chartPath, "Images.lock", func(tr *tar.Reader) error { + var err error lock, err = imagelock.FromYAML(tr) return err }, utils.TarConfig{StripComponents: 2}); err != nil { return nil, err } if lock == nil { - return nil, fmt.Errorf("Images.lock not found in wrap") + return nil, fmt.Errorf("wrap does not contain Images.lock") } return lock, nil } @@ -178,7 +178,7 @@ func ReadLockFromChart(chartPath string) (*imagelock.ImagesLock, error) { return nil, fmt.Errorf("failed to find Images.lock: %v", err) } if !utils.FileExists(f) { - return nil, fmt.Errorf("Images.lock file does not exist") + return nil, fmt.Errorf("file Images.lock does not exist") } return imagelock.FromYAMLFile(f) } diff --git a/pkg/chartutils/images.go b/pkg/chartutils/images.go index 634ed88..69d2f37 100644 --- a/pkg/chartutils/images.go +++ b/pkg/chartutils/images.go @@ -211,7 +211,8 @@ func loadImage(path string) (v1.Image, error) { } if !stat.IsDir() { - img, err := crane.Load(path) + var img v1.Image + img, err = crane.Load(path) if err != nil { return nil, fmt.Errorf("could not load %q as tarball: %w", path, err) } diff --git a/pkg/chartutils/images_test.go b/pkg/chartutils/images_test.go index 935fdf7..94c7834 100644 --- a/pkg/chartutils/images_test.go +++ b/pkg/chartutils/images_test.go @@ -23,6 +23,7 @@ func (suite *ChartUtilsTestSuite) TestPullImages() { silentLog := log.New(io.Discard, "", 0) s := httptest.NewServer(registry.New(registry.Logger(silentLog))) defer s.Close() + u, err := url.Parse(s.URL) if err != nil { t.Fatal(err) @@ -51,10 +52,8 @@ func (suite *ChartUtilsTestSuite) TestPullImages() { )) imagesDir := filepath.Join(chartDir, "images") - require.NoError(err) - - lock, err := imagelock.FromYAMLFile(filepath.Join(chartDir, "Images.lock")) - require.NoError(err) + lock, tErr := imagelock.FromYAMLFile(filepath.Join(chartDir, "Images.lock")) + require.NoError(tErr) require.NoError(PullImages(lock, imagesDir)) require.DirExists(imagesDir) @@ -78,10 +77,8 @@ func (suite *ChartUtilsTestSuite) TestPullImages() { )) imagesDir := filepath.Join(chartDir, "images") - require.NoError(err) - - lock, err := imagelock.FromYAMLFile(filepath.Join(chartDir, "Images.lock")) - require.NoError(err) + lock, tErr := imagelock.FromYAMLFile(filepath.Join(chartDir, "Images.lock")) + require.NoError(tErr) require.Error(PullImages(lock, imagesDir)) require.DirExists(imagesDir) @@ -123,8 +120,8 @@ func (suite *ChartUtilsTestSuite) TestPushImages() { "linux/amd64", "linux/arm", } - craneImgs, err := tu.CreateSampleImages(&imageData, architectures) + craneImgs, err := tu.CreateSampleImages(&imageData, architectures) if err != nil { t.Fatal(err) } @@ -144,18 +141,18 @@ func (suite *ChartUtilsTestSuite) TestPushImages() { imagesDir := filepath.Join(chartDir, "images") require.NoError(os.MkdirAll(imagesDir, 0755)) for _, img := range craneImgs { - d, err := img.Digest() - if err != nil { - t.Fatal(err) + d, tErr := img.Digest() + if tErr != nil { + t.Fatal(tErr) } + imgFile := filepath.Join(imagesDir, fmt.Sprintf("%s.layout", d.Hex)) - if err := crane.SaveOCI(img, imgFile); err != nil { - t.Fatal(err) + if tErr = crane.SaveOCI(img, imgFile); tErr != nil { + t.Fatal(tErr) } } t.Run("Push images", func(t *testing.T) { - require.NoError(err) lock, err := imagelock.FromYAMLFile(filepath.Join(chartDir, "Images.lock")) require.NoError(err) require.NoError(PushImages(lock, imagesDir)) diff --git a/pkg/chartutils/values.go b/pkg/chartutils/values.go index b242f31..0eeaad0 100644 --- a/pkg/chartutils/values.go +++ b/pkg/chartutils/values.go @@ -125,7 +125,7 @@ func (v *ValuesImageElement) Relocate(prefix string) error { } if slices.Contains(v.foundFields, "registry") { - v.Registry = newRef.Context().Registry.RegistryStr() + v.Registry = newRef.Context().RegistryStr() v.Repository = newRef.Context().RepositoryStr() } else { v.Repository = newRef.Context().Name() diff --git a/pkg/imagelock/image.go b/pkg/imagelock/image.go index 9155525..f9c5f2f 100644 --- a/pkg/imagelock/image.go +++ b/pkg/imagelock/image.go @@ -66,12 +66,12 @@ func (i *ChartImage) Diff(other *ChartImage) error { for _, digest := range other.Digests { existingDigest, err := i.GetDigestForArch(digest.Arch) if err != nil { - allErrors = errors.Join(allErrors, fmt.Errorf("Helm chart %q: image %q: %v", other.Chart, other.Image, err)) + allErrors = errors.Join(allErrors, fmt.Errorf("chart %q: image %q: %v", other.Chart, other.Image, err)) continue } if existingDigest.Digest != digest.Digest { allErrors = errors.Join(allErrors, - fmt.Errorf("Helm chart %q: image %q: digests do not match:\n- %s\n+ %s", + fmt.Errorf("chart %q: image %q: digests do not match:\n- %s\n+ %s", other.Chart, other.Image, digest.Digest, existingDigest.Digest)) continue } diff --git a/pkg/imagelock/lock_test.go b/pkg/imagelock/lock_test.go index a0a8561..789533f 100644 --- a/pkg/imagelock/lock_test.go +++ b/pkg/imagelock/lock_test.go @@ -197,14 +197,13 @@ func (suite *ImageLockTestSuite) TestGenerateFromChart() { t.Run("Retrieves only the specified platforms", func(_ *testing.T) { scenarioName := "custom-chart" - chartName := "test" scenarioDir := fmt.Sprintf("../../testdata/scenarios/%s", scenarioName) chartDir := sb.TempFile() require.NoError(tu.RenderScenario(scenarioDir, chartDir, - map[string]interface{}{"ServerURL": serverURL, "Images": sampleImages, "Name": chartName, "RepositoryURL": serverURL}, + map[string]interface{}{"ServerURL": serverURL, "Images": sampleImages, "Name": "test", "RepositoryURL": serverURL}, )) platforms := []string{"linux/amd64"} @@ -228,28 +227,27 @@ func (suite *ImageLockTestSuite) TestGenerateFromChart() { if err != nil { t.Fatal(err) } - serverURL := u.Host images := []*tu.ImageData{ { Name: "app1", - Image: fmt.Sprintf("%s/bitnami/app1:latest", serverURL), + Image: fmt.Sprintf("%s/bitnami/app1:latest", u.Host), }, } for _, img := range images { - craneImg, err := tu.CreateSingleArchImage(img, "linux/amd64") - require.NoError(err) + craneImg, tErr := tu.CreateSingleArchImage(img, "linux/amd64") + require.NoError(tErr) require.NoError(crane.Push(craneImg, img.Image, crane.Insecure)) } scenarioName := "custom-chart" - chartName := "test" - chartVersion := "1.0.0" - appVersion := "2.2.0" + chartName := "test" //nolint:govet + chartVersion := "1.0.0" //nolint:govet + appVersion := "2.2.0" //nolint:govet scenarioDir := fmt.Sprintf("../../testdata/scenarios/%s", scenarioName) chartDir := sb.TempFile() require.NoError(tu.RenderScenario(scenarioDir, chartDir, - map[string]interface{}{"ServerURL": serverURL, "Images": images, "Name": chartName, "Version": chartVersion, "AppVersion": appVersion}, + map[string]interface{}{"ServerURL": u.Host, "Images": images, "Name": chartName, "Version": chartVersion, "AppVersion": appVersion}, )) expectedLock := createLockFromImageData(map[string][]*tu.ImageData{ @@ -278,14 +276,13 @@ func (suite *ImageLockTestSuite) TestGenerateFromChart() { if err != nil { t.Fatal(err) } - serverURL := u.Host craneImg, err := crane.Image(map[string][]byte{ "platform.txt": []byte("undefined"), }) require.NoError(err) - image := fmt.Sprintf("%s/bitnami/app1:latest", serverURL) + image := fmt.Sprintf("%s/bitnami/app1:latest", u.Host) require.NoError(crane.Push(craneImg, image, crane.Insecure)) @@ -296,7 +293,7 @@ func (suite *ImageLockTestSuite) TestGenerateFromChart() { require.NoError(tu.RenderScenario(scenarioDir, chartDir, map[string]interface{}{ - "ServerURL": serverURL, + "ServerURL": u.Host, "Images": []*tu.ImageData{ { Name: "app1", diff --git a/pkg/log/logrus/logger.go b/pkg/log/logrus/logger.go index 760b1f3..f499e23 100644 --- a/pkg/log/logrus/logger.go +++ b/pkg/log/logrus/logger.go @@ -28,7 +28,7 @@ func (l *Logger) SetLevel(level log.Level) { // SetWriter sets the internal writer used by the log func (l *Logger) SetWriter(w io.Writer) { - l.Logger.SetOutput(w) + l.SetOutput(w) } // Printf prints a message in the log diff --git a/pkg/log/pterm/progress.go b/pkg/log/pterm/progress.go index 02534fd..fba46c6 100644 --- a/pkg/log/pterm/progress.go +++ b/pkg/log/pterm/progress.go @@ -63,7 +63,7 @@ func (p *ProgressBar) formatTitle(title string) string { // We prefix with a leading " " so we align with other printers, that // start with a leading space paddedTitle := " " + p.padding + title - maxTitleLength := int(float32(p.ProgressbarPrinter.MaxWidth) * 0.70) + maxTitleLength := int(float32(p.MaxWidth) * 0.70) truncatedTitle := utils.TruncateStringWithEllipsis(paddedTitle, maxTitleLength) return fmt.Sprintf("%-*s", maxTitleLength, truncatedTitle) } diff --git a/pkg/relocator/annotations.go b/pkg/relocator/annotations.go index 9e9e418..e567dcf 100644 --- a/pkg/relocator/annotations.go +++ b/pkg/relocator/annotations.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/vmware-labs/distribution-tooling-for-helm/pkg/chartutils" - cu "github.com/vmware-labs/distribution-tooling-for-helm/pkg/chartutils" ) // RelocateAnnotations rewrites the image urls in the chart annotations using the provided prefix @@ -20,7 +19,7 @@ func RelocateAnnotations(chartDir string, prefix string, opts ...chartutils.Opti return string(res.Data), nil } -func relocateAnnotations(c *cu.Chart, prefix string) (*RelocationResult, error) { +func relocateAnnotations(c *chartutils.Chart, prefix string) (*RelocationResult, error) { images, err := c.GetAnnotatedImages() if err != nil { return nil, fmt.Errorf("failed to read images from annotations: %v", err) diff --git a/pkg/relocator/chart.go b/pkg/relocator/chart.go index c1431d9..43d4c91 100644 --- a/pkg/relocator/chart.go +++ b/pkg/relocator/chart.go @@ -38,7 +38,7 @@ func relocateChart(chart *cu.Chart, prefix string, cfg *RelocateConfig) error { for _, result := range valuesReplRes { if result.Count > 0 { - if err := os.WriteFile(chart.AbsFilePath(result.Name), result.Data, 0644); err != nil { + if err = os.WriteFile(chart.AbsFilePath(result.Name), result.Data, 0644); err != nil { return fmt.Errorf("failed to write %s: %v", result.Name, err) } } @@ -51,7 +51,7 @@ func relocateChart(chart *cu.Chart, prefix string, cfg *RelocateConfig) error { } else { if annotationsRelocResult.Count > 0 { annotationsKeyPath := fmt.Sprintf("$.annotations['%s']", cfg.ImageLockConfig.AnnotationsKey) - if err := utils.YamlFileSet(chart.AbsFilePath("Chart.yaml"), map[string]string{ + if err = utils.YamlFileSet(chart.AbsFilePath("Chart.yaml"), map[string]string{ annotationsKeyPath: string(annotationsRelocResult.Data), }); err != nil { allErrors = errors.Join(allErrors, fmt.Errorf("failed to relocate Helm chart: failed to write annotations: %v", err)) diff --git a/pkg/relocator/chart_test.go b/pkg/relocator/chart_test.go index 74d3b72..37d96be 100644 --- a/pkg/relocator/chart_test.go +++ b/pkg/relocator/chart_test.go @@ -34,52 +34,52 @@ func TestRelocateChartDir(t *testing.T) { t.Run("Values Relocated", func(t *testing.T) { for _, valuesFile := range valuesFiles { t.Logf("checking %s file", valuesFile) - data, err := os.ReadFile(filepath.Join(chartDir, valuesFile)) - require.NoError(t, err) - relocatedValues, err := tu.NormalizeYAML(string(data)) - require.NoError(t, err) + data, tErr := os.ReadFile(filepath.Join(chartDir, valuesFile)) + require.NoError(t, tErr) + relocatedValues, tErr := tu.NormalizeYAML(string(data)) + require.NoError(t, tErr) - expectedData, err := tu.RenderTemplateFile(filepath.Join(scenarioDir, fmt.Sprintf("%s.tmpl", valuesFile)), map[string]string{"ServerURL": newServerURL, "RepositoryPrefix": repositoryPrefix}) - require.NoError(t, err) + expectedData, tErr := tu.RenderTemplateFile(filepath.Join(scenarioDir, fmt.Sprintf("%s.tmpl", valuesFile)), map[string]string{"ServerURL": newServerURL, "RepositoryPrefix": repositoryPrefix}) + require.NoError(t, tErr) - expectedValues, err := tu.NormalizeYAML(expectedData) - require.NoError(t, err) + expectedValues, tErr := tu.NormalizeYAML(expectedData) + require.NoError(t, tErr) assert.Equal(t, expectedValues, relocatedValues) } }) t.Run("Annotations Relocated", func(t *testing.T) { - c, err := loader.Load(chartDir) - require.NoError(t, err) + c, tErr := loader.Load(chartDir) + require.NoError(t, tErr) - relocatedAnnotations, err := tu.NormalizeYAML(c.Metadata.Annotations["images"]) - require.NoError(t, err) + relocatedAnnotations, tErr := tu.NormalizeYAML(c.Metadata.Annotations["images"]) + require.NoError(t, tErr) require.NotEqual(t, relocatedAnnotations, "") - expectedData, err := tu.RenderTemplateFile(filepath.Join(scenarioDir, "images.partial.tmpl"), map[string]string{"ServerURL": fullNewURL}) - require.NoError(t, err) + expectedData, tErr := tu.RenderTemplateFile(filepath.Join(scenarioDir, "images.partial.tmpl"), map[string]string{"ServerURL": fullNewURL}) + require.NoError(t, tErr) - expectedAnnotations, err := tu.NormalizeYAML(expectedData) - require.NoError(t, err) + expectedAnnotations, tErr := tu.NormalizeYAML(expectedData) + require.NoError(t, tErr) assert.Equal(t, expectedAnnotations, relocatedAnnotations) }) t.Run("ImageLock Relocated", func(t *testing.T) { - data, err := os.ReadFile(filepath.Join(chartDir, "Images.lock")) - assert.NoError(t, err) + data, tErr := os.ReadFile(filepath.Join(chartDir, "Images.lock")) + assert.NoError(t, tErr) var lockData map[string]interface{} require.NoError(t, yaml.Unmarshal(data, &lockData)) - imagesElemData, err := yaml.Marshal(lockData["images"]) - require.NoError(t, err) + imagesElemData, tErr := yaml.Marshal(lockData["images"]) + require.NoError(t, tErr) - relocatedImagesData, err := tu.NormalizeYAML(string(imagesElemData)) - require.NoError(t, err) + relocatedImagesData, tErr := tu.NormalizeYAML(string(imagesElemData)) + require.NoError(t, tErr) - expectedData, err := tu.RenderTemplateFile(filepath.Join(scenarioDir, "lock_images.partial.tmpl"), map[string]string{"ServerURL": fullNewURL}) - require.NoError(t, err) - expectedData, err = tu.NormalizeYAML(expectedData) - require.NoError(t, err) + expectedData, tErr := tu.RenderTemplateFile(filepath.Join(scenarioDir, "lock_images.partial.tmpl"), map[string]string{"ServerURL": fullNewURL}) + require.NoError(t, tErr) + expectedData, tErr = tu.NormalizeYAML(expectedData) + require.NoError(t, tErr) assert.Equal(t, expectedData, relocatedImagesData) @@ -94,54 +94,54 @@ func TestRelocateChartDir(t *testing.T) { t.Run("Values Relocated SkipImageRelocation", func(t *testing.T) { for _, valuesFile := range valuesFiles { t.Logf("checking %s file", valuesFile) - data, err := os.ReadFile(filepath.Join(chartDir, valuesFile)) - require.NoError(t, err) - relocatedValues, err := tu.NormalizeYAML(string(data)) - require.NoError(t, err) + data, tErr := os.ReadFile(filepath.Join(chartDir, valuesFile)) + require.NoError(t, tErr) + relocatedValues, tErr := tu.NormalizeYAML(string(data)) + require.NoError(t, tErr) - expectedData, err := tu.RenderTemplateFile(filepath.Join(scenarioDir, fmt.Sprintf("%s.tmpl", valuesFile)), map[string]string{"ServerURL": serverURL}) - require.NoError(t, err) + expectedData, tErr := tu.RenderTemplateFile(filepath.Join(scenarioDir, fmt.Sprintf("%s.tmpl", valuesFile)), map[string]string{"ServerURL": serverURL}) + require.NoError(t, tErr) - expectedValues, err := tu.NormalizeYAML(expectedData) - require.NoError(t, err) + expectedValues, tErr := tu.NormalizeYAML(expectedData) + require.NoError(t, tErr) assert.Equal(t, expectedValues, relocatedValues) } }) t.Run("Annotations Relocated ", func(t *testing.T) { - c, err := loader.Load(chartDir) - require.NoError(t, err) + c, tErr := loader.Load(chartDir) + require.NoError(t, tErr) - relocatedAnnotations, err := tu.NormalizeYAML(c.Metadata.Annotations["images"]) - require.NoError(t, err) + relocatedAnnotations, tErr := tu.NormalizeYAML(c.Metadata.Annotations["images"]) + require.NoError(t, tErr) require.NotEqual(t, relocatedAnnotations, "") - expectedData, err := tu.RenderTemplateFile(filepath.Join(scenarioDir, "images.partial.tmpl"), map[string]string{"ServerURL": serverURL}) - require.NoError(t, err) + expectedData, tErr := tu.RenderTemplateFile(filepath.Join(scenarioDir, "images.partial.tmpl"), map[string]string{"ServerURL": serverURL}) + require.NoError(t, tErr) - expectedAnnotations, err := tu.NormalizeYAML(expectedData) - require.NoError(t, err) + expectedAnnotations, tErr := tu.NormalizeYAML(expectedData) + require.NoError(t, tErr) assert.Equal(t, expectedAnnotations, relocatedAnnotations) }) t.Run("ImageLock Relocated SkipImageRelocation", func(t *testing.T) { - data, err := os.ReadFile(filepath.Join(chartDir, "Images.lock")) - assert.NoError(t, err) + data, tErr := os.ReadFile(filepath.Join(chartDir, "Images.lock")) + assert.NoError(t, tErr) var lockData map[string]interface{} require.NoError(t, yaml.Unmarshal(data, &lockData)) - imagesElemData, err := yaml.Marshal(lockData["images"]) - require.NoError(t, err) + imagesElemData, tErr := yaml.Marshal(lockData["images"]) + require.NoError(t, tErr) - relocatedImagesData, err := tu.NormalizeYAML(string(imagesElemData)) - require.NoError(t, err) + relocatedImagesData, tErr := tu.NormalizeYAML(string(imagesElemData)) + require.NoError(t, tErr) - expectedData, err := tu.RenderTemplateFile(filepath.Join(scenarioDir, "lock_images.partial.tmpl"), map[string]string{"ServerURL": serverURL}) - require.NoError(t, err) - expectedData, err = tu.NormalizeYAML(expectedData) - require.NoError(t, err) + expectedData, tErr := tu.RenderTemplateFile(filepath.Join(scenarioDir, "lock_images.partial.tmpl"), map[string]string{"ServerURL": serverURL}) + require.NoError(t, tErr) + expectedData, tErr = tu.NormalizeYAML(expectedData) + require.NoError(t, tErr) assert.Equal(t, expectedData, relocatedImagesData) diff --git a/pkg/relocator/values.go b/pkg/relocator/values.go index a2cf673..7f4ee3c 100644 --- a/pkg/relocator/values.go +++ b/pkg/relocator/values.go @@ -24,8 +24,7 @@ func relocateValuesData(valuesFile string, valuesData []byte, prefix string) (*R data := make(map[string]string, 0) for _, e := range imageElems { - err := e.Relocate(prefix) - if err != nil { + if err = e.Relocate(prefix); err != nil { return nil, fmt.Errorf("unexpected error relocating: %v", err) } for k, v := range e.YamlReplaceMap() { diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 749f577..ba8af83 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -65,12 +65,10 @@ func YamlSet(data []byte, values map[string]string) ([]byte, error) { var allErrors error var n yaml.Node - err := yaml.Unmarshal(data, &n) - if err != nil { + if err := yaml.Unmarshal(data, &n); err != nil { return nil, fmt.Errorf("cannot unmarshal YAML data: %v", err) } for path, value := range values { - if err := rawYamlSet(&n, path, value); err != nil { allErrors = errors.Join(allErrors, err) } @@ -83,8 +81,7 @@ func YamlSet(data []byte, values map[string]string) ([]byte, error) { e := yaml.NewEncoder(&buf) e.SetIndent(2) - err = e.Encode(&n) - if err != nil { + if err := e.Encode(&n); err != nil { return nil, fmt.Errorf("failed to format YAML: %v", err) } if err := e.Close(); err != nil { diff --git a/pkg/wrapping/wrap.go b/pkg/wrapping/wrap.go index 0558cc5..8467230 100644 --- a/pkg/wrapping/wrap.go +++ b/pkg/wrapping/wrap.go @@ -96,8 +96,7 @@ func Load(dir string, opts ...chartutils.Option) (Wrap, error) { // Create receives a path to a source Helm chart and a destination directory where to wrap it and returns a Wrap func Create(chartSrc string, destDir string, opts ...chartutils.Option) (Wrap, error) { // Check we got a chart dir - _, err := loader.Load(chartSrc) - if err != nil { + if _, err := loader.Load(chartSrc); err != nil { return nil, fmt.Errorf("failed to load Helm chart: %v", err) }