refactor: enable several checks from gocritic

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
pull/32321/head
Matthieu MOREL 2 months ago
parent d5465e930e
commit 9662fdd73b

@ -84,19 +84,14 @@ linters:
gocritic: gocritic:
disabled-checks: disabled-checks:
- appendAssign - appendAssign
- appendCombine
- assignOp
- badCall - badCall
- commentedOutCode - commentedOutCode
- commentFormatting
- deferInLoop - deferInLoop
- elseif - elseif
- exposedSyncMutex - exposedSyncMutex
- filepathJoin
- hugeParam - hugeParam
- ifElseChain - ifElseChain
- importShadow - importShadow
- nilValReturn
- paramTypeCombine - paramTypeCombine
- ptrToRefParam - ptrToRefParam
- rangeValCopy - rangeValCopy

@ -26,7 +26,7 @@ import (
"helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/internal/test/ensure"
) )
var nonExistingValuesFilePath = filepath.Join("/fake/dir", "values.yaml") var nonExistingValuesFilePath = filepath.FromSlash("/fake/dir/values.yaml")
const testSchema = ` const testSchema = `
{ {

@ -121,7 +121,7 @@ func TestCreate_Overwrite(t *testing.T) {
dir := filepath.Join(tdir, "foo") dir := filepath.Join(tdir, "foo")
tplname := filepath.Join(dir, "templates/hpa.yaml") tplname := filepath.Join(dir, "templates", "hpa.yaml")
writeFile(tplname, []byte("FOO")) writeFile(tplname, []byte("FOO"))
// Now re-run the create // Now re-run the create

@ -64,7 +64,7 @@ func SplitManifests(bigFile string) map[string]string {
d = strings.TrimLeftFunc(d, unicode.IsSpace) d = strings.TrimLeftFunc(d, unicode.IsSpace)
res[fmt.Sprintf(tpl, count)] = d res[fmt.Sprintf(tpl, count)] = d
count = count + 1 count++
} }
return res return res
} }

@ -358,9 +358,9 @@ func TestCopyFileSymlink(t *testing.T) {
tempdir := t.TempDir() tempdir := t.TempDir()
testcases := map[string]string{ testcases := map[string]string{
filepath.Join("./testdata/symlinks/file-symlink"): filepath.Join(tempdir, "dst-file"), filepath.Join(".", "testdata", "symlinks", "file-symlink"): filepath.Join(tempdir, "dst-file"),
filepath.Join("./testdata/symlinks/windows-file-symlink"): filepath.Join(tempdir, "windows-dst-file"), filepath.Join(".", "testdata", "symlinks", "windows-file-symlink"): filepath.Join(tempdir, "windows-dst-file"),
filepath.Join("./testdata/symlinks/invalid-symlink"): filepath.Join(tempdir, "invalid-symlink"), filepath.Join(".", "testdata", "symlinks", "invalid-symlink"): filepath.Join(tempdir, "invalid-symlink"),
} }
for symlink, dst := range testcases { for symlink, dst := range testcases {

@ -201,7 +201,7 @@ func (d *Dependency) printDependencies(chartpath string, out io.Writer, c *chart
// printMissing prints warnings about charts that are present on disk, but are // printMissing prints warnings about charts that are present on disk, but are
// not in Chart.yaml. // not in Chart.yaml.
func (d *Dependency) printMissing(chartpath string, out io.Writer, reqs []*chart.Dependency) { func (d *Dependency) printMissing(chartpath string, out io.Writer, reqs []*chart.Dependency) {
folder := filepath.Join(chartpath, "charts/*") folder := filepath.Join(chartpath, "charts", "*")
files, err := filepath.Glob(folder) files, err := filepath.Glob(folder)
if err != nil { if err != nil {
fmt.Fprintln(out, err) fmt.Fprintln(out, err)

@ -868,21 +868,21 @@ func TestInstallReleaseOutputDir(t *testing.T) {
t.Fatalf("Failed install: %s", err) t.Fatalf("Failed install: %s", err)
} }
_, err = os.Stat(filepath.Join(dir, "hello/templates/goodbye")) _, err = os.Stat(filepath.Join(dir, "hello", "templates", "goodbye"))
req.NoError(err) req.NoError(err)
_, err = os.Stat(filepath.Join(dir, "hello/templates/hello")) _, err = os.Stat(filepath.Join(dir, "hello", "templates", "hello"))
req.NoError(err) req.NoError(err)
_, err = os.Stat(filepath.Join(dir, "hello/templates/with-partials")) _, err = os.Stat(filepath.Join(dir, "hello", "templates", "with-partials"))
req.NoError(err) req.NoError(err)
_, err = os.Stat(filepath.Join(dir, "hello/templates/rbac")) _, err = os.Stat(filepath.Join(dir, "hello", "templates", "rbac"))
req.NoError(err) req.NoError(err)
test.AssertGoldenFile(t, filepath.Join(dir, "hello/templates/rbac"), "rbac.txt") test.AssertGoldenFile(t, filepath.Join(dir, "hello", "templates", "rbac"), "rbac.txt")
_, err = os.Stat(filepath.Join(dir, "hello/templates/empty")) _, err = os.Stat(filepath.Join(dir, "hello", "templates", "empty"))
is.ErrorIs(err, fs.ErrNotExist) is.ErrorIs(err, fs.ErrNotExist)
} }
@ -905,21 +905,21 @@ func TestInstallOutputDirWithReleaseName(t *testing.T) {
t.Fatalf("Failed install: %s", err) t.Fatalf("Failed install: %s", err)
} }
_, err = os.Stat(filepath.Join(newDir, "hello/templates/goodbye")) _, err = os.Stat(filepath.Join(newDir, "hello", "templates", "goodbye"))
req.NoError(err) req.NoError(err)
_, err = os.Stat(filepath.Join(newDir, "hello/templates/hello")) _, err = os.Stat(filepath.Join(newDir, "hello", "templates", "hello"))
req.NoError(err) req.NoError(err)
_, err = os.Stat(filepath.Join(newDir, "hello/templates/with-partials")) _, err = os.Stat(filepath.Join(newDir, "hello", "templates", "with-partials"))
req.NoError(err) req.NoError(err)
_, err = os.Stat(filepath.Join(newDir, "hello/templates/rbac")) _, err = os.Stat(filepath.Join(newDir, "hello", "templates", "rbac"))
req.NoError(err) req.NoError(err)
test.AssertGoldenFile(t, filepath.Join(newDir, "hello/templates/rbac"), "rbac.txt") test.AssertGoldenFile(t, filepath.Join(newDir, "hello", "templates", "rbac"), "rbac.txt")
_, err = os.Stat(filepath.Join(newDir, "hello/templates/empty")) _, err = os.Stat(filepath.Join(newDir, "hello", "templates", "empty"))
is.ErrorIs(err, fs.ErrNotExist) is.ErrorIs(err, fs.ErrNotExist)
} }

@ -178,7 +178,7 @@ func (l *List) Run() ([]ri.Releaser, error) {
} }
if results == nil { if results == nil {
return results, nil return nil, nil
} }
rresults, err := releaseListToV1List(results) rresults, err := releaseListToV1List(results)

@ -26,7 +26,7 @@ import (
"helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/internal/test/ensure"
) )
var nonExistingValuesFilePath = filepath.Join("/fake/dir", "values.yaml") var nonExistingValuesFilePath = filepath.FromSlash("/fake/dir/values.yaml")
const testSchema = ` const testSchema = `
{ {

@ -121,7 +121,7 @@ func TestCreate_Overwrite(t *testing.T) {
dir := filepath.Join(tdir, "foo") dir := filepath.Join(tdir, "foo")
tplname := filepath.Join(dir, "templates/hpa.yaml") tplname := filepath.Join(dir, "templates", "hpa.yaml")
writeFile(tplname, []byte("FOO")) writeFile(tplname, []byte("FOO"))
// Now re-run the create // Now re-run the create

@ -72,7 +72,7 @@ func TestDependencyBuildCmd(t *testing.T) {
} }
// Make sure the actual file got downloaded. // Make sure the actual file got downloaded.
expect := filepath.Join(rootDir, chartname, "charts/reqtest-0.1.0.tgz") expect := filepath.Join(rootDir, chartname, "charts", "reqtest-0.1.0.tgz")
if _, err := os.Stat(expect); err != nil { if _, err := os.Stat(expect); err != nil {
t.Fatal(err) t.Fatal(err)
} }

@ -49,7 +49,7 @@ func TestRepoAddCmd(t *testing.T) {
) )
defer srv2.Stop() defer srv2.Stop()
tmpdir := filepath.Join(t.TempDir(), "path-component.yaml/data") tmpdir := filepath.Join(t.TempDir(), "path-component.yaml", "data")
if err := os.MkdirAll(tmpdir, 0o777); err != nil { if err := os.MkdirAll(tmpdir, 0o777); err != nil {
t.Fatal(err) t.Fatal(err)
} }

@ -171,7 +171,7 @@ func TestRepoRemoveCompletion(t *testing.T) {
rootDir := t.TempDir() rootDir := t.TempDir()
repoFile := filepath.Join(rootDir, "repositories.yaml") repoFile := filepath.Join(rootDir, "repositories.yaml")
repoCache := filepath.Join(rootDir, "cache/") repoCache := filepath.Join(rootDir, "cache")
var testRepoNames = []string{"foo", "bar", "baz"} var testRepoNames = []string{"foo", "bar", "baz"}

@ -382,15 +382,15 @@ func compListCharts(toComplete string, includeFiles bool) ([]string, cobra.Shell
directive := cobra.ShellCompDirectiveDefault directive := cobra.ShellCompDirectiveDefault
if noFile { if noFile {
directive = directive | cobra.ShellCompDirectiveNoFileComp directive |= cobra.ShellCompDirectiveNoFileComp
} }
if noSpace { if noSpace {
directive = directive | cobra.ShellCompDirectiveNoSpace directive |= cobra.ShellCompDirectiveNoSpace
} }
if !includeFiles { if !includeFiles {
// If we should not include files in the completions, // If we should not include files in the completions,
// we should disable file completion // we should disable file completion
directive = directive | cobra.ShellCompDirectiveNoFileComp directive |= cobra.ShellCompDirectiveNoFileComp
} }
return completions, directive return completions, directive
} }

@ -76,7 +76,6 @@ func TestShowPreReleaseChart(t *testing.T) {
outdir, outdir,
contentTmp, contentTmp,
) )
//_, out, err := executeActionCommand(cmd)
_, _, err := executeActionCommand(cmd) _, _, err := executeActionCommand(cmd)
if err != nil { if err != nil {
if tt.fail { if tt.fail {

@ -40,7 +40,7 @@ func TestTemplateCmd(t *testing.T) {
}, },
{ {
name: "check values files", name: "check values files",
cmd: fmt.Sprintf("template '%s' --values '%s'", chartPath, filepath.Join(chartPath, "/charts/subchartA/values.yaml")), cmd: fmt.Sprintf("template '%s' --values '%s'", chartPath, filepath.Join(chartPath, "charts", "subchartA", "values.yaml")),
golden: "output/template-values-files.txt", golden: "output/template-values-files.txt",
}, },
{ {

@ -117,6 +117,6 @@ func TestDiskCache_fileName(t *testing.T) {
cache := &DiskCache{Root: "/tmp/cache"} cache := &DiskCache{Root: "/tmp/cache"}
key := sha256.Sum256([]byte("some data")) key := sha256.Sum256([]byte("some data"))
assert.Equal(t, filepath.Join("/tmp/cache", "13", "1307990e6ba5ca145eb35e99182a9bec46531bc54ddf656a602c780fa0240dee.chart"), cache.fileName(key, CacheChart)) assert.Equal(t, filepath.FromSlash("/tmp/cache/13/1307990e6ba5ca145eb35e99182a9bec46531bc54ddf656a602c780fa0240dee.chart"), cache.fileName(key, CacheChart))
assert.Equal(t, filepath.Join("/tmp/cache", "13", "1307990e6ba5ca145eb35e99182a9bec46531bc54ddf656a602c780fa0240dee.prov"), cache.fileName(key, CacheProv)) assert.Equal(t, filepath.FromSlash("/tmp/cache/13/1307990e6ba5ca145eb35e99182a9bec46531bc54ddf656a602c780fa0240dee.prov"), cache.fileName(key, CacheProv))
} }

@ -278,7 +278,7 @@ func TestDownloadTo_TLS(t *testing.T) {
getter.WithTLSClientConfig( getter.WithTLSClientConfig(
"", "",
"", "",
filepath.Join("../../testdata/rootca.crt"), filepath.FromSlash("../../testdata/rootca.crt"),
), ),
}, },
} }

@ -764,7 +764,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)) url, err = repo.FindChartInRepoURL(repoURL, name, m.Getters, repo.WithChartVersion(version), repo.WithClientTLS(certFile, keyFile, caFile))
if err == nil { 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) err = fmt.Errorf("chart %s not found in %s: %w", name, repoURL, err)
return url, username, password, false, false, "", "", "", err return url, username, password, false, false, "", "", "", err

@ -28,7 +28,7 @@ import (
) )
func TestFuncs(t *testing.T) { func TestFuncs(t *testing.T) {
//TODO write tests for failure cases // TODO write tests for failure cases
tests := []struct { tests := []struct {
tpl, expect string tpl, expect string
vars any vars any

@ -225,7 +225,7 @@ func TestDownload(t *testing.T) {
// A different host is provided for the WithURL from the one used for Get // A different host is provided for the WithURL from the one used for Get
u2, _ := url.ParseRequestURI(crossAuthSrv.URL) u2, _ := url.ParseRequestURI(crossAuthSrv.URL)
host := strings.Split(u2.Host, ":") host := strings.Split(u2.Host, ":")
host[0] = host[0] + "a" host[0] += "a"
u2.Host = strings.Join(host, ":") u2.Host = strings.Join(host, ":")
httpgetter, err = NewHTTPGetter( httpgetter, err = NewHTTPGetter(
WithURL(u2.String()), 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 // A different host is provided for the WithURL from the one used for Get
u2, _ = url.ParseRequestURI(crossAuthSrv.URL) u2, _ = url.ParseRequestURI(crossAuthSrv.URL)
host = strings.Split(u2.Host, ":") host = strings.Split(u2.Host, ":")
host[0] = host[0] + "a" host[0] += "a"
u2.Host = strings.Join(host, ":") u2.Host = strings.Join(host, ":")
httpgetter, err = NewHTTPGetter( httpgetter, err = NewHTTPGetter(
WithURL(u2.String()), WithURL(u2.String()),

@ -38,7 +38,7 @@ func TestDataPath(t *testing.T) {
t.Setenv(xdg.DataHomeEnvVar, "/tmp") t.Setenv(xdg.DataHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile) expected = filepath.FromSlash("/tmp/" + appName + "/" + testFile)
assert.Equal(t, expected, lazy.dataPath(testFile)) assert.Equal(t, expected, lazy.dataPath(testFile))
} }
@ -50,7 +50,7 @@ func TestConfigPath(t *testing.T) {
t.Setenv(xdg.ConfigHomeEnvVar, "/tmp") t.Setenv(xdg.ConfigHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile) expected = filepath.FromSlash("/tmp/" + appName + "/" + testFile)
assert.Equal(t, expected, lazy.configPath(testFile)) assert.Equal(t, expected, lazy.configPath(testFile))
} }
@ -62,7 +62,7 @@ func TestCachePath(t *testing.T) {
t.Setenv(xdg.CacheHomeEnvVar, "/tmp") t.Setenv(xdg.CacheHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile) expected = filepath.FromSlash("/tmp/" + appName + "/" + testFile)
assert.Equal(t, expected, lazy.cachePath(testFile)) assert.Equal(t, expected, lazy.cachePath(testFile))
} }

@ -213,7 +213,7 @@ func Test_ReadyChecker_IsReady_Deployment(t *testing.T) {
wantErr: true, wantErr: true,
}, },
{ {
name: "IsReady Deployments", //TODO fix this one name: "IsReady Deployments", // TODO fix this one
fields: fields{ fields: fields{
client: fake.NewClientset(), client: fake.NewClientset(),
checkJobs: true, checkJobs: true,

@ -76,7 +76,7 @@ func (suite *RegistryScopeTestSuite) Test_1_Check_Push_Request_Scope() {
_, err = suite.RegistryClient.Push(chartData, ref, PushOptCreationTime(testingChartCreationTime)) _, err = suite.RegistryClient.Push(chartData, ref, PushOptCreationTime(testingChartCreationTime))
suite.Require().Error(err, "error pushing good ref because auth server doesn't give proper token") suite.Require().Error(err, "error pushing good ref because auth server doesn't give proper token")
//check the url that authentication server received // check the url that authentication server received
select { select {
case urlStr := <-requestURL: case urlStr := <-requestURL:
u, err := url.Parse(urlStr) u, err := url.Parse(urlStr)
@ -122,7 +122,7 @@ func (suite *RegistryScopeTestSuite) Test_2_Check_Pull_Request_Scope() {
_, err = suite.RegistryClient.Pull(ref) _, err = suite.RegistryClient.Pull(ref)
suite.Require().Error(err, "error pulling a simple chart because auth server doesn't give proper token") suite.Require().Error(err, "error pulling a simple chart because auth server doesn't give proper token")
//check the url that authentication server received // check the url that authentication server received
select { select {
case urlStr := <-requestURL: case urlStr := <-requestURL:
u, err := url.Parse(urlStr) u, err := url.Parse(urlStr)

@ -150,7 +150,7 @@ func setup(suite *TestRegistry, tlsEnabled, insecure bool, auth string) {
suite.Require().NoError(err, "no error finding free port for test auth server") suite.Require().NoError(err, "no error finding free port for test auth server")
defer ln.Close() defer ln.Close()
//set test auth server host // set test auth server host
suite.AuthServerHost = ln.Addr().String() suite.AuthServerHost = ln.Addr().String()
config.Auth = configuration.Auth{ config.Auth = configuration.Auth{

@ -64,7 +64,7 @@ func SplitManifests(bigFile string) map[string]string {
d = strings.TrimLeftFunc(d, unicode.IsSpace) d = strings.TrimLeftFunc(d, unicode.IsSpace)
res[fmt.Sprintf(tpl, count)] = d res[fmt.Sprintf(tpl, count)] = d
count = count + 1 count++
} }
return res return res
} }

@ -318,7 +318,7 @@ func IndexDirectory(dir, baseURL string) (*IndexFile, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
moreArchives, err := filepath.Glob(filepath.Join(dir, "**/*.tgz")) moreArchives, err := filepath.Glob(filepath.Join(dir, "**", "*.tgz"))
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -112,12 +112,14 @@ func TestSQLGet(t *testing.T) {
func TestSQLList(t *testing.T) { func TestSQLList(t *testing.T) {
releases := []*rspb.Release{} releases := []*rspb.Release{}
releases = append(releases, releaseStub("key-1", 1, "default", common.StatusUninstalled)) releases = append(releases,
releases = append(releases, releaseStub("key-2", 1, "default", common.StatusUninstalled)) releaseStub("key-1", 1, "default", common.StatusUninstalled),
releases = append(releases, releaseStub("key-3", 1, "default", common.StatusDeployed)) releaseStub("key-2", 1, "default", common.StatusUninstalled),
releases = append(releases, releaseStub("key-4", 1, "default", common.StatusDeployed)) releaseStub("key-3", 1, "default", common.StatusDeployed),
releases = append(releases, releaseStub("key-5", 1, "default", common.StatusSuperseded)) releaseStub("key-4", 1, "default", common.StatusDeployed),
releases = append(releases, releaseStub("key-6", 1, "default", common.StatusSuperseded)) releaseStub("key-5", 1, "default", common.StatusSuperseded),
releaseStub("key-6", 1, "default", common.StatusSuperseded),
)
sqlDriver, mock := newTestFixtureSQL(t) sqlDriver, mock := newTestFixtureSQL(t)

@ -324,7 +324,6 @@ func (d *MaxHistoryMockDriver) Name() string {
} }
func TestMaxHistoryErrorHandling(t *testing.T) { func TestMaxHistoryErrorHandling(t *testing.T) {
//func TestStorageRemoveLeastRecentWithError(t *testing.T) {
storage := Init(NewMaxHistoryMockDriver(driver.NewMemory())) storage := Init(NewMaxHistoryMockDriver(driver.NewMemory()))
storage.MaxHistory = 1 storage.MaxHistory = 1

@ -422,7 +422,7 @@ func TestParseLiteralNestedLevels(t *testing.T) {
for i := 1; i <= MaxNestedNameLevel+2; i++ { for i := 1; i <= MaxNestedNameLevel+2; i++ {
tmpStr := fmt.Sprintf("name%d", i) tmpStr := fmt.Sprintf("name%d", i)
if i <= MaxNestedNameLevel+1 { if i <= MaxNestedNameLevel+1 {
tmpStr = tmpStr + "." tmpStr += "."
} }
keyMultipleNestedLevels.WriteString(tmpStr) keyMultipleNestedLevels.WriteString(tmpStr)
} }

@ -190,8 +190,6 @@ func (t *parser) key(data map[string]any, nestedNameLevel int) (reterr error) {
return err return err
} }
return fmt.Errorf("key %q has no value", string(k)) return fmt.Errorf("key %q has no value", string(k))
//set(data, string(k), "")
//return err
case last == '[': case last == '[':
// We are in a list index context, so we need to set an index. // We are in a list index context, so we need to set an index.
i, err := t.keyIndex() i, err := t.keyIndex()

@ -750,7 +750,7 @@ func TestParseSetNestedLevels(t *testing.T) {
for i := 1; i <= MaxNestedNameLevel+2; i++ { for i := 1; i <= MaxNestedNameLevel+2; i++ {
tmpStr := fmt.Sprintf("name%d", i) tmpStr := fmt.Sprintf("name%d", i)
if i <= MaxNestedNameLevel+1 { if i <= MaxNestedNameLevel+1 {
tmpStr = tmpStr + "." tmpStr += "."
} }
keyMultipleNestedLevels.WriteString(tmpStr) keyMultipleNestedLevels.WriteString(tmpStr)
} }

Loading…
Cancel
Save