diff --git a/.golangci-kustomize.yml b/.golangci-kustomize.yml deleted file mode 100644 index 1ef067984..000000000 --- a/.golangci-kustomize.yml +++ /dev/null @@ -1,58 +0,0 @@ -run: - deadline: 5m - -linters: - disable-all: true - enable: - - bodyclose - - deadcode - - depguard - - dogsled - - dupl -# - errcheck - - exportloopref -# - funlen - - gochecknoinits - - goconst - - gocritic - - gocyclo - - gofmt - - goimports - - gosec - - gosimple - - govet - - ineffassign - - lll - - misspell - - nakedret - - nolintlint - - revive - - staticcheck - - structcheck -# - stylecheck # seems redundant with revive, which replaced golint - - typecheck - - unconvert - - unparam - - unused - - varcheck - - whitespace - -linters-settings: - dupl: - threshold: 400 - lll: - line-length: 170 - gocyclo: - min-complexity: 15 - revive: - rules: - - name: var-naming - arguments: - - [ "ID", "API", "JSON" ] # AllowList - - [ ] # DenyList - -issues: - exclude-rules: - - linters: - - revive - text: "don't use leading" diff --git a/kyaml/.golangci.yml b/.golangci.yml similarity index 50% rename from kyaml/.golangci.yml rename to .golangci.yml index 32932a562..7623b5b89 100644 --- a/kyaml/.golangci.yml +++ b/.golangci.yml @@ -3,47 +3,91 @@ run: deadline: 5m - skip-dirs: - - yaml/internal/k8sgen/pkg - - internal/forked linters: # please, do not use `enable-all`: it's deprecated and will be removed soon. # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint disable-all: true enable: + - asciicheck + - bidichk - bodyclose + - contextcheck +# - cyclop - deadcode - depguard - dogsled - dupl -# - errcheck + - durationcheck +# - errcheck # TODO: enable going forward +# - errname # TODO: enable going forward +# - errorlint # TODO: enable going forward +# - exhaustive # TODO: enable going forward +# - exhaustivestruct - exportloopref +# - forbidigo +# - forcetypeassert # TODO: enable going forward # - funlen +# - gci +# - gochecknoglobals - gochecknoinits +# - gocognit - goconst - gocritic - gocyclo +# - godot +# - godox +# - goerr113 # TODO: enable going forward - gofmt +# - gofumpt + - goheader - goimports +# - gomnd + - gomoddirectives + - gomodguard + - goprintffuncname - gosec - gosimple - govet +# - ifshort + - importas - ineffassign +# - ireturn - lll + - makezero - misspell - nakedret +# - nestif # TODO: enable going forward +# - nilerr # TODO: enable going forward +# - nilnil +# - nlreturn +# - noctx - nolintlint +# - paralleltest +# - prealloc # TODO: enable going forward + - predeclared + - promlinter - revive + - rowserrcheck + - sqlclosecheck - staticcheck - structcheck -# - stylecheck # seems redundant with revive, which replaced golint +# - stylecheck + - tagliatelle + - tenv +# - testpackage # TODO: enable going forward + - thelper + - tparallel - typecheck - unconvert - unparam - unused - varcheck +# - varnamelen + - wastedassign - whitespace +# - wrapcheck # TODO: enable going forward +# - wsl linters-settings: dupl: @@ -58,11 +102,14 @@ linters-settings: arguments: - [ "ID", "API", "JSON" ] # AllowList - [ ] # DenyList + gomoddirectives: + replace-local: true gosec: config: G306: "0644" issues: + max-same-issues: 0 exclude-rules: - linters: - revive diff --git a/Makefile b/Makefile index d69ca93bb..1d6d80653 100644 --- a/Makefile +++ b/Makefile @@ -203,15 +203,15 @@ clean-kustomize-external-go-plugin: .PHONY: lint-kustomize lint-kustomize: $(MYGOBIN)/golangci-lint-kustomize $(builtinplugins) cd api; $(MYGOBIN)/golangci-lint-kustomize \ - -c ../.golangci-kustomize.yml \ + -c ../.golangci.yml \ --path-prefix api \ run ./... cd kustomize; $(MYGOBIN)/golangci-lint-kustomize \ - -c ../.golangci-kustomize.yml \ + -c ../.golangci.yml \ --path-prefix kustomize \ run ./... cd cmd/pluginator; $(MYGOBIN)/golangci-lint-kustomize \ - -c ../../.golangci-kustomize.yml \ + -c ../../.golangci.yml \ --path-prefix cmd/pluginator \ run ./... diff --git a/api/hasher/hasher_test.go b/api/hasher/hasher_test.go index 0235d409e..a0de2bb4f 100644 --- a/api/hasher/hasher_test.go +++ b/api/hasher/hasher_test.go @@ -341,6 +341,7 @@ data: // The return value indicates whether we should skip the rest of the test case // due to the error result. func SkipRest(t *testing.T, desc string, err error, contains string) bool { + t.Helper() if err != nil { if len(contains) == 0 { t.Errorf("case %q, expect nil error but got %q", desc, err.Error()) diff --git a/api/internal/accumulator/resaccumulator_test.go b/api/internal/accumulator/resaccumulator_test.go index 1d2140c1e..6cc565682 100644 --- a/api/internal/accumulator/resaccumulator_test.go +++ b/api/internal/accumulator/resaccumulator_test.go @@ -22,6 +22,7 @@ import ( ) func makeResAccumulator(t *testing.T) *ResAccumulator { + t.Helper() ra := MakeEmptyAccumulator() err := ra.MergeConfig(builtinconfig.MakeDefaultConfig()) if err != nil { @@ -133,6 +134,7 @@ func TestResolveVarsOneUnused(t *testing.T) { } func expectLog(t *testing.T, log bytes.Buffer, expect string) { + t.Helper() if !strings.Contains(log.String(), expect) { t.Fatalf("expected log containing '%s', got '%s'", expect, log.String()) } diff --git a/api/internal/target/maker_test.go b/api/internal/target/maker_test.go index 9d4f9b1ef..67f1d8dbe 100644 --- a/api/internal/target/maker_test.go +++ b/api/internal/target/maker_test.go @@ -20,6 +20,7 @@ func makeAndLoadKustTarget( t *testing.T, fSys filesys.FileSystem, root string) *target.KustTarget { + t.Helper() kt := makeKustTargetWithRf(t, fSys, root, provider.NewDefaultDepProvider()) if err := kt.Load(); err != nil { t.Fatalf("Unexpected load error %v", err) @@ -32,6 +33,7 @@ func makeKustTargetWithRf( fSys filesys.FileSystem, root string, pvd *provider.DepProvider) *target.KustTarget { + t.Helper() ldr, err := fLdr.NewLoader(fLdr.RestrictionRootOnly, root, fSys) if err != nil { t.Fatal(err) diff --git a/api/konfig/plugins_test.go b/api/konfig/plugins_test.go index f3ed8e828..87320a19f 100644 --- a/api/konfig/plugins_test.go +++ b/api/konfig/plugins_test.go @@ -179,9 +179,11 @@ func TestDefaultAbsPluginHomeNoXdgJustHomeDir(t *testing.T) { } func setenv(t *testing.T, key, value string) { + t.Helper() require.NoError(t, os.Setenv(key, value)) } func unsetenv(t *testing.T, key string) { + t.Helper() require.NoError(t, os.Unsetenv(key)) } diff --git a/api/krusty/fnplugin_test.go b/api/krusty/fnplugin_test.go index 88fa8dee8..e4d5fa83b 100644 --- a/api/krusty/fnplugin_test.go +++ b/api/krusty/fnplugin_test.go @@ -214,6 +214,7 @@ spec: } func skipIfNoDocker(t *testing.T) { + t.Helper() if _, err := exec.LookPath("docker"); err != nil { t.Skip("skipping because docker binary wasn't found in PATH") } diff --git a/api/krusty/pluginenv_test.go b/api/krusty/pluginenv_test.go index a4d8c230c..86351e780 100644 --- a/api/krusty/pluginenv_test.go +++ b/api/krusty/pluginenv_test.go @@ -67,6 +67,7 @@ metadata: } func makeTmpDir(t *testing.T) string { + t.Helper() base, err := os.Getwd() if err != nil { t.Fatalf("err %v", err) diff --git a/api/loader/fileloader_test.go b/api/loader/fileloader_test.go index b276121cb..79cc4050e 100644 --- a/api/loader/fileloader_test.go +++ b/api/loader/fileloader_test.go @@ -240,6 +240,7 @@ func commonSetupForLoaderRestrictionTest() (string, filesys.FileSystem, error) { // in or below the loader root. func doSanityChecksAndDropIntoBase( t *testing.T, l ifc.Loader) ifc.Loader { + t.Helper() data, err := l.Load(path.Join("base", "okayData")) if err != nil { t.Fatalf("unexpected error: %v", err) diff --git a/api/resmap/reswrangler_test.go b/api/resmap/reswrangler_test.go index 44f3f11a9..d254ad9f5 100644 --- a/api/resmap/reswrangler_test.go +++ b/api/resmap/reswrangler_test.go @@ -56,12 +56,14 @@ var origin2 = &resource.Origin{ } func doAppend(t *testing.T, w ResMap, r *resource.Resource) { + t.Helper() err := w.Append(r) if err != nil { t.Fatalf("append error: %v", err) } } func doRemove(t *testing.T, w ResMap, id resid.ResId) { + t.Helper() err := w.Remove(id) if err != nil { t.Fatalf("remove error: %v", err) diff --git a/api/resmap/selector_test.go b/api/resmap/selector_test.go index 922fb1c63..e31642e12 100644 --- a/api/resmap/selector_test.go +++ b/api/resmap/selector_test.go @@ -13,6 +13,7 @@ import ( ) func setupRMForPatchTargets(t *testing.T) ResMap { + t.Helper() result, err := rmF.NewResMapFromBytes([]byte(` apiVersion: group1/v1 kind: Kind1 diff --git a/api/resource/resource.go b/api/resource/resource.go index faf882045..9997e408b 100644 --- a/api/resource/resource.go +++ b/api/resource/resource.go @@ -26,7 +26,6 @@ type Resource struct { refVarNames []string } -// nolint var BuildAnnotations = []string{ utils.BuildAnnotationPreviousKinds, utils.BuildAnnotationPreviousNames, diff --git a/api/testutils/filtertest/runfilter.go b/api/testutils/filtertest/runfilter.go index 95f8d26c3..9c6d308b3 100644 --- a/api/testutils/filtertest/runfilter.go +++ b/api/testutils/filtertest/runfilter.go @@ -32,6 +32,7 @@ func run(input string, f kio.Filter) (string, error) { // RunFilter runs filter and panic if there is error func RunFilter(t *testing.T, input string, f kio.Filter) string { + t.Helper() output, err := run(input, f) if !assert.NoError(t, err) { t.FailNow() @@ -41,6 +42,7 @@ func RunFilter(t *testing.T, input string, f kio.Filter) string { // RunFilterE runs filter and return error if there is func RunFilterE(t *testing.T, input string, f kio.Filter) (string, error) { + t.Helper() output, err := run(input, f) if err != nil { return "", err diff --git a/api/testutils/kusttest/harness.go b/api/testutils/kusttest/harness.go index 412502a50..c60a614a5 100644 --- a/api/testutils/kusttest/harness.go +++ b/api/testutils/kusttest/harness.go @@ -22,11 +22,13 @@ type Harness struct { } func MakeHarness(t *testing.T) Harness { + t.Helper() return MakeHarnessWithFs(t, filesys.MakeFsInMemory()) } func MakeHarnessWithFs( t *testing.T, fSys filesys.FileSystem) Harness { + t.Helper() return Harness{ t: t, fSys: fSys, diff --git a/api/testutils/kusttest/harnessenhanced.go b/api/testutils/kusttest/harnessenhanced.go index fa33f5db8..bf77155bb 100644 --- a/api/testutils/kusttest/harnessenhanced.go +++ b/api/testutils/kusttest/harnessenhanced.go @@ -47,6 +47,7 @@ type HarnessEnhanced struct { } func MakeEnhancedHarness(t *testing.T) *HarnessEnhanced { + t.Helper() r := makeBaseEnhancedHarness(t) r.Harness = MakeHarnessWithFs(t, filesys.MakeFsInMemory()) // Point the Harness's file loader to the root ('/') @@ -56,6 +57,7 @@ func MakeEnhancedHarness(t *testing.T) *HarnessEnhanced { } func MakeEnhancedHarnessWithTmpRoot(t *testing.T) *HarnessEnhanced { + t.Helper() r := makeBaseEnhancedHarness(t) fSys := filesys.MakeFsOnDisk() r.Harness = MakeHarnessWithFs(t, fSys) @@ -72,6 +74,7 @@ func MakeEnhancedHarnessWithTmpRoot(t *testing.T) *HarnessEnhanced { } func makeBaseEnhancedHarness(t *testing.T) *HarnessEnhanced { + t.Helper() rf := resmap.NewFactory( provider.NewDefaultDepProvider().GetResourceFactory()) return &HarnessEnhanced{ diff --git a/api/testutils/kusttest/hasgett.go b/api/testutils/kusttest/hasgett.go index 33496b9d2..822f99fde 100644 --- a/api/testutils/kusttest/hasgett.go +++ b/api/testutils/kusttest/hasgett.go @@ -26,6 +26,7 @@ func AssertActualEqualsExpectedWithTweak( t *testing.T, m resmap.ResMap, tweaker func([]byte) []byte, expected string) { + t.Helper() if m == nil { t.Fatalf("Map should not be nil.") } @@ -49,13 +50,14 @@ func AssertActualEqualsExpectedWithTweak( // Pretty printing of file differences. func reportDiffAndFail( t *testing.T, actual []byte, expected string) { + t.Helper() sE, maxLen := convertToArray(expected) sA, _ := convertToArray(string(actual)) fmt.Println("===== ACTUAL BEGIN ========================================") fmt.Print(string(actual)) fmt.Println("===== ACTUAL END ==========================================") format := fmt.Sprintf("%%s %%-%ds %%s\n", maxLen+4) - limit := 0 + var limit int if len(sE) < len(sA) { limit = len(sE) } else { diff --git a/api/testutils/kusttest/plugintestenv.go b/api/testutils/kusttest/plugintestenv.go index 0bc5bd183..460e57e4c 100644 --- a/api/testutils/kusttest/plugintestenv.go +++ b/api/testutils/kusttest/plugintestenv.go @@ -25,6 +25,7 @@ type pluginTestEnv struct { // newPluginTestEnv returns a new instance of pluginTestEnv. func newPluginTestEnv(t *testing.T) *pluginTestEnv { + t.Helper() return &pluginTestEnv{t: t} } diff --git a/api/testutils/resmaptest/rmbuilder.go b/api/testutils/resmaptest/rmbuilder.go index 5b725c3c4..1eea23b19 100644 --- a/api/testutils/resmaptest/rmbuilder.go +++ b/api/testutils/resmaptest/rmbuilder.go @@ -20,18 +20,22 @@ type rmBuilder struct { } func NewSeededRmBuilder(t *testing.T, rf *resource.Factory, m resmap.ResMap) *rmBuilder { + t.Helper() return &rmBuilder{t: t, rf: rf, m: m} } func NewRmBuilder(t *testing.T, rf *resource.Factory) *rmBuilder { + t.Helper() return NewSeededRmBuilder(t, rf, resmap.New()) } func NewRmBuilderDefault(t *testing.T) *rmBuilder { + t.Helper() return NewSeededRmBuilderDefault(t, resmap.New()) } func NewSeededRmBuilderDefault(t *testing.T, m resmap.ResMap) *rmBuilder { + t.Helper() return NewSeededRmBuilder( t, provider.NewDefaultDepProvider().GetResourceFactory(), m) } diff --git a/api/testutils/valtest/fakevalidator.go b/api/testutils/valtest/fakevalidator.go index 7e7daadfa..9da5a38ca 100644 --- a/api/testutils/valtest/fakevalidator.go +++ b/api/testutils/valtest/fakevalidator.go @@ -22,11 +22,13 @@ const SAD = "i'm not happy Bob, NOT HAPPY" // MakeHappyMapValidator makes a fakeValidator that always passes. func MakeHappyMapValidator(t *testing.T) *fakeValidator { + t.Helper() return &fakeValidator{happy: true, t: t} } // MakeSadMapValidator makes a fakeValidator that always fails. func MakeSadMapValidator(t *testing.T) *fakeValidator { + t.Helper() return &fakeValidator{happy: false, t: t} } diff --git a/api/types/helmchartargs.go b/api/types/helmchartargs.go index 32575835d..05d540462 100644 --- a/api/types/helmchartargs.go +++ b/api/types/helmchartargs.go @@ -71,7 +71,7 @@ type HelmChart struct { // IncludeCRDs specifies if Helm should also generate CustomResourceDefinitions. // Defaults to 'false'. - IncludeCRDs bool `json:"includeCRDs,omitempty" yaml:"includeCRDs,omitempty"` + IncludeCRDs bool `json:"includeCRDs,omitempty" yaml:"includeCRDs,omitempty"` // nolint: tagliatelle } // HelmChartArgs contains arguments to helm. diff --git a/cmd/config/.golangci.yml b/cmd/config/.golangci.yml deleted file mode 100644 index 18de10587..000000000 --- a/cmd/config/.golangci.yml +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright 2019 The Kubernetes Authors. -# SPDX-License-Identifier: Apache-2.0 - -run: - deadline: 5m - -linters: - # please, do not use `enable-all`: it's deprecated and will be removed soon. - # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint - disable-all: true - enable: - - bodyclose - - deadcode - - depguard - - dogsled - - dupl -# - errcheck - - exportloopref -# - funlen - - gochecknoinits - - goconst - - gocritic - - gocyclo - - gofmt - - goimports - - gosec - - gosimple - - govet - - ineffassign - - lll - - misspell - - nakedret - - nolintlint - - revive - - staticcheck - - structcheck -# - stylecheck # seems redundant with revive, which replaced golint - - typecheck - - unconvert - - unparam - - unused - - varcheck - - whitespace - -linters-settings: - dupl: - threshold: 400 - lll: - line-length: 170 - gocyclo: - min-complexity: 30 - revive: - rules: - - name: var-naming - arguments: - - [ "ID", "API", "JSON" ] # AllowList - - [ ] # DenyList - gosec: - config: - G306: "0644" - -issues: - exclude-rules: - - linters: - - revive - text: "don't use leading" diff --git a/cmd/config/Makefile b/cmd/config/Makefile index 80b936436..63f51539b 100644 --- a/cmd/config/Makefile +++ b/cmd/config/Makefile @@ -37,7 +37,8 @@ lint: $(GOBIN)/golangci-lint $(GOBIN)/golangci-lint \ --skip-dirs $(k8sGenDir) \ run ./... \ - --path-prefix=cmd/config + --path-prefix=cmd/config \ + -c ../../.golangci.yml license: $(GOBIN)/addlicense $(GOBIN)/addlicense \ diff --git a/cmd/config/internal/commands/annotate_test.go b/cmd/config/internal/commands/annotate_test.go index 33c86f43a..cbf20f11c 100644 --- a/cmd/config/internal/commands/annotate_test.go +++ b/cmd/config/internal/commands/annotate_test.go @@ -88,6 +88,7 @@ func TestAnnotateCommand(t *testing.T) { } func initTestDir(t *testing.T) string { + t.Helper() d, err := ioutil.TempDir("", "kustomize-annotate-test") if !assert.NoError(t, err) { t.FailNow() diff --git a/cmd/config/internal/commands/cat.go b/cmd/config/internal/commands/cat.go index 53ccdc906..62e8f3d96 100644 --- a/cmd/config/internal/commands/cat.go +++ b/cmd/config/internal/commands/cat.go @@ -166,7 +166,6 @@ func (r *CatRunner) catFilters() []kio.Filter { return fltrs } -// nolint func (r *CatRunner) out(w io.Writer) ([]kio.Writer, error) { var outputs []kio.Writer var functionConfig *yaml.RNode diff --git a/cmd/config/internal/commands/e2e/test_util_test.go b/cmd/config/internal/commands/e2e/test_util_test.go index 38c1cbbc6..1bf83c8f9 100644 --- a/cmd/config/internal/commands/e2e/test_util_test.go +++ b/cmd/config/internal/commands/e2e/test_util_test.go @@ -36,6 +36,7 @@ type test struct { } func runTests(t *testing.T, tests []test) { + t.Helper() dir := build() bin := filepath.Join(dir, kyamlBin) diff --git a/cmd/config/internal/commands/sink.go b/cmd/config/internal/commands/sink.go index 3efd381de..653c05302 100644 --- a/cmd/config/internal/commands/sink.go +++ b/cmd/config/internal/commands/sink.go @@ -46,7 +46,6 @@ See discussion in https://github.com/kubernetes-sigs/kustomize/issues/3953.`) return err } -// nolint func (r *SinkRunner) runE(c *cobra.Command, args []string) error { var outputs []kio.Writer if len(args) == 1 { diff --git a/cmd/config/runner/runner.go b/cmd/config/runner/runner.go index 38fe0ae11..6e4adb0e1 100644 --- a/cmd/config/runner/runner.go +++ b/cmd/config/runner/runner.go @@ -132,11 +132,11 @@ var StackOnError bool const cmdName = "kustomize fn" // FixDocs replaces instances of old with new in the docs for c -func FixDocs(new string, c *cobra.Command) { - c.Use = strings.ReplaceAll(c.Use, cmdName, new) - c.Short = strings.ReplaceAll(c.Short, cmdName, new) - c.Long = strings.ReplaceAll(c.Long, cmdName, new) - c.Example = strings.ReplaceAll(c.Example, cmdName, new) +func FixDocs(newStr string, c *cobra.Command) { + c.Use = strings.ReplaceAll(c.Use, cmdName, newStr) + c.Short = strings.ReplaceAll(c.Short, cmdName, newStr) + c.Long = strings.ReplaceAll(c.Long, cmdName, newStr) + c.Example = strings.ReplaceAll(c.Example, cmdName, newStr) } // containsString returns true if slice contains s diff --git a/cmd/pluginator/internal/krmfunction/converter_test.go b/cmd/pluginator/internal/krmfunction/converter_test.go index aa87571a1..15558ec46 100644 --- a/cmd/pluginator/internal/krmfunction/converter_test.go +++ b/cmd/pluginator/internal/krmfunction/converter_test.go @@ -12,6 +12,7 @@ import ( ) func makeTempDir(t *testing.T) string { + t.Helper() s, err := ioutil.TempDir("", "pluginator-*") assert.NoError(t, err) return s @@ -99,6 +100,7 @@ items: } func runKrmFunction(t *testing.T, input []byte, dir string) []byte { + t.Helper() cmd := exec.Command("go", "run", ".") ib := bytes.NewReader(input) cmd.Stdin = ib diff --git a/kustomize/commands/create/create_test.go b/kustomize/commands/create/create_test.go index 3d0624f74..7d869f4b7 100644 --- a/kustomize/commands/create/create_test.go +++ b/kustomize/commands/create/create_test.go @@ -16,6 +16,7 @@ import ( var factory = provider.NewDefaultDepProvider().GetResourceFactory() func readKustomizationFS(t *testing.T, fSys filesys.FileSystem) *types.Kustomization { + t.Helper() kf, err := kustfile.NewKustomizationFile(fSys) if err != nil { t.Errorf("unexpected new error %v", err) diff --git a/kustomize/commands/edit/add/addmetadata_test.go b/kustomize/commands/edit/add/addmetadata_test.go index c3c5ca55c..2c2c7980a 100644 --- a/kustomize/commands/edit/add/addmetadata_test.go +++ b/kustomize/commands/edit/add/addmetadata_test.go @@ -16,6 +16,7 @@ import ( ) func makeKustomization(t *testing.T) *types.Kustomization { + t.Helper() fSys := filesys.MakeFsInMemory() testutils_test.WriteTestKustomization(fSys) kf, err := kustfile.NewKustomizationFile(fSys) diff --git a/kustomize/commands/edit/remove/removemetadata_test.go b/kustomize/commands/edit/remove/removemetadata_test.go index 54ad78fff..53afe6129 100644 --- a/kustomize/commands/edit/remove/removemetadata_test.go +++ b/kustomize/commands/edit/remove/removemetadata_test.go @@ -27,6 +27,7 @@ func makeKustomizationFS() filesys.FileSystem { } func readKustomizationFS(t *testing.T, fSys filesys.FileSystem) *types.Kustomization { + t.Helper() kf, err := kustfile.NewKustomizationFile(fSys) if err != nil { t.Errorf("unexpected new error %v", err) @@ -39,6 +40,7 @@ func readKustomizationFS(t *testing.T, fSys filesys.FileSystem) *types.Kustomiza } func makeKustomization(t *testing.T) *types.Kustomization { + t.Helper() fSys := makeKustomizationFS() return readKustomizationFS(t, fSys) } diff --git a/kustomize/commands/edit/remove_test/removetest.go b/kustomize/commands/edit/remove_test/removetest.go index 2fdced459..062ee8745 100644 --- a/kustomize/commands/edit/remove_test/removetest.go +++ b/kustomize/commands/edit/remove_test/removetest.go @@ -43,6 +43,7 @@ type Case struct { // collection Name (e.g. transformers or resources) and newRemoveCmdToTest function. func ExecuteTestCases(t *testing.T, testCases []Case, collectionName string, newRemoveCmdToTest func(filesys.FileSystem) *cobra.Command) { + t.Helper() for _, tc := range testCases { t.Run(tc.Description, func(t *testing.T) { fSys := filesys.MakeFsInMemory() diff --git a/kustomize/commands/edit/set/setannotation_test.go b/kustomize/commands/edit/set/setannotation_test.go index a109301fb..9b1a5d06f 100644 --- a/kustomize/commands/edit/set/setannotation_test.go +++ b/kustomize/commands/edit/set/setannotation_test.go @@ -17,6 +17,7 @@ const invalidAnnotationKey string = "invalid annotation key: see the syntax and "https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/" func makeAnnotationKustomization(t *testing.T) *types.Kustomization { + t.Helper() fSys := filesys.MakeFsInMemory() testutils_test.WriteTestKustomization(fSys) kf, err := kustfile.NewKustomizationFile(fSys) diff --git a/kustomize/commands/edit/set/setlabel_test.go b/kustomize/commands/edit/set/setlabel_test.go index 749dccf30..1c755b3cf 100644 --- a/kustomize/commands/edit/set/setlabel_test.go +++ b/kustomize/commands/edit/set/setlabel_test.go @@ -14,6 +14,7 @@ import ( ) func makeKustomization(t *testing.T) *types.Kustomization { + t.Helper() fSys := filesys.MakeFsInMemory() testutils_test.WriteTestKustomization(fSys) kf, err := kustfile.NewKustomizationFile(fSys) diff --git a/kyaml/Makefile b/kyaml/Makefile index 0346a522c..825abb9fa 100644 --- a/kyaml/Makefile +++ b/kyaml/Makefile @@ -34,7 +34,10 @@ clean: lint: $(MYGOBIN)/golangci-lint $(MYGOBIN)/golangci-lint \ run ./... \ - --path-prefix=kyaml + --path-prefix=kyaml \ + -c ../.golangci.yml \ + --skip-dirs yaml/internal/k8sgen/pkg \ + --skip-dirs internal/forked license: $(MYGOBIN)/addlicense diff --git a/kyaml/copyutil/copyutil.go b/kyaml/copyutil/copyutil.go index 3b7d01784..e66ec6911 100644 --- a/kyaml/copyutil/copyutil.go +++ b/kyaml/copyutil/copyutil.go @@ -188,8 +188,7 @@ func SyncFile(src, dst string) error { // deleteFile deletes file from path, returns no error if file doesn't exist func deleteFile(path string) error { - _, err := os.Stat(path) - if err != nil { + if _, err := os.Stat(path); err != nil { // return nil if file doesn't exist return nil } diff --git a/kyaml/filesys/confirmeddir_test.go b/kyaml/filesys/confirmeddir_test.go index bcdb817c3..fdc9ae90a 100644 --- a/kyaml/filesys/confirmeddir_test.go +++ b/kyaml/filesys/confirmeddir_test.go @@ -14,8 +14,7 @@ import ( func TestJoin(t *testing.T) { fSys := MakeFsInMemory() - err := fSys.Mkdir("/foo") - if err != nil { + if err := fSys.Mkdir("/foo"); err != nil { t.Fatalf("unexpected err: %v", err) } d, f, err := fSys.CleanedAbs("/foo") diff --git a/kyaml/filesys/filesystem_test.go b/kyaml/filesys/filesystem_test.go index 9599e6c45..a84943c96 100644 --- a/kyaml/filesys/filesystem_test.go +++ b/kyaml/filesys/filesystem_test.go @@ -26,6 +26,7 @@ func TestNotExistErr(t *testing.T) { } func testNotExistErr(t *testing.T, fs FileSystem) { + t.Helper() const path = "bad-dir/file.txt" err := fs.RemoveAll(path) diff --git a/kyaml/filesys/fsnode_test.go b/kyaml/filesys/fsnode_test.go index 29dd3fb3d..b880f1bce 100644 --- a/kyaml/filesys/fsnode_test.go +++ b/kyaml/filesys/fsnode_test.go @@ -96,6 +96,7 @@ func TestMakeFsInMemory(t *testing.T) { func runBasicOperations( t *testing.T, tName string, isFSysRooted bool, cases []pathCase, fSys FileSystem) { + t.Helper() for _, c := range cases { err := fSys.WriteFile(c.arg, []byte(content)) if c.errStr != "" { @@ -370,6 +371,7 @@ func TestAddFile(t *testing.T) { func checkNode( t *testing.T, what string, f *fsNode, name string, size int, isDir bool, path string) { + t.Helper() if f.isNodeADir() != isDir { t.Fatalf("%s; unexpected isNodeADir = %v", what, f.isNodeADir()) } @@ -387,6 +389,7 @@ func checkNode( func checkOsStat( t *testing.T, what string, f File, name string, size int, isDir bool) { + t.Helper() info, err := f.Stat() if err != nil { t.Fatalf("%s; unexpected stat error %v", what, err) @@ -473,6 +476,7 @@ var bunchOfFiles = []struct { } func makeLoadedFileTree(t *testing.T) *fsNode { + t.Helper() n := MakeEmptyDirInMemory() var err error expectedFileCount := 0 @@ -487,8 +491,7 @@ func makeLoadedFileTree(t *testing.T) *fsNode { t.Fatalf("unexpected error %v", err) } } - fc := n.FileCount() - if fc != expectedFileCount { + if fc := n.FileCount(); fc != expectedFileCount { t.Fatalf("expected file count %d, got %d", expectedFileCount, fc) } @@ -565,8 +568,7 @@ func TestRemove(t *testing.T) { } orgCount -= 1 - fc := n.FileCount() - if fc != orgCount { + if fc := n.FileCount(); fc != orgCount { t.Fatalf("expected file count %d, got %d", orgCount, fc) } diff --git a/kyaml/filesys/fsondisk_test.go b/kyaml/filesys/fsondisk_test.go index 221f10daa..80a9cba01 100644 --- a/kyaml/filesys/fsondisk_test.go +++ b/kyaml/filesys/fsondisk_test.go @@ -17,6 +17,7 @@ import ( ) func makeTestDir(t *testing.T) (FileSystem, string) { + t.Helper() fSys := MakeFsOnDisk() td, err := ioutil.TempDir("", "kustomize_testing_dir") if err != nil { diff --git a/kyaml/filesys/util.go b/kyaml/filesys/util.go index 4d8958a2b..fdbe5e2c7 100644 --- a/kyaml/filesys/util.go +++ b/kyaml/filesys/util.go @@ -121,7 +121,7 @@ func InsertPathPart(path string, pos int, part string) string { result := make([]string, len(parts)+1) copy(result, parts[0:pos]) result[pos] = part - return PathJoin(append(result, parts[pos:]...)) + return PathJoin(append(result, parts[pos:]...)) // nolint: makezero } func IsHiddenFilePath(pattern string) bool { diff --git a/kyaml/filesys/util_test.go b/kyaml/filesys/util_test.go index da8d3f6bc..24c08cfb5 100644 --- a/kyaml/filesys/util_test.go +++ b/kyaml/filesys/util_test.go @@ -159,6 +159,7 @@ func TestPathSplitAndJoin(t *testing.T) { } for n, c := range cases { f := func(t *testing.T, original string, expected []string) { + t.Helper() actual := PathSplit(original) if len(actual) != len(expected) { t.Fatalf( diff --git a/kyaml/fn/framework/frameworktestutil/frameworktestutil.go b/kyaml/fn/framework/frameworktestutil/frameworktestutil.go index 246c6e2e0..8a6ec6c49 100644 --- a/kyaml/fn/framework/frameworktestutil/frameworktestutil.go +++ b/kyaml/fn/framework/frameworktestutil/frameworktestutil.go @@ -81,6 +81,7 @@ type CommandResultsChecker struct { // Assert runs the command with the input provided in each valid test directory // and verifies that the actual output and error match the fixtures in the directory. func (rc *CommandResultsChecker) Assert(t *testing.T) bool { + t.Helper() if rc.ConfigInputFilename == "" { rc.ConfigInputFilename = DefaultConfigInputFilename } @@ -109,6 +110,7 @@ func (rc *CommandResultsChecker) isTestDir(path string) bool { } func (rc *CommandResultsChecker) runInCurrentDir(t *testing.T) (string, string) { + t.Helper() _, err := os.Stat(rc.ConfigInputFilename) if os.IsNotExist(err) { t.Errorf("Test case is missing FunctionConfig input file (default: %s)", DefaultConfigInputFilename) @@ -180,6 +182,7 @@ type ProcessorResultsChecker struct { // Assert runs the processor with the input provided in each valid test directory // and verifies that the actual output and error match the fixtures in the directory. func (rc *ProcessorResultsChecker) Assert(t *testing.T) bool { + t.Helper() if rc.InputFilename == "" { rc.InputFilename = DefaultInputFilename } @@ -205,6 +208,7 @@ func (rc *ProcessorResultsChecker) isTestDir(path string) bool { } func (rc *ProcessorResultsChecker) runInCurrentDir(t *testing.T) (string, string) { + t.Helper() _, err := os.Stat(rc.InputFilename) if os.IsNotExist(err) { t.Errorf("Test case is missing input file (default: %s)", DefaultInputFilename) @@ -232,6 +236,7 @@ type AssertionFunc func(t *testing.T, expected string, actual string) // RequireEachLineMatches is an AssertionFunc that treats each line of expected string // as a regex that must match the actual string. func RequireEachLineMatches(t *testing.T, expected, actual string) { + t.Helper() // Check that each expected line matches the output actual = standardizeSpacing(actual) for _, msg := range strings.Split(standardizeSpacing(expected), "\n") { @@ -242,6 +247,7 @@ func RequireEachLineMatches(t *testing.T, expected, actual string) { // RequireStrippedStringsEqual is an AssertionFunc that does a simple string comparison // of expected and actual after normalizing whitespace. func RequireStrippedStringsEqual(t *testing.T, expected, actual string) { + t.Helper() require.Equal(t, standardizeSpacing(expected), standardizeSpacing(actual)) @@ -330,6 +336,7 @@ func (rc *checkerCore) shouldUpdateFixtures() bool { } func (rc *checkerCore) updateFixtures(t *testing.T, actualOutput string, actualError string) { + t.Helper() if actualError != "" { require.NoError(t, ioutil.WriteFile(rc.expectedErrorFilename, []byte(actualError), 0600)) } @@ -340,14 +347,17 @@ func (rc *checkerCore) updateFixtures(t *testing.T, actualOutput string, actualE } func (rc *checkerCore) assertOutputMatches(t *testing.T, expected string, actual string) { + t.Helper() rc.outputAssertionFunc(t, expected, actual) } func (rc *checkerCore) assertErrorMatches(t *testing.T, expected string, actual string) { + t.Helper() rc.errorAssertionFunc(t, expected, actual) } func (rc *checkerCore) readAssertionFiles(t *testing.T) (string, string) { + t.Helper() // read the expected results var expectedOutput, expectedError string if rc.expectedOutputFilename != "" { @@ -385,6 +395,7 @@ func (rc *checkerCore) readAssertionFiles(t *testing.T) (string, string) { // under test in each directory, and then runs assertions on the returned output and error results. // It triggers a test failure if no valid test directories were found. func runAllTestCases(t *testing.T, checker resultsChecker) { + t.Helper() checker.resetTestCasesRun() err := filepath.Walk(checker.rootDir(), func(path string, info os.FileInfo, err error) error { @@ -399,6 +410,7 @@ func runAllTestCases(t *testing.T, checker resultsChecker) { } func runDirectoryTestCase(t *testing.T, path string, checker resultsChecker) { + t.Helper() // cd into the directory so we can test functions that refer to local files by relative paths d, err := os.Getwd() require.NoError(t, err) diff --git a/kyaml/fn/framework/function_definition.go b/kyaml/fn/framework/function_definition.go index 8bbdf89a0..683219896 100644 --- a/kyaml/fn/framework/function_definition.go +++ b/kyaml/fn/framework/function_definition.go @@ -82,7 +82,7 @@ type KRMFunctionVersion struct { type KRMFunctionValidation struct { // OpenAPIV3Schema is the OpenAPI v3 schema for an instance of the KRM function. - OpenAPIV3Schema *spec.Schema `yaml:"openAPIV3Schema,omitempty" json:"openAPIV3Schema,omitempty"` + OpenAPIV3Schema *spec.Schema `yaml:"openAPIV3Schema,omitempty" json:"openAPIV3Schema,omitempty"` // nolint: tagliatelle } type KRMFunctionNames struct { diff --git a/kyaml/fn/runtime/container/container_test.go b/kyaml/fn/runtime/container/container_test.go index 1fb51f077..06c3a7dd2 100644 --- a/kyaml/fn/runtime/container/container_test.go +++ b/kyaml/fn/runtime/container/container_test.go @@ -242,6 +242,7 @@ func TestFilter_ExitCode(t *testing.T) { } func getWorkingDir(t *testing.T) string { + t.Helper() wd, err := os.Getwd() require.NoError(t, err) return wd diff --git a/kyaml/fn/runtime/starlark/starlark.go b/kyaml/fn/runtime/starlark/starlark.go index 825ff63a0..9d7450a48 100644 --- a/kyaml/fn/runtime/starlark/starlark.go +++ b/kyaml/fn/runtime/starlark/starlark.go @@ -40,8 +40,7 @@ func (sf *Filter) String() string { } func (sf *Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) { - err := sf.setup() - if err != nil { + if err := sf.setup(); err != nil { return nil, err } sf.FunctionFilter.Run = sf.Run diff --git a/kyaml/kio/kio_test.go b/kyaml/kio/kio_test.go index 0bd3c6dd3..fb399ad98 100644 --- a/kyaml/kio/kio_test.go +++ b/kyaml/kio/kio_test.go @@ -91,8 +91,7 @@ func TestEmptyInput(t *testing.T) { Outputs: []Writer{output}, } - err := p.Execute() - if err != nil { + if err := p.Execute(); err != nil { t.Fatal(err) } @@ -132,8 +131,7 @@ func TestEmptyInputWithFilter(t *testing.T) { Filters: filters, } - err := p.Execute() - if err != nil { + if err := p.Execute(); err != nil { t.Fatal(err) } diff --git a/kyaml/kio/pkgio_reader_test.go b/kyaml/kio/pkgio_reader_test.go index 1f7183361..721f15c60 100644 --- a/kyaml/kio/pkgio_reader_test.go +++ b/kyaml/kio/pkgio_reader_test.go @@ -65,6 +65,7 @@ func TestLocalPackageReader_Read_pkg(t *testing.T) { {path: "c_test.yaml", content: readFileC}, {path: "d_test.yaml", content: readFileD}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS}, @@ -136,6 +137,7 @@ func TestLocalPackageReader_Read_pkgAndSkipFile(t *testing.T) { {path: "c_test.yaml", content: readFileC}, {path: "d_test.yaml", content: readFileD}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, FileSkipFunc: func(relPath string) bool { return relPath == "d_test.yaml" }, @@ -207,6 +209,7 @@ func TestLocalPackageReader_Read_JSON(t *testing.T) { }`), }, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, MatchFilesGlob: []string{"*.json"}, @@ -246,6 +249,7 @@ func TestLocalPackageReader_Read_file(t *testing.T) { {path: "a_test.yaml", content: readFileA}, {path: "b_test.yaml", content: readFileB}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: filepath.Join(path, "a_test.yaml"), FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS}, @@ -286,6 +290,7 @@ func TestLocalPackageReader_Read_pkgOmitAnnotations(t *testing.T) { {path: "a_test.yaml", content: readFileA}, {path: "b_test.yaml", content: readFileB}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, OmitReaderAnnotations: true, @@ -322,6 +327,7 @@ func TestLocalPackageReader_Read_PreserveSeqIndent(t *testing.T) { {path: "a_test.yaml", content: readFileA}, {path: "b_test.yaml", content: readFileB}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, PreserveSeqIndent: true, @@ -379,6 +385,7 @@ func TestLocalPackageReader_Read_nestedDirs(t *testing.T) { {path: "a/b/a_test.yaml", content: readFileA}, {path: "a/b/b_test.yaml", content: readFileB}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS}, @@ -433,6 +440,7 @@ func TestLocalPackageReader_Read_matchRegex(t *testing.T) { {path: "a/b/a_test.yaml", content: readFileA}, {path: "a/b/b_test.yaml", content: readFileB}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, MatchFilesGlob: []string{`a*.yaml`}, @@ -478,6 +486,7 @@ func TestLocalPackageReader_Read_skipSubpackage(t *testing.T) { {path: "a/c/c_test.yaml", content: readFileB}, {path: "a/c/pkgFile", content: pkgFile}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, PackageFileName: "pkgFile", @@ -523,6 +532,7 @@ func TestLocalPackageReader_Read_includeSubpackage(t *testing.T) { {path: "a/c/c_test.yaml", content: readFileB}, {path: "a/c/pkgFile", content: pkgFile}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, IncludeSubpackages: true, @@ -581,6 +591,7 @@ type mockFile struct { } func testOnDiskAndOnMem(t *testing.T, files []mockFile, f func(t *testing.T, path string, fs filesys.FileSystem)) { + t.Helper() t.Run("on_disk", func(t *testing.T) { var dirs []string for _, file := range files { @@ -627,6 +638,7 @@ func TestLocalPackageReader_ReadBareSeqNodes(t *testing.T) { {path: "a/c"}, {path: "e_test.yaml", content: readFileE}, }, func(t *testing.T, path string, mockFS filesys.FileSystem) { + t.Helper() rfr := LocalPackageReader{ PackagePath: path, FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS}, diff --git a/kyaml/kio/pkgio_writer_test.go b/kyaml/kio/pkgio_writer_test.go index 16aea4adf..387eae1d1 100644 --- a/kyaml/kio/pkgio_writer_test.go +++ b/kyaml/kio/pkgio_writer_test.go @@ -25,6 +25,7 @@ import ( // - ReaderAnnotations are cleared when writing the Resources func TestLocalPackageWriter_Write(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -57,6 +58,7 @@ g: // - ReaderAnnotations are kept when writing the Resources func TestLocalPackageWriter_Write_keepReaderAnnotations(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -108,6 +110,7 @@ metadata: // - ClearAnnotations are removed from Resources func TestLocalPackageWriter_Write_clearAnnotations(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -141,6 +144,7 @@ g: // - If a relative path above the package is defined, write fails func TestLocalPackageWriter_Write_failRelativePath(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -171,6 +175,7 @@ metadata: // - If a non-int index is given, fail func TestLocalPackageWriter_Write_invalidIndex(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -201,6 +206,7 @@ metadata: // - If config.kubernetes.io/path is absolute, fail func TestLocalPackageWriter_Write_absPath(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -232,6 +238,7 @@ metadata: // - If config.kubernetes.io/path or index are missing, then default them func TestLocalPackageWriter_Write_missingAnnotations(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -263,6 +270,7 @@ metadata: // - If config.kubernetes.io/path is a directory, fail func TestLocalPackageWriter_Write_pathIsDir(t *testing.T) { testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) { + t.Helper() d, node1, node2, node3, cleanup := getWriterInputs(t, fs) defer cleanup() @@ -289,6 +297,7 @@ metadata: } func testWriterOnDiskAndOnMem(t *testing.T, f func(t *testing.T, fs filesys.FileSystem)) { + t.Helper() t.Run("on_disk", func(t *testing.T) { f(t, filesys.MakeFsOnDisk()) }) // TODO: Once fsnode supports Windows, these tests should also be run. if runtime.GOOS != "windows" { @@ -297,6 +306,7 @@ func testWriterOnDiskAndOnMem(t *testing.T, f func(t *testing.T, fs filesys.File } func getWriterInputs(t *testing.T, mockFS filesys.FileSystem) (string, *yaml.RNode, *yaml.RNode, *yaml.RNode, func()) { + t.Helper() node1, err := yaml.Parse(`a: b #first metadata: annotations: diff --git a/kyaml/kio/testing.go b/kyaml/kio/testing.go index b973e9fbb..6c46a2804 100644 --- a/kyaml/kio/testing.go +++ b/kyaml/kio/testing.go @@ -20,6 +20,7 @@ type Setup struct { // setupDirectories creates directories for reading test configuration from func SetupDirectories(t *testing.T, dirs ...string) Setup { + t.Helper() d, err := ioutil.TempDir("", "kyaml-test") require.NoError(t, err) err = os.Chdir(d) @@ -33,6 +34,7 @@ func SetupDirectories(t *testing.T, dirs ...string) Setup { // writeFile writes a file under the test directory func (s Setup) WriteFile(t *testing.T, path string, value []byte) { + t.Helper() err := os.MkdirAll(filepath.Dir(filepath.Join(s.Root, path)), 0700) require.NoError(t, err) err = ioutil.WriteFile(filepath.Join(s.Root, path), value, 0600) diff --git a/kyaml/openapi/openapi.go b/kyaml/openapi/openapi.go index 8b644166a..bc36766a1 100644 --- a/kyaml/openapi/openapi.go +++ b/kyaml/openapi/openapi.go @@ -316,9 +316,8 @@ func toTypeMeta(ext interface{}) (yaml.TypeMeta, bool) { return yaml.TypeMeta{}, false } - g := m[groupKey].(string) apiVersion := m[versionKey].(string) - if g != "" { + if g := m[groupKey].(string); g != "" { apiVersion = g + "/" + apiVersion } return yaml.TypeMeta{Kind: m[kindKey].(string), APIVersion: apiVersion}, true diff --git a/kyaml/runfn/runfn_test.go b/kyaml/runfn/runfn_test.go index 36b660737..460ddae02 100644 --- a/kyaml/runfn/runfn_test.go +++ b/kyaml/runfn/runfn_test.go @@ -1170,6 +1170,7 @@ func TestCmd_Execute_enableLogSteps(t *testing.T) { } func getGeneratorFilterProvider(t *testing.T) func(runtimeutil.FunctionSpec, *yaml.RNode, currentUserFunc) (kio.Filter, error) { + t.Helper() return func(f runtimeutil.FunctionSpec, node *yaml.RNode, currentUser currentUserFunc) (kio.Filter, error) { return kio.FilterFunc(func(items []*yaml.RNode) ([]*yaml.RNode, error) { if f.Container.Image == "generate" { @@ -1238,6 +1239,7 @@ metadata: // setupTest initializes a temp test directory containing test data func setupTest(t *testing.T) string { + t.Helper() dir, err := ioutil.TempDir("", "kustomize-kyaml-test") if !assert.NoError(t, err) { t.FailNow() @@ -1264,6 +1266,7 @@ func setupTest(t *testing.T) string { // a filter to s/kind: Deployment/kind: StatefulSet/g. // this can be used to simulate running a filter. func getFilterProvider(t *testing.T) func(runtimeutil.FunctionSpec, *yaml.RNode, currentUserFunc) (kio.Filter, error) { + t.Helper() return func(f runtimeutil.FunctionSpec, node *yaml.RNode, currentUser currentUserFunc) (kio.Filter, error) { // parse the filter from the input filter := yaml.YFilter{} diff --git a/kyaml/setters2/set_test.go b/kyaml/setters2/set_test.go index 532a03e28..c9385cc55 100644 --- a/kyaml/setters2/set_test.go +++ b/kyaml/setters2/set_test.go @@ -1002,6 +1002,7 @@ spec: // initSchema initializes the openAPI with the definitions from s func SettersSchema(t *testing.T, s string) *spec.Schema { + t.Helper() dir, err := ioutil.TempDir("", "") assert.NoError(t, err) defer os.RemoveAll(dir) diff --git a/kyaml/testutil/testutil.go b/kyaml/testutil/testutil.go index b9f6b5397..5f1b8accc 100644 --- a/kyaml/testutil/testutil.go +++ b/kyaml/testutil/testutil.go @@ -6,12 +6,11 @@ package testutil import ( "bytes" "runtime" + "testing" "sigs.k8s.io/kustomize/kyaml/kio" "sigs.k8s.io/kustomize/kyaml/yaml" - "testing" - goerrors "github.com/go-errors/errors" "github.com/stretchr/testify/assert" @@ -43,6 +42,7 @@ func UpdateYamlBytes(b []byte, function ...yaml.Filter) ([]byte, error) { } func AssertErrorContains(t *testing.T, err error, value string, msg ...string) { + t.Helper() if !assert.Error(t, err, msg) { t.FailNow() } @@ -52,6 +52,7 @@ func AssertErrorContains(t *testing.T, err error, value string, msg ...string) { } func AssertNoError(t *testing.T, err error, msg ...string) { + t.Helper() if !assert.NoError(t, err, msg) { gerr, ok := err.(*goerrors.Error) if ok { @@ -62,6 +63,7 @@ func AssertNoError(t *testing.T, err error, msg ...string) { } func SkipWindows(t *testing.T) { + t.Helper() if runtime.GOOS == "windows" { t.Skip() } diff --git a/kyaml/yaml/example_test.go b/kyaml/yaml/example_test.go index 89da82731..f581d88bb 100644 --- a/kyaml/yaml/example_test.go +++ b/kyaml/yaml/example_test.go @@ -281,7 +281,7 @@ func ExampleElementMatcher_Filter_objectNotFound() { if err != nil { log.Fatal(err) } - append, err := Parse(` + toAppend, err := Parse(` name: baz image: nginx `) @@ -289,7 +289,7 @@ image: nginx log.Fatal(err) } elem, err := obj.Pipe(ElementMatcher{ - Keys: []string{"name"}, Values: []string{"baz"}, Create: append}) + Keys: []string{"name"}, Values: []string{"baz"}, Create: toAppend}) if err != nil { log.Fatal(err) } @@ -315,7 +315,7 @@ func ExampleElementMatcher_Filter_objectFound() { if err != nil { log.Fatal(err) } - append, err := Parse(` + toAppend, err := Parse(` name: baz image: nginx `) @@ -323,7 +323,7 @@ image: nginx log.Fatal(err) } elem, err := obj.Pipe(ElementMatcher{ - Keys: []string{"name"}, Values: []string{"baz"}, Create: append}) + Keys: []string{"name"}, Values: []string{"baz"}, Create: toAppend}) if err != nil { log.Fatal(err) } diff --git a/kyaml/yaml/fns.go b/kyaml/yaml/fns.go index c4ab1fb53..c5ac0acfa 100644 --- a/kyaml/yaml/fns.go +++ b/kyaml/yaml/fns.go @@ -552,7 +552,6 @@ func (l PathGetter) getFilter(part, nextPart string, fieldPath *[]string) (Filte } func (l PathGetter) elemFilter(part string) (Filter, error) { - var match *RNode name, value, err := SplitIndexNameValue(part) if err != nil { return nil, errors.Wrap(err) @@ -567,10 +566,9 @@ func (l PathGetter) elemFilter(part string) (Filter, error) { // append a ScalarNode elem = NewScalarRNode(value) elem.YNode().Style = l.Style - match = elem } else { // append a MappingNode - match = NewRNode(&yaml.Node{Kind: yaml.ScalarNode, Value: value, Style: l.Style}) + match := NewRNode(&yaml.Node{Kind: yaml.ScalarNode, Value: value, Style: l.Style}) elem = NewRNode(&yaml.Node{ Kind: yaml.MappingNode, Content: []*yaml.Node{{Kind: yaml.ScalarNode, Value: name}, match.YNode()}, diff --git a/kyaml/yaml/fns_test.go b/kyaml/yaml/fns_test.go index 0c6ed8c0b..8ad049e8e 100644 --- a/kyaml/yaml/fns_test.go +++ b/kyaml/yaml/fns_test.go @@ -23,19 +23,19 @@ c: d func TestResourceNode_SetValue(t *testing.T) { instance := *NewScalarRNode("foo") - copy := instance + instanceCopy := instance instance.SetYNode(&yaml.Node{Kind: yaml.ScalarNode, Value: "bar"}) assert.Equal(t, `bar -`, assertNoErrorString(t)(copy.String())) +`, assertNoErrorString(t)(instanceCopy.String())) assert.Equal(t, `bar `, assertNoErrorString(t)(instance.String())) instance = *NewScalarRNode("foo") - copy = instance + instanceCopy = instance instance.SetYNode(nil) instance.SetYNode(&yaml.Node{Kind: yaml.ScalarNode, Value: "bar"}) assert.Equal(t, `foo -`, assertNoErrorString(t)(copy.String())) +`, assertNoErrorString(t)(instanceCopy.String())) assert.Equal(t, `bar `, assertNoErrorString(t)(instance.String())) } @@ -1279,6 +1279,7 @@ metadata: } func assertNoError(t *testing.T) func(o *RNode, err error) *RNode { + t.Helper() return func(o *RNode, err error) *RNode { assert.NoError(t, err) return o @@ -1286,6 +1287,7 @@ func assertNoError(t *testing.T) func(o *RNode, err error) *RNode { } func assertNoErrorString(t *testing.T) func(string, error) string { + t.Helper() return func(s string, err error) string { assert.NoError(t, err) return s diff --git a/kyaml/yaml/kfns_test.go b/kyaml/yaml/kfns_test.go index 371a7aea3..e26ff1194 100644 --- a/kyaml/yaml/kfns_test.go +++ b/kyaml/yaml/kfns_test.go @@ -74,8 +74,6 @@ data: if err != nil { t.Fatalf("unexpected error %v", err) } - output := rn.MustString() - expected := `apiVersion: v1 kind: ConfigMap data: @@ -84,7 +82,7 @@ metadata: labels: foo: 'bar' ` - if output != expected { + if output := rn.MustString(); output != expected { t.Fatalf("expected \n%s\nbut got \n%s\n", expected, output) } } @@ -102,7 +100,6 @@ data: if err != nil { t.Fatalf("unexpected error %v", err) } - output := rn.MustString() expected := `apiVersion: v1 kind: ConfigMap @@ -114,7 +111,7 @@ data: altGreeting: "Good Morning!" enableRisky: "false" ` - if output != expected { + if output := rn.MustString(); output != expected { t.Fatalf("expected \n%s\nbut got \n%s\n", expected, output) } } diff --git a/kyaml/yaml/rnode_test.go b/kyaml/yaml/rnode_test.go index 35b73ffdb..bb9398734 100644 --- a/kyaml/yaml/rnode_test.go +++ b/kyaml/yaml/rnode_test.go @@ -2180,8 +2180,7 @@ func TestRoundTripJSON(t *testing.T) { if err != nil { t.Fatalf("unexpected MarshalJSON err: %v", err) } - actual := string(data) - if actual != deploymentLittleJson { + if actual := string(data); actual != deploymentLittleJson { t.Fatalf("expected %s, got %s", deploymentLittleJson, actual) } } diff --git a/kyaml/yaml/types_test.go b/kyaml/yaml/types_test.go index ab2f4e465..7497a094d 100644 --- a/kyaml/yaml/types_test.go +++ b/kyaml/yaml/types_test.go @@ -32,8 +32,7 @@ func TestCopyYNode(t *testing.T) { Line: 7000, Column: 8000, } - ynAddr := &yn - if !reflect.DeepEqual(&yn, ynAddr) { + if ynAddr := &yn; !reflect.DeepEqual(&yn, ynAddr) { t.Fatalf("truly %v should equal %v", &yn, ynAddr) } ynC := CopyYNode(&yn)