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

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

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

@ -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

@ -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

@ -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")
}
}

@ -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}}
}

@ -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")
}

@ -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

@ -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)
}

@ -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")

@ -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)
}
}

@ -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"

@ -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"

@ -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

@ -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

@ -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 {

@ -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

@ -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)
}
}

@ -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 {

@ -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)
}
})

@ -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"

@ -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(

@ -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)

@ -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

@ -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

@ -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")
}
}

@ -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 {

@ -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

@ -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"
}

@ -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 {

@ -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")

@ -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
}

@ -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
}
}

@ -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) {

@ -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)
}

@ -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

@ -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
}

Loading…
Cancel
Save