From 96b315f188932b7602e1ab1497e2d81d1caa8068 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 6 Jul 2026 23:16:46 +0200 Subject: [PATCH] chore: fix emptyStringTest, nestingReduce and singleCaseSwitch checks issues from gocritic Signed-off-by: Matthieu MOREL --- .golangci.yml | 3 - internal/chart/v3/lint/rules/chartfile.go | 2 +- internal/chart/v3/util/dependencies.go | 2 +- .../plugin/installer/http_installer_test.go | 2 +- internal/plugin/metadata.go | 2 +- internal/plugin/metadata_legacy.go | 2 +- internal/plugin/subprocess_commands.go | 4 +- .../release/v2/util/manifest_sorter_test.go | 37 ++++---- pkg/action/install.go | 2 +- pkg/action/show_test.go | 2 +- pkg/action/uninstall.go | 2 +- pkg/action/upgrade.go | 6 +- pkg/chart/v2/lint/rules/chartfile.go | 2 +- pkg/chart/v2/util/dependencies.go | 2 +- pkg/cli/values/options.go | 2 +- pkg/cmd/get_notes.go | 2 +- pkg/cmd/load_plugins.go | 4 +- pkg/cmd/package_test.go | 4 +- pkg/cmd/plugin_test.go | 2 +- pkg/cmd/repo_add.go | 2 +- pkg/cmd/root.go | 2 +- pkg/cmd/search_repo.go | 6 +- pkg/cmd/status.go | 2 +- pkg/downloader/chart_downloader.go | 2 +- pkg/downloader/chart_downloader_test.go | 2 +- pkg/downloader/manager.go | 88 ++++++++++--------- pkg/engine/engine.go | 2 +- pkg/kube/client.go | 2 +- pkg/kube/statuswait.go | 7 +- pkg/provenance/sign_test.go | 2 +- pkg/registry/chart.go | 8 +- pkg/registry/client.go | 3 +- pkg/registry/transport.go | 2 +- pkg/release/v1/util/manifest_sorter_test.go | 37 ++++---- pkg/repo/v1/index.go | 6 +- pkg/strvals/parser.go | 4 +- 36 files changed, 129 insertions(+), 132 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 518e47052..067b102d0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -91,18 +91,15 @@ linters: - commentFormatting - deferInLoop - elseif - - emptyStringTest - exposedSyncMutex - filepathJoin - hugeParam - ifElseChain - importShadow - - nestingReduce - nilValReturn - paramTypeCombine - ptrToRefParam - rangeValCopy - - singleCaseSwitch - todoCommentWithoutDetail - tooManyResultsChecker - uncheckedInlineErr diff --git a/internal/chart/v3/lint/rules/chartfile.go b/internal/chart/v3/lint/rules/chartfile.go index 29991a8d5..6f51a1de5 100644 --- a/internal/chart/v3/lint/rules/chartfile.go +++ b/internal/chart/v3/lint/rules/chartfile.go @@ -205,7 +205,7 @@ func validateChartDependencies(cf *chart.Metadata) error { } func validateChartType(cf *chart.Metadata) error { - if len(cf.Type) > 0 && cf.APIVersion != chart.APIVersionV3 { + if cf.Type != "" && cf.APIVersion != chart.APIVersionV3 { return fmt.Errorf("chart type is not valid in apiVersion '%s'. It is valid in apiVersion '%s'", cf.APIVersion, chart.APIVersionV3) } return nil diff --git a/internal/chart/v3/util/dependencies.go b/internal/chart/v3/util/dependencies.go index b31f7eb96..e1b3e0b97 100644 --- a/internal/chart/v3/util/dependencies.go +++ b/internal/chart/v3/util/dependencies.go @@ -43,7 +43,7 @@ func processDependencyConditions(reqs []*chart.Dependency, cvals common.Values, } 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) var errNoValue common.ErrNoValue diff --git a/internal/plugin/installer/http_installer_test.go b/internal/plugin/installer/http_installer_test.go index b080aa2ef..cbd868f3a 100644 --- a/internal/plugin/installer/http_installer_test.go +++ b/internal/plugin/installer/http_installer_test.go @@ -342,7 +342,7 @@ func TestMediaTypeToExtension(t *testing.T) { if shouldPass && ext == "" { t.Error("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/internal/plugin/metadata.go b/internal/plugin/metadata.go index 562861b1c..53d6da4e6 100644 --- a/internal/plugin/metadata.go +++ b/internal/plugin/metadata.go @@ -165,7 +165,7 @@ func buildLegacyRuntimeConfig(m MetadataLegacy) RuntimeConfig { } platformCommand := m.PlatformCommand - if len(platformCommand) == 0 && len(m.Command) > 0 { + if len(platformCommand) == 0 && m.Command != "" { platformCommand = []PlatformCommand{{Command: m.Command}} } diff --git a/internal/plugin/metadata_legacy.go b/internal/plugin/metadata_legacy.go index 26132a783..0bc11a81a 100644 --- a/internal/plugin/metadata_legacy.go +++ b/internal/plugin/metadata_legacy.go @@ -81,7 +81,7 @@ func (m *MetadataLegacy) Validate() error { m.Usage = sanitizeString(m.Usage) - if len(m.PlatformCommand) > 0 && len(m.Command) > 0 { + if len(m.PlatformCommand) > 0 && m.Command != "" { return errors.New("both platformCommand and command are set") } diff --git a/internal/plugin/subprocess_commands.go b/internal/plugin/subprocess_commands.go index 211ce5ebf..eb3e2b11b 100644 --- a/internal/plugin/subprocess_commands.go +++ b/internal/plugin/subprocess_commands.go @@ -48,12 +48,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 diff --git a/internal/release/v2/util/manifest_sorter_test.go b/internal/release/v2/util/manifest_sorter_test.go index 1c932d70c..eac9c9f36 100644 --- a/internal/release/v2/util/manifest_sorter_test.go +++ b/internal/release/v2/util/manifest_sorter_test.go @@ -149,27 +149,28 @@ metadata: for _, out := range hs { found := false for _, expect := range data { - if out.Path == expect.path { - found = true - assert.Equal(t, expect.path, out.Path) - nameFound := false - for _, expectedName := range expect.name { - if out.Name == expectedName { - nameFound = true - } + if out.Path != expect.path { + continue + } + found = true + assert.Equal(t, expect.path, out.Path) + nameFound := false + for _, expectedName := range expect.name { + if out.Name == expectedName { + nameFound = true } - assert.True(t, nameFound, "Got unexpected name %s", out.Name) - kindFound := false - for _, expectedKind := range expect.kind { - if out.Kind == expectedKind { - kindFound = true - } + } + assert.True(t, nameFound, "Got unexpected name %s", out.Name) + kindFound := false + for _, expectedKind := range expect.kind { + if out.Kind == expectedKind { + kindFound = true } - assert.True(t, kindFound, "Got unexpected kind %s", out.Kind) - - expectedHooks := expect.hooks[out.Name] - assert.Equal(t, expectedHooks, out.Events, "expected events: %v but got: %v", expectedHooks, out.Events) } + assert.True(t, kindFound, "Got unexpected kind %s", out.Kind) + + expectedHooks := expect.hooks[out.Name] + assert.Equal(t, expectedHooks, out.Events, "expected events: %v but got: %v", expectedHooks, out.Events) } assert.True(t, found, "Result not found: %v", out) } diff --git a/pkg/action/install.go b/pkg/action/install.go index d36d2fc3e..d73eca619 100644 --- a/pkg/action/install.go +++ b/pkg/action/install.go @@ -558,7 +558,7 @@ func (i *Install) performInstall(rel *release.Release, toBeAdopted kube.Resource } } - if len(i.Description) > 0 { + if i.Description != "" { rel.SetStatus(rcommon.StatusDeployed, i.Description) } else { rel.SetStatus(rcommon.StatusDeployed, "Install complete") diff --git a/pkg/action/show_test.go b/pkg/action/show_test.go index 854dee07a..0dde7fb74 100644 --- a/pkg/action/show_test.go +++ b/pkg/action/show_test.go @@ -86,7 +86,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 b14305112..47b2e47de 100644 --- a/pkg/action/uninstall.go +++ b/pkg/action/uninstall.go @@ -234,7 +234,7 @@ func (u *Uninstall) Run(name string) (*releasei.UninstallReleaseResponse, error) } rel.Info.Status = common.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 81d51164f..98ac44690 100644 --- a/pkg/action/upgrade.go +++ b/pkg/action/upgrade.go @@ -335,7 +335,7 @@ func (u *Upgrade) prepareUpgrade(ctx context.Context, name string, chart *chartv ApplyMethod: string(determineReleaseSSApplyMethod(serverSideApply)), } - if len(notesTxt) > 0 { + if notesTxt != "" { upgradedRelease.Info.Notes = notesTxt } err = validateManifest(u.cfg.KubeClient, manifestDoc.Bytes(), !u.DisableOpenAPIValidation) @@ -398,7 +398,7 @@ func (u *Upgrade) performUpgrade(ctx context.Context, originalRelease, upgradedR if isDryRun(u.DryRunStrategy) { u.cfg.Logger().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" @@ -516,7 +516,7 @@ func (u *Upgrade) releasingUpgrade(c chan<- resultMessage, upgradedRelease *rele u.cfg.recordRelease(originalRelease) upgradedRelease.Info.Status = rcommon.StatusDeployed - if len(u.Description) > 0 { + if u.Description != "" { upgradedRelease.Info.Description = u.Description } else { upgradedRelease.Info.Description = "Upgrade complete" diff --git a/pkg/chart/v2/lint/rules/chartfile.go b/pkg/chart/v2/lint/rules/chartfile.go index f8f609280..cb58bbac0 100644 --- a/pkg/chart/v2/lint/rules/chartfile.go +++ b/pkg/chart/v2/lint/rules/chartfile.go @@ -216,7 +216,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/chart/v2/util/dependencies.go b/pkg/chart/v2/util/dependencies.go index f28a4f4b1..019cd1cda 100644 --- a/pkg/chart/v2/util/dependencies.go +++ b/pkg/chart/v2/util/dependencies.go @@ -43,7 +43,7 @@ func processDependencyConditions(reqs []*chart.Dependency, cvals common.Values, } 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) var errNoValue common.ErrNoValue diff --git a/pkg/cli/values/options.go b/pkg/cli/values/options.go index 336dfb72b..6edfb415c 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]any, error) { // 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]any if err := json.Unmarshal([]byte(trimmedValue), &jsonMap); err != nil { diff --git a/pkg/cmd/get_notes.go b/pkg/cmd/get_notes.go index 46fbeeaf5..7f8754f3c 100644 --- a/pkg/cmd/get_notes.go +++ b/pkg/cmd/get_notes.go @@ -55,7 +55,7 @@ func newGetNotesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { if err != nil { return err } - if len(rac.Notes()) > 0 { + if rac.Notes() != "" { fmt.Fprintf(out, "NOTES:\n%s\n", rac.Notes()) } return nil diff --git a/pkg/cmd/load_plugins.go b/pkg/cmd/load_plugins.go index 474eaea2e..dee42f750 100644 --- a/pkg/cmd/load_plugins.go +++ b/pkg/cmd/load_plugins.go @@ -242,7 +242,7 @@ func addPluginCommands(plug plugin.Plugin, baseCmd *cobra.Command, cmds *pluginC return } - if len(cmds.Name) == 0 { + if cmds.Name == "" { slog.Debug("sub-command name field missing", slog.String("commandPath", baseCmd.CommandPath())) return } @@ -380,7 +380,7 @@ func pluginDynamicComp(plug plugin.Plugin, cmd *cobra.Command, args []string, to 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_test.go b/pkg/cmd/plugin_test.go index 0a6435d99..476997110 100644 --- a/pkg/cmd/plugin_test.go +++ b/pkg/cmd/plugin_test.go @@ -291,7 +291,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/repo_add.go b/pkg/cmd/repo_add.go index 3fc1a7249..a7a02ef75 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/root.go b/pkg/cmd/root.go index 3203ced25..7ee71f4ef 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -238,7 +238,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 53626f1b6..9c5b1dd18 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 } @@ -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,7 +375,7 @@ 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) diff --git a/pkg/cmd/status.go b/pkg/cmd/status.go index 705691aaf..6998e341a 100644 --- a/pkg/cmd/status.go +++ b/pkg/cmd/status.go @@ -236,7 +236,7 @@ func (s statusPrinter) WriteTable(out io.Writer) error { } // Hide notes from output - option in install and upgrades - if !s.hideNotes && len(rel.Info.Notes) > 0 { + if !s.hideNotes && rel.Info.Notes != "" { _, _ = fmt.Fprintf(out, "NOTES:\n%s\n", strings.TrimSpace(rel.Info.Notes)) } return nil diff --git a/pkg/downloader/chart_downloader.go b/pkg/downloader/chart_downloader.go index 4a13fc5ed..eca4e3342 100644 --- a/pkg/downloader/chart_downloader.go +++ b/pkg/downloader/chart_downloader.go @@ -382,7 +382,7 @@ func (c *ChartDownloader) ResolveChartVersion(ref, version string) (string, *url 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 07b25a1eb..b3899d813 100644 --- a/pkg/downloader/chart_downloader_test.go +++ b/pkg/downloader/chart_downloader_test.go @@ -167,7 +167,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 543f685eb..683f96007 100644 --- a/pkg/downloader/manager.go +++ b/pkg/downloader/manager.go @@ -441,21 +441,22 @@ func (m *Manager) safeMoveDeps(deps []*chart.Dependency, source, dest string) er fmt.Fprintln(m.Out, "Deleting outdated charts") // find all files that exist in dest that do not exist in source; delete them (outdated dependencies) for _, file := range destFiles { - if !file.IsDir() && !existsInSourceDirectory[file.Name()] { - fname := filepath.Join(dest, file.Name()) - ch, err := loader.LoadFile(fname) - if err != nil { - fmt.Fprintf(m.Out, "Could not verify %s for deletion: %s (Skipping)\n", fname, err) - continue - } - // local dependency - skip - if isLocalDependency[ch.Name()] { - continue - } - if err := os.Remove(fname); err != nil { - fmt.Fprintf(m.Out, "Could not delete %s: %s (Skipping)", fname, err) - continue - } + if file.IsDir() || existsInSourceDirectory[file.Name()] { + continue + } + fname := filepath.Join(dest, file.Name()) + ch, err := loader.LoadFile(fname) + if err != nil { + fmt.Fprintf(m.Out, "Could not verify %s for deletion: %s (Skipping)\n", fname, err) + continue + } + // local dependency - skip + if isLocalDependency[ch.Name()] { + continue + } + if err := os.Remove(fname); err != nil { + fmt.Fprintf(m.Out, "Could not delete %s: %s (Skipping)", fname, err) + continue } } @@ -728,37 +729,38 @@ func (m *Manager) findChartURL(name, version, repoURL string, repos map[string]* } for _, cr := range repos { - if urlutil.Equal(repoURL, cr.Config.URL) { - var entry repo.ChartVersions - entry, err = findEntryByName(name, cr) - if err != nil { - // TODO: Where linting is skipped in this function we should - // refactor to remove naked returns while ensuring the same - // behavior - //nolint:nakedret - return - } - var ve *repo.ChartVersion - ve, err = findVersionedEntry(version, entry) - if err != nil { - //nolint:nakedret - return - } - url, err = repo.ResolveReferenceURL(repoURL, ve.URLs[0]) - if err != nil { - //nolint:nakedret - return - } - username = cr.Config.Username - password = cr.Config.Password - passCredentialsAll = cr.Config.PassCredentialsAll - insecureSkipTLSVerify = cr.Config.InsecureSkipTLSVerify - caFile = cr.Config.CAFile - certFile = cr.Config.CertFile - keyFile = cr.Config.KeyFile + if !urlutil.Equal(repoURL, cr.Config.URL) { + continue + } + var entry repo.ChartVersions + entry, err = findEntryByName(name, cr) + if err != nil { + // TODO: Where linting is skipped in this function we should + // refactor to remove naked returns while ensuring the same + // behavior + //nolint:nakedret + return + } + var ve *repo.ChartVersion + ve, err = findVersionedEntry(version, entry) + if err != nil { + //nolint:nakedret + return + } + url, err = repo.ResolveReferenceURL(repoURL, ve.URLs[0]) + if err != nil { //nolint:nakedret return } + username = cr.Config.Username + password = cr.Config.Password + passCredentialsAll = cr.Config.PassCredentialsAll + insecureSkipTLSVerify = cr.Config.InsecureSkipTLSVerify + caFile = cr.Config.CAFile + certFile = cr.Config.CertFile + keyFile = cr.Config.KeyFile + //nolint:nakedret + return } url, err = repo.FindChartInRepoURL(repoURL, name, m.Getters, repo.WithChartVersion(version), repo.WithClientTLS(certFile, keyFile, caFile)) if err == nil { diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go index d304aea7d..1d0affd93 100644 --- a/pkg/engine/engine.go +++ b/pkg/engine/engine.go @@ -437,7 +437,7 @@ func parseTemplateSimpleErrorString(remainder string) (TraceableError, bool) { // Matches https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/text/template/exec.go;l=141 func parseTemplateExecutingAtErrorType(remainder string) (TraceableError, bool) { if templateName, after, found := strings.Cut(remainder, ": executing "); found { - if len(after) == 0 || after[0] != '"' { + if after == "" || after[0] != '"' { return TraceableError{}, false } // find closing quote for function name diff --git a/pkg/kube/client.go b/pkg/kube/client.go index 7b02f47ef..4e6d5c3a9 100644 --- a/pkg/kube/client.go +++ b/pkg/kube/client.go @@ -961,7 +961,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/statuswait.go b/pkg/kube/statuswait.go index 29de0af2b..12c3e95a6 100644 --- a/pkg/kube/statuswait.go +++ b/pkg/kube/statuswait.go @@ -180,11 +180,8 @@ 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.Spec.Paused { - continue - } + if value, ok := AsVersioned(resource).(*appsv1.Deployment); ok && value.Spec.Paused { + continue } obj, err := object.RuntimeToObjMeta(resource.Object) if err != nil { diff --git a/pkg/provenance/sign_test.go b/pkg/provenance/sign_test.go index 8784e6c12..faf402b43 100644 --- a/pkg/provenance/sign_test.go +++ b/pkg/provenance/sign_test.go @@ -380,7 +380,7 @@ func TestVerify(t *testing.T) { if ver, err := signer.Verify(archiveData, sigData, filepath.Base(testChartfile)); err != nil { t.Errorf("Failed to pass verify. Err: %s", err) - } else if len(ver.FileHash) == 0 { + } else if ver.FileHash == "" { t.Error("Verification is missing hash.") } else if ver.SignedBy == nil { t.Error("No SignedBy field") diff --git a/pkg/registry/chart.go b/pkg/registry/chart.go index d70b7e912..7c41785c5 100644 --- a/pkg/registry/chart.go +++ b/pkg/registry/chart.go @@ -72,7 +72,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 = time.Now().UTC().Format(time.RFC3339) } @@ -86,11 +86,11 @@ func generateChartOCIAnnotations(meta *chart.Metadata, creationTime string) map[ var maintainerSb strings.Builder 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(")") @@ -110,7 +110,7 @@ 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 { // Add item to map if its - if len(strings.TrimSpace(newValue)) > 0 { + if strings.TrimSpace(newValue) != "" { inputMap[newKey] = newValue } diff --git a/pkg/registry/client.go b/pkg/registry/client.go index 4d7da78dc..a14afdd1f 100644 --- a/pkg/registry/client.go +++ b/pkg/registry/client.go @@ -303,8 +303,7 @@ func ensureTLSConfig(client *auth.Client, setConfig *tls.Config) (*tls.Config, e 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 } } diff --git a/pkg/registry/transport.go b/pkg/registry/transport.go index e4177efb3..68e4ac587 100644 --- a/pkg/registry/transport.go +++ b/pkg/registry/transport.go @@ -130,7 +130,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/release/v1/util/manifest_sorter_test.go b/pkg/release/v1/util/manifest_sorter_test.go index b02400938..35c7a0721 100644 --- a/pkg/release/v1/util/manifest_sorter_test.go +++ b/pkg/release/v1/util/manifest_sorter_test.go @@ -149,27 +149,28 @@ metadata: for _, out := range hs { found := false for _, expect := range data { - if out.Path == expect.path { - found = true - assert.Equal(t, expect.path, out.Path) - nameFound := false - for _, expectedName := range expect.name { - if out.Name == expectedName { - nameFound = true - } + if out.Path != expect.path { + continue + } + found = true + assert.Equal(t, expect.path, out.Path) + nameFound := false + for _, expectedName := range expect.name { + if out.Name == expectedName { + nameFound = true } - assert.True(t, nameFound, "Got unexpected name %s", out.Name) - kindFound := false - for _, expectedKind := range expect.kind { - if out.Kind == expectedKind { - kindFound = true - } + } + assert.True(t, nameFound, "Got unexpected name %s", out.Name) + kindFound := false + for _, expectedKind := range expect.kind { + if out.Kind == expectedKind { + kindFound = true } - assert.True(t, kindFound, "Got unexpected kind %s", out.Kind) - - expectedHooks := expect.hooks[out.Name] - assert.Equal(t, expectedHooks, out.Events, "expected events: %v but got: %v", expectedHooks, out.Events) } + assert.True(t, kindFound, "Got unexpected kind %s", out.Kind) + + expectedHooks := expect.hooks[out.Name] + assert.Equal(t, expectedHooks, out.Events, "expected events: %v but got: %v", expectedHooks, out.Events) } assert.True(t, found, "Result not found: %v", out) } diff --git a/pkg/repo/v1/index.go b/pkg/repo/v1/index.go index 57e4c081f..15f72891b 100644 --- a/pkg/repo/v1/index.go +++ b/pkg/repo/v1/index.go @@ -214,7 +214,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 @@ -229,9 +229,9 @@ func (i IndexFile) Get(name, version string) (*ChartVersion, error) { } if constraint.Check(test) { - if len(version) != 0 && !isVersionRange(version) { + if version != "" && !isVersionRange(version) { slog.Warn("unable to find exact version requested; falling back to closest available version", "chart", name, "requested", version, "selected", ver.Version) - } else if len(version) != 0 && isVersionRange(version) { + } else if version != "" && isVersionRange(version) { slog.Debug("selected version matching constraint", "chart", name, "constraint", version, "selected", ver.Version) } return ver, nil diff --git a/pkg/strvals/parser.go b/pkg/strvals/parser.go index a0b72bee3..c52e8aed9 100644 --- a/pkg/strvals/parser.go +++ b/pkg/strvals/parser.go @@ -290,7 +290,7 @@ func (t *parser) key(data map[string]any, nestedNameLevel int) (reterr error) { func set(data map[string]any, key string, val any) { // If key is empty, don't set it. - if len(key) == 0 { + if key == "" { return } data[key] = val @@ -549,7 +549,7 @@ func typedVal(v []rune, st bool) any { } // 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 }