chore: fix emptyStringTest, nestingReduce and singleCaseSwitch checks issues from gocritic

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
pull/32296/head
Matthieu MOREL 2 months ago
parent 7b999ddc07
commit 96b315f188

@ -91,18 +91,15 @@ linters:
- commentFormatting - commentFormatting
- deferInLoop - deferInLoop
- elseif - elseif
- emptyStringTest
- exposedSyncMutex - exposedSyncMutex
- filepathJoin - filepathJoin
- hugeParam - hugeParam
- ifElseChain - ifElseChain
- importShadow - importShadow
- nestingReduce
- nilValReturn - nilValReturn
- paramTypeCombine - paramTypeCombine
- ptrToRefParam - ptrToRefParam
- rangeValCopy - rangeValCopy
- singleCaseSwitch
- todoCommentWithoutDetail - todoCommentWithoutDetail
- tooManyResultsChecker - tooManyResultsChecker
- uncheckedInlineErr - uncheckedInlineErr

@ -205,7 +205,7 @@ func validateChartDependencies(cf *chart.Metadata) error {
} }
func validateChartType(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 fmt.Errorf("chart type is not valid in apiVersion '%s'. It is valid in apiVersion '%s'", cf.APIVersion, chart.APIVersionV3)
} }
return nil return nil

@ -43,7 +43,7 @@ func processDependencyConditions(reqs []*chart.Dependency, cvals common.Values,
} }
for _, r := range reqs { for _, r := range reqs {
for c := range strings.SplitSeq(strings.TrimSpace(r.Condition), ",") { for c := range strings.SplitSeq(strings.TrimSpace(r.Condition), ",") {
if len(c) > 0 { if c != "" {
// retrieve value // retrieve value
vv, err := cvals.PathValue(cpath + c) vv, err := cvals.PathValue(cpath + c)
var errNoValue common.ErrNoValue var errNoValue common.ErrNoValue

@ -342,7 +342,7 @@ func TestMediaTypeToExtension(t *testing.T) {
if shouldPass && ext == "" { if shouldPass && ext == "" {
t.Error("Expected an extension but got empty string") 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") t.Error("Expected extension to be empty for unrecognized type")
} }
} }

@ -165,7 +165,7 @@ func buildLegacyRuntimeConfig(m MetadataLegacy) RuntimeConfig {
} }
platformCommand := m.PlatformCommand platformCommand := m.PlatformCommand
if len(platformCommand) == 0 && len(m.Command) > 0 { if len(platformCommand) == 0 && m.Command != "" {
platformCommand = []PlatformCommand{{Command: m.Command}} platformCommand = []PlatformCommand{{Command: m.Command}}
} }

@ -81,7 +81,7 @@ func (m *MetadataLegacy) Validate() error {
m.Usage = sanitizeString(m.Usage) 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") return errors.New("both platformCommand and command are set")
} }

@ -48,12 +48,12 @@ func getPlatformCommand(cmds []PlatformCommand) ([]string, []string) {
return strings.Split(c.Command, " "), c.Args 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 // Skip if OS is not empty and doesn't match or if arch is set as a set arch requires an OS match
continue 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 // First OS match with empty arch, can only be overridden by a direct match
command = strings.Split(c.Command, " ") command = strings.Split(c.Command, " ")
args = c.Args args = c.Args

@ -149,27 +149,28 @@ metadata:
for _, out := range hs { for _, out := range hs {
found := false found := false
for _, expect := range data { for _, expect := range data {
if out.Path == expect.path { if out.Path != expect.path {
found = true continue
assert.Equal(t, expect.path, out.Path) }
nameFound := false found = true
for _, expectedName := range expect.name { assert.Equal(t, expect.path, out.Path)
if out.Name == expectedName { nameFound := false
nameFound = true for _, expectedName := range expect.name {
} if out.Name == expectedName {
nameFound = true
} }
assert.True(t, nameFound, "Got unexpected name %s", out.Name) }
kindFound := false assert.True(t, nameFound, "Got unexpected name %s", out.Name)
for _, expectedKind := range expect.kind { kindFound := false
if out.Kind == expectedKind { for _, expectedKind := range expect.kind {
kindFound = true 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) assert.True(t, found, "Result not found: %v", out)
} }

@ -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) rel.SetStatus(rcommon.StatusDeployed, i.Description)
} else { } else {
rel.SetStatus(rcommon.StatusDeployed, "Install complete") rel.SetStatus(rcommon.StatusDeployed, "Install complete")

@ -86,7 +86,7 @@ func TestShowNoValues(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if len(output) != 0 { if output != "" {
t.Errorf("expected empty values buffer, got %s", output) t.Errorf("expected empty values buffer, got %s", output)
} }
} }

@ -234,7 +234,7 @@ func (u *Uninstall) Run(name string) (*releasei.UninstallReleaseResponse, error)
} }
rel.Info.Status = common.StatusUninstalled rel.Info.Status = common.StatusUninstalled
if len(u.Description) > 0 { if u.Description != "" {
rel.Info.Description = u.Description rel.Info.Description = u.Description
} else { } else {
rel.Info.Description = "Uninstallation complete" rel.Info.Description = "Uninstallation complete"

@ -335,7 +335,7 @@ func (u *Upgrade) prepareUpgrade(ctx context.Context, name string, chart *chartv
ApplyMethod: string(determineReleaseSSApplyMethod(serverSideApply)), ApplyMethod: string(determineReleaseSSApplyMethod(serverSideApply)),
} }
if len(notesTxt) > 0 { if notesTxt != "" {
upgradedRelease.Info.Notes = notesTxt upgradedRelease.Info.Notes = notesTxt
} }
err = validateManifest(u.cfg.KubeClient, manifestDoc.Bytes(), !u.DisableOpenAPIValidation) 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) { if isDryRun(u.DryRunStrategy) {
u.cfg.Logger().Debug("dry run for release", "name", upgradedRelease.Name) u.cfg.Logger().Debug("dry run for release", "name", upgradedRelease.Name)
if len(u.Description) > 0 { if u.Description != "" {
upgradedRelease.Info.Description = u.Description upgradedRelease.Info.Description = u.Description
} else { } else {
upgradedRelease.Info.Description = "Dry run complete" upgradedRelease.Info.Description = "Dry run complete"
@ -516,7 +516,7 @@ func (u *Upgrade) releasingUpgrade(c chan<- resultMessage, upgradedRelease *rele
u.cfg.recordRelease(originalRelease) u.cfg.recordRelease(originalRelease)
upgradedRelease.Info.Status = rcommon.StatusDeployed upgradedRelease.Info.Status = rcommon.StatusDeployed
if len(u.Description) > 0 { if u.Description != "" {
upgradedRelease.Info.Description = u.Description upgradedRelease.Info.Description = u.Description
} else { } else {
upgradedRelease.Info.Description = "Upgrade complete" upgradedRelease.Info.Description = "Upgrade complete"

@ -216,7 +216,7 @@ func validateChartDependencies(cf *chart.Metadata) error {
} }
func validateChartType(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 fmt.Errorf("chart type is not valid in apiVersion '%s'. It is valid in apiVersion '%s'", cf.APIVersion, chart.APIVersionV2)
} }
return nil return nil

@ -43,7 +43,7 @@ func processDependencyConditions(reqs []*chart.Dependency, cvals common.Values,
} }
for _, r := range reqs { for _, r := range reqs {
for c := range strings.SplitSeq(strings.TrimSpace(r.Condition), ",") { for c := range strings.SplitSeq(strings.TrimSpace(r.Condition), ",") {
if len(c) > 0 { if c != "" {
// retrieve value // retrieve value
vv, err := cvals.PathValue(cpath + c) vv, err := cvals.PathValue(cpath + c)
var errNoValue common.ErrNoValue var errNoValue common.ErrNoValue

@ -62,7 +62,7 @@ func (opts *Options) MergeValues(p getter.Providers) (map[string]any, error) {
// User specified a value via --set-json // User specified a value via --set-json
for _, value := range opts.JSONValues { for _, value := range opts.JSONValues {
trimmedValue := strings.TrimSpace(value) trimmedValue := strings.TrimSpace(value)
if len(trimmedValue) > 0 && trimmedValue[0] == '{' { if trimmedValue != "" && trimmedValue[0] == '{' {
// If value is JSON object format, parse it as map // If value is JSON object format, parse it as map
var jsonMap map[string]any var jsonMap map[string]any
if err := json.Unmarshal([]byte(trimmedValue), &jsonMap); err != nil { if err := json.Unmarshal([]byte(trimmedValue), &jsonMap); err != nil {

@ -55,7 +55,7 @@ func newGetNotesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
if len(rac.Notes()) > 0 { if rac.Notes() != "" {
fmt.Fprintf(out, "NOTES:\n%s\n", rac.Notes()) fmt.Fprintf(out, "NOTES:\n%s\n", rac.Notes())
} }
return nil return nil

@ -242,7 +242,7 @@ func addPluginCommands(plug plugin.Plugin, baseCmd *cobra.Command, cmds *pluginC
return return
} }
if len(cmds.Name) == 0 { if cmds.Name == "" {
slog.Debug("sub-command name field missing", slog.String("commandPath", baseCmd.CommandPath())) slog.Debug("sub-command name field missing", slog.String("commandPath", baseCmd.CommandPath()))
return return
} }
@ -380,7 +380,7 @@ func pluginDynamicComp(plug plugin.Plugin, cmd *cobra.Command, args []string, to
var completions []string var completions []string
for comp := range strings.SplitSeq(buf.String(), "\n") { for comp := range strings.SplitSeq(buf.String(), "\n") {
// Remove any empty lines // Remove any empty lines
if len(comp) > 0 { if comp != "" {
completions = append(completions, comp) completions = append(completions, comp)
} }
} }

@ -119,7 +119,7 @@ func TestPackage(t *testing.T) {
} }
// This is an unfortunate byproduct of the tmpdir // 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) 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) 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 { if fi, err := os.Stat(tt.hasfile); err != nil {
t.Errorf("%q: expected file %q, got err %q", tt.name, tt.hasfile, err) t.Errorf("%q: expected file %q, got err %q", tt.name, tt.hasfile, err)
} else if fi.Size() == 0 { } else if fi.Size() == 0 {

@ -291,7 +291,7 @@ func checkCommand(t *testing.T, plugins []*cobra.Command, tests []staticCompleti
var pflags []string var pflags []string
pp.LocalFlags().VisitAll(func(flag *pflag.Flag) { pp.LocalFlags().VisitAll(func(flag *pflag.Flag) {
pflags = append(pflags, flag.Name) 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) pflags = append(pflags, flag.Shorthand)
} }
}) })

@ -121,7 +121,7 @@ func (o *repoAddOptions) run(out io.Writer) error {
// Acquire a file lock for process synchronization // Acquire a file lock for process synchronization
repoFileExt := filepath.Ext(o.repoFile) repoFileExt := filepath.Ext(o.repoFile)
var lockPath string 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" lockPath = strings.TrimSuffix(o.repoFile, repoFileExt) + ".lock"
} else { } else {
lockPath = o.repoFile + ".lock" lockPath = o.repoFile + ".lock"

@ -238,7 +238,7 @@ func newRootCmdWithConfig(actionConfig *action.Configuration, out io.Writer, arg
cobra.CompDebugln("About to get the different kube-contexts", settings.Debug) cobra.CompDebugln("About to get the different kube-contexts", settings.Debug)
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
if len(settings.KubeConfig) > 0 { if settings.KubeConfig != "" {
loadingRules = &clientcmd.ClientConfigLoadingRules{ExplicitPath: settings.KubeConfig} loadingRules = &clientcmd.ClientConfigLoadingRules{ExplicitPath: settings.KubeConfig}
} }
if config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( if config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(

@ -194,7 +194,7 @@ func (o *searchRepoOptions) buildIndex() (*search.Index, error) {
continue continue
} }
i.AddRepo(n, ind, o.versions || len(o.version) > 0) i.AddRepo(n, ind, o.versions || o.version != "")
} }
return i, nil 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 // 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 // listing the entire content of the current directory which will
// be too many choices for the user to find the real repos) // 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 { if files, err := os.ReadDir("."); err == nil {
for _, file := range files { for _, file := range files {
if strings.HasPrefix(file.Name(), toComplete) { 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, // If the user didn't provide any input to completion,
// we provide a hint that a path can also be used // 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") 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) cobra.CompDebugln(fmt.Sprintf("Completions after checking empty input: %v", completions), settings.Debug)

@ -236,7 +236,7 @@ func (s statusPrinter) WriteTable(out io.Writer) error {
} }
// Hide notes from output - option in install and upgrades // 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)) _, _ = fmt.Fprintf(out, "NOTES:\n%s\n", strings.TrimSpace(rel.Info.Notes))
} }
return nil return nil

@ -382,7 +382,7 @@ func (c *ChartDownloader) ResolveChartVersion(ref, version string) (string, *url
return "", u, err 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 // 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 // URL. And this is an unfortunate problem, as it requires actually going
// through each repo cache file and finding a matching URL. But basically // through each repo cache file and finding a matching URL. But basically

@ -167,7 +167,7 @@ func TestVerifyChart(t *testing.T) {
} }
// The verification is tested at length in the provenance package. Here, // The verification is tested at length in the provenance package. Here,
// we just want a quick sanity check that the v is not empty. // 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") t.Error("Digest missing")
} }
} }

@ -441,21 +441,22 @@ func (m *Manager) safeMoveDeps(deps []*chart.Dependency, source, dest string) er
fmt.Fprintln(m.Out, "Deleting outdated charts") fmt.Fprintln(m.Out, "Deleting outdated charts")
// find all files that exist in dest that do not exist in source; delete them (outdated dependencies) // find all files that exist in dest that do not exist in source; delete them (outdated dependencies)
for _, file := range destFiles { for _, file := range destFiles {
if !file.IsDir() && !existsInSourceDirectory[file.Name()] { if file.IsDir() || existsInSourceDirectory[file.Name()] {
fname := filepath.Join(dest, file.Name()) continue
ch, err := loader.LoadFile(fname) }
if err != nil { fname := filepath.Join(dest, file.Name())
fmt.Fprintf(m.Out, "Could not verify %s for deletion: %s (Skipping)\n", fname, err) ch, err := loader.LoadFile(fname)
continue if err != nil {
} fmt.Fprintf(m.Out, "Could not verify %s for deletion: %s (Skipping)\n", fname, err)
// local dependency - skip continue
if isLocalDependency[ch.Name()] { }
continue // local dependency - skip
} if isLocalDependency[ch.Name()] {
if err := os.Remove(fname); err != nil { continue
fmt.Fprintf(m.Out, "Could not delete %s: %s (Skipping)", fname, err) }
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 { for _, cr := range repos {
if urlutil.Equal(repoURL, cr.Config.URL) { if !urlutil.Equal(repoURL, cr.Config.URL) {
var entry repo.ChartVersions continue
entry, err = findEntryByName(name, cr) }
if err != nil { var entry repo.ChartVersions
// TODO: Where linting is skipped in this function we should entry, err = findEntryByName(name, cr)
// refactor to remove naked returns while ensuring the same if err != nil {
// behavior // TODO: Where linting is skipped in this function we should
//nolint:nakedret // refactor to remove naked returns while ensuring the same
return // behavior
} //nolint:nakedret
var ve *repo.ChartVersion return
ve, err = findVersionedEntry(version, entry) }
if err != nil { var ve *repo.ChartVersion
//nolint:nakedret ve, err = findVersionedEntry(version, entry)
return if err != nil {
} //nolint:nakedret
url, err = repo.ResolveReferenceURL(repoURL, ve.URLs[0]) return
if err != nil { }
//nolint:nakedret url, err = repo.ResolveReferenceURL(repoURL, ve.URLs[0])
return if err != nil {
}
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 //nolint:nakedret
return 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)) url, err = repo.FindChartInRepoURL(repoURL, name, m.Getters, repo.WithChartVersion(version), repo.WithClientTLS(certFile, keyFile, caFile))
if err == nil { if err == nil {

@ -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 // 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) { func parseTemplateExecutingAtErrorType(remainder string) (TraceableError, bool) {
if templateName, after, found := strings.Cut(remainder, ": executing "); found { if templateName, after, found := strings.Cut(remainder, ": executing "); found {
if len(after) == 0 || after[0] != '"' { if after == "" || after[0] != '"' {
return TraceableError{}, false return TraceableError{}, false
} }
// find closing quote for function name // find closing quote for function name

@ -961,7 +961,7 @@ func getManagedFieldsManager() string {
} }
// When no manager is set and no calling application can be found it is unknown // 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" return "unknown"
} }

@ -180,11 +180,8 @@ func (w *statusWaiter) wait(ctx context.Context, resourceList ResourceList, sw w
defer cancel() defer cancel()
resources := []object.ObjMetadata{} resources := []object.ObjMetadata{}
for _, resource := range resourceList { for _, resource := range resourceList {
switch value := AsVersioned(resource).(type) { if value, ok := AsVersioned(resource).(*appsv1.Deployment); ok && value.Spec.Paused {
case *appsv1.Deployment: continue
if value.Spec.Paused {
continue
}
} }
obj, err := object.RuntimeToObjMeta(resource.Object) obj, err := object.RuntimeToObjMeta(resource.Object)
if err != nil { if err != nil {

@ -380,7 +380,7 @@ func TestVerify(t *testing.T) {
if ver, err := signer.Verify(archiveData, sigData, filepath.Base(testChartfile)); err != nil { if ver, err := signer.Verify(archiveData, sigData, filepath.Base(testChartfile)); err != nil {
t.Errorf("Failed to pass verify. Err: %s", err) 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.") t.Error("Verification is missing hash.")
} else if ver.SignedBy == nil { } else if ver.SignedBy == nil {
t.Error("No SignedBy field") t.Error("No SignedBy field")

@ -72,7 +72,7 @@ func generateChartOCIAnnotations(meta *chart.Metadata, creationTime string) map[
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationVersion, meta.Version) chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationVersion, meta.Version)
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationURL, meta.Home) chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationURL, meta.Home)
if len(creationTime) == 0 { if creationTime == "" {
creationTime = time.Now().UTC().Format(time.RFC3339) creationTime = time.Now().UTC().Format(time.RFC3339)
} }
@ -86,11 +86,11 @@ func generateChartOCIAnnotations(meta *chart.Metadata, creationTime string) map[
var maintainerSb strings.Builder var maintainerSb strings.Builder
for maintainerIdx, maintainer := range meta.Maintainers { for maintainerIdx, maintainer := range meta.Maintainers {
if len(maintainer.Name) > 0 { if maintainer.Name != "" {
maintainerSb.WriteString(maintainer.Name) maintainerSb.WriteString(maintainer.Name)
} }
if len(maintainer.Email) > 0 { if maintainer.Email != "" {
maintainerSb.WriteString(" (") maintainerSb.WriteString(" (")
maintainerSb.WriteString(maintainer.Email) maintainerSb.WriteString(maintainer.Email)
maintainerSb.WriteString(")") 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 // 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 string, newValue string) map[string]string {
// Add item to map if its // Add item to map if its
if len(strings.TrimSpace(newValue)) > 0 { if strings.TrimSpace(newValue) != "" {
inputMap[newKey] = newValue inputMap[newKey] = newValue
} }

@ -303,8 +303,7 @@ func ensureTLSConfig(client *auth.Client, setConfig *tls.Config) (*tls.Config, e
case *http.Transport: case *http.Transport:
transport = t transport = t
case *LoggingTransport: case *LoggingTransport:
switch t := t.RoundTripper.(type) { if t, ok := t.RoundTripper.(*http.Transport); ok {
case *http.Transport:
transport = t transport = t
} }
} }

@ -130,7 +130,7 @@ func logResponseBody(resp *http.Response) string {
} }
readBody := buf.String() readBody := buf.String()
if len(readBody) == 0 { if readBody == "" {
return " Response body is empty" return " Response body is empty"
} }
if containsCredentials(readBody) { if containsCredentials(readBody) {

@ -149,27 +149,28 @@ metadata:
for _, out := range hs { for _, out := range hs {
found := false found := false
for _, expect := range data { for _, expect := range data {
if out.Path == expect.path { if out.Path != expect.path {
found = true continue
assert.Equal(t, expect.path, out.Path) }
nameFound := false found = true
for _, expectedName := range expect.name { assert.Equal(t, expect.path, out.Path)
if out.Name == expectedName { nameFound := false
nameFound = true for _, expectedName := range expect.name {
} if out.Name == expectedName {
nameFound = true
} }
assert.True(t, nameFound, "Got unexpected name %s", out.Name) }
kindFound := false assert.True(t, nameFound, "Got unexpected name %s", out.Name)
for _, expectedKind := range expect.kind { kindFound := false
if out.Kind == expectedKind { for _, expectedKind := range expect.kind {
kindFound = true 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) assert.True(t, found, "Result not found: %v", out)
} }

@ -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 // when customer inputs specific version, check whether there's an exact match first
if len(version) != 0 { if version != "" {
for _, ver := range vs { for _, ver := range vs {
if version == ver.Version { if version == ver.Version {
return ver, nil return ver, nil
@ -229,9 +229,9 @@ func (i IndexFile) Get(name, version string) (*ChartVersion, error) {
} }
if constraint.Check(test) { 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) 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) slog.Debug("selected version matching constraint", "chart", name, "constraint", version, "selected", ver.Version)
} }
return ver, nil return ver, nil

@ -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) { func set(data map[string]any, key string, val any) {
// If key is empty, don't set it. // If key is empty, don't set it.
if len(key) == 0 { if key == "" {
return return
} }
data[key] = val 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 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 { if iv, err := strconv.ParseInt(val, 10, 64); err == nil {
return iv return iv
} }

Loading…
Cancel
Save