From 24b604d5d1fb43ff55a939d01f745d0c21976450 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 16 May 2025 10:30:42 +0200 Subject: [PATCH] chore: enable gocritic Signed-off-by: Matthieu MOREL --- .golangci.yml | 21 ++++++++++ internal/chart/v3/loader/directory.go | 3 +- internal/chart/v3/loader/load_test.go | 2 +- internal/chart/v3/util/chartfile.go | 2 +- internal/chart/v3/util/coalesce.go | 10 +++-- internal/chart/v3/util/create.go | 6 +-- internal/chart/v3/util/dependencies.go | 2 +- internal/chart/v3/util/expand.go | 4 +- internal/chart/v3/util/save.go | 6 +-- internal/chart/v3/util/save_test.go | 2 +- internal/fileutil/fileutil_test.go | 2 +- internal/monocular/search.go | 2 +- internal/sympath/walk.go | 2 +- internal/sympath/walk_test.go | 2 +- internal/test/test.go | 4 +- internal/third_party/dep/fs/fs.go | 2 +- internal/third_party/dep/fs/fs_test.go | 42 ++++++++++---------- pkg/action/action.go | 4 +- pkg/action/dependency_test.go | 4 +- pkg/action/install.go | 16 ++++---- pkg/action/list.go | 2 +- pkg/action/package.go | 2 +- pkg/action/package_test.go | 2 +- pkg/action/pull.go | 2 +- pkg/action/push.go | 2 +- pkg/action/registry_login.go | 2 +- pkg/action/show_test.go | 2 +- pkg/action/uninstall.go | 2 +- pkg/action/upgrade.go | 8 ++-- pkg/action/validate_test.go | 2 +- pkg/chart/v2/loader/directory.go | 2 +- pkg/chart/v2/loader/load_test.go | 2 +- pkg/chart/v2/util/chartfile.go | 2 +- pkg/chart/v2/util/coalesce.go | 10 +++-- pkg/chart/v2/util/create.go | 6 +-- pkg/chart/v2/util/dependencies.go | 2 +- pkg/chart/v2/util/expand.go | 4 +- pkg/chart/v2/util/save.go | 6 +-- pkg/chart/v2/util/save_test.go | 2 +- pkg/cli/values/options.go | 2 +- pkg/cli/values/options_test.go | 4 +- pkg/cmd/docs.go | 2 +- pkg/cmd/flags.go | 2 +- pkg/cmd/get_notes.go | 2 +- pkg/cmd/list.go | 2 +- pkg/cmd/load_plugins.go | 11 +++-- pkg/cmd/package_test.go | 4 +- pkg/cmd/plugin.go | 6 +-- pkg/cmd/plugin_test.go | 2 +- pkg/cmd/pull_test.go | 4 +- pkg/cmd/registry_login.go | 9 +++-- pkg/cmd/repo_add.go | 2 +- pkg/cmd/repo_add_test.go | 2 +- pkg/cmd/repo_remove.go | 2 +- pkg/cmd/repo_remove_test.go | 4 +- pkg/cmd/root.go | 2 +- pkg/cmd/search_repo.go | 14 +++---- pkg/cmd/show_test.go | 1 - pkg/cmd/status.go | 2 +- pkg/cmd/template.go | 8 ++-- pkg/downloader/chart_downloader.go | 6 +-- pkg/downloader/chart_downloader_test.go | 2 +- pkg/downloader/manager.go | 10 ++--- pkg/downloader/manager_test.go | 12 +++--- pkg/engine/engine.go | 2 +- pkg/engine/funcs_test.go | 2 +- pkg/engine/lookup_func.go | 2 +- pkg/getter/httpgetter.go | 2 +- pkg/getter/httpgetter_test.go | 10 ++--- pkg/getter/plugingetter.go | 8 ++-- pkg/kube/client.go | 2 +- pkg/kube/client_test.go | 6 +-- pkg/kube/ready_test.go | 6 +-- pkg/kube/roundtripper_test.go | 2 +- pkg/kube/statuswait.go | 3 +- pkg/lint/rules/chartfile.go | 9 +++-- pkg/lint/rules/values_test.go | 2 +- pkg/plugin/installer/http_installer.go | 6 +-- pkg/plugin/installer/http_installer_test.go | 18 ++++----- pkg/plugin/installer/installer.go | 2 +- pkg/plugin/installer/local_installer_test.go | 2 +- pkg/plugin/installer/vcs_installer_test.go | 2 +- pkg/plugin/plugin.go | 12 +++--- pkg/provenance/sign_test.go | 10 +++-- pkg/pusher/ocipusher_test.go | 12 +++--- pkg/registry/client.go | 11 ++--- pkg/registry/transport.go | 9 +++-- pkg/registry/util.go | 10 ++--- pkg/registry/utils_test.go | 13 +++--- pkg/release/util/kind_sorter.go | 2 +- pkg/release/util/manifest.go | 2 +- pkg/repo/chartrepo.go | 10 ++--- pkg/repo/index.go | 5 ++- pkg/repo/index_test.go | 4 +- pkg/repo/repo.go | 2 +- pkg/repo/repo_test.go | 2 +- pkg/repo/repotest/tlsconfig.go | 1 - pkg/storage/driver/cfgmaps.go | 2 +- pkg/storage/driver/sql.go | 4 +- pkg/storage/driver/sql_test.go | 16 ++++---- pkg/storage/storage_test.go | 1 - pkg/strvals/literal_parser_test.go | 9 +++-- pkg/strvals/parser.go | 14 +++---- pkg/strvals/parser_test.go | 19 ++++----- pkg/time/time.go | 4 +- pkg/time/time_test.go | 2 +- 106 files changed, 304 insertions(+), 275 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index a9b13c35f..88b90a410 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,6 +20,7 @@ linters: enable: - depguard - dupl + - gocritic - gomodguard - govet - ineffassign @@ -57,6 +58,26 @@ linters: dupl: threshold: 400 + + gocritic: + disabled-checks: + - appendAssign + - badCall + - commentedOutCode + - deferInLoop + - exposedSyncMutex + - filepathJoin + - hugeParam + - importShadow + - nestingReduce + - ptrToRefParam + - rangeValCopy + - tooManyResultsChecker + - typeAssertChain + - unnamedResult + - unnecessaryDefer + - whyNoLint + enable-all: true gomodguard: blocked: diff --git a/internal/chart/v3/loader/directory.go b/internal/chart/v3/loader/directory.go index 947051604..14ff63708 100644 --- a/internal/chart/v3/loader/directory.go +++ b/internal/chart/v3/loader/directory.go @@ -113,7 +113,8 @@ func LoadDir(dir string) (*chart.Chart, error) { files = append(files, &BufferedFile{Name: n, Data: data}) return nil } - if err = sympath.Walk(topdir, walk); err != nil { + err = sympath.Walk(topdir, walk) + if err != nil { return c, err } diff --git a/internal/chart/v3/loader/load_test.go b/internal/chart/v3/loader/load_test.go index e770923ff..5cda971f0 100644 --- a/internal/chart/v3/loader/load_test.go +++ b/internal/chart/v3/loader/load_test.go @@ -363,7 +363,7 @@ func TestLoadInvalidArchive(t *testing.T) { h := &tar.Header{ Name: internalPath, - Mode: 0755, + Mode: 0o755, Size: int64(len(body)), ModTime: time.Now(), } diff --git a/internal/chart/v3/util/chartfile.go b/internal/chart/v3/util/chartfile.go index 25271e1cf..76dec9d47 100644 --- a/internal/chart/v3/util/chartfile.go +++ b/internal/chart/v3/util/chartfile.go @@ -58,7 +58,7 @@ func SaveChartfile(filename string, cf *chart.Metadata) error { if err != nil { return err } - return os.WriteFile(filename, out, 0644) + return os.WriteFile(filename, out, 0o644) } // IsChartDir validate a chart directory. diff --git a/internal/chart/v3/util/coalesce.go b/internal/chart/v3/util/coalesce.go index caea2e119..704dd70c8 100644 --- a/internal/chart/v3/util/coalesce.go +++ b/internal/chart/v3/util/coalesce.go @@ -290,17 +290,19 @@ func coalesceTablesFullKey(printf printFn, dst, src map[string]interface{}, pref // values. for key, val := range src { fullkey := concatPrefix(prefix, key) - if dv, ok := dst[key]; ok && !merge && dv == nil { + dv, ok := dst[key] + switch { + case ok && !merge && dv == nil: delete(dst, key) - } else if !ok { + case !ok: dst[key] = val - } else if istable(val) { + case istable(val): if istable(dv) { coalesceTablesFullKey(printf, dv.(map[string]interface{}), val.(map[string]interface{}), fullkey, merge) } else { printf("warning: cannot overwrite table with non table for %s (%v)", fullkey, val) } - } else if istable(dv) && val != nil { + case istable(dv) && val != nil: printf("warning: destination for %s is a table. Ignoring non-table value (%v)", fullkey, val) } } diff --git a/internal/chart/v3/util/create.go b/internal/chart/v3/util/create.go index 72fed5955..891f6ba56 100644 --- a/internal/chart/v3/util/create.go +++ b/internal/chart/v3/util/create.go @@ -802,7 +802,7 @@ func Create(name, dir string) (string, error) { } } // Need to add the ChartsDir explicitly as it does not contain any file OOTB - if err := os.MkdirAll(filepath.Join(cdir, ChartsDir), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(cdir, ChartsDir), 0o755); err != nil { return cdir, err } return cdir, nil @@ -815,10 +815,10 @@ func transform(src, replacement string) []byte { } func writeFile(name string, content []byte) error { - if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil { return err } - return os.WriteFile(name, content, 0644) + return os.WriteFile(name, content, 0o644) } func validateChartName(name string) error { diff --git a/internal/chart/v3/util/dependencies.go b/internal/chart/v3/util/dependencies.go index bd5032ce4..76e8e1f71 100644 --- a/internal/chart/v3/util/dependencies.go +++ b/internal/chart/v3/util/dependencies.go @@ -39,7 +39,7 @@ func processDependencyConditions(reqs []*chart.Dependency, cvals Values, cpath s } for _, r := range reqs { for c := range strings.SplitSeq(strings.TrimSpace(r.Condition), ",") { - if len(c) > 0 { + if c != "" { // retrieve value vv, err := cvals.PathValue(cpath + c) if err == nil { diff --git a/internal/chart/v3/util/expand.go b/internal/chart/v3/util/expand.go index 6cbbeabf2..6c7662f04 100644 --- a/internal/chart/v3/util/expand.go +++ b/internal/chart/v3/util/expand.go @@ -71,11 +71,11 @@ func Expand(dir string, r io.Reader) error { // Make sure the necessary subdirs get created. basedir := filepath.Dir(outpath) - if err := os.MkdirAll(basedir, 0755); err != nil { + if err := os.MkdirAll(basedir, 0o755); err != nil { return err } - if err := os.WriteFile(outpath, file.Data, 0644); err != nil { + if err := os.WriteFile(outpath, file.Data, 0o644); err != nil { return err } } diff --git a/internal/chart/v3/util/save.go b/internal/chart/v3/util/save.go index 3125cc3c9..358cfde49 100644 --- a/internal/chart/v3/util/save.go +++ b/internal/chart/v3/util/save.go @@ -48,7 +48,7 @@ func SaveDir(c *chart.Chart, dest string) error { if fi, err := os.Stat(outdir); err == nil && !fi.IsDir() { return fmt.Errorf("file %s already exists and is not a directory", outdir) } - if err := os.MkdirAll(outdir, 0755); err != nil { + if err := os.MkdirAll(outdir, 0o755); err != nil { return err } @@ -114,7 +114,7 @@ func Save(c *chart.Chart, outDir string) (string, error) { dir := filepath.Dir(filename) if stat, err := os.Stat(dir); err != nil { if errors.Is(err, fs.ErrNotExist) { - if err2 := os.MkdirAll(dir, 0755); err2 != nil { + if err2 := os.MkdirAll(dir, 0o755); err2 != nil { return "", err2 } } else { @@ -229,7 +229,7 @@ func writeToTar(out *tar.Writer, name string, body []byte) error { // TODO: Do we need to create dummy parent directory names if none exist? h := &tar.Header{ Name: filepath.ToSlash(name), - Mode: 0644, + Mode: 0o644, Size: int64(len(body)), ModTime: time.Now(), } diff --git a/internal/chart/v3/util/save_test.go b/internal/chart/v3/util/save_test.go index 852675bb0..ec58e74fd 100644 --- a/internal/chart/v3/util/save_test.go +++ b/internal/chart/v3/util/save_test.go @@ -251,7 +251,7 @@ func TestSaveDir(t *testing.T) { tmp2 := t.TempDir() c.Metadata.Name = "../ahab" pth := filepath.Join(tmp2, "tmpcharts") - if err := os.MkdirAll(filepath.Join(pth), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(pth), 0o755); err != nil { t.Fatal(err) } diff --git a/internal/fileutil/fileutil_test.go b/internal/fileutil/fileutil_test.go index 92920d3c4..d612c0297 100644 --- a/internal/fileutil/fileutil_test.go +++ b/internal/fileutil/fileutil_test.go @@ -29,7 +29,7 @@ func TestAtomicWriteFile(t *testing.T) { testpath := filepath.Join(dir, "test") stringContent := "Test content" reader := bytes.NewReader([]byte(stringContent)) - mode := os.FileMode(0644) + mode := os.FileMode(0o644) err := AtomicWriteFile(testpath, reader, mode) if err != nil { diff --git a/internal/monocular/search.go b/internal/monocular/search.go index fcf04b7a4..afc1f978c 100644 --- a/internal/monocular/search.go +++ b/internal/monocular/search.go @@ -114,7 +114,7 @@ func (c *Client) Search(term string) ([]SearchResult, error) { p.RawQuery = "q=" + url.QueryEscape(term) // Create request - req, err := http.NewRequest(http.MethodGet, p.String(), nil) + req, err := http.NewRequest(http.MethodGet, p.String(), http.NoBody) if err != nil { return nil, err } diff --git a/internal/sympath/walk.go b/internal/sympath/walk.go index f67b9f1b9..812bb68ce 100644 --- a/internal/sympath/walk.go +++ b/internal/sympath/walk.go @@ -70,7 +70,7 @@ func symwalk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error { if err != nil { return fmt.Errorf("error evaluating symlink %s: %w", path, err) } - //This log message is to highlight a symlink that is being used within a chart, symlinks can be used for nefarious reasons. + // This log message is to highlight a symlink that is being used within a chart, symlinks can be used for nefarious reasons. slog.Info("found symbolic link in path. Contents of linked file included and used", "path", path, "resolved", resolved) if info, err = os.Lstat(resolved); err != nil { return err diff --git a/internal/sympath/walk_test.go b/internal/sympath/walk_test.go index 1eba8b996..6ef0f142c 100644 --- a/internal/sympath/walk_test.go +++ b/internal/sympath/walk_test.go @@ -92,7 +92,7 @@ func makeTree(t *testing.T) { fd.Close() } } else { - if err := os.Mkdir(path, 0770); err != nil { + if err := os.Mkdir(path, 0o770); err != nil { t.Fatalf("makeTree: %v", err) } } diff --git a/internal/test/test.go b/internal/test/test.go index 632bc72fd..2ad44ead3 100644 --- a/internal/test/test.go +++ b/internal/test/test.go @@ -49,7 +49,7 @@ func AssertGoldenString(t TestingT, actual, filename string) { } // AssertGoldenFile asserts that the content of the actual file matches the contents of the expected file -func AssertGoldenFile(t TestingT, actualFileName string, expectedFilename string) { +func AssertGoldenFile(t TestingT, actualFileName, expectedFilename string) { t.Helper() actual, err := os.ReadFile(actualFileName) @@ -87,7 +87,7 @@ func update(filename string, in []byte) error { if !*updateGolden { return nil } - return os.WriteFile(filename, normalize(in), 0666) + return os.WriteFile(filename, normalize(in), 0o666) } func normalize(in []byte) []byte { diff --git a/internal/third_party/dep/fs/fs.go b/internal/third_party/dep/fs/fs.go index 717eff04d..00b7d8f3f 100644 --- a/internal/third_party/dep/fs/fs.go +++ b/internal/third_party/dep/fs/fs.go @@ -192,7 +192,7 @@ func copyFile(src, dst string) (err error) { } // Check for write errors on Close - if err = out.Close(); err != nil { + if err := out.Close(); err != nil { return err } diff --git a/internal/third_party/dep/fs/fs_test.go b/internal/third_party/dep/fs/fs_test.go index 4c59d17fe..a904ae144 100644 --- a/internal/third_party/dep/fs/fs_test.go +++ b/internal/third_party/dep/fs/fs_test.go @@ -58,12 +58,12 @@ func TestRenameWithFallback(t *testing.T) { } srcpath = filepath.Join(dir, "a") - if err := os.MkdirAll(srcpath, 0777); err != nil { + if err := os.MkdirAll(srcpath, 0o777); err != nil { t.Fatal(err) } dstpath := filepath.Join(dir, "b") - if err := os.MkdirAll(dstpath, 0777); err != nil { + if err := os.MkdirAll(dstpath, 0o777); err != nil { t.Fatal(err) } @@ -76,7 +76,7 @@ func TestCopyDir(t *testing.T) { dir := t.TempDir() srcdir := filepath.Join(dir, "src") - if err := os.MkdirAll(srcdir, 0755); err != nil { + if err := os.MkdirAll(srcdir, 0o755); err != nil { t.Fatal(err) } @@ -93,7 +93,7 @@ func TestCopyDir(t *testing.T) { for i, file := range files { fn := filepath.Join(srcdir, file.path) dn := filepath.Dir(fn) - if err := os.MkdirAll(dn, 0755); err != nil { + if err := os.MkdirAll(dn, 0o755); err != nil { t.Fatal(err) } @@ -102,7 +102,7 @@ func TestCopyDir(t *testing.T) { t.Fatal(err) } - if _, err = fh.Write([]byte(file.contents)); err != nil { + if _, err = fh.WriteString(file.contents); err != nil { t.Fatal(err) } fh.Close() @@ -170,7 +170,7 @@ func TestCopyDirFail_SrcInaccessible(t *testing.T) { cleanup := setupInaccessibleDir(t, func(dir string) error { srcdir = filepath.Join(dir, "src") - return os.MkdirAll(srcdir, 0755) + return os.MkdirAll(srcdir, 0o755) }) defer cleanup() @@ -202,7 +202,7 @@ func TestCopyDirFail_DstInaccessible(t *testing.T) { dir := t.TempDir() srcdir = filepath.Join(dir, "src") - if err := os.MkdirAll(srcdir, 0755); err != nil { + if err := os.MkdirAll(srcdir, 0o755); err != nil { t.Fatal(err) } @@ -247,12 +247,12 @@ func TestCopyDirFail_DstExists(t *testing.T) { dir := t.TempDir() srcdir = filepath.Join(dir, "src") - if err = os.MkdirAll(srcdir, 0755); err != nil { + if err = os.MkdirAll(srcdir, 0o755); err != nil { t.Fatal(err) } dstdir = filepath.Join(dir, "dst") - if err = os.MkdirAll(dstdir, 0755); err != nil { + if err = os.MkdirAll(dstdir, 0o755); err != nil { t.Fatal(err) } @@ -288,7 +288,7 @@ func TestCopyDirFailOpen(t *testing.T) { dir := t.TempDir() srcdir = filepath.Join(dir, "src") - if err := os.MkdirAll(srcdir, 0755); err != nil { + if err := os.MkdirAll(srcdir, 0o755); err != nil { t.Fatal(err) } @@ -300,7 +300,7 @@ func TestCopyDirFailOpen(t *testing.T) { srcf.Close() // setup source file so that it cannot be read - if err = os.Chmod(srcfn, 0222); err != nil { + if err = os.Chmod(srcfn, 0o222); err != nil { t.Fatal(err) } @@ -320,7 +320,7 @@ func TestCopyFile(t *testing.T) { } want := "hello world" - if _, err := srcf.Write([]byte(want)); err != nil { + if _, err := srcf.WriteString(want); err != nil { t.Fatal(err) } srcf.Close() @@ -433,7 +433,7 @@ func TestCopyFileFail(t *testing.T) { cleanup := setupInaccessibleDir(t, func(dir string) error { dstdir = filepath.Join(dir, "dir") - return os.Mkdir(dstdir, 0777) + return os.Mkdir(dstdir, 0o777) }) defer cleanup() @@ -463,12 +463,12 @@ func setupInaccessibleDir(t *testing.T, op func(dir string) error) func() { subdir := filepath.Join(dir, "dir") cleanup := func() { - if err := os.Chmod(subdir, 0777); err != nil { + if err := os.Chmod(subdir, 0o777); err != nil { t.Error(err) } } - if err := os.Mkdir(subdir, 0777); err != nil { + if err := os.Mkdir(subdir, 0o777); err != nil { cleanup() t.Fatal(err) return nil @@ -480,7 +480,7 @@ func setupInaccessibleDir(t *testing.T, op func(dir string) error) func() { return nil } - if err := os.Chmod(subdir, 0666); err != nil { + if err := os.Chmod(subdir, 0o666); err != nil { cleanup() t.Fatal(err) return nil @@ -507,7 +507,7 @@ func TestIsDir(t *testing.T) { cleanup := setupInaccessibleDir(t, func(dir string) error { dn = filepath.Join(dir, "dir") - return os.Mkdir(dn, 0777) + return os.Mkdir(dn, 0o777) }) defer cleanup() @@ -554,7 +554,7 @@ func TestIsSymlink(t *testing.T) { dir := t.TempDir() dirPath := filepath.Join(dir, "directory") - if err := os.MkdirAll(dirPath, 0777); err != nil { + if err := os.MkdirAll(dirPath, 0o777); err != nil { t.Fatal(err) } @@ -582,9 +582,11 @@ func TestIsSymlink(t *testing.T) { cleanup := setupInaccessibleDir(t, func(dir string) error { inaccessibleFile = filepath.Join(dir, "file") - if fh, err := os.Create(inaccessibleFile); err != nil { + fh, err := os.Create(inaccessibleFile) + if err != nil { return err - } else if err = fh.Close(); err != nil { + } + if err := fh.Close(); err != nil { return err } diff --git a/pkg/action/action.go b/pkg/action/action.go index 69bcf4da2..b8b9e1323 100644 --- a/pkg/action/action.go +++ b/pkg/action/action.go @@ -291,9 +291,9 @@ func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Valu if includeCrds { for _, crd := range ch.CRDObjects() { if outputDir == "" { - fmt.Fprintf(b, "---\n# Source: %s\n%s\n", crd.Filename, string(crd.File.Data[:])) + fmt.Fprintf(b, "---\n# Source: %s\n%s\n", crd.Filename, string(crd.File.Data)) } else { - err = writeToFile(outputDir, crd.Filename, string(crd.File.Data[:]), fileWritten[crd.Filename]) + err = writeToFile(outputDir, crd.Filename, string(crd.File.Data), fileWritten[crd.Filename]) if err != nil { return hs, b, "", err } diff --git a/pkg/action/dependency_test.go b/pkg/action/dependency_test.go index 5be7bf5a9..3899c20fc 100644 --- a/pkg/action/dependency_test.go +++ b/pkg/action/dependency_test.go @@ -70,7 +70,7 @@ func TestDependencyStatus_Dashes(t *testing.T) { dir := t.TempDir() chartpath := filepath.Join(dir, "charts") - if err := os.MkdirAll(chartpath, 0700); err != nil { + if err := os.MkdirAll(chartpath, 0o700); err != nil { t.Fatal(err) } @@ -104,7 +104,7 @@ func TestStatArchiveForStatus(t *testing.T) { dir := t.TempDir() chartpath := filepath.Join(dir, "charts") - if err := os.MkdirAll(chartpath, 0700); err != nil { + if err := os.MkdirAll(chartpath, 0o700); err != nil { t.Fatal(err) } diff --git a/pkg/action/install.go b/pkg/action/install.go index d8efa5d5d..3a7fd34ab 100644 --- a/pkg/action/install.go +++ b/pkg/action/install.go @@ -63,7 +63,7 @@ import ( // since there can be filepath in front of it. const notesFileSuffix = "NOTES.txt" -const defaultDirectoryPermission = 0755 +const defaultDirectoryPermission = 0o755 // Install performs an installation operation. type Install struct { @@ -427,7 +427,7 @@ func (i *Install) RunWithContext(ctx context.Context, chrt *chart.Chart, vals ma return rel, err } -func (i *Install) performInstallCtx(ctx context.Context, rel *release.Release, toBeAdopted kube.ResourceList, resources kube.ResourceList) (*release.Release, error) { +func (i *Install) performInstallCtx(ctx context.Context, rel *release.Release, toBeAdopted, resources kube.ResourceList) (*release.Release, error) { type Msg struct { r *release.Release e error @@ -455,7 +455,7 @@ func (i *Install) isDryRun() bool { return false } -func (i *Install) performInstall(rel *release.Release, toBeAdopted kube.ResourceList, resources kube.ResourceList) (*release.Release, error) { +func (i *Install) performInstall(rel *release.Release, toBeAdopted, resources kube.ResourceList) (*release.Release, error) { var err error // pre-install hooks if !i.DisableHooks { @@ -500,7 +500,7 @@ func (i *Install) performInstall(rel *release.Release, toBeAdopted kube.Resource } } - if len(i.Description) > 0 { + if i.Description != "" { rel.SetStatus(release.StatusDeployed, i.Description) } else { rel.SetStatus(release.StatusDeployed, "Install complete") @@ -621,8 +621,8 @@ func (i *Install) replaceRelease(rel *release.Release) error { } // write the to /. controls if the file is created or content will be appended -func writeToFile(outputDir string, name string, data string, appendData bool) error { - outfileName := strings.Join([]string{outputDir, name}, string(filepath.Separator)) +func writeToFile(outputDir, name, data string, appendData bool) error { + outfileName := outputDir + string(filepath.Separator) + name err := ensureDirectoryForFile(outfileName) if err != nil { @@ -648,7 +648,7 @@ func writeToFile(outputDir string, name string, data string, appendData bool) er func createOrOpenFile(filename string, appendData bool) (*os.File, error) { if appendData { - return os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600) + return os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0o600) } return os.Create(filename) } @@ -864,7 +864,7 @@ func (c *ChartPathOptions) LocateChart(name string, settings *cli.EnvSettings) ( dl.Options = append(dl.Options, getter.WithBasicAuth(c.Username, c.Password)) } - if err := os.MkdirAll(settings.RepositoryCache, 0755); err != nil { + if err := os.MkdirAll(settings.RepositoryCache, 0o755); err != nil { return "", err } diff --git a/pkg/action/list.go b/pkg/action/list.go index 82500582f..35d12d618 100644 --- a/pkg/action/list.go +++ b/pkg/action/list.go @@ -173,7 +173,7 @@ func (l *List) Run() ([]*release.Release, error) { } if results == nil { - return results, nil + return nil, nil } // by definition, superseded releases are never shown if diff --git a/pkg/action/package.go b/pkg/action/package.go index e57ce4921..a10d39cc5 100644 --- a/pkg/action/package.go +++ b/pkg/action/package.go @@ -148,7 +148,7 @@ func (p *Package) Clearsign(filename string) error { return err } - return os.WriteFile(filename+".prov", []byte(sig), 0644) + return os.WriteFile(filename+".prov", []byte(sig), 0o644) } // promptUser implements provenance.PassphraseFetcher diff --git a/pkg/action/package_test.go b/pkg/action/package_test.go index 12bea10dd..bf6f9bcc3 100644 --- a/pkg/action/package_test.go +++ b/pkg/action/package_test.go @@ -90,7 +90,7 @@ func TestPassphraseFileFetcher_WithStdinAndMultipleFetches(t *testing.T) { passphrase := "secret-from-stdin" go func() { - w.Write([]byte(passphrase + "\n")) + w.WriteString(passphrase + "\n") }() for i := 0; i < 4; i++ { diff --git a/pkg/action/pull.go b/pkg/action/pull.go index a2f53af0d..6e471c2c4 100644 --- a/pkg/action/pull.go +++ b/pkg/action/pull.go @@ -160,7 +160,7 @@ func (p *Pull) Run(chartRef string) (string, error) { } if _, err := os.Stat(udCheck); err != nil { - if err := os.MkdirAll(udCheck, 0755); err != nil { + if err := os.MkdirAll(udCheck, 0o755); err != nil { return out.String(), fmt.Errorf("failed to untar (mkdir): %w", err) } } else { diff --git a/pkg/action/push.go b/pkg/action/push.go index 35472415c..8d9c2291f 100644 --- a/pkg/action/push.go +++ b/pkg/action/push.go @@ -90,7 +90,7 @@ func NewPushWithOpts(opts ...PushOpt) *Push { } // Run executes 'helm push' against the given chart archive. -func (p *Push) Run(chartRef string, remote string) (string, error) { +func (p *Push) Run(chartRef, remote string) (string, error) { var out strings.Builder c := uploader.ChartUploader{ diff --git a/pkg/action/registry_login.go b/pkg/action/registry_login.go index fd9d4bfc6..23bbfd02f 100644 --- a/pkg/action/registry_login.go +++ b/pkg/action/registry_login.go @@ -82,7 +82,7 @@ func NewRegistryLogin(cfg *Configuration) *RegistryLogin { } // Run executes the registry login operation -func (a *RegistryLogin) Run(_ io.Writer, hostname string, username string, password string, opts ...RegistryLoginOpt) error { +func (a *RegistryLogin) Run(_ io.Writer, hostname, username, password string, opts ...RegistryLoginOpt) error { for _, opt := range opts { if err := opt(a); err != nil { return err diff --git a/pkg/action/show_test.go b/pkg/action/show_test.go index b1c5d6164..4eea862c9 100644 --- a/pkg/action/show_test.go +++ b/pkg/action/show_test.go @@ -76,7 +76,7 @@ func TestShowNoValues(t *testing.T) { t.Fatal(err) } - if len(output) != 0 { + if output != "" { t.Errorf("expected empty values buffer, got %s", output) } } diff --git a/pkg/action/uninstall.go b/pkg/action/uninstall.go index 61e10b2c8..9dbbd63e3 100644 --- a/pkg/action/uninstall.go +++ b/pkg/action/uninstall.go @@ -146,7 +146,7 @@ func (u *Uninstall) Run(name string) (*release.UninstallReleaseResponse, error) } rel.Info.Status = release.StatusUninstalled - if len(u.Description) > 0 { + if u.Description != "" { rel.Info.Description = u.Description } else { rel.Info.Description = "Uninstallation complete" diff --git a/pkg/action/upgrade.go b/pkg/action/upgrade.go index 0567c8de2..16d773f68 100644 --- a/pkg/action/upgrade.go +++ b/pkg/action/upgrade.go @@ -300,7 +300,7 @@ func (u *Upgrade) prepareUpgrade(name string, chart *chart.Chart, vals map[strin Labels: mergeCustomLabels(lastRelease.Labels, u.Labels), } - if len(notesTxt) > 0 { + if notesTxt != "" { upgradedRelease.Info.Notes = notesTxt } err = validateManifest(u.cfg.KubeClient, manifestDoc.Bytes(), !u.DisableOpenAPIValidation) @@ -364,7 +364,7 @@ func (u *Upgrade) performUpgrade(ctx context.Context, originalRelease, upgradedR // Run if it is a dry run if u.isDryRun() { slog.Debug("dry run for release", "name", upgradedRelease.Name) - if len(u.Description) > 0 { + if u.Description != "" { upgradedRelease.Info.Description = u.Description } else { upgradedRelease.Info.Description = "Dry run complete" @@ -414,7 +414,7 @@ func (u *Upgrade) handleContext(ctx context.Context, done chan interface{}, c ch return } } -func (u *Upgrade) releasingUpgrade(c chan<- resultMessage, upgradedRelease *release.Release, current kube.ResourceList, target kube.ResourceList, originalRelease *release.Release) { +func (u *Upgrade) releasingUpgrade(c chan<- resultMessage, upgradedRelease *release.Release, current, target kube.ResourceList, originalRelease *release.Release) { // pre-upgrade hooks if !u.DisableHooks { @@ -465,7 +465,7 @@ func (u *Upgrade) releasingUpgrade(c chan<- resultMessage, upgradedRelease *rele u.cfg.recordRelease(originalRelease) upgradedRelease.Info.Status = release.StatusDeployed - if len(u.Description) > 0 { + if u.Description != "" { upgradedRelease.Info.Description = u.Description } else { upgradedRelease.Info.Description = "Upgrade complete" diff --git a/pkg/action/validate_test.go b/pkg/action/validate_test.go index 3efecd6ff..1e8061326 100644 --- a/pkg/action/validate_test.go +++ b/pkg/action/validate_test.go @@ -73,7 +73,7 @@ func newMissingDeployment(name, namespace string) *resource.Info { return info } -func newDeploymentWithOwner(name, namespace string, labels map[string]string, annotations map[string]string) *resource.Info { +func newDeploymentWithOwner(name, namespace string, labels, annotations map[string]string) *resource.Info { obj := &appsv1.Deployment{ ObjectMeta: v1.ObjectMeta{ Name: name, diff --git a/pkg/chart/v2/loader/directory.go b/pkg/chart/v2/loader/directory.go index 4f72925dc..fd398d086 100644 --- a/pkg/chart/v2/loader/directory.go +++ b/pkg/chart/v2/loader/directory.go @@ -113,7 +113,7 @@ func LoadDir(dir string) (*chart.Chart, error) { files = append(files, &BufferedFile{Name: n, Data: data}) return nil } - if err = sympath.Walk(topdir, walk); err != nil { + if err := sympath.Walk(topdir, walk); err != nil { return c, err } diff --git a/pkg/chart/v2/loader/load_test.go b/pkg/chart/v2/loader/load_test.go index 41154421c..05fb8d7cb 100644 --- a/pkg/chart/v2/loader/load_test.go +++ b/pkg/chart/v2/loader/load_test.go @@ -415,7 +415,7 @@ func TestLoadInvalidArchive(t *testing.T) { h := &tar.Header{ Name: internalPath, - Mode: 0755, + Mode: 0o755, Size: int64(len(body)), ModTime: time.Now(), } diff --git a/pkg/chart/v2/util/chartfile.go b/pkg/chart/v2/util/chartfile.go index 1f9c712b2..525f1efd4 100644 --- a/pkg/chart/v2/util/chartfile.go +++ b/pkg/chart/v2/util/chartfile.go @@ -67,7 +67,7 @@ func SaveChartfile(filename string, cf *chart.Metadata) error { if err != nil { return err } - return os.WriteFile(filename, out, 0644) + return os.WriteFile(filename, out, 0o644) } // IsChartDir validate a chart directory. diff --git a/pkg/chart/v2/util/coalesce.go b/pkg/chart/v2/util/coalesce.go index a3e0f5ae8..7aa9fc3af 100644 --- a/pkg/chart/v2/util/coalesce.go +++ b/pkg/chart/v2/util/coalesce.go @@ -290,17 +290,19 @@ func coalesceTablesFullKey(printf printFn, dst, src map[string]interface{}, pref // values. for key, val := range src { fullkey := concatPrefix(prefix, key) - if dv, ok := dst[key]; ok && !merge && dv == nil { + dv, ok := dst[key] + switch { + case ok && !merge && dv == nil: delete(dst, key) - } else if !ok { + case !ok: dst[key] = val - } else if istable(val) { + case istable(val): if istable(dv) { coalesceTablesFullKey(printf, dv.(map[string]interface{}), val.(map[string]interface{}), fullkey, merge) } else { printf("warning: cannot overwrite table with non table for %s (%v)", fullkey, val) } - } else if istable(dv) && val != nil { + case istable(dv) && val != nil: printf("warning: destination for %s is a table. Ignoring non-table value (%v)", fullkey, val) } } diff --git a/pkg/chart/v2/util/create.go b/pkg/chart/v2/util/create.go index 93699e0fd..2b8afcaac 100644 --- a/pkg/chart/v2/util/create.go +++ b/pkg/chart/v2/util/create.go @@ -802,7 +802,7 @@ func Create(name, dir string) (string, error) { } } // Need to add the ChartsDir explicitly as it does not contain any file OOTB - if err := os.MkdirAll(filepath.Join(cdir, ChartsDir), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(cdir, ChartsDir), 0o755); err != nil { return cdir, err } return cdir, nil @@ -815,10 +815,10 @@ func transform(src, replacement string) []byte { } func writeFile(name string, content []byte) error { - if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil { return err } - return os.WriteFile(name, content, 0644) + return os.WriteFile(name, content, 0o644) } func validateChartName(name string) error { diff --git a/pkg/chart/v2/util/dependencies.go b/pkg/chart/v2/util/dependencies.go index f34144526..efb6b142e 100644 --- a/pkg/chart/v2/util/dependencies.go +++ b/pkg/chart/v2/util/dependencies.go @@ -39,7 +39,7 @@ func processDependencyConditions(reqs []*chart.Dependency, cvals Values, cpath s } for _, r := range reqs { for c := range strings.SplitSeq(strings.TrimSpace(r.Condition), ",") { - if len(c) > 0 { + if c != "" { // retrieve value vv, err := cvals.PathValue(cpath + c) if err == nil { diff --git a/pkg/chart/v2/util/expand.go b/pkg/chart/v2/util/expand.go index 9d08571ed..daa42b629 100644 --- a/pkg/chart/v2/util/expand.go +++ b/pkg/chart/v2/util/expand.go @@ -71,11 +71,11 @@ func Expand(dir string, r io.Reader) error { // Make sure the necessary subdirs get created. basedir := filepath.Dir(outpath) - if err := os.MkdirAll(basedir, 0755); err != nil { + if err := os.MkdirAll(basedir, 0o755); err != nil { return err } - if err := os.WriteFile(outpath, file.Data, 0644); err != nil { + if err := os.WriteFile(outpath, file.Data, 0o644); err != nil { return err } } diff --git a/pkg/chart/v2/util/save.go b/pkg/chart/v2/util/save.go index 624a5b562..7737dd730 100644 --- a/pkg/chart/v2/util/save.go +++ b/pkg/chart/v2/util/save.go @@ -48,7 +48,7 @@ func SaveDir(c *chart.Chart, dest string) error { if fi, err := os.Stat(outdir); err == nil && !fi.IsDir() { return fmt.Errorf("file %s already exists and is not a directory", outdir) } - if err := os.MkdirAll(outdir, 0755); err != nil { + if err := os.MkdirAll(outdir, 0o755); err != nil { return err } @@ -114,7 +114,7 @@ func Save(c *chart.Chart, outDir string) (string, error) { dir := filepath.Dir(filename) if stat, err := os.Stat(dir); err != nil { if errors.Is(err, fs.ErrNotExist) { - if err2 := os.MkdirAll(dir, 0755); err2 != nil { + if err2 := os.MkdirAll(dir, 0o755); err2 != nil { return "", err2 } } else { @@ -241,7 +241,7 @@ func writeToTar(out *tar.Writer, name string, body []byte) error { // TODO: Do we need to create dummy parent directory names if none exist? h := &tar.Header{ Name: filepath.ToSlash(name), - Mode: 0644, + Mode: 0o644, Size: int64(len(body)), ModTime: time.Now(), } diff --git a/pkg/chart/v2/util/save_test.go b/pkg/chart/v2/util/save_test.go index ff96331b5..21d40fe8b 100644 --- a/pkg/chart/v2/util/save_test.go +++ b/pkg/chart/v2/util/save_test.go @@ -254,7 +254,7 @@ func TestSaveDir(t *testing.T) { tmp2 := t.TempDir() c.Metadata.Name = "../ahab" pth := filepath.Join(tmp2, "tmpcharts") - if err := os.MkdirAll(filepath.Join(pth), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(pth), 0o755); err != nil { t.Fatal(err) } diff --git a/pkg/cli/values/options.go b/pkg/cli/values/options.go index cd65fa885..364fc0d5e 100644 --- a/pkg/cli/values/options.go +++ b/pkg/cli/values/options.go @@ -62,7 +62,7 @@ func (opts *Options) MergeValues(p getter.Providers) (map[string]interface{}, er // User specified a value via --set-json for _, value := range opts.JSONValues { trimmedValue := strings.TrimSpace(value) - if len(trimmedValue) > 0 && trimmedValue[0] == '{' { + if trimmedValue != "" && trimmedValue[0] == '{' { // If value is JSON object format, parse it as map var jsonMap map[string]interface{} if err := json.Unmarshal([]byte(trimmedValue), &jsonMap); err != nil { diff --git a/pkg/cli/values/options_test.go b/pkg/cli/values/options_test.go index 4dbc709f1..cc41279c6 100644 --- a/pkg/cli/values/options_test.go +++ b/pkg/cli/values/options_test.go @@ -91,7 +91,7 @@ func TestReadFile(t *testing.T) { tmpDir := t.TempDir() filePath := filepath.Join(tmpDir, "test.txt") content := []byte("local file content") - err := os.WriteFile(filePath, content, 0644) + err := os.WriteFile(filePath, content, 0o644) if err != nil { t.Fatal(err) } @@ -155,7 +155,7 @@ func TestReadFile(t *testing.T) { fileName := "ftp_file.txt" // Valid filename for filesystem filePath := filepath.Join(tmpDir, fileName) content := []byte("local fallback content") - err := os.WriteFile(filePath, content, 0644) + err := os.WriteFile(filePath, content, 0o644) if err != nil { t.Fatal(err) } diff --git a/pkg/cmd/docs.go b/pkg/cmd/docs.go index 7fae60743..6463170b9 100644 --- a/pkg/cmd/docs.go +++ b/pkg/cmd/docs.go @@ -86,7 +86,7 @@ func (o *docsOptions) run(_ io.Writer) error { base := filepath.Base(filename) name := strings.TrimSuffix(base, path.Ext(base)) title := cases.Title(language.Und, cases.NoLower).String(strings.ReplaceAll(name, "_", " ")) - return fmt.Sprintf("---\ntitle: \"%s\"\n---\n\n", title) + return fmt.Sprintf("---\ntitle: %q\n---\n\n", title) } return doc.GenMarkdownTreeCustom(o.topCmd, o.dest, hdrFunc, standardLinks) diff --git a/pkg/cmd/flags.go b/pkg/cmd/flags.go index 74c3c8352..aa21e1121 100644 --- a/pkg/cmd/flags.go +++ b/pkg/cmd/flags.go @@ -246,7 +246,7 @@ func (p *postRendererArgsSlice) GetSlice() []string { return p.options.args } -func compVersionFlag(chartRef string, _ string) ([]string, cobra.ShellCompDirective) { +func compVersionFlag(chartRef, _ string) ([]string, cobra.ShellCompDirective) { chartInfo := strings.Split(chartRef, "/") if len(chartInfo) != 2 { return nil, cobra.ShellCompDirectiveNoFileComp diff --git a/pkg/cmd/get_notes.go b/pkg/cmd/get_notes.go index ae79d8bcc..5fddbd8ca 100644 --- a/pkg/cmd/get_notes.go +++ b/pkg/cmd/get_notes.go @@ -50,7 +50,7 @@ func newGetNotesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { if err != nil { return err } - if len(res.Info.Notes) > 0 { + if res.Info.Notes != "" { fmt.Fprintf(out, "NOTES:\n%s\n", res.Info.Notes) } return nil diff --git a/pkg/cmd/list.go b/pkg/cmd/list.go index 55d828036..a246611d3 100644 --- a/pkg/cmd/list.go +++ b/pkg/cmd/list.go @@ -150,7 +150,7 @@ type releaseListWriter struct { noColor bool } -func newReleaseListWriter(releases []*release.Release, timeFormat string, noHeaders bool, noColor bool) *releaseListWriter { +func newReleaseListWriter(releases []*release.Release, timeFormat string, noHeaders, noColor bool) *releaseListWriter { // Initialize the array so no results returns an empty array instead of null elements := make([]releaseElement, 0, len(releases)) for _, r := range releases { diff --git a/pkg/cmd/load_plugins.go b/pkg/cmd/load_plugins.go index 5c7f618eb..d15fa57c5 100644 --- a/pkg/cmd/load_plugins.go +++ b/pkg/cmd/load_plugins.go @@ -121,7 +121,7 @@ func processParent(cmd *cobra.Command, args []string) ([]string, error) { // This function is used to setup the environment for the plugin and then // call the executable specified by the parameter 'main' -func callPluginExecutable(pluginName string, main string, argv []string, out io.Writer) error { +func callPluginExecutable(pluginName, main string, argv []string, out io.Writer) error { env := os.Environ() for k, v := range settings.EnvVars() { env = append(env, fmt.Sprintf("%s=%s", k, v)) @@ -203,8 +203,7 @@ type pluginCommand struct { // and add the dynamic completion hook to call the optional plugin.complete func loadCompletionForPlugin(pluginCmd *cobra.Command, plugin *plugin.Plugin) { // Parse the yaml file providing the plugin's sub-commands and flags - cmds, err := loadFile(strings.Join( - []string{plugin.Dir, pluginStaticCompletionFile}, string(filepath.Separator))) + cmds, err := loadFile(plugin.Dir + string(filepath.Separator) + pluginStaticCompletionFile) if err != nil { // The file could be missing or invalid. No static completion for this plugin. @@ -228,7 +227,7 @@ func addPluginCommands(plugin *plugin.Plugin, baseCmd *cobra.Command, cmds *plug return } - if len(cmds.Name) == 0 { + if cmds.Name == "" { // Missing name for a command if settings.Debug { log.Output(2, fmt.Sprintf("[info] sub-command name field missing for %s", baseCmd.CommandPath())) @@ -329,7 +328,7 @@ func pluginDynamicComp(plug *plugin.Plugin, cmd *cobra.Command, args []string, t } // We will call the dynamic completion script of the plugin - main := strings.Join([]string{plug.Dir, pluginDynamicCompletionExecutable}, string(filepath.Separator)) + main := plug.Dir + string(filepath.Separator) + pluginDynamicCompletionExecutable // We must include all sub-commands passed on the command-line. // To do that, we pass-in the entire CommandPath, except the first two elements @@ -352,7 +351,7 @@ func pluginDynamicComp(plug *plugin.Plugin, cmd *cobra.Command, args []string, t var completions []string for comp := range strings.SplitSeq(buf.String(), "\n") { // Remove any empty lines - if len(comp) > 0 { + if comp != "" { completions = append(completions, comp) } } diff --git a/pkg/cmd/package_test.go b/pkg/cmd/package_test.go index db4a2523a..5705c9b9e 100644 --- a/pkg/cmd/package_test.go +++ b/pkg/cmd/package_test.go @@ -119,7 +119,7 @@ func TestPackage(t *testing.T) { } // This is an unfortunate byproduct of the tmpdir - if v, ok := tt.flags["keyring"]; ok && len(v) > 0 { + if v, ok := tt.flags["keyring"]; ok && v != "" { tt.flags["keyring"] = filepath.Join(origDir, v) } @@ -147,7 +147,7 @@ func TestPackage(t *testing.T) { t.Fatalf("%q: expected error %q, got %q", tt.name, tt.expect, err) } - if len(tt.hasfile) > 0 { + if tt.hasfile != "" { if fi, err := os.Stat(tt.hasfile); err != nil { t.Errorf("%q: expected file %q, got err %q", tt.name, tt.hasfile, err) } else if fi.Size() == 0 { diff --git a/pkg/cmd/plugin.go b/pkg/cmd/plugin.go index a2bb838df..22e5ad288 100644 --- a/pkg/cmd/plugin.go +++ b/pkg/cmd/plugin.go @@ -52,9 +52,9 @@ func runHook(p *plugin.Plugin, event string) error { cmds := p.Metadata.PlatformHooks[event] expandArgs := true - if len(cmds) == 0 && len(p.Metadata.Hooks) > 0 { - cmd := p.Metadata.Hooks[event] - if len(cmd) > 0 { + if len(cmds) == 0 && len(p.Metadata.Hooks) > 0 { //nolint:staticcheck + cmd := p.Metadata.Hooks[event] //nolint:staticcheck + if cmd != "" { cmds = []plugin.PlatformCommand{{Command: "sh", Args: []string{"-c", cmd}}} expandArgs = false } diff --git a/pkg/cmd/plugin_test.go b/pkg/cmd/plugin_test.go index 74f7a276a..0a6c459f3 100644 --- a/pkg/cmd/plugin_test.go +++ b/pkg/cmd/plugin_test.go @@ -305,7 +305,7 @@ func checkCommand(t *testing.T, plugins []*cobra.Command, tests []staticCompleti var pflags []string pp.LocalFlags().VisitAll(func(flag *pflag.Flag) { pflags = append(pflags, flag.Name) - if len(flag.Shorthand) > 0 && flag.Shorthand != flag.Name { + if flag.Shorthand != "" && flag.Shorthand != flag.Name { pflags = append(pflags, flag.Shorthand) } }) diff --git a/pkg/cmd/pull_test.go b/pkg/cmd/pull_test.go index c30c94b49..fb38f89c3 100644 --- a/pkg/cmd/pull_test.go +++ b/pkg/cmd/pull_test.go @@ -220,7 +220,7 @@ func TestPullCmd(t *testing.T) { } if tt.existDir != "" { file := filepath.Join(outdir, tt.existDir) - err := os.Mkdir(file, 0755) + err := os.Mkdir(file, 0o755) if err != nil { t.Fatal(err) } @@ -331,7 +331,7 @@ func TestPullWithCredentialsCmd(t *testing.T) { } if tt.existDir != "" { file := filepath.Join(outdir, tt.existDir) - err := os.Mkdir(file, 0755) + err := os.Mkdir(file, 0o755) if err != nil { t.Fatal(err) } diff --git a/pkg/cmd/registry_login.go b/pkg/cmd/registry_login.go index 1350fb244..605717e22 100644 --- a/pkg/cmd/registry_login.go +++ b/pkg/cmd/registry_login.go @@ -91,19 +91,20 @@ func newRegistryLoginCmd(cfg *action.Configuration, out io.Writer) *cobra.Comman } // Adapted from https://github.com/oras-project/oras -func getUsernamePassword(usernameOpt string, passwordOpt string, passwordFromStdinOpt bool) (string, string, error) { +func getUsernamePassword(usernameOpt, passwordOpt string, passwordFromStdinOpt bool) (string, string, error) { var err error username := usernameOpt password := passwordOpt - if passwordFromStdinOpt { + switch { + case passwordFromStdinOpt: passwordFromStdin, err := io.ReadAll(os.Stdin) if err != nil { return "", "", err } password = strings.TrimSuffix(string(passwordFromStdin), "\n") password = strings.TrimSuffix(password, "\r") - } else if password == "" { + case password == "": if username == "" { username, err = readLine("Username: ", false) if err != nil { @@ -126,7 +127,7 @@ func getUsernamePassword(usernameOpt string, passwordOpt string, passwordFromStd return "", "", errors.New("password required") } } - } else { + default: slog.Warn("using --password via the CLI is insecure. Use --password-stdin") } diff --git a/pkg/cmd/repo_add.go b/pkg/cmd/repo_add.go index 187234486..a8c16d32a 100644 --- a/pkg/cmd/repo_add.go +++ b/pkg/cmd/repo_add.go @@ -121,7 +121,7 @@ func (o *repoAddOptions) run(out io.Writer) error { // Acquire a file lock for process synchronization repoFileExt := filepath.Ext(o.repoFile) var lockPath string - if len(repoFileExt) > 0 && len(repoFileExt) < len(o.repoFile) { + if repoFileExt != "" && len(repoFileExt) < len(o.repoFile) { lockPath = strings.TrimSuffix(o.repoFile, repoFileExt) + ".lock" } else { lockPath = o.repoFile + ".lock" diff --git a/pkg/cmd/repo_add_test.go b/pkg/cmd/repo_add_test.go index aa6c4eaad..7e01f81b9 100644 --- a/pkg/cmd/repo_add_test.go +++ b/pkg/cmd/repo_add_test.go @@ -270,7 +270,7 @@ func TestRepoAddWithPasswordFromStdin(t *testing.T) { t.Errorf("unexpected error, got '%v'", err) } - if !strings.Contains(result, fmt.Sprintf("\"%s\" has been added to your repositories", testName)) { + if !strings.Contains(result, fmt.Sprintf("%q has been added to your repositories", testName)) { t.Errorf("Repo was not successfully added. Output: %s", result) } } diff --git a/pkg/cmd/repo_remove.go b/pkg/cmd/repo_remove.go index d0a3aa205..92960f577 100644 --- a/pkg/cmd/repo_remove.go +++ b/pkg/cmd/repo_remove.go @@ -68,7 +68,7 @@ func (o *repoRemoveOptions) run(out io.Writer) error { if !r.Remove(name) { return fmt.Errorf("no repo named %q found", name) } - if err := r.WriteFile(o.repoFile, 0600); err != nil { + if err := r.WriteFile(o.repoFile, 0o600); err != nil { return err } diff --git a/pkg/cmd/repo_remove_test.go b/pkg/cmd/repo_remove_test.go index bd8757812..27aad8a21 100644 --- a/pkg/cmd/repo_remove_test.go +++ b/pkg/cmd/repo_remove_test.go @@ -140,7 +140,7 @@ func TestRepoRemove(t *testing.T) { } } -func createCacheFiles(rootDir string, repoName string) (cacheIndexFile string, cacheChartsFile string) { +func createCacheFiles(rootDir, repoName string) (cacheIndexFile, cacheChartsFile string) { cacheIndexFile = filepath.Join(rootDir, helmpath.CacheIndexFile(repoName)) mf, _ := os.Create(cacheIndexFile) mf.Close() @@ -152,7 +152,7 @@ func createCacheFiles(rootDir string, repoName string) (cacheIndexFile string, c return cacheIndexFile, cacheChartsFile } -func testCacheFiles(t *testing.T, cacheIndexFile string, cacheChartsFile string, repoName string) { +func testCacheFiles(t *testing.T, cacheIndexFile, cacheChartsFile, repoName string) { t.Helper() if _, err := os.Stat(cacheIndexFile); err == nil { t.Errorf("Error cache index file was not removed for repository %s", repoName) diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index f43ce7abe..0832f3193 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -227,7 +227,7 @@ func newRootCmdWithConfig(actionConfig *action.Configuration, out io.Writer, arg cobra.CompDebugln("About to get the different kube-contexts", settings.Debug) loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() - if len(settings.KubeConfig) > 0 { + if settings.KubeConfig != "" { loadingRules = &clientcmd.ClientConfigLoadingRules{ExplicitPath: settings.KubeConfig} } if config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( diff --git a/pkg/cmd/search_repo.go b/pkg/cmd/search_repo.go index dffa0d1c4..499152f60 100644 --- a/pkg/cmd/search_repo.go +++ b/pkg/cmd/search_repo.go @@ -194,7 +194,7 @@ func (o *searchRepoOptions) buildIndex() (*search.Index, error) { continue } - i.AddRepo(n, ind, o.versions || len(o.version) > 0) + i.AddRepo(n, ind, o.versions || o.version != "") } return i, nil } @@ -268,7 +268,7 @@ func (r *repoSearchWriter) encodeByFormat(out io.Writer, format output.Format) e } // Provides the list of charts that are part of the specified repo, and that starts with 'prefix'. -func compListChartsOfRepo(repoName string, prefix string) []string { +func compListChartsOfRepo(repoName, prefix string) []string { var charts []string path := filepath.Join(settings.RepositoryCache, helmpath.CacheChartsFile(repoName)) @@ -361,7 +361,7 @@ func compListCharts(toComplete string, includeFiles bool) ([]string, cobra.Shell // 2- If there is some input from the user (or else we will end up // listing the entire content of the current directory which will // be too many choices for the user to find the real repos) - if includeFiles && len(completions) > 0 && len(toComplete) > 0 { + if includeFiles && len(completions) > 0 && toComplete != "" { if files, err := os.ReadDir("."); err == nil { for _, file := range files { if strings.HasPrefix(file.Name(), toComplete) { @@ -375,22 +375,22 @@ func compListCharts(toComplete string, includeFiles bool) ([]string, cobra.Shell // If the user didn't provide any input to completion, // we provide a hint that a path can also be used - if includeFiles && len(toComplete) == 0 { + if includeFiles && toComplete == "" { completions = append(completions, "./\tRelative path prefix to local chart", "/\tAbsolute path prefix to local chart") } cobra.CompDebugln(fmt.Sprintf("Completions after checking empty input: %v", completions), settings.Debug) directive := cobra.ShellCompDirectiveDefault if noFile { - directive = directive | cobra.ShellCompDirectiveNoFileComp + directive |= cobra.ShellCompDirectiveNoFileComp } if noSpace { - directive = directive | cobra.ShellCompDirectiveNoSpace + directive |= cobra.ShellCompDirectiveNoSpace } if !includeFiles { // If we should not include files in the completions, // we should disable file completion - directive = directive | cobra.ShellCompDirectiveNoFileComp + directive |= cobra.ShellCompDirectiveNoFileComp } return completions, directive } diff --git a/pkg/cmd/show_test.go b/pkg/cmd/show_test.go index ab8cafc37..ae630e226 100644 --- a/pkg/cmd/show_test.go +++ b/pkg/cmd/show_test.go @@ -73,7 +73,6 @@ func TestShowPreReleaseChart(t *testing.T) { filepath.Join(outdir, "repositories.yaml"), outdir, ) - //_, out, err := executeActionCommand(cmd) _, _, err := executeActionCommand(cmd) if err != nil { if tt.fail { diff --git a/pkg/cmd/status.go b/pkg/cmd/status.go index aa836f9f3..91b7d9de6 100644 --- a/pkg/cmd/status.go +++ b/pkg/cmd/status.go @@ -220,7 +220,7 @@ func (s statusPrinter) WriteTable(out io.Writer) error { } // Hide notes from output - option in install and upgrades - if !s.hideNotes && len(s.release.Info.Notes) > 0 { + if !s.hideNotes && s.release.Info.Notes != "" { _, _ = fmt.Fprintf(out, "NOTES:\n%s\n", strings.TrimSpace(s.release.Info.Notes)) } return nil diff --git a/pkg/cmd/template.go b/pkg/cmd/template.go index ac20a45b3..3fea2e358 100644 --- a/pkg/cmd/template.go +++ b/pkg/cmd/template.go @@ -217,8 +217,8 @@ func isTestHook(h *release.Hook) bool { // bug introduced by #8156. As part of the todo to refactor renderResources // this duplicate code should be removed. It is added here so that the API // surface area is as minimally impacted as possible in fixing the issue. -func writeToFile(outputDir string, name string, data string, appendData bool) error { - outfileName := strings.Join([]string{outputDir, name}, string(filepath.Separator)) +func writeToFile(outputDir, name, data string, appendData bool) error { + outfileName := outputDir + string(filepath.Separator) + name err := ensureDirectoryForFile(outfileName) if err != nil { @@ -244,7 +244,7 @@ func writeToFile(outputDir string, name string, data string, appendData bool) er func createOrOpenFile(filename string, appendData bool) (*os.File, error) { if appendData { - return os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600) + return os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0o600) } return os.Create(filename) } @@ -256,5 +256,5 @@ func ensureDirectoryForFile(file string) error { return err } - return os.MkdirAll(baseDir, 0755) + return os.MkdirAll(baseDir, 0o755) } diff --git a/pkg/downloader/chart_downloader.go b/pkg/downloader/chart_downloader.go index 529fd788e..816487e5e 100644 --- a/pkg/downloader/chart_downloader.go +++ b/pkg/downloader/chart_downloader.go @@ -110,7 +110,7 @@ func (c *ChartDownloader) DownloadTo(ref, version, dest string) (string, *proven } destfile := filepath.Join(dest, name) - if err := fileutil.AtomicWriteFile(destfile, data, 0644); err != nil { + if err := fileutil.AtomicWriteFile(destfile, data, 0o644); err != nil { return destfile, nil, err } @@ -126,7 +126,7 @@ func (c *ChartDownloader) DownloadTo(ref, version, dest string) (string, *proven return destfile, ver, nil } provfile := destfile + ".prov" - if err := fileutil.AtomicWriteFile(provfile, body, 0644); err != nil { + if err := fileutil.AtomicWriteFile(provfile, body, 0o644); err != nil { return destfile, nil, err } @@ -176,7 +176,7 @@ func (c *ChartDownloader) ResolveChartVersion(ref, version string) (*url.URL, er return u, err } - if u.IsAbs() && len(u.Host) > 0 && len(u.Path) > 0 { + if u.IsAbs() && u.Host != "" && u.Path != "" { // In this case, we have to find the parent repo that contains this chart // URL. And this is an unfortunate problem, as it requires actually going // through each repo cache file and finding a matching URL. But basically diff --git a/pkg/downloader/chart_downloader_test.go b/pkg/downloader/chart_downloader_test.go index a2e09eae5..0eb4d15d7 100644 --- a/pkg/downloader/chart_downloader_test.go +++ b/pkg/downloader/chart_downloader_test.go @@ -161,7 +161,7 @@ func TestVerifyChart(t *testing.T) { } // The verification is tested at length in the provenance package. Here, // we just want a quick sanity check that the v is not empty. - if len(v.FileHash) == 0 { + if v.FileHash == "" { t.Error("Digest missing") } } diff --git a/pkg/downloader/manager.go b/pkg/downloader/manager.go index b43165975..daf5a250b 100644 --- a/pkg/downloader/manager.go +++ b/pkg/downloader/manager.go @@ -254,7 +254,7 @@ func (m *Manager) downloadAll(deps []*chart.Dependency) error { return fmt.Errorf("%q is not a directory", destPath) } } else if errors.Is(err, stdfs.ErrNotExist) { - if err := os.MkdirAll(destPath, 0755); err != nil { + if err := os.MkdirAll(destPath, 0o755); err != nil { return err } } else { @@ -262,7 +262,7 @@ func (m *Manager) downloadAll(deps []*chart.Dependency) error { } // Prepare tmpPath - if err := os.MkdirAll(tmpPath, 0755); err != nil { + if err := os.MkdirAll(tmpPath, 0o755); err != nil { return err } defer os.RemoveAll(tmpPath) @@ -374,7 +374,7 @@ func (m *Manager) downloadAll(deps []*chart.Dependency) error { } func parseOCIRef(chartRef string) (string, string, error) { - refTagRegexp := regexp.MustCompile(`^(oci://[^:]+(:[0-9]{1,5})?[^:]+):(.*)$`) + refTagRegexp := regexp.MustCompile(`^(oci://[^:]+(:\d{1,5})?[^:]+):(.*)$`) caps := refTagRegexp.FindStringSubmatch(chartRef) if len(caps) != 4 { return "", "", fmt.Errorf("improperly formatted oci chart reference: %s", chartRef) @@ -761,7 +761,7 @@ func (m *Manager) findChartURL(name, version, repoURL string, repos map[string]* } url, err = repo.FindChartInRepoURL(repoURL, name, m.Getters, repo.WithChartVersion(version), repo.WithClientTLS(certFile, keyFile, caFile)) if err == nil { - return url, username, password, false, false, "", "", "", err + return url, username, password, false, false, "", "", "", nil } err = fmt.Errorf("chart %s not found in %s: %w", name, repoURL, err) return url, username, password, false, false, "", "", "", err @@ -865,7 +865,7 @@ func writeLock(chartpath string, lock *chart.Lock, legacyLockfile bool) error { } } - return os.WriteFile(dest, data, 0644) + return os.WriteFile(dest, data, 0o644) } // archive a dep chart from local directory and save it into destPath diff --git a/pkg/downloader/manager_test.go b/pkg/downloader/manager_test.go index f01a5d7ad..0ad16054a 100644 --- a/pkg/downloader/manager_test.go +++ b/pkg/downloader/manager_test.go @@ -264,7 +264,7 @@ func TestDownloadAll(t *testing.T) { } // create a 'tmpcharts' directory to test #5567 - if err := os.MkdirAll(filepath.Join(chartPath, "tmpcharts"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(chartPath, "tmpcharts"), 0o755); err != nil { t.Fatal(err) } if err := m.downloadAll([]*chart.Dependency{signDep, localDep}); err != nil { @@ -282,10 +282,10 @@ func TestDownloadAll(t *testing.T) { description: A Helm chart for Kubernetes name: ../bad-local-subchart version: 0.1.0` - if err := os.MkdirAll(filepath.Join(chartPath, "testdata", "bad-local-subchart"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(chartPath, "testdata", "bad-local-subchart"), 0o755); err != nil { t.Fatal(err) } - err = os.WriteFile(filepath.Join(chartPath, "testdata", "bad-local-subchart", "Chart.yaml"), []byte(badchartyaml), 0644) + err = os.WriteFile(filepath.Join(chartPath, "testdata", "bad-local-subchart", "Chart.yaml"), []byte(badchartyaml), 0o644) if err != nil { t.Fatal(err) } @@ -733,7 +733,7 @@ func TestWriteLock(t *testing.T) { t.Run("overwrite existing lock file", func(t *testing.T) { dir := t.TempDir() lockfilePath := filepath.Join(dir, "Chart.lock") - assert.NoError(t, os.WriteFile(lockfilePath, []byte("old content"), 0644)) + assert.NoError(t, os.WriteFile(lockfilePath, []byte("old content"), 0o644)) err = writeLock(dir, lock, false) assert.NoError(t, err) @@ -746,7 +746,7 @@ func TestWriteLock(t *testing.T) { t.Run("lock file is a symlink", func(t *testing.T) { dir := t.TempDir() dummyFile := filepath.Join(dir, "dummy.txt") - assert.NoError(t, os.WriteFile(dummyFile, []byte("dummy"), 0644)) + assert.NoError(t, os.WriteFile(dummyFile, []byte("dummy"), 0o644)) lockfilePath := filepath.Join(dir, "Chart.lock") assert.NoError(t, os.Symlink(dummyFile, lockfilePath)) @@ -759,7 +759,7 @@ func TestWriteLock(t *testing.T) { t.Run("chart path is not a directory", func(t *testing.T) { dir := t.TempDir() filePath := filepath.Join(dir, "not-a-dir") - assert.NoError(t, os.WriteFile(filePath, []byte("file"), 0644)) + assert.NoError(t, os.WriteFile(filePath, []byte("file"), 0o644)) err = writeLock(filePath, lock, false) assert.Error(t, err) diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go index 6e47a0e39..e4492564c 100644 --- a/pkg/engine/engine.go +++ b/pkg/engine/engine.go @@ -447,7 +447,7 @@ func (p byPathLen) Less(i, j int) bool { a, b := p[i], p[j] ca, cb := strings.Count(a, "/"), strings.Count(b, "/") if ca == cb { - return strings.Compare(a, b) == -1 + return a < b } return ca < cb } diff --git a/pkg/engine/funcs_test.go b/pkg/engine/funcs_test.go index 71a72e2e4..05b94b7ae 100644 --- a/pkg/engine/funcs_test.go +++ b/pkg/engine/funcs_test.go @@ -25,7 +25,7 @@ import ( ) func TestFuncs(t *testing.T) { - //TODO write tests for failure cases + // TODO write tests for failure cases tests := []struct { tpl, expect string vars interface{} diff --git a/pkg/engine/lookup_func.go b/pkg/engine/lookup_func.go index 605b43a48..759e5b5cf 100644 --- a/pkg/engine/lookup_func.go +++ b/pkg/engine/lookup_func.go @@ -94,7 +94,7 @@ func newLookupFunction(clientProvider ClientProvider) lookupFunc { } // getDynamicClientOnKind returns a dynamic client on an Unstructured type. This client can be further namespaced. -func getDynamicClientOnKind(apiversion string, kind string, config *rest.Config) (dynamic.NamespaceableResourceInterface, bool, error) { +func getDynamicClientOnKind(apiversion, kind string, config *rest.Config) (dynamic.NamespaceableResourceInterface, bool, error) { gvk := schema.FromAPIVersionAndKind(apiversion, kind) apiRes, err := getAPIResourceForGVK(gvk, config) if err != nil { diff --git a/pkg/getter/httpgetter.go b/pkg/getter/httpgetter.go index 925df201e..ecf660509 100644 --- a/pkg/getter/httpgetter.go +++ b/pkg/getter/httpgetter.go @@ -46,7 +46,7 @@ func (g *HTTPGetter) Get(href string, options ...Option) (*bytes.Buffer, error) func (g *HTTPGetter) get(href string) (*bytes.Buffer, error) { // Set a helm specific user agent so that a repo server and metrics can // separate helm calls from other tools interacting with repos. - req, err := http.NewRequest(http.MethodGet, href, nil) + req, err := http.NewRequest(http.MethodGet, href, http.NoBody) if err != nil { return nil, err } diff --git a/pkg/getter/httpgetter_test.go b/pkg/getter/httpgetter_test.go index a997c7f03..e0268e04a 100644 --- a/pkg/getter/httpgetter_test.go +++ b/pkg/getter/httpgetter_test.go @@ -225,7 +225,7 @@ func TestDownload(t *testing.T) { // A different host is provided for the WithURL from the one used for Get u2, _ := url.ParseRequestURI(crossAuthSrv.URL) host := strings.Split(u2.Host, ":") - host[0] = host[0] + "a" + host[0] += "a" u2.Host = strings.Join(host, ":") httpgetter, err = NewHTTPGetter( WithURL(u2.String()), @@ -260,7 +260,7 @@ func TestDownload(t *testing.T) { // A different host is provided for the WithURL from the one used for Get u2, _ = url.ParseRequestURI(crossAuthSrv.URL) host = strings.Split(u2.Host, ":") - host[0] = host[0] + "a" + host[0] += "a" u2.Host = strings.Join(host, ":") httpgetter, err = NewHTTPGetter( WithURL(u2.String()), @@ -520,11 +520,11 @@ func TestHTTPGetterTarDownload(t *testing.T) { b := make([]byte, 512) f.Read(b) - //Get the file size + // Get the file size FileStat, _ := f.Stat() FileSize := strconv.FormatInt(FileStat.Size(), 10) - //Simulating improper header values from bitbucket + // Simulating improper header values from bitbucket w.Header().Set("Content-Type", "application/x-tar") w.Header().Set("Content-Encoding", "gzip") w.Header().Set("Content-Length", FileSize) @@ -570,7 +570,7 @@ func TestHttpClientInsecureSkipVerify(t *testing.T) { g.opts.keyFile = "testdata/client.key" g.opts.insecureSkipVerifyTLS = true transport := verifyInsecureSkipVerify(t, &g, "HTTPGetter with 2 way ssl", true) - if len(transport.TLSClientConfig.Certificates) <= 0 { + if len(transport.TLSClientConfig.Certificates) == 0 { t.Fatal("transport.TLSClientConfig.Certificates is not present") } } diff --git a/pkg/getter/plugingetter.go b/pkg/getter/plugingetter.go index 3b8185543..cf6236407 100644 --- a/pkg/getter/plugingetter.go +++ b/pkg/getter/plugingetter.go @@ -62,9 +62,11 @@ type pluginGetter struct { } func (p *pluginGetter) setupOptionsEnv(env []string) []string { - env = append(env, fmt.Sprintf("HELM_PLUGIN_USERNAME=%s", p.opts.username)) - env = append(env, fmt.Sprintf("HELM_PLUGIN_PASSWORD=%s", p.opts.password)) - env = append(env, fmt.Sprintf("HELM_PLUGIN_PASS_CREDENTIALS_ALL=%t", p.opts.passCredentialsAll)) + env = append(env, + fmt.Sprintf("HELM_PLUGIN_USERNAME=%s", p.opts.username), + fmt.Sprintf("HELM_PLUGIN_PASSWORD=%s", p.opts.password), + fmt.Sprintf("HELM_PLUGIN_PASS_CREDENTIALS_ALL=%t", p.opts.passCredentialsAll), + ) return env } diff --git a/pkg/kube/client.go b/pkg/kube/client.go index 78ed4e088..117c94b00 100644 --- a/pkg/kube/client.go +++ b/pkg/kube/client.go @@ -558,7 +558,7 @@ func getManagedFieldsManager() string { } // When no manager is set and no calling application can be found it is unknown - if len(os.Args[0]) == 0 { + if os.Args[0] == "" { return "unknown" } diff --git a/pkg/kube/client_test.go b/pkg/kube/client_test.go index 5ffa0972b..12f98eb9a 100644 --- a/pkg/kube/client_test.go +++ b/pkg/kube/client_test.go @@ -1176,10 +1176,8 @@ func TestIsReachable(t *testing.T) { t.Errorf("expected error message to contain '%s', got: %v", tt.errorContains, err) } - } else { - if err != nil { - t.Errorf("expected no error but got: %v", err) - } + } else if err != nil { + t.Errorf("expected no error but got: %v", err) } }) } diff --git a/pkg/kube/ready_test.go b/pkg/kube/ready_test.go index db0d02cbe..bff354ab8 100644 --- a/pkg/kube/ready_test.go +++ b/pkg/kube/ready_test.go @@ -213,7 +213,7 @@ func Test_ReadyChecker_IsReady_Deployment(t *testing.T) { wantErr: true, }, { - name: "IsReady Deployments", //TODO fix this one + name: "IsReady Deployments", // TODO fix this one fields: fields{ client: fake.NewClientset(), checkJobs: true, @@ -1469,7 +1469,7 @@ func newReplicationController(name string, generationInSync bool) *corev1.Replic } } -func newReplicaSet(name string, replicas int, readyReplicas int, generationInSync bool) *appsv1.ReplicaSet { +func newReplicaSet(name string, replicas, readyReplicas int, generationInSync bool) *appsv1.ReplicaSet { d := newDeployment(name, replicas, 0, 0, generationInSync) return &appsv1.ReplicaSet{ ObjectMeta: metav1.ObjectMeta{ @@ -1528,7 +1528,7 @@ func newPersistentVolumeClaim(name string, phase corev1.PersistentVolumeClaimPha } } -func newJob(name string, backoffLimit int, completions *int32, succeeded int, failed int) *batchv1.Job { +func newJob(name string, backoffLimit int, completions *int32, succeeded, failed int) *batchv1.Job { return &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{ Name: name, diff --git a/pkg/kube/roundtripper_test.go b/pkg/kube/roundtripper_test.go index 96602c1f4..77da800ab 100644 --- a/pkg/kube/roundtripper_test.go +++ b/pkg/kube/roundtripper_test.go @@ -134,7 +134,7 @@ func TestRetryingRoundTripper_RoundTrip(t *testing.T) { rt := RetryingRoundTripper{ Wrapped: fakeRT, } - req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) + req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) resp, err := rt.RoundTrip(req) if tt.expectedErr != "" { diff --git a/pkg/kube/statuswait.go b/pkg/kube/statuswait.go index 2d7cfe971..ecb341826 100644 --- a/pkg/kube/statuswait.go +++ b/pkg/kube/statuswait.go @@ -141,8 +141,7 @@ func (w *statusWaiter) wait(ctx context.Context, resourceList ResourceList, sw w defer cancel() resources := []object.ObjMetadata{} for _, resource := range resourceList { - switch value := AsVersioned(resource).(type) { - case *appsv1.Deployment: + if value, ok := AsVersioned(resource).(*appsv1.Deployment); ok { if value.Spec.Paused { continue } diff --git a/pkg/lint/rules/chartfile.go b/pkg/lint/rules/chartfile.go index 724c3f2ea..cee5c968c 100644 --- a/pkg/lint/rules/chartfile.go +++ b/pkg/lint/rules/chartfile.go @@ -160,11 +160,12 @@ func validateChartVersion(cf *chart.Metadata) error { func validateChartMaintainer(cf *chart.Metadata) error { for _, maintainer := range cf.Maintainers { - if maintainer.Name == "" { + switch { + case maintainer.Name == "": return errors.New("each maintainer requires a name") - } else if maintainer.Email != "" && !govalidator.IsEmail(maintainer.Email) { + case maintainer.Email != "" && !govalidator.IsEmail(maintainer.Email): return fmt.Errorf("invalid email '%s' for maintainer '%s'", maintainer.Email, maintainer.Name) - } else if maintainer.URL != "" && !govalidator.IsURL(maintainer.URL) { + case maintainer.URL != "" && !govalidator.IsURL(maintainer.URL): return fmt.Errorf("invalid url '%s' for maintainer '%s'", maintainer.URL, maintainer.Name) } } @@ -202,7 +203,7 @@ func validateChartDependencies(cf *chart.Metadata) error { } func validateChartType(cf *chart.Metadata) error { - if len(cf.Type) > 0 && cf.APIVersion != chart.APIVersionV2 { + if cf.Type != "" && cf.APIVersion != chart.APIVersionV2 { return fmt.Errorf("chart type is not valid in apiVersion '%s'. It is valid in apiVersion '%s'", cf.APIVersion, chart.APIVersionV2) } return nil diff --git a/pkg/lint/rules/values_test.go b/pkg/lint/rules/values_test.go index 348695785..78af19745 100644 --- a/pkg/lint/rules/values_test.go +++ b/pkg/lint/rules/values_test.go @@ -162,7 +162,7 @@ func TestValidateValuesFile(t *testing.T) { func createTestingSchema(t *testing.T, dir string) string { t.Helper() schemafile := filepath.Join(dir, "values.schema.json") - if err := os.WriteFile(schemafile, []byte(testSchema), 0700); err != nil { + if err := os.WriteFile(schemafile, []byte(testSchema), 0o700); err != nil { t.Fatalf("Failed to write schema to tmpdir: %s", err) } return schemafile diff --git a/pkg/plugin/installer/http_installer.go b/pkg/plugin/installer/http_installer.go index 3bcf71208..77d3c61ce 100644 --- a/pkg/plugin/installer/http_installer.go +++ b/pkg/plugin/installer/http_installer.go @@ -120,7 +120,7 @@ func stripPluginName(name string) string { break } } - re := regexp.MustCompile(`(.*)-[0-9]+\..*`) + re := regexp.MustCompile(`(.*)-\d+\..*`) return re.ReplaceAllString(strippedName, `$1`) } @@ -227,7 +227,7 @@ func (g *TarGzExtractor) Extract(buffer *bytes.Buffer, targetDir string) error { return err } - if err := os.MkdirAll(targetDir, 0755); err != nil { + if err := os.MkdirAll(targetDir, 0o755); err != nil { return err } @@ -248,7 +248,7 @@ func (g *TarGzExtractor) Extract(buffer *bytes.Buffer, targetDir string) error { switch header.Typeflag { case tar.TypeDir: - if err := os.Mkdir(path, 0755); err != nil { + if err := os.Mkdir(path, 0o755); err != nil { return err } case tar.TypeReg: diff --git a/pkg/plugin/installer/http_installer_test.go b/pkg/plugin/installer/http_installer_test.go index ed4b73b35..a6067b22a 100644 --- a/pkg/plugin/installer/http_installer_test.go +++ b/pkg/plugin/installer/http_installer_test.go @@ -85,7 +85,7 @@ func TestHTTPInstaller(t *testing.T) { defer srv.Close() source := srv.URL + "/plugins/fake-plugin-0.0.1.tar.gz" - if err := os.MkdirAll(helmpath.DataPath("plugins"), 0755); err != nil { + if err := os.MkdirAll(helmpath.DataPath("plugins"), 0o755); err != nil { t.Fatalf("Could not create %s: %s", helmpath.DataPath("plugins"), err) } @@ -133,7 +133,7 @@ func TestHTTPInstallerNonExistentVersion(t *testing.T) { defer srv.Close() source := srv.URL + "/plugins/fake-plugin-0.0.1.tar.gz" - if err := os.MkdirAll(helmpath.DataPath("plugins"), 0755); err != nil { + if err := os.MkdirAll(helmpath.DataPath("plugins"), 0o755); err != nil { t.Fatalf("Could not create %s: %s", helmpath.DataPath("plugins"), err) } @@ -166,7 +166,7 @@ func TestHTTPInstallerUpdate(t *testing.T) { source := srv.URL + "/plugins/fake-plugin-0.0.1.tar.gz" ensure.HelmHome(t) - if err := os.MkdirAll(helmpath.DataPath("plugins"), 0755); err != nil { + if err := os.MkdirAll(helmpath.DataPath("plugins"), 0o755); err != nil { t.Fatalf("Could not create %s: %s", helmpath.DataPath("plugins"), err) } @@ -211,7 +211,7 @@ func TestExtract(t *testing.T) { tempDir := t.TempDir() // Set the umask to default open permissions so we can actually test - oldmask := syscall.Umask(0000) + oldmask := syscall.Umask(0o000) defer func() { syscall.Umask(oldmask) }() @@ -223,8 +223,8 @@ func TestExtract(t *testing.T) { Name, Body string Mode int64 }{ - {"plugin.yaml", "plugin metadata", 0600}, - {"README.md", "some text", 0777}, + {"plugin.yaml", "plugin metadata", 0o600}, + {"README.md", "some text", 0o777}, } for _, file := range files { hdr := &tar.Header{ @@ -280,7 +280,7 @@ func TestExtract(t *testing.T) { t.Fatalf("Expected %s to exist but doesn't", pluginYAMLFullPath) } t.Fatal(err) - } else if info.Mode().Perm() != 0600 { + } else if info.Mode().Perm() != 0o600 { t.Fatalf("Expected %s to have 0600 mode it but has %o", pluginYAMLFullPath, info.Mode().Perm()) } @@ -290,7 +290,7 @@ func TestExtract(t *testing.T) { t.Fatalf("Expected %s to exist but doesn't", readmeFullPath) } t.Fatal(err) - } else if info.Mode().Perm() != 0777 { + } else if info.Mode().Perm() != 0o777 { t.Fatalf("Expected %s to have 0777 mode it but has %o", readmeFullPath, info.Mode().Perm()) } @@ -343,7 +343,7 @@ func TestMediaTypeToExtension(t *testing.T) { if shouldPass && ext == "" { t.Errorf("Expected an extension but got empty string") } - if !shouldPass && len(ext) != 0 { + if !shouldPass && ext != "" { t.Error("Expected extension to be empty for unrecognized type") } } diff --git a/pkg/plugin/installer/installer.go b/pkg/plugin/installer/installer.go index d88737ebf..48d6786c5 100644 --- a/pkg/plugin/installer/installer.go +++ b/pkg/plugin/installer/installer.go @@ -43,7 +43,7 @@ type Installer interface { // Install installs a plugin. func Install(i Installer) error { - if err := os.MkdirAll(filepath.Dir(i.Path()), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(i.Path()), 0o755); err != nil { return err } if _, pathErr := os.Stat(i.Path()); !os.IsNotExist(pathErr) { diff --git a/pkg/plugin/installer/local_installer_test.go b/pkg/plugin/installer/local_installer_test.go index 9effcd2c4..00e982bad 100644 --- a/pkg/plugin/installer/local_installer_test.go +++ b/pkg/plugin/installer/local_installer_test.go @@ -30,7 +30,7 @@ func TestLocalInstaller(t *testing.T) { ensure.HelmHome(t) // Make a temp dir tdir := t.TempDir() - if err := os.WriteFile(filepath.Join(tdir, "plugin.yaml"), []byte{}, 0644); err != nil { + if err := os.WriteFile(filepath.Join(tdir, "plugin.yaml"), []byte{}, 0o644); err != nil { t.Fatal(err) } diff --git a/pkg/plugin/installer/vcs_installer_test.go b/pkg/plugin/installer/vcs_installer_test.go index 491d58a3f..f397d6377 100644 --- a/pkg/plugin/installer/vcs_installer_test.go +++ b/pkg/plugin/installer/vcs_installer_test.go @@ -52,7 +52,7 @@ func (r *testRepo) UpdateVersion(version string) error { func TestVCSInstaller(t *testing.T) { ensure.HelmHome(t) - if err := os.MkdirAll(helmpath.DataPath("plugins"), 0755); err != nil { + if err := os.MkdirAll(helmpath.DataPath("plugins"), 0o755); err != nil { t.Fatalf("Could not create %s: %s", helmpath.DataPath("plugins"), err) } diff --git a/pkg/plugin/plugin.go b/pkg/plugin/plugin.go index 930bf3664..9e71b9590 100644 --- a/pkg/plugin/plugin.go +++ b/pkg/plugin/plugin.go @@ -92,7 +92,7 @@ type Metadata struct { // Note that command is not executed in a shell. To do so, we suggest // pointing the command to a shell script. // - // DEPRECATED: Use PlatformCommand instead. Remove in Helm 4. + // Deprecated: Use PlatformCommand instead. Remove in Helm 4. Command string `json:"command"` // IgnoreFlags ignores any flags passed in from Helm @@ -126,7 +126,7 @@ type Metadata struct { // // Note that the command is executed in the sh shell. // - // DEPRECATED: Use PlatformHooks instead. Remove in Helm 4. + // Deprecated: Use PlatformHooks instead. Remove in Helm 4. Hooks Hooks // Downloaders field is used if the plugin supply downloader mechanism @@ -160,12 +160,12 @@ func getPlatformCommand(cmds []PlatformCommand) ([]string, []string) { return strings.Split(c.Command, " "), c.Args } - if (len(c.OperatingSystem) > 0 && !eq(c.OperatingSystem, runtime.GOOS)) || len(c.Architecture) > 0 { + if (c.OperatingSystem != "" && !eq(c.OperatingSystem, runtime.GOOS)) || c.Architecture != "" { // Skip if OS is not empty and doesn't match or if arch is set as a set arch requires an OS match continue } - if !foundOs && len(c.OperatingSystem) > 0 && eq(c.OperatingSystem, runtime.GOOS) { + if !foundOs && c.OperatingSystem != "" && eq(c.OperatingSystem, runtime.GOOS) { // First OS match with empty arch, can only be overridden by a direct match command = strings.Split(c.Command, " ") args = c.Args @@ -235,7 +235,7 @@ func (p *Plugin) PrepareCommand(extraArgs []string) (string, []string, error) { } cmds := p.Metadata.PlatformCommand - if len(cmds) == 0 && len(p.Metadata.Command) > 0 { + if len(cmds) == 0 && p.Metadata.Command != "" { cmds = []PlatformCommand{{Command: p.Metadata.Command}} } @@ -258,7 +258,7 @@ func validatePluginData(plug *Plugin, filepath string) error { } plug.Metadata.Usage = sanitizeString(plug.Metadata.Usage) - if len(plug.Metadata.PlatformCommand) > 0 && len(plug.Metadata.Command) > 0 { + if len(plug.Metadata.PlatformCommand) > 0 && plug.Metadata.Command != "" { return fmt.Errorf("both platformCommand and command are set in %q", filepath) } diff --git a/pkg/provenance/sign_test.go b/pkg/provenance/sign_test.go index 9a60fd19c..0a171c071 100644 --- a/pkg/provenance/sign_test.go +++ b/pkg/provenance/sign_test.go @@ -309,13 +309,15 @@ func TestVerify(t *testing.T) { t.Fatal(err) } - if ver, err := signer.Verify(testChartfile, testSigBlock); err != nil { + ver, err := signer.Verify(testChartfile, testSigBlock) + switch { + case err != nil: t.Errorf("Failed to pass verify. Err: %s", err) - } else if len(ver.FileHash) == 0 { + case ver.FileHash == "": t.Error("Verification is missing hash.") - } else if ver.SignedBy == nil { + case ver.SignedBy == nil: t.Error("No SignedBy field") - } else if ver.FileName != filepath.Base(testChartfile) { + case ver.FileName != filepath.Base(testChartfile): t.Errorf("FileName is unexpectedly %q", ver.FileName) } diff --git a/pkg/pusher/ocipusher_test.go b/pkg/pusher/ocipusher_test.go index 24f52a7ad..fafade82a 100644 --- a/pkg/pusher/ocipusher_test.go +++ b/pkg/pusher/ocipusher_test.go @@ -301,12 +301,12 @@ func TestOCIPusher_Push_ChartOperations(t *testing.T) { dst.Close() // Make the file unreadable - if err := os.Chmod(tempChart, 0000); err != nil { + if err := os.Chmod(tempChart, 0o000); err != nil { t.Fatal(err) } return tempChart, func() { - os.Chmod(tempChart, 0644) // Restore permissions for cleanup + os.Chmod(tempChart, 0o644) // Restore permissions for cleanup } }, href: "oci://localhost:5000/test", @@ -342,7 +342,7 @@ func TestOCIPusher_Push_ChartOperations(t *testing.T) { dst.Close() // Create provenance file - if err := os.WriteFile(tempProv, []byte("test provenance data"), 0644); err != nil { + if err := os.WriteFile(tempProv, []byte("test provenance data"), 0o644); err != nil { t.Fatal(err) } @@ -384,10 +384,8 @@ func TestOCIPusher_Push_ChartOperations(t *testing.T) { if tt.errorContains != "" && !strings.Contains(err.Error(), tt.errorContains) { t.Errorf("Expected error containing %q, got %q", tt.errorContains, err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) } diff --git a/pkg/registry/client.go b/pkg/registry/client.go index 3ea68f181..b32e22f5b 100644 --- a/pkg/registry/client.go +++ b/pkg/registry/client.go @@ -253,7 +253,7 @@ func (c *Client) Login(host string, options ...LoginOption) error { } // LoginOptBasicAuth returns a function that sets the username/password settings on login -func LoginOptBasicAuth(username string, password string) LoginOption { +func LoginOptBasicAuth(username, password string) LoginOption { return func(o *loginOperation) { o.client.username = username o.client.password = password @@ -279,8 +279,7 @@ func ensureTLSConfig(client *auth.Client) (*tls.Config, error) { case *http.Transport: transport = t case *LoggingTransport: - switch t := t.RoundTripper.(type) { - case *http.Transport: + if t, ok := t.RoundTripper.(*http.Transport); ok { transport = t } } @@ -820,10 +819,8 @@ func (c *Client) ValidateReference(ref, version string, u *url.URL) (*url.URL, e if version == "" { // Use OCI URI tag as default version = registryReference.Tag - } else { - if registryReference.Tag != "" && registryReference.Tag != version { - return nil, fmt.Errorf("chart reference and version mismatch: %s is not %s", version, registryReference.Tag) - } + } else if registryReference.Tag != "" && registryReference.Tag != version { + return nil, fmt.Errorf("chart reference and version mismatch: %s is not %s", version, registryReference.Tag) } if registryReference.Digest != "" { diff --git a/pkg/registry/transport.go b/pkg/registry/transport.go index a82229e2f..000c5bc64 100644 --- a/pkg/registry/transport.go +++ b/pkg/registry/transport.go @@ -83,11 +83,12 @@ func (t *LoggingTransport) RoundTrip(req *http.Request) (resp *http.Response, er slog.Debug(req.Method, "id", id, "url", req.URL, "header", logHeader(req.Header)) resp, err = t.RoundTripper.RoundTrip(req) - if err != nil { + switch { + case err != nil: slog.Debug("Response"[:len(req.Method)], "id", id, "error", err) - } else if resp != nil { + case resp != nil: slog.Debug("Response"[:len(req.Method)], "id", id, "status", resp.Status, "header", logHeader(resp.Header), "body", logResponseBody(resp)) - } else { + default: slog.Debug("Response"[:len(req.Method)], "id", id, "response", "nil") } @@ -142,7 +143,7 @@ func logResponseBody(resp *http.Response) string { } readBody := buf.String() - if len(readBody) == 0 { + if readBody == "" { return " Response body is empty" } if containsCredentials(readBody) { diff --git a/pkg/registry/util.go b/pkg/registry/util.go index b31ab63fe..2f282bb57 100644 --- a/pkg/registry/util.go +++ b/pkg/registry/util.go @@ -156,7 +156,7 @@ func generateChartOCIAnnotations(meta *chart.Metadata, creationTime string) map[ chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationVersion, meta.Version) chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationURL, meta.Home) - if len(creationTime) == 0 { + if creationTime == "" { creationTime = helmtime.Now().UTC().Format(time.RFC3339) } @@ -171,11 +171,11 @@ func generateChartOCIAnnotations(meta *chart.Metadata, creationTime string) map[ for maintainerIdx, maintainer := range meta.Maintainers { - if len(maintainer.Name) > 0 { + if maintainer.Name != "" { maintainerSb.WriteString(maintainer.Name) } - if len(maintainer.Email) > 0 { + if maintainer.Email != "" { maintainerSb.WriteString(" (") maintainerSb.WriteString(maintainer.Email) maintainerSb.WriteString(")") @@ -195,10 +195,10 @@ func generateChartOCIAnnotations(meta *chart.Metadata, creationTime string) map[ } // addToMap takes an existing map and adds an item if the value is not empty -func addToMap(inputMap map[string]string, newKey string, newValue string) map[string]string { +func addToMap(inputMap map[string]string, newKey, newValue string) map[string]string { // Add item to map if its - if len(strings.TrimSpace(newValue)) > 0 { + if strings.TrimSpace(newValue) != "" { inputMap[newKey] = newValue } diff --git a/pkg/registry/utils_test.go b/pkg/registry/utils_test.go index f4ff5bd58..fd2d31c4b 100644 --- a/pkg/registry/utils_test.go +++ b/pkg/registry/utils_test.go @@ -73,7 +73,7 @@ type TestSuite struct { func setup(suite *TestSuite, tlsEnabled, insecure bool) *registry.Registry { suite.WorkspaceDir = testWorkspaceDir os.RemoveAll(suite.WorkspaceDir) - os.Mkdir(suite.WorkspaceDir, 0700) + os.Mkdir(suite.WorkspaceDir, 0o700) var ( out bytes.Buffer @@ -121,7 +121,7 @@ func setup(suite *TestSuite, tlsEnabled, insecure bool) *registry.Registry { pwBytes, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.DefaultCost) suite.Nil(err, "no error generating bcrypt password for test htpasswd file") htpasswdPath := filepath.Join(suite.WorkspaceDir, testHtpasswdFileBasename) - err = os.WriteFile(htpasswdPath, []byte(fmt.Sprintf("%s:%s\n", testUsername, string(pwBytes))), 0644) + err = os.WriteFile(htpasswdPath, []byte(fmt.Sprintf("%s:%s\n", testUsername, string(pwBytes))), 0o644) suite.Nil(err, "no error creating test htpasswd file") // Registry config @@ -185,7 +185,8 @@ func teardown(suite *TestSuite) { func initCompromisedRegistryTestServer() string { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if strings.Contains(r.URL.Path, "manifests") { + switch { + case strings.Contains(r.URL.Path, "manifests"): w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json") w.WriteHeader(http.StatusOK) @@ -202,17 +203,17 @@ func initCompromisedRegistryTestServer() string { } ] }`, ConfigMediaType, ChartLayerMediaType) - } else if r.URL.Path == "/v2/testrepo/supposedlysafechart/blobs/sha256:a705ee2789ab50a5ba20930f246dbd5cc01ff9712825bb98f57ee8414377f133" { + case r.URL.Path == "/v2/testrepo/supposedlysafechart/blobs/sha256:a705ee2789ab50a5ba20930f246dbd5cc01ff9712825bb98f57ee8414377f133": w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte("{\"name\":\"mychart\",\"version\":\"0.1.0\",\"description\":\"A Helm chart for Kubernetes\\n" + "an 'application' or a 'library' chart.\",\"apiVersion\":\"v2\",\"appVersion\":\"1.16.0\",\"type\":" + "\"application\"}")) - } else if r.URL.Path == "/v2/testrepo/supposedlysafechart/blobs/sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb" { + case r.URL.Path == "/v2/testrepo/supposedlysafechart/blobs/sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb": w.Header().Set("Content-Type", ChartLayerMediaType) w.WriteHeader(http.StatusOK) w.Write([]byte("b")) - } else { + default: w.WriteHeader(http.StatusInternalServerError) } })) diff --git a/pkg/release/util/kind_sorter.go b/pkg/release/util/kind_sorter.go index bc074340f..2f13e2d35 100644 --- a/pkg/release/util/kind_sorter.go +++ b/pkg/release/util/kind_sorter.go @@ -137,7 +137,7 @@ func sortHooksByKind(hooks []*release.Hook, ordering KindSortOrder) []*release.H return h } -func lessByKind(_ interface{}, _ interface{}, kindA string, kindB string, o KindSortOrder) bool { +func lessByKind(_, _ interface{}, kindA, kindB string, o KindSortOrder) bool { ordering := make(map[string]int, len(o)) for v, k := range o { ordering[k] = v diff --git a/pkg/release/util/manifest.go b/pkg/release/util/manifest.go index 9a87949f8..9751d4bf0 100644 --- a/pkg/release/util/manifest.go +++ b/pkg/release/util/manifest.go @@ -54,7 +54,7 @@ func SplitManifests(bigFile string) map[string]string { d = strings.TrimSpace(d) res[fmt.Sprintf(tpl, count)] = d - count = count + 1 + count++ } return res } diff --git a/pkg/repo/chartrepo.go b/pkg/repo/chartrepo.go index c54197d60..867cdfefd 100644 --- a/pkg/repo/chartrepo.go +++ b/pkg/repo/chartrepo.go @@ -107,13 +107,13 @@ func (r *ChartRepository) DownloadIndexFile() (string, error) { fmt.Fprintln(&charts, name) } chartsFile := filepath.Join(r.CachePath, helmpath.CacheChartsFile(r.Config.Name)) - os.MkdirAll(filepath.Dir(chartsFile), 0755) - os.WriteFile(chartsFile, []byte(charts.String()), 0644) + os.MkdirAll(filepath.Dir(chartsFile), 0o755) + os.WriteFile(chartsFile, []byte(charts.String()), 0o644) // Create the index file in the cache directory fname := filepath.Join(r.CachePath, helmpath.CacheIndexFile(r.Config.Name)) - os.MkdirAll(filepath.Dir(fname), 0755) - return fname, os.WriteFile(fname, index, 0644) + os.MkdirAll(filepath.Dir(fname), 0o755) + return fname, os.WriteFile(fname, index, 0o644) } type findChartInRepoURLOptions struct { @@ -169,7 +169,7 @@ func WithInsecureSkipTLSverify(insecureSkipTLSverify bool) FindChartInRepoURLOpt // FindChartInRepoURL finds chart in chart repository pointed by repoURL // without adding repo to repositories -func FindChartInRepoURL(repoURL string, chartName string, getters getter.Providers, options ...FindChartInRepoURLOption) (string, error) { +func FindChartInRepoURL(repoURL, chartName string, getters getter.Providers, options ...FindChartInRepoURLOption) (string, error) { opts := findChartInRepoURLOptions{} for _, option := range options { diff --git a/pkg/repo/index.go b/pkg/repo/index.go index c26d7581c..af00da0a8 100644 --- a/pkg/repo/index.go +++ b/pkg/repo/index.go @@ -200,7 +200,7 @@ func (i IndexFile) Get(name, version string) (*ChartVersion, error) { } // when customer inputs specific version, check whether there's an exact match first - if len(version) != 0 { + if version != "" { for _, ver := range vs { if version == ver.Version { return ver, nil @@ -365,7 +365,8 @@ func loadIndex(data []byte, source string) (*IndexFile, error) { if cvs[idx].APIVersion == "" { cvs[idx].APIVersion = chart.APIVersionV1 } - if err := cvs[idx].Validate(); ignoreSkippableChartValidationError(err) != nil { + err := cvs[idx].Validate() + if ignoreSkippableChartValidationError(err) != nil { slog.Warn("skipping loading invalid entry for chart %q %q from %s: %s", name, cvs[idx].Version, source, err) cvs = append(cvs[:idx], cvs[idx+1:]...) } diff --git a/pkg/repo/index_test.go b/pkg/repo/index_test.go index d40719b12..dfc164108 100644 --- a/pkg/repo/index_test.go +++ b/pkg/repo/index_test.go @@ -550,7 +550,7 @@ func TestIndexWrite(t *testing.T) { } dir := t.TempDir() testpath := filepath.Join(dir, "test") - i.WriteFile(testpath, 0600) + i.WriteFile(testpath, 0o600) got, err := os.ReadFile(testpath) if err != nil { @@ -568,7 +568,7 @@ func TestIndexJSONWrite(t *testing.T) { } dir := t.TempDir() testpath := filepath.Join(dir, "test") - i.WriteJSONFile(testpath, 0600) + i.WriteJSONFile(testpath, 0o600) got, err := os.ReadFile(testpath) if err != nil { diff --git a/pkg/repo/repo.go b/pkg/repo/repo.go index 48c0e0193..ab4ba5e50 100644 --- a/pkg/repo/repo.go +++ b/pkg/repo/repo.go @@ -118,7 +118,7 @@ func (r *File) WriteFile(path string, perm os.FileMode) error { if err != nil { return err } - if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } return os.WriteFile(path, data, perm) diff --git a/pkg/repo/repo_test.go b/pkg/repo/repo_test.go index bdaa61eda..86b303765 100644 --- a/pkg/repo/repo_test.go +++ b/pkg/repo/repo_test.go @@ -202,7 +202,7 @@ func TestWriteFile(t *testing.T) { t.Errorf("failed to create test-file (%v)", err) } defer os.Remove(file.Name()) - if err := sampleRepository.WriteFile(file.Name(), 0600); err != nil { + if err := sampleRepository.WriteFile(file.Name(), 0o600); err != nil { t.Errorf("failed to write file (%v)", err) } diff --git a/pkg/repo/repotest/tlsconfig.go b/pkg/repo/repotest/tlsconfig.go index 3ea7338ff..474740037 100644 --- a/pkg/repo/repotest/tlsconfig.go +++ b/pkg/repo/repotest/tlsconfig.go @@ -35,7 +35,6 @@ func MakeTestTLSConfig(t *testing.T, path string) *tls.Config { tlsutil.WithCertKeyPairFiles(pub, priv), tlsutil.WithCAFile(ca), ) - //require.Nil(t, err, err.Error()) require.Nil(t, err) tlsConf.ServerName = "helm.sh" diff --git a/pkg/storage/driver/cfgmaps.go b/pkg/storage/driver/cfgmaps.go index de097f294..75daf81d1 100644 --- a/pkg/storage/driver/cfgmaps.go +++ b/pkg/storage/driver/cfgmaps.go @@ -211,7 +211,7 @@ func (cfgmaps *ConfigMaps) Delete(key string) (rls *rspb.Release, err error) { return nil, err } // delete the release - if err = cfgmaps.impl.Delete(context.Background(), key, metav1.DeleteOptions{}); err != nil { + if err := cfgmaps.impl.Delete(context.Background(), key, metav1.DeleteOptions{}); err != nil { return rls, err } return rls, nil diff --git a/pkg/storage/driver/sql.go b/pkg/storage/driver/sql.go index 46f6c6b2e..adfa4d019 100644 --- a/pkg/storage/driver/sql.go +++ b/pkg/storage/driver/sql.go @@ -276,7 +276,7 @@ type SQLReleaseCustomLabelWrapper struct { } // NewSQL initializes a new sql driver. -func NewSQL(connectionString string, namespace string) (*SQL, error) { +func NewSQL(connectionString, namespace string) (*SQL, error) { db, err := sqlx.Connect(postgreSQLDialect, connectionString) if err != nil { return nil, err @@ -659,7 +659,7 @@ func (s *SQL) Delete(key string) (*rspb.Release, error) { } // Get release custom labels from database -func (s *SQL) getReleaseCustomLabels(key string, _ string) (map[string]string, error) { +func (s *SQL) getReleaseCustomLabels(key, _ string) (map[string]string, error) { query, args, err := s.statementBuilder. Select(sqlCustomLabelsTableKeyColumn, sqlCustomLabelsTableValueColumn). From(sqlCustomLabelsTableName). diff --git a/pkg/storage/driver/sql_test.go b/pkg/storage/driver/sql_test.go index bd2918aad..6cc636a11 100644 --- a/pkg/storage/driver/sql_test.go +++ b/pkg/storage/driver/sql_test.go @@ -81,12 +81,14 @@ func TestSQLGet(t *testing.T) { func TestSQLList(t *testing.T) { releases := []*rspb.Release{} - releases = append(releases, releaseStub("key-1", 1, "default", rspb.StatusUninstalled)) - releases = append(releases, releaseStub("key-2", 1, "default", rspb.StatusUninstalled)) - releases = append(releases, releaseStub("key-3", 1, "default", rspb.StatusDeployed)) - releases = append(releases, releaseStub("key-4", 1, "default", rspb.StatusDeployed)) - releases = append(releases, releaseStub("key-5", 1, "default", rspb.StatusSuperseded)) - releases = append(releases, releaseStub("key-6", 1, "default", rspb.StatusSuperseded)) + releases = append(releases, + releaseStub("key-1", 1, "default", rspb.StatusUninstalled), + releaseStub("key-2", 1, "default", rspb.StatusUninstalled), + releaseStub("key-3", 1, "default", rspb.StatusDeployed), + releaseStub("key-4", 1, "default", rspb.StatusDeployed), + releaseStub("key-5", 1, "default", rspb.StatusSuperseded), + releaseStub("key-6", 1, "default", rspb.StatusSuperseded), + ) sqlDriver, mock := newTestFixtureSQL(t) @@ -520,7 +522,7 @@ func TestSqlDelete(t *testing.T) { } } -func mockGetReleaseCustomLabels(mock sqlmock.Sqlmock, key string, namespace string, labels map[string]string) { +func mockGetReleaseCustomLabels(mock sqlmock.Sqlmock, key, namespace string, labels map[string]string) { query := fmt.Sprintf( regexp.QuoteMeta("SELECT %s, %s FROM %s WHERE %s = $1 AND %s = $2"), sqlCustomLabelsTableKeyColumn, diff --git a/pkg/storage/storage_test.go b/pkg/storage/storage_test.go index d3025eca3..854afc8df 100644 --- a/pkg/storage/storage_test.go +++ b/pkg/storage/storage_test.go @@ -309,7 +309,6 @@ func (d *MaxHistoryMockDriver) Name() string { } func TestMaxHistoryErrorHandling(t *testing.T) { - //func TestStorageRemoveLeastRecentWithError(t *testing.T) { storage := Init(NewMaxHistoryMockDriver(driver.NewMemory())) storage.MaxHistory = 1 diff --git a/pkg/strvals/literal_parser_test.go b/pkg/strvals/literal_parser_test.go index 4e74423d6..a1922c917 100644 --- a/pkg/strvals/literal_parser_test.go +++ b/pkg/strvals/literal_parser_test.go @@ -16,6 +16,7 @@ limitations under the License. package strvals import ( + "bytes" "fmt" "testing" @@ -296,7 +297,7 @@ func TestParseLiteral(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2) } } @@ -409,7 +410,7 @@ func TestParseLiteralInto(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.input, y1, y2) } } @@ -421,7 +422,7 @@ func TestParseLiteralNestedLevels(t *testing.T) { for i := 1; i <= MaxNestedNameLevel+2; i++ { tmpStr := fmt.Sprintf("name%d", i) if i <= MaxNestedNameLevel+1 { - tmpStr = tmpStr + "." + tmpStr += "." } keyMultipleNestedLevels += tmpStr } @@ -473,7 +474,7 @@ func TestParseLiteralNestedLevels(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2) } } diff --git a/pkg/strvals/parser.go b/pkg/strvals/parser.go index c65e98c84..88dfeec9a 100644 --- a/pkg/strvals/parser.go +++ b/pkg/strvals/parser.go @@ -190,8 +190,8 @@ func (t *parser) key(data map[string]interface{}, nestedNameLevel int) (reterr e return err } return fmt.Errorf("key %q has no value", string(k)) - //set(data, string(k), "") - //return err + // set(data, string(k), "") + // return err case last == '[': // We are in a list index context, so we need to set an index. i, err := t.keyIndex() @@ -226,7 +226,7 @@ func (t *parser) key(data map[string]interface{}, nestedNameLevel int) (reterr e // discard in t.sc the chars of the decoded json value (the number of those characters is returned by InputOffset). var jsonval interface{} dec := json.NewDecoder(strings.NewReader(t.sc.String())) - if err = dec.Decode(&jsonval); err != nil { + if err := dec.Decode(&jsonval); err != nil { return err } set(data, string(k), jsonval) @@ -237,7 +237,7 @@ func (t *parser) key(data map[string]interface{}, nestedNameLevel int) (reterr e _, err = t.emptyVal() return err } - //End of key. Consume =, Get value. + // End of key. Consume =, Get value. // FIXME: Get value list first vl, e := t.valList() switch e { @@ -290,7 +290,7 @@ func (t *parser) key(data map[string]interface{}, nestedNameLevel int) (reterr e func set(data map[string]interface{}, key string, val interface{}) { // If key is empty, don't set it. - if len(key) == 0 { + if key == "" { return } data[key] = val @@ -359,7 +359,7 @@ func (t *parser) listItem(list []interface{}, i, nestedNameLevel int) ([]interfa // discard in t.sc the chars of the decoded json value (the number of those characters is returned by InputOffset). var jsonval interface{} dec := json.NewDecoder(strings.NewReader(t.sc.String())) - if err = dec.Decode(&jsonval); err != nil { + if err := dec.Decode(&jsonval); err != nil { return list, err } if list, err = setIndex(list, i, jsonval); err != nil { @@ -550,7 +550,7 @@ func typedVal(v []rune, st bool) interface{} { } // If this value does not start with zero, try parsing it to an int - if len(val) != 0 && val[0] != '0' { + if val != "" && val[0] != '0' { if iv, err := strconv.ParseInt(val, 10, 64); err == nil { return iv } diff --git a/pkg/strvals/parser_test.go b/pkg/strvals/parser_test.go index a0c67b791..b337a6919 100644 --- a/pkg/strvals/parser_test.go +++ b/pkg/strvals/parser_test.go @@ -16,6 +16,7 @@ limitations under the License. package strvals import ( + "bytes" "fmt" "testing" @@ -398,7 +399,7 @@ func TestParseSet(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2) } } @@ -423,7 +424,7 @@ func TestParseSet(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2) } } @@ -536,7 +537,7 @@ func TestParseInto(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.input, y1, y2) } } @@ -571,7 +572,7 @@ func TestParseIntoString(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2) } } @@ -671,7 +672,7 @@ func TestParseJSON(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.input, y1, y2) } } @@ -705,7 +706,7 @@ func TestParseFile(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2) } } @@ -738,7 +739,7 @@ func TestParseIntoFile(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2) } } @@ -761,7 +762,7 @@ func TestParseSetNestedLevels(t *testing.T) { for i := 1; i <= MaxNestedNameLevel+2; i++ { tmpStr := fmt.Sprintf("name%d", i) if i <= MaxNestedNameLevel+1 { - tmpStr = tmpStr + "." + tmpStr += "." } keyMultipleNestedLevels += tmpStr } @@ -811,7 +812,7 @@ func TestParseSetNestedLevels(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2) } } diff --git a/pkg/time/time.go b/pkg/time/time.go index 16973b455..1877e5344 100644 --- a/pkg/time/time.go +++ b/pkg/time/time.go @@ -75,10 +75,10 @@ func Date(year int, month time.Month, day, hour, minute, second, nanoSecond int, return Time{Time: time.Date(year, month, day, hour, minute, second, nanoSecond, loc)} } -func Unix(sec int64, nsec int64) Time { return Time{Time: time.Unix(sec, nsec)} } +func Unix(sec, nsec int64) Time { return Time{Time: time.Unix(sec, nsec)} } func (t Time) Add(d time.Duration) Time { return Time{Time: t.Time.Add(d)} } -func (t Time) AddDate(years int, months int, days int) Time { +func (t Time) AddDate(years, months, days int) Time { return Time{Time: t.Time.AddDate(years, months, days)} } func (t Time) After(u Time) bool { return t.Time.After(u.Time) } diff --git a/pkg/time/time_test.go b/pkg/time/time_test.go index 342ca4a10..789e23ce9 100644 --- a/pkg/time/time_test.go +++ b/pkg/time/time_test.go @@ -39,7 +39,7 @@ func givenTime(t *testing.T) Time { func TestDate(t *testing.T) { testingTime := givenTime(t) - got := Date(1977, 9, 2, 22, 04, 05, 0, time.UTC) + got := Date(1977, 9, 2, 22, 4, 5, 0, time.UTC) assert.Equal(t, timeString, got.String()) assert.True(t, testingTime.Equal(got)) assert.True(t, got.Equal(testingTime))