From 8cc1e0aee9e8f79673fc431638e9aa833cb010c1 Mon Sep 17 00:00:00 2001 From: Julien Duchesne Date: Wed, 21 Sep 2022 07:20:29 -0400 Subject: [PATCH] More `golanci-lint` checks (#762) Active a bunch more linters following https://github.com/grafana/tanka/pull/761 This is mostly style checks like remove snake case variables and not starting error messages with an uppercase. This leads to a more consistent codebase --- .golangci.yml | 22 ++++++++++++++++++++++ Makefile | 4 +--- cmd/tk/env.go | 13 +++++++------ cmd/tk/fmt.go | 4 ++-- cmd/tk/init.go | 12 ++++++------ cmd/tk/main.go | 2 +- cmd/tk/prefix.go | 12 ++++++------ cmd/tk/tool.go | 12 ++++++------ cmd/tk/toolCharts.go | 2 +- pkg/helm/jsonnet.go | 6 +++--- pkg/helm/template.go | 4 ++-- pkg/jsonnet/eval.go | 6 +++--- pkg/jsonnet/imports.go | 2 -- pkg/jsonnet/jpath/errors.go | 2 +- pkg/jsonnet/jpath/jpath.go | 5 ++--- pkg/jsonnet/jpath/jpath_test.go | 3 +-- pkg/jsonnet/lint.go | 1 - pkg/kubernetes/apply.go | 6 +++--- pkg/kubernetes/client/apply_test.go | 1 - pkg/kubernetes/client/context.go | 2 +- pkg/kubernetes/client/delete.go | 1 - pkg/kubernetes/client/delete_test.go | 1 - pkg/kubernetes/client/kubectl.go | 1 - pkg/kubernetes/delete.go | 4 +--- pkg/kubernetes/diff.go | 4 ++-- pkg/kubernetes/manifest/manifest.go | 14 +++++++------- pkg/kubernetes/util/diff.go | 4 ++-- pkg/kustomize/jsonnet.go | 12 ++++++------ pkg/kustomize/kustomize.go | 2 +- pkg/process/filter.go | 4 ++-- pkg/tanka/export.go | 12 ++++++------ pkg/tanka/load.go | 2 +- pkg/tanka/tanka.go | 18 +++++++++--------- pkg/tanka/workflow.go | 11 +++++++---- 34 files changed, 112 insertions(+), 99 deletions(-) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..44c01b19c --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,22 @@ +linters: + enable: + - depguard + - dogsled + - errcheck + - exportloopref + - goconst + - gocritic + - gofmt + - goimports + - gosimple + - govet + - ineffassign + - megacheck + - misspell + - revive + - staticcheck + - stylecheck + - typecheck + - unconvert + - unused + - whitespace diff --git a/Makefile b/Makefile index bd5719318..0d3df8b06 100644 --- a/Makefile +++ b/Makefile @@ -9,8 +9,6 @@ $(GOLINTER): go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.49.0 lint: $(GOLINTER) - test -z $$(gofmt -s -l cmd/ pkg/ | tee /dev/stderr) - go vet ./... $(GOLINTER) run test: @@ -20,7 +18,7 @@ test: dev: go build -ldflags "-X main.Version=dev-${VERSION}" ./cmd/tk -LDFLAGS := '-s -w -extldflags "-static" -X github.com/grafana/tanka/pkg/tanka.CURRENT_VERSION=${VERSION}' +LDFLAGS := '-s -w -extldflags "-static" -X github.com/grafana/tanka/pkg/tanka.CurrentVersion=${VERSION}' static: CGO_ENABLED=0 go build -ldflags=${LDFLAGS} ./cmd/tk diff --git a/cmd/tk/env.go b/cmd/tk/env.go index 300ac353f..2caa8a770 100644 --- a/cmd/tk/env.go +++ b/cmd/tk/env.go @@ -3,12 +3,13 @@ package main import ( "encoding/json" "fmt" - "k8s.io/utils/strings/slices" "os" "path/filepath" "sort" "text/tabwriter" + "k8s.io/utils/strings/slices" + "github.com/go-clix/cli" "github.com/pkg/errors" "github.com/posener/complete" @@ -63,7 +64,7 @@ func envSetCmd() *cli.Command { cmd.Run = func(cmd *cli.Command, args []string) error { if *name != "" { - return fmt.Errorf("It looks like you attempted to rename the environment using `--name`. However, this is not possible with Tanka, because the environments name is inferred from the directories name. To rename the environment, rename its directory instead.") + return fmt.Errorf("it looks like you attempted to rename the environment using `--name`. However, this is not possible with Tanka, because the environments name is inferred from the directories name. To rename the environment, rename its directory instead") } path, err := filepath.Abs(args[0]) @@ -74,7 +75,7 @@ func envSetCmd() *cli.Command { if cmd.Flags().Changed("server-from-context") { server, err := client.IPFromContext(tmp.Spec.APIServer) if err != nil { - return fmt.Errorf("Resolving IP from context: %s", err) + return fmt.Errorf("resolving IP from context: %s", err) } tmp.Spec.APIServer = server } @@ -134,7 +135,7 @@ func envAddCmd() *cli.Command { if cmd.Flags().Changed("server-from-context") { server, err := client.IPFromContext(cfg.Spec.APIServer) if err != nil { - return fmt.Errorf("Resolving IP from context: %s", err) + return fmt.Errorf("resolving IP from context: %s", err) } cfg.Spec.APIServer = server } @@ -221,7 +222,7 @@ func envRemoveCmd() *cli.Command { return err } if err := os.RemoveAll(path); err != nil { - return fmt.Errorf("Removing '%s': %s", path, err) + return fmt.Errorf("removing '%s': %s", path, err) } fmt.Println("Removed", path) } @@ -272,7 +273,7 @@ func envListCmd() *cli.Command { if *useJSON { j, err := json.Marshal(envs) if err != nil { - return fmt.Errorf("Formatting as json: %s", err) + return fmt.Errorf("formatting as json: %s", err) } fmt.Println(string(j)) return nil diff --git a/cmd/tk/fmt.go b/cmd/tk/fmt.go index 58b5c5eaf..4b4ed926d 100644 --- a/cmd/tk/fmt.go +++ b/cmd/tk/fmt.go @@ -24,7 +24,7 @@ func fmtCmd() *cli.Command { Args: cli.Args{ Validator: cli.ValidateFunc(func(args []string) error { if len(args) == 0 { - return errors.New("At least one file or directory is required") + return errors.New("at least one file or directory is required") } return nil }), @@ -51,7 +51,7 @@ func fmtCmd() *cli.Command { globs[i] = g } - var outFn tanka.OutFn = nil + var outFn tanka.OutFn switch { case *test: outFn = func(name, content string) error { return nil } diff --git a/cmd/tk/init.go b/cmd/tk/init.go index 713e4976f..7f9030611 100644 --- a/cmd/tk/init.go +++ b/cmd/tk/init.go @@ -32,22 +32,22 @@ func initCmd() *cli.Command { files, err := os.ReadDir(".") if err != nil { - return fmt.Errorf("Error listing files: %s", err) + return fmt.Errorf("error listing files: %s", err) } if len(files) > 0 && !*force { - return fmt.Errorf("Error: directory not empty. Use `-f` to force") + return fmt.Errorf("error: directory not empty. Use `-f` to force") } if err := writeNewFile("jsonnetfile.json", "{}"); err != nil { - return fmt.Errorf("Error creating `jsonnetfile.json`: %s", err) + return fmt.Errorf("error creating `jsonnetfile.json`: %s", err) } if err := os.Mkdir("vendor", os.ModePerm); err != nil { - return fmt.Errorf("Error creating `vendor/` folder: %s", err) + return fmt.Errorf("error creating `vendor/` folder: %s", err) } if err := os.Mkdir("lib", os.ModePerm); err != nil { - return fmt.Errorf("Error creating `lib/` folder: %s", err) + return fmt.Errorf("error creating `lib/` folder: %s", err) } cfg := v1alpha1.New() @@ -79,7 +79,7 @@ func initCmd() *cli.Command { fmt.Println("Directory structure set up! Remember to configure the API endpoint:\n`tk env set environments/default --server=https://127.0.0.1:6443`") } if failed { - log.Println("Errors occured while initializing the project. Check the above logs for details.") + log.Println("Errors occurred while initializing the project. Check the above logs for details.") } return nil diff --git a/cmd/tk/main.go b/cmd/tk/main.go index bc135e802..af9280af1 100644 --- a/cmd/tk/main.go +++ b/cmd/tk/main.go @@ -19,7 +19,7 @@ func main() { rootCmd := &cli.Command{ Use: "tk", Short: "tanka <3 jsonnet", - Version: tanka.CURRENT_VERSION, + Version: tanka.CurrentVersion, } // workflow commands diff --git a/cmd/tk/prefix.go b/cmd/tk/prefix.go index 76fa2a70e..4a6ca28c8 100644 --- a/cmd/tk/prefix.go +++ b/cmd/tk/prefix.go @@ -24,16 +24,16 @@ func prefixCommands(prefix string) (cmds []*cli.Command) { Args: cli.ArgsAny(), } - ext_command := exec.Command(path) + extCommand := exec.Command(path) if ex, err := os.Executable(); err == nil { - ext_command.Env = append(os.Environ(), fmt.Sprintf("EXECUTABLE=%s", ex)) + extCommand.Env = append(os.Environ(), fmt.Sprintf("EXECUTABLE=%s", ex)) } - ext_command.Stdout = os.Stdout - ext_command.Stderr = os.Stderr + extCommand.Stdout = os.Stdout + extCommand.Stderr = os.Stderr cmd.Run = func(cmd *cli.Command, args []string) error { - ext_command.Args = append(ext_command.Args, args...) - return ext_command.Run() + extCommand.Args = append(extCommand.Args, args...) + return extCommand.Run() } cmds = append(cmds, cmd) } diff --git a/cmd/tk/tool.go b/cmd/tk/tool.go index a5ab070fc..bf0fb93fd 100644 --- a/cmd/tk/tool.go +++ b/cmd/tk/tool.go @@ -43,12 +43,12 @@ func jpathCmd() *cli.Command { entrypoint, err := jpath.Entrypoint(path) if err != nil { - return fmt.Errorf("Resolving JPATH: %s", err) + return fmt.Errorf("resolving JPATH: %s", err) } jsonnetpath, base, root, err := jpath.Resolve(entrypoint, false) if err != nil { - return fmt.Errorf("Resolving JPATH: %s", err) + return fmt.Errorf("resolving JPATH: %s", err) } if *debug { @@ -89,17 +89,17 @@ func importsCmd() *cli.Command { path, err := filepath.Abs(args[0]) if err != nil { - return fmt.Errorf("Loading environment: %s", err) + return fmt.Errorf("loading environment: %s", err) } deps, err := jsonnet.TransitiveImports(path) if err != nil { - return fmt.Errorf("Resolving imports: %s", err) + return fmt.Errorf("resolving imports: %s", err) } root, err := gitRoot() if err != nil { - return fmt.Errorf("Invoking git: %s", err) + return fmt.Errorf("invoking git: %s", err) } if modFiles != nil { for _, m := range modFiles { @@ -121,7 +121,7 @@ func importsCmd() *cli.Command { s, err := json.Marshal(deps) if err != nil { - return fmt.Errorf("Formatting: %s", err) + return fmt.Errorf("formatting: %s", err) } fmt.Println(string(s)) diff --git a/cmd/tk/toolCharts.go b/cmd/tk/toolCharts.go index 4b18892a6..58ea7f84e 100644 --- a/cmd/tk/toolCharts.go +++ b/cmd/tk/toolCharts.go @@ -126,7 +126,7 @@ func chartsInitCmd() *cli.Command { path := filepath.Join(wd, helm.Filename) if _, err := os.Stat(path); err == nil { - return fmt.Errorf("Chartfile at '%s' already exists. Aborting", path) + return fmt.Errorf("chartfile at '%s' already exists. Aborting", path) } if _, err := helm.InitChartfile(path); err != nil { diff --git a/pkg/helm/jsonnet.go b/pkg/helm/jsonnet.go index 3a03596e8..e0d7111e6 100644 --- a/pkg/helm/jsonnet.go +++ b/pkg/helm/jsonnet.go @@ -40,12 +40,12 @@ func NativeFunc(h Helm) *jsonnet.NativeFunction { Func: func(data []interface{}) (interface{}, error) { name, ok := data[0].(string) if !ok { - return nil, fmt.Errorf("First argument 'name' must be of 'string' type, got '%T' instead", data[0]) + return nil, fmt.Errorf("first argument 'name' must be of 'string' type, got '%T' instead", data[0]) } chartpath, ok := data[1].(string) if !ok { - return nil, fmt.Errorf("Second argument 'chart' must be of 'string' type, got '%T' instead", data[1]) + return nil, fmt.Errorf("second argument 'chart' must be of 'string' type, got '%T' instead", data[1]) } // TODO: validate data[2] actually follows the struct scheme @@ -90,7 +90,7 @@ func parseOpts(data interface{}) (*JsonnetOpts, error) { // Charts are only allowed at relative paths. Use conf.CalledFrom to find the callers directory if opts.CalledFrom == "" { - return nil, fmt.Errorf("helmTemplate: 'opts.calledFrom' is unset or empty.\nTanka needs this to find your charts. See https://tanka.dev/helm#optscalledfrom-unset\n") + return nil, fmt.Errorf("helmTemplate: 'opts.calledFrom' is unset or empty.\nTanka needs this to find your charts. See https://tanka.dev/helm#optscalledfrom-unset") } return &opts, nil diff --git a/pkg/helm/template.go b/pkg/helm/template.go index b5edfc9b3..7aa704395 100644 --- a/pkg/helm/template.go +++ b/pkg/helm/template.go @@ -12,13 +12,13 @@ import ( // Template expands a Helm Chart into a regular manifest.List using the `helm // template` command -func (h ExecHelm) Template(name, chart string, opts TemplateOpts) (manifest.List, error) { +func (e ExecHelm) Template(name, chart string, opts TemplateOpts) (manifest.List, error) { args := []string{name, chart, "--values", "-", // values from stdin } args = append(args, opts.Flags()...) - cmd := h.cmd("template", args...) + cmd := e.cmd("template", args...) var buf bytes.Buffer cmd.Stdout = &buf cmd.Stderr = os.Stderr diff --git a/pkg/jsonnet/eval.go b/pkg/jsonnet/eval.go index 55f8ca874..c9d47e00d 100644 --- a/pkg/jsonnet/eval.go +++ b/pkg/jsonnet/eval.go @@ -41,13 +41,13 @@ type Opts struct { // PathIsCached determines if a given path is matched by any of the configured cached path regexes // If no path regexes are defined, all paths are matched -func (opts Opts) PathIsCached(path string) bool { - for _, regex := range opts.CachePathRegexes { +func (o Opts) PathIsCached(path string) bool { + for _, regex := range o.CachePathRegexes { if regex.MatchString(path) { return true } } - return len(opts.CachePathRegexes) == 0 + return len(o.CachePathRegexes) == 0 } // Clone returns a deep copy of Opts diff --git a/pkg/jsonnet/imports.go b/pkg/jsonnet/imports.go index 1b8dc7fc4..1c1a59a5d 100644 --- a/pkg/jsonnet/imports.go +++ b/pkg/jsonnet/imports.go @@ -66,14 +66,12 @@ func TransitiveImports(dir string) ([]string, error) { paths := make([]string, 0, len(imports)+1) for k := range imports { - // Try to resolve any symlinks; use the original path as a last resort p, err := filepath.EvalSymlinks(k) if err != nil { return nil, errors.Wrap(err, "resolving symlinks") } paths = append(paths, p) - } paths = append(paths, entrypoint) diff --git a/pkg/jsonnet/jpath/errors.go b/pkg/jsonnet/jpath/errors.go index a75ee7b5d..94c569019 100644 --- a/pkg/jsonnet/jpath/errors.go +++ b/pkg/jsonnet/jpath/errors.go @@ -6,7 +6,7 @@ import ( ) // ErrorNoRoot means no rootDir was found in the parent directories -var ErrorNoRoot = errors.New(`Unable to identify the project root. +var ErrorNoRoot = errors.New(`unable to identify the project root. Tried to find 'tkrc.yaml' or 'jsonnetfile.json' in the parent directories. Please refer to https://tanka.dev/directory-structure for more information`) diff --git a/pkg/jsonnet/jpath/jpath.go b/pkg/jsonnet/jpath/jpath.go index 96ca678b4..e99f0bc2e 100644 --- a/pkg/jsonnet/jpath/jpath.go +++ b/pkg/jsonnet/jpath/jpath.go @@ -5,7 +5,7 @@ import ( "path/filepath" ) -const DEFAULT_ENTRYPOINT = "main.jsonnet" +const defaultEntrypoint = "main.jsonnet" // Resolve the given path and resolves the jPath around it. This means it: // - figures out the project root (the one with .jsonnetfile, vendor/ and lib/) @@ -49,11 +49,10 @@ func Filename(path string) (string, error) { } if fi.IsDir() { - return DEFAULT_ENTRYPOINT, nil + return defaultEntrypoint, nil } return filepath.Base(fi.Name()), nil - } // Entrypoint returns the absolute path of the environments entrypoint file (the diff --git a/pkg/jsonnet/jpath/jpath_test.go b/pkg/jsonnet/jpath/jpath_test.go index bb872f707..0c21d8ffd 100644 --- a/pkg/jsonnet/jpath/jpath_test.go +++ b/pkg/jsonnet/jpath/jpath_test.go @@ -2,7 +2,6 @@ package jpath_test import ( "encoding/json" - "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -12,7 +11,7 @@ import ( ) func TestResolvePrecedence(t *testing.T) { - s, err := jsonnet.EvaluateFile(filepath.Join("./testdata/precedence/environments/default/main.jsonnet"), jsonnet.Opts{}) + s, err := jsonnet.EvaluateFile("./testdata/precedence/environments/default/main.jsonnet", jsonnet.Opts{}) require.NoError(t, err) want := map[string]string{ diff --git a/pkg/jsonnet/lint.go b/pkg/jsonnet/lint.go index 75d0ce4a7..b3a36990f 100644 --- a/pkg/jsonnet/lint.go +++ b/pkg/jsonnet/lint.go @@ -28,7 +28,6 @@ type LintOpts struct { // Lint takes a list of files and directories, processes them and prints // out to stderr if there are linting warnings func Lint(fds []string, opts *LintOpts) error { - var paths []string for _, f := range fds { fs, err := FindFiles(f, opts.Excludes) diff --git a/pkg/kubernetes/apply.go b/pkg/kubernetes/apply.go index dc57f4b71..fff243710 100644 --- a/pkg/kubernetes/apply.go +++ b/pkg/kubernetes/apply.go @@ -27,7 +27,7 @@ func (k *Kubernetes) Orphaned(state manifest.List) (manifest.List, error) { if !k.Env.Spec.InjectLabels { return nil, fmt.Errorf(`spec.injectLabels is set to false in your spec.json. Tanka needs to add a label to your resources to reliably detect which were removed from Jsonnet. -See https://tanka.dev/garbage-collection for more details.`) +See https://tanka.dev/garbage-collection for more details`) } apiResources, err := k.ctl.Resources() @@ -95,8 +95,8 @@ func (k *Kubernetes) isKubectlCreated(manifest manifest.Manifest) bool { } // Check if created by server-side apply for _, manager := range manifest.Metadata().ManagedFields() { - manager_name := manager.(map[string]interface{})["manager"] - if manager_name == "tanka" || manager_name == "kubectl-client-side-apply" { + managerName := manager.(map[string]interface{})["manager"] + if managerName == "tanka" || managerName == "kubectl-client-side-apply" { return true } } diff --git a/pkg/kubernetes/client/apply_test.go b/pkg/kubernetes/client/apply_test.go index 193075b7e..3994e1e5d 100644 --- a/pkg/kubernetes/client/apply_test.go +++ b/pkg/kubernetes/client/apply_test.go @@ -73,7 +73,6 @@ func TestKubectl_applyCtl(t *testing.T) { if gotSet.HasAny(tt.unExpectedArgs...) { t.Errorf("Kubectl.applyCtl() = %v has (any) unExpectedArgs='%v'", got.Args, tt.unExpectedArgs) } - }) } } diff --git a/pkg/kubernetes/client/context.go b/pkg/kubernetes/client/context.go index 12068450f..d565c0d48 100644 --- a/pkg/kubernetes/client/context.go +++ b/pkg/kubernetes/client/context.go @@ -199,7 +199,7 @@ func tryMSISlice(v *objx.Value, what string) ([]map[string]interface{}, error) { } // ErrorNoMatch occurs when no item matched had the expected value -var ErrorNoMatch error = errors.New("no matches found") +var ErrorNoMatch = errors.New("no matches found") // find attempts to find an object in list whose prop equals expected. // If found, the value is unmarshalled to ptr, otherwise errNotFound is returned. diff --git a/pkg/kubernetes/client/delete.go b/pkg/kubernetes/client/delete.go index 7a827be3e..b6fa37d38 100644 --- a/pkg/kubernetes/client/delete.go +++ b/pkg/kubernetes/client/delete.go @@ -28,7 +28,6 @@ func (k Kubectl) deleteCtl(namespace, kind, name string, opts DeleteOpts) *exec. // Delete deletes the given Kubernetes resource from the cluster func (k Kubectl) Delete(namespace, kind, name string, opts DeleteOpts) error { - cmd := k.deleteCtl(namespace, kind, name, opts) var stdout bytes.Buffer diff --git a/pkg/kubernetes/client/delete_test.go b/pkg/kubernetes/client/delete_test.go index ddb9e5f70..f950e86b6 100644 --- a/pkg/kubernetes/client/delete_test.go +++ b/pkg/kubernetes/client/delete_test.go @@ -68,7 +68,6 @@ func TestKubectl_deleteCtl(t *testing.T) { if gotSet.HasAny(tt.unExpectedArgs...) { t.Errorf("Kubectl.applyCtl() = %v has (any) unExpectedArgs='%v'", got.Args, tt.unExpectedArgs) } - }) } } diff --git a/pkg/kubernetes/client/kubectl.go b/pkg/kubernetes/client/kubectl.go index e80e84a5e..399472caa 100644 --- a/pkg/kubernetes/client/kubectl.go +++ b/pkg/kubernetes/client/kubectl.go @@ -53,7 +53,6 @@ func NewFromNames(names []string) (*Kubectl, error) { } return &k, nil - } // Info returns known informational data about the client and its environment diff --git a/pkg/kubernetes/delete.go b/pkg/kubernetes/delete.go index cfdb3249a..2d405fbe1 100644 --- a/pkg/kubernetes/delete.go +++ b/pkg/kubernetes/delete.go @@ -12,9 +12,7 @@ func (k *Kubernetes) Delete(state manifest.List, opts DeleteOpts) error { // Sort and reverse the manifests to avoid cascading deletions process.Sort(state) for i := 0; i < len(state)/2; i++ { - t := state[i] - state[i] = state[len(state)-1-i] - state[len(state)-1-i] = t + state[i], state[len(state)-1-i] = state[len(state)-1-i], state[i] } for _, m := range state { diff --git a/pkg/kubernetes/diff.go b/pkg/kubernetes/diff.go index d57759b85..84401e0db 100644 --- a/pkg/kubernetes/diff.go +++ b/pkg/kubernetes/diff.go @@ -15,9 +15,9 @@ import ( func (k *Kubernetes) Diff(state manifest.List, opts DiffOpts) (*string, error) { // prevent https://github.com/kubernetes/kubernetes/issues/89762 until fixed if k.ctl.Info().ClientVersion.Equal(semver.MustParse("1.18.0")) { - return nil, fmt.Errorf(`You seem to be using kubectl 1.18.0, which contains an unfixed issue + return nil, fmt.Errorf(`you seem to be using kubectl 1.18.0, which contains an unfixed issue that makes 'kubectl diff' modify resources in your cluster. -Please upgrade kubectl to at least version 1.18.1.`) +Please upgrade kubectl to at least version 1.18.1`) } // required for separating diff --git a/pkg/kubernetes/manifest/manifest.go b/pkg/kubernetes/manifest/manifest.go index ea3a53065..629131c39 100644 --- a/pkg/kubernetes/manifest/manifest.go +++ b/pkg/kubernetes/manifest/manifest.go @@ -41,8 +41,8 @@ func (m Manifest) String() string { } var ( - ErrInvalidStr = fmt.Errorf("Missing or not of string type") - ErrInvalidMap = fmt.Errorf("Missing or not an object") + ErrInvalidStr = fmt.Errorf("missing or not of string type") + ErrInvalidMap = fmt.Errorf("missing or not an object") ) // Verify checks whether the manifest is correctly structured @@ -96,12 +96,12 @@ func verifyMSS(ptr interface{}) error { case map[string]interface{}: for k, v := range t { if _, ok := v.(string); !ok { - return fmt.Errorf("Contains non-string field '%s' of type '%T'", k, v) + return fmt.Errorf("contains non-string field '%s' of type '%T'", k, v) } } return nil default: - return fmt.Errorf("Must be object, but got '%T' instead", ptr) + return fmt.Errorf("must be object, but got '%T' instead", ptr) } } @@ -120,7 +120,7 @@ func (m Manifest) IsList() bool { // Items returns list items if the manifest is of List type func (m Manifest) Items() (List, error) { if !m.IsList() { - return nil, fmt.Errorf("Attempt to unwrap non-list object '%s' of kind '%s'", m.Metadata().Name(), m.Kind()) + return nil, fmt.Errorf("attempt to unwrap non-list object '%s' of kind '%s'", m.Metadata().Name(), m.Kind()) } // This is safe, IsList() asserts this @@ -129,7 +129,7 @@ func (m Manifest) Items() (List, error) { for _, i := range items { child, ok := i.(map[string]interface{}) if !ok { - return nil, fmt.Errorf("Unwrapped list item is not an object, but '%T'", child) + return nil, fmt.Errorf("unwrapped list item is not an object, but '%T'", child) } m := Manifest(child) @@ -312,7 +312,7 @@ func ListAsMap(list List, nameFormat string) (map[string]interface{}, error) { Funcs(sprig.TxtFuncMap()). Parse(nameFormat) if err != nil { - return nil, fmt.Errorf("Parsing name format: %w", err) + return nil, fmt.Errorf("parsing name format: %w", err) } out := make(map[string]interface{}) diff --git a/pkg/kubernetes/util/diff.go b/pkg/kubernetes/util/diff.go index fe0432452..1ffd5fc16 100644 --- a/pkg/kubernetes/util/diff.go +++ b/pkg/kubernetes/util/diff.go @@ -14,12 +14,12 @@ import ( // DiffName computes the filename for use with `DiffStr` func DiffName(m manifest.Manifest) string { - return strings.Replace(fmt.Sprintf("%s.%s.%s.%s", + return strings.ReplaceAll(fmt.Sprintf("%s.%s.%s.%s", m.APIVersion(), m.Kind(), m.Metadata().Namespace(), m.Metadata().Name(), - ), "/", "-", -1) + ), "/", "-") } // DiffStr computes the differences between the strings `is` and `should` using the diff --git a/pkg/kustomize/jsonnet.go b/pkg/kustomize/jsonnet.go index c857ec0b5..d6934d090 100644 --- a/pkg/kustomize/jsonnet.go +++ b/pkg/kustomize/jsonnet.go @@ -34,7 +34,7 @@ func NativeFunc(k Kustomize) *jsonnet.NativeFunction { Func: func(data []interface{}) (interface{}, error) { path, ok := data[0].(string) if !ok { - return nil, fmt.Errorf("Argument 'path' must be of 'string' type, got '%T' instead", data[0]) + return nil, fmt.Errorf("argument 'path' must be of 'string' type, got '%T' instead", data[0]) } // TODO: validate data[1] actually follows the struct scheme @@ -45,13 +45,13 @@ func NativeFunc(k Kustomize) *jsonnet.NativeFunction { // resolve the Kustomize path relative to the caller callerDir := filepath.Dir(opts.CalledFrom) - actual_path := filepath.Join(callerDir, path) - if _, err := os.Stat(actual_path); err != nil { - return nil, fmt.Errorf("kustomizeBuild: Failed to find kustomization at '%s': %s. See https://tanka.dev/kustomize#failed-to-find-kustomization", actual_path, err) + actualPath := filepath.Join(callerDir, path) + if _, err := os.Stat(actualPath); err != nil { + return nil, fmt.Errorf("kustomizeBuild: Failed to find kustomization at '%s': %s. See https://tanka.dev/kustomize#failed-to-find-kustomization", actualPath, err) } // render resources - list, err := k.Build(actual_path) + list, err := k.Build(actualPath) if err != nil { return nil, err } @@ -79,7 +79,7 @@ func parseOpts(data interface{}) (*JsonnetOpts, error) { // Kustomize paths are only allowed at relative paths. Use conf.CalledFrom to find the callers directory if opts.CalledFrom == "" { - return nil, fmt.Errorf("kustomizeBuild: 'opts.calledFrom' is unset or empty.\nTanka needs this to find your Kustomize. See https://tanka.dev/kustomize#optscalledfrom-unset\n") + return nil, fmt.Errorf("kustomizeBuild: 'opts.calledFrom' is unset or empty.\nTanka needs this to find your Kustomize. See https://tanka.dev/kustomize#optscalledfrom-unset") } return &opts, nil diff --git a/pkg/kustomize/kustomize.go b/pkg/kustomize/kustomize.go index 1d4c5bd5b..0811888c3 100644 --- a/pkg/kustomize/kustomize.go +++ b/pkg/kustomize/kustomize.go @@ -18,7 +18,7 @@ type Kustomize interface { type ExecKustomize struct{} // cmd returns a prepared exec.Cmd to use the `kustomize` binary -func (e ExecKustomize) cmd(action string, args ...string) *exec.Cmd { +func (k ExecKustomize) cmd(action string, args ...string) *exec.Cmd { argv := []string{action} argv = append(argv, args...) diff --git a/pkg/process/filter.go b/pkg/process/filter.go index bbbf276e0..8d3595926 100644 --- a/pkg/process/filter.go +++ b/pkg/process/filter.go @@ -32,13 +32,13 @@ type Matcher interface { MatchString(string) bool } -// Ignorer is like matcher, but for explicitely ignoring resources +// Ignorer is like matcher, but for explicitly ignoring resources type Ignorer interface { IgnoreString(string) bool } // Matchers is a collection of multiple expressions. -// A matcher may also implement Ignorer to explicitely ignore fields +// A matcher may also implement Ignorer to explicitly ignore fields type Matchers []Matcher // MatchString returns whether at least one expression (OR) matches the string diff --git a/pkg/tanka/export.go b/pkg/tanka/export.go index 40febb4b1..153c34e43 100644 --- a/pkg/tanka/export.go +++ b/pkg/tanka/export.go @@ -50,10 +50,10 @@ func ExportEnvironments(envs []*v1alpha1.Environment, to string, opts *ExportEnv // dir must be empty empty, err := dirEmpty(to) if err != nil { - return fmt.Errorf("Checking target dir: %s", err) + return fmt.Errorf("checking target dir: %s", err) } if !empty && !opts.Merge { - return fmt.Errorf("Output dir `%s` not empty. Pass --merge to ignore this", to) + return fmt.Errorf("output dir `%s` not empty. Pass --merge to ignore this", to) } // get all environments for paths @@ -90,7 +90,7 @@ func ExportEnvironments(envs []*v1alpha1.Environment, to string, opts *ExportEnv // create template manifestTemplate, err := createTemplate(opts.Format, menv) if err != nil { - return fmt.Errorf("Parsing format: %s", err) + return fmt.Errorf("parsing format: %s", err) } // write each to a file @@ -111,7 +111,7 @@ func ExportEnvironments(envs []*v1alpha1.Environment, to string, opts *ExportEnv if exists, err := fileExists(path); err != nil { return err } else if exists { - return fmt.Errorf("File '%s' already exists. Aborting", path) + return fmt.Errorf("file '%s' already exists. Aborting", path) } // Write manifest @@ -213,9 +213,9 @@ func applyTemplate(template *template.Template, m manifest.Manifest) (path strin } // Replace all os.path separators in string in order to not accidentally create subfolders - path = strings.Replace(buf.String(), string(os.PathSeparator), "-", -1) + path = strings.ReplaceAll(buf.String(), string(os.PathSeparator), "-") // Replace the BEL character inserted with a path separator again in order to create a subfolder - path = strings.Replace(path, BelRune, string(os.PathSeparator), -1) + path = strings.ReplaceAll(path, BelRune, string(os.PathSeparator)) return path, nil } diff --git a/pkg/tanka/load.go b/pkg/tanka/load.go index ec033414b..fa393b5ab 100644 --- a/pkg/tanka/load.go +++ b/pkg/tanka/load.go @@ -169,7 +169,7 @@ func (l LoadResult) Connect() (*kubernetes.Kubernetes, error) { s += " * spec.namespace: Default namespace missing" } if s != "" { - return nil, fmt.Errorf("Your Environment's spec.json seems incomplete:\n%s\n\nPlease see https://tanka.dev/config for reference", s) + return nil, fmt.Errorf("your Environment's spec.json seems incomplete:\n%s\n\nPlease see https://tanka.dev/config for reference", s) } // connect client diff --git a/pkg/tanka/tanka.go b/pkg/tanka/tanka.go index d7f91a088..637410a74 100644 --- a/pkg/tanka/tanka.go +++ b/pkg/tanka/tanka.go @@ -26,33 +26,33 @@ type Opts struct { Name string } -// DEFAULT_DEV_VERSION is the placeholder version used when no actual semver is +// defaultDevVersion is the placeholder version used when no actual semver is // provided using ldflags -const DEFAULT_DEV_VERSION = "dev" +const defaultDevVersion = "dev" -// CURRENT_VERSION is the current version of the running Tanka code -var CURRENT_VERSION = DEFAULT_DEV_VERSION +// CurrentVersion is the current version of the running Tanka code +var CurrentVersion = defaultDevVersion func checkVersion(constraint string) error { if constraint == "" { return nil } - if CURRENT_VERSION == DEFAULT_DEV_VERSION { + if CurrentVersion == defaultDevVersion { return nil } c, err := semver.NewConstraint(constraint) if err != nil { - return fmt.Errorf("Parsing version constraint: '%w'. Please check 'spec.expectVersions.tanka'", err) + return fmt.Errorf("parsing version constraint: '%w'. Please check 'spec.expectVersions.tanka'", err) } - v, err := semver.NewVersion(CURRENT_VERSION) + v, err := semver.NewVersion(CurrentVersion) if err != nil { - return fmt.Errorf("'%s' is not a valid semantic version: '%w'.\nThis likely means your build of Tanka is broken, as this is a compile-time value. When in doubt, please raise an issue", CURRENT_VERSION, err) + return fmt.Errorf("'%s' is not a valid semantic version: '%w'.\nThis likely means your build of Tanka is broken, as this is a compile-time value. When in doubt, please raise an issue", CurrentVersion, err) } if !c.Check(v) { - return fmt.Errorf("Current version '%s' does not satisfy the version required by the environment: '%s'. You likely need to use another version of Tanka", CURRENT_VERSION, constraint) + return fmt.Errorf("current version '%s' does not satisfy the version required by the environment: '%s'. You likely need to use another version of Tanka", CurrentVersion, constraint) } return nil diff --git a/pkg/tanka/workflow.go b/pkg/tanka/workflow.go index 84130f573..5bf089ec2 100644 --- a/pkg/tanka/workflow.go +++ b/pkg/tanka/workflow.go @@ -22,6 +22,9 @@ const ( AutoApproveAlways AutoApproveSetting = "always" // AutoApproveNoChanges enables auto-approval if there were no changes found in the diff AutoApproveNoChanges AutoApproveSetting = "if-no-changes" + + ApplyStrategyServer = "server" + ApplyStrategyClient = "client" ) type ApplyBaseOpts struct { @@ -75,16 +78,16 @@ func Apply(baseDir string, opts ApplyOpts) error { if l.Env.Spec.ApplyStrategy != "" { opts.ApplyStrategy = l.Env.Spec.ApplyStrategy } else { - opts.ApplyStrategy = "client" + opts.ApplyStrategy = ApplyStrategyClient } } - if opts.ApplyStrategy != "client" && opts.ApplyStrategy != "server" { + if opts.ApplyStrategy != ApplyStrategyClient && opts.ApplyStrategy != ApplyStrategyServer { return ErrorApplyStrategyUnknown{Requested: opts.ApplyStrategy} } // Default to `server` diff in server apply mode - if opts.ApplyStrategy == "server" && opts.DiffStrategy == "" && l.Env.Spec.DiffStrategy == "" { - l.Env.Spec.DiffStrategy = "server" + if opts.ApplyStrategy == ApplyStrategyServer && opts.DiffStrategy == "" && l.Env.Spec.DiffStrategy == "" { + l.Env.Spec.DiffStrategy = ApplyStrategyServer } kube, err := l.Connect()