From 14947e449bde0785cd6cc3ee90562095b34f1985 Mon Sep 17 00:00:00 2001 From: Katrina Verey Date: Tue, 29 Mar 2022 18:18:23 -0400 Subject: [PATCH] Address new linter complaints --- .golangci-kustomize.yml | 33 ++++++++++------- Makefile | 3 ++ api/filters/annotations/annotations_test.go | 2 +- .../iampolicygenerator/iampolicygenerator.go | 2 +- api/filters/imagetag/legacy.go | 4 +-- api/filters/imagetag/updater.go | 7 ++-- api/filters/namespace/namespace.go | 1 - api/filters/namespace/namespace_test.go | 2 +- api/filters/refvar/refvar_test.go | 1 - api/filters/replacement/replacement.go | 8 ++--- .../accumulator/namereferencetransformer.go | 1 - api/internal/accumulator/resaccumulator.go | 1 - api/internal/git/repospec.go | 11 +++--- api/internal/git/repospec_test.go | 10 +++--- .../plugins/builtinhelpers/builtins.go | 2 +- .../plugins/execplugin/execplugin_test.go | 1 - api/internal/plugins/utils/utils_test.go | 4 +-- api/krusty/basic_io_test.go | 2 +- api/krusty/configmaps_test.go | 1 - api/krusty/diamondcomposition_test.go | 16 ++++----- api/krusty/disablenamesuffix_test.go | 4 +-- api/krusty/namespaces_test.go | 1 + api/krusty/repeatbase_test.go | 3 +- api/loader/fileloader.go | 4 +-- api/loader/fileloader_test.go | 16 ++++----- api/loader/loader.go | 2 +- api/resmap/factory.go | 8 ++--- api/resmap/reswrangler.go | 3 +- api/resmap/reswrangler_test.go | 3 +- api/resource/origin.go | 2 +- api/types/helmchartargs.go | 4 +-- api/types/kustomization.go | 4 +-- cmd/config/.golangci.yml | 3 +- cmd/config/Makefile | 2 +- .../internal/krmfunction/converter.go | 4 +-- .../internal/krmfunction/converter_test.go | 4 +-- .../krmfunction/funcwrappersrc/fakeplugin.go | 1 - kustomize/commands/build/build_test.go | 6 ++-- kustomize/commands/edit/add/addbase.go | 1 - kustomize/commands/edit/fix/convert.go | 5 --- kustomize/commands/edit/fix/fix.go | 1 - .../commands/edit/remove/removeresource.go | 1 - kustomize/commands/edit/set/setimage.go | 4 --- kustomize/commands/edit/set/setreplicas.go | 2 -- .../internal/kustfile/kustomizationfile.go | 10 +++--- kustomize/commands/internal/util/util.go | 7 ++-- kustomize/commands/openapi/openapi.go | 1 - kustomize/go.mod | 1 + kyaml/.golangci.yml | 36 ++++++++++++++----- kyaml/Makefile | 10 +++--- kyaml/filesys/fsnode.go | 1 - kyaml/filesys/fsnode_test.go | 11 +++--- kyaml/filesys/fsondisk.go | 2 +- kyaml/filesys/fsondisk_test.go | 6 ++-- .../frameworktestutil/frameworktestutil.go | 4 +-- kyaml/fn/framework/validation_test.go | 8 +++-- kyaml/fn/runtime/container/container.go | 2 +- kyaml/fn/runtime/container/container_test.go | 2 +- kyaml/fn/runtime/exec/exec.go | 2 +- kyaml/kio/byteio_reader.go | 2 +- kyaml/kio/ignorefilesmatcher_test.go | 34 +++++++++--------- kyaml/kio/kio.go | 25 +++++++------ kyaml/kio/kio_test.go | 1 - kyaml/kio/kioutil/kioutil_test.go | 4 ++- kyaml/kio/pkgio_reader_test.go | 14 ++++++-- kyaml/kio/pkgio_writer_test.go | 2 +- kyaml/order/syncorder.go | 5 +-- kyaml/order/syncorder_test.go | 4 +-- kyaml/pathutil/pathutil_test.go | 6 ++-- kyaml/runfn/runfn_test.go | 14 ++++---- kyaml/setters2/settersutil/fieldsetter.go | 2 +- kyaml/setters2/settersutil/settercreator.go | 2 +- kyaml/yaml/fns_test.go | 6 ++-- kyaml/yaml/match.go | 2 -- kyaml/yaml/rnode_test.go | 1 - kyaml/yaml/util.go | 1 - .../HelmChartInflationGenerator_test.go | 2 +- 77 files changed, 220 insertions(+), 210 deletions(-) diff --git a/.golangci-kustomize.yml b/.golangci-kustomize.yml index eee1c335c9..1ef067984c 100644 --- a/.golangci-kustomize.yml +++ b/.golangci-kustomize.yml @@ -7,13 +7,14 @@ linters: - bodyclose - deadcode - depguard - # - dogsled + - dogsled - dupl - # - errcheck - # - funlen - # - gochecknoinits +# - errcheck + - exportloopref +# - funlen + - gochecknoinits - goconst - # - gocritic + - gocritic - gocyclo - gofmt - goimports @@ -24,19 +25,17 @@ linters: - lll - misspell - nakedret + - nolintlint - revive - # - scopelint - staticcheck - structcheck - # stylecheck demands that acronyms not be treated as words - # in camelCase, so JsonOp become JSONOp, etc. Yuck. - # - stylecheck +# - stylecheck # seems redundant with revive, which replaced golint - typecheck - unconvert - unparam - unused - varcheck - # - whitespace + - whitespace linters-settings: dupl: @@ -45,5 +44,15 @@ linters-settings: line-length: 170 gocyclo: min-complexity: 15 - golint: - min-confidence: 0.85 + revive: + rules: + - name: var-naming + arguments: + - [ "ID", "API", "JSON" ] # AllowList + - [ ] # DenyList + +issues: + exclude-rules: + - linters: + - revive + text: "don't use leading" diff --git a/Makefile b/Makefile index f66648544f..d69ca93bb9 100644 --- a/Makefile +++ b/Makefile @@ -204,12 +204,15 @@ clean-kustomize-external-go-plugin: lint-kustomize: $(MYGOBIN)/golangci-lint-kustomize $(builtinplugins) cd api; $(MYGOBIN)/golangci-lint-kustomize \ -c ../.golangci-kustomize.yml \ + --path-prefix api \ run ./... cd kustomize; $(MYGOBIN)/golangci-lint-kustomize \ -c ../.golangci-kustomize.yml \ + --path-prefix kustomize \ run ./... cd cmd/pluginator; $(MYGOBIN)/golangci-lint-kustomize \ -c ../../.golangci-kustomize.yml \ + --path-prefix cmd/pluginator \ run ./... # Used to add non-default compilation flags when experimenting with diff --git a/api/filters/annotations/annotations_test.go b/api/filters/annotations/annotations_test.go index d52cd673a6..94669e8f99 100644 --- a/api/filters/annotations/annotations_test.go +++ b/api/filters/annotations/annotations_test.go @@ -285,7 +285,7 @@ spec: t.Run(tn, func(t *testing.T) { filter := tc.filter filter.WithMutationTracker(tc.setEntryCallback) - filter.FsSlice = append(annosFs, tc.fsslice...) + filter.FsSlice = append(annosFs, tc.fsslice...) //nolint:gocritic if !assert.Equal(t, strings.TrimSpace(tc.expectedOutput), strings.TrimSpace(filtertest_test.RunFilter(t, tc.input, filter))) { diff --git a/api/filters/iampolicygenerator/iampolicygenerator.go b/api/filters/iampolicygenerator/iampolicygenerator.go index c1f8593fbe..97ea31693e 100644 --- a/api/filters/iampolicygenerator/iampolicygenerator.go +++ b/api/filters/iampolicygenerator/iampolicygenerator.go @@ -43,7 +43,7 @@ metadata: f.IAMPolicyGenerator.KubernetesService.Name) if f.IAMPolicyGenerator.Namespace != "" { - input = input + fmt.Sprintf("\n namespace: %s", f.IAMPolicyGenerator.Namespace) + input += fmt.Sprintf("\n namespace: %s", f.IAMPolicyGenerator.Namespace) } sa, err := yaml.Parse(input) diff --git a/api/filters/imagetag/legacy.go b/api/filters/imagetag/legacy.go index d07080b8ee..66dcfc8c76 100644 --- a/api/filters/imagetag/legacy.go +++ b/api/filters/imagetag/legacy.go @@ -81,9 +81,7 @@ func (f findFieldsFilter) walk(node *yaml.RNode) error { return nil }) case yaml.SequenceNode: - return node.VisitElements(func(n *yaml.RNode) error { - return f.walk(n) - }) + return node.VisitElements(f.walk) } return nil } diff --git a/api/filters/imagetag/updater.go b/api/filters/imagetag/updater.go index 45c6c748da..810f205914 100644 --- a/api/filters/imagetag/updater.go +++ b/api/filters/imagetag/updater.go @@ -36,13 +36,14 @@ func (u imageTagUpdater) SetImageValue(rn *yaml.RNode) error { } // overriding tag or digest will replace both original tag and digest values - if u.ImageTag.NewTag != "" && u.ImageTag.Digest != "" { + switch { + case u.ImageTag.NewTag != "" && u.ImageTag.Digest != "": tag = u.ImageTag.NewTag digest = u.ImageTag.Digest - } else if u.ImageTag.NewTag != "" { + case u.ImageTag.NewTag != "": tag = u.ImageTag.NewTag digest = "" - } else if u.ImageTag.Digest != "" { + case u.ImageTag.Digest != "": tag = "" digest = u.ImageTag.Digest } diff --git a/api/filters/namespace/namespace.go b/api/filters/namespace/namespace.go index 016a14a134..8d0f54ea28 100644 --- a/api/filters/namespace/namespace.go +++ b/api/filters/namespace/namespace.go @@ -139,7 +139,6 @@ func (ns Filter) roleBindingHack(obj *yaml.RNode, gvk resid.Gvk) error { } return ns.trackableSetter.SetEntry("", ns.Namespace, yaml.NodeTagString)(node) - }) return err diff --git a/api/filters/namespace/namespace_test.go b/api/filters/namespace/namespace_test.go index 32a24d29fc..5e4813dc13 100644 --- a/api/filters/namespace/namespace_test.go +++ b/api/filters/namespace/namespace_test.go @@ -406,7 +406,7 @@ func TestNamespace_Filter(t *testing.T) { test := tests[i] test.filter.WithMutationTracker(test.mutationTracker) t.Run(test.name, func(t *testing.T) { - test.filter.FsSlice = append(config.NameSpace, test.fsslice...) + test.filter.FsSlice = append(config.NameSpace, test.fsslice...) //nolint:gocritic if !assert.Equal(t, strings.TrimSpace(test.expected), strings.TrimSpace( diff --git a/api/filters/refvar/refvar_test.go b/api/filters/refvar/refvar_test.go index c80dc79bd1..87147ef626 100644 --- a/api/filters/refvar/refvar_test.go +++ b/api/filters/refvar/refvar_test.go @@ -17,7 +17,6 @@ var makeMf = func(theMap map[string]interface{}) MappingFunc { } func TestFilter(t *testing.T) { - testCases := map[string]struct { input string expected string diff --git a/api/filters/replacement/replacement.go b/api/filters/replacement/replacement.go index f4627ddbcb..a96dfff719 100644 --- a/api/filters/replacement/replacement.go +++ b/api/filters/replacement/replacement.go @@ -20,11 +20,11 @@ type Filter struct { // Filter replaces values of targets with values from sources func (f Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) { - for _, r := range f.Replacements { + for i, r := range f.Replacements { if r.Source == nil || r.Targets == nil { return nil, fmt.Errorf("replacements must specify a source and at least one target") } - value, err := getReplacement(nodes, &r) + value, err := getReplacement(nodes, &f.Replacements[i]) if err != nil { return nil, err } @@ -60,8 +60,8 @@ func applyReplacement(nodes []*yaml.RNode, value *yaml.RNode, targets []*types.T } // filter targets by matching resource IDs - for _, id := range ids { - if id.IsSelectedBy(t.Select.ResId) && !rejectId(t.Reject, &id) { + for i, id := range ids { + if id.IsSelectedBy(t.Select.ResId) && !rejectId(t.Reject, &ids[i]) { err := applyToNode(n, value, t) if err != nil { return nil, err diff --git a/api/internal/accumulator/namereferencetransformer.go b/api/internal/accumulator/namereferencetransformer.go index e039db4b1f..f8f12b4f2b 100644 --- a/api/internal/accumulator/namereferencetransformer.go +++ b/api/internal/accumulator/namereferencetransformer.go @@ -113,7 +113,6 @@ func debug(fMap filterMap) { // 'spec/scaleTargetRef/name' field. Return a filter that can do that. func (t *nameReferenceTransformer) determineFilters( resources []*resource.Resource) (fMap filterMap) { - // We cache the resource OrgId values because they don't change and otherwise are very visible in a memory pprof resourceOrgIds := make([]resid.ResId, len(resources)) for i, resource := range resources { diff --git a/api/internal/accumulator/resaccumulator.go b/api/internal/accumulator/resaccumulator.go index 9345537572..2c1fc71b50 100644 --- a/api/internal/accumulator/resaccumulator.go +++ b/api/internal/accumulator/resaccumulator.go @@ -107,7 +107,6 @@ func (ra *ResAccumulator) findVarValueFromResources(v types.Var) (interface{}, e for _, res := range ra.resMap.Resources() { for _, varName := range res.GetRefVarNames() { if varName == v.Name { - //nolint: staticcheck s, err := res.GetFieldValue(v.FieldRef.FieldPath) if err != nil { return "", fmt.Errorf( diff --git a/api/internal/git/repospec.go b/api/internal/git/repospec.go index 10ebb980a7..996f0cf239 100644 --- a/api/internal/git/repospec.go +++ b/api/internal/git/repospec.go @@ -78,15 +78,15 @@ func (x *RepoSpec) Cleaner(fSys filesys.FileSystem) func() error { return func() error { return fSys.RemoveAll(x.Dir.String()) } } -// NewRepoSpecFromUrl parses git-like urls. +// NewRepoSpecFromURL parses git-like urls. // From strings like git@github.com:someOrg/someRepo.git or // https://github.com/someOrg/someRepo?ref=someHash, extract // the parts. -func NewRepoSpecFromUrl(n string) (*RepoSpec, error) { +func NewRepoSpecFromURL(n string) (*RepoSpec, error) { if filepath.IsAbs(n) { return nil, fmt.Errorf("uri looks like abs path: %s", n) } - host, orgRepo, path, gitRef, gitSubmodules, suffix, gitTimeout := parseGitUrl(n) + host, orgRepo, path, gitRef, gitSubmodules, suffix, gitTimeout := parseGitURL(n) if orgRepo == "" { return nil, fmt.Errorf("url lacks orgRepo: %s", n) } @@ -108,9 +108,8 @@ const ( // From strings like git@github.com:someOrg/someRepo.git or // https://github.com/someOrg/someRepo?ref=someHash, extract // the parts. -func parseGitUrl(n string) ( +func parseGitURL(n string) ( host string, orgRepo string, path string, gitRef string, gitSubmodules bool, gitSuff string, gitTimeout time.Duration) { - if strings.Contains(n, gitDelimiter) { index := strings.Index(n, gitDelimiter) // Adding _git/ to host @@ -229,7 +228,7 @@ func parseHostSpec(n string) (string, string) { if strings.HasSuffix(host, p) { i := strings.Index(n, "/") if i > -1 { - host = host + n[0:i+1] + host += n[0 : i+1] n = n[i+1:] } break diff --git a/api/internal/git/repospec_test.go b/api/internal/git/repospec_test.go index 2e4404d035..41e89ca31e 100644 --- a/api/internal/git/repospec_test.go +++ b/api/internal/git/repospec_test.go @@ -37,7 +37,7 @@ var hostNamesRawAndNormalized = [][]string{ {"git@github.com/", "git@github.com:"}, } -func makeUrl(hostFmt, orgRepo, path, href string) string { +func makeURL(hostFmt, orgRepo, path, href string) string { if len(path) > 0 { orgRepo = filepath.Join(orgRepo, path) } @@ -56,8 +56,8 @@ func TestNewRepoSpecFromUrl(t *testing.T) { for _, orgRepo := range orgRepos { for _, pathName := range pathNames { for _, hrefArg := range hrefArgs { - uri := makeUrl(hostRaw, orgRepo, pathName, hrefArg) - rs, err := NewRepoSpecFromUrl(uri) + uri := makeURL(hostRaw, orgRepo, pathName, hrefArg) + rs, err := NewRepoSpecFromURL(uri) if err != nil { t.Errorf("problem %v", err) } @@ -99,7 +99,7 @@ var badData = [][]string{ func TestNewRepoSpecFromUrlErrors(t *testing.T) { for _, tuple := range badData { - _, err := NewRepoSpecFromUrl(tuple[0]) + _, err := NewRepoSpecFromURL(tuple[0]) if err == nil { t.Error("expected error") } @@ -191,7 +191,7 @@ func TestNewRepoSpecFromUrl_CloneSpecs(t *testing.T) { } for tn, tc := range testcases { t.Run(tn, func(t *testing.T) { - rs, err := NewRepoSpecFromUrl(tc.input) + rs, err := NewRepoSpecFromURL(tc.input) assert.NoError(t, err) assert.Equal(t, tc.cloneSpec, rs.CloneSpec(), "cloneSpec mismatch") assert.Equal(t, tc.absPath, rs.AbsPath(), "absPath mismatch") diff --git a/api/internal/plugins/builtinhelpers/builtins.go b/api/internal/plugins/builtinhelpers/builtins.go index 260ed1bf5b..b1c987a52f 100644 --- a/api/internal/plugins/builtinhelpers/builtins.go +++ b/api/internal/plugins/builtinhelpers/builtins.go @@ -36,7 +36,7 @@ const ( var stringToBuiltinPluginTypeMap map[string]BuiltinPluginType -func init() { +func init() { //nolint:gochecknoinits stringToBuiltinPluginTypeMap = makeStringToBuiltinPluginTypeMap() } diff --git a/api/internal/plugins/execplugin/execplugin_test.go b/api/internal/plugins/execplugin/execplugin_test.go index 5cc637f3b0..b20626297e 100644 --- a/api/internal/plugins/execplugin/execplugin_test.go +++ b/api/internal/plugins/execplugin/execplugin_test.go @@ -83,7 +83,6 @@ metadata: ` if expected != string(p.Cfg()) { t.Fatalf("expected cfg '%s', got '%s'", expected, string(p.Cfg())) - } if len(p.Args()) != 6 { t.Fatalf("unexpected arg len %d, %#v", len(p.Args()), p.Args()) diff --git a/api/internal/plugins/utils/utils_test.go b/api/internal/plugins/utils/utils_test.go index 9aa0184ed6..32ef658267 100644 --- a/api/internal/plugins/utils/utils_test.go +++ b/api/internal/plugins/utils/utils_test.go @@ -105,10 +105,10 @@ func TestUpdateResourceOptionsWithInvalidHashAnnotationValues(t *testing.T) { "TrUe", "potato", } - for i, c := range cases { + for i := range cases { name := fmt.Sprintf("test%d", i) in := resmap.New() - err := in.Append(makeConfigMap(rf, name, "", &c)) + err := in.Append(makeConfigMap(rf, name, "", &cases[i])) require.NoError(t, err) _, err = UpdateResourceOptions(in) require.Error(t, err) diff --git a/api/krusty/basic_io_test.go b/api/krusty/basic_io_test.go index 5e6eef8fd8..354c4d2d21 100644 --- a/api/krusty/basic_io_test.go +++ b/api/krusty/basic_io_test.go @@ -82,7 +82,7 @@ spec: `) } -//test for https://github.com/kubernetes-sigs/kustomize/issues/3812#issuecomment-862339267 +// test for https://github.com/kubernetes-sigs/kustomize/issues/3812#issuecomment-862339267 func TestBasicIO3812(t *testing.T) { th := kusttest_test.MakeHarness(t) th.WriteK(".", ` diff --git a/api/krusty/configmaps_test.go b/api/krusty/configmaps_test.go index 7219799831..a2b954444f 100644 --- a/api/krusty/configmaps_test.go +++ b/api/krusty/configmaps_test.go @@ -460,7 +460,6 @@ metadata: } func TestConfigMapGeneratorMergeNamePrefix(t *testing.T) { - th := kusttest_test.MakeHarness(t) th.WriteK("base", ` configMapGenerator: diff --git a/api/krusty/diamondcomposition_test.go b/api/krusty/diamondcomposition_test.go index 401afb1a99..9603b325e5 100644 --- a/api/krusty/diamondcomposition_test.go +++ b/api/krusty/diamondcomposition_test.go @@ -34,7 +34,7 @@ const container = `{ "image": "my-image", "livenessProbe": { "httpGet" : {"path" const patchJsonAddProbe = `[{"op": "replace", "path": "/spec/template/spec/containers/0", "value": ` + container + `}]` -const patchDnsPolicy = ` +const patchDNSPolicy = ` apiVersion: apps/v1 kind: Deployment metadata: @@ -44,7 +44,7 @@ spec: spec: dnsPolicy: ClusterFirst ` -const patchJsonDnsPolicy = `[{"op": "add", "path": "/spec/template/spec/dnsPolicy", "value": "ClusterFirst"}]` +const patchJsonDNSPolicy = `[{"op": "add", "path": "/spec/template/spec/dnsPolicy", "value": "ClusterFirst"}]` const patchRestartPolicy = ` apiVersion: apps/v1 @@ -96,7 +96,7 @@ resources: patchesStrategicMerge: - dep-patch.yaml `) - th.WriteF("dns/dep-patch.yaml", patchDnsPolicy) + th.WriteF("dns/dep-patch.yaml", patchDNSPolicy) } func writeRestartOverlay(th kusttest_test.Harness) { @@ -209,7 +209,7 @@ patchesStrategicMerge: - patchRestartPolicy.yaml `) th.WriteF("composite/patchRestartPolicy.yaml", patchRestartPolicy) - th.WriteF("composite/patchDnsPolicy.yaml", patchDnsPolicy) + th.WriteF("composite/patchDnsPolicy.yaml", patchDNSPolicy) th.WriteF("composite/patchAddProbe.yaml", patchAddProbe) m := th.Run("composite", th.MakeDefaultOptions()) @@ -220,7 +220,7 @@ func definePatchDirStructure(th kusttest_test.Harness) { writeDeploymentBase(th) th.WriteF("patches/patchRestartPolicy.yaml", patchRestartPolicy) - th.WriteF("patches/patchDnsPolicy.yaml", patchDnsPolicy) + th.WriteF("patches/patchDnsPolicy.yaml", patchDNSPolicy) th.WriteF("patches/patchAddProbe.yaml", patchAddProbe) } @@ -368,7 +368,7 @@ func TestIssue1251_Plugins_Local(t *testing.T) { writeDeploymentBase(th.Harness) writeJsonTransformerPluginConfig( - th, "composite", "addDnsPolicy", patchJsonDnsPolicy) + th, "composite", "addDnsPolicy", patchJsonDNSPolicy) writeJsonTransformerPluginConfig( th, "composite", "addRestartPolicy", patchJsonRestartPolicy) writeJsonTransformerPluginConfig( @@ -417,7 +417,7 @@ resources: - addProbeConfig.yaml `) writeJsonTransformerPluginConfig( - th, "patches", "addDnsPolicy", patchJsonDnsPolicy) + th, "patches", "addDnsPolicy", patchJsonDNSPolicy) writeJsonTransformerPluginConfig( th, "patches", "addRestartPolicy", patchJsonRestartPolicy) writeJsonTransformerPluginConfig( @@ -441,7 +441,7 @@ resources: - addDnsPolicyConfig.yaml `) writeJsonTransformerPluginConfig( - th, "patches/addDnsPolicy", "addDnsPolicy", patchJsonDnsPolicy) + th, "patches/addDnsPolicy", "addDnsPolicy", patchJsonDNSPolicy) th.WriteK("patches/addRestartPolicy", ` resources: diff --git a/api/krusty/disablenamesuffix_test.go b/api/krusty/disablenamesuffix_test.go index 5c4ca2dc90..d50a65ed8f 100644 --- a/api/krusty/disablenamesuffix_test.go +++ b/api/krusty/disablenamesuffix_test.go @@ -87,9 +87,9 @@ metadata: } th.WriteK("/whatever", - strings.Replace(kustomizationContent, + strings.ReplaceAll(kustomizationContent, "disableNameSuffixHash: false", - "disableNameSuffixHash: true", -1)) + "disableNameSuffixHash: true")) m = th.Run("/whatever", th.MakeDefaultOptions()) secret = findSecret(m, "") if secret == nil { diff --git a/api/krusty/namespaces_test.go b/api/krusty/namespaces_test.go index 45d18078db..58dbb86864 100644 --- a/api/krusty/namespaces_test.go +++ b/api/krusty/namespaces_test.go @@ -692,6 +692,7 @@ resources: th.AssertActualEqualsExpected(m, namespaceNeedInVarExpectedOutput) } +// nolint:gosec const namespaceNeedInVarMyAppWithNamespace string = ` resources: - elasticsearch-dev-service.yaml diff --git a/api/krusty/repeatbase_test.go b/api/krusty/repeatbase_test.go index 438b7af287..0fc80e4628 100644 --- a/api/krusty/repeatbase_test.go +++ b/api/krusty/repeatbase_test.go @@ -172,6 +172,5 @@ spec: // containers: // - image: image-canary-a // name: container-a - //`) - + // `) } diff --git a/api/loader/fileloader.go b/api/loader/fileloader.go index ffeef3b02e..793b82c82b 100644 --- a/api/loader/fileloader.go +++ b/api/loader/fileloader.go @@ -172,7 +172,7 @@ func (fl *fileLoader) New(path string) (ifc.Loader, error) { return nil, fmt.Errorf("new root cannot be empty") } - repoSpec, err := git.NewRepoSpecFromUrl(path) + repoSpec, err := git.NewRepoSpecFromURL(path) if err == nil { // Treat this as git repo clone request. if err = fl.errIfRepoCycle(repoSpec); err != nil { @@ -315,7 +315,7 @@ func (fl *fileLoader) Load(path string) ([]byte, error) { } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { - _, err := git.NewRepoSpecFromUrl(path) + _, err := git.NewRepoSpecFromURL(path) if err == nil { return nil, errors.New("URL is a git repository") } diff --git a/api/loader/fileloader_test.go b/api/loader/fileloader_test.go index aedfd1693d..b276121cb0 100644 --- a/api/loader/fileloader_test.go +++ b/api/loader/fileloader_test.go @@ -347,7 +347,7 @@ func splitOnNthSlash(v string, n int) (string, string) { if k < 0 { break } - left = left + v[:k+1] + left += v[:k+1] v = v[k+1:] } return left[:len(left)-1], v @@ -367,9 +367,9 @@ func TestSplit(t *testing.T) { } func TestNewLoaderAtGitClone(t *testing.T) { - rootUrl := "github.com/someOrg/someRepo" + rootURL := "github.com/someOrg/someRepo" pathInRepo := "foo/base" - url := rootUrl + "/" + pathInRepo + url := rootURL + "/" + pathInRepo coRoot := "/tmp" fSys := filesys.MakeFsInMemory() fSys.MkdirAll(coRoot) @@ -381,7 +381,7 @@ func TestNewLoaderAtGitClone(t *testing.T) { whatever `)) - repoSpec, err := git.NewRepoSpecFromUrl(url) + repoSpec, err := git.NewRepoSpecFromURL(url) if err != nil { t.Fatalf("unexpected err: %v\n", err) } @@ -398,13 +398,13 @@ whatever if _, err = l.New(url); err == nil { t.Fatalf("expected cycle error 1") } - if _, err = l.New(rootUrl + "/" + "foo"); err == nil { + if _, err = l.New(rootURL + "/" + "foo"); err == nil { t.Fatalf("expected cycle error 2") } pathInRepo = "foo/overlay" fSys.MkdirAll(coRoot + "/" + pathInRepo) - url = rootUrl + "/" + pathInRepo + url = rootURL + "/" + pathInRepo l2, err := l.New(url) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -459,7 +459,7 @@ func TestLoaderDisallowsLocalBaseFromRemoteOverlay(t *testing.T) { // exist in its own repository, so presumably the // remote K would be deliberately designed to phish // for local K's. - repoSpec, err := git.NewRepoSpecFromUrl( + repoSpec, err := git.NewRepoSpecFromURL( "github.com/someOrg/someRepo/foo/overlay") if err != nil { t.Fatalf("unexpected err: %v\n", err) @@ -533,7 +533,7 @@ func TestRepoDirectCycleDetection(t *testing.T) { RestrictionRootOnly, root, fSys, nil, git.DoNothingCloner(filesys.ConfirmedDir(cloneRoot))) p1 := "github.com/someOrg/someRepo/foo" - rs1, err := git.NewRepoSpecFromUrl(p1) + rs1, err := git.NewRepoSpecFromURL(p1) if err != nil { t.Fatalf("unexpected err: %v", err) } diff --git a/api/loader/loader.go b/api/loader/loader.go index 7a2b75f20a..17dbad8974 100644 --- a/api/loader/loader.go +++ b/api/loader/loader.go @@ -19,7 +19,7 @@ import ( func NewLoader( lr LoadRestrictorFunc, target string, fSys filesys.FileSystem) (ifc.Loader, error) { - repoSpec, err := git.NewRepoSpecFromUrl(target) + repoSpec, err := git.NewRepoSpecFromURL(target) if err == nil { // The target qualifies as a remote git target. return newLoaderAtGitClone( diff --git a/api/resmap/factory.go b/api/resmap/factory.go index 9ec0fe3967..ee6c68f107 100644 --- a/api/resmap/factory.go +++ b/api/resmap/factory.go @@ -78,8 +78,8 @@ func (rmF *Factory) NewResMapFromBytes(b []byte) (ResMap, error) { func (rmF *Factory) NewResMapFromConfigMapArgs( kvLdr ifc.KvLoader, argList []types.ConfigMapArgs) (ResMap, error) { var resources []*resource.Resource - for _, args := range argList { - res, err := rmF.resF.MakeConfigMap(kvLdr, &args) + for i := range argList { + res, err := rmF.resF.MakeConfigMap(kvLdr, &argList[i]) if err != nil { return nil, errors.Wrap(err, "NewResMapFromConfigMapArgs") } @@ -103,8 +103,8 @@ func (rmF *Factory) FromConfigMapArgs( func (rmF *Factory) NewResMapFromSecretArgs( kvLdr ifc.KvLoader, argsList []types.SecretArgs) (ResMap, error) { var resources []*resource.Resource - for _, args := range argsList { - res, err := rmF.resF.MakeSecret(kvLdr, &args) + for i := range argsList { + res, err := rmF.resF.MakeSecret(kvLdr, &argsList[i]) if err != nil { return nil, errors.Wrap(err, "NewResMapFromSecretArgs") } diff --git a/api/resmap/reswrangler.go b/api/resmap/reswrangler.go index 5ce98dc777..e802994482 100644 --- a/api/resmap/reswrangler.go +++ b/api/resmap/reswrangler.go @@ -429,7 +429,6 @@ func getNamespacesForRoleBinding(r *resource.Resource) (map[string]bool, error) if r.GetKind() != "RoleBinding" { return result, nil } - //nolint staticcheck subjects, err := r.GetSlice("subjects") if err != nil || subjects == nil { return result, nil @@ -442,7 +441,7 @@ func getNamespacesForRoleBinding(r *resource.Resource) (map[string]bool, error) if n, ok3 := ns.(string); ok3 { result[n] = true } else { - return nil, errors.New(fmt.Sprintf("Invalid Input: namespace is blank for resource %q\n", r.CurId())) + return nil, errors.Errorf("Invalid Input: namespace is blank for resource %q\n", r.CurId()) } } } diff --git a/api/resmap/reswrangler_test.go b/api/resmap/reswrangler_test.go index d81c76cdd8..44f3f11a93 100644 --- a/api/resmap/reswrangler_test.go +++ b/api/resmap/reswrangler_test.go @@ -116,7 +116,7 @@ func TestAppendRemove(t *testing.T) { doAppend(t, w2, makeCm(2)) doAppend(t, w2, makeCm(4)) doAppend(t, w2, makeCm(6)) - if !reflect.DeepEqual(w1, w1) { + if !reflect.DeepEqual(w1, w2) { w1.Debug("w1") w2.Debug("w2") t.Fatalf("mismatch") @@ -431,7 +431,6 @@ func TestGetMatchingResourcesByAnyId(t *testing.T) { m := resmaptest_test.NewRmBuilder(t, rf). AddR(r1).AddR(r2).AddR(r3).AddR(r4).AddR(r5).ResMap() - // nolint:goconst tests := []struct { name string matcher IdMatcher diff --git a/api/resource/origin.go b/api/resource/origin.go index d5ac3a1a4f..3f4cfe3406 100644 --- a/api/resource/origin.go +++ b/api/resource/origin.go @@ -50,7 +50,7 @@ func (origin *Origin) Copy() Origin { // Append returns a copy of origin with a path appended to it func (origin *Origin) Append(path string) *Origin { originCopy := origin.Copy() - repoSpec, err := git.NewRepoSpecFromUrl(path) + repoSpec, err := git.NewRepoSpecFromURL(path) if err == nil { originCopy.Repo = repoSpec.Host + repoSpec.OrgRepo absPath := repoSpec.AbsPath() diff --git a/api/types/helmchartargs.go b/api/types/helmchartargs.go index c0fff2457e..32575835d0 100644 --- a/api/types/helmchartargs.go +++ b/api/types/helmchartargs.go @@ -96,8 +96,8 @@ type HelmChartArgs struct { // per-chart params and global chart-independent parameters. func SplitHelmParameters( oldArgs []HelmChartArgs) (charts []HelmChart, globals HelmGlobals) { - for _, old := range oldArgs { - charts = append(charts, makeHelmChartFromHca(&old)) + for i, old := range oldArgs { + charts = append(charts, makeHelmChartFromHca(&oldArgs[i])) if old.HelmHome != "" { // last non-empty wins globals.ConfigHome = old.HelmHome diff --git a/api/types/kustomization.go b/api/types/kustomization.go index e7935d16ff..c194dcc3c1 100644 --- a/api/types/kustomization.go +++ b/api/types/kustomization.go @@ -192,14 +192,14 @@ func (k *Kustomization) FixKustomizationPostUnmarshalling() { for i, g := range k.ConfigMapGenerator { if g.EnvSource != "" { k.ConfigMapGenerator[i].EnvSources = - append(g.EnvSources, g.EnvSource) + append(g.EnvSources, g.EnvSource) //nolint:gocritic k.ConfigMapGenerator[i].EnvSource = "" } } for i, g := range k.SecretGenerator { if g.EnvSource != "" { k.SecretGenerator[i].EnvSources = - append(g.EnvSources, g.EnvSource) + append(g.EnvSources, g.EnvSource) //nolint:gocritic k.SecretGenerator[i].EnvSource = "" } } diff --git a/cmd/config/.golangci.yml b/cmd/config/.golangci.yml index 5eb0673fc6..d9f6c6a33f 100644 --- a/cmd/config/.golangci.yml +++ b/cmd/config/.golangci.yml @@ -49,5 +49,4 @@ linters-settings: line-length: 170 gocyclo: min-complexity: 30 - golint: - min-confidence: 0.85 + diff --git a/cmd/config/Makefile b/cmd/config/Makefile index 774bf3e15f..bfa4c6368c 100644 --- a/cmd/config/Makefile +++ b/cmd/config/Makefile @@ -12,7 +12,7 @@ $(GOBIN)/addlicense: go get github.com/google/addlicense $(GOBIN)/golangci-lint: - go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.19.1 + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.2 $(GOBIN)/k8scopy: ( cd ../k8scopy; go install . ) diff --git a/cmd/pluginator/internal/krmfunction/converter.go b/cmd/pluginator/internal/krmfunction/converter.go index 4798e92d8d..3c5b748534 100644 --- a/cmd/pluginator/internal/krmfunction/converter.go +++ b/cmd/pluginator/internal/krmfunction/converter.go @@ -105,7 +105,7 @@ func (c *Converter) prepareWrapper(content string) string { } // assign to plugin variable if strings.TrimSpace(line) == "var plugin resmap.Configurable" { - line = line + ` + line += ` // KustomizePlugin is a global variable defined in every plugin plugin = &KustomizePlugin ` @@ -156,7 +156,7 @@ func (c *Converter) mkDstDir() error { func (c *Converter) write(m map[string]string) error { for k, v := range m { p := filepath.Join(c.outputDir, k) - err := ioutil.WriteFile(p, []byte(v), 0644) + err := ioutil.WriteFile(p, []byte(v), 0644) //nolint:gosec if err != nil { return err } diff --git a/cmd/pluginator/internal/krmfunction/converter_test.go b/cmd/pluginator/internal/krmfunction/converter_test.go index 4016e55502..aa87571a15 100644 --- a/cmd/pluginator/internal/krmfunction/converter_test.go +++ b/cmd/pluginator/internal/krmfunction/converter_test.go @@ -118,7 +118,7 @@ func TestTransformerConverter(t *testing.T) { dir := makeTempDir(t) defer os.RemoveAll(dir) - ioutil.WriteFile(filepath.Join(dir, "Plugin.go"), + ioutil.WriteFile(filepath.Join(dir, "Plugin.go"), // nolint: gosec getTransformerCode(), 0644) c := NewConverter(filepath.Join(dir, "output"), @@ -215,7 +215,7 @@ func TestGeneratorConverter(t *testing.T) { dir := makeTempDir(t) defer os.RemoveAll(dir) - ioutil.WriteFile(filepath.Join(dir, "Plugin.go"), + ioutil.WriteFile(filepath.Join(dir, "Plugin.go"), // nolint: gosec getGeneratorCode(), 0644) c := NewConverter(filepath.Join(dir, "output"), diff --git a/cmd/pluginator/internal/krmfunction/funcwrappersrc/fakeplugin.go b/cmd/pluginator/internal/krmfunction/funcwrappersrc/fakeplugin.go index b5a5426d86..1f3d9e7a25 100644 --- a/cmd/pluginator/internal/krmfunction/funcwrappersrc/fakeplugin.go +++ b/cmd/pluginator/internal/krmfunction/funcwrappersrc/fakeplugin.go @@ -1,4 +1,3 @@ -//nolint package funcwrappersrc import ( diff --git a/kustomize/commands/build/build_test.go b/kustomize/commands/build/build_test.go index ef90f2cd74..caf89c3fa3 100644 --- a/kustomize/commands/build/build_test.go +++ b/kustomize/commands/build/build_test.go @@ -243,10 +243,8 @@ func TestValidation(t *testing.T) { t.Errorf("%s: Expected error %s, but got %v", n, tc.erMsg, err) } - } else { - if err != nil { - t.Errorf("%s: unknown error: %v", n, err) - } + } else if err != nil { + t.Errorf("%s: unknown error: %v", n, err) } }) } diff --git a/kustomize/commands/edit/add/addbase.go b/kustomize/commands/edit/add/addbase.go index 4f8b433d58..d5835813a3 100644 --- a/kustomize/commands/edit/add/addbase.go +++ b/kustomize/commands/edit/add/addbase.go @@ -68,7 +68,6 @@ func (o *addBaseOptions) RunAddBase(fSys filesys.FileSystem) error { return fmt.Errorf("base %s already in kustomization file", path) } m.Resources = append(m.Resources, path) - } return mf.Write(m) diff --git a/kustomize/commands/edit/fix/convert.go b/kustomize/commands/edit/fix/convert.go index b0c8de0f0d..43aeadf177 100644 --- a/kustomize/commands/edit/fix/convert.go +++ b/kustomize/commands/edit/fix/convert.go @@ -78,11 +78,9 @@ func filesTouchedByKustomize(k *types.Kustomization, filepath string, fSys files } result = append(result, paths...) } - } // read the resource as a file result = append(result, path.Join(filepath, r)) - } // aggregate all of the paths from the `patches` field @@ -149,7 +147,6 @@ func findVarName(node *kyaml.RNode, varName string, path []string) ([]string, [] var options []*types.FieldOptions switch node.YNode().Kind { - case kyaml.SequenceNode: elements, err := node.Elements() if err != nil { @@ -237,7 +234,6 @@ func constructFieldOptions(value string, varString string) ([]*types.FieldOption func constructTargets(file string, node *kyaml.RNode, fieldPaths []string, options []*types.FieldOptions) ([]*types.TargetSelector, error) { - if len(fieldPaths) != len(options) { // this should never happen return nil, fmt.Errorf("internal error: length of fieldPaths != length of fieldOptions") @@ -287,7 +283,6 @@ func constructTargets(file string, node *kyaml.RNode, fieldPaths []string, // resources may have different IDs than the patch func writePatchTargets(patch types.Patch, node *kyaml.RNode, fieldPaths []string, options []*types.FieldOptions) ([]*types.TargetSelector, error) { - var result []*types.TargetSelector selector := patch.Target.Copy() diff --git a/kustomize/commands/edit/fix/fix.go b/kustomize/commands/edit/fix/fix.go index fd547b5adf..eb1e260fb4 100644 --- a/kustomize/commands/edit/fix/fix.go +++ b/kustomize/commands/edit/fix/fix.go @@ -70,7 +70,6 @@ Fixed fields: patchesJson6902 -> patches commonLabels -> labels vars -> replacements`) - } else { fmt.Fprintln(w, ` Fixed fields: diff --git a/kustomize/commands/edit/remove/removeresource.go b/kustomize/commands/edit/remove/removeresource.go index ae04657bcb..4a85356ef1 100644 --- a/kustomize/commands/edit/remove/removeresource.go +++ b/kustomize/commands/edit/remove/removeresource.go @@ -52,7 +52,6 @@ func (o *removeResourceOptions) Validate(args []string) error { // RunRemoveResource runs Resource command (do real work). func (o *removeResourceOptions) RunRemoveResource(fSys filesys.FileSystem) error { - mf, err := kustfile.NewKustomizationFile(fSys) if err != nil { return err diff --git a/kustomize/commands/edit/set/setimage.go b/kustomize/commands/edit/set/setimage.go index 94f02f57c3..e68d7b1912 100644 --- a/kustomize/commands/edit/set/setimage.go +++ b/kustomize/commands/edit/set/setimage.go @@ -105,7 +105,6 @@ func (o *setImageOptions) Validate(args []string) error { o.imageMap = make(map[string]types.Image) for _, arg := range args { - img, err := parse(arg) if err != nil { return err @@ -129,7 +128,6 @@ func (o *setImageOptions) RunSetImage(fSys filesys.FileSystem) error { // append only new images from kustomize file for _, im := range m.Images { if argIm, ok := o.imageMap[im.Name]; ok { - // Reuse the existing new name when asterisk new name is passed if argIm.NewName == preserveSeparator { argIm = replaceNewName(argIm, im.NewName) @@ -155,7 +153,6 @@ func (o *setImageOptions) RunSetImage(fSys filesys.FileSystem) error { var images []types.Image for _, v := range o.imageMap { - if v.NewName == preserveSeparator { v = replaceNewName(v, "") } @@ -207,7 +204,6 @@ func replaceDigest(image types.Image, digest string) types.Image { } func parse(arg string) (types.Image, error) { - // matches if there is an image name to overwrite // =<:|@> if s := strings.Split(arg, separator); len(s) == 2 { diff --git a/kustomize/commands/edit/set/setreplicas.go b/kustomize/commands/edit/set/setreplicas.go index ab32900aa4..695f19ad28 100644 --- a/kustomize/commands/edit/set/setreplicas.go +++ b/kustomize/commands/edit/set/setreplicas.go @@ -69,7 +69,6 @@ func (o *setReplicasOptions) Validate(args []string) error { o.replicasMap = make(map[string]types.Replica) for _, arg := range args { - replica, err := parseReplicasArg(arg) if err != nil { return err @@ -113,7 +112,6 @@ func (o *setReplicasOptions) RunSetReplicas(fSys filesys.FileSystem) error { } func parseReplicasArg(arg string) (types.Replica, error) { - // matches a name and a replica count // = if s := strings.Split(arg, replicasSeparator); len(s) == 2 { diff --git a/kustomize/commands/internal/kustfile/kustomizationfile.go b/kustomize/commands/internal/kustfile/kustomizationfile.go index 3d569cee11..967e8312f2 100644 --- a/kustomize/commands/internal/kustfile/kustomizationfile.go +++ b/kustomize/commands/internal/kustfile/kustomizationfile.go @@ -11,8 +11,9 @@ import ( "log" "reflect" "regexp" - "strings" + "golang.org/x/text/cases" + "golang.org/x/text/language" "sigs.k8s.io/kustomize/api/konfig" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/filesys" @@ -116,7 +117,7 @@ type kustomizationFile struct { } // NewKustomizationFile returns a new instance. -func NewKustomizationFile(fSys filesys.FileSystem) (*kustomizationFile, error) { // nolint +func NewKustomizationFile(fSys filesys.FileSystem) (*kustomizationFile, error) { mf := &kustomizationFile{fSys: fSys} err := mf.validate() if err != nil { @@ -291,7 +292,8 @@ func findMatchedField(line []byte) (bool, string) { // an empty []byte is returned. func marshalField(field string, kustomization *types.Kustomization) ([]byte, error) { r := reflect.ValueOf(*kustomization) - v := r.FieldByName(strings.Title(field)) + titleCaser := cases.Title(language.English, cases.NoLower) + v := r.FieldByName(titleCaser.String(field)) if !v.IsValid() || isEmpty(v) { return []byte{}, nil @@ -299,7 +301,7 @@ func marshalField(field string, kustomization *types.Kustomization) ([]byte, err k := &types.Kustomization{} kr := reflect.ValueOf(k) - kv := kr.Elem().FieldByName(strings.Title(field)) + kv := kr.Elem().FieldByName(titleCaser.String(field)) kv.Set(v) return yaml.Marshal(k) diff --git a/kustomize/commands/internal/util/util.go b/kustomize/commands/internal/util/util.go index 943c4d4d62..c084909cdf 100644 --- a/kustomize/commands/internal/util/util.go +++ b/kustomize/commands/internal/util/util.go @@ -72,13 +72,14 @@ func ConvertSliceToMap(inputs []string, kind string) (map[string]string, error) result := make(map[string]string) for _, input := range inputs { c := strings.Index(input, ":") - if c == 0 { + switch { + case c == 0: // key is not passed return nil, fmt.Errorf("invalid %s: '%s' (%s)", kind, input, "need k:v pair where v may be quoted") - } else if c < 0 { + case c < 0: // only key passed result[input] = "" - } else { + default: // both key and value passed key := input[:c] value := trimQuotes(input[c+1:]) diff --git a/kustomize/commands/openapi/openapi.go b/kustomize/commands/openapi/openapi.go index 84e9b96265..4fdcad8823 100644 --- a/kustomize/commands/openapi/openapi.go +++ b/kustomize/commands/openapi/openapi.go @@ -13,7 +13,6 @@ import ( // NewCmdOpenAPI makes a new openapi command. func NewCmdOpenAPI(w io.Writer) *cobra.Command { - openApiCmd := &cobra.Command{ Use: "openapi", Short: "Commands for interacting with the OpenAPI data", diff --git a/kustomize/go.mod b/kustomize/go.mod index c58248aae5..8f580c17b9 100644 --- a/kustomize/go.mod +++ b/kustomize/go.mod @@ -8,6 +8,7 @@ require ( github.com/spf13/cobra v1.4.0 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.7.0 + golang.org/x/text v0.3.7 sigs.k8s.io/kustomize/api v0.11.4 sigs.k8s.io/kustomize/cmd/config v0.10.6 sigs.k8s.io/kustomize/kyaml v0.13.6 diff --git a/kyaml/.golangci.yml b/kyaml/.golangci.yml index 280e44b3c0..32932a5629 100644 --- a/kyaml/.golangci.yml +++ b/kyaml/.golangci.yml @@ -5,6 +5,7 @@ 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. @@ -14,34 +15,35 @@ linters: - bodyclose - deadcode - depguard - # - dogsled # uncomment after upgrading golangci-lint (Issue #3663) + - dogsled - dupl - - errcheck +# - errcheck + - exportloopref +# - funlen - gochecknoinits - goconst - gocritic - gocyclo - gofmt - goimports -# - gosec + - gosec - gosimple - govet - ineffassign - lll - misspell - nakedret + - nolintlint - revive - - scopelint - staticcheck - structcheck - - stylecheck +# - stylecheck # seems redundant with revive, which replaced golint - typecheck - unconvert - unparam - unused - varcheck - # - whitespace # uncomment after upgrading golangci-lint (Issue #3663) - + - whitespace linters-settings: dupl: @@ -50,5 +52,21 @@ linters-settings: line-length: 170 gocyclo: min-complexity: 30 - golint: - min-confidence: 0.85 + 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" + - linters: + - staticcheck + text: "SA1019: kioutil.Legacy" diff --git a/kyaml/Makefile b/kyaml/Makefile index 3dca1442fb..0346a522c2 100644 --- a/kyaml/Makefile +++ b/kyaml/Makefile @@ -12,11 +12,8 @@ export PATH := $(MYGOBIN):$(PATH) $(MYGOBIN)/addlicense: go get github.com/google/addlicense -# TODO: Issue #3663 -# Update this version of golangci-lint -# Ideally use same version as in {REPO}/hack/go.mod $(MYGOBIN)/golangci-lint: - go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.17.0 + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.2 $(MYGOBIN)/k8scopy: ( cd ../cmd/k8scopy; go install . ) @@ -24,7 +21,7 @@ $(MYGOBIN)/k8scopy: $(MYGOBIN)/stringer: go get golang.org/x/tools/cmd/stringer -all: license fix vet fmt test tidy +all: license fix vet fmt test lint tidy k8sGenDir := yaml/internal/k8sgen/pkg @@ -36,7 +33,8 @@ clean: lint: $(MYGOBIN)/golangci-lint $(MYGOBIN)/golangci-lint \ - run ./... + run ./... \ + --path-prefix=kyaml license: $(MYGOBIN)/addlicense diff --git a/kyaml/filesys/fsnode.go b/kyaml/filesys/fsnode.go index 983815fa90..7b84b51183 100644 --- a/kyaml/filesys/fsnode.go +++ b/kyaml/filesys/fsnode.go @@ -163,7 +163,6 @@ func (n *fsNode) AddFile( } func (n *fsNode) addDir(path string) (result *fsNode, err error) { - parent := n dName, subDirName := mySplit(path) if dName != "" { diff --git a/kyaml/filesys/fsnode_test.go b/kyaml/filesys/fsnode_test.go index 27751f3029..29dd3fb3df 100644 --- a/kyaml/filesys/fsnode_test.go +++ b/kyaml/filesys/fsnode_test.go @@ -93,7 +93,6 @@ func TestMakeFsInMemory(t *testing.T) { t, "MakeFsInMemory", true, topCases, MakeFsInMemory()) } -//nolint:gocyclo func runBasicOperations( t *testing.T, tName string, isFSysRooted bool, cases []pathCase, fSys FileSystem) { @@ -449,10 +448,10 @@ var bunchOfFiles = []struct { addAsDir: true, }, { - path: filepath.Join("x"), + path: "x", }, { - path: filepath.Join("y"), + path: "y", }, { path: filepath.Join("b", "d", "a", "c", "i", "beans"), @@ -559,7 +558,7 @@ func TestRemove(t *testing.T) { orgCount -= 3 // Now drop one more for a total of four dropped. - result, _ = n.Find(filepath.Join("y")) + result, _ = n.Find("y") err = result.Remove() if err != nil { t.Fatalf("%s; unable to remove: %v", path, err) @@ -692,7 +691,7 @@ func TestFind(t *testing.T) { }, { what: "directory", - arg: filepath.Join("b"), + arg: "b", expectDir: true, }, { @@ -869,7 +868,7 @@ func TestFileOps(t *testing.T) { defer f.Close() for { - buf := make([]byte, rand.Intn(10)) + buf := make([]byte, rand.Intn(10)) // nolint:gosec n, err := f.Read(buf) if err != nil && err != io.EOF { t.Fatalf("unexpected error: %v", err) diff --git a/kyaml/filesys/fsondisk.go b/kyaml/filesys/fsondisk.go index 7fd02a255a..22bb845eed 100644 --- a/kyaml/filesys/fsondisk.go +++ b/kyaml/filesys/fsondisk.go @@ -128,7 +128,7 @@ func (fsOnDisk) ReadFile(name string) ([]byte, error) { return ioutil.ReadFile(n // WriteFile delegates to ioutil.WriteFile with read/write permissions. func (fsOnDisk) WriteFile(name string, c []byte) error { - return ioutil.WriteFile(name, c, 0666) + return ioutil.WriteFile(name, c, 0666) //nolint:gosec } // Walk delegates to filepath.Walk. diff --git a/kyaml/filesys/fsondisk_test.go b/kyaml/filesys/fsondisk_test.go index 8de95f7ea4..221f10daa5 100644 --- a/kyaml/filesys/fsondisk_test.go +++ b/kyaml/filesys/fsondisk_test.go @@ -194,8 +194,8 @@ func TestReadFilesRealFS(t *testing.T) { "file-1.xtn", }, expectedDirs: map[string][]string{ - testDir: []string{dir}, - dir: []string{nestedDir}, + testDir: {dir}, + dir: {nestedDir}, }, }, "AllHiddenFiles": { @@ -206,7 +206,7 @@ func TestReadFilesRealFS(t *testing.T) { ".some-file-4.xtn", }, expectedDirs: map[string][]string{ - testDir: []string{hiddenDir}, + testDir: {hiddenDir}, }, }, "foo_File": { diff --git a/kyaml/fn/framework/frameworktestutil/frameworktestutil.go b/kyaml/fn/framework/frameworktestutil/frameworktestutil.go index df1b161f15..246c6e2e0d 100644 --- a/kyaml/fn/framework/frameworktestutil/frameworktestutil.go +++ b/kyaml/fn/framework/frameworktestutil/frameworktestutil.go @@ -273,9 +273,9 @@ type resultsChecker interface { shouldUpdateFixtures() bool // updateFixtures modifies the test fixture files to match the given content updateFixtures(t *testing.T, actualOutput string, actualError string) - // assertOutputMatches compares the expected output to the output recieved. + // assertOutputMatches compares the expected output to the output received. assertOutputMatches(t *testing.T, expected string, actual string) - // assertErrorMatches compares teh expected error to the error received. + // assertErrorMatches compares the expected error to the error received. assertErrorMatches(t *testing.T, expected string, actual string) } diff --git a/kyaml/fn/framework/validation_test.go b/kyaml/fn/framework/validation_test.go index c7a4a40536..199ef41010 100644 --- a/kyaml/fn/framework/validation_test.go +++ b/kyaml/fn/framework/validation_test.go @@ -75,14 +75,16 @@ spec: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + internal value, and may reject unrecognized values. More info: + https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' type: string color: type: string kind: description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + submits requests to. Cannot be updated. In CamelCase. More info: + https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' type: string metadata: type: object @@ -141,7 +143,7 @@ func TestSchemaFromFunctionDefinition(t *testing.T) { } else { require.NoError(t, err) var gotProps []string - for prop, _ := range got.Properties { + for prop := range got.Properties { gotProps = append(gotProps, prop) } sort.Strings(tt.wantProps) diff --git a/kyaml/fn/runtime/container/container.go b/kyaml/fn/runtime/container/container.go index 99ad88be37..c7cda7dbda 100644 --- a/kyaml/fn/runtime/container/container.go +++ b/kyaml/fn/runtime/container/container.go @@ -189,7 +189,7 @@ func (c *Filter) getCommand() (string, []string) { } args = append(args, runtimeutil.NewContainerEnvFromStringSlice(c.Env).GetDockerFlags()...) - a := append(args, c.Image) + a := append(args, c.Image) //nolint:gocritic return "docker", a } diff --git a/kyaml/fn/runtime/container/container_test.go b/kyaml/fn/runtime/container/container_test.go index 3774723d68..1fb51f077d 100644 --- a/kyaml/fn/runtime/container/container_test.go +++ b/kyaml/fn/runtime/container/container_test.go @@ -6,11 +6,11 @@ package container import ( "bytes" "fmt" - "github.com/stretchr/testify/require" "os" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil" "sigs.k8s.io/kustomize/kyaml/kio" "sigs.k8s.io/kustomize/kyaml/yaml" diff --git a/kyaml/fn/runtime/exec/exec.go b/kyaml/fn/runtime/exec/exec.go index f5a0b384cc..e9546820fc 100644 --- a/kyaml/fn/runtime/exec/exec.go +++ b/kyaml/fn/runtime/exec/exec.go @@ -34,7 +34,7 @@ func (c *Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) { } func (c *Filter) Run(reader io.Reader, writer io.Writer) error { - cmd := exec.Command(c.Path, c.Args...) + cmd := exec.Command(c.Path, c.Args...) // nolint:gosec cmd.Stdin = reader cmd.Stdout = writer cmd.Stderr = os.Stderr diff --git a/kyaml/kio/byteio_reader.go b/kyaml/kio/byteio_reader.go index fbcf4b6bef..230ab891bb 100644 --- a/kyaml/kio/byteio_reader.go +++ b/kyaml/kio/byteio_reader.go @@ -330,7 +330,7 @@ func (r *ByteReader) decode(originalYAML string, index int, decoder *yaml.Decode // derive and add the seqindent annotation seqIndentStyle := yaml.DeriveSeqIndentStyle(originalYAML) if seqIndentStyle != "" { - r.SetAnnotations[kioutil.SeqIndentAnnotation] = fmt.Sprintf("%s", seqIndentStyle) + r.SetAnnotations[kioutil.SeqIndentAnnotation] = seqIndentStyle } } } diff --git a/kyaml/kio/ignorefilesmatcher_test.go b/kyaml/kio/ignorefilesmatcher_test.go index 91e9dc15c6..ceb20bf0c3 100644 --- a/kyaml/kio/ignorefilesmatcher_test.go +++ b/kyaml/kio/ignorefilesmatcher_test.go @@ -41,7 +41,7 @@ func TestIgnoreFilesMatcher_readIgnoreFile(t *testing.T) { fsMakers := map[string]func(bool) (string, filesys.FileSystem){ // onDisk creates a temp directory and returns a nil FileSystem, testing // the normal conditions under which ignoreFileMatcher is used. - "onDisk": func(writeIgnoreFile bool) (string, filesys.FileSystem) { + "onDisk": func(writeIgnoreFile bool) (string, filesys.FileSystem) { //nolint:unparam dir, err := ioutil.TempDir("", "kyaml-test") require.NoError(t, err) @@ -107,10 +107,10 @@ func TestLocalPackageReader_Read_ignoreFile(t *testing.T) { filepath.Join("a", "c"), }, files: map[string][]byte{ - filepath.Join("pkgFile"): {}, + "pkgFile": {}, filepath.Join("a", "b", "a_test.yaml"): readFileA, filepath.Join("a", "c", "c_test.yaml"): readFileB, - filepath.Join(".krmignore"): []byte(` + ".krmignore": []byte(` a/c/c_test.yaml `, ), @@ -127,10 +127,10 @@ a/c/c_test.yaml filepath.Join("a", "c"), }, files: map[string][]byte{ - filepath.Join("pkgFile"): {}, + "pkgFile": {}, filepath.Join("a", "b", "a_test.yaml"): readFileA, filepath.Join("a", "c", "c_test.yaml"): readFileB, - filepath.Join(".krmignore"): []byte(` + ".krmignore": []byte(` a/c `, ), @@ -146,10 +146,10 @@ a/c filepath.Join("a", "c"), }, files: map[string][]byte{ - filepath.Join("pkgFile"): {}, + "pkgFile": {}, filepath.Join("a", "c", "a_test.yaml"): readFileA, filepath.Join("a", "c", "c_test.yaml"): readFileB, - filepath.Join(".krmignore"): []byte(` + ".krmignore": []byte(` d/e/f.yaml `, ), @@ -168,10 +168,10 @@ a_test.yaml filepath.Join("a", "c"), }, files: map[string][]byte{ - filepath.Join("pkgFile"): {}, + "pkgFile": {}, filepath.Join("a", "c", "a_test.yaml"): readFileA, filepath.Join("a", "c", "c_test.yaml"): readFileB, - filepath.Join(".krmignore"): []byte(` + ".krmignore": []byte(` a/c/c_test.yaml `, ), @@ -187,16 +187,16 @@ a_test.yaml { name: "handles a combination of packages and directories", directories: []string{ - filepath.Join("a"), + "a", filepath.Join("d", "e"), - filepath.Join("f"), + "f", }, files: map[string][]byte{ - filepath.Join("pkgFile"): {}, + "pkgFile": {}, filepath.Join("d", "pkgFile"): {}, filepath.Join("d", "e", "pkgFile"): {}, filepath.Join("f", "pkgFile"): {}, - filepath.Join("manifest.yaml"): []byte(`root: root`), + "manifest.yaml": []byte(`root: root`), filepath.Join("a", "manifest.yaml"): []byte(`a: a`), filepath.Join("d", "manifest.yaml"): []byte(`d: d`), filepath.Join("d", "e", "manifest.yaml"): []byte(`e: e`), @@ -215,14 +215,14 @@ manifest.yaml { name: "ignore file can exclude subpackages", directories: []string{ - filepath.Join("a"), + "a", }, files: map[string][]byte{ - filepath.Join("pkgFile"): {}, + "pkgFile": {}, filepath.Join("a", "pkgFile"): {}, - filepath.Join("manifest.yaml"): []byte(`root: root`), + "manifest.yaml": []byte(`root: root`), filepath.Join("a", "manifest.yaml"): []byte(`a: a`), - filepath.Join(".krmignore"): []byte(` + ".krmignore": []byte(` a `), }, diff --git a/kyaml/kio/kio.go b/kyaml/kio/kio.go index 776b6a73aa..9e00509ebe 100644 --- a/kyaml/kio/kio.go +++ b/kyaml/kio/kio.go @@ -270,7 +270,10 @@ func ReconcileInternalAnnotations(result []*yaml.RNode, nodeAnnosMap map[string] } // determineAnnotationsFormat determines if the resources are using one of the internal and legacy annotation format or both of them. -func determineAnnotationsFormat(nodeAnnosMap map[string]map[string]string) (useInternal, useLegacy bool, err error) { +func determineAnnotationsFormat(nodeAnnosMap map[string]map[string]string) (bool, bool, error) { + var useInternal, useLegacy bool + var err error + if len(nodeAnnosMap) == 0 { return true, true, nil } @@ -295,7 +298,7 @@ func determineAnnotationsFormat(nodeAnnosMap map[string]map[string]string) (useI } if (foundOneOf && !*internal) || (!foundOneOf && *internal) { err = fmt.Errorf("the annotation formatting in the input resources is not consistent") - return + return useInternal, useLegacy, err } foundOneOf = foundLegacyPath || foundLegacyIndex || foundLegacyId @@ -305,7 +308,7 @@ func determineAnnotationsFormat(nodeAnnosMap map[string]map[string]string) (useI } if (foundOneOf && !*legacy) || (!foundOneOf && *legacy) { err = fmt.Errorf("the annotation formatting in the input resources is not consistent") - return + return useInternal, useLegacy, err } } if internal != nil { @@ -314,7 +317,7 @@ func determineAnnotationsFormat(nodeAnnosMap map[string]map[string]string) (useI if legacy != nil { useLegacy = *legacy } - return + return useInternal, useLegacy, err } func missingInternalOrLegacyAnnotations(rn *yaml.RNode) error { @@ -382,13 +385,14 @@ func checkAnnotationsAltered(rn *yaml.RNode, nodeAnnosMap map[string]map[string] originalPath = originalAnnotations[kioutil.LegacyPathAnnotation] } if originalPath != "" { - if originalPath != internal.path && originalPath != legacy.path && internal.path != legacy.path { + switch { + case originalPath != internal.path && originalPath != legacy.path && internal.path != legacy.path: return fmt.Errorf("resource input to function has mismatched legacy and internal path annotations") - } else if originalPath != internal.path { + case originalPath != internal.path: if _, err := rn.Pipe(yaml.SetAnnotation(kioutil.LegacyPathAnnotation, internal.path)); err != nil { return err } - } else if originalPath != legacy.path { + case originalPath != legacy.path: if _, err := rn.Pipe(yaml.SetAnnotation(kioutil.PathAnnotation, legacy.path)); err != nil { return err } @@ -400,13 +404,14 @@ func checkAnnotationsAltered(rn *yaml.RNode, nodeAnnosMap map[string]map[string] originalIndex = originalAnnotations[kioutil.LegacyIndexAnnotation] } if originalIndex != "" { - if originalIndex != internal.index && originalIndex != legacy.index && internal.index != legacy.index { + switch { + case originalIndex != internal.index && originalIndex != legacy.index && internal.index != legacy.index: return fmt.Errorf("resource input to function has mismatched legacy and internal index annotations") - } else if originalIndex != internal.index { + case originalIndex != internal.index: if _, err := rn.Pipe(yaml.SetAnnotation(kioutil.LegacyIndexAnnotation, internal.index)); err != nil { return err } - } else if originalIndex != legacy.index { + case originalIndex != legacy.index: if _, err := rn.Pipe(yaml.SetAnnotation(kioutil.IndexAnnotation, legacy.index)); err != nil { return err } diff --git a/kyaml/kio/kio_test.go b/kyaml/kio/kio_test.go index e7e5d046a9..0bd3c6dd35 100644 --- a/kyaml/kio/kio_test.go +++ b/kyaml/kio/kio_test.go @@ -883,7 +883,6 @@ data: assert.Error(t, err) assert.Equal(t, tc.expectedErr, err.Error()) } - }) } } diff --git a/kyaml/kio/kioutil/kioutil_test.go b/kyaml/kio/kioutil/kioutil_test.go index 3bbdea26a9..d054626527 100644 --- a/kyaml/kio/kioutil/kioutil_test.go +++ b/kyaml/kio/kioutil/kioutil_test.go @@ -644,7 +644,9 @@ metadata: internal.config.kubernetes.io/e: 'f' internal.config.kubernetes.io/g: 'h' `, - expectedErr: `internal annotations differ: internal.config.kubernetes.io/a, internal.config.kubernetes.io/c, internal.config.kubernetes.io/e, internal.config.kubernetes.io/g`, + expectedErr: `internal annotations differ: ` + + `internal.config.kubernetes.io/a, internal.config.kubernetes.io/c, ` + + `internal.config.kubernetes.io/e, internal.config.kubernetes.io/g`, }, } diff --git a/kyaml/kio/pkgio_reader_test.go b/kyaml/kio/pkgio_reader_test.go index 9d887b98f3..1f71833616 100644 --- a/kyaml/kio/pkgio_reader_test.go +++ b/kyaml/kio/pkgio_reader_test.go @@ -216,9 +216,19 @@ func TestLocalPackageReader_Read_JSON(t *testing.T) { require.NoError(t, err) require.Len(t, nodes, 2) expected := []string{ - `{"a": "b", metadata: {annotations: {config.kubernetes.io/index: '0', config.kubernetes.io/path: 'a_test.json', internal.config.kubernetes.io/index: '0', internal.config.kubernetes.io/path: 'a_test.json'}}} + `{"a": "b", ` + + `metadata: {annotations: {` + + `config.kubernetes.io/index: '0', ` + + `config.kubernetes.io/path: 'a_test.json', ` + + `internal.config.kubernetes.io/index: '0', ` + + `internal.config.kubernetes.io/path: 'a_test.json'}}} `, - `{"e": "f", "g": {"h": ["i", "j"]}, metadata: {annotations: {config.kubernetes.io/index: '0', config.kubernetes.io/path: 'b_test.json', internal.config.kubernetes.io/index: '0', internal.config.kubernetes.io/path: 'b_test.json'}}} + `{"e": "f", "g": {"h": ["i", "j"]}, ` + + `metadata: {annotations: {` + + `config.kubernetes.io/index: '0', ` + + `config.kubernetes.io/path: 'b_test.json', ` + + `internal.config.kubernetes.io/index: '0', ` + + `internal.config.kubernetes.io/path: 'b_test.json'}}} `, } for i := range nodes { diff --git a/kyaml/kio/pkgio_writer_test.go b/kyaml/kio/pkgio_writer_test.go index 0ef6648525..16aea4adf3 100644 --- a/kyaml/kio/pkgio_writer_test.go +++ b/kyaml/kio/pkgio_writer_test.go @@ -325,7 +325,7 @@ metadata: // These two lines are similar to calling ioutil.TempDir, but we don't actually create any directory. rand.Seed(time.Now().Unix()) - path := filepath.Join(os.TempDir(), fmt.Sprintf("kyaml-test%d", rand.Int31())) + path := filepath.Join(os.TempDir(), fmt.Sprintf("kyaml-test%d", rand.Int31())) //nolint:gosec require.NoError(t, mockFS.MkdirAll(filepath.Join(path, "a"))) return path, node1, node2, node3, func() { require.NoError(t, mockFS.RemoveAll(path)) } } diff --git a/kyaml/order/syncorder.go b/kyaml/order/syncorder.go index 9352fd8ccd..57bc865039 100644 --- a/kyaml/order/syncorder.go +++ b/kyaml/order/syncorder.go @@ -39,10 +39,7 @@ func syncOrder(from, to *yaml.RNode) error { return syncOrder(fNode.Value, tNode.Value) }) case yaml.SequenceNode: - return VisitElements(from, to, func(fNode, tNode *yaml.RNode) error { - // Traverse each list element - return syncOrder(fNode, tNode) - }) + return VisitElements(from, to, syncOrder) // Traverse each list element } return nil } diff --git a/kyaml/order/syncorder_test.go b/kyaml/order/syncorder_test.go index 6fa8fe021d..94b5cff529 100644 --- a/kyaml/order/syncorder_test.go +++ b/kyaml/order/syncorder_test.go @@ -259,7 +259,7 @@ spec: properties: conditions: items: - description: ControlPlaneRevisionCondition is a repeated struct definining the current conditions of a ControlPlaneRevision. + description: ControlPlaneRevisionCondition is a repeated struct defining the current conditions of a ControlPlaneRevision. properties: lastTransitionTime: description: Last time the condition transitioned from one status to another @@ -347,7 +347,7 @@ spec: type: array items: type: object - description: ControlPlaneRevisionCondition is a repeated struct definining the current conditions of a ControlPlaneRevision. + description: ControlPlaneRevisionCondition is a repeated struct defining the current conditions of a ControlPlaneRevision. properties: type: type: string diff --git a/kyaml/pathutil/pathutil_test.go b/kyaml/pathutil/pathutil_test.go index 6069a581f7..39a49611d2 100644 --- a/kyaml/pathutil/pathutil_test.go +++ b/kyaml/pathutil/pathutil_test.go @@ -82,15 +82,15 @@ func createTestDirStructure(dir string) error { if err != nil { return err } - err = ioutil.WriteFile(filepath.Join(dir, "subpkg1", "Krmfile"), []byte(""), 0777) + err = ioutil.WriteFile(filepath.Join(dir, "subpkg1", "Krmfile"), []byte(""), 0644) if err != nil { return err } - err = ioutil.WriteFile(filepath.Join(dir, "subpkg2", "Krmfile"), []byte(""), 0777) + err = ioutil.WriteFile(filepath.Join(dir, "subpkg2", "Krmfile"), []byte(""), 0644) if err != nil { return err } - err = ioutil.WriteFile(filepath.Join(dir, "Krmfile"), []byte(""), 0777) + err = ioutil.WriteFile(filepath.Join(dir, "Krmfile"), []byte(""), 0644) if err != nil { return err } diff --git a/kyaml/runfn/runfn_test.go b/kyaml/runfn/runfn_test.go index fcb0ec7e83..36b660737c 100644 --- a/kyaml/runfn/runfn_test.go +++ b/kyaml/runfn/runfn_test.go @@ -342,7 +342,7 @@ metadata: {name: "sort functions -- deepest first", in: []f{ { - path: filepath.Join("a.yaml"), + path: "a.yaml", value: ` metadata: annotations: @@ -382,7 +382,7 @@ metadata: `, }, { - path: filepath.Join("b.yaml"), + path: "b.yaml", value: ` metadata: annotations: @@ -412,7 +412,7 @@ metadata: `, }, { - path: filepath.Join("b.yaml"), + path: "b.yaml", value: ` metadata: annotations: @@ -442,7 +442,7 @@ metadata: `, }, { - path: filepath.Join("b.yaml"), + path: "b.yaml", value: ` metadata: annotations: @@ -473,7 +473,7 @@ metadata: `, }, { - path: filepath.Join("b.yaml"), + path: "b.yaml", value: ` metadata: annotations: @@ -502,7 +502,7 @@ metadata: `, }, { - path: filepath.Join("b.yaml"), + path: "b.yaml", value: ` metadata: annotations: @@ -543,7 +543,7 @@ metadata: `, }, { - path: filepath.Join("b.yaml"), + path: "b.yaml", value: ` metadata: annotations: diff --git a/kyaml/setters2/settersutil/fieldsetter.go b/kyaml/setters2/settersutil/fieldsetter.go index baf4a5f2eb..8b753661eb 100644 --- a/kyaml/setters2/settersutil/fieldsetter.go +++ b/kyaml/setters2/settersutil/fieldsetter.go @@ -50,7 +50,7 @@ func (fs *FieldSetter) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { } // Set updates the OpenAPI definitions and resources with the new setter value -func (fs FieldSetter) Set() (int, error) { +func (fs *FieldSetter) Set() (int, error) { // Update the OpenAPI definitions soa := setters2.SetOpenAPI{ Name: fs.Name, diff --git a/kyaml/setters2/settersutil/settercreator.go b/kyaml/setters2/settersutil/settercreator.go index be551c741b..ded388a8ac 100644 --- a/kyaml/setters2/settersutil/settercreator.go +++ b/kyaml/setters2/settersutil/settercreator.go @@ -64,7 +64,7 @@ func (c *SetterCreator) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { return nil, c.Create() } -func (c SetterCreator) Create() error { +func (c *SetterCreator) Create() error { err := c.validateSetterInfo() if err != nil { return err diff --git a/kyaml/yaml/fns_test.go b/kyaml/yaml/fns_test.go index ae6f00747c..0c6ed8c0b1 100644 --- a/kyaml/yaml/fns_test.go +++ b/kyaml/yaml/fns_test.go @@ -864,7 +864,6 @@ func TestMapEntrySetter(t *testing.T) { assert.NotNil(t, err) assert.Equal(t, tc.expectedErr.Error(), err.Error()) } - }) } } @@ -1092,15 +1091,14 @@ func (c filter) Filter(object *RNode) (*RNode, error) { } func TestResourceNode_Pipe(t *testing.T) { - r0, r1, r2, r3 := &RNode{}, &RNode{}, &RNode{}, &RNode{} + var r0, r1, r2, r3 *RNode var called []string // check the nil value case - r0 = nil _, err := r0.Pipe(FieldMatcher{Name: "foo"}) assert.NoError(t, err) - r0 = &RNode{} + r0, r1, r2, r3 = &RNode{}, &RNode{}, &RNode{}, &RNode{} // all filters successful v, err := r0.Pipe( filter{fn: func(object *RNode) (*RNode, error) { diff --git a/kyaml/yaml/match.go b/kyaml/yaml/match.go index a7cdf83d82..d53f563d6a 100644 --- a/kyaml/yaml/match.go +++ b/kyaml/yaml/match.go @@ -99,7 +99,6 @@ func (p *PathMatcher) filter(rn *RNode) (*RNode, error) { } func (p *PathMatcher) doMatchEvery(rn *RNode) (*RNode, error) { - if err := rn.VisitElements(p.visitEveryElem); err != nil { return nil, err } @@ -108,7 +107,6 @@ func (p *PathMatcher) doMatchEvery(rn *RNode) (*RNode, error) { } func (p *PathMatcher) visitEveryElem(elem *RNode) error { - fieldName := p.Path[0] // recurse on the matching element pm := &PathMatcher{Path: p.Path[1:]} diff --git a/kyaml/yaml/rnode_test.go b/kyaml/yaml/rnode_test.go index d308efed20..35b73ffdb1 100644 --- a/kyaml/yaml/rnode_test.go +++ b/kyaml/yaml/rnode_test.go @@ -1168,7 +1168,6 @@ items: assert.NotNil(t, err) assert.Equal(t, tc.expectedErr.Error(), err.Error()) } - }) } } diff --git a/kyaml/yaml/util.go b/kyaml/yaml/util.go index dc78807813..8c9439342f 100644 --- a/kyaml/yaml/util.go +++ b/kyaml/yaml/util.go @@ -67,5 +67,4 @@ func keyLineBeforeSeqElem(lines []string, seqElemIndex int) string { return parts[0] // throw away the trailing comment part } return "" - } diff --git a/plugin/builtin/helmchartinflationgenerator/HelmChartInflationGenerator_test.go b/plugin/builtin/helmchartinflationgenerator/HelmChartInflationGenerator_test.go index aeeb131649..83c896b9dc 100644 --- a/plugin/builtin/helmchartinflationgenerator/HelmChartInflationGenerator_test.go +++ b/plugin/builtin/helmchartinflationgenerator/HelmChartInflationGenerator_test.go @@ -472,7 +472,7 @@ func TestHelmChartInflationGeneratorWithIncludeCRDs(t *testing.T) { // and has backticks, which makes string literals wonky testData, err := ioutil.ReadFile("include_crds_testdata.txt") if err != nil { - t.Errorf("unable to read test data for includeCRDs: %w", err) + t.Error(fmt.Errorf("unable to read test data for includeCRDs: %w", err)) } rm := th.LoadAndRunGenerator(`