From 5464b005e8f6bedd644c95d67e8c09eee3c7352f Mon Sep 17 00:00:00 2001 From: Johan Fylling Date: Wed, 19 Jun 2024 15:13:43 +0200 Subject: [PATCH] Bumping golangci-lint to v1.59.1 (#6817) Signed-off-by: Johan Fylling --- Makefile | 2 +- ast/annotations.go | 3 +- ast/check_test.go | 4 +- ast/compile.go | 2 +- ast/env.go | 4 +- ast/index.go | 2 +- ast/map_test.go | 2 +- ast/parser.go | 7 +-- ast/term.go | 8 +-- ast/term_test.go | 2 +- ast/visit.go | 12 ++--- bundle/bundle.go | 6 +-- bundle/file.go | 2 +- bundle/file_test.go | 2 +- bundle/sign_test.go | 2 +- bundle/verify_test.go | 2 +- cmd/bench_test.go | 8 +-- cmd/build.go | 2 +- cmd/capabilities.go | 2 +- cmd/deps.go | 2 +- cmd/eval.go | 2 +- cmd/eval_test.go | 2 +- cmd/exec.go | 4 +- cmd/fmt.go | 4 +- cmd/fmt_test.go | 2 +- cmd/internal/env/env_test.go | 8 +-- cmd/oracle.go | 4 +- cmd/refactor.go | 2 +- cmd/run.go | 8 +-- cmd/sign.go | 2 +- cmd/sign_test.go | 2 +- cmd/test.go | 2 +- cmd/version.go | 4 +- cmd/version_test.go | 2 +- format/format.go | 10 +++- internal/bundle/utils.go | 7 +-- internal/compiler/wasm/wasm.go | 2 +- internal/edittree/bitvector/bitvector_test.go | 52 +++++++++---------- internal/gojsonschema/jsonschema_test.go | 6 +-- internal/gojsonschema/schema.go | 2 +- internal/gojsonschema/validation.go | 8 +-- .../rules/fragments_on_composite_types.go | 2 +- .../validator/rules/known_argument_names.go | 4 +- .../validator/rules/known_directives.go | 2 +- .../validator/rules/known_fragment_names.go | 2 +- .../validator/rules/no_unused_fragments.go | 4 +- .../validator/rules/no_unused_variables.go | 2 +- .../rules/provided_required_arguments.go | 4 +- .../validator/rules/unique_argument_names.go | 4 +- .../rules/unique_directives_per_location.go | 2 +- .../validator/rules/unique_fragment_names.go | 2 +- .../rules/unique_input_field_names.go | 2 +- .../validator/rules/unique_operation_names.go | 2 +- .../validator/rules/unique_variable_names.go | 2 +- .../validator/rules/values_of_correct_type.go | 2 +- .../rules/variables_are_input_types.go | 2 +- internal/oracle/oracle.go | 2 +- internal/planner/planner.go | 2 +- internal/providers/aws/ecr_test.go | 2 +- internal/providers/aws/kms_test.go | 2 +- internal/providers/aws/signing_v4a.go | 2 +- internal/providers/aws/v4/util.go | 9 +--- internal/report/report_test.go | 4 +- internal/wasm/encoding/reader.go | 4 +- internal/wasm/sdk/internal/wasm/pool.go | 2 +- internal/wasm/sdk/internal/wasm/vm.go | 6 +-- internal/wasm/sdk/opa/loader/file/loader.go | 6 +-- .../wasm/sdk/opa/loader/file/loader_test.go | 2 +- ir/pretty.go | 4 +- loader/loader.go | 6 +-- plugins/bundle/plugin_test.go | 52 +++++++++---------- plugins/discovery/config.go | 8 +-- plugins/discovery/discovery_test.go | 2 +- plugins/logs/mask_test.go | 4 +- plugins/logs/plugin.go | 2 +- plugins/plugins.go | 7 ++- plugins/plugins_test.go | 2 +- plugins/rest/auth.go | 2 +- plugins/rest/gcp_test.go | 2 +- plugins/rest/rest_test.go | 12 ++--- plugins/status/plugin.go | 2 +- plugins/status/plugin_test.go | 2 +- rego/rego.go | 10 ++-- rego/rego_test.go | 4 +- repl/repl.go | 9 ++-- runtime/plugins_test.go | 8 +-- runtime/runtime_test.go | 4 +- server/authorizer/authorizer_test.go | 4 +- server/certs.go | 4 +- server/handlers/compress_test.go | 2 +- server/server.go | 4 +- server/server_test.go | 14 ++--- server/writer/writer.go | 2 +- storage/disk/disk.go | 8 +-- storage/disk/disk_test.go | 6 +-- storage/inmem/example_test.go | 2 + storage/inmem/inmem_test.go | 28 +++++----- test/authz/testing.go | 2 +- test/e2e/certrefresh/certrefresh_test.go | 10 ++-- test/e2e/http/http_test.go | 2 +- test/e2e/metrics/metrics_test.go | 2 +- test/scheduler/scheduler_test.go | 2 +- test/wasm/cmd/wasm-rego-testgen/main.go | 2 +- tester/runner.go | 2 +- topdown/bindings.go | 2 +- topdown/copypropagation/copypropagation.go | 6 +-- topdown/eval.go | 10 ++-- topdown/example_test.go | 2 + topdown/http.go | 2 +- topdown/http_test.go | 14 ++--- topdown/net_test.go | 2 +- topdown/parse_bytes.go | 2 +- topdown/providers.go | 2 +- topdown/reachable.go | 4 +- topdown/semver.go | 4 +- topdown/strings.go | 8 +-- topdown/tokens.go | 19 ++++--- topdown/tokens_test.go | 2 +- topdown/topdown_test.go | 6 +-- types/decode.go | 6 +-- types/types.go | 8 +-- 121 files changed, 316 insertions(+), 313 deletions(-) diff --git a/Makefile b/Makefile index 6be0c37ae9..b3ff50c1db 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ ifeq ($(WASM_ENABLED),1) GO_TAGS = -tags=opa_wasm endif -GOLANGCI_LINT_VERSION := v1.51.0 +GOLANGCI_LINT_VERSION := v1.59.1 YAML_LINT_VERSION := 0.29.0 YAML_LINT_FORMAT ?= auto diff --git a/ast/annotations.go b/ast/annotations.go index f7a5c78f76..9663b0cc67 100644 --- a/ast/annotations.go +++ b/ast/annotations.go @@ -627,9 +627,8 @@ func (a *AuthorAnnotation) String() string { return a.Name } else if len(a.Name) == 0 { return fmt.Sprintf("<%s>", a.Email) - } else { - return fmt.Sprintf("%s <%s>", a.Name, a.Email) } + return fmt.Sprintf("%s <%s>", a.Name, a.Email) } // Copy returns a deep copy of rr. diff --git a/ast/check_test.go b/ast/check_test.go index 8127dd1680..bc84952d37 100644 --- a/ast/check_test.go +++ b/ast/check_test.go @@ -2429,7 +2429,7 @@ func TestRemoteSchema(t *testing.T) { schema := `{"type": "boolean"}` schemaCalled := false - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { schemaCalled = true w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(schema)) @@ -2477,7 +2477,7 @@ func TestRemoteSchemaHostNotAllowed(t *testing.T) { schema := `{"type": "boolean"}` schemaCalled := false - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { schemaCalled = true w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(schema)) diff --git a/ast/compile.go b/ast/compile.go index 4e229c8b04..3010bfe8ba 100644 --- a/ast/compile.go +++ b/ast/compile.go @@ -4194,7 +4194,7 @@ func resolveRefsInRule(globals map[Var]*usedRef, rule *Rule) error { // Object keys cannot be pattern matched so only walk values. case *object: - x.Foreach(func(k, v *Term) { + x.Foreach(func(_, v *Term) { vis.Walk(v) }) diff --git a/ast/env.go b/ast/env.go index 784a34c047..c767aafefb 100644 --- a/ast/env.go +++ b/ast/env.go @@ -472,7 +472,7 @@ func insertIntoObject(o *types.Object, path Ref, tpe types.Type, env *TypeEnv) ( func (n *typeTreeNode) Leafs() map[*Ref]types.Type { leafs := map[*Ref]types.Type{} - n.children.Iter(func(k, v util.T) bool { + n.children.Iter(func(_, v util.T) bool { collectLeafs(v.(*typeTreeNode), nil, leafs) return false }) @@ -485,7 +485,7 @@ func collectLeafs(n *typeTreeNode, path Ref, leafs map[*Ref]types.Type) { leafs[&nPath] = n.Value() return } - n.children.Iter(func(k, v util.T) bool { + n.children.Iter(func(_, v util.T) bool { collectLeafs(v.(*typeTreeNode), nPath, leafs) return false }) diff --git a/ast/index.go b/ast/index.go index e14bb72eef..8cad71f1ec 100644 --- a/ast/index.go +++ b/ast/index.go @@ -164,7 +164,7 @@ func (i *baseDocEqIndex) Lookup(resolver ValueResolver) (*IndexResult, error) { return result, nil } -func (i *baseDocEqIndex) AllRules(resolver ValueResolver) (*IndexResult, error) { +func (i *baseDocEqIndex) AllRules(_ ValueResolver) (*IndexResult, error) { tr := newTrieTraversalResult() // Walk over the rule trie and accumulate _all_ rules diff --git a/ast/map_test.go b/ast/map_test.go index 545577e158..08f0fd2fb4 100644 --- a/ast/map_test.go +++ b/ast/map_test.go @@ -27,7 +27,7 @@ func TestValueMapIter(t *testing.T) { a.Put(String("y"), String("bar")) a.Put(String("z"), String("baz")) values := []string{} - a.Iter(func(k, v Value) bool { + a.Iter(func(_, v Value) bool { values = append(values, string(v.(String))) return false }) diff --git a/ast/parser.go b/ast/parser.go index c323e67495..15001ad403 100644 --- a/ast/parser.go +++ b/ast/parser.go @@ -2430,10 +2430,11 @@ func augmentYamlError(err error, comments []*Comment) error { return err } -func unwrapPair(pair map[string]interface{}) (k string, v interface{}) { - for k, v = range pair { +func unwrapPair(pair map[string]interface{}) (string, interface{}) { + for k, v := range pair { + return k, v } - return + return "", nil } var errInvalidSchemaRef = fmt.Errorf("invalid schema reference") diff --git a/ast/term.go b/ast/term.go index bb39c18e3b..4664bc5dac 100644 --- a/ast/term.go +++ b/ast/term.go @@ -2633,7 +2633,7 @@ func filterObject(o Value, filter Value) (Value, error) { other = v } - err := iterObj.Iter(func(key *Term, value *Term) error { + err := iterObj.Iter(func(key *Term, _ *Term) error { if other.Get(key) != nil { filteredValue, err := filterObject(v.Get(key).Value, filteredObj.Get(key).Value) if err != nil { @@ -3091,12 +3091,12 @@ func unmarshalTermSlice(s []interface{}) ([]*Term, error) { buf := []*Term{} for _, x := range s { if m, ok := x.(map[string]interface{}); ok { - if t, err := unmarshalTerm(m); err == nil { + t, err := unmarshalTerm(m) + if err == nil { buf = append(buf, t) continue - } else { - return nil, err } + return nil, err } return nil, fmt.Errorf("ast: unable to unmarshal term") } diff --git a/ast/term_test.go b/ast/term_test.go index 130f14c59d..6cec4a2b5f 100644 --- a/ast/term_test.go +++ b/ast/term_test.go @@ -927,7 +927,7 @@ func TestObjectConcurrentReads(t *testing.T) { go func() { defer wg.Done() var retrieved []*Term - o.Foreach(func(k, v *Term) { + o.Foreach(func(k, _ *Term) { retrieved = append(retrieved, k) }) // Check for sortedness of retrieved results. diff --git a/ast/visit.go b/ast/visit.go index 7b0d3b08e7..d83c31149e 100644 --- a/ast/visit.go +++ b/ast/visit.go @@ -352,12 +352,12 @@ func (vis *GenericVisitor) Walk(x interface{}) { vis.Walk(x[i]) } case *object: - x.Foreach(func(k, v *Term) { + x.Foreach(func(k, _ *Term) { vis.Walk(k) vis.Walk(x.Get(k)) }) case Object: - x.Foreach(func(k, v *Term) { + x.Foreach(func(k, _ *Term) { vis.Walk(k) vis.Walk(x.Get(k)) }) @@ -492,12 +492,12 @@ func (vis *BeforeAfterVisitor) Walk(x interface{}) { vis.Walk(x[i]) } case *object: - x.Foreach(func(k, v *Term) { + x.Foreach(func(k, _ *Term) { vis.Walk(k) vis.Walk(x.Get(k)) }) case Object: - x.Foreach(func(k, v *Term) { + x.Foreach(func(k, _ *Term) { vis.Walk(k) vis.Walk(x.Get(k)) }) @@ -579,7 +579,7 @@ func (vis *VarVisitor) Vars() VarSet { func (vis *VarVisitor) visit(v interface{}) bool { if vis.params.SkipObjectKeys { if o, ok := v.(Object); ok { - o.Foreach(func(k, v *Term) { + o.Foreach(func(_, v *Term) { vis.Walk(v) }) return true @@ -741,7 +741,7 @@ func (vis *VarVisitor) Walk(x interface{}) { vis.Walk(x[i]) } case *object: - x.Foreach(func(k, v *Term) { + x.Foreach(func(k, _ *Term) { vis.Walk(k) vis.Walk(x.Get(k)) }) diff --git a/bundle/bundle.go b/bundle/bundle.go index 3b9eba115e..a68c3c7125 100644 --- a/bundle/bundle.go +++ b/bundle/bundle.go @@ -1191,7 +1191,8 @@ func (b *Bundle) SetRegoVersion(v ast.RegoVersion) { // If there is no defined version for the given path, the default version def is returned. // If the version does not correspond to ast.RegoV0 or ast.RegoV1, an error is returned. func (b *Bundle) RegoVersionForFile(path string, def ast.RegoVersion) (ast.RegoVersion, error) { - if version, err := b.Manifest.numericRegoVersionForFile(path); err != nil { + version, err := b.Manifest.numericRegoVersionForFile(path) + if err != nil { return def, err } else if version == nil { return def, nil @@ -1199,9 +1200,8 @@ func (b *Bundle) RegoVersionForFile(path string, def ast.RegoVersion) (ast.RegoV return ast.RegoV0, nil } else if *version == 1 { return ast.RegoV1, nil - } else { - return def, fmt.Errorf("unknown bundle rego-version %d for file '%s'", *version, path) } + return def, fmt.Errorf("unknown bundle rego-version %d for file '%s'", *version, path) } func (m *Manifest) numericRegoVersionForFile(path string) (*int, error) { diff --git a/bundle/file.go b/bundle/file.go index 2b9ba14177..c2c5a6b849 100644 --- a/bundle/file.go +++ b/bundle/file.go @@ -211,7 +211,7 @@ func (d *dirLoader) NextFile() (*Descriptor, error) { // build a list of all files we will iterate over and read, but only one time if d.files == nil { d.files = []string{} - err := filepath.Walk(d.root, func(path string, info os.FileInfo, err error) error { + err := filepath.Walk(d.root, func(path string, info os.FileInfo, _ error) error { if info != nil && info.Mode().IsRegular() { if d.filter != nil && d.filter(filepath.ToSlash(path), info, getdepth(path, false)) { return nil diff --git a/bundle/file_test.go b/bundle/file_test.go index d44db53745..252aea7b44 100644 --- a/bundle/file_test.go +++ b/bundle/file_test.go @@ -539,7 +539,7 @@ func TestNewDirectoryLoaderNormalizedRoot(t *testing.T) { } func getFilter(pattern string, minDepth int) filter.LoaderFilter { - return func(abspath string, info os.FileInfo, depth int) bool { + return func(_ string, info os.FileInfo, depth int) bool { match, _ := filepath.Match(pattern, info.Name()) return match && depth >= minDepth } diff --git a/bundle/sign_test.go b/bundle/sign_test.go index 5a8b93d6b7..c579716c31 100644 --- a/bundle/sign_test.go +++ b/bundle/sign_test.go @@ -193,7 +193,7 @@ func TestGeneratePayload(t *testing.T) { type CustomSigner struct{} -func (*CustomSigner) GenerateSignedToken(files []FileInfo, sc *SigningConfig, keyID string) (string, error) { +func (*CustomSigner) GenerateSignedToken(_ []FileInfo, _ *SigningConfig, _ string) (string, error) { return "", nil } diff --git a/bundle/verify_test.go b/bundle/verify_test.go index fb4cd02c56..3d5de0a6de 100644 --- a/bundle/verify_test.go +++ b/bundle/verify_test.go @@ -288,7 +288,7 @@ func TestVerifyBundleFile(t *testing.T) { type CustomVerifier struct{} -func (*CustomVerifier) VerifyBundleSignature(sc SignaturesConfig, bvc *VerificationConfig) (map[string]FileInfo, error) { +func (*CustomVerifier) VerifyBundleSignature(_ SignaturesConfig, _ *VerificationConfig) (map[string]FileInfo, error) { return map[string]FileInfo{}, nil } diff --git a/cmd/bench_test.go b/cmd/bench_test.go index 2bb4dd1c37..bb347964ab 100644 --- a/cmd/bench_test.go +++ b/cmd/bench_test.go @@ -382,7 +382,7 @@ func TestBenchMainErrRunningBenchmark(t *testing.T) { var buf bytes.Buffer mockRunner := &mockBenchRunner{} - mockRunner.onRun = func(ctx context.Context, ectx *evalContext, params benchmarkCommandParams, f func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { + mockRunner.onRun = func(_ context.Context, _ *evalContext, _ benchmarkCommandParams, _ func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { return testing.BenchmarkResult{}, errors.New("error error error") } @@ -405,7 +405,7 @@ func TestBenchMainWithCount(t *testing.T) { params.count = 25 actualCount := 0 - mockRunner.onRun = func(ctx context.Context, ectx *evalContext, params benchmarkCommandParams, f func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { + mockRunner.onRun = func(_ context.Context, _ *evalContext, _ benchmarkCommandParams, _ func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { actualCount++ return testing.BenchmarkResult{}, nil } @@ -433,7 +433,7 @@ func TestBenchMainWithNegativeCount(t *testing.T) { params.count = -1 actualCount := 0 - mockRunner.onRun = func(ctx context.Context, ectx *evalContext, params benchmarkCommandParams, f func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { + mockRunner.onRun = func(_ context.Context, _ *evalContext, _ benchmarkCommandParams, _ func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { actualCount++ return testing.BenchmarkResult{}, nil } @@ -458,7 +458,7 @@ func validateBenchMainPrep(t *testing.T, args []string, params benchmarkCommandP mockRunner := &mockBenchRunner{} - mockRunner.onRun = func(ctx context.Context, ectx *evalContext, params benchmarkCommandParams, f func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { + mockRunner.onRun = func(ctx context.Context, ectx *evalContext, _ benchmarkCommandParams, _ func(context.Context, ...rego.EvalOption) error) (testing.BenchmarkResult, error) { // cheat and use the ectx to evalute the query to ensure the input setup on it was valid r := rego.New(ectx.regoArgs...) diff --git a/cmd/build.go b/cmd/build.go index 824f1b8f62..fffb8f2a37 100644 --- a/cmd/build.go +++ b/cmd/build.go @@ -222,7 +222,7 @@ against OPA v0.22.0: } return env.CmdFlags.CheckEnvironmentVariables(Cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { if err := dobuild(buildParams, args); err != nil { fmt.Println("error:", err) os.Exit(1) diff --git a/cmd/capabilities.go b/cmd/capabilities.go index bf2f2589be..4fdc3685a9 100644 --- a/cmd/capabilities.go +++ b/cmd/capabilities.go @@ -70,7 +70,7 @@ Print the capabilities of a capabilities file } `, - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(cmd *cobra.Command, _ []string) error { return env.CmdFlags.CheckEnvironmentVariables(cmd) }, RunE: func(*cobra.Command, []string) error { diff --git a/cmd/deps.go b/cmd/deps.go index 1ef22a180c..823758faa5 100644 --- a/cmd/deps.go +++ b/cmd/deps.go @@ -96,7 +96,7 @@ data.policy.is_admin. } return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { if err := deps(args, params, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) diff --git a/cmd/eval.go b/cmd/eval.go index 4dba949d99..21569b0d5d 100644 --- a/cmd/eval.go +++ b/cmd/eval.go @@ -276,7 +276,7 @@ access. } return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { defined, err := eval(args, params, os.Stdout) if err != nil { diff --git a/cmd/eval_test.go b/cmd/eval_test.go index 06646f64c2..7292817797 100755 --- a/cmd/eval_test.go +++ b/cmd/eval_test.go @@ -1659,7 +1659,7 @@ func TestPolicyWithStrictFlag(t *testing.T) { "test.rego": tc.policy, } - test.WithTempFS(files, func(path string) { + test.WithTempFS(files, func(_ string) { params := newEvalCommandParams() params.strict = true diff --git a/cmd/exec.go b/cmd/exec.go index f8fad7514b..a39f3030bf 100644 --- a/cmd/exec.go +++ b/cmd/exec.go @@ -53,10 +53,10 @@ specifying the --decision argument and pointing at a specific policy decision, e.g., opa exec --decision /foo/bar/baz ...`, Args: cobra.MinimumNArgs(1), - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(cmd *cobra.Command, _ []string) error { return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { params.Paths = args params.BundlePaths = bundlePaths.v if err := runExec(params); err != nil { diff --git a/cmd/fmt.go b/cmd/fmt.go index 48616102da..df0622aadb 100644 --- a/cmd/fmt.go +++ b/cmd/fmt.go @@ -64,10 +64,10 @@ to stdout from the 'fmt' command. If the '--fail' option is supplied, the 'fmt' command will return a non zero exit code if a file would be reformatted.`, - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(cmd *cobra.Command, _ []string) error { return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { os.Exit(opaFmt(args)) }, } diff --git a/cmd/fmt_test.go b/cmd/fmt_test.go index f36405aa8f..f772546c9f 100644 --- a/cmd/fmt_test.go +++ b/cmd/fmt_test.go @@ -58,7 +58,7 @@ type errorWriter struct { ErrMsg string } -func (ew errorWriter) Write(p []byte) (n int, err error) { +func (ew errorWriter) Write(_ []byte) (n int, err error) { return 0, fmt.Errorf(ew.ErrMsg) } diff --git a/cmd/internal/env/env_test.go b/cmd/internal/env/env_test.go index 2a637d8657..fd4b63c56a 100644 --- a/cmd/internal/env/env_test.go +++ b/cmd/internal/env/env_test.go @@ -20,10 +20,10 @@ func mockRootCmd(writer io.Writer) *cobra.Command { Use: "opa [opts]", Short: "test root command", Long: `test root command`, - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(cmd *cobra.Command, _ []string) error { return CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { fmt.Fprintf(writer, "%v; %v; %v", rootArgs.IntFlag, rootArgs.StrFlag, rootArgs.BoolFlag) }, } @@ -43,10 +43,10 @@ func mockChildCmd(writer io.Writer) *cobra.Command { Use: "child [opts]", Short: "test child command", Long: `test child command`, - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(cmd *cobra.Command, _ []string) error { return CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { fmt.Fprintf(writer, "%v; %v; %v", rootArgs.IntFlag, rootArgs.StrFlag, rootArgs.BoolFlag) }, } diff --git a/cmd/oracle.go b/cmd/oracle.go index 5ffea13e5d..d688aa0b68 100644 --- a/cmd/oracle.go +++ b/cmd/oracle.go @@ -82,7 +82,7 @@ by the input location.`, } return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { if err := dofindDefinition(findDefinitionParams, os.Stdin, os.Stdout, args); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) @@ -111,7 +111,7 @@ func dofindDefinition(params findDefinitionParams, stdin io.Reader, stdout io.Wr } b, err = loader.NewFileLoader(). WithSkipBundleVerification(true). - WithFilter(func(abspath string, info os.FileInfo, depth int) bool { + WithFilter(func(_ string, info os.FileInfo, _ int) bool { // While directories may contain other things of interest for OPA (json, yaml..), // only .rego will work reliably for the purpose of finding definitions return strings.HasPrefix(info.Name(), ".rego") diff --git a/cmd/refactor.go b/cmd/refactor.go index 0786a3e5b7..4cad94e9cc 100644 --- a/cmd/refactor.go +++ b/cmd/refactor.go @@ -76,7 +76,7 @@ The 'move' command outputs the below policy to stdout with the package name rewr } return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { if err := doMove(moveCommandParams, args, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) diff --git a/cmd/run.go b/cmd/run.go index 18291e0265..28ac319e73 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -195,7 +195,7 @@ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1 See https://godoc.org/crypto/tls#pkg-constants for more information. `, - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(cmd *cobra.Command, _ []string) error { return env.CmdFlags.CheckEnvironmentVariables(cmd) }, Run: func(cmd *cobra.Command, args []string) { @@ -391,7 +391,7 @@ func verifyCipherSuites(cipherSuites []string) (*[]uint16, error) { cipherSuitesMap[c.Name] = c } - cipherSuitesIds := []uint16{} + cipherSuitesIDs := []uint16{} for _, c := range cipherSuites { val, ok := cipherSuitesMap[c] if !ok { @@ -405,10 +405,10 @@ func verifyCipherSuites(cipherSuites []string) (*[]uint16, error) { } } - cipherSuitesIds = append(cipherSuitesIds, val.ID) + cipherSuitesIDs = append(cipherSuitesIDs, val.ID) } - return &cipherSuitesIds, nil + return &cipherSuitesIDs, nil } func historyPath() string { diff --git a/cmd/sign.go b/cmd/sign.go index a59e57658d..1580b13ad3 100644 --- a/cmd/sign.go +++ b/cmd/sign.go @@ -138,7 +138,7 @@ https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { if err := doSign(args, cmdParams); err != nil { fmt.Println("error:", err) os.Exit(1) diff --git a/cmd/sign_test.go b/cmd/sign_test.go index f70e8decbf..3f8809f81c 100644 --- a/cmd/sign_test.go +++ b/cmd/sign_test.go @@ -96,7 +96,7 @@ func TestBundleSignVerification(t *testing.T) { // create gzipped tarball var filesInBundle [][2]string - err = filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error { + err = filepath.Walk(rootDir, func(path string, info os.FileInfo, _ error) error { if !info.IsDir() { bs, err := os.ReadFile(path) if err != nil { diff --git a/cmd/test.go b/cmd/test.go index 09fa2092ce..b50176f3e8 100644 --- a/cmd/test.go +++ b/cmd/test.go @@ -520,7 +520,7 @@ recommended as some updates might cause them to be dropped by OPA. return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { exitCode, _ := opaTest(args, testParams) os.Exit(exitCode) }, diff --git a/cmd/version.go b/cmd/version.go index 2501ad1173..3d3b0de4ab 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -26,10 +26,10 @@ func init() { Use: "version", Short: "Print the version of OPA", Long: "Show version and build information for OPA.", - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(cmd *cobra.Command, _ []string) error { return env.CmdFlags.CheckEnvironmentVariables(cmd) }, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { generateCmdOutput(os.Stdout, check) }, } diff --git a/cmd/version_test.go b/cmd/version_test.go index 5fbb8ef9a0..830c9af2b5 100644 --- a/cmd/version_test.go +++ b/cmd/version_test.go @@ -101,7 +101,7 @@ func getTestServer(update interface{}, statusCode int) (baseURL string, teardown mux := http.NewServeMux() ts := httptest.NewServer(mux) - mux.HandleFunc("/v1/version", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("/v1/version", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(statusCode) bs, _ := json.Marshal(update) w.Header().Set("Content-Type", "application/json") diff --git a/format/format.go b/format/format.go index 6d327296dd..02b6f73d82 100644 --- a/format/format.go +++ b/format/format.go @@ -1340,7 +1340,10 @@ func closingLoc(skipOpen, skipClose, open, close byte, loc *ast.Location) *ast.L i, offset = skipPast(skipOpen, skipClose, loc) } - for ; i < len(loc.Text) && loc.Text[i] != open; i++ { + for ; i < len(loc.Text); i++ { + if loc.Text[i] == open { + break + } } if i >= len(loc.Text) { @@ -1369,7 +1372,10 @@ func closingLoc(skipOpen, skipClose, open, close byte, loc *ast.Location) *ast.L func skipPast(open, close byte, loc *ast.Location) (int, int) { i := 0 - for ; i < len(loc.Text) && loc.Text[i] != open; i++ { + for ; i < len(loc.Text); i++ { + if loc.Text[i] == open { + break + } } state := 1 diff --git a/internal/bundle/utils.go b/internal/bundle/utils.go index 89f3e2a6f4..064649733a 100644 --- a/internal/bundle/utils.go +++ b/internal/bundle/utils.go @@ -95,7 +95,8 @@ func LoadBundleFromDisk(path, name string, bvc *bundle.VerificationConfig) (*bun func LoadBundleFromDiskForRegoVersion(regoVersion ast.RegoVersion, path, name string, bvc *bundle.VerificationConfig) (*bundle.Bundle, error) { bundlePath := filepath.Join(path, name, "bundle.tar.gz") - if _, err := os.Stat(bundlePath); err == nil { + _, err := os.Stat(bundlePath) + if err == nil { f, err := os.Open(filepath.Join(bundlePath)) if err != nil { return nil, err @@ -116,9 +117,9 @@ func LoadBundleFromDiskForRegoVersion(regoVersion ast.RegoVersion, path, name st return &b, nil } else if os.IsNotExist(err) { return nil, nil - } else { - return nil, err } + + return nil, err } // SaveBundleToDisk saves the given raw bytes representing the bundle's content to disk diff --git a/internal/compiler/wasm/wasm.go b/internal/compiler/wasm/wasm.go index b827ebb91b..9a5cebec54 100644 --- a/internal/compiler/wasm/wasm.go +++ b/internal/compiler/wasm/wasm.go @@ -1332,7 +1332,7 @@ func (c *Compiler) compileWithStmt(with *ir.WithStmt, result *[]instruction.Inst return nil } -func (c *Compiler) compileUpsert(local ir.Local, path []int, value ir.Operand, loc ir.Location, instrs []instruction.Instruction) []instruction.Instruction { +func (c *Compiler) compileUpsert(local ir.Local, path []int, value ir.Operand, _ ir.Location, instrs []instruction.Instruction) []instruction.Instruction { lcopy := c.genLocal() // holds copy of local instrs = append(instrs, instruction.GetLocal{Index: c.local(local)}) diff --git a/internal/edittree/bitvector/bitvector_test.go b/internal/edittree/bitvector/bitvector_test.go index ff9743953e..7a63b8e760 100644 --- a/internal/edittree/bitvector/bitvector_test.go +++ b/internal/edittree/bitvector/bitvector_test.go @@ -3,42 +3,42 @@ package bitvector import ( "testing" - . "gopkg.in/check.v1" + "gopkg.in/check.v1" ) -func Test(t *testing.T) { TestingT(t) } +func Test(t *testing.T) { check.TestingT(t) } type BitVectorSuite struct { vector *BitVector lVector *BitVector } -var _ = Suite(&BitVectorSuite{}) +var _ = check.Suite(&BitVectorSuite{}) -func (s *BitVectorSuite) SetUpTest(c *C) { +func (s *BitVectorSuite) SetUpTest(_ *check.C) { // This sets elements 4-12 s.vector = NewBitVector([]byte{0xF0, 0x0F}, 12) s.lVector = NewBitVector([]byte{0xF0, 0x0F}, 16) } -func (s *BitVectorSuite) TestElement(c *C) { +func (s *BitVectorSuite) TestElement(c *check.C) { for i := 0; i < 4; i++ { - c.Assert(s.vector.Element(i), Equals, byte(0)) + c.Assert(s.vector.Element(i), check.Equals, byte(0)) } for i := 4; i < 12; i++ { - c.Assert(s.vector.Element(i), Equals, byte(1)) + c.Assert(s.vector.Element(i), check.Equals, byte(1)) } } -func (s *BitVectorSuite) TestInsert(c *C) { +func (s *BitVectorSuite) TestInsert(c *check.C) { for i := 0; i < 4; i++ { s.vector.Insert(0, 8) } - c.Assert(s.vector.Bytes(), DeepEquals, []byte{0xF0, 0xF0}) + c.Assert(s.vector.Bytes(), check.DeepEquals, []byte{0xF0, 0xF0}) } -func (s *BitVectorSuite) TestAppend(c *C) { +func (s *BitVectorSuite) TestAppend(c *check.C) { for i := 0; i < 4; i++ { if i%2 == 0 { s.vector.Append(0) @@ -46,42 +46,42 @@ func (s *BitVectorSuite) TestAppend(c *C) { s.vector.Append(1) } } - c.Assert(s.vector.Bytes(), DeepEquals, []byte{0xF0, 0xAF}) + c.Assert(s.vector.Bytes(), check.DeepEquals, []byte{0xF0, 0xAF}) } -func (s *BitVectorSuite) TestSet(c *C) { +func (s *BitVectorSuite) TestSet(c *check.C) { for i := 4; i < 8; i++ { if i%2 == 0 { s.vector.Set(0, i) } } - c.Assert(s.vector.Bytes(), DeepEquals, []byte{0xA0, 0x0F}) + c.Assert(s.vector.Bytes(), check.DeepEquals, []byte{0xA0, 0x0F}) } -func (s *BitVectorSuite) TestSetOneBit(c *C) { +func (s *BitVectorSuite) TestSetOneBit(c *check.C) { for i := 4; i < 8; i++ { if i%2 == 0 { s.vector.Set(1, i) } } - c.Assert(s.vector.Bytes(), DeepEquals, []byte{0xF0, 0x0F}) + c.Assert(s.vector.Bytes(), check.DeepEquals, []byte{0xF0, 0x0F}) } -func (s *BitVectorSuite) TestDelete(c *C) { +func (s *BitVectorSuite) TestDelete(c *check.C) { for i := 0; i < 4; i++ { s.vector.Delete(8) } - c.Assert(s.vector.Bytes(), DeepEquals, []byte{0xF0}) + c.Assert(s.vector.Bytes(), check.DeepEquals, []byte{0xF0}) } -func (s *BitVectorSuite) TestDeleteFirstIndex(c *C) { +func (s *BitVectorSuite) TestDeleteFirstIndex(c *check.C) { for i := 0; i < 4; i++ { s.vector.Delete(0) } - c.Assert(s.vector.Bytes(), DeepEquals, []byte{0xFF}) + c.Assert(s.vector.Bytes(), check.DeepEquals, []byte{0xFF}) } -func (s *BitVectorSuite) TestDeleteInvalidInput(c *C) { +func (s *BitVectorSuite) TestDeleteInvalidInput(c *check.C) { defer func() { if r := recover(); r == nil { @@ -91,16 +91,16 @@ func (s *BitVectorSuite) TestDeleteInvalidInput(c *C) { s.vector.Delete(-1) } -func (s *BitVectorSuite) TestLength(c *C) { - c.Assert(s.vector.Length(), Equals, 12) +func (s *BitVectorSuite) TestLength(c *check.C) { + c.Assert(s.vector.Length(), check.Equals, 12) } -func (s *BitVectorSuite) TestInsertLongVector(c *C) { +func (s *BitVectorSuite) TestInsertLongVector(c *check.C) { s.lVector.Insert(1, 1) - c.Assert(s.lVector.Bytes(), DeepEquals, []byte{0xE2, 0x1F, 0x0}) + c.Assert(s.lVector.Bytes(), check.DeepEquals, []byte{0xE2, 0x1F, 0x0}) } -func (s *BitVectorSuite) TestAppendLongVector(c *C) { +func (s *BitVectorSuite) TestAppendLongVector(c *check.C) { s.lVector.Append(1) - c.Assert(s.lVector.Bytes(), DeepEquals, []byte{0xF0, 0xF, 0x1}) + c.Assert(s.lVector.Bytes(), check.DeepEquals, []byte{0xF0, 0xF, 0x1}) } diff --git a/internal/gojsonschema/jsonschema_test.go b/internal/gojsonschema/jsonschema_test.go index 7381caa733..136202663c 100644 --- a/internal/gojsonschema/jsonschema_test.go +++ b/internal/gojsonschema/jsonschema_test.go @@ -135,7 +135,7 @@ func TestSuite(t *testing.T) { SetAllowNet(nil) - err = filepath.Walk(wd, func(path string, fileInfo os.FileInfo, err error) error { + err = filepath.Walk(wd, func(path string, fileInfo os.FileInfo, _ error) error { if fileInfo.IsDir() && path != wd && !testDirectories.MatchString(fileInfo.Name()) { return filepath.SkipDir } @@ -176,7 +176,7 @@ func TestFormats(t *testing.T) { } formatsDirectory := filepath.Join(wd, dir.Name(), "optional", "format") - err = filepath.Walk(formatsDirectory, func(path string, fileInfo os.FileInfo, err error) error { + err = filepath.Walk(formatsDirectory, func(path string, fileInfo os.FileInfo, _ error) error { if fileInfo == nil || !strings.HasSuffix(fileInfo.Name(), ".json") { return nil } @@ -190,7 +190,7 @@ func TestFormats(t *testing.T) { } } -func Test_ConcurrentNetAccessModification(t *testing.T) { +func Test_ConcurrentNetAccessModification(_ *testing.T) { go func() { SetAllowNet([]string{"something"}) }() diff --git a/internal/gojsonschema/schema.go b/internal/gojsonschema/schema.go index 5bdfada5d9..8e035013c2 100644 --- a/internal/gojsonschema/schema.go +++ b/internal/gojsonschema/schema.go @@ -788,7 +788,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) return nil } -func (d *Schema) parseReference(documentNode interface{}, currentSchema *SubSchema) error { +func (d *Schema) parseReference(_ interface{}, currentSchema *SubSchema) error { var ( refdDocumentNode interface{} dsp *schemaPoolDocument diff --git a/internal/gojsonschema/validation.go b/internal/gojsonschema/validation.go index 58d10c1f76..7c86e37245 100644 --- a/internal/gojsonschema/validation.go +++ b/internal/gojsonschema/validation.go @@ -556,10 +556,10 @@ func (v *SubSchema) validateArray(currentSubSchema *SubSchema, value []interface if validationResult.Valid() { validatedOne = true break - } else { - if bestValidationResult == nil || validationResult.score > bestValidationResult.score { - bestValidationResult = validationResult - } + } + + if bestValidationResult == nil || validationResult.score > bestValidationResult.score { + bestValidationResult = validationResult } } if !validatedOne { diff --git a/internal/gqlparser/validator/rules/fragments_on_composite_types.go b/internal/gqlparser/validator/rules/fragments_on_composite_types.go index 1af9c4f966..66bd348c47 100644 --- a/internal/gqlparser/validator/rules/fragments_on_composite_types.go +++ b/internal/gqlparser/validator/rules/fragments_on_composite_types.go @@ -25,7 +25,7 @@ func init() { ) }) - observers.OnFragment(func(walker *Walker, fragment *ast.FragmentDefinition) { + observers.OnFragment(func(_ *Walker, fragment *ast.FragmentDefinition) { if fragment.Definition == nil || fragment.TypeCondition == "" || fragment.Definition.IsCompositeType() { return } diff --git a/internal/gqlparser/validator/rules/known_argument_names.go b/internal/gqlparser/validator/rules/known_argument_names.go index d9aa8873e0..36b2d057c9 100644 --- a/internal/gqlparser/validator/rules/known_argument_names.go +++ b/internal/gqlparser/validator/rules/known_argument_names.go @@ -10,7 +10,7 @@ import ( func init() { AddRule("KnownArgumentNames", func(observers *Events, addError AddErrFunc) { // A GraphQL field is only valid if all supplied arguments are defined by that field. - observers.OnField(func(walker *Walker, field *ast.Field) { + observers.OnField(func(_ *Walker, field *ast.Field) { if field.Definition == nil || field.ObjectDefinition == nil { return } @@ -33,7 +33,7 @@ func init() { } }) - observers.OnDirective(func(walker *Walker, directive *ast.Directive) { + observers.OnDirective(func(_ *Walker, directive *ast.Directive) { if directive.Definition == nil { return } diff --git a/internal/gqlparser/validator/rules/known_directives.go b/internal/gqlparser/validator/rules/known_directives.go index 016541e821..9855291e3b 100644 --- a/internal/gqlparser/validator/rules/known_directives.go +++ b/internal/gqlparser/validator/rules/known_directives.go @@ -15,7 +15,7 @@ func init() { Column int } var seen = map[mayNotBeUsedDirective]bool{} - observers.OnDirective(func(walker *Walker, directive *ast.Directive) { + observers.OnDirective(func(_ *Walker, directive *ast.Directive) { if directive.Definition == nil { addError( Message(`Unknown directive "@%s".`, directive.Name), diff --git a/internal/gqlparser/validator/rules/known_fragment_names.go b/internal/gqlparser/validator/rules/known_fragment_names.go index 94583dac33..8ae1fc33f4 100644 --- a/internal/gqlparser/validator/rules/known_fragment_names.go +++ b/internal/gqlparser/validator/rules/known_fragment_names.go @@ -9,7 +9,7 @@ import ( func init() { AddRule("KnownFragmentNames", func(observers *Events, addError AddErrFunc) { - observers.OnFragmentSpread(func(walker *Walker, fragmentSpread *ast.FragmentSpread) { + observers.OnFragmentSpread(func(_ *Walker, fragmentSpread *ast.FragmentSpread) { if fragmentSpread.Definition == nil { addError( Message(`Unknown fragment "%s".`, fragmentSpread.Name), diff --git a/internal/gqlparser/validator/rules/no_unused_fragments.go b/internal/gqlparser/validator/rules/no_unused_fragments.go index f82cfe9f9c..f6ba046a1c 100644 --- a/internal/gqlparser/validator/rules/no_unused_fragments.go +++ b/internal/gqlparser/validator/rules/no_unused_fragments.go @@ -13,13 +13,13 @@ func init() { inFragmentDefinition := false fragmentNameUsed := make(map[string]bool) - observers.OnFragmentSpread(func(walker *Walker, fragmentSpread *ast.FragmentSpread) { + observers.OnFragmentSpread(func(_ *Walker, fragmentSpread *ast.FragmentSpread) { if !inFragmentDefinition { fragmentNameUsed[fragmentSpread.Name] = true } }) - observers.OnFragment(func(walker *Walker, fragment *ast.FragmentDefinition) { + observers.OnFragment(func(_ *Walker, fragment *ast.FragmentDefinition) { inFragmentDefinition = true if !fragmentNameUsed[fragment.Name] { addError( diff --git a/internal/gqlparser/validator/rules/no_unused_variables.go b/internal/gqlparser/validator/rules/no_unused_variables.go index c019ae42e0..163ac895b5 100644 --- a/internal/gqlparser/validator/rules/no_unused_variables.go +++ b/internal/gqlparser/validator/rules/no_unused_variables.go @@ -9,7 +9,7 @@ import ( func init() { AddRule("NoUnusedVariables", func(observers *Events, addError AddErrFunc) { - observers.OnOperation(func(walker *Walker, operation *ast.OperationDefinition) { + observers.OnOperation(func(_ *Walker, operation *ast.OperationDefinition) { for _, varDef := range operation.VariableDefinitions { if varDef.Used { continue diff --git a/internal/gqlparser/validator/rules/provided_required_arguments.go b/internal/gqlparser/validator/rules/provided_required_arguments.go index 20364f8ba9..d6d12c4fd2 100644 --- a/internal/gqlparser/validator/rules/provided_required_arguments.go +++ b/internal/gqlparser/validator/rules/provided_required_arguments.go @@ -9,7 +9,7 @@ import ( func init() { AddRule("ProvidedRequiredArguments", func(observers *Events, addError AddErrFunc) { - observers.OnField(func(walker *Walker, field *ast.Field) { + observers.OnField(func(_ *Walker, field *ast.Field) { if field.Definition == nil { return } @@ -35,7 +35,7 @@ func init() { } }) - observers.OnDirective(func(walker *Walker, directive *ast.Directive) { + observers.OnDirective(func(_ *Walker, directive *ast.Directive) { if directive.Definition == nil { return } diff --git a/internal/gqlparser/validator/rules/unique_argument_names.go b/internal/gqlparser/validator/rules/unique_argument_names.go index 4466d56720..7458c5f6cb 100644 --- a/internal/gqlparser/validator/rules/unique_argument_names.go +++ b/internal/gqlparser/validator/rules/unique_argument_names.go @@ -9,11 +9,11 @@ import ( func init() { AddRule("UniqueArgumentNames", func(observers *Events, addError AddErrFunc) { - observers.OnField(func(walker *Walker, field *ast.Field) { + observers.OnField(func(_ *Walker, field *ast.Field) { checkUniqueArgs(field.Arguments, addError) }) - observers.OnDirective(func(walker *Walker, directive *ast.Directive) { + observers.OnDirective(func(_ *Walker, directive *ast.Directive) { checkUniqueArgs(directive.Arguments, addError) }) }) diff --git a/internal/gqlparser/validator/rules/unique_directives_per_location.go b/internal/gqlparser/validator/rules/unique_directives_per_location.go index 09968a7416..ecf5a0a82e 100644 --- a/internal/gqlparser/validator/rules/unique_directives_per_location.go +++ b/internal/gqlparser/validator/rules/unique_directives_per_location.go @@ -9,7 +9,7 @@ import ( func init() { AddRule("UniqueDirectivesPerLocation", func(observers *Events, addError AddErrFunc) { - observers.OnDirectiveList(func(walker *Walker, directives []*ast.Directive) { + observers.OnDirectiveList(func(_ *Walker, directives []*ast.Directive) { seen := map[string]bool{} for _, dir := range directives { diff --git a/internal/gqlparser/validator/rules/unique_fragment_names.go b/internal/gqlparser/validator/rules/unique_fragment_names.go index 3da46467e8..c94f3ad27c 100644 --- a/internal/gqlparser/validator/rules/unique_fragment_names.go +++ b/internal/gqlparser/validator/rules/unique_fragment_names.go @@ -11,7 +11,7 @@ func init() { AddRule("UniqueFragmentNames", func(observers *Events, addError AddErrFunc) { seenFragments := map[string]bool{} - observers.OnFragment(func(walker *Walker, fragment *ast.FragmentDefinition) { + observers.OnFragment(func(_ *Walker, fragment *ast.FragmentDefinition) { if seenFragments[fragment.Name] { addError( Message(`There can be only one fragment named "%s".`, fragment.Name), diff --git a/internal/gqlparser/validator/rules/unique_input_field_names.go b/internal/gqlparser/validator/rules/unique_input_field_names.go index f9f69051bf..a93d63bd1e 100644 --- a/internal/gqlparser/validator/rules/unique_input_field_names.go +++ b/internal/gqlparser/validator/rules/unique_input_field_names.go @@ -9,7 +9,7 @@ import ( func init() { AddRule("UniqueInputFieldNames", func(observers *Events, addError AddErrFunc) { - observers.OnValue(func(walker *Walker, value *ast.Value) { + observers.OnValue(func(_ *Walker, value *ast.Value) { if value.Kind != ast.ObjectValue { return } diff --git a/internal/gqlparser/validator/rules/unique_operation_names.go b/internal/gqlparser/validator/rules/unique_operation_names.go index dc937795bd..dcd404dadf 100644 --- a/internal/gqlparser/validator/rules/unique_operation_names.go +++ b/internal/gqlparser/validator/rules/unique_operation_names.go @@ -11,7 +11,7 @@ func init() { AddRule("UniqueOperationNames", func(observers *Events, addError AddErrFunc) { seen := map[string]bool{} - observers.OnOperation(func(walker *Walker, operation *ast.OperationDefinition) { + observers.OnOperation(func(_ *Walker, operation *ast.OperationDefinition) { if seen[operation.Name] { addError( Message(`There can be only one operation named "%s".`, operation.Name), diff --git a/internal/gqlparser/validator/rules/unique_variable_names.go b/internal/gqlparser/validator/rules/unique_variable_names.go index 94dab3cf13..7a214dbe4c 100644 --- a/internal/gqlparser/validator/rules/unique_variable_names.go +++ b/internal/gqlparser/validator/rules/unique_variable_names.go @@ -9,7 +9,7 @@ import ( func init() { AddRule("UniqueVariableNames", func(observers *Events, addError AddErrFunc) { - observers.OnOperation(func(walker *Walker, operation *ast.OperationDefinition) { + observers.OnOperation(func(_ *Walker, operation *ast.OperationDefinition) { seen := map[string]int{} for _, def := range operation.VariableDefinitions { // add the same error only once per a variable. diff --git a/internal/gqlparser/validator/rules/values_of_correct_type.go b/internal/gqlparser/validator/rules/values_of_correct_type.go index 88d8f53c45..8858023d4e 100644 --- a/internal/gqlparser/validator/rules/values_of_correct_type.go +++ b/internal/gqlparser/validator/rules/values_of_correct_type.go @@ -13,7 +13,7 @@ import ( func init() { AddRule("ValuesOfCorrectType", func(observers *Events, addError AddErrFunc) { - observers.OnValue(func(walker *Walker, value *ast.Value) { + observers.OnValue(func(_ *Walker, value *ast.Value) { if value.Definition == nil || value.ExpectedType == nil { return } diff --git a/internal/gqlparser/validator/rules/variables_are_input_types.go b/internal/gqlparser/validator/rules/variables_are_input_types.go index 51cb77ca31..ea4dfcc5ab 100644 --- a/internal/gqlparser/validator/rules/variables_are_input_types.go +++ b/internal/gqlparser/validator/rules/variables_are_input_types.go @@ -9,7 +9,7 @@ import ( func init() { AddRule("VariablesAreInputTypes", func(observers *Events, addError AddErrFunc) { - observers.OnOperation(func(walker *Walker, operation *ast.OperationDefinition) { + observers.OnOperation(func(_ *Walker, operation *ast.OperationDefinition) { for _, def := range operation.VariableDefinitions { if def.Definition == nil { continue diff --git a/internal/oracle/oracle.go b/internal/oracle/oracle.go index e3eb3afa1a..baa74fae7f 100644 --- a/internal/oracle/oracle.go +++ b/internal/oracle/oracle.go @@ -142,7 +142,7 @@ func compileUpto(stage string, modules map[string]*ast.Module, bs []byte, filena if stage != "" { compiler = compiler.WithStageAfter(stage, ast.CompilerStageDefinition{ Name: "halt", - Stage: func(c *ast.Compiler) *ast.Error { + Stage: func(_ *ast.Compiler) *ast.Error { return &ast.Error{ Code: "halt", } diff --git a/internal/planner/planner.go b/internal/planner/planner.go index df1d66b85e..b75d26ddab 100644 --- a/internal/planner/planner.go +++ b/internal/planner/planner.go @@ -1523,7 +1523,7 @@ func (p *Planner) planValue(t ast.Value, loc *ast.Location, iter planiter) error } } -func (p *Planner) planNull(null ast.Null, iter planiter) error { +func (p *Planner) planNull(_ ast.Null, iter planiter) error { target := p.newLocal() diff --git a/internal/providers/aws/ecr_test.go b/internal/providers/aws/ecr_test.go index c231b2aca2..839e9e887e 100644 --- a/internal/providers/aws/ecr_test.go +++ b/internal/providers/aws/ecr_test.go @@ -21,7 +21,7 @@ func TestECR(t *testing.T) { } ] }` - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { if _, err := io.WriteString(w, payload); err != nil { t.Fatalf("io.WriteString(w, payload) = %v", err) } diff --git a/internal/providers/aws/kms_test.go b/internal/providers/aws/kms_test.go index ced9e3d248..b680e52084 100644 --- a/internal/providers/aws/kms_test.go +++ b/internal/providers/aws/kms_test.go @@ -27,7 +27,7 @@ func TestKMS_SignDigest(t *testing.T) { } run := func(t *testing.T, tc testCase) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { if tc.responseStatus != 200 { w.WriteHeader(tc.responseStatus) } diff --git a/internal/providers/aws/signing_v4a.go b/internal/providers/aws/signing_v4a.go index 12bc38ec86..929f2006e7 100644 --- a/internal/providers/aws/signing_v4a.go +++ b/internal/providers/aws/signing_v4a.go @@ -174,7 +174,7 @@ type httpSigner struct { PayloadHash string } -func (s *httpSigner) setRequiredSigningFields(headers http.Header, query url.Values) { +func (s *httpSigner) setRequiredSigningFields(headers http.Header, _ url.Values) { amzDate := s.Time.Format(timeFormat) headers.Set(AmzRegionSetKey, strings.Join(s.RegionSet, ",")) diff --git a/internal/providers/aws/v4/util.go b/internal/providers/aws/v4/util.go index 0cb9cffaf5..c8e7fb1bab 100644 --- a/internal/providers/aws/v4/util.go +++ b/internal/providers/aws/v4/util.go @@ -11,14 +11,9 @@ const doubleSpace = " " // contain multiple side-by-side spaces. func StripExcessSpaces(str string) string { var j, k, l, m, spaces int - // Trim trailing spaces - for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { - } - // Trim leading spaces - for k = 0; k < j && str[k] == ' '; k++ { - } - str = str[k : j+1] + // Trim leading and trailing spaces + str = strings.Trim(str, " ") // Strip multiple spaces. j = strings.Index(str, doubleSpace) diff --git a/internal/report/report_test.go b/internal/report/report_test.go index 2171cd26b8..ba07867a95 100644 --- a/internal/report/report_test.go +++ b/internal/report/report_test.go @@ -136,7 +136,7 @@ func TestReportWithExtraKeys(t *testing.T) { t.Fatalf("Unexpected error %v", err) } - reporter.RegisterGatherer("foobear", func(ctx context.Context) (any, error) { + reporter.RegisterGatherer("foobear", func(_ context.Context) (any, error) { return map[string]any{"baz": []string{"one", "two"}}, nil }) @@ -222,7 +222,7 @@ func getTestServer(update interface{}, statusCode int) (baseURL string, teardown mux := http.NewServeMux() ts := httptest.NewServer(mux) - mux.HandleFunc("/v1/version", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("/v1/version", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(statusCode) bs, _ := json.Marshal(update) w.Header().Set("Content-Type", "application/json") diff --git a/internal/wasm/encoding/reader.go b/internal/wasm/encoding/reader.go index d9c1bda3da..35e6059c72 100644 --- a/internal/wasm/encoding/reader.go +++ b/internal/wasm/encoding/reader.go @@ -375,10 +375,10 @@ func readTableSection(r io.Reader, s *module.TableSection) error { return err } else if elem != constant.ElementTypeAnyFunc { return fmt.Errorf("illegal element type") - } else { - table.Type = types.Anyfunc } + table.Type = types.Anyfunc + if err := readLimits(r, &table.Lim); err != nil { return err } diff --git a/internal/wasm/sdk/internal/wasm/pool.go b/internal/wasm/sdk/internal/wasm/pool.go index bfc211240b..40970be819 100644 --- a/internal/wasm/sdk/internal/wasm/pool.go +++ b/internal/wasm/sdk/internal/wasm/pool.go @@ -220,7 +220,7 @@ func (p *Pool) SetPolicyData(ctx context.Context, policy []byte, data []byte) er func (p *Pool) SetDataPath(ctx context.Context, path []string, value interface{}) error { p.dataMtx.Lock() defer p.dataMtx.Unlock() - return p.updateVMs(func(vm *VM, opts vmOpts) error { + return p.updateVMs(func(vm *VM, _ vmOpts) error { return vm.SetDataPath(ctx, path, value) }) } diff --git a/internal/wasm/sdk/internal/wasm/vm.go b/internal/wasm/sdk/internal/wasm/vm.go index 40453682c4..b089a20422 100644 --- a/internal/wasm/sdk/internal/wasm/vm.go +++ b/internal/wasm/sdk/internal/wasm/vm.go @@ -487,11 +487,11 @@ func (i *VM) SetPolicyData(ctx context.Context, opts vmOpts) error { } } mem := i.memory.UnsafeData(i.store) - len := int32(len(opts.parsedData)) - copy(mem[i.baseHeapPtr:i.baseHeapPtr+len], opts.parsedData) + length := int32(len(opts.parsedData)) + copy(mem[i.baseHeapPtr:i.baseHeapPtr+length], opts.parsedData) i.dataAddr = opts.parsedDataAddr - i.evalHeapPtr = i.baseHeapPtr + len + i.evalHeapPtr = i.baseHeapPtr + length err := i.setHeapState(ctx, i.evalHeapPtr) if err != nil { return err diff --git a/internal/wasm/sdk/opa/loader/file/loader.go b/internal/wasm/sdk/opa/loader/file/loader.go index 82e6bf4686..f41068c5de 100644 --- a/internal/wasm/sdk/opa/loader/file/loader.go +++ b/internal/wasm/sdk/opa/loader/file/loader.go @@ -45,11 +45,11 @@ type policyData interface { // New constructs a new file loader periodically reloading the bundle // from a file. func New(opa *opa.OPA) *Loader { - return new(opa) + return newLoader(opa) } -// new constructs a new file loader. This is for tests. -func new(pd policyData) *Loader { +// newLoader constructs a newLoader file loader. This is for tests. +func newLoader(pd policyData) *Loader { return &Loader{ pd: pd, interval: DefaultInterval, diff --git a/internal/wasm/sdk/opa/loader/file/loader_test.go b/internal/wasm/sdk/opa/loader/file/loader_test.go index 25cec6b606..2b8cdacccc 100644 --- a/internal/wasm/sdk/opa/loader/file/loader_test.go +++ b/internal/wasm/sdk/opa/loader/file/loader_test.go @@ -32,7 +32,7 @@ func TestFileLoader(t *testing.T) { // Start loader, without having a file in place. var pd testPolicyData - loader, err := new(&pd).WithFile(f.Name()).WithInterval(10 * time.Millisecond).Init() + loader, err := newLoader(&pd).WithFile(f.Name()).WithInterval(10 * time.Millisecond).Init() if err != nil { t.Fatal(err.Error()) } diff --git a/ir/pretty.go b/ir/pretty.go index a0f2df3bc5..6102c5a911 100644 --- a/ir/pretty.go +++ b/ir/pretty.go @@ -25,11 +25,11 @@ type prettyPrinter struct { w io.Writer } -func (pp *prettyPrinter) Before(x interface{}) { +func (pp *prettyPrinter) Before(_ interface{}) { pp.depth++ } -func (pp *prettyPrinter) After(x interface{}) { +func (pp *prettyPrinter) After(_ interface{}) { pp.depth-- } diff --git a/loader/loader.go b/loader/loader.go index 1ce0e7868f..e584bab3cb 100644 --- a/loader/loader.go +++ b/loader/loader.go @@ -81,7 +81,7 @@ type Filter = filter.LoaderFilter // GlobExcludeName excludes files and directories whose names do not match the // shell style pattern at minDepth or greater. func GlobExcludeName(pattern string, minDepth int) Filter { - return func(abspath string, info fs.FileInfo, depth int) bool { + return func(_ string, info fs.FileInfo, depth int) bool { match, _ := filepath.Match(pattern, info.Name()) return match && depth >= minDepth } @@ -486,7 +486,7 @@ func AsBundle(path string) (*bundle.Bundle, error) { // AllRegos returns a Result object loaded (recursively) with all Rego source // files from the specified paths. func AllRegos(paths []string) (*Result, error) { - return NewFileLoader().Filtered(paths, func(_ string, info os.FileInfo, depth int) bool { + return NewFileLoader().Filtered(paths, func(_ string, info os.FileInfo, _ int) bool { return !info.IsDir() && !strings.HasSuffix(info.Name(), bundle.RegoExt) }) } @@ -522,7 +522,7 @@ func Paths(path string, recurse bool) (paths []string, err error) { if err != nil { return nil, err } - err = filepath.Walk(path, func(f string, info os.FileInfo, err error) error { + err = filepath.Walk(path, func(f string, _ os.FileInfo, _ error) error { if !recurse { if path != f && path != filepath.Dir(f) { return filepath.SkipDir diff --git a/plugins/bundle/plugin_test.go b/plugins/bundle/plugin_test.go index 2615d5f41d..36a34e2c47 100644 --- a/plugins/bundle/plugin_test.go +++ b/plugins/bundle/plugin_test.go @@ -757,7 +757,7 @@ func TestPluginStartLazyLoadInMem(t *testing.T) { }, } - s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { err := bundle.NewWriter(w).Write(mockBundle1) if err != nil { t.Fatal(err) @@ -772,7 +772,7 @@ func TestPluginStartLazyLoadInMem(t *testing.T) { }, } - s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { err := bundle.NewWriter(w).Write(mockBundle2) if err != nil { t.Fatal(err) @@ -3349,8 +3349,8 @@ func TestPluginActivateScopedBundle(t *testing.T) { // Ensure a/a3-6 are intact. a1-2 are overwritten by bundle, and // that the manifest has been written to storage. expData := util.MustUnmarshalJSON([]byte(`{"a1": "foo", "a3": "x2", "a5": "x3"}`)) - expIds := []string{filepath.Join(bundleName, "bundle/id1"), "some/id2", "some/id3"} - validateStoreState(ctx, t, manager.Store, "/a", expData, expIds, bundleName, "quickbrownfaux", nil) + expIDs := []string{filepath.Join(bundleName, "bundle/id1"), "some/id2", "some/id3"} + validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux", nil) // Activate a bundle that is scoped to a/a3 ad a/a6. Include a function // inside package a.a4 that we can depend on outside of the bundle scope to @@ -3384,8 +3384,8 @@ func TestPluginActivateScopedBundle(t *testing.T) { // Ensure a/a5-a6 are intact. a3 and a4 are overwritten by bundle. expData = util.MustUnmarshalJSON([]byte(`{"a3": "foo", "a5": "x3"}`)) - expIds = []string{filepath.Join(bundleName, "bundle/id2"), "some/id3"} - validateStoreState(ctx, t, manager.Store, "/a", expData, expIds, bundleName, "quickbrownfaux-2", + expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "some/id3"} + validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2", map[string]interface{}{ "a": map[string]interface{}{"a1": "deadbeef"}, }) @@ -3408,8 +3408,8 @@ func TestPluginActivateScopedBundle(t *testing.T) { // Ensure bundle activation failed by checking that previous revision is // still active. - expIds = []string{filepath.Join(bundleName, "bundle/id2"), "not_scoped", "some/id3"} - validateStoreState(ctx, t, manager.Store, "/a", expData, expIds, bundleName, "quickbrownfaux-2", + expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "not_scoped", "some/id3"} + validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2", map[string]interface{}{ "a": map[string]interface{}{"a1": "deadbeef"}, }) @@ -3789,8 +3789,8 @@ func TestUpgradeLegacyBundleToMuiltiBundleSameBundle(t *testing.T) { // Ensure it has been activated expData := util.MustUnmarshalJSON([]byte(`{"a2": "foo"}`)) - expIds := []string{"bundle/id1"} - validateStoreState(ctx, t, manager.Store, "/a", expData, expIds, bundleName, "quickbrownfaux", nil) + expIDs := []string{"bundle/id1"} + validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux", nil) if plugin.config.IsMultiBundle() { t.Fatalf("Expected plugin to be in non-multi bundle config mode") @@ -3810,8 +3810,8 @@ func TestUpgradeLegacyBundleToMuiltiBundleSameBundle(t *testing.T) { plugin.oneShot(ctx, bundleName, download.Update{Bundle: &b}) // The only thing that should have changed is the store id for the policy - expIds = []string{"test-bundle/bundle/id1"} - validateStoreState(ctx, t, manager.Store, "/a", expData, expIds, bundleName, "quickbrownfaux-2", nil) + expIDs = []string{"test-bundle/bundle/id1"} + validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2", nil) // Make sure the legacy path is gone now that we are in multi-bundle mode var actual string @@ -3908,8 +3908,8 @@ func TestUpgradeLegacyBundleToMultiBundleNewBundles(t *testing.T) { // Ensure it has been activated expData := util.MustUnmarshalJSON([]byte(`{"a2": "foo"}`)) - expIds := []string{"bundle/id1"} - validateStoreState(ctx, t, manager.Store, "/a", expData, expIds, bundleName, "quickbrownfaux", nil) + expIDs := []string{"bundle/id1"} + validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux", nil) if plugin.config.IsMultiBundle() { t.Fatalf("Expected plugin to be in non-multi bundle config mode") @@ -3949,8 +3949,8 @@ func TestUpgradeLegacyBundleToMultiBundleNewBundles(t *testing.T) { plugin.oneShot(ctx, "b2", download.Update{Bundle: &b}) expData = util.MustUnmarshalJSON([]byte(`{"b2": "foo"}`)) - expIds = []string{"b2/id1"} - validateStoreState(ctx, t, manager.Store, "/a", expData, expIds, "b2", "b2-1", nil) + expIDs = []string{"b2/id1"} + validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, "b2", "b2-1", nil) // Make sure the legacy path is gone now that we are in multi-bundle mode var actual string @@ -5698,7 +5698,7 @@ func TestPluginManualTrigger(t *testing.T) { Modules: []bundle.ModuleFile{}, } - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { err := bundle.NewWriter(w).Write(mockBundle) if err != nil { t.Fatal(err) @@ -5798,7 +5798,7 @@ func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) { }, } - s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { err := bundle.NewWriter(w).Write(mockBundle1) if err != nil { t.Fatal(err) @@ -5813,7 +5813,7 @@ func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) { }, } - s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { err := bundle.NewWriter(w).Write(mockBundle2) if err != nil { t.Fatal(err) @@ -5938,7 +5938,7 @@ func TestPluginManualTriggerMultiple(t *testing.T) { }, } - s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { err := bundle.NewWriter(w).Write(mockBundle1) if err != nil { t.Fatal(err) @@ -5953,7 +5953,7 @@ func TestPluginManualTriggerMultiple(t *testing.T) { }, } - s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { err := bundle.NewWriter(w).Write(mockBundle2) if err != nil { t.Fatal(err) @@ -6034,7 +6034,7 @@ func TestPluginManualTriggerWithTimeout(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { time.Sleep(3 * time.Second) // this should cause the context deadline to exceed })) @@ -6160,7 +6160,7 @@ func getTestRawBundle(t *testing.T) io.Reader { return &buf } -func validateStoreState(ctx context.Context, t *testing.T, store storage.Store, root string, expData interface{}, expIds []string, expBundleName string, expBundleRev string, expMetadata map[string]interface{}) { +func validateStoreState(ctx context.Context, t *testing.T, store storage.Store, root string, expData interface{}, expIDs []string, expBundleName string, expBundleRev string, expMetadata map[string]interface{}) { t.Helper() if err := storage.Txn(ctx, store, storage.TransactionParams{}, func(txn storage.Transaction) error { value, err := store.Read(ctx, txn, storage.MustParsePath(root)) @@ -6178,10 +6178,10 @@ func validateStoreState(ctx context.Context, t *testing.T, store storage.Store, } sort.Strings(ids) - sort.Strings(expIds) + sort.Strings(expIDs) - if !reflect.DeepEqual(ids, expIds) { - return fmt.Errorf("Expected ids %v but got %v", expIds, ids) + if !reflect.DeepEqual(ids, expIDs) { + return fmt.Errorf("Expected ids %v but got %v", expIDs, ids) } rev, err := bundle.ReadBundleRevisionFromStore(ctx, store, txn, expBundleName) diff --git a/plugins/discovery/config.go b/plugins/discovery/config.go index a157f7abb1..869ae9b4d6 100644 --- a/plugins/discovery/config.go +++ b/plugins/discovery/config.go @@ -90,19 +90,19 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin } // make a copy of the keys map - copy := map[string]*keys.Config{} + cpy := map[string]*keys.Config{} for key, kc := range confKeys { - copy[key] = kc + cpy[key] = kc } if c.Signing != nil { - err := c.Signing.ValidateAndInjectDefaults(copy) + err := c.Signing.ValidateAndInjectDefaults(cpy) if err != nil { return fmt.Errorf("invalid configuration for discovery service: %s", err.Error()) } } else { if len(confKeys) > 0 { - c.Signing = bundle.NewVerificationConfig(copy, "", "", nil) + c.Signing = bundle.NewVerificationConfig(cpy, "", "", nil) } } diff --git a/plugins/discovery/discovery_test.go b/plugins/discovery/discovery_test.go index 2ee273ad72..1b7c05d5c4 100644 --- a/plugins/discovery/discovery_test.go +++ b/plugins/discovery/discovery_test.go @@ -502,7 +502,7 @@ func (r *reconfigureTestPlugin) Start(context.Context) error { func (*reconfigureTestPlugin) Stop(context.Context) { } -func (r *reconfigureTestPlugin) Reconfigure(_ context.Context, config interface{}) { +func (r *reconfigureTestPlugin) Reconfigure(_ context.Context, _ interface{}) { r.counts["reconfig"]++ } diff --git a/plugins/logs/mask_test.go b/plugins/logs/mask_test.go index 36f2b26a48..0585bc4333 100644 --- a/plugins/logs/mask_test.go +++ b/plugins/logs/mask_test.go @@ -628,7 +628,7 @@ func TestNewMaskRuleSet(t *testing.T) { for _, tc := range tests { t.Run(tc.note, func(t *testing.T) { - _, err := newMaskRuleSet(tc.value, func(mRule *maskRule, err error) {}) + _, err := newMaskRuleSet(tc.value, func(_ *maskRule, _ error) {}) if err != nil { if exp, act := tc.err.Error(), err.Error(); exp != act { t.Fatalf("Expected: %s\nGot: %s", exp, act) @@ -706,7 +706,7 @@ func TestMaskRuleSetMask(t *testing.T) { ptr := &maskRuleSet{} var ruleErr error if tc.expErr != nil { - ptr.OnRuleError = func(mRule *maskRule, err error) { + ptr.OnRuleError = func(_ *maskRule, err error) { ruleErr = err } } else { diff --git a/plugins/logs/plugin.go b/plugins/logs/plugin.go index 10e9bdc6b0..64a58a4b32 100644 --- a/plugins/logs/plugin.go +++ b/plugins/logs/plugin.go @@ -577,7 +577,7 @@ func Lookup(manager *plugins.Manager) *Plugin { } // Start starts the plugin. -func (p *Plugin) Start(ctx context.Context) error { +func (p *Plugin) Start(_ context.Context) error { p.logger.Info("Starting decision logger.") go p.loop() p.manager.UpdatePluginStatus(Name, &plugins.Status{State: plugins.StateOK}) diff --git a/plugins/plugins.go b/plugins/plugins.go index 0859305952..bacdd15076 100644 --- a/plugins/plugins.go +++ b/plugins/plugins.go @@ -286,11 +286,10 @@ func ValidateAndInjectDefaultsForTriggerMode(a, b *TriggerMode) (*TriggerMode, e return nil, err } return a, nil - - } else { - t := DefaultTriggerMode - return &t, nil } + + t := DefaultTriggerMode + return &t, nil } type namedplugin struct { diff --git a/plugins/plugins_test.go b/plugins/plugins_test.go index ddd64eabc8..12cfc2f6df 100644 --- a/plugins/plugins_test.go +++ b/plugins/plugins_test.go @@ -439,7 +439,7 @@ type mockForInitStartOrdering struct { Started bool } -func (m *mockForInitStartOrdering) Start(ctx context.Context) error { +func (m *mockForInitStartOrdering) Start(_ context.Context) error { m.Started = true if m.Manager.initialized { return nil diff --git a/plugins/rest/auth.go b/plugins/rest/auth.go index 99eac12409..c656817339 100644 --- a/plugins/rest/auth.go +++ b/plugins/rest/auth.go @@ -690,7 +690,7 @@ func (ap *clientTLSAuthPlugin) NewClient(c Config) (*http.Client, error) { return client, nil } -func (ap *clientTLSAuthPlugin) Prepare(req *http.Request) error { +func (ap *clientTLSAuthPlugin) Prepare(_ *http.Request) error { return nil } diff --git a/plugins/rest/gcp_test.go b/plugins/rest/gcp_test.go index cd324d2078..5e3fb36a35 100644 --- a/plugins/rest/gcp_test.go +++ b/plugins/rest/gcp_test.go @@ -14,7 +14,7 @@ import ( func TestGCPMetadataAuthPlugin(t *testing.T) { idToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.Et9HFtf9R3GEMA0IICOfFMVXY7kkTX1wr4qCyhIf58U" - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + s := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) defer s.Close() ts := httptest.NewServer(http.Handler(&gcpMetadataHandler{idToken})) diff --git a/plugins/rest/rest_test.go b/plugins/rest/rest_test.go index fb0b632a0e..cb1983ae16 100644 --- a/plugins/rest/rest_test.go +++ b/plugins/rest/rest_test.go @@ -922,7 +922,7 @@ func TestDoWithDistributedTracingOpts(t *testing.T) { tracing.RegisterHTTPTracing(&mock) body := "Some Bad Request was received" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, body) })) @@ -957,7 +957,7 @@ func TestDoWithResponseInClientLog(t *testing.T) { ctx := context.Background() body := "Some Bad Request was received" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, body) })) @@ -991,7 +991,7 @@ func TestDoWithResponseInClientLog(t *testing.T) { func TestDoWithTruncatedResponseInClientLog(t *testing.T) { ctx := context.Background() - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, strings.Repeat("Some Bad Request was received", 50)) })) @@ -1492,7 +1492,7 @@ func TestOauth2ClientCredentials(t *testing.T) { defer tc.ots.stop() if tc.options == nil { - tc.options = func(c *Config) {} + tc.options = func(_ *Config) {} } client := newOauth2TestClient(t, tc.ts, tc.ots, tc.options) @@ -1767,7 +1767,7 @@ func TestS3SigningInstantiationInitializesLogger(t *testing.T) { authPlugin := &awsSigningAuthPlugin{ AWSEnvironmentCredentials: &awsEnvironmentCredentialService{}, } - client, err := New([]byte(config), map[string]*keys.Config{}, AuthPluginLookup(func(name string) HTTPAuthPlugin { + client, err := New([]byte(config), map[string]*keys.Config{}, AuthPluginLookup(func(_ string) HTTPAuthPlugin { return authPlugin })) if err != nil { @@ -2447,7 +2447,7 @@ func getTestServerWithTimeout(d time.Duration) (baseURL string, teardownFn func( mux := http.NewServeMux() ts := httptest.NewServer(mux) - mux.HandleFunc("/v1/test", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("/v1/test", func(w http.ResponseWriter, _ *http.Request) { time.Sleep(d * time.Second) w.WriteHeader(http.StatusOK) }) diff --git a/plugins/status/plugin.go b/plugins/status/plugin.go index 295e1d8cc6..8807524039 100644 --- a/plugins/status/plugin.go +++ b/plugins/status/plugin.go @@ -283,7 +283,7 @@ func (p *Plugin) unregisterAll() { } // Stop stops the plugin. -func (p *Plugin) Stop(ctx context.Context) { +func (p *Plugin) Stop(_ context.Context) { p.logger.Info("Stopping status reporter.") p.manager.UnregisterPluginStatusListener(Name) done := make(chan struct{}) diff --git a/plugins/status/plugin_test.go b/plugins/status/plugin_test.go index dafee8749d..c5f167459c 100644 --- a/plugins/status/plugin_test.go +++ b/plugins/status/plugin_test.go @@ -423,7 +423,7 @@ func TestPluginStartTriggerManualWithTimeout(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { time.Sleep(3 * time.Second) // this should cause the context deadline to exceed })) diff --git a/rego/rego.go b/rego/rego.go index cbe2d0c7da..266e6d6ab0 100644 --- a/rego/rego.go +++ b/rego/rego.go @@ -1496,7 +1496,7 @@ func (r *Rego) Compile(ctx context.Context, opts ...CompileOption) (*CompileResu return r.compileWasm(modules, queries, compileQueryType) // TODO(sr) control flow is funky here } -func (r *Rego) compileWasm(modules []*ast.Module, queries []ast.Body, qType queryType) (*CompileResult, error) { +func (r *Rego) compileWasm(_ []*ast.Module, queries []ast.Body, qType queryType) (*CompileResult, error) { policy, err := r.planQuery(queries, qType) if err != nil { return nil, err @@ -1871,7 +1871,7 @@ func (r *Rego) loadFiles(ctx context.Context, txn storage.Transaction, m metrics return nil } -func (r *Rego) loadBundles(ctx context.Context, txn storage.Transaction, m metrics.Metrics) error { +func (r *Rego) loadBundles(_ context.Context, _ storage.Transaction, m metrics.Metrics) error { if len(r.bundlePaths) == 0 { return nil } @@ -2035,7 +2035,7 @@ func (r *Rego) prepareImports() ([]*ast.Import, error) { return imports, nil } -func (r *Rego) compileQuery(query ast.Body, imports []*ast.Import, m metrics.Metrics, extras []extraStage) (ast.QueryCompiler, ast.Body, error) { +func (r *Rego) compileQuery(query ast.Body, imports []*ast.Import, _ metrics.Metrics, extras []extraStage) (ast.QueryCompiler, ast.Body, error) { var pkg *ast.Package if r.pkg != "" { @@ -2476,7 +2476,7 @@ func (r *Rego) partial(ctx context.Context, ectx *EvalContext) (*PartialQueries, return pq, nil } -func (r *Rego) rewriteQueryToCaptureValue(qc ast.QueryCompiler, query ast.Body) (ast.Body, error) { +func (r *Rego) rewriteQueryToCaptureValue(_ ast.QueryCompiler, query ast.Body) (ast.Body, error) { checkCapture := iteration(query) || len(query) > 1 @@ -2593,7 +2593,7 @@ type transactionCloser func(ctx context.Context, err error) error // regardless of status. func (r *Rego) getTxn(ctx context.Context) (storage.Transaction, transactionCloser, error) { - noopCloser := func(ctx context.Context, err error) error { + noopCloser := func(_ context.Context, _ error) error { return nil // no-op default } diff --git a/rego/rego_test.go b/rego/rego_test.go index f7a59143f1..c69e978b97 100644 --- a/rego/rego_test.go +++ b/rego/rego_test.go @@ -1705,7 +1705,7 @@ func TestUnsafeBuiltins(t *testing.T) { } }) - t.Run("ignore if given compiler", func(t *testing.T) { + t.Run("ignore if given compiler", func(_ *testing.T) { r := New( Compiler(ast.NewCompiler()), UnsafeBuiltins(map[string]struct{}{"count": {}}), @@ -2026,7 +2026,7 @@ func TestRegoEvalWithRegoV1(t *testing.T) { }, { name: "Store", - options: func(path string, policies map[string]string, t *testing.T, ctx context.Context) []func(*Rego) { + options: func(_ string, policies map[string]string, t *testing.T, ctx context.Context) []func(*Rego) { t.Helper() store := mock.New() txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams) diff --git a/repl/repl.go b/repl/repl.go index fe101144dc..be0f33fbf3 100644 --- a/repl/repl.go +++ b/repl/repl.go @@ -508,9 +508,8 @@ func (r *REPL) cmdShow(args []string) error { } fmt.Fprintln(r.output, string(b)) return nil - } else { - return fmt.Errorf("unknown option '%v'", args[0]) } + return fmt.Errorf("unknown option '%v'", args[0]) } type replDebugState struct { @@ -688,7 +687,7 @@ func (r *REPL) unsetRule(ctx context.Context, name ast.Var) (bool, error) { return true, nil } -func (r *REPL) unsetPackage(ctx context.Context, pkg *ast.Package) (bool, error) { +func (r *REPL) unsetPackage(_ context.Context, pkg *ast.Package) (bool, error) { path := fmt.Sprintf("%v", pkg.Path) _, ok := r.modules[path] if ok { @@ -748,7 +747,7 @@ func (r *REPL) recompile(ctx context.Context, cpy *ast.Module) error { return nil } -func (r *REPL) compileBody(ctx context.Context, compiler *ast.Compiler, body ast.Body) (ast.Body, *ast.TypeEnv, error) { +func (r *REPL) compileBody(_ context.Context, compiler *ast.Compiler, body ast.Body) (ast.Body, *ast.TypeEnv, error) { r.timerStart(metrics.RegoQueryCompile) defer r.timerStop(metrics.RegoQueryCompile) @@ -1280,7 +1279,7 @@ func (r *REPL) loadModules(ctx context.Context, txn storage.Transaction) (map[st return modules, nil } -func (r *REPL) printTypes(ctx context.Context, typeEnv *ast.TypeEnv, body ast.Body) { +func (r *REPL) printTypes(_ context.Context, typeEnv *ast.TypeEnv, body ast.Body) { ast.WalkRefs(body, func(ref ast.Ref) bool { fmt.Fprintf(r.output, "# %v: %v\n", ref, typeEnv.Get(ref)) diff --git a/runtime/plugins_test.go b/runtime/plugins_test.go index c59c449960..af7042f42e 100644 --- a/runtime/plugins_test.go +++ b/runtime/plugins_test.go @@ -21,13 +21,13 @@ type Tester struct { startErr error } -func (t *Tester) Start(ctx context.Context) error { +func (t *Tester) Start(_ context.Context) error { return t.startErr } -func (t *Tester) Stop(ctx context.Context) {} +func (t *Tester) Stop(_ context.Context) {} -func (t *Tester) Reconfigure(ctx context.Context, config interface{}) {} +func (t *Tester) Reconfigure(_ context.Context, _ interface{}) {} type Config struct { ConfigErr bool `json:"configerr"` @@ -50,7 +50,7 @@ func (f Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error return cfg, nil } -func (f Factory) New(_ *plugins.Manager, config interface{}) plugins.Plugin { +func (f Factory) New(_ *plugins.Manager, _ interface{}) plugins.Plugin { return &Tester{} } diff --git a/runtime/runtime_test.go b/runtime/runtime_test.go index f90c387cea..5ab40fba17 100644 --- a/runtime/runtime_test.go +++ b/runtime/runtime_test.go @@ -161,7 +161,7 @@ func testRuntimeProcessWatchEventPolicyError(t *testing.T, asBundle bool) { ch := make(chan error) - testFunc := func(d time.Duration, err error) { + testFunc := func(_ time.Duration, err error) { ch <- err } @@ -1325,7 +1325,7 @@ func getTestServer(update interface{}, statusCode int) (baseURL string, teardown mux := http.NewServeMux() ts := httptest.NewServer(mux) - mux.HandleFunc("/v1/version", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("/v1/version", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(statusCode) bs, _ := json.Marshal(update) w.Header().Set("Content-Type", "application/json") diff --git a/server/authorizer/authorizer_test.go b/server/authorizer/authorizer_test.go index e30833fe52..e1351404fa 100644 --- a/server/authorizer/authorizer_test.go +++ b/server/authorizer/authorizer_test.go @@ -35,7 +35,7 @@ func (a appendingPrintHook) Print(_ print.Context, s string) error { return nil } -func (h *mockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { +func (h *mockHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) } @@ -460,7 +460,7 @@ func TestMakeInputWithBody(t *testing.T) { func TestInterQueryCache(t *testing.T) { count := 0 - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) count++ })) diff --git a/server/certs.go b/server/certs.go index 6c92eca07d..a02d747296 100644 --- a/server/certs.go +++ b/server/certs.go @@ -21,7 +21,7 @@ import ( "github.com/open-policy-agent/opa/logging" ) -func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) { +func (s *Server) getCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { s.tlsConfigMtx.RLock() defer s.tlsConfigMtx.RUnlock() return s.cert, nil @@ -72,7 +72,7 @@ func (s *Server) reloadTLSConfig(logger logging.Logger) error { } // reloadCertificatePool loads the CA cert pool from the given file and returns a new pool if the file has changed. -func reloadCertificatePool(certPoolFile string, certPoolFileHash []byte, logger logging.Logger) (*x509.CertPool, []byte, bool, error) { +func reloadCertificatePool(certPoolFile string, certPoolFileHash []byte, _ logging.Logger) (*x509.CertPool, []byte, bool, error) { certPoolHash, err := hash(certPoolFile) if err != nil { return nil, nil, false, fmt.Errorf("failed to hash CA cert pool file: %w", err) diff --git a/server/handlers/compress_test.go b/server/handlers/compress_test.go index 1da6649726..525c97957b 100644 --- a/server/handlers/compress_test.go +++ b/server/handlers/compress_test.go @@ -27,7 +27,7 @@ type compressHandlerTestScenario struct { } func executeRequest(w *httptest.ResponseRecorder, testScenario compressHandlerTestScenario) { - CompressHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + CompressHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := io.WriteString(w, requestBody) if err != nil { diff --git a/server/server.go b/server/server.go index 4e0e7930f9..7cdf3ab0fd 100644 --- a/server/server.go +++ b/server/server.go @@ -647,7 +647,7 @@ func (s *Server) getListenerForHTTPSServer(u *url.URL, h http.Handler, t httpLis // GetConfigForClient is used to ensure that a fresh config is provided containing the latest cert pool. // This is not required, but appears to be how connect time updates config should be done: // https://github.com/golang/go/issues/16066#issuecomment-250606132 - GetConfigForClient: func(info *tls.ClientHelloInfo) (*tls.Config, error) { + GetConfigForClient: func(_ *tls.ClientHelloInfo) (*tls.Config, error) { s.tlsConfigMtx.Lock() defer s.tlsConfigMtx.Unlock() @@ -2503,7 +2503,7 @@ func (s *Server) getCompiler() *ast.Compiler { return s.manager.GetCompiler() } -func (s *Server) makeRego(ctx context.Context, +func (s *Server) makeRego(_ context.Context, strictBuiltinErrors bool, txn storage.Transaction, input ast.Value, diff --git a/server/server_test.go b/server/server_test.go index 1e3d3b7213..ea0e0fab1a 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -4304,23 +4304,23 @@ type queryBindingErrStore struct { storage.PolicyNotSupported } -func (s *queryBindingErrStore) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (interface{}, error) { +func (s *queryBindingErrStore) Read(_ context.Context, _ storage.Transaction, _ storage.Path) (interface{}, error) { return nil, fmt.Errorf("expected error") } -func (*queryBindingErrStore) ListPolicies(ctx context.Context, txn storage.Transaction) ([]string, error) { +func (*queryBindingErrStore) ListPolicies(_ context.Context, _ storage.Transaction) ([]string, error) { return nil, nil } -func (queryBindingErrStore) NewTransaction(ctx context.Context, params ...storage.TransactionParams) (storage.Transaction, error) { +func (queryBindingErrStore) NewTransaction(_ context.Context, _ ...storage.TransactionParams) (storage.Transaction, error) { return nil, nil } -func (queryBindingErrStore) Commit(ctx context.Context, txn storage.Transaction) error { +func (queryBindingErrStore) Commit(_ context.Context, _ storage.Transaction) error { return nil } -func (queryBindingErrStore) Abort(ctx context.Context, txn storage.Transaction) { +func (queryBindingErrStore) Abort(_ context.Context, _ storage.Transaction) { } @@ -4881,7 +4881,7 @@ func TestMixedAddrTypes(t *testing.T) { func TestCustomRoute(t *testing.T) { router := mux.NewRouter() - router.HandleFunc("/customEndpoint", func(w http.ResponseWriter, r *http.Request) { + router.HandleFunc("/customEndpoint", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"myCustomResponse": true}`)) // ignore error }) f := newFixture(t, func(server *Server) { @@ -5405,7 +5405,7 @@ func TestCertReloading(t *testing.T) { addr string, initialCert *tls.Certificate, initialCertPool *x509.CertPool, - certFilePath, keyFilePath, caCertPath string, + certFilePath, keyFilePath, _ string, ) *Server { return New(). WithAddresses([]string{addr}). diff --git a/server/writer/writer.go b/server/writer/writer.go index 4e8f36c68f..378eb17efc 100644 --- a/server/writer/writer.go +++ b/server/writer/writer.go @@ -17,7 +17,7 @@ import ( // HTTPStatus is used to set a specific status code // Adapted from https://stackoverflow.com/questions/27711154/what-response-code-to-return-on-a-non-supported-http-method-on-rest func HTTPStatus(code int) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(code) } } diff --git a/storage/disk/disk.go b/storage/disk/disk.go index 71b06c4761..0ebd980ff2 100644 --- a/storage/disk/disk.go +++ b/storage/disk/disk.go @@ -229,7 +229,7 @@ func (w *wrap) Warningf(f string, as ...interface{}) { w.debugDo(w.l.Warn, f, as func (w *wrap) Errorf(f string, as ...interface{}) { w.debugDo(w.l.Error, f, as...) } // NewTransaction implements the storage.Store interface. -func (db *Store) NewTransaction(ctx context.Context, params ...storage.TransactionParams) (storage.Transaction, error) { +func (db *Store) NewTransaction(_ context.Context, params ...storage.TransactionParams) (storage.Transaction, error) { var write bool var context *storage.Context @@ -655,7 +655,7 @@ type handle struct { cb func(context.Context, storage.Transaction, storage.TriggerEvent) } -func (h *handle) Unregister(ctx context.Context, txn storage.Transaction) { +func (h *handle) Unregister(_ context.Context, txn storage.Transaction) { underlying, err := h.db.underlying(txn) if err != nil { panic(err) @@ -750,7 +750,7 @@ func (db *Store) init(ctx context.Context, txn *badger.Txn, partitions []storage }) } -func (db *Store) validatePartitions(ctx context.Context, txn *badger.Txn, existing metadata, partitions []storage.Path) error { +func (db *Store) validatePartitions(_ context.Context, txn *badger.Txn, existing metadata, partitions []storage.Path) error { oldPathSet := pathSet(existing.Partitions) newPathSet := pathSet(partitions) @@ -812,7 +812,7 @@ func (db *Store) validatePartitions(ctx context.Context, txn *badger.Txn, existi // // Here, we only check if it's a write transaction, for consistency with // other implementations, and do nothing. -func (db *Store) MakeDir(_ context.Context, txn storage.Transaction, path storage.Path) error { +func (db *Store) MakeDir(_ context.Context, txn storage.Transaction, _ storage.Path) error { underlying, err := db.underlying(txn) if err != nil { return err diff --git a/storage/disk/disk_test.go b/storage/disk/disk_test.go index fcc8711b26..f28a749eed 100644 --- a/storage/disk/disk_test.go +++ b/storage/disk/disk_test.go @@ -275,11 +275,11 @@ func runTruncateTest(t *testing.T, dir string) { t.Fatal(err) } - expectedIds := map[string]struct{}{"policy.rego": {}, "roles/policy.rego": {}} + expectedIDs := map[string]struct{}{"policy.rego": {}, "roles/policy.rego": {}} for _, id := range ids { - if _, ok := expectedIds[id]; !ok { - t.Fatalf("Expected list policies to contain %v but got: %v", expectedIds, id) + if _, ok := expectedIDs[id]; !ok { + t.Fatalf("Expected list policies to contain %v but got: %v", expectedIDs, id) } } diff --git a/storage/inmem/example_test.go b/storage/inmem/example_test.go index d7473fa7db..14b089ed75 100644 --- a/storage/inmem/example_test.go +++ b/storage/inmem/example_test.go @@ -2,6 +2,8 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. +//revive:disable:empty-block + package inmem_test import ( diff --git a/storage/inmem/inmem_test.go b/storage/inmem/inmem_test.go index 679fd155db..0d36aa9357 100644 --- a/storage/inmem/inmem_test.go +++ b/storage/inmem/inmem_test.go @@ -459,11 +459,11 @@ func TestTruncate(t *testing.T) { t.Fatal(err) } - expectedIds := map[string]struct{}{"policy.rego": {}, "roles/policy.rego": {}} + expectedIDs := map[string]struct{}{"policy.rego": {}, "roles/policy.rego": {}} for _, id := range ids { - if _, ok := expectedIds[id]; !ok { - t.Fatalf("Expected list policies to contain %v but got: %v", id, expectedIds) + if _, ok := expectedIDs[id]; !ok { + t.Fatalf("Expected list policies to contain %v but got: %v", id, expectedIDs) } } @@ -638,9 +638,9 @@ func TestInMemoryTxnPolicies(t *testing.T) { } ids, err := store.ListPolicies(ctx, txn) - expectedIds := []string{"test"} - if err != nil || !reflect.DeepEqual(expectedIds, ids) { - t.Fatalf("Expected list policies to return %v but got: %v (err: %v)", expectedIds, ids, err) + expectedIDs := []string{"test"} + if err != nil || !reflect.DeepEqual(expectedIDs, ids) { + t.Fatalf("Expected list policies to return %v but got: %v (err: %v)", expectedIDs, ids, err) } bs, err := store.GetPolicy(ctx, txn, "test") @@ -658,9 +658,9 @@ func TestInMemoryTxnPolicies(t *testing.T) { } ids, err = store.ListPolicies(ctx, txn) - expectedIds = []string{"test2"} - if err != nil || !reflect.DeepEqual(expectedIds, ids) { - t.Fatalf("Expected list policies to return %v but got: %v (err: %v)", expectedIds, ids, err) + expectedIDs = []string{"test2"} + if err != nil || !reflect.DeepEqual(expectedIDs, ids) { + t.Fatalf("Expected list policies to return %v but got: %v (err: %v)", expectedIDs, ids, err) } bs, err = store.GetPolicy(ctx, txn, "test2") @@ -677,9 +677,9 @@ func TestInMemoryTxnPolicies(t *testing.T) { txn = storage.NewTransactionOrDie(ctx, store) ids, err = store.ListPolicies(ctx, txn) - expectedIds = []string{"test"} - if err != nil || !reflect.DeepEqual(expectedIds, ids) { - t.Fatalf("Expected list policies to return %v but got: %v (err: %v)", expectedIds, ids, err) + expectedIDs = []string{"test"} + if err != nil || !reflect.DeepEqual(expectedIDs, ids) { + t.Fatalf("Expected list policies to return %v but got: %v (err: %v)", expectedIDs, ids, err) } if exist, err := store.GetPolicy(ctx, txn, "test2"); !storage.IsNotFound(err) { @@ -782,7 +782,7 @@ func TestInMemoryTriggersUnregister(t *testing.T) { var called bool _, err := store.Register(ctx, writeTxn, storage.TriggerConfig{ - OnCommit: func(ctx context.Context, txn storage.Transaction, evt storage.TriggerEvent) { + OnCommit: func(_ context.Context, _ storage.Transaction, evt storage.TriggerEvent) { if !evt.IsZero() { called = true } @@ -793,7 +793,7 @@ func TestInMemoryTriggersUnregister(t *testing.T) { } handle, err := store.Register(ctx, writeTxn, storage.TriggerConfig{ - OnCommit: func(ctx context.Context, txn storage.Transaction, evt storage.TriggerEvent) { + OnCommit: func(_ context.Context, _ storage.Transaction, evt storage.TriggerEvent) { if !evt.IsZero() { t.Fatalf("Callback should have been unregistered") } diff --git a/test/authz/testing.go b/test/authz/testing.go index fdd7790a8f..2690560861 100644 --- a/test/authz/testing.go +++ b/test/authz/testing.go @@ -146,7 +146,7 @@ func generateAuthzProfiles(profile DataSetProfile) []authzProfile { return profiles } -func generateAuthzProfile(profile DataSetProfile, i int) authzProfile { +func generateAuthzProfile(_ DataSetProfile, i int) authzProfile { return authzProfile{ Path: generateAuthzPath(i), Methods: []string{ diff --git a/test/e2e/certrefresh/certrefresh_test.go b/test/e2e/certrefresh/certrefresh_test.go index ae51fced9e..99f9c428b2 100644 --- a/test/e2e/certrefresh/certrefresh_test.go +++ b/test/e2e/certrefresh/certrefresh_test.go @@ -58,12 +58,12 @@ func TestMain(m *testing.M) { defer os.RemoveAll(tmp) certFile = filepath.Join(tmp, "server-cert.pem") - if err := copy(certFile0, certFile); err != nil { + if err := cpy(certFile0, certFile); err != nil { fatal(err) } certKeyFile = filepath.Join(tmp, "server-key.pem") - if err := copy(certKeyFile0, certKeyFile); err != nil { + if err := cpy(certKeyFile0, certKeyFile); err != nil { fatal(err) } @@ -140,7 +140,7 @@ func newClient() *http.Client { return &c } -func copy(from, to string) error { +func cpy(from, to string) error { src, err := os.Open(from) if err != nil { return err @@ -182,10 +182,10 @@ func getCert(t *testing.T) *x509.Certificate { func replaceCerts(t *testing.T, cert, key string) { t.Helper() - if err := copy(cert, certFile); err != nil { + if err := cpy(cert, certFile); err != nil { t.Fatal(err) } - if err := copy(key, certKeyFile); err != nil { + if err := cpy(key, certKeyFile); err != nil { t.Fatal(err) } } diff --git a/test/e2e/http/http_test.go b/test/e2e/http/http_test.go index 3a18ac9555..a2ee7d1179 100644 --- a/test/e2e/http/http_test.go +++ b/test/e2e/http/http_test.go @@ -69,7 +69,7 @@ func TestHttpSendInterQueryForceCache(t *testing.T) { for _, tc := range tests { t.Run(tc.note, func(t *testing.T) { counter := 0 - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { counter++ w.Header()["Content-Type"] = []string{"application/json"} for k, v := range tc.respHeaders { diff --git a/test/e2e/metrics/metrics_test.go b/test/e2e/metrics/metrics_test.go index e067909915..0899af5853 100644 --- a/test/e2e/metrics/metrics_test.go +++ b/test/e2e/metrics/metrics_test.go @@ -170,7 +170,7 @@ func TestRequestWithInstrumentationV1CompileAPI(t *testing.T) { assertCompileInstrumentationMetricsInMap(t, true, resp.Metrics) } -func assertCompileInstrumentationMetricsInMap(t *testing.T, includeCompile bool, metrics map[string]interface{}) { +func assertCompileInstrumentationMetricsInMap(t *testing.T, _ bool, metrics map[string]interface{}) { expectedKeys := []string{ "histogram_eval_op_plug", "timer_eval_op_plug_ns", diff --git a/test/scheduler/scheduler_test.go b/test/scheduler/scheduler_test.go index 92910bdb55..cf2ff56d4a 100644 --- a/test/scheduler/scheduler_test.go +++ b/test/scheduler/scheduler_test.go @@ -39,7 +39,7 @@ func TestScheduler(t *testing.T) { } } -func setup(ctx context.Context, t *testing.T, filename string) *rego.Rego { +func setup(_ context.Context, t *testing.T, filename string) *rego.Rego { // policy compilation c := ast.NewCompiler() diff --git a/test/wasm/cmd/wasm-rego-testgen/main.go b/test/wasm/cmd/wasm-rego-testgen/main.go index a286288a24..e232de83a7 100644 --- a/test/wasm/cmd/wasm-rego-testgen/main.go +++ b/test/wasm/cmd/wasm-rego-testgen/main.go @@ -238,7 +238,7 @@ func main() { command := &cobra.Command{ Use: executable, Short: executable, - RunE: func(_ *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { return run(params) }, } diff --git a/tester/runner.go b/tester/runner.go index b489cea03a..8fccea82cd 100644 --- a/tester/runner.go +++ b/tester/runner.go @@ -39,7 +39,7 @@ func Run(ctx context.Context, paths ...string) ([]*Result, error) { // RunWithFilter executes all test cases found under files in path. The filter // will be applied to exclude files that should not be included. -func RunWithFilter(ctx context.Context, filter loader.Filter, paths ...string) ([]*Result, error) { +func RunWithFilter(ctx context.Context, _ loader.Filter, paths ...string) ([]*Result, error) { modules, store, err := Load(paths, nil) if err != nil { return nil, err diff --git a/topdown/bindings.go b/topdown/bindings.go index 7621dac529..30a8ac5ec4 100644 --- a/topdown/bindings.go +++ b/topdown/bindings.go @@ -43,7 +43,7 @@ func (u *bindings) Iter(caller *bindings, iter func(*ast.Term, *ast.Term) error) var err error - u.values.Iter(func(k *ast.Term, v value) bool { + u.values.Iter(func(k *ast.Term, _ value) bool { if err != nil { return true } diff --git a/topdown/copypropagation/copypropagation.go b/topdown/copypropagation/copypropagation.go index 4c6b8c42c7..8824d19bd2 100644 --- a/topdown/copypropagation/copypropagation.go +++ b/topdown/copypropagation/copypropagation.go @@ -222,11 +222,11 @@ func (p *CopyPropagator) plugBindings(pctx *plugContext, expr *ast.Expr) *ast.Ex // errors unreachable. x, err := ast.Transform(xform, expr.Copy()) - if expr, ok := x.(*ast.Expr); !ok || err != nil { + expr, ok := x.(*ast.Expr) + if !ok || err != nil { panic("unreachable") - } else { - return expr } + return expr } type bindingPlugTransform struct { diff --git a/topdown/eval.go b/topdown/eval.go index f0ce3b2a60..51147dc138 100644 --- a/topdown/eval.go +++ b/topdown/eval.go @@ -1096,10 +1096,10 @@ func (e *eval) biunifyComprehension(a, b *ast.Term, b1, b2 *bindings, swap bool, return err } else if value != nil { return e.biunify(value, b, b1, b2, iter) - } else { - e.instr.counterIncr(evalOpComprehensionCacheMiss) } + e.instr.counterIncr(evalOpComprehensionCacheMiss) + switch a := a.Value.(type) { case *ast.ArrayComprehension: return e.biunifyComprehensionArray(a, b, b1, b2, iter) @@ -2560,7 +2560,7 @@ func (e evalVirtualPartial) evalOneRulePreUnify(iter unifyIterator, rule *ast.Ru } // Walk the dynamic portion of rule ref and key to unify vars - err := child.biunifyRuleHead(e.pos+1, e.ref, rule, e.bindings, child.bindings, func(pos int) error { + err := child.biunifyRuleHead(e.pos+1, e.ref, rule, e.bindings, child.bindings, func(_ int) error { defined = true return child.eval(func(child *eval) error { @@ -2648,7 +2648,7 @@ func (e evalVirtualPartial) evalOneRulePostUnify(iter unifyIterator, rule *ast.R err := child.eval(func(child *eval) error { defined = true - return e.e.biunifyRuleHead(e.pos+1, e.ref, rule, e.bindings, child.bindings, func(pos int) error { + return e.e.biunifyRuleHead(e.pos+1, e.ref, rule, e.bindings, child.bindings, func(_ int) error { return e.evalOneRuleContinue(iter, rule, child) }) }) @@ -2724,7 +2724,7 @@ func (e evalVirtualPartial) partialEvalSupport(iter unifyIterator) error { return e.e.saveUnify(term, e.rterm, e.bindings, e.rbindings, iter) } -func (e evalVirtualPartial) partialEvalSupportRule(rule *ast.Rule, path ast.Ref) (bool, error) { +func (e evalVirtualPartial) partialEvalSupportRule(rule *ast.Rule, _ ast.Ref) (bool, error) { child := e.e.child(rule.Body) child.traceEnter(rule) diff --git a/topdown/example_test.go b/topdown/example_test.go index 5feeee764b..0a007a4abd 100644 --- a/topdown/example_test.go +++ b/topdown/example_test.go @@ -2,6 +2,8 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. +//revive:disable:empty-block + package topdown_test import ( diff --git a/topdown/http.go b/topdown/http.go index 188c79aa1d..9d01bc14b2 100644 --- a/topdown/http.go +++ b/topdown/http.go @@ -346,7 +346,7 @@ func useSocket(rawURL string, tlsConfig *tls.Config) (bool, string, *http.Transp u.RawQuery = v.Encode() tr := http.DefaultTransport.(*http.Transport).Clone() - tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { return http.DefaultTransport.(*http.Transport).DialContext(ctx, "unix", socket) } tr.TLSClientConfig = tlsConfig diff --git a/topdown/http_test.go b/topdown/http_test.go index aea6f2de45..7521c8e1e8 100644 --- a/topdown/http_test.go +++ b/topdown/http_test.go @@ -53,7 +53,7 @@ func TestHTTPGetRequest(t *testing.T) { people = append(people, Person{ID: "1", Firstname: "John"}) // test server - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { headers := w.Header() headers["test-header"] = []string{"test-value"} w.WriteHeader(http.StatusOK) @@ -107,7 +107,7 @@ func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) { people = append(people, Person{ID: "1", Firstname: "John"}) // test server - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _ = json.NewEncoder(w).Encode(people) })) @@ -2299,7 +2299,7 @@ func getTestServer() (baseURL string, teardownFn func()) { mux := http.NewServeMux() ts := httptest.NewServer(mux) - mux.HandleFunc("/test", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("/test", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) @@ -2314,7 +2314,7 @@ func getTLSTestServer() (ts *httptest.Server) { mux := http.NewServeMux() ts = httptest.NewUnstartedServer(mux) - mux.HandleFunc("/test", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("/test", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) @@ -2331,7 +2331,7 @@ func getTLSTestServer() (ts *httptest.Server) { _, _ = w.Write(js) }) - mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) @@ -3361,7 +3361,7 @@ func getAllRequests(ch chan *http.Request) []*http.Request { func TestHTTPSendMetrics(t *testing.T) { // run test server - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) @@ -3565,7 +3565,7 @@ func TestHTTPGetRequestAllowNet(t *testing.T) { body := map[string]bool{"ok": true} // test server - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _ = json.NewEncoder(w).Encode(body) })) diff --git a/topdown/net_test.go b/topdown/net_test.go index 41a18a433e..14144f46df 100644 --- a/topdown/net_test.go +++ b/topdown/net_test.go @@ -202,7 +202,7 @@ func TestNetLookupIPAddr(t *testing.T) { Capabilities: capabilities, } srv.PatchNet(resolv) - err := builtinLookupIPAddr(bctx, []*ast.Term{ast.StringTerm(addr)}, func(act *ast.Term) error { + err := builtinLookupIPAddr(bctx, []*ast.Term{ast.StringTerm(addr)}, func(_ *ast.Term) error { t.Fatal("expected not to be called") return nil }) diff --git a/topdown/parse_bytes.go b/topdown/parse_bytes.go index 9d8fe50681..0cd4bc193a 100644 --- a/topdown/parse_bytes.go +++ b/topdown/parse_bytes.go @@ -45,7 +45,7 @@ var ( errBytesValueIncludesSpaces = parseNumBytesError("spaces not allowed in resource strings") ) -func builtinNumBytes(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinNumBytes(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { var m big.Float raw, err := builtins.StringOperand(operands[0].Value, 1) diff --git a/topdown/providers.go b/topdown/providers.go index 1affac51c9..77db917982 100644 --- a/topdown/providers.go +++ b/topdown/providers.go @@ -86,7 +86,7 @@ func validateAWSAuthParameters(o ast.Object) error { return nil } -func builtinAWSSigV4SignReq(ctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinAWSSigV4SignReq(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { // Request object. reqObj, err := builtins.ObjectOperand(operands[0].Value, 1) if err != nil { diff --git a/topdown/reachable.go b/topdown/reachable.go index 9cb15d51e3..8d61018e76 100644 --- a/topdown/reachable.go +++ b/topdown/reachable.go @@ -31,7 +31,7 @@ func numberOfEdges(collection *ast.Term) int { return 0 } -func builtinReachable(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinReachable(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { // Error on wrong types for args. graph, err := builtins.ObjectOperand(operands[0].Value, 1) if err != nil { @@ -109,7 +109,7 @@ func pathBuilder(graph ast.Object, root *ast.Term, path []*ast.Term, edgeRslt as } -func builtinReachablePaths(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinReachablePaths(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { var traceResult = ast.NewSet() // Error on wrong types for args. graph, err := builtins.ObjectOperand(operands[0].Value, 1) diff --git a/topdown/semver.go b/topdown/semver.go index ab5aed3eec..7bb7b9c183 100644 --- a/topdown/semver.go +++ b/topdown/semver.go @@ -12,7 +12,7 @@ import ( "github.com/open-policy-agent/opa/topdown/builtins" ) -func builtinSemVerCompare(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinSemVerCompare(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { versionStringA, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err @@ -37,7 +37,7 @@ func builtinSemVerCompare(bctx BuiltinContext, operands []*ast.Term, iter func(* return iter(ast.IntNumberTerm(result)) } -func builtinSemVerIsValid(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinSemVerIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { versionString, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return iter(ast.BooleanTerm(false)) diff --git a/topdown/strings.go b/topdown/strings.go index d5baa31972..57f8eab9ca 100644 --- a/topdown/strings.go +++ b/topdown/strings.go @@ -16,7 +16,7 @@ import ( "github.com/open-policy-agent/opa/topdown/builtins" ) -func builtinAnyPrefixMatch(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinAnyPrefixMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { a, b := operands[0].Value, operands[1].Value var strs []string @@ -50,7 +50,7 @@ func builtinAnyPrefixMatch(bctx BuiltinContext, operands []*ast.Term, iter func( return iter(ast.BooleanTerm(anyStartsWithAny(strs, prefixes))) } -func builtinAnySuffixMatch(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinAnySuffixMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { a, b := operands[0].Value, operands[1].Value var strsReversed []string @@ -384,12 +384,12 @@ func builtinReplace(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) return err } - new, err := builtins.StringOperand(operands[2].Value, 3) + n, err := builtins.StringOperand(operands[2].Value, 3) if err != nil { return err } - return iter(ast.StringTerm(strings.Replace(string(s), string(old), string(new), -1))) + return iter(ast.StringTerm(strings.Replace(string(s), string(old), string(n), -1))) } func builtinReplaceN(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { diff --git a/topdown/tokens.go b/topdown/tokens.go index b69f3f2d24..4d5a520f26 100644 --- a/topdown/tokens.go +++ b/topdown/tokens.go @@ -233,7 +233,7 @@ func builtinJWTVerifyRSA(a ast.Value, b ast.Value, hasher func() hash.Hash, veri } // Implements ES256 JWT signature verification. -func builtinJWTVerifyES256(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinJWTVerifyES256(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { result, err := builtinJWTVerify(operands[0].Value, operands[1].Value, sha256.New, verifyES) if err == nil { return iter(ast.NewTerm(result)) @@ -242,7 +242,7 @@ func builtinJWTVerifyES256(bctx BuiltinContext, operands []*ast.Term, iter func( } // Implements ES384 JWT signature verification -func builtinJWTVerifyES384(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinJWTVerifyES384(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { result, err := builtinJWTVerify(operands[0].Value, operands[1].Value, sha512.New384, verifyES) if err == nil { return iter(ast.NewTerm(result)) @@ -251,7 +251,7 @@ func builtinJWTVerifyES384(bctx BuiltinContext, operands []*ast.Term, iter func( } // Implements ES512 JWT signature verification -func builtinJWTVerifyES512(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinJWTVerifyES512(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { result, err := builtinJWTVerify(operands[0].Value, operands[1].Value, sha512.New, verifyES) if err == nil { return iter(ast.NewTerm(result)) @@ -413,7 +413,7 @@ func builtinJWTVerify(a ast.Value, b ast.Value, hasher func() hash.Hash, verify } // Implements HS256 (secret) JWT signature verification -func builtinJWTVerifyHS256(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinJWTVerifyHS256(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { // Decode the JSON Web Token token, err := decodeJWT(operands[0].Value) if err != nil { @@ -442,7 +442,7 @@ func builtinJWTVerifyHS256(bctx BuiltinContext, operands []*ast.Term, iter func( } // Implements HS384 JWT signature verification -func builtinJWTVerifyHS384(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinJWTVerifyHS384(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { // Decode the JSON Web Token token, err := decodeJWT(operands[0].Value) if err != nil { @@ -471,7 +471,7 @@ func builtinJWTVerifyHS384(bctx BuiltinContext, operands []*ast.Term, iter func( } // Implements HS512 JWT signature verification -func builtinJWTVerifyHS512(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinJWTVerifyHS512(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { // Decode the JSON Web Token token, err := decodeJWT(operands[0].Value) if err != nil { @@ -793,7 +793,7 @@ func verifyRSAPSS(key interface{}, hash crypto.Hash, digest []byte, signature [] return nil } -func verifyECDSA(key interface{}, hash crypto.Hash, digest []byte, signature []byte) (err error) { +func verifyECDSA(key interface{}, _ crypto.Hash, digest []byte, signature []byte) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("ECDSA signature verification error: %v", r) @@ -1048,10 +1048,9 @@ func builtinJWTDecodeVerify(bctx BuiltinContext, operands []*ast.Term, iter func // Nested JWT, go round again with payload as first argument a = p.Value continue - } else { - // Non-nested JWT (or we've reached the bottom of the nesting). - break } + // Non-nested JWT (or we've reached the bottom of the nesting). + break } payload, err := extractJSONObject(string(p.Value.(ast.String))) if err != nil { diff --git a/topdown/tokens_test.go b/topdown/tokens_test.go index d3f482cb00..7d54b2d9a4 100644 --- a/topdown/tokens_test.go +++ b/topdown/tokens_test.go @@ -617,7 +617,7 @@ func TestTopdownJWTVerifyOnlyVerifiesUsingApplicableKeys(t *testing.T) { token := ast.MustInterfaceToValue(fmt.Sprintf("%s.%s.%s", header, payload, signature)) verifyCalls := 0 - verifier := func(publicKey interface{}, digest []byte, signature []byte) error { + verifier := func(_ interface{}, _ []byte, _ []byte) error { verifyCalls++ return fmt.Errorf("fail") } diff --git a/topdown/topdown_test.go b/topdown/topdown_test.go index 3a381700c5..f7955c39e5 100644 --- a/topdown/topdown_test.go +++ b/topdown/topdown_test.go @@ -232,7 +232,7 @@ func TestTopDownQueryCancellation(t *testing.T) { func TestTopDownQueryCancellationEvery(t *testing.T) { ctx := context.Background() - module := func(ev ast.Every, extra ...interface{}) *ast.Module { + module := func(ev ast.Every, _ ...interface{}) *ast.Module { t.Helper() m := ast.MustParseModule(`package test p { true }`) @@ -1735,7 +1735,7 @@ func (*contextPropagationStore) Truncate(context.Context, storage.Transaction, s return nil } -func (m *contextPropagationStore) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (interface{}, error) { +func (m *contextPropagationStore) Read(ctx context.Context, _ storage.Transaction, _ storage.Path) (interface{}, error) { val := ctx.Value(contextPropagationMock{}) m.calls = append(m.calls, val) return nil, nil @@ -1795,7 +1795,7 @@ func (*astStore) Truncate(context.Context, storage.Transaction, storage.Transact return nil } -func (a *astStore) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (interface{}, error) { +func (a *astStore) Read(_ context.Context, _ storage.Transaction, path storage.Path) (interface{}, error) { if path.String() == a.path { return a.value, nil } diff --git a/types/decode.go b/types/decode.go index 4e123384a0..a6bd9ea030 100644 --- a/types/decode.go +++ b/types/decode.go @@ -77,10 +77,10 @@ func Unmarshal(bs []byte) (result Type, err error) { } } case typeAny: - var any rawunion - if err = util.UnmarshalJSON(bs, &any); err == nil { + var union rawunion + if err = util.UnmarshalJSON(bs, &union); err == nil { var of []Type - if of, err = unmarshalSlice(any.Of); err == nil { + if of, err = unmarshalSlice(union.Of); err == nil { result = NewAny(of...) } } diff --git a/types/types.go b/types/types.go index a4b87cd554..2a050927dd 100644 --- a/types/types.go +++ b/types/types.go @@ -938,8 +938,8 @@ func Compare(a, b Type) int { // Contains returns true if a is a superset or equal to b. func Contains(a, b Type) bool { - if any, ok := unwrap(a).(Any); ok { - return any.Contains(b) + if x, ok := unwrap(a).(Any); ok { + return x.Contains(b) } return Compare(a, b) == 0 } @@ -994,8 +994,8 @@ func Select(a Type, x interface{}) Type { if Compare(a.of, tpe) == 0 { return a.of } - if any, ok := a.of.(Any); ok { - if any.Contains(tpe) { + if x, ok := a.of.(Any); ok { + if x.Contains(tpe) { return tpe } }