diff --git a/ast/compare.go b/ast/compare.go index d36078e338..5e617e992f 100644 --- a/ast/compare.go +++ b/ast/compare.go @@ -34,6 +34,6 @@ import ( // Sets are considered equal if and only if the symmetric difference of a and b // is empty. // Other comparisons are consistent but not defined. -func Compare(a, b interface{}) int { +func Compare(a, b any) int { return v1.Compare(a, b) } diff --git a/ast/errors.go b/ast/errors.go index 0cb8ee28f7..722cfc0fb7 100644 --- a/ast/errors.go +++ b/ast/errors.go @@ -41,6 +41,6 @@ type ErrorDetails = v1.ErrorDetails type Error = v1.Error // NewError returns a new Error object. -func NewError(code string, loc *Location, f string, a ...interface{}) *Error { +func NewError(code string, loc *Location, f string, a ...any) *Error { return v1.NewError(code, loc, f, a...) } diff --git a/ast/policy.go b/ast/policy.go index 3da7fdd636..5055e8f23f 100644 --- a/ast/policy.go +++ b/ast/policy.go @@ -211,7 +211,7 @@ func NewBody(exprs ...*Expr) Body { } // NewExpr returns a new Expr object. -func NewExpr(terms interface{}) *Expr { +func NewExpr(terms any) *Expr { return v1.NewExpr(terms) } @@ -222,7 +222,7 @@ func NewBuiltinExpr(terms ...*Term) *Expr { } // Copy returns a deep copy of the AST node x. If x is not an AST node, x is returned unmodified. -func Copy(x interface{}) interface{} { +func Copy(x any) any { return v1.Copy(x) } diff --git a/ast/pretty.go b/ast/pretty.go index f2b8104e0a..84e42f9aec 100644 --- a/ast/pretty.go +++ b/ast/pretty.go @@ -13,6 +13,6 @@ import ( // Pretty writes a pretty representation of the AST rooted at x to w. // // This is function is intended for debug purposes when inspecting ASTs. -func Pretty(w io.Writer, x interface{}) { +func Pretty(w io.Writer, x any) { v1.Pretty(w, x) } diff --git a/ast/strings.go b/ast/strings.go index ef9354bf78..c2c81de8b7 100644 --- a/ast/strings.go +++ b/ast/strings.go @@ -9,6 +9,6 @@ import ( ) // TypeName returns a human readable name for the AST element type. -func TypeName(x interface{}) string { +func TypeName(x any) string { return v1.TypeName(x) } diff --git a/ast/term.go b/ast/term.go index a5d146ea27..202355070f 100644 --- a/ast/term.go +++ b/ast/term.go @@ -30,7 +30,7 @@ func NewLocation(text []byte, file string, row int, col int) *Location { type Value = v1.Value // InterfaceToValue converts a native Go value x to a Value. -func InterfaceToValue(x interface{}) (Value, error) { +func InterfaceToValue(x any) (Value, error) { return v1.InterfaceToValue(x) } @@ -40,7 +40,7 @@ func ValueFromReader(r io.Reader) (Value, error) { } // As converts v into a Go native type referred to by x. -func As(v Value, x interface{}) error { +func As(v Value, x any) error { return v1.As(v, x) } @@ -62,13 +62,13 @@ func IsUnknownValueErr(err error) bool { // ValueToInterface returns the Go representation of an AST value. The AST // value should not contain any values that require evaluation (e.g., vars, // comprehensions, etc.) -func ValueToInterface(v Value, resolver Resolver) (interface{}, error) { +func ValueToInterface(v Value, resolver Resolver) (any, error) { return v1.ValueToInterface(v, resolver) } // JSON returns the JSON representation of v. The value must not contain any // refs or terms that require evaluation (e.g., vars, comprehensions, etc.) -func JSON(v Value) (interface{}, error) { +func JSON(v Value) (any, error) { return v1.JSON(v) } @@ -77,7 +77,7 @@ type JSONOpt = v1.JSONOpt // JSONWithOpt returns the JSON representation of v. The value must not contain any // refs or terms that require evaluation (e.g., vars, comprehensions, etc.) -func JSONWithOpt(v Value, opt JSONOpt) (interface{}, error) { +func JSONWithOpt(v Value, opt JSONOpt) (any, error) { return v1.JSONWithOpt(v, opt) } @@ -85,14 +85,14 @@ func JSONWithOpt(v Value, opt JSONOpt) (interface{}, error) { // refs or terms that require evaluation (e.g., vars, comprehensions, etc.) If // the conversion fails, this function will panic. This function is mostly for // test purposes. -func MustJSON(v Value) interface{} { +func MustJSON(v Value) any { return v1.MustJSON(v) } // MustInterfaceToValue converts a native Go value x to a Value. If the // conversion fails, this function will panic. This function is mostly for test // purposes. -func MustInterfaceToValue(x interface{}) Value { +func MustInterfaceToValue(x any) Value { return v1.MustInterfaceToValue(x) } @@ -115,17 +115,17 @@ func IsComprehension(x Value) bool { } // ContainsRefs returns true if the Value v contains refs. -func ContainsRefs(v interface{}) bool { +func ContainsRefs(v any) bool { return v1.ContainsRefs(v) } // ContainsComprehensions returns true if the Value v contains comprehensions. -func ContainsComprehensions(v interface{}) bool { +func ContainsComprehensions(v any) bool { return v1.ContainsComprehensions(v) } // ContainsClosures returns true if the Value v contains closures. -func ContainsClosures(v interface{}) bool { +func ContainsClosures(v any) bool { return v1.ContainsClosures(v) } @@ -256,7 +256,7 @@ func ObjectTerm(o ...[2]*Term) *Term { return v1.ObjectTerm(o...) } -func LazyObject(blob map[string]interface{}) Object { +func LazyObject(blob map[string]any) Object { return v1.LazyObject(blob) } diff --git a/ast/transform.go b/ast/transform.go index cfb137813f..8c03c48663 100644 --- a/ast/transform.go +++ b/ast/transform.go @@ -16,22 +16,22 @@ type Transformer = v1.Transformer // Transform iterates the AST and calls the Transform function on the // Transformer t for x before recursing. -func Transform(t Transformer, x interface{}) (interface{}, error) { +func Transform(t Transformer, x any) (any, error) { return v1.Transform(t, x) } // TransformRefs calls the function f on all references under x. -func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, error) { +func TransformRefs(x any, f func(Ref) (Value, error)) (any, error) { return v1.TransformRefs(x, f) } // TransformVars calls the function f on all vars under x. -func TransformVars(x interface{}, f func(Var) (Value, error)) (interface{}, error) { +func TransformVars(x any, f func(Var) (Value, error)) (any, error) { return v1.TransformVars(x, f) } // TransformComprehensions calls the functio nf on all comprehensions under x. -func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) (interface{}, error) { +func TransformComprehensions(x any, f func(any) (Value, error)) (any, error) { return v1.TransformComprehensions(x, f) } @@ -41,6 +41,6 @@ type GenericTransformer = v1.GenericTransformer // NewGenericTransformer returns a new GenericTransformer that will transform // AST nodes using the function f. -func NewGenericTransformer(f func(x interface{}) (interface{}, error)) *GenericTransformer { +func NewGenericTransformer(f func(x any) (any, error)) *GenericTransformer { return v1.NewGenericTransformer(f) } diff --git a/ast/visit.go b/ast/visit.go index 94823c6cc7..f4f2459ecc 100644 --- a/ast/visit.go +++ b/ast/visit.go @@ -21,68 +21,68 @@ type BeforeAndAfterVisitor = v1.BeforeAndAfterVisitor // Walk iterates the AST by calling the Visit function on the Visitor // v for x before recursing. // Deprecated: use GenericVisitor.Walk -func Walk(v Visitor, x interface{}) { +func Walk(v Visitor, x any) { v1.Walk(v, x) } // WalkBeforeAndAfter iterates the AST by calling the Visit function on the // Visitor v for x before recursing. // Deprecated: use GenericVisitor.Walk -func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x interface{}) { +func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any) { v1.WalkBeforeAndAfter(v, x) } // WalkVars calls the function f on all vars under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkVars(x interface{}, f func(Var) bool) { +func WalkVars(x any, f func(Var) bool) { v1.WalkVars(x, f) } // WalkClosures calls the function f on all closures under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkClosures(x interface{}, f func(interface{}) bool) { +func WalkClosures(x any, f func(any) bool) { v1.WalkClosures(x, f) } // WalkRefs calls the function f on all references under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkRefs(x interface{}, f func(Ref) bool) { +func WalkRefs(x any, f func(Ref) bool) { v1.WalkRefs(x, f) } // WalkTerms calls the function f on all terms under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkTerms(x interface{}, f func(*Term) bool) { +func WalkTerms(x any, f func(*Term) bool) { v1.WalkTerms(x, f) } // WalkWiths calls the function f on all with modifiers under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkWiths(x interface{}, f func(*With) bool) { +func WalkWiths(x any, f func(*With) bool) { v1.WalkWiths(x, f) } // WalkExprs calls the function f on all expressions under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkExprs(x interface{}, f func(*Expr) bool) { +func WalkExprs(x any, f func(*Expr) bool) { v1.WalkExprs(x, f) } // WalkBodies calls the function f on all bodies under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkBodies(x interface{}, f func(Body) bool) { +func WalkBodies(x any, f func(Body) bool) { v1.WalkBodies(x, f) } // WalkRules calls the function f on all rules under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkRules(x interface{}, f func(*Rule) bool) { +func WalkRules(x any, f func(*Rule) bool) { v1.WalkRules(x, f) } // WalkNodes calls the function f on all nodes under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkNodes(x interface{}, f func(Node) bool) { +func WalkNodes(x any, f func(Node) bool) { v1.WalkNodes(x, f) } @@ -93,7 +93,7 @@ type GenericVisitor = v1.GenericVisitor // NewGenericVisitor returns a new GenericVisitor that will invoke the function // f on AST nodes. -func NewGenericVisitor(f func(x interface{}) bool) *GenericVisitor { +func NewGenericVisitor(f func(x any) bool) *GenericVisitor { return v1.NewGenericVisitor(f) } @@ -105,7 +105,7 @@ type BeforeAfterVisitor = v1.BeforeAfterVisitor // NewBeforeAfterVisitor returns a new BeforeAndAfterVisitor that // will invoke the functions before and after AST nodes. -func NewBeforeAfterVisitor(before func(x interface{}) bool, after func(x interface{})) *BeforeAfterVisitor { +func NewBeforeAfterVisitor(before func(x any) bool, after func(x any)) *BeforeAfterVisitor { return v1.NewBeforeAfterVisitor(before, after) } diff --git a/bundle/store.go b/bundle/store.go index d73cc77422..cf20b506c9 100644 --- a/bundle/store.go +++ b/bundle/store.go @@ -70,7 +70,7 @@ func ReadBundleRevisionFromStore(ctx context.Context, store storage.Store, txn s // ReadBundleMetadataFromStore returns the metadata in the specified bundle. // If the bundle is not activated, this function will return // storage NotFound error. -func ReadBundleMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (map[string]interface{}, error) { +func ReadBundleMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (map[string]any, error) { return v1.ReadBundleMetadataFromStore(ctx, store, txn, name) } diff --git a/cmd/bench.go b/cmd/bench.go index 68be3904da..07f0901ac2 100644 --- a/cmd/bench.go +++ b/cmd/bench.go @@ -165,7 +165,7 @@ func benchMain(args []string, params benchmarkCommandParams, w io.Writer, r benc return 1, errRender } - resultHandler := rego.GenerateJSON(func(*ast.Term, *rego.EvalContext) (interface{}, error) { + resultHandler := rego.GenerateJSON(func(*ast.Term, *rego.EvalContext) (any, error) { // Do nothing with the result, as we are only interested in benchmarking evaluation — // not the potentially slow process of rendering the result. // Undefined / empty results will still be handled normally (fail the benchmark unless --fail @@ -380,7 +380,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams, } // Wrap input in "input" attribute - inp := make(map[string]interface{}) + inp := make(map[string]any) if input != nil { if err = util.Unmarshal(input, &inp); err != nil { @@ -388,7 +388,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams, } } - body := map[string]interface{}{"input": inp} + body := map[string]any{"input": inp} var path string if params.partial { @@ -426,7 +426,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams, return nil } -func runE2E(params benchmarkCommandParams, url string, input map[string]interface{}) (testing.BenchmarkResult, error) { +func runE2E(params benchmarkCommandParams, url string, input map[string]any) (testing.BenchmarkResult, error) { hist := metrics.New() var benchErr error @@ -482,7 +482,7 @@ func runE2E(params benchmarkCommandParams, url string, input map[string]interfac return br, benchErr } -func e2eQuery(params benchmarkCommandParams, url string, input map[string]interface{}) (types.MetricsV1, error) { +func e2eQuery(params benchmarkCommandParams, url string, input map[string]any) (types.MetricsV1, error) { reqBody, err := json.Marshal(input) if err != nil { @@ -507,7 +507,7 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf } if resp.StatusCode != 200 { - var e map[string]interface{} + var e map[string]any if err = util.Unmarshal(body, &e); err != nil { return nil, err } @@ -555,7 +555,7 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf i := *result.Result - peResult, ok := i.(map[string]interface{}) + peResult, ok := i.(map[string]any) if !ok { return nil, errors.New("invalid result for compile response") } @@ -565,7 +565,7 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf } if val, ok := peResult["queries"]; ok { - queries, ok := val.([]interface{}) + queries, ok := val.([]any) if !ok { return nil, errors.New("invalid result for output of partial evaluation") } @@ -666,11 +666,11 @@ func prettyFormatFloat(x float64) string { return fmt.Sprintf(format, x) } -func reportMetrics(b *testing.B, m map[string]interface{}) { +func reportMetrics(b *testing.B, m map[string]any) { // For each histogram add their values to the benchmark results. // Note: If there are many metrics this gets super verbose. for histName, metric := range m { - histValues, ok := metric.(map[string]interface{}) + histValues, ok := metric.(map[string]any) if !ok { continue } diff --git a/cmd/bench_test.go b/cmd/bench_test.go index 09c624bf27..8e48e07e73 100644 --- a/cmd/bench_test.go +++ b/cmd/bench_test.go @@ -1211,7 +1211,7 @@ a contains 4 if { RegoVersion: &tc.bundleRegoVersion, FileRegoVersions: tc.bundleFileRegoVersions, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, } for k, v := range tc.modules { b.Modules = append(b.Modules, bundle.ModuleFile{ @@ -1550,9 +1550,9 @@ func testBundle() bundle.Bundle { return bundle.Bundle{ Manifest: bundle.Manifest{}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": 42, }, }, diff --git a/cmd/eval.go b/cmd/eval.go index f78401b37a..4d5d4c9164 100644 --- a/cmd/eval.go +++ b/cmd/eval.go @@ -392,7 +392,7 @@ func eval(args []string, params evalCommandParams, w io.Writer) (bool, error) { results := make([]pr.Output, ectx.params.count) profiles := make([][]profiler.ExprStats, ectx.params.count) - timers := make([]map[string]interface{}, ectx.params.count) + timers := make([]map[string]any, ectx.params.count) for i := range ectx.params.count { results[i] = evalOnce(ctx, ectx) @@ -408,7 +408,7 @@ func eval(args []string, params evalCommandParams, w io.Writer) (bool, error) { result.Profile = nil result.Metrics = nil result.AggregatedProfile = profiler.AggregateProfiles(profiles...) - timersAggregated := map[string]interface{}{} + timersAggregated := map[string]any{} for name := range timers[0] { var vals []int64 for _, t := range timers { @@ -632,7 +632,7 @@ func setupEval(args []string, params evalCommandParams) (*evalContext, error) { return nil, err } if inputBytes != nil { - var input interface{} + var input any err := util.Unmarshal(inputBytes, &input) if err != nil { return nil, fmt.Errorf("unable to parse input: %s", err.Error()) @@ -862,7 +862,7 @@ type astLocationResetVisitor struct { n int } -func (vis *astLocationResetVisitor) visit(x interface{}) bool { +func (vis *astLocationResetVisitor) visit(x any) bool { if expr, ok := x.(*ast.Expr); ok { if expr.Location != nil { cpy := *expr.Location diff --git a/cmd/eval_test.go b/cmd/eval_test.go index 980deb577f..74f2bc34c3 100755 --- a/cmd/eval_test.go +++ b/cmd/eval_test.go @@ -1154,10 +1154,10 @@ func TestEvalWithStrictBuiltinErrors(t *testing.T) { func assertResultSet(t *testing.T, rs rego.ResultSet, expected string) { t.Helper() - result := []interface{}{} + result := []any{} for i := range rs { - values := []interface{}{} + values := []any{} for j := range rs[i].Expressions { values = append(values, rs[i].Expressions[j].Value) } @@ -1186,7 +1186,7 @@ func TestEvalErrorJSONOutput(t *testing.T) { // Only check that it *can* be loaded as valid JSON, and that the errors // are populated. - var output map[string]interface{} + var output map[string]any if err := util.NewJSONDecoder(&buf).Decode(&output); err != nil { t.Fatal(err) @@ -1250,10 +1250,10 @@ func TestEvalDebugTraceJSONOutput(t *testing.T) { var output struct { Explanation []struct { - Op string `json:"Op"` - Node interface{} `json:"Node"` - Location *ast.Location `json:"Location"` - Locals []map[string]interface{} `json:"Locals"` + Op string `json:"Op"` + Node any `json:"Node"` + Location *ast.Location `json:"Location"` + Locals []map[string]any `json:"Locals"` LocalMetadata map[string]struct { Name string `json:"name"` } `json:"LocalMetadata"` @@ -1802,7 +1802,7 @@ func TestResetExprLocations(t *testing.T) { var exp int - vis := ast.NewGenericVisitor(func(x interface{}) bool { + vis := ast.NewGenericVisitor(func(x any) bool { if expr, ok := x.(*ast.Expr); ok { if expr.Location.Row != exp { t.Fatalf("Expected %v to have row %v but got %v", expr, exp, expr.Location.Row) @@ -2178,7 +2178,7 @@ func TestEvalDiscardProfilerOutput(t *testing.T) { t.Fatalf("unexpected error: %s", err) } - var output map[string]interface{} + var output map[string]any if err := util.NewJSONDecoder(&buf).Decode(&output); err != nil { t.Fatal(err) } diff --git a/cmd/exec.go b/cmd/exec.go index 8c27be5ebd..dd7adcfb00 100644 --- a/cmd/exec.go +++ b/cmd/exec.go @@ -65,7 +65,7 @@ e.g., opa exec --decision /foo/bar/baz ... params.Paths = args params.BundlePaths = bundlePaths.v if err := runExec(params); err != nil { - logging.Get().WithFields(map[string]interface{}{"err": err}).Error("Unexpected error.") + logging.Get().WithFields(map[string]any{"err": err}).Error("Unexpected error.") os.Exit(1) } }, @@ -204,7 +204,7 @@ func setupConfig(file string, overrides []string, overrideFiles []string, bundle return nil, err } - var root map[string]interface{} + var root map[string]any if err := util.Unmarshal(bs, &root); err != nil { return nil, err @@ -221,39 +221,39 @@ func setupConfig(file string, overrides []string, overrideFiles []string, bundle // that all plugins will inherit the trigger mode by default. If the plugin // trigger mode is explicitly set to something other than 'manual' this will // result in a configuration error. - if cfg, ok := root["discovery"].(map[string]interface{}); ok { + if cfg, ok := root["discovery"].(map[string]any); ok { cfg["trigger"] = "manual" } - if cfg, ok := root["bundles"].(map[string]interface{}); ok { + if cfg, ok := root["bundles"].(map[string]any); ok { for _, x := range cfg { - if bcfg, ok := x.(map[string]interface{}); ok { + if bcfg, ok := x.(map[string]any); ok { bcfg["trigger"] = "manual" } } } - if cfg, ok := root["decision_logs"].(map[string]interface{}); ok { - if rcfg, ok := cfg["reporting"].(map[string]interface{}); ok { + if cfg, ok := root["decision_logs"].(map[string]any); ok { + if rcfg, ok := cfg["reporting"].(map[string]any); ok { rcfg["trigger"] = "manual" } } - if cfg, ok := root["status"].(map[string]interface{}); ok { + if cfg, ok := root["status"].(map[string]any); ok { cfg["trigger"] = "manual" } return json.Marshal(root) } -func injectExplicitBundles(root map[string]interface{}, paths []string) error { +func injectExplicitBundles(root map[string]any, paths []string) error { if len(paths) == 0 { return nil } - bundles, ok := root["bundles"].(map[string]interface{}) + bundles, ok := root["bundles"].(map[string]any) if !ok { - bundles = map[string]interface{}{} + bundles = map[string]any{} root["bundles"] = bundles } @@ -263,7 +263,7 @@ func injectExplicitBundles(root map[string]interface{}, paths []string) error { return err } abspath = filepath.ToSlash(abspath) - bundles[fmt.Sprintf("~%d", i)] = map[string]interface{}{ + bundles[fmt.Sprintf("~%d", i)] = map[string]any{ "resource": fmt.Sprintf("file://%v", abspath), } } diff --git a/cmd/exec_test.go b/cmd/exec_test.go index 3eb0766d72..79f64863f0 100644 --- a/cmd/exec_test.go +++ b/cmd/exec_test.go @@ -50,7 +50,7 @@ func toStringSlice(a *any) []string { switch a := (*a).(type) { case []string: return a - case []interface{}: + case []any: strSlice := make([]string, len(a)) for i := range a { strSlice[i] = a[i].(string) diff --git a/cmd/fmt.go b/cmd/fmt.go index 502f748521..2d22e182db 100644 --- a/cmd/fmt.go +++ b/cmd/fmt.go @@ -273,7 +273,7 @@ func (e fmtError) Error() string { return fmt.Sprintf("%s (%d)", e.msg, e.code) } -func newError(msg string, a ...interface{}) fmtError { +func newError(msg string, a ...any) fmtError { return fmtError{ msg: fmt.Sprintf(msg, a...), code: 2, diff --git a/cmd/internal/exec/exec.go b/cmd/internal/exec/exec.go index 974b755c95..a30c22c94d 100644 --- a/cmd/internal/exec/exec.go +++ b/cmd/internal/exec/exec.go @@ -118,7 +118,7 @@ func listAllPaths(roots []string) chan fileListItem { return ch } -func parse(p string) (*interface{}, error) { +func parse(p string) (*any, error) { selectedParser, ok := parsers[path.Ext(p)] if !ok { return nil, nil diff --git a/cmd/internal/exec/exec_test.go b/cmd/internal/exec/exec_test.go index 6a42e3c79f..58e352d407 100644 --- a/cmd/internal/exec/exec_test.go +++ b/cmd/internal/exec/exec_test.go @@ -40,7 +40,7 @@ func TestParse(t *testing.T) { t.Fatalf("unexpected error when passing file wiith valid json: %q", err.Error()) } else { v := *val - that, ok := v.(map[string]interface{})["this"] + that, ok := v.(map[string]any)["this"] if !ok { t.Fatalf("expected parsed data to have key %q with value %q, found none", "this", "that") } diff --git a/cmd/internal/exec/json_reporter.go b/cmd/internal/exec/json_reporter.go index 9c4e62ae22..f10e28e4a2 100644 --- a/cmd/internal/exec/json_reporter.go +++ b/cmd/internal/exec/json_reporter.go @@ -64,7 +64,7 @@ func (jr *jsonReporter) StoreDecision(input *any, itemPath string) { if jr.params.FailNonEmpty && rs.Result != nil { // Check if rs.Result is an array and has one or more members - resultArray, isArray := rs.Result.([]interface{}) + resultArray, isArray := rs.Result.([]any) if (!isArray) || (isArray && (len(resultArray) > 0)) { jr.failCount++ } diff --git a/cmd/internal/exec/parser.go b/cmd/internal/exec/parser.go index 1f857c6ac7..90407019c0 100644 --- a/cmd/internal/exec/parser.go +++ b/cmd/internal/exec/parser.go @@ -7,17 +7,17 @@ import ( ) type parser interface { - Parse(io.Reader) (interface{}, error) + Parse(io.Reader) (any, error) } type utilParser struct { } -func (utilParser) Parse(r io.Reader) (interface{}, error) { +func (utilParser) Parse(r io.Reader) (any, error) { bs, err := io.ReadAll(r) if err != nil { return nil, err } - var x interface{} + var x any return x, util.Unmarshal(bs, &x) } diff --git a/cmd/internal/exec/parser_test.go b/cmd/internal/exec/parser_test.go index 6b7671226a..3676e4f003 100644 --- a/cmd/internal/exec/parser_test.go +++ b/cmd/internal/exec/parser_test.go @@ -25,7 +25,7 @@ func TestUtilParser_Parse(t *testing.T) { Name string Reader io.Reader ShouldError bool - Expectation func(x interface{}) + Expectation func(x any) }{ { Name: "should return an error if the provided reader raises an error", @@ -41,8 +41,8 @@ func TestUtilParser_Parse(t *testing.T) { Name: "should return a valid JSON object", Reader: bytes.NewBuffer(b), ShouldError: false, - Expectation: func(x interface{}) { - if val, ok := x.(map[string]interface{})["this"]; !ok { + Expectation: func(x any) { + if val, ok := x.(map[string]any)["this"]; !ok { t.Fatalf("expected returned value to have key %q, but none was found", "this") } else if val != "that" { t.Fatalf("expected returned value to have value %q for key %q, instead got %q", "that", "this", val) diff --git a/cmd/oracle.go b/cmd/oracle.go index 403098e838..b6355d6f7d 100644 --- a/cmd/oracle.go +++ b/cmd/oracle.go @@ -172,7 +172,7 @@ func dofindDefinition(params findDefinitionParams, stdin io.Reader, stdout io.Wr }) if err != nil { - return presentation.JSON(stdout, map[string]interface{}{ + return presentation.JSON(stdout, map[string]any{ "error": err, }) } diff --git a/cmd/oracle_test.go b/cmd/oracle_test.go index a17e96528f..4f90a2a61b 100644 --- a/cmd/oracle_test.go +++ b/cmd/oracle_test.go @@ -106,11 +106,11 @@ func expectJSON(t *testing.T, err error, buffer *bytes.Buffer, exp string) { if err != nil { t.Fatal(err) } - var x interface{} + var x any if err := util.UnmarshalJSON(buffer.Bytes(), &x); err != nil { t.Fatal(err) } - var y interface{} + var y any if err := util.UnmarshalJSON([]byte(exp), &y); err != nil { t.Fatal(err) } diff --git a/cmd/sign.go b/cmd/sign.go index 44a76f5219..1cc1558060 100644 --- a/cmd/sign.go +++ b/cmd/sign.go @@ -237,7 +237,7 @@ func readBundleFiles(loaders []initload.BundleLoader, h bundle.SignatureHasher) func hashFileContent(h bundle.SignatureHasher, data []byte, path string) (bundle.FileInfo, error) { var fileInfo bundle.FileInfo - var value interface{} + var value any if bundle.IsStructuredDoc(path) { err := util.Unmarshal(data, &value) @@ -257,7 +257,7 @@ func hashFileContent(h bundle.SignatureHasher, data []byte, path string) (bundle } func writeTokenToFile(token, fileLoc string) error { - content := make(map[string]interface{}) + content := make(map[string]any) content["signatures"] = []string{token} bs, err := json.MarshalIndent(content, "", " ") diff --git a/cmd/sign_test.go b/cmd/sign_test.go index 47f0c67e02..38025350cb 100644 --- a/cmd/sign_test.go +++ b/cmd/sign_test.go @@ -20,7 +20,7 @@ import ( func TestWriteTokenToFile(t *testing.T) { token := `eyJhbGciOiJSUzI1NiJ9.eyJmaWxlcyI6W3sibmFtZSI6ImJ1bmRsZS8ubWFuaWZlc3QiLCJoYXNoIjoiZWUwZWRiZGZkMjgzNTBjNDk2ZjA4ODI3Y2E1Y2VhYjgwMzA2NzI0YjYyZGY1ZjY0MDRlNzBjYjc2NjYxNWQ5ZCIsImFsZ29yaXRobSI6IlNIQTI1NiJ9LHsibmFtZSI6ImJ1bmRsZS9odHRwL2V4YW1wbGUvYXV0aHovYXV0aHoucmVnbyIsImhhc2giOiI2MDJiZTcwMWIyYmE4ZTc3YTljNTNmOWIzM2QwZTkwM2MzNGMwMGMzMDkzM2Y2NDZiYmU3NGI3YzE2NGY2OGM2IiwiYWxnb3JpdGhtIjoiU0hBMjU2In0seyJuYW1lIjoiYnVuZGxlL3JvbGVzL2JpbmRpbmcvZGF0YS5qc29uIiwiaGFzaCI6ImIxODg1NTViZjczMGVlNDdkZjBiY2Y4MzVlYTNmNTQ1MjlmMzc4N2Y0ODQxZjFhZGE2MDM5M2RhYWZhZmJkYzciLCJhbGdvcml0aG0iOiJTSEEyNTYifV0sImtleWlkIjoiZm9vIiwic2NvcGUiOiJyZWFkIn0.YojuPnGWutdlDL7lwFGBXqPfDtxOG2BuZmShN5zm-G9zfMprI1AMqKDoPoNv4tuCGIBNXwoNsYHYiK538CHfJEfY1v4iDX3JFEWQlwx_CfJWDonwqT9SY9tHUW7PUUrI_WgJXZ5zei8RAMYMymKSb9hpSAtfGg_PU0kZr52WzjbPUj4SRiB19Swi61r0CFXYjbfx3GDJdjrGTNBSWrUCMrdhHYLEWqJPfSQ-fYfRrgQVhq3BJLwJJe66dgBEGnHEgA7XMuxkNIOv7mj3Y_EChbv2tjrD9NJPekDcYH1zCEc4BycHjNCcsGiQXDE6sFtoNZiCXLB2D0sLqUnBx4TCw27wTPfcOuL2KauLPahZitnH5mYvQD8NI76Pm4NSyJfevwdWjSsrT7vf0DCLS-dU6r9dJ79xM_hJU7136CT8ARcmSrk-EvCqfkrH2c4WwZyAzdyyyFumMZh4CYc2vcC7ap0NANHJT193fTud1i23mx1PBslwXdsIqXvBGlTbR7nb9o661m-B_mxbHMkG4nIeoGpZoaBJw8RVaA6-4D55gtk8aaMyLJIlIIlV2_AKOLk3nPG3ACHiLSndasLDOIRIYkCluIEaM2FLEEPEtJfKNR6e1K-EK2TvNKMDAEUtJW71ggOuGQ3b5otYOoVVENJLwm-PsO7qb2Tq6PyAquI3ExU` - expected := make(map[string]interface{}) + expected := make(map[string]any) expected["signatures"] = []string{token} files := map[string]string{} diff --git a/cmd/test_test.go b/cmd/test_test.go index 973905a07b..cc8850c7ba 100644 --- a/cmd/test_test.go +++ b/cmd/test_test.go @@ -2517,7 +2517,7 @@ test_l if { } testBundle := bundle.Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, } for k, v := range tc.files { testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{ @@ -2864,7 +2864,7 @@ test_l if { } testBundle := bundle.Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, } for k, v := range tc.files { testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{ @@ -3118,7 +3118,7 @@ test_l if { } testBundle := bundle.Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, } for k, v := range tc.files { testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{ diff --git a/cmd/version_test.go b/cmd/version_test.go index e9c25e5556..3792b3ae93 100644 --- a/cmd/version_test.go +++ b/cmd/version_test.go @@ -99,7 +99,7 @@ func expectOutputKeys(t *testing.T, stdout string, expectedKeys []string) { } } -func getTestServer(update interface{}, statusCode int) (baseURL string, teardownFn func()) { +func getTestServer(update any, statusCode int) (baseURL string, teardownFn func()) { mux := http.NewServeMux() ts := httptest.NewServer(mux) diff --git a/compile/compile_test.go b/compile/compile_test.go index 78dbc82a07..4d3dad4947 100644 --- a/compile/compile_test.go +++ b/compile/compile_test.go @@ -414,7 +414,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Manifest: bundle.Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, }, @@ -429,7 +429,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, }, @@ -443,14 +443,14 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Manifest: bundle.Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, { Manifest: bundle.Manifest{ Roots: &[]string{"b"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, }, @@ -465,7 +465,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -480,7 +480,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"b"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/test1.rego", @@ -507,7 +507,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV0, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -522,7 +522,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"b"}, RegoVersion: ®oV0, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/test1.rego", @@ -549,7 +549,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV0, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -564,7 +564,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"b"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/test1.rego", @@ -590,7 +590,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -614,7 +614,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { "/test1.rego": 0, }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { // we don't expect this file to get an individual rego-version in the result, as @@ -637,7 +637,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { RegoVersion: ®oV0, Roots: &[]string{"c"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ // we don't expect these files to get individual rego-versions in the result, // as they have the same rego-version as the global rego-version @@ -677,7 +677,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { "a/*": 1, }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/foo/test.rego", @@ -705,7 +705,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { "*/bar/*": 0, }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/foo/test.rego", diff --git a/dependencies/deps.go b/dependencies/deps.go index 868edd1794..804bd883d6 100644 --- a/dependencies/deps.go +++ b/dependencies/deps.go @@ -10,7 +10,7 @@ import ( ) // All returns the list of data ast.Refs that the given AST element depends on. -func All(x interface{}) (resolved []ast.Ref, err error) { +func All(x any) (resolved []ast.Ref, err error) { return v1.All(x) } @@ -20,7 +20,7 @@ func All(x interface{}) (resolved []ast.Ref, err error) { // // As an example, if an element depends on data.x and data.x.y, only data.x will // be in the returned list. -func Minimal(x interface{}) (resolved []ast.Ref, err error) { +func Minimal(x any) (resolved []ast.Ref, err error) { return v1.Minimal(x) } @@ -28,7 +28,7 @@ func Minimal(x interface{}) (resolved []ast.Ref, err error) { // // The returned refs are always constant and are truncated at any point where they become // dynamic. That is, a ref like data.a.b[x] will be truncated to data.a.b. -func Base(compiler *ast.Compiler, x interface{}) ([]ast.Ref, error) { +func Base(compiler *ast.Compiler, x any) ([]ast.Ref, error) { return v1.Base(compiler, x) } @@ -37,6 +37,6 @@ func Base(compiler *ast.Compiler, x interface{}) ([]ast.Ref, error) { // // The returned refs are always constant and are truncated at any point where they become // dynamic. That is, a ref like data.a.b[x] will be truncated to data.a.b. -func Virtual(compiler *ast.Compiler, x interface{}) ([]ast.Ref, error) { +func Virtual(compiler *ast.Compiler, x any) ([]ast.Ref, error) { return v1.Virtual(compiler, x) } diff --git a/docs/content/_index.md b/docs/content/_index.md index 020cca0b39..3a5e479f66 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -1103,7 +1103,7 @@ if err != nil { // handle error } -var input interface{} +var input any if err := json.Unmarshal(bs, &input); err != nil { // handle error @@ -1157,7 +1157,7 @@ func main() { } // Load the input document from stdin. - var input interface{} + var input any dec := json.NewDecoder(os.Stdin) dec.UseNumber() if err := dec.Decode(&input); err != nil { diff --git a/docs/content/configuration.md b/docs/content/configuration.md index 8b369a1892..6548368be8 100644 --- a/docs/content/configuration.md +++ b/docs/content/configuration.md @@ -695,10 +695,10 @@ type Plugin struct { manager *plugins.Manager config Config stop chan chan struct{} - reconfig chan interface{} + reconfig chan any } -func (p *PluginFactory) Validate(manager *plugins.Manager, config []byte) (interface{}, error) { +func (p *PluginFactory) Validate(manager *plugins.Manager, config []byte) (any, error) { var parsedConfig Config if err := util.Unmarshal(config, &parsedConfig); err != nil { return nil, err @@ -706,12 +706,12 @@ func (p *PluginFactory) Validate(manager *plugins.Manager, config []byte) (inter return &parsedConfig, nil } -func (p *PluginFactory) New(manager *plugins.Manager, config interface{}) plugins.Plugin { +func (p *PluginFactory) New(manager *plugins.Manager, config any) plugins.Plugin { return &Plugin{ config: *config.(*Config), manager: manager, stop: make(chan chan struct{}), - reconfig: make(chan interface{}), + reconfig: make(chan any), } } @@ -728,7 +728,7 @@ func (p *Plugin) Stop(ctx context.Context) { return } -func (p *Plugin) Reconfigure(ctx context.Context, config interface{}) { +func (p *Plugin) Reconfigure(ctx context.Context, config any) { p.reconfig <- config return } diff --git a/docs/content/extensions.md b/docs/content/extensions.md index aa059d493f..0004febaa1 100644 --- a/docs/content/extensions.md +++ b/docs/content/extensions.md @@ -250,7 +250,7 @@ func (p *PrintlnLogger) Stop(ctx context.Context) { p.manager.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateNotReady}) } -func (p *PrintlnLogger) Reconfigure(ctx context.Context, config interface{}) { +func (p *PrintlnLogger) Reconfigure(ctx context.Context, config any) { p.mtx.Lock() defer p.mtx.Unlock() p.config = config.(Config) @@ -289,7 +289,7 @@ import ( type Factory struct{} -func (Factory) New(m *plugins.Manager, config interface{}) plugins.Plugin { +func (Factory) New(m *plugins.Manager, config any) plugins.Plugin { m.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateNotReady}) @@ -299,7 +299,7 @@ func (Factory) New(m *plugins.Manager, config interface{}) plugins.Plugin { } } -func (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) { +func (Factory) Validate(_ *plugins.Manager, config []byte) (any, error) { parsedConfig := Config{} return parsedConfig, util.Unmarshal(config, &parsedConfig) } diff --git a/docs/content/integration.md b/docs/content/integration.md index 5b7653bebc..6fefa11537 100644 --- a/docs/content/integration.md +++ b/docs/content/integration.md @@ -29,13 +29,13 @@ OPA supports different ways to evaluate policies. * The [REST API](../rest-api) returns decisions as JSON over HTTP. * Also see the [Language SDKs](/ecosystem/#languages) for working with the REST API in different languages. * The [Go API (GoDoc)](https://pkg.go.dev/github.com/open-policy-agent/opa/v1/rego) returns - decisions as simple Go types (`bool`, `string`, `map[string]interface{}`, + decisions as simple Go types (`bool`, `string`, `map[string]any`, etc.) * [WebAssembly](../wasm) compiles Rego policies into Wasm instructions so they can be embedded and evaluated by any WebAssembly runtime * Custom compilers and evaluators may be written to parse evaluation plans in the low-level [Intermediate Representation](../ir) format, which can be emitted by the `opa build` command * The [SDK](https://pkg.go.dev/github.com/open-policy-agent/opa/v1/sdk) provides high-level APIs for obtaining the output - of query evaluation as simple Go types (`bool`, `string`, `map[string]interface{}`, etc.) + of query evaluation as simple Go types (`bool`, `string`, `map[string]any`, etc.) ### Integrating with the REST API @@ -264,7 +264,7 @@ func main() { defer opa.Stop(ctx) // get the named policy decision for the specified input - if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/authz/allow", Input: map[string]interface{}{"open": "sesame"}}); err != nil { + if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/authz/allow", Input: map[string]any{"open": "sesame"}}); err != nil { // handle error. } else if decision, ok := result.Result.(bool); !ok || !decision { // handle error. @@ -380,12 +380,12 @@ Using the `query` returned by `rego.Rego#PrepareForEval` call the `Eval` function to evaluate the policy: ```go -input := map[string]interface{}{ +input := map[string]any{ "method": "GET", - "path": []interface{}{"salary", "bob"}, - "subject": map[string]interface{}{ + "path": []any{"salary", "bob"}, + "subject": map[string]any{ "user": "bob", - "groups": []interface{}{"sales", "marketing"}, + "groups": []any{"sales", "marketing"}, }, } diff --git a/download/oci_download_unavailable.go b/download/oci_download_unavailable.go index e105d2bd79..5727804d28 100644 --- a/download/oci_download_unavailable.go +++ b/download/oci_download_unavailable.go @@ -18,7 +18,7 @@ func (d *OCIDownloader) WithCallback(f func(context.Context, Update)) *OCIDownlo panic("built without OCI support") } -func (d *OCIDownloader) WithLogAttrs(map[string]interface{}) *OCIDownloader { +func (d *OCIDownloader) WithLogAttrs(map[string]any) *OCIDownloader { panic("built without OCI support") } diff --git a/format/format.go b/format/format.go index ad09cea843..5782dd2aa8 100644 --- a/format/format.go +++ b/format/format.go @@ -42,7 +42,7 @@ func SourceWithOpts(filename string, src []byte, opts Opts) ([]byte, error) { // MustAst is a helper function to format a Rego AST element. If any errors // occurs this function will panic. This is mostly used for test -func MustAst(x interface{}) []byte { +func MustAst(x any) []byte { bs, err := Ast(x) if err != nil { panic(err) @@ -52,7 +52,7 @@ func MustAst(x interface{}) []byte { // MustAstWithOpts is a helper function to format a Rego AST element. If any errors // occurs this function will panic. This is mostly used for test -func MustAstWithOpts(x interface{}, opts Opts) []byte { +func MustAstWithOpts(x any, opts Opts) []byte { bs, err := AstWithOpts(x, opts) if err != nil { panic(err) @@ -63,13 +63,13 @@ func MustAstWithOpts(x interface{}, opts Opts) []byte { // Ast formats a Rego AST element. If the passed value is not a valid AST // element, Ast returns nil and an error. If AST nodes are missing locations // an arbitrary location will be used. -func Ast(x interface{}) ([]byte, error) { +func Ast(x any) ([]byte, error) { return AstWithOpts(x, Opts{ RegoVersion: ast.DefaultRegoVersion, }) } -func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { +func AstWithOpts(x any, opts Opts) ([]byte, error) { if opts.RegoVersion == ast.RegoUndefined { opts.RegoVersion = ast.DefaultRegoVersion } diff --git a/internal/bundle/inspect/inspect.go b/internal/bundle/inspect/inspect.go index c95dc4f6aa..8a350b73b9 100644 --- a/internal/bundle/inspect/inspect.go +++ b/internal/bundle/inspect/inspect.go @@ -23,12 +23,12 @@ import ( // Info represents information about a bundle. type Info struct { - Manifest *bundle.Manifest `json:"manifest,omitempty"` - Signatures bundle.SignaturesConfig `json:"signatures_config,omitempty"` - WasmModules []map[string]interface{} `json:"wasm_modules,omitempty"` - Namespaces map[string][]string `json:"namespaces,omitempty"` - Annotations []*ast.AnnotationsRef `json:"annotations,omitempty"` - Required *ast.Capabilities `json:"capabilities,omitempty"` + Manifest *bundle.Manifest `json:"manifest,omitempty"` + Signatures bundle.SignaturesConfig `json:"signatures_config,omitempty"` + WasmModules []map[string]any `json:"wasm_modules,omitempty"` + Namespaces map[string][]string `json:"namespaces,omitempty"` + Annotations []*ast.AnnotationsRef `json:"annotations,omitempty"` + Required *ast.Capabilities `json:"capabilities,omitempty"` } func File(path string, includeAnnotations bool) (*Info, error) { @@ -103,9 +103,9 @@ func bundleOrDirInfoForRegoVersion(regoVersion ast.RegoVersion, path string, inc return nil, err } - wasmModules := make([]map[string]interface{}, 0, len(b.WasmModules)) + wasmModules := make([]map[string]any, 0, len(b.WasmModules)) for _, w := range b.WasmModules { - wasmModule := map[string]interface{}{ + wasmModule := map[string]any{ "url": w.URL, "path": w.Path, } diff --git a/internal/bundle/inspect/inspect_test.go b/internal/bundle/inspect/inspect_test.go index 757302caf3..5e17cc382c 100644 --- a/internal/bundle/inspect/inspect_test.go +++ b/internal/bundle/inspect/inspect_test.go @@ -137,8 +137,8 @@ func TestGenerateBundleInfoWithFile(t *testing.T) { Roots: &[]string{"a", "b/c"}, Revision: "123", }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": []int{4, 5, 6}, }, }, @@ -217,7 +217,7 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) { t.Fatalf("Unexpected error: %v", err) } - metadata := map[string]interface{}{"foo": "bar"} + metadata := map[string]any{"foo": "bar"} wasmResolvers := []bundle.WasmResolver{{ Entrypoint: "http/example/authz/allow", Module: "/policy.wasm", @@ -250,14 +250,14 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) { t.Fatalf("expected namespaces %v, but got %v", expectedNamespaces, info.Namespaces) } - expectedWasmModules := []map[string]interface{}{} - expectedWasmModule1 := map[string]interface{}{ + expectedWasmModules := []map[string]any{} + expectedWasmModule1 := map[string]any{ "path": "/example/policy.wasm", "url": filepath.Join(bundleFile, "example", "policy.wasm"), "entrypoints": []string{"data.http.example.foo.allow"}, } - expectedWasmModule2 := map[string]interface{}{ + expectedWasmModule2 := map[string]any{ "path": "/policy.wasm", "url": filepath.Join(bundleFile, "policy.wasm"), "entrypoints": []string{"data.http.example.authz.allow"}, diff --git a/internal/cmd/genbuiltinmetadata/main.go b/internal/cmd/genbuiltinmetadata/main.go index 27335793e9..4cff1afc62 100644 --- a/internal/cmd/genbuiltinmetadata/main.go +++ b/internal/cmd/genbuiltinmetadata/main.go @@ -20,7 +20,7 @@ func main() { sorted := sortedCaps() sorted = append(sorted, versionedCaps{version: "edge", caps: f}) - mdata := make(map[string]interface{}) + mdata := make(map[string]any) categories := make(map[string][]string) for _, bi := range f.Builtins { @@ -29,11 +29,11 @@ func main() { categories[cat] = append(categories[cat], bi.Name) } - argTypes := make([]map[string]interface{}, len(latest.Decl.FuncArgs().Args)) + argTypes := make([]map[string]any, len(latest.Decl.FuncArgs().Args)) for i, typ := range latest.Decl.NamedFuncArgs().Args { if n, ok := typ.(*types.NamedType); ok { - argTypes[i] = map[string]interface{}{ + argTypes[i] = map[string]any{ "name": n.Name, "type": n.Type.String(), } @@ -41,12 +41,12 @@ func main() { argTypes[i]["description"] = n.Descr } } else { - argTypes[i] = map[string]interface{}{ + argTypes[i] = map[string]any{ "type": typ.String(), } } } - res := map[string]interface{}{} + res := map[string]any{} resType := latest.Decl.NamedResult() if n, ok := resType.(*types.NamedType); ok { res["name"] = n.Name @@ -58,7 +58,7 @@ func main() { res["type"] = resType.String() } versions := getVersions(bi.Name, sorted) - md := map[string]interface{}{ + md := map[string]any{ "introduced": versions[0], "available": versions, "wasm": getWasm(bi.Name), diff --git a/internal/config/config.go b/internal/config/config.go index fdac487720..d4fae5fa65 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -70,7 +70,7 @@ func ParseServicesConfig(opts ServiceOptions) (map[string]rest.Client, error) { // read from disk (if specified) and overrides will be applied. If no config file is // specified, the overrides can still be applied to an empty config. func Load(configFile string, overrides []string, overrideFiles []string) ([]byte, error) { - baseConf := map[string]interface{}{} + baseConf := map[string]any{} // User specified config file if configFile != "" { @@ -88,7 +88,7 @@ func Load(configFile string, overrides []string, overrideFiles []string) ([]byte } } - overrideConf := map[string]interface{}{} + overrideConf := map[string]any{} // User specified a config override via --set for _, override := range overrides { @@ -100,7 +100,7 @@ func Load(configFile string, overrides []string, overrideFiles []string) ([]byte // User specified a config override value via --set-file for _, override := range overrideFiles { - reader := func(rs []rune) (interface{}, error) { + reader := func(rs []rune) (any, error) { bytes, err := os.ReadFile(string(rs)) value := strings.TrimSpace(string(bytes)) return value, err @@ -141,21 +141,21 @@ func subEnvVars(s string) string { } // mergeValues will merge source and destination map, preferring values from the source map -func mergeValues(dest map[string]interface{}, src map[string]interface{}) map[string]interface{} { +func mergeValues(dest map[string]any, src map[string]any) map[string]any { for k, v := range src { // If the key doesn't exist already, then just set the key to that value if _, exists := dest[k]; !exists { dest[k] = v continue } - nextMap, ok := v.(map[string]interface{}) + nextMap, ok := v.(map[string]any) // If it isn't another map, overwrite the value if !ok { dest[k] = v continue } // Edge case: If the key exists in the destination, but isn't a map - destMap, isMap := dest[k].(map[string]interface{}) + destMap, isMap := dest[k].(map[string]any) // If the source map has a map for this key, prefer it if !isMap { dest[k] = v diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 694f399212..1e748eb62f 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -119,17 +119,17 @@ func TestSubEnvVarsVarsSubEmptyVarName(t *testing.T) { } func TestMergeValuesNoOverride(t *testing.T) { - dest := map[string]interface{}{} - src := map[string]interface{}{ - "a": map[string]interface{}{ + dest := map[string]any{} + src := map[string]any{ + "a": map[string]any{ "b": "foo", }, } actual := mergeValues(dest, src) - expected := map[string]interface{}{ - "a": map[string]interface{}{ + expected := map[string]any{ + "a": map[string]any{ "b": "foo", }, } @@ -140,16 +140,16 @@ func TestMergeValuesNoOverride(t *testing.T) { } func TestMergeValuesOverrideSingle(t *testing.T) { - dest := map[string]interface{}{ + dest := map[string]any{ "a": "bar", } - src := map[string]interface{}{ + src := map[string]any{ "a": "override-value", } actual := mergeValues(dest, src) - expected := map[string]interface{}{ + expected := map[string]any{ "a": "override-value", } @@ -159,21 +159,21 @@ func TestMergeValuesOverrideSingle(t *testing.T) { } func TestMergeValuesOverrideSingleNested(t *testing.T) { - dest := map[string]interface{}{ - "a": map[string]interface{}{ + dest := map[string]any{ + "a": map[string]any{ "b": "foo", }, } - src := map[string]interface{}{ - "a": map[string]interface{}{ + src := map[string]any{ + "a": map[string]any{ "b": "override-value", }, } actual := mergeValues(dest, src) - expected := map[string]interface{}{ - "a": map[string]interface{}{ + expected := map[string]any{ + "a": map[string]any{ "b": "override-value", }, } @@ -184,9 +184,9 @@ func TestMergeValuesOverrideSingleNested(t *testing.T) { } func TestMergeValuesOverrideMultipleNested(t *testing.T) { - dest := map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + dest := map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "k1": "v1", "k2": "v2", "k3": "v3", @@ -194,9 +194,9 @@ func TestMergeValuesOverrideMultipleNested(t *testing.T) { }, }, } - src := map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + src := map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "k1": "v1-override", "k4": "v4-override", }, @@ -205,9 +205,9 @@ func TestMergeValuesOverrideMultipleNested(t *testing.T) { actual := mergeValues(dest, src) - expected := map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + expected := map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "k1": "v1-override", "k2": "v2", "k3": "v3", @@ -222,9 +222,9 @@ func TestMergeValuesOverrideMultipleNested(t *testing.T) { } func TestMergeValuesOverrideSingleList(t *testing.T) { - dest := map[string]interface{}{ - "a": map[string]interface{}{ - "b": []map[string]interface{}{ + dest := map[string]any{ + "a": map[string]any{ + "b": []map[string]any{ { "k1": "v1", "k2": "v2", @@ -232,9 +232,9 @@ func TestMergeValuesOverrideSingleList(t *testing.T) { }, }, } - src := map[string]interface{}{ - "a": map[string]interface{}{ - "b": []map[string]interface{}{ + src := map[string]any{ + "a": map[string]any{ + "b": []map[string]any{ { "k3": "v3", }, @@ -245,9 +245,9 @@ func TestMergeValuesOverrideSingleList(t *testing.T) { actual := mergeValues(dest, src) // The list index 0 should have been replaced instead of merging the sub objects - expected := map[string]interface{}{ - "a": map[string]interface{}{ - "b": []map[string]interface{}{ + expected := map[string]any{ + "a": map[string]any{ + "b": []map[string]any{ { "k3": "v3", }, @@ -261,17 +261,17 @@ func TestMergeValuesOverrideSingleList(t *testing.T) { } func TestMergeValuesNoSrc(t *testing.T) { - dest := map[string]interface{}{ - "a": map[string]interface{}{ + dest := map[string]any{ + "a": map[string]any{ "b": "foo", }, } - src := map[string]interface{}{} + src := map[string]any{} actual := mergeValues(dest, src) - expected := map[string]interface{}{ - "a": map[string]interface{}{ + expected := map[string]any{ + "a": map[string]any{ "b": "foo", }, } @@ -282,12 +282,12 @@ func TestMergeValuesNoSrc(t *testing.T) { } func TestMergeValuesNoSrcOrDest(t *testing.T) { - dest := map[string]interface{}{} - src := map[string]interface{}{} + dest := map[string]any{} + src := map[string]any{} actual := mergeValues(dest, src) - expected := map[string]interface{}{} + expected := map[string]any{} if !reflect.DeepEqual(actual, expected) { t.Errorf("merged map does not match expected:\n\nExpected: %+v\nActual: %+v", expected, actual) @@ -314,24 +314,24 @@ discovery: t.Errorf("unexpected error loading config: %s", err.Error()) } - config := map[string]interface{}{} + config := map[string]any{} err = yaml.Unmarshal(configBytes, &config) if err != nil { t.Errorf("unexpected error unmarshalling config") } - expected := map[string]interface{}{ - "services": map[string]interface{}{ - "acmecorp": map[string]interface{}{ + expected := map[string]any{ + "services": map[string]any{ + "acmecorp": map[string]any{ "url": "https://example.com/control-plane-api/v1", - "credentials": map[string]interface{}{ - "bearer": map[string]interface{}{ + "credentials": map[string]any{ + "bearer": map[string]any{ "token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm", }, }, }, }, - "discovery": map[string]interface{}{ + "discovery": map[string]any{ "name": "/example/discovery", "prefix": "configuration", }, @@ -370,24 +370,24 @@ discovery: t.Errorf("unexpected error loading config: %s", err.Error()) } - config := map[string]interface{}{} + config := map[string]any{} err = yaml.Unmarshal(configBytes, &config) if err != nil { t.Errorf("unexpected error unmarshalling config") } - expected := map[string]interface{}{ - "services": map[string]interface{}{ - "acmecorp": map[string]interface{}{ + expected := map[string]any{ + "services": map[string]any{ + "acmecorp": map[string]any{ "url": "https://example.com/control-plane-api/v1", - "credentials": map[string]interface{}{ - "bearer": map[string]interface{}{ + "credentials": map[string]any{ + "bearer": map[string]any{ "token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm", }, }, }, }, - "discovery": map[string]interface{}{ + "discovery": map[string]any{ "name": "/example/discovery", "prefix": "configuration", }, @@ -412,24 +412,24 @@ func TestLoadConfigWithParamOverrideNoConfigFile(t *testing.T) { t.Errorf("unexpected error loading config: %s", err.Error()) } - config := map[string]interface{}{} + config := map[string]any{} err = yaml.Unmarshal(configBytes, &config) if err != nil { t.Errorf("unexpected error unmarshalling config") } - expected := map[string]interface{}{ - "services": map[string]interface{}{ - "acmecorp": map[string]interface{}{ + expected := map[string]any{ + "services": map[string]any{ + "acmecorp": map[string]any{ "url": "https://example.com/control-plane-api/v1", - "credentials": map[string]interface{}{ - "bearer": map[string]interface{}{ + "credentials": map[string]any{ + "bearer": map[string]any{ "token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm", }, }, }, }, - "discovery": map[string]interface{}{ + "discovery": map[string]any{ "name": "/example/discovery", "prefix": "configuration", }, @@ -454,29 +454,29 @@ func TestLoadConfigWithParamOverrideNoConfigFileWithEmptyObject(t *testing.T) { t.Errorf("unexpected error loading config: %s", err.Error()) } - config := map[string]interface{}{} + config := map[string]any{} err = yaml.Unmarshal(configBytes, &config) if err != nil { t.Errorf("unexpected error unmarshalling config") } - expected := map[string]interface{}{ - "services": map[string]interface{}{ - "acmecorp": map[string]interface{}{ + expected := map[string]any{ + "services": map[string]any{ + "acmecorp": map[string]any{ "url": "https://example.com/control-plane-api/v1", - "headers": map[string]interface{}{}, - "credentials": map[string]interface{}{ - "s3_signing": map[string]interface{}{ - "environment_credentials": map[string]interface{}{}, + "headers": map[string]any{}, + "credentials": map[string]any{ + "s3_signing": map[string]any{ + "environment_credentials": map[string]any{}, }, }, }, }, - "decision_logs": map[string]interface{}{ + "decision_logs": map[string]any{ "plugin": "my_plugin", }, - "plugins": map[string]interface{}{ - "my_plugin": map[string]interface{}{}, + "plugins": map[string]any{ + "my_plugin": map[string]any{}, }, } diff --git a/internal/debug/debug.go b/internal/debug/debug.go index 7b90bd1bb0..9448aeb288 100644 --- a/internal/debug/debug.go +++ b/internal/debug/debug.go @@ -8,7 +8,7 @@ import ( // Debug allows printing debug messages. type Debug interface { // Printf prints, with a short file:line-number prefix - Printf(format string, args ...interface{}) + Printf(format string, args ...any) // Writer returns the writer being written to, which may be // `io.Discard` if no debug output is requested. Writer() io.Writer diff --git a/internal/deepcopy/deepcopy.go b/internal/deepcopy/deepcopy.go index 00e8df6f88..dc3a231bc1 100644 --- a/internal/deepcopy/deepcopy.go +++ b/internal/deepcopy/deepcopy.go @@ -5,25 +5,25 @@ package deepcopy // DeepCopy performs a recursive deep copy for nested slices/maps and -// returns the copied object. Supports []interface{} -// and map[string]interface{} only -func DeepCopy(val interface{}) interface{} { +// returns the copied object. Supports []any +// and map[string]any only +func DeepCopy(val any) any { switch val := val.(type) { - case []interface{}: - cpy := make([]interface{}, len(val)) + case []any: + cpy := make([]any, len(val)) for i := range cpy { cpy[i] = DeepCopy(val[i]) } return cpy - case map[string]interface{}: + case map[string]any: return Map(val) default: return val } } -func Map(val map[string]interface{}) map[string]interface{} { - cpy := make(map[string]interface{}, len(val)) +func Map(val map[string]any) map[string]any { + cpy := make(map[string]any, len(val)) for k := range val { cpy[k] = DeepCopy(val[k]) } diff --git a/internal/deepcopy/deepcopy_test.go b/internal/deepcopy/deepcopy_test.go index d0290bdb7d..0d2847b6d6 100644 --- a/internal/deepcopy/deepcopy_test.go +++ b/internal/deepcopy/deepcopy_test.go @@ -10,9 +10,9 @@ import ( ) func TestDeepCopyMapRoot(t *testing.T) { - target := map[string]interface{}{ - "a": map[string]interface{}{ - "b": []interface{}{ + target := map[string]any{ + "a": map[string]any{ + "b": []any{ "c", "d", }, @@ -20,7 +20,7 @@ func TestDeepCopyMapRoot(t *testing.T) { }, "x": "y", } - result := DeepCopy(target).(map[string]interface{}) + result := DeepCopy(target).(map[string]any) if !reflect.DeepEqual(target, result) { t.Fatal("Expected result of DeepCopy to be DeepEqual with original.") } diff --git a/internal/distributedtracing/distributedtracing.go b/internal/distributedtracing/distributedtracing.go index 8ed6bbeb8c..22b225ea9f 100644 --- a/internal/distributedtracing/distributedtracing.go +++ b/internal/distributedtracing/distributedtracing.go @@ -394,18 +394,18 @@ func (s *sink) Enabled(level int) bool { func (*sink) Init(logr.RuntimeInfo) {} // ignored -func (s *sink) Info(_ int, msg string, _ ...interface{}) { +func (s *sink) Info(_ int, msg string, _ ...any) { s.logger.Info(msg) } -func (s *sink) Error(err error, msg string, _ ...interface{}) { - s.logger.WithFields(map[string]interface{}{"err": err}).Error(msg) +func (s *sink) Error(err error, msg string, _ ...any) { + s.logger.WithFields(map[string]any{"err": err}).Error(msg) } func (s *sink) WithName(name string) logr.LogSink { - return &sink{s.logger.WithFields(map[string]interface{}{"name": name})} + return &sink{s.logger.WithFields(map[string]any{"name": name})} } -func (s *sink) WithValues(...interface{}) logr.LogSink { // ignored +func (s *sink) WithValues(...any) logr.LogSink { // ignored return s } diff --git a/internal/gojsonschema/draft.go b/internal/gojsonschema/draft.go index dac1aafdac..656804acb7 100644 --- a/internal/gojsonschema/draft.go +++ b/internal/gojsonschema/draft.go @@ -86,12 +86,12 @@ func (dc draftConfigs) GetSchemaURL(draft Draft) string { return "" } -func parseSchemaURL(documentNode interface{}) (string, *Draft, error) { +func parseSchemaURL(documentNode any) (string, *Draft, error) { if _, ok := documentNode.(bool); ok { return "", nil, nil } - m, ok := documentNode.(map[string]interface{}) + m, ok := documentNode.(map[string]any) if !ok { return "", nil, errors.New("schema is invalid") } diff --git a/internal/gojsonschema/errors.go b/internal/gojsonschema/errors.go index f7aaf90306..a937d9b3b9 100644 --- a/internal/gojsonschema/errors.go +++ b/internal/gojsonschema/errors.go @@ -212,7 +212,7 @@ type ( ) // newError takes a ResultError type and sets the type, context, description, details, value, and field -func newError(err ResultError, context *JSONContext, value interface{}, locale locale, details ErrorDetails) { +func newError(err ResultError, context *JSONContext, value any, locale locale, details ErrorDetails) { var t string var d string switch err.(type) { diff --git a/internal/gojsonschema/format_checkers.go b/internal/gojsonschema/format_checkers.go index 1e770464e8..c078e9862f 100644 --- a/internal/gojsonschema/format_checkers.go +++ b/internal/gojsonschema/format_checkers.go @@ -14,7 +14,7 @@ type ( // FormatChecker is the interface all formatters added to FormatCheckerChain must implement FormatChecker interface { // IsFormat checks if input has the correct format - IsFormat(input interface{}) bool + IsFormat(input any) bool } // FormatCheckerChain holds the formatters @@ -174,7 +174,7 @@ func (c *FormatCheckerChain) Has(name string) bool { // IsFormat will check an input against a FormatChecker with the given name // to see if it is the correct format -func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool { +func (c *FormatCheckerChain) IsFormat(name string, input any) bool { lock.RLock() f, ok := c.formatters[name] lock.RUnlock() @@ -188,7 +188,7 @@ func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool { } // IsFormat checks if input is a correctly formatted e-mail address -func (f EmailFormatChecker) IsFormat(input interface{}) bool { +func (f EmailFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -199,7 +199,7 @@ func (f EmailFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted IPv4-address -func (f IPV4FormatChecker) IsFormat(input interface{}) bool { +func (f IPV4FormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -211,7 +211,7 @@ func (f IPV4FormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted IPv6=address -func (f IPV6FormatChecker) IsFormat(input interface{}) bool { +func (f IPV6FormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -223,7 +223,7 @@ func (f IPV6FormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted date/time per RFC3339 5.6 -func (f DateTimeFormatChecker) IsFormat(input interface{}) bool { +func (f DateTimeFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -247,7 +247,7 @@ func (f DateTimeFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted date (YYYY-MM-DD) -func (f DateFormatChecker) IsFormat(input interface{}) bool { +func (f DateFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -257,7 +257,7 @@ func (f DateFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input correctly formatted time (HH:MM:SS or HH:MM:SSZ-07:00) -func (f TimeFormatChecker) IsFormat(input interface{}) bool { +func (f TimeFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -272,7 +272,7 @@ func (f TimeFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is correctly formatted URI with a valid Scheme per RFC3986 -func (f URIFormatChecker) IsFormat(input interface{}) bool { +func (f URIFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -288,7 +288,7 @@ func (f URIFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted URI or relative-reference per RFC3986 -func (f URIReferenceFormatChecker) IsFormat(input interface{}) bool { +func (f URIReferenceFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -299,7 +299,7 @@ func (f URIReferenceFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted URI template per RFC6570 -func (f URITemplateFormatChecker) IsFormat(input interface{}) bool { +func (f URITemplateFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -314,7 +314,7 @@ func (f URITemplateFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted hostname -func (f HostnameFormatChecker) IsFormat(input interface{}) bool { +func (f HostnameFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -324,7 +324,7 @@ func (f HostnameFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted UUID -func (f UUIDFormatChecker) IsFormat(input interface{}) bool { +func (f UUIDFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -334,7 +334,7 @@ func (f UUIDFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted regular expression -func (f RegexFormatChecker) IsFormat(input interface{}) bool { +func (f RegexFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -348,7 +348,7 @@ func (f RegexFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted JSON Pointer per RFC6901 -func (f JSONPointerFormatChecker) IsFormat(input interface{}) bool { +func (f JSONPointerFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true @@ -358,7 +358,7 @@ func (f JSONPointerFormatChecker) IsFormat(input interface{}) bool { } // IsFormat checks if input is a correctly formatted relative JSON Pointer -func (f RelativeJSONPointerFormatChecker) IsFormat(input interface{}) bool { +func (f RelativeJSONPointerFormatChecker) IsFormat(input any) bool { asString, ok := input.(string) if !ok { return true diff --git a/internal/gojsonschema/format_checkers_test.go b/internal/gojsonschema/format_checkers_test.go index 225f1331a1..ed9fb24f26 100644 --- a/internal/gojsonschema/format_checkers_test.go +++ b/internal/gojsonschema/format_checkers_test.go @@ -58,8 +58,8 @@ const formatSchema = `{ type arrayChecker struct{} -func (c arrayChecker) IsFormat(input interface{}) bool { - arr, ok := input.([]interface{}) +func (c arrayChecker) IsFormat(input any) bool { + arr, ok := input.([]any) if !ok { return true } @@ -73,7 +73,7 @@ func (c arrayChecker) IsFormat(input interface{}) bool { type boolChecker struct{} -func (c boolChecker) IsFormat(input interface{}) bool { +func (c boolChecker) IsFormat(input any) bool { b, ok := input.(bool) if !ok { return true @@ -83,7 +83,7 @@ func (c boolChecker) IsFormat(input interface{}) bool { type integerChecker struct{} -func (c integerChecker) IsFormat(input interface{}) bool { +func (c integerChecker) IsFormat(input any) bool { number, ok := input.(json.Number) if !ok { return true @@ -94,8 +94,8 @@ func (c integerChecker) IsFormat(input interface{}) bool { type objectChecker struct{} -func (c objectChecker) IsFormat(input interface{}) bool { - obj, ok := input.(map[string]interface{}) +func (c objectChecker) IsFormat(input any) bool { + obj, ok := input.(map[string]any) if !ok { return true } @@ -104,7 +104,7 @@ func (c objectChecker) IsFormat(input interface{}) bool { type stringChecker struct{} -func (c stringChecker) IsFormat(input interface{}) bool { +func (c stringChecker) IsFormat(input any) bool { str, ok := input.(string) if !ok { return true @@ -121,7 +121,7 @@ func TestCustomFormat(t *testing.T) { Add("StringChecker", stringChecker{}) sl := NewStringLoader(formatSchema) - validResult, err := Validate(sl, NewGoLoader(map[string]interface{}{ + validResult, err := Validate(sl, NewGoLoader(map[string]any{ "arr": []string{"x", "y", "z"}, "bool": true, "int": "2", // format not defined for string @@ -138,7 +138,7 @@ func TestCustomFormat(t *testing.T) { } } - invalidResult, err := Validate(sl, NewGoLoader(map[string]interface{}{ + invalidResult, err := Validate(sl, NewGoLoader(map[string]any{ "arr": []string{"a", "b", "c"}, "bool": false, "int": 1, diff --git a/internal/gojsonschema/internalLog.go b/internal/gojsonschema/internalLog.go index 4ef7a8d03e..bab75112eb 100644 --- a/internal/gojsonschema/internalLog.go +++ b/internal/gojsonschema/internalLog.go @@ -32,6 +32,6 @@ import ( const internalLogEnabled = false -func internalLog(format string, v ...interface{}) { +func internalLog(format string, v ...any) { log.Printf(format, v...) } diff --git a/internal/gojsonschema/jsonLoader.go b/internal/gojsonschema/jsonLoader.go index 1011552dee..73f25e3b7f 100644 --- a/internal/gojsonschema/jsonLoader.go +++ b/internal/gojsonschema/jsonLoader.go @@ -77,8 +77,8 @@ var osFS = osFileSystem(os.Open) // JSONLoader defines the JSON loader interface type JSONLoader interface { - JSONSource() interface{} - LoadJSON() (interface{}, error) + JSONSource() any + LoadJSON() (any, error) JSONReference() (gojsonreference.JsonReference, error) LoaderFactory() JSONLoaderFactory } @@ -130,7 +130,7 @@ type jsonReferenceLoader struct { source string } -func (l *jsonReferenceLoader) JSONSource() interface{} { +func (l *jsonReferenceLoader) JSONSource() any { return l.source } @@ -160,7 +160,7 @@ func NewReferenceLoaderFileSystem(source string, fs http.FileSystem) JSONLoader } } -func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) { +func (l *jsonReferenceLoader) LoadJSON() (any, error) { var err error @@ -207,7 +207,7 @@ func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) { return nil, fmt.Errorf("remote reference loading disabled: %s", reference.String()) } -func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error) { +func (l *jsonReferenceLoader) loadFromHTTP(address string) (any, error) { resp, err := http.Get(address) if err != nil { @@ -227,7 +227,7 @@ func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error) return decodeJSONUsingNumber(bytes.NewReader(bodyBuff)) } -func (l *jsonReferenceLoader) loadFromFile(path string) (interface{}, error) { +func (l *jsonReferenceLoader) loadFromFile(path string) (any, error) { f, err := l.fs.Open(path) if err != nil { return nil, err @@ -249,7 +249,7 @@ type jsonStringLoader struct { source string } -func (l *jsonStringLoader) JSONSource() interface{} { +func (l *jsonStringLoader) JSONSource() any { return l.source } @@ -266,7 +266,7 @@ func NewStringLoader(source string) JSONLoader { return &jsonStringLoader{source: source} } -func (l *jsonStringLoader) LoadJSON() (interface{}, error) { +func (l *jsonStringLoader) LoadJSON() (any, error) { return decodeJSONUsingNumber(strings.NewReader(l.JSONSource().(string))) @@ -278,7 +278,7 @@ type jsonBytesLoader struct { source []byte } -func (l *jsonBytesLoader) JSONSource() interface{} { +func (l *jsonBytesLoader) JSONSource() any { return l.source } @@ -295,18 +295,18 @@ func NewBytesLoader(source []byte) JSONLoader { return &jsonBytesLoader{source: source} } -func (l *jsonBytesLoader) LoadJSON() (interface{}, error) { +func (l *jsonBytesLoader) LoadJSON() (any, error) { return decodeJSONUsingNumber(bytes.NewReader(l.JSONSource().([]byte))) } // JSON Go (types) loader -// used to load JSONs from the code as maps, interface{}, structs ... +// used to load JSONs from the code as maps, any, structs ... type jsonGoLoader struct { - source interface{} + source any } -func (l *jsonGoLoader) JSONSource() interface{} { +func (l *jsonGoLoader) JSONSource() any { return l.source } @@ -319,11 +319,11 @@ func (l *jsonGoLoader) LoaderFactory() JSONLoaderFactory { } // NewGoLoader creates a new JSONLoader from a given Go struct -func NewGoLoader(source interface{}) JSONLoader { +func NewGoLoader(source any) JSONLoader { return &jsonGoLoader{source: source} } -func (l *jsonGoLoader) LoadJSON() (interface{}, error) { +func (l *jsonGoLoader) LoadJSON() (any, error) { // convert it to a compliant JSON first to avoid types "mismatches" @@ -352,11 +352,11 @@ func NewWriterLoader(source io.Writer) (JSONLoader, io.Writer) { return &jsonIOLoader{buf: buf}, io.MultiWriter(source, buf) } -func (l *jsonIOLoader) JSONSource() interface{} { +func (l *jsonIOLoader) JSONSource() any { return l.buf.String() } -func (l *jsonIOLoader) LoadJSON() (interface{}, error) { +func (l *jsonIOLoader) LoadJSON() (any, error) { return decodeJSONUsingNumber(l.buf) } @@ -369,21 +369,21 @@ func (l *jsonIOLoader) LoaderFactory() JSONLoaderFactory { } // JSON raw loader -// In case the JSON is already marshalled to interface{} use this loader +// In case the JSON is already marshalled to any use this loader // This is used for testing as otherwise there is no guarantee the JSON is marshalled // "properly" by using https://golang.org/pkg/encoding/json/#Decoder.UseNumber type jsonRawLoader struct { - source interface{} + source any } // NewRawLoader creates a new JSON raw loader for the given source -func NewRawLoader(source interface{}) JSONLoader { +func NewRawLoader(source any) JSONLoader { return &jsonRawLoader{source: source} } -func (l *jsonRawLoader) JSONSource() interface{} { +func (l *jsonRawLoader) JSONSource() any { return l.source } -func (l *jsonRawLoader) LoadJSON() (interface{}, error) { +func (l *jsonRawLoader) LoadJSON() (any, error) { return l.source, nil } func (l *jsonRawLoader) JSONReference() (gojsonreference.JsonReference, error) { @@ -393,9 +393,9 @@ func (l *jsonRawLoader) LoaderFactory() JSONLoaderFactory { return &DefaultJSONLoaderFactory{} } -func decodeJSONUsingNumber(r io.Reader) (interface{}, error) { +func decodeJSONUsingNumber(r io.Reader) (any, error) { - var document interface{} + var document any decoder := json.NewDecoder(r) decoder.UseNumber() diff --git a/internal/gojsonschema/jsonschema_test.go b/internal/gojsonschema/jsonschema_test.go index 136202663c..54d24ccf76 100644 --- a/internal/gojsonschema/jsonschema_test.go +++ b/internal/gojsonschema/jsonschema_test.go @@ -30,13 +30,13 @@ type jsonSchemaTest struct { // Some tests may not always pass, so some tests are manually edited to include // an extra attribute whether that specific test should be disabled and skipped Disabled bool `json:"disabled"` - Schema interface{} `json:"schema"` + Schema any `json:"schema"` Tests []jsonSchemaTestCase `json:"tests"` } type jsonSchemaTestCase struct { - Description string `json:"description"` - Data interface{} `json:"data"` - Valid bool `json:"valid"` + Description string `json:"description"` + Data any `json:"data"` + Valid bool `json:"valid"` } // Skip any directories not named appropiately diff --git a/internal/gojsonschema/result.go b/internal/gojsonschema/result.go index 8baff07179..0329721c20 100644 --- a/internal/gojsonschema/result.go +++ b/internal/gojsonschema/result.go @@ -33,7 +33,7 @@ import ( type ( // ErrorDetails is a map of details specific to each error. // While the values will vary, every error will contain a "field" value - ErrorDetails map[string]interface{} + ErrorDetails map[string]any // ResultError is the interface that library errors must implement ResultError interface { @@ -57,9 +57,9 @@ type ( // DescriptionFormat returns the format for the description in the default text/template format DescriptionFormat() string // SetValue sets the value related to the error - SetValue(interface{}) + SetValue(any) // Value returns the value related to the error - Value() interface{} + Value() any // SetDetails sets the details specific to the error SetDetails(ErrorDetails) // Details returns details about the error @@ -76,7 +76,7 @@ type ( context *JSONContext // Tree like notation of the part that failed the validation. ex (root).a.b ... description string // A human readable error message descriptionFormat string // A format for human readable error message - value interface{} // Value given by the JSON file that is the source of the error + value any // Value given by the JSON file that is the source of the error details ErrorDetails } @@ -136,12 +136,12 @@ func (v *ResultErrorFields) DescriptionFormat() string { } // SetValue sets the value related to the error -func (v *ResultErrorFields) SetValue(value interface{}) { +func (v *ResultErrorFields) SetValue(value any) { v.value = value } // Value returns the value related to the error -func (v *ResultErrorFields) Value() interface{} { +func (v *ResultErrorFields) Value() any { return v.value } @@ -203,7 +203,7 @@ func (v *Result) AddError(err ResultError, details ErrorDetails) { v.errors = append(v.errors, err) } -func (v *Result) addInternalError(err ResultError, context *JSONContext, value interface{}, details ErrorDetails) { +func (v *Result) addInternalError(err ResultError, context *JSONContext, value any, details ErrorDetails) { newError(err, context, value, Locale, details) v.errors = append(v.errors, err) v.score -= 2 // results in a net -1 when added to the +1 we get at the end of the validation function diff --git a/internal/gojsonschema/schema.go b/internal/gojsonschema/schema.go index 8e035013c2..e8007ee2b6 100644 --- a/internal/gojsonschema/schema.go +++ b/internal/gojsonschema/schema.go @@ -58,7 +58,7 @@ type Schema struct { ReferencePool *schemaReferencePool } -func (d *Schema) parse(document interface{}, draft Draft) error { +func (d *Schema) parse(document any, draft Draft) error { d.RootSchema = &SubSchema{Property: StringRootSchemaProperty, Draft: &draft} return d.parseSchema(document, d.RootSchema) } @@ -73,7 +73,7 @@ func (d *Schema) SetRootSchemaName(name string) { // Pretty long function ( sorry :) )... but pretty straight forward, repetitive and boring // Not much magic involved here, most of the job is to validate the key names and their values, // then the values are copied into SubSchema struct -func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) error { +func (d *Schema) parseSchema(documentNode any, currentSchema *SubSchema) error { if currentSchema.Draft == nil { if currentSchema.Parent == nil { @@ -90,7 +90,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) } } - m, isMap := documentNode.(map[string]interface{}) + m, isMap := documentNode.(map[string]any) if !isMap { return errors.New(formatErrorDescription( Locale.ParseError(), @@ -146,10 +146,10 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) // definitions if v, ok := m[KeyDefinitions]; ok { switch mt := v.(type) { - case map[string]interface{}: + case map[string]any: for _, dv := range mt { switch dv.(type) { - case bool, map[string]interface{}: + case bool, map[string]any: newSchema := &SubSchema{Property: KeyDefinitions, Parent: currentSchema} err := d.parseSchema(dv, newSchema) if err != nil { @@ -203,7 +203,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) if err != nil { return err } - case []interface{}: + case []any: for _, typeInArray := range t { s, isString := typeInArray.(string) if !isString { @@ -231,7 +231,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) switch v := additionalProperties.(type) { case bool: currentSchema.additionalProperties = v - case map[string]interface{}: + case map[string]any: newSchema := &SubSchema{Property: KeyAdditionalProperties, Parent: currentSchema, Ref: currentSchema.Ref} currentSchema.additionalProperties = newSchema err := d.parseSchema(v, newSchema) @@ -270,7 +270,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) // propertyNames if propertyNames, found := m[KeyPropertyNames]; found && *currentSchema.Draft >= Draft6 { switch propertyNames.(type) { - case bool, map[string]interface{}: + case bool, map[string]any: newSchema := &SubSchema{Property: KeyPropertyNames, Parent: currentSchema, Ref: currentSchema.Ref} currentSchema.propertyNames = newSchema err := d.parseSchema(propertyNames, newSchema) @@ -299,10 +299,10 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) // items if items, found := m[KeyItems]; found { switch i := items.(type) { - case []interface{}: + case []any: for _, itemElement := range i { switch itemElement.(type) { - case map[string]interface{}, bool: + case map[string]any, bool: newSchema := &SubSchema{Parent: currentSchema, Property: KeyItems} newSchema.Ref = currentSchema.Ref currentSchema.ItemsChildren = append(currentSchema.ItemsChildren, newSchema) @@ -315,7 +315,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) } currentSchema.ItemsChildrenIsSingleSchema = false } - case map[string]interface{}, bool: + case map[string]any, bool: newSchema := &SubSchema{Parent: currentSchema, Property: KeyItems} newSchema.Ref = currentSchema.Ref currentSchema.ItemsChildren = append(currentSchema.ItemsChildren, newSchema) @@ -334,7 +334,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) switch i := additionalItems.(type) { case bool: currentSchema.additionalItems = i - case map[string]interface{}: + case map[string]any: newSchema := &SubSchema{Property: KeyAdditionalItems, Parent: currentSchema, Ref: currentSchema.Ref} currentSchema.additionalItems = newSchema err := d.parseSchema(additionalItems, newSchema) @@ -717,7 +717,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) if vNot, found := m[KeyNot]; found { switch vNot.(type) { - case bool, map[string]interface{}: + case bool, map[string]any: newSchema := &SubSchema{Property: KeyNot, Parent: currentSchema, Ref: currentSchema.Ref} currentSchema.not = newSchema err := d.parseSchema(vNot, newSchema) @@ -735,7 +735,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) if *currentSchema.Draft >= Draft7 { if vIf, found := m[KeyIf]; found { switch vIf.(type) { - case bool, map[string]interface{}: + case bool, map[string]any: newSchema := &SubSchema{Property: KeyIf, Parent: currentSchema, Ref: currentSchema.Ref} currentSchema._if = newSchema err := d.parseSchema(vIf, newSchema) @@ -752,7 +752,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) if then, found := m[KeyThen]; found { switch then.(type) { - case bool, map[string]interface{}: + case bool, map[string]any: newSchema := &SubSchema{Property: KeyThen, Parent: currentSchema, Ref: currentSchema.Ref} currentSchema._then = newSchema err := d.parseSchema(then, newSchema) @@ -769,7 +769,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) if vElse, found := m[KeyElse]; found { switch vElse.(type) { - case bool, map[string]interface{}: + case bool, map[string]any: newSchema := &SubSchema{Property: KeyElse, Parent: currentSchema, Ref: currentSchema.Ref} currentSchema._else = newSchema err := d.parseSchema(vElse, newSchema) @@ -788,9 +788,9 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema) return nil } -func (d *Schema) parseReference(_ interface{}, currentSchema *SubSchema) error { +func (d *Schema) parseReference(_ any, currentSchema *SubSchema) error { var ( - refdDocumentNode interface{} + refdDocumentNode any dsp *schemaPoolDocument err error ) @@ -809,7 +809,7 @@ func (d *Schema) parseReference(_ interface{}, currentSchema *SubSchema) error { newSchema.Draft = dsp.Draft switch refdDocumentNode.(type) { - case bool, map[string]interface{}: + case bool, map[string]any: // expected default: return errors.New(formatErrorDescription( @@ -829,8 +829,8 @@ func (d *Schema) parseReference(_ interface{}, currentSchema *SubSchema) error { } -func (d *Schema) parseProperties(documentNode interface{}, currentSchema *SubSchema) error { - m, isMap := documentNode.(map[string]interface{}) +func (d *Schema) parseProperties(documentNode any, currentSchema *SubSchema) error { + m, isMap := documentNode.(map[string]any) if !isMap { return errors.New(formatErrorDescription( Locale.MustBeOfType(), @@ -851,19 +851,19 @@ func (d *Schema) parseProperties(documentNode interface{}, currentSchema *SubSch return nil } -func (d *Schema) parseDependencies(documentNode interface{}, currentSchema *SubSchema) error { - m, isMap := documentNode.(map[string]interface{}) +func (d *Schema) parseDependencies(documentNode any, currentSchema *SubSchema) error { + m, isMap := documentNode.(map[string]any) if !isMap { return errors.New(formatErrorDescription( Locale.MustBeOfType(), ErrorDetails{"key": KeyDependencies, "type": TypeObject}, )) } - currentSchema.dependencies = make(map[string]interface{}) + currentSchema.dependencies = make(map[string]any) for k := range m { switch values := m[k].(type) { - case []interface{}: + case []any: var valuesToRegister []string for _, value := range values { str, isString := value.(string) @@ -880,7 +880,7 @@ func (d *Schema) parseDependencies(documentNode interface{}, currentSchema *SubS currentSchema.dependencies[k] = valuesToRegister } - case bool, map[string]interface{}: + case bool, map[string]any: depSchema := &SubSchema{Property: k, Parent: currentSchema, Ref: currentSchema.Ref} err := d.parseSchema(m[k], depSchema) if err != nil { @@ -913,7 +913,7 @@ func invalidType(expected, given string) error { )) } -func getString(m map[string]interface{}, key string) (*string, error) { +func getString(m map[string]any, key string) (*string, error) { v, found := m[key] if !found { // not found @@ -927,13 +927,13 @@ func getString(m map[string]interface{}, key string) (*string, error) { return &s, nil } -func getMap(m map[string]interface{}, key string) (map[string]interface{}, error) { +func getMap(m map[string]any, key string) (map[string]any, error) { v, found := m[key] if !found { // not found return nil, nil } - s, isMap := v.(map[string]interface{}) + s, isMap := v.(map[string]any) if !isMap { // wrong type return nil, invalidType(StringSchema, key) @@ -941,12 +941,12 @@ func getMap(m map[string]interface{}, key string) (map[string]interface{}, error return s, nil } -func getSlice(m map[string]interface{}, key string) ([]interface{}, error) { +func getSlice(m map[string]any, key string) ([]any, error) { v, found := m[key] if !found { return nil, nil } - s, isArray := v.([]interface{}) + s, isArray := v.([]any) if !isArray { return nil, errors.New(formatErrorDescription( Locale.MustBeOfAn(), diff --git a/internal/gojsonschema/schemaLoader.go b/internal/gojsonschema/schemaLoader.go index 8cc6dc03b8..88caa65de2 100644 --- a/internal/gojsonschema/schemaLoader.go +++ b/internal/gojsonschema/schemaLoader.go @@ -45,7 +45,7 @@ func NewSchemaLoader() *SchemaLoader { return ps } -func (sl *SchemaLoader) validateMetaschema(documentNode interface{}) error { +func (sl *SchemaLoader) validateMetaschema(documentNode any) error { var ( schema string @@ -158,7 +158,7 @@ func (sl *SchemaLoader) Compile(rootSchema JSONLoader) (*Schema, error) { d.DocumentReference = ref d.ReferencePool = newSchemaReferencePool() - var doc interface{} + var doc any if ref.String() != "" { // Get document from schema pool spd, err := d.Pool.GetDocument(d.DocumentReference) diff --git a/internal/gojsonschema/schemaPool.go b/internal/gojsonschema/schemaPool.go index ed8ff688b5..513f8df2cc 100644 --- a/internal/gojsonschema/schemaPool.go +++ b/internal/gojsonschema/schemaPool.go @@ -34,7 +34,7 @@ import ( ) type schemaPoolDocument struct { - Document interface{} + Document any Draft *Draft } @@ -44,7 +44,7 @@ type schemaPool struct { autoDetect *bool } -func (p *schemaPool) parseReferences(document interface{}, ref gojsonreference.JsonReference, pooled bool) error { +func (p *schemaPool) parseReferences(document any, ref gojsonreference.JsonReference, pooled bool) error { var ( draft *Draft @@ -72,7 +72,7 @@ func (p *schemaPool) parseReferences(document interface{}, ref gojsonreference.J return err } -func (p *schemaPool) parseReferencesRecursive(document interface{}, ref gojsonreference.JsonReference, draft *Draft) error { +func (p *schemaPool) parseReferencesRecursive(document any, ref gojsonreference.JsonReference, draft *Draft) error { // parseReferencesRecursive parses a JSON document and resolves all $id and $ref references. // For $ref references it takes into account the $id scope it is in and replaces // the reference by the absolute resolved reference @@ -80,14 +80,14 @@ func (p *schemaPool) parseReferencesRecursive(document interface{}, ref gojsonre // When encountering errors it fails silently. Error handling is done when the schema // is syntactically parsed and any error encountered here should also come up there. switch m := document.(type) { - case []interface{}: + case []any: for _, v := range m { err := p.parseReferencesRecursive(v, ref, draft) if err != nil { return err } } - case map[string]interface{}: + case map[string]any: localRef := &ref keyID := KeyIDNew @@ -129,7 +129,7 @@ func (p *schemaPool) parseReferencesRecursive(document interface{}, ref gojsonre // Something like a property or a dependency is not a valid schema, as it might describe properties named "$ref", "$id" or "const", etc // Therefore don't treat it like a schema. if k == KeyProperties || k == KeyDependencies || k == KeyPatternProperties { - if child, ok := v.(map[string]interface{}); ok { + if child, ok := v.(map[string]any); ok { for _, v := range child { err := p.parseReferencesRecursive(v, *localRef, draft) if err != nil { diff --git a/internal/gojsonschema/subSchema.go b/internal/gojsonschema/subSchema.go index d8bc0cb568..b7ceb3136e 100644 --- a/internal/gojsonschema/subSchema.go +++ b/internal/gojsonschema/subSchema.go @@ -123,8 +123,8 @@ type SubSchema struct { maxProperties *int required []string - dependencies map[string]interface{} - additionalProperties interface{} + dependencies map[string]any + additionalProperties any patternProperties map[string]*SubSchema propertyNames *SubSchema @@ -134,7 +134,7 @@ type SubSchema struct { uniqueItems bool contains *SubSchema - additionalItems interface{} + additionalItems any // validation : all _const *string //const is a golang keyword diff --git a/internal/gojsonschema/utils.go b/internal/gojsonschema/utils.go index fd0f1870f9..05808ecfd2 100644 --- a/internal/gojsonschema/utils.go +++ b/internal/gojsonschema/utils.go @@ -40,7 +40,7 @@ func isStringInSlice(s []string, what string) bool { return false } -func marshalToJSONString(value interface{}) (*string, error) { +func marshalToJSONString(value any) (*string, error) { mBytes, err := json.Marshal(value) if err != nil { @@ -51,7 +51,7 @@ func marshalToJSONString(value interface{}) (*string, error) { return &sBytes, nil } -func marshalWithoutNumber(value interface{}) (*string, error) { +func marshalWithoutNumber(value any) (*string, error) { // The JSON is decoded using https://golang.org/pkg/encoding/json/#Decoder.UseNumber // This means the numbers are internally still represented as strings and therefore 1.00 is unequal to 1 @@ -63,7 +63,7 @@ func marshalWithoutNumber(value interface{}) (*string, error) { return nil, err } - var document interface{} + var document any err = json.Unmarshal([]byte(*jsonString), &document) if err != nil { @@ -73,7 +73,7 @@ func marshalWithoutNumber(value interface{}) (*string, error) { return marshalToJSONString(document) } -func isJSONNumber(what interface{}) bool { +func isJSONNumber(what any) bool { switch what.(type) { @@ -84,7 +84,7 @@ func isJSONNumber(what interface{}) bool { return false } -func checkJSONInteger(what interface{}) (isInt bool) { +func checkJSONInteger(what any) (isInt bool) { jsonNumber := what.(json.Number) @@ -100,7 +100,7 @@ const ( minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 ) -func mustBeInteger(what interface{}) *int { +func mustBeInteger(what any) *int { number, ok := what.(json.Number) if !ok { return nil @@ -123,7 +123,7 @@ func mustBeInteger(what interface{}) *int { return &int32Value } -func mustBeNumber(what interface{}) *big.Rat { +func mustBeNumber(what any) *big.Rat { number, ok := what.(json.Number) if !ok { return nil @@ -136,11 +136,11 @@ func mustBeNumber(what interface{}) *big.Rat { return nil } -func convertDocumentNode(val interface{}) interface{} { +func convertDocumentNode(val any) any { - if lval, ok := val.([]interface{}); ok { + if lval, ok := val.([]any); ok { - res := []interface{}{} + res := []any{} for _, v := range lval { res = append(res, convertDocumentNode(v)) } @@ -149,9 +149,9 @@ func convertDocumentNode(val interface{}) interface{} { } - if mval, ok := val.(map[interface{}]interface{}); ok { + if mval, ok := val.(map[any]any); ok { - res := map[string]interface{}{} + res := map[string]any{} for k, v := range mval { res[k.(string)] = convertDocumentNode(v) diff --git a/internal/gojsonschema/validation.go b/internal/gojsonschema/validation.go index efdea58b6b..e33a0f3d27 100644 --- a/internal/gojsonschema/validation.go +++ b/internal/gojsonschema/validation.go @@ -54,21 +54,21 @@ func (v *Schema) Validate(l JSONLoader) (*Result, error) { return v.validateDocument(root), nil } -func (v *Schema) validateDocument(root interface{}) *Result { +func (v *Schema) validateDocument(root any) *Result { result := &Result{} context := NewJSONContext(StringContextRoot, nil) v.RootSchema.validateRecursive(v.RootSchema, root, result, context) return result } -func (v *SubSchema) subValidateWithContext(document interface{}, context *JSONContext) *Result { +func (v *SubSchema) subValidateWithContext(document any, context *JSONContext) *Result { result := &Result{} v.validateRecursive(v, document, result, context) return result } // Walker function to validate the json recursively against the SubSchema -func (v *SubSchema) validateRecursive(currentSubSchema *SubSchema, currentNode interface{}, result *Result, context *JSONContext) { +func (v *SubSchema) validateRecursive(currentSubSchema *SubSchema, currentNode any, result *Result, context *JSONContext) { if internalLogEnabled { internalLog("validateRecursive %s", context.String()) @@ -167,7 +167,7 @@ func (v *SubSchema) validateRecursive(currentSubSchema *SubSchema, currentNode i return } - castCurrentNode := currentNode.([]interface{}) + castCurrentNode := currentNode.([]any) currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) @@ -190,9 +190,9 @@ func (v *SubSchema) validateRecursive(currentSubSchema *SubSchema, currentNode i return } - castCurrentNode, ok := currentNode.(map[string]interface{}) + castCurrentNode, ok := currentNode.(map[string]any) if !ok { - castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{}) + castCurrentNode = convertDocumentNode(currentNode).(map[string]any) } currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) @@ -264,7 +264,7 @@ func (v *SubSchema) validateRecursive(currentSubSchema *SubSchema, currentNode i } // Different kinds of validation there, SubSchema / common / array / object / string... -func (v *SubSchema) validateSchema(currentSubSchema *SubSchema, currentNode interface{}, result *Result, context *JSONContext) { +func (v *SubSchema) validateSchema(currentSubSchema *SubSchema, currentNode any, result *Result, context *JSONContext) { if internalLogEnabled { internalLog("validateSchema %s", context.String()) @@ -349,14 +349,14 @@ func (v *SubSchema) validateSchema(currentSubSchema *SubSchema, currentNode inte } if len(currentSubSchema.dependencies) > 0 { - if currentNodeMap, ok := currentNode.(map[string]interface{}); ok { + if currentNodeMap, ok := currentNode.(map[string]any); ok { for elementKey := range currentNodeMap { if dependency, ok := currentSubSchema.dependencies[elementKey]; ok { switch dependency := dependency.(type) { case []string: for _, dependOnKey := range dependency { - if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved { + if _, dependencyResolved := currentNode.(map[string]any)[dependOnKey]; !dependencyResolved { result.addInternalError( new(MissingDependencyError), context, @@ -395,7 +395,7 @@ func (v *SubSchema) validateSchema(currentSubSchema *SubSchema, currentNode inte result.incrementScore() } -func (v *SubSchema) validateCommon(currentSubSchema *SubSchema, value interface{}, result *Result, context *JSONContext) { +func (v *SubSchema) validateCommon(currentSubSchema *SubSchema, value any, result *Result, context *JSONContext) { if internalLogEnabled { internalLog("validateCommon %s", context.String()) @@ -452,7 +452,7 @@ func (v *SubSchema) validateCommon(currentSubSchema *SubSchema, value interface{ result.incrementScore() } -func (v *SubSchema) validateArray(currentSubSchema *SubSchema, value []interface{}, result *Result, context *JSONContext) { +func (v *SubSchema) validateArray(currentSubSchema *SubSchema, value []any, result *Result, context *JSONContext) { if internalLogEnabled { internalLog("validateArray %s", context.String()) @@ -578,7 +578,7 @@ func (v *SubSchema) validateArray(currentSubSchema *SubSchema, value []interface result.incrementScore() } -func (v *SubSchema) validateObject(currentSubSchema *SubSchema, value map[string]interface{}, result *Result, context *JSONContext) { +func (v *SubSchema) validateObject(currentSubSchema *SubSchema, value map[string]any, result *Result, context *JSONContext) { if internalLogEnabled { internalLog("validateObject %s", context.String()) @@ -675,7 +675,7 @@ func (v *SubSchema) validateObject(currentSubSchema *SubSchema, value map[string result.incrementScore() } -func (v *SubSchema) validatePatternProperty(currentSubSchema *SubSchema, key string, value interface{}, result *Result, context *JSONContext) bool { +func (v *SubSchema) validatePatternProperty(currentSubSchema *SubSchema, key string, value any, result *Result, context *JSONContext) bool { if internalLogEnabled { internalLog("validatePatternProperty %s", context.String()) @@ -701,7 +701,7 @@ func (v *SubSchema) validatePatternProperty(currentSubSchema *SubSchema, key str return true } -func (v *SubSchema) validateString(currentSubSchema *SubSchema, value interface{}, result *Result, context *JSONContext) { +func (v *SubSchema) validateString(currentSubSchema *SubSchema, value any, result *Result, context *JSONContext) { // Ignore JSON numbers stringValue, isString := value.(string) @@ -752,7 +752,7 @@ func (v *SubSchema) validateString(currentSubSchema *SubSchema, value interface{ result.incrementScore() } -func (v *SubSchema) validateNumber(currentSubSchema *SubSchema, value interface{}, result *Result, context *JSONContext) { +func (v *SubSchema) validateNumber(currentSubSchema *SubSchema, value any, result *Result, context *JSONContext) { // Ignore non numbers number, isNumber := value.(json.Number) diff --git a/internal/jwx/jwa/key_type.go b/internal/jwx/jwa/key_type.go index 98f0cc42e2..61d23844a1 100644 --- a/internal/jwx/jwa/key_type.go +++ b/internal/jwx/jwa/key_type.go @@ -21,7 +21,7 @@ const ( // Accept is used when conversion from values given by // outside sources (such as JSON payloads) is required -func (keyType *KeyType) Accept(value interface{}) error { +func (keyType *KeyType) Accept(value any) error { var tmp KeyType switch x := value.(type) { case string: diff --git a/internal/jwx/jwa/signature.go b/internal/jwx/jwa/signature.go index 45e400176d..c601c46ea9 100644 --- a/internal/jwx/jwa/signature.go +++ b/internal/jwx/jwa/signature.go @@ -32,7 +32,7 @@ const ( // Accept is used when conversion from values given by // outside sources (such as JSON payloads) is required -func (signature *SignatureAlgorithm) Accept(value interface{}) error { +func (signature *SignatureAlgorithm) Accept(value any) error { var tmp SignatureAlgorithm switch x := value.(type) { case string: diff --git a/internal/jwx/jwk/ecdsa.go b/internal/jwx/jwk/ecdsa.go index b46689f037..0677f4dc30 100644 --- a/internal/jwx/jwk/ecdsa.go +++ b/internal/jwx/jwk/ecdsa.go @@ -39,12 +39,12 @@ func newECDSAPrivateKey(key *ecdsa.PrivateKey) (*ECDSAPrivateKey, error) { } // Materialize returns the EC-DSA public key represented by this JWK -func (k ECDSAPublicKey) Materialize() (interface{}, error) { +func (k ECDSAPublicKey) Materialize() (any, error) { return k.key, nil } // Materialize returns the EC-DSA private key represented by this JWK -func (k ECDSAPrivateKey) Materialize() (interface{}, error) { +func (k ECDSAPrivateKey) Materialize() (any, error) { return k.key, nil } diff --git a/internal/jwx/jwk/headers.go b/internal/jwx/jwk/headers.go index b0fd51e901..b1a6763dda 100644 --- a/internal/jwx/jwk/headers.go +++ b/internal/jwx/jwk/headers.go @@ -18,15 +18,15 @@ const ( // Headers provides a common interface to all future possible headers type Headers interface { - Get(string) (interface{}, bool) - Set(string, interface{}) error - Walk(func(string, interface{}) error) error + Get(string) (any, bool) + Set(string, any) error + Walk(func(string, any) error) error GetAlgorithm() jwa.SignatureAlgorithm GetKeyID() string GetKeyOps() KeyOperationList GetKeyType() jwa.KeyType GetKeyUsage() string - GetPrivateParams() map[string]interface{} + GetPrivateParams() map[string]any } // StandardHeaders stores the common JWK parameters @@ -36,7 +36,7 @@ type StandardHeaders struct { KeyOps KeyOperationList `json:"key_ops,omitempty"` // https://tools.ietf.org/html/rfc7517#section-4.3 KeyType jwa.KeyType `json:"kty,omitempty"` // https://tools.ietf.org/html/rfc7517#section-4.1 KeyUsage string `json:"use,omitempty"` // https://tools.ietf.org/html/rfc7517#section-4.2 - PrivateParams map[string]interface{} `json:"privateParams,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.4 + PrivateParams map[string]any `json:"privateParams,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.4 } // GetAlgorithm is a convenience function to retrieve the corresponding value stored in the StandardHeaders @@ -68,12 +68,12 @@ func (h *StandardHeaders) GetKeyUsage() string { } // GetPrivateParams is a convenience function to retrieve the corresponding value stored in the StandardHeaders -func (h *StandardHeaders) GetPrivateParams() map[string]interface{} { +func (h *StandardHeaders) GetPrivateParams() map[string]any { return h.PrivateParams } // Get is a general getter function for JWK StandardHeaders structure -func (h *StandardHeaders) Get(name string) (interface{}, bool) { +func (h *StandardHeaders) Get(name string) (any, bool) { switch name { case AlgorithmKey: alg := h.GetAlgorithm() @@ -117,7 +117,7 @@ func (h *StandardHeaders) Get(name string) (interface{}, bool) { } // Set is a general getter function for JWK StandardHeaders structure -func (h *StandardHeaders) Set(name string, value interface{}) error { +func (h *StandardHeaders) Set(name string, value any) error { switch name { case AlgorithmKey: var acceptor jwa.SignatureAlgorithm @@ -149,7 +149,7 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { } return fmt.Errorf("invalid value for %s key: %T", KeyUsageKey, value) case PrivateParamsKey: - if v, ok := value.(map[string]interface{}); ok { + if v, ok := value.(map[string]any); ok { h.PrivateParams = v return nil } @@ -160,7 +160,7 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { } // Walk iterates over all JWK standard headers fields while applying a function to its value. -func (h StandardHeaders) Walk(f func(string, interface{}) error) error { +func (h StandardHeaders) Walk(f func(string, any) error) error { for _, key := range []string{AlgorithmKey, KeyIDKey, KeyOpsKey, KeyTypeKey, KeyUsageKey, PrivateParamsKey} { if v, ok := h.Get(key); ok { if err := f(key, v); err != nil { diff --git a/internal/jwx/jwk/headers_test.go b/internal/jwx/jwk/headers_test.go index f1d64b8b5f..a900ac8e64 100644 --- a/internal/jwx/jwk/headers_test.go +++ b/internal/jwx/jwk/headers_test.go @@ -10,9 +10,9 @@ import ( func TestHeader(t *testing.T) { - privateHeaderParams := map[string]interface{}{"one": "1", "two": "11"} + privateHeaderParams := map[string]any{"one": "1", "two": "11"} t.Run("RoundTrip", func(t *testing.T) { - values := map[string]interface{}{ + values := map[string]any{ jwk.KeyIDKey: "helloworld01", jwk.KeyTypeKey: jwa.RSA, jwk.KeyOpsKey: jwk.KeyOperationList{jwk.KeyOpSign}, @@ -49,7 +49,7 @@ func TestHeader(t *testing.T) { dummy2 float64 } dummy := &dummyStruct{1, 3.4} - values := map[string]interface{}{ + values := map[string]any{ jwk.AlgorithmKey: dummy, jwk.KeyIDKey: dummy, jwk.KeyTypeKey: dummy, @@ -92,7 +92,7 @@ func TestHeader(t *testing.T) { dummy2 float64 } dummy := &dummyStruct{1, 3.4} - values := map[string]interface{}{ + values := map[string]any{ jwk.AlgorithmKey: jwa.SignatureAlgorithm("dummy"), jwk.KeyIDKey: 1, jwk.KeyTypeKey: jwa.KeyType("dummy"), @@ -131,7 +131,7 @@ func TestHeader(t *testing.T) { t.Run("Algorithm", func(t *testing.T) { var h jwk.StandardHeaders - for _, value := range []interface{}{jwa.RS256, jwa.ES256} { + for _, value := range []any{jwa.RS256, jwa.ES256} { err := h.Set("alg", value) if err != nil { t.Fatalf("Failed to set algorithm value: %s", err.Error()) @@ -147,7 +147,7 @@ func TestHeader(t *testing.T) { }) t.Run("KeyType", func(t *testing.T) { var h jwk.StandardHeaders - for _, value := range []interface{}{jwa.RSA, "RSA"} { + for _, value := range []any{jwa.RSA, "RSA"} { err := h.Set(jwk.KeyTypeKey, value) if err != nil { t.Fatalf("failed to set key type: %s", err.Error()) diff --git a/internal/jwx/jwk/interface.go b/internal/jwx/jwk/interface.go index 7a7d03ef1c..9c7846269e 100644 --- a/internal/jwx/jwk/interface.go +++ b/internal/jwx/jwk/interface.go @@ -24,7 +24,7 @@ type Key interface { // RSA types would create *rsa.PublicKey or *rsa.PrivateKey, // EC types would create *ecdsa.PublicKey or *ecdsa.PrivateKey, // and OctetSeq types create a []byte key. - Materialize() (interface{}, error) + Materialize() (any, error) GenerateKey(*RawKeyJSON) error } diff --git a/internal/jwx/jwk/jwk.go b/internal/jwx/jwk/jwk.go index 7de27d4e4e..b13245d172 100644 --- a/internal/jwx/jwk/jwk.go +++ b/internal/jwx/jwk/jwk.go @@ -15,7 +15,7 @@ import ( // For rsa key types *rsa.PublicKey is returned; for ecdsa key types *ecdsa.PublicKey; // for byte slice (raw) keys, the key itself is returned. If the corresponding // public key cannot be deduced, an error is returned -func GetPublicKey(key interface{}) (interface{}, error) { +func GetPublicKey(key any) (any, error) { if key == nil { return nil, errors.New("jwk.New requires a non-nil key") } @@ -23,7 +23,7 @@ func GetPublicKey(key interface{}) (interface{}, error) { switch v := key.(type) { // Mental note: although Public() is defined in both types, // you can not coalesce the clauses for rsa.PrivateKey and - // ecdsa.PrivateKey, as then `v` becomes interface{} + // ecdsa.PrivateKey, as then `v` becomes any // b/c the compiler cannot deduce the exact type. case *rsa.PrivateKey: return v.Public(), nil @@ -37,7 +37,7 @@ func GetPublicKey(key interface{}) (interface{}, error) { } // GetKeyTypeFromKey creates a jwk.Key from the given key. -func GetKeyTypeFromKey(key interface{}) jwa.KeyType { +func GetKeyTypeFromKey(key any) jwa.KeyType { switch key.(type) { case *rsa.PrivateKey, *rsa.PublicKey: @@ -52,7 +52,7 @@ func GetKeyTypeFromKey(key interface{}) jwa.KeyType { } // New creates a jwk.Key from the given key. -func New(key interface{}) (Key, error) { +func New(key any) (Key, error) { if key == nil { return nil, errors.New("jwk.New requires a non-nil key") } diff --git a/internal/jwx/jwk/key_ops.go b/internal/jwx/jwk/key_ops.go index c02b0b9990..628caae4ad 100644 --- a/internal/jwx/jwk/key_ops.go +++ b/internal/jwx/jwk/key_ops.go @@ -39,7 +39,7 @@ const ( ) // Accept determines if Key Operation is valid -func (keyOperationList *KeyOperationList) Accept(v interface{}) error { +func (keyOperationList *KeyOperationList) Accept(v any) error { switch x := v.(type) { case KeyOperationList: *keyOperationList = x diff --git a/internal/jwx/jwk/rsa.go b/internal/jwx/jwk/rsa.go index 11b8e3b56b..d7b5089418 100644 --- a/internal/jwx/jwk/rsa.go +++ b/internal/jwx/jwk/rsa.go @@ -65,7 +65,7 @@ func newRSAPrivateKey(key *rsa.PrivateKey) (*RSAPrivateKey, error) { } // Materialize returns the standard RSA Public Key representation stored in the internal representation -func (k *RSAPublicKey) Materialize() (interface{}, error) { +func (k *RSAPublicKey) Materialize() (any, error) { if k.key == nil { return nil, errors.New("key has no rsa.PublicKey associated with it") } @@ -73,7 +73,7 @@ func (k *RSAPublicKey) Materialize() (interface{}, error) { } // Materialize returns the standard RSA Private Key representation stored in the internal representation -func (k *RSAPrivateKey) Materialize() (interface{}, error) { +func (k *RSAPrivateKey) Materialize() (any, error) { if k.key == nil { return nil, errors.New("key has no rsa.PrivateKey associated with it") } diff --git a/internal/jwx/jwk/rsa_test.go b/internal/jwx/jwk/rsa_test.go index 5ad7060694..8007c8bb85 100644 --- a/internal/jwx/jwk/rsa_test.go +++ b/internal/jwx/jwk/rsa_test.go @@ -24,7 +24,7 @@ func TestRSA(t *testing.T) { t.Fatalf("jwk.New failed: %s", err.Error()) } - err = key.Walk(func(k string, v interface{}) error { + err = key.Walk(func(k string, v any) error { return newKey.Set(k, v) }) if err != nil { diff --git a/internal/jwx/jwk/symmetric.go b/internal/jwx/jwk/symmetric.go index e0cc0751e6..e76189f523 100644 --- a/internal/jwx/jwk/symmetric.go +++ b/internal/jwx/jwk/symmetric.go @@ -21,7 +21,7 @@ func newSymmetricKey(key []byte) (*SymmetricKey, error) { // Materialize returns the octets for this symmetric key. // Since this is a symmetric key, this just calls Octets -func (s SymmetricKey) Materialize() (interface{}, error) { +func (s SymmetricKey) Materialize() (any, error) { return s.Octets(), nil } diff --git a/internal/jwx/jws/headers.go b/internal/jwx/jws/headers.go index 0c8b355087..dcadea43e2 100644 --- a/internal/jwx/jws/headers.go +++ b/internal/jwx/jws/headers.go @@ -20,8 +20,8 @@ const ( // Headers provides a common interface for common header parameters type Headers interface { - Get(string) (interface{}, bool) - Set(string, interface{}) error + Get(string) (any, bool) + Set(string, any) error GetAlgorithm() jwa.SignatureAlgorithm } @@ -33,7 +33,7 @@ type StandardHeaders struct { JWK string `json:"jwk,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.3 JWKSetURL string `json:"jku,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.2 KeyID string `json:"kid,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.4 - PrivateParams map[string]interface{} `json:"privateParams,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.9 + PrivateParams map[string]any `json:"privateParams,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.9 Type string `json:"typ,omitempty"` // https://tools.ietf.org/html/rfc7515#section-4.1.9 } @@ -43,7 +43,7 @@ func (h *StandardHeaders) GetAlgorithm() jwa.SignatureAlgorithm { } // Get is a general getter function for StandardHeaders structure -func (h *StandardHeaders) Get(name string) (interface{}, bool) { +func (h *StandardHeaders) Get(name string) (any, bool) { switch name { case AlgorithmKey: v := h.Algorithm @@ -99,7 +99,7 @@ func (h *StandardHeaders) Get(name string) (interface{}, bool) { } // Set is a general setter function for StandardHeaders structure -func (h *StandardHeaders) Set(name string, value interface{}) error { +func (h *StandardHeaders) Set(name string, value any) error { switch name { case AlgorithmKey: if err := h.Algorithm.Accept(value); err != nil { @@ -137,7 +137,7 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { } return fmt.Errorf("invalid value for %s key: %T", KeyIDKey, value) case PrivateParamsKey: - if v, ok := value.(map[string]interface{}); ok { + if v, ok := value.(map[string]any); ok { h.PrivateParams = v return nil } diff --git a/internal/jwx/jws/headers_test.go b/internal/jwx/jws/headers_test.go index 7327972f03..8a092b3378 100644 --- a/internal/jwx/jws/headers_test.go +++ b/internal/jwx/jws/headers_test.go @@ -18,9 +18,9 @@ func TestHeader(t *testing.T) { "kid": "2011-04-29" }` - privateHeaderParams := map[string]interface{}{"one": "1", "two": "11"} + privateHeaderParams := map[string]any{"one": "1", "two": "11"} - values := map[string]interface{}{ + values := map[string]any{ jws.AlgorithmKey: jwa.ES256, jws.ContentTypeKey: "example", jws.CriticalKey: []string{"exp"}, @@ -81,7 +81,7 @@ func TestHeader(t *testing.T) { } dummy := &dummyStruct{1, 3.4} - values := map[string]interface{}{ + values := map[string]any{ jws.AlgorithmKey: dummy, jws.ContentTypeKey: dummy, jws.CriticalKey: dummy, diff --git a/internal/jwx/jws/jws.go b/internal/jwx/jws/jws.go index 20fb957d3e..b2b2248306 100644 --- a/internal/jwx/jws/jws.go +++ b/internal/jwx/jws/jws.go @@ -38,7 +38,7 @@ import ( // SignLiteral generates a Signature for the given Payload and Headers, and serializes // it in compact serialization format. In this format you may NOT use // multiple signers. -func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, hdrBuf []byte, rnd io.Reader) ([]byte, error) { +func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key any, hdrBuf []byte, rnd io.Reader) ([]byte, error) { encodedHdr := base64.RawURLEncoding.EncodeToString(hdrBuf) encodedPayload := base64.RawURLEncoding.EncodeToString(payload) signingInput := strings.Join( @@ -77,7 +77,7 @@ func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, hd // multiple signers. // // If you would like to pass custom Headers, use the WithHeaders option. -func SignWithOption(payload []byte, alg jwa.SignatureAlgorithm, key interface{}) ([]byte, error) { +func SignWithOption(payload []byte, alg jwa.SignatureAlgorithm, key any) ([]byte, error) { var headers Headers = &StandardHeaders{} err := headers.Set(AlgorithmKey, alg) @@ -99,7 +99,7 @@ func SignWithOption(payload []byte, alg jwa.SignatureAlgorithm, key interface{}) // Payload that was signed is returned. If you need more fine-grained // control of the verification process, manually call `Parse`, generate a // verifier, and call `Verify` on the parsed JWS message object. -func Verify(buf []byte, alg jwa.SignatureAlgorithm, key interface{}) (ret []byte, err error) { +func Verify(buf []byte, alg jwa.SignatureAlgorithm, key any) (ret []byte, err error) { verifier, err := verify.New(alg) if err != nil { diff --git a/internal/jwx/jws/sign/ecdsa.go b/internal/jwx/jws/sign/ecdsa.go index db1aadec67..5f3e8accad 100644 --- a/internal/jwx/jws/sign/ecdsa.go +++ b/internal/jwx/jws/sign/ecdsa.go @@ -72,7 +72,7 @@ func (s ECDSASigner) Algorithm() jwa.SignatureAlgorithm { // SignWithRand signs payload with a ECDSA private key and a provided randomness // source (such as `rand.Reader`). -func (s ECDSASigner) SignWithRand(payload []byte, key interface{}, r io.Reader) ([]byte, error) { +func (s ECDSASigner) SignWithRand(payload []byte, key any, r io.Reader) ([]byte, error) { if key == nil { return nil, errors.New("missing private key while signing payload") } @@ -85,6 +85,6 @@ func (s ECDSASigner) SignWithRand(payload []byte, key interface{}, r io.Reader) } // Sign signs payload with a ECDSA private key -func (s ECDSASigner) Sign(payload []byte, key interface{}) ([]byte, error) { +func (s ECDSASigner) Sign(payload []byte, key any) ([]byte, error) { return s.SignWithRand(payload, key, rand.Reader) } diff --git a/internal/jwx/jws/sign/hmac.go b/internal/jwx/jws/sign/hmac.go index a4fad4208b..de541755ef 100644 --- a/internal/jwx/jws/sign/hmac.go +++ b/internal/jwx/jws/sign/hmac.go @@ -52,7 +52,7 @@ func (s HMACSigner) Algorithm() jwa.SignatureAlgorithm { } // Sign signs payload with a Symmetric key -func (s HMACSigner) Sign(payload []byte, key interface{}) ([]byte, error) { +func (s HMACSigner) Sign(payload []byte, key any) ([]byte, error) { hmackey, ok := key.([]byte) if !ok { return nil, fmt.Errorf(`invalid key type %T. []byte is required`, key) diff --git a/internal/jwx/jws/sign/interface.go b/internal/jwx/jws/sign/interface.go index 2ef2bee486..25b592ed4e 100644 --- a/internal/jwx/jws/sign/interface.go +++ b/internal/jwx/jws/sign/interface.go @@ -16,7 +16,7 @@ type Signer interface { // for `jwa.RSXXX` and `jwa.PSXXX` types, you need to pass the // `*"crypto/rsa".PrivateKey` type. // Check the documentation for each signer for details - Sign(payload []byte, key interface{}) ([]byte, error) + Sign(payload []byte, key any) ([]byte, error) Algorithm() jwa.SignatureAlgorithm } diff --git a/internal/jwx/jws/sign/rsa.go b/internal/jwx/jws/sign/rsa.go index 1e02993eb0..a671b7318a 100644 --- a/internal/jwx/jws/sign/rsa.go +++ b/internal/jwx/jws/sign/rsa.go @@ -84,7 +84,7 @@ func (s RSASigner) Algorithm() jwa.SignatureAlgorithm { // Sign creates a signature using crypto/rsa. key must be a non-nil instance of // `*"crypto/rsa".PrivateKey`. -func (s RSASigner) Sign(payload []byte, key interface{}) ([]byte, error) { +func (s RSASigner) Sign(payload []byte, key any) ([]byte, error) { if key == nil { return nil, errors.New(`missing private key while signing payload`) } diff --git a/internal/jwx/jws/sign/sign.go b/internal/jwx/jws/sign/sign.go index fd123eb759..c1432236fb 100644 --- a/internal/jwx/jws/sign/sign.go +++ b/internal/jwx/jws/sign/sign.go @@ -26,7 +26,7 @@ func New(alg jwa.SignatureAlgorithm) (Signer, error) { // GetSigningKey returns a *rsa.PrivateKey or *ecdsa.PrivateKey typically encoded in PEM blocks of type "RSA PRIVATE KEY" // or "EC PRIVATE KEY" for RSA and ECDSA family of algorithms. // For HMAC family, it return a []byte value -func GetSigningKey(key string, alg jwa.SignatureAlgorithm) (interface{}, error) { +func GetSigningKey(key string, alg jwa.SignatureAlgorithm) (any, error) { switch alg { case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512: block, _ := pem.Decode([]byte(key)) diff --git a/internal/jwx/jws/verify/ecdsa.go b/internal/jwx/jws/verify/ecdsa.go index 0d4971dc19..ba32078ac9 100644 --- a/internal/jwx/jws/verify/ecdsa.go +++ b/internal/jwx/jws/verify/ecdsa.go @@ -54,7 +54,7 @@ func newECDSA(alg jwa.SignatureAlgorithm) (*ECDSAVerifier, error) { } // Verify checks whether the signature for a given input and key is correct -func (v ECDSAVerifier) Verify(payload []byte, signature []byte, key interface{}) error { +func (v ECDSAVerifier) Verify(payload []byte, signature []byte, key any) error { if key == nil { return errors.New(`missing public key while verifying payload`) } diff --git a/internal/jwx/jws/verify/hmac.go b/internal/jwx/jws/verify/hmac.go index d8498f50f2..25651a0f8d 100644 --- a/internal/jwx/jws/verify/hmac.go +++ b/internal/jwx/jws/verify/hmac.go @@ -19,7 +19,7 @@ func newHMAC(alg jwa.SignatureAlgorithm) (*HMACVerifier, error) { } // Verify checks whether the signature for a given input and key is correct -func (v HMACVerifier) Verify(signingInput, signature []byte, key interface{}) (err error) { +func (v HMACVerifier) Verify(signingInput, signature []byte, key any) (err error) { expected, err := v.signer.Sign(signingInput, key) if err != nil { diff --git a/internal/jwx/jws/verify/interface.go b/internal/jwx/jws/verify/interface.go index f5beb69741..e72c3ed7f7 100644 --- a/internal/jwx/jws/verify/interface.go +++ b/internal/jwx/jws/verify/interface.go @@ -16,7 +16,7 @@ type Verifier interface { // for `jwa.RSXXX` and `jwa.PSXXX` types, you need to pass the // `*"crypto/rsa".PublicKey` type. // Check the documentation for each verifier for details - Verify(payload []byte, signature []byte, key interface{}) error + Verify(payload []byte, signature []byte, key any) error } type rsaVerifyFunc func([]byte, []byte, *rsa.PublicKey) error diff --git a/internal/jwx/jws/verify/rsa.go b/internal/jwx/jws/verify/rsa.go index edc560dfa6..163ff84bcf 100644 --- a/internal/jwx/jws/verify/rsa.go +++ b/internal/jwx/jws/verify/rsa.go @@ -75,7 +75,7 @@ func newRSA(alg jwa.SignatureAlgorithm) (*RSAVerifier, error) { } // Verify checks if a JWS is valid. -func (v RSAVerifier) Verify(payload, signature []byte, key interface{}) error { +func (v RSAVerifier) Verify(payload, signature []byte, key any) error { if key == nil { return errors.New(`missing public key while verifying payload`) } diff --git a/internal/jwx/jws/verify/verify.go b/internal/jwx/jws/verify/verify.go index 04ee9141e9..7370b4a2f1 100644 --- a/internal/jwx/jws/verify/verify.go +++ b/internal/jwx/jws/verify/verify.go @@ -29,7 +29,7 @@ func New(alg jwa.SignatureAlgorithm) (Verifier, error) { // GetSigningKey returns a *rsa.PublicKey or *ecdsa.PublicKey typically encoded in PEM blocks of type "PUBLIC KEY", // for RSA and ECDSA family of algorithms. // For HMAC family, it return a []byte value -func GetSigningKey(key string, alg jwa.SignatureAlgorithm) (interface{}, error) { +func GetSigningKey(key string, alg jwa.SignatureAlgorithm) (any, error) { switch alg { case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512, jwa.ES256, jwa.ES384, jwa.ES512: block, _ := pem.Decode([]byte(key)) diff --git a/internal/lcss/lcss_test.go b/internal/lcss/lcss_test.go index 854a6e3ae3..54b8cdf80c 100644 --- a/internal/lcss/lcss_test.go +++ b/internal/lcss/lcss_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -func assertEqual(t *testing.T, expected, actual interface{}) { +func assertEqual(t *testing.T, expected, actual any) { t.Helper() if !reflect.DeepEqual(expected, actual) { diff --git a/internal/logging/logging_test.go b/internal/logging/logging_test.go index 6e0d882f04..e3cc8a4982 100644 --- a/internal/logging/logging_test.go +++ b/internal/logging/logging_test.go @@ -143,11 +143,11 @@ public_servers[server] { func TestPrettyFormatterMultilineJSONFields(t *testing.T) { fmtr := prettyFormatter{} - obj := map[string]interface{}{ + obj := map[string]any{ "a": 123, "b": nil, "d": "abc", - "e": map[string]interface{}{ + "e": map[string]any{ "test": []string{ "aa", "bb", diff --git a/internal/merge/merge.go b/internal/merge/merge.go index 16f39350be..ba1a09c329 100644 --- a/internal/merge/merge.go +++ b/internal/merge/merge.go @@ -8,7 +8,7 @@ package merge // InterfaceMaps returns the result of merging a and b. If a and b cannot be // merged because of conflicting key-value pairs, ok is false. -func InterfaceMaps(a map[string]interface{}, b map[string]interface{}) (map[string]interface{}, bool) { +func InterfaceMaps(a map[string]any, b map[string]any) (map[string]any, bool) { if a == nil { return b, true @@ -21,7 +21,7 @@ func InterfaceMaps(a map[string]interface{}, b map[string]interface{}) (map[stri return merge(a, b), true } -func merge(a, b map[string]interface{}) map[string]interface{} { +func merge(a, b map[string]any) map[string]any { for k := range b { @@ -32,8 +32,8 @@ func merge(a, b map[string]interface{}) map[string]interface{} { continue } - existObj := exist.(map[string]interface{}) - addObj := add.(map[string]interface{}) + existObj := exist.(map[string]any) + addObj := add.(map[string]any) a[k] = merge(existObj, addObj) } @@ -41,7 +41,7 @@ func merge(a, b map[string]interface{}) map[string]interface{} { return a } -func hasConflicts(a, b map[string]interface{}) bool { +func hasConflicts(a, b map[string]any) bool { for k := range b { add := b[k] @@ -50,8 +50,8 @@ func hasConflicts(a, b map[string]interface{}) bool { continue } - existObj, existOk := exist.(map[string]interface{}) - addObj, addOk := add.(map[string]interface{}) + existObj, existOk := exist.(map[string]any) + addObj, addOk := add.(map[string]any) if !existOk || !addOk { return true } diff --git a/internal/merge/merge_test.go b/internal/merge/merge_test.go index 3200662bfa..94c04fe26d 100644 --- a/internal/merge/merge_test.go +++ b/internal/merge/merge_test.go @@ -26,16 +26,16 @@ func TestMergeDocs(t *testing.T) { } for _, tc := range tests { - a := map[string]interface{}{} + a := map[string]any{} if err := util.UnmarshalJSON([]byte(tc.a), &a); err != nil { panic(err) } - aInitial := map[string]interface{}{} + aInitial := map[string]any{} if err := util.UnmarshalJSON([]byte(tc.a), &aInitial); err != nil { panic(err) } - b := map[string]interface{}{} + b := map[string]any{} if err := util.UnmarshalJSON([]byte(tc.b), &b); err != nil { panic(err) } @@ -53,7 +53,7 @@ func TestMergeDocs(t *testing.T) { } else { - expected := map[string]interface{}{} + expected := map[string]any{} if err := util.UnmarshalJSON([]byte(tc.c), &expected); err != nil { panic(err) } diff --git a/internal/planner/planner.go b/internal/planner/planner.go index 661703e08c..b26e7d5205 100644 --- a/internal/planner/planner.go +++ b/internal/planner/planner.go @@ -51,10 +51,10 @@ type Planner struct { // debugf prepends the planner location. We're passing callstack depth 2 because // it should still log the file location of p.debugf. -func (p *Planner) debugf(format string, args ...interface{}) { +func (p *Planner) debugf(format string, args ...any) { var msg string if p.loc != nil { - msg = fmt.Sprintf("%s: "+format, append([]interface{}{p.loc}, args...)...) + msg = fmt.Sprintf("%s: "+format, append([]any{p.loc}, args...)...) } else { msg = fmt.Sprintf(format, args...) } diff --git a/internal/planner/planner_test.go b/internal/planner/planner_test.go index 74c504b33b..1bd92705ba 100644 --- a/internal/planner/planner_test.go +++ b/internal/planner/planner_test.go @@ -428,13 +428,13 @@ q = 2`, } type cmpWalker struct { - needle interface{} + needle any loc string found bool // stop comparing after first found needle } -func (*cmpWalker) Before(interface{}) {} -func (*cmpWalker) After(interface{}) {} +func (*cmpWalker) Before(any) {} +func (*cmpWalker) After(any) {} // Visit takes, for example, // @@ -447,7 +447,7 @@ func (*cmpWalker) After(interface{}) {} // Caveat: If NO value of the desired type is found, there's no error // returned. This trap can be avoided by starting with a failing test, // and proceeding with caution. ;) -func (f *cmpWalker) Visit(x interface{}) (ir.Visitor, error) { +func (f *cmpWalker) Visit(x any) (ir.Visitor, error) { if !f.found && reflect.TypeOf(f.needle) == reflect.TypeOf(x) { f.found = true expLoc := f.loc @@ -459,7 +459,7 @@ func (f *cmpWalker) Visit(x interface{}) (ir.Visitor, error) { return f, nil } -func getLocation(x interface{}) string { +func getLocation(x any) string { v := reflect.ValueOf(x).Elem().FieldByName("Location") li := v.Interface() file := v.FieldByName("file").String() @@ -470,7 +470,7 @@ func getLocation(x interface{}) string { return "unknown" } -func findInPolicy(needle interface{}, loc string, p interface{}) error { +func findInPolicy(needle any, loc string, p any) error { return ir.Walk(&cmpWalker{needle: needle, loc: loc}, p) } @@ -479,7 +479,7 @@ func findInPolicy(needle interface{}, loc string, p interface{}) error { // counted differently in the editor vs. in code. func TestPlannerLocations(t *testing.T) { - funcs := func(p *ir.Policy) interface{} { + funcs := func(p *ir.Policy) any { return p.Funcs } @@ -487,8 +487,8 @@ func TestPlannerLocations(t *testing.T) { note string queries []string modules []string - exps map[ir.Stmt]string // stmt -> expected location "file:row:col: text" - where func(*ir.Policy) interface{} // where to start walking search for `exps` + exps map[ir.Stmt]string // stmt -> expected location "file:row:col: text" + where func(*ir.Policy) any // where to start walking search for `exps` }{ { note: "complete rule reference", @@ -567,7 +567,7 @@ p = x if { &ir.MakeObjectStmt{}: `module-0.rego:3:9: p = {"foo": "bar"}`, &ir.AssignVarOnceStmt{}: `module-0.rego:3:9: p = {"foo": "bar"}`, }, - where: func(p *ir.Policy) interface{} { + where: func(p *ir.Policy) any { return p.Funcs.Funcs[0].Blocks[2] // default rule block }, }, @@ -634,7 +634,7 @@ q = 2 if { &ir.CallStmt{}: ":1:1: data", &ir.ObjectInsertStmt{}: ":1:1: data", }, - where: func(p *ir.Policy) interface{} { + where: func(p *ir.Policy) any { return p.Plans.Plans[0].Blocks[0].Stmts[4] }, }, @@ -650,7 +650,7 @@ a = true`}, &ir.ResultSetAddStmt{}: ":1:1: data[y].a = x", &ir.DotStmt{}: ":1:1: data[y].a = x", }, - where: func(p *ir.Policy) interface{} { + where: func(p *ir.Policy) any { return p.Plans.Plans[0] }, }, @@ -713,7 +713,7 @@ a if { t.Fatal(err) } } - start := interface{}(policy) + start := any(policy) if tc.where != nil { start = tc.where(policy) } @@ -1130,17 +1130,17 @@ func TestPlannerCallDynamic(t *testing.T) { note string queries []string modules []string - path []interface{} // path expected on irCallDynamicStmt, string => string const, int => local - where func(*ir.Policy) interface{} // where to start walking search for `exps` - extras []func(interface{}) error + path []any // path expected on irCallDynamicStmt, string => string const, int => local + where func(*ir.Policy) any // where to start walking search for `exps` + extras []func(any) error }{ { note: "CallDynamicStmt optimization", queries: []string{`x := "a"; data.test[x] = y`}, modules: []string{`package test a if { true }`}, - path: []interface{}{"g0", "test", 2}, - extras: []func(interface{}) error{ + path: []any{"g0", "test", 2}, + extras: []func(any) error{ findFunc("g0.data.test.a", "g0.test.a"), }, }, @@ -1149,8 +1149,8 @@ a if { true }`}, queries: []string{`x := "a"; data.test.a[x].c = y`}, modules: []string{`package test a.b.c = 1 if { true }`}, - path: []interface{}{"g0", "test", "a", 2, "c"}, - extras: []func(interface{}) error{ + path: []any{"g0", "test", "a", 2, "c"}, + extras: []func(any) error{ findFunc("g0.data.test.a.b.c", "g0.test.a.b.c"), }, }, @@ -1160,8 +1160,8 @@ a.b.c = 1 if { true }`}, modules: []string{`package test a.b.c = 1 if { true } a.b[t] = 2 if { t := input }`}, - path: []interface{}{"g0", "test", "a", 2}, - extras: []func(interface{}) error{ + path: []any{"g0", "test", "a", 2}, + extras: []func(any) error{ findFunc("g0.data.test.a.b", "g0.test.a.b"), }, }, @@ -1171,8 +1171,8 @@ a.b[t] = 2 if { t := input }`}, modules: []string{`package test a.b[1] = 1 if { true } a.b[t] = 2 if { t := input }`}, - path: []interface{}{"g0", "test", "a", 2}, - extras: []func(interface{}) error{ + path: []any{"g0", "test", "a", 2}, + extras: []func(any) error{ findFunc("g0.data.test.a.b", "g0.test.a.b"), }, }, @@ -1181,8 +1181,8 @@ a.b[t] = 2 if { t := input }`}, queries: []string{`x := "a"; data.test.a[x] = y`}, modules: []string{`package test a.b[1] = 1 if { true }`}, - path: []interface{}{"g0", "test", "a", 2}, - extras: []func(interface{}) error{ + path: []any{"g0", "test", "a", 2}, + extras: []func(any) error{ findFunc("g0.data.test.a.b", "g0.test.a.b"), }, }, @@ -1222,7 +1222,7 @@ a.b[1] = 1 if { true }`}, t.Fatal(err) } } - start := interface{}(policy) + start := any(policy) if tc.where != nil { start = tc.where(policy) } @@ -1255,13 +1255,13 @@ a.b[1] = 1 if { true }`}, } type stmtCmpWalker struct { - stmt interface{} + stmt any found bool // stop comparing after first found needle } -func (*stmtCmpWalker) Before(interface{}) {} -func (*stmtCmpWalker) After(interface{}) {} -func (w *stmtCmpWalker) Visit(x interface{}) (ir.Visitor, error) { +func (*stmtCmpWalker) Before(any) {} +func (*stmtCmpWalker) After(any) {} +func (w *stmtCmpWalker) Visit(x any) (ir.Visitor, error) { if !w.found { switch s := w.stmt.(type) { case *ir.CallDynamicStmt: @@ -1285,7 +1285,7 @@ func (w *stmtCmpWalker) Visit(x interface{}) (ir.Visitor, error) { return w, nil } -func findCallDynamic(path []ir.Operand, p interface{}) error { +func findCallDynamic(path []ir.Operand, p any) error { w := &stmtCmpWalker{stmt: &ir.CallDynamicStmt{Path: path}} if err := ir.Walk(w, p); err != nil { return err @@ -1296,8 +1296,8 @@ func findCallDynamic(path []ir.Operand, p interface{}) error { return nil } -func findFunc(name, path string) func(interface{}) error { - return func(p interface{}) error { +func findFunc(name, path string) func(any) error { + return func(p any) error { w := &stmtCmpWalker{stmt: &ir.Func{Name: name, Path: strings.Split(path, ".")}} if err := ir.Walk(w, p); err != nil { return err diff --git a/internal/presentation/presentation.go b/internal/presentation/presentation.go index 3168c63b2f..7f89f24312 100644 --- a/internal/presentation/presentation.go +++ b/internal/presentation/presentation.go @@ -114,7 +114,7 @@ type Output struct { Result rego.ResultSet `json:"result,omitempty"` Partial *rego.PartialQueries `json:"partial,omitempty"` Metrics metrics.Metrics `json:"metrics,omitempty"` - AggregatedMetrics map[string]interface{} `json:"aggregated_metrics,omitempty"` + AggregatedMetrics map[string]any `json:"aggregated_metrics,omitempty"` Explanation []*topdown.Event `json:"explanation,omitempty"` Profile []profiler.ExprStats `json:"profile,omitempty"` AggregatedProfile []profiler.ExprStatsAggregated `json:"aggregated_profile,omitempty"` @@ -236,7 +236,7 @@ type OutputError struct { Message string `json:"message"` Code string `json:"code,omitempty"` Location *ast.Location `json:"location,omitempty"` - Details interface{} `json:"details,omitempty"` + Details any `json:"details,omitempty"` err error } @@ -245,7 +245,7 @@ func (j OutputError) Error() string { } // JSON writes x to w with indentation. -func JSON(w io.Writer, x interface{}) error { +func JSON(w io.Writer, x any) error { encoder := json.NewEncoder(w) encoder.SetIndent("", " ") return encoder.Encode(x) @@ -270,7 +270,7 @@ func Values(w io.Writer, r Output) error { return prettyError(w, r.Errors) } for _, rs := range r.Result { - line := make([]interface{}, len(rs.Expressions)) + line := make([]any, len(rs.Expressions)) for i := range line { line[i] = rs.Expressions[i].Value } @@ -406,7 +406,7 @@ func Raw(w io.Writer, r Output) error { return nil } -func Discard(w io.Writer, x interface{}) error { +func Discard(w io.Writer, x any) error { encoder := json.NewEncoder(w) encoder.SetIndent("", " ") field, ok := x.(Output) @@ -417,7 +417,7 @@ func Discard(w io.Writer, x interface{}) error { if err != nil { return err } - var rawData map[string]interface{} + var rawData map[string]any err = json.Unmarshal(bs, &rawData) if err != nil { return err @@ -486,7 +486,7 @@ func prettyPartial(w io.Writer, pq *rego.PartialQueries) error { } // prettyASTNode is used for pretty-printing the result of partial eval -func prettyASTNode(x interface{}, regoVersion ast.RegoVersion) (string, int, error) { +func prettyASTNode(x any, regoVersion ast.RegoVersion) (string, int, error) { bs, err := format.AstWithOpts(x, format.Opts{IgnoreLocations: true, RegoVersion: regoVersion}) if err != nil { return "", 0, fmt.Errorf("format error: %w", err) @@ -513,7 +513,7 @@ func prettyMetrics(w io.Writer, m metrics.Metrics, limit int) error { var statKeys = []string{"min", "max", "mean", "90%", "99%"} -func prettyAggregatedMetrics(w io.Writer, ms map[string]interface{}, limit int) error { +func prettyAggregatedMetrics(w io.Writer, ms map[string]any, limit int) error { keys := []string{"metric"} tableMetrics := generateTableWithKeys(w, append(keys, statKeys...)...) populateTableAggregatedMetrics(ms, tableMetrics, limit) @@ -548,7 +548,7 @@ func prettyAggregatedProfile(w io.Writer, profile []profiler.ExprStatsAggregated for _, rs := range profile { line := []string{} for _, k := range statKeys { - v := rs.ExprTimeNsStats.(map[string]interface{})[k] + v := rs.ExprTimeNsStats.(map[string]any)[k] if f, ok := v.(float64); ok { line = append(line, time.Duration(f).String()) } else if i, ok := v.(int64); ok { @@ -649,7 +649,7 @@ func generateTableProfile(writer io.Writer) *tablewriter.Table { func populateTableMetrics(m metrics.Metrics, table *tablewriter.Table, prettyLimit int) { lines := [][]string{} for varName, varValueInterface := range m.All() { - val, ok := varValueInterface.(map[string]interface{}) + val, ok := varValueInterface.(map[string]any) if !ok { line := []string{} varValue := checkStrLimit(fmt.Sprintf("%v", varValueInterface), prettyLimit) @@ -669,11 +669,11 @@ func populateTableMetrics(m metrics.Metrics, table *tablewriter.Table, prettyLim table.AppendBulk(lines) } -func populateTableAggregatedMetrics(ms map[string]interface{}, table *tablewriter.Table, prettyLimit int) { +func populateTableAggregatedMetrics(ms map[string]any, table *tablewriter.Table, prettyLimit int) { lines := [][]string{} for name, vals := range ms { line := []string{name} - vs := vals.(map[string]interface{}) + vs := vals.(map[string]any) for _, k := range statKeys { line = append(line, checkStrLimit(fmt.Sprintf("%v", vs[k]), prettyLimit)) } @@ -712,7 +712,7 @@ func (rk resultKey) string() string { return rk.exprText } -func (rk resultKey) selectVarValue(result rego.Result) interface{} { +func (rk resultKey) selectVarValue(result rego.Result) any { if rk.varName != "" { return result.Bindings[rk.varName] } diff --git a/internal/presentation/presentation_test.go b/internal/presentation/presentation_test.go index ec4799f010..974ad38868 100644 --- a/internal/presentation/presentation_test.go +++ b/internal/presentation/presentation_test.go @@ -127,7 +127,7 @@ func TestOutputJSONErrorStructuredASTErr(t *testing.T) { func TestOutputJSONErrorStructuredStorageErr(t *testing.T) { store := inmem.New() txn := storage.NewTransactionOrDie(context.Background(), store) - err := store.Write(context.Background(), txn, storage.AddOp, storage.Path{}, map[string]interface{}{"foo": 1}) + err := store.Write(context.Background(), txn, storage.AddOp, storage.Path{}, map[string]any{"foo": 1}) expected := `{ "errors": [ { @@ -470,9 +470,9 @@ func TestRaw(t *testing.T) { Result: []rego.Result{ { Expressions: []*rego.ExpressionValue{ - {Value: []interface{}{"one"}}, - {Value: map[string]interface{}{ - "key": []interface{}{}, + {Value: []any{"one"}}, + {Value: map[string]any{ + "key": []any{}, }}, }, }, diff --git a/internal/prometheus/prometheus.go b/internal/prometheus/prometheus.go index feab3617fe..c84d38d0ec 100644 --- a/internal/prometheus/prometheus.go +++ b/internal/prometheus/prometheus.go @@ -34,7 +34,7 @@ type Provider struct { logger loggerFunc } -type loggerFunc func(attrs map[string]interface{}, f string, a ...interface{}) +type loggerFunc func(attrs map[string]any, f string, a ...any) // New returns a new Provider object. func New(inner metrics.Metrics, logger loggerFunc, httpRequestBuckets []float64) *Provider { @@ -102,13 +102,13 @@ func (*Provider) Info() metrics.Info { // All returns the union of the inner metric provider and the underlying // prometheus registry. -func (p *Provider) All() map[string]interface{} { +func (p *Provider) All() map[string]any { all := p.inner.All() families, err := p.registry.Gather() if err != nil && p.logger != nil { - p.logger(map[string]interface{}{ + p.logger(map[string]any{ "err": err, }, "Failed to gather metrics from Prometheus registry.") } diff --git a/internal/prometheus/prometheus_test.go b/internal/prometheus/prometheus_test.go index d3233b61f9..7d1b92908a 100644 --- a/internal/prometheus/prometheus_test.go +++ b/internal/prometheus/prometheus_test.go @@ -19,7 +19,7 @@ import ( func TestJSONSerialization(t *testing.T) { inner := metrics.New() logger := func(logger logging.Logger) loggerFunc { - return func(attrs map[string]interface{}, f string, a ...interface{}) { + return func(attrs map[string]any, f string, a ...any) { logger.WithFields(attrs).Error(f, a...) } }(logging.NewNoOpLogger()) @@ -32,7 +32,7 @@ func TestJSONSerialization(t *testing.T) { t.Fatal(err) } - act := make(map[string]map[string]interface{}, len(m)) + act := make(map[string]map[string]any, len(m)) err = json.Unmarshal(bs, &act) if err != nil { t.Fatal(err) diff --git a/internal/providers/aws/util.go b/internal/providers/aws/util.go index 9ce9af90da..d43339c961 100644 --- a/internal/providers/aws/util.go +++ b/internal/providers/aws/util.go @@ -18,7 +18,7 @@ func DoRequestWithClient(req *http.Request, client *http.Client, desc string, lo } defer resp.Body.Close() - logger.WithFields(map[string]interface{}{ + logger.WithFields(map[string]any{ "url": req.URL.String(), "status": resp.Status, "headers": resp.Header, diff --git a/internal/rego/opa/engine.go b/internal/rego/opa/engine.go index 36ee844504..7defdf788c 100644 --- a/internal/rego/opa/engine.go +++ b/internal/rego/opa/engine.go @@ -36,10 +36,10 @@ type EvalEngine interface { Init() (EvalEngine, error) Entrypoints(context.Context) (map[string]int32, error) WithPolicyBytes([]byte) EvalEngine - WithDataJSON(interface{}) EvalEngine + WithDataJSON(any) EvalEngine Eval(context.Context, EvalOpts) (*Result, error) - SetData(context.Context, interface{}) error - SetDataPath(context.Context, []string, interface{}) error + SetData(context.Context, any) error + SetDataPath(context.Context, []string, any) error RemoveDataPath(context.Context, []string) error Close() } diff --git a/internal/rego/opa/options.go b/internal/rego/opa/options.go index 072e37667a..97aa41bf0e 100644 --- a/internal/rego/opa/options.go +++ b/internal/rego/opa/options.go @@ -18,7 +18,7 @@ type Result struct { // EvalOpts define options for performing an evaluation. type EvalOpts struct { - Input *interface{} + Input *any Metrics metrics.Metrics Entrypoint int32 Time time.Time diff --git a/internal/report/report_test.go b/internal/report/report_test.go index ba07867a95..e7a0caca75 100644 --- a/internal/report/report_test.go +++ b/internal/report/report_test.go @@ -218,7 +218,7 @@ func TestSlice(t *testing.T) { } } -func getTestServer(update interface{}, statusCode int) (baseURL string, teardownFn func()) { +func getTestServer(update any, statusCode int) (baseURL string, teardownFn func()) { mux := http.NewServeMux() ts := httptest.NewServer(mux) diff --git a/internal/runtime/init/init_test.go b/internal/runtime/init/init_test.go index fe2983da8b..db1cae01d8 100644 --- a/internal/runtime/init/init_test.go +++ b/internal/runtime/init/init_test.go @@ -206,12 +206,12 @@ func TestLoadTarGzsInBundleAndNonBundleMode(t *testing.T) { Manifest: bundle.Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "foo": "bar1", - "x": map[string]interface{}{ - "y": map[string]interface{}{ - "z": []interface{}{json.Number("1")}, + "x": map[string]any{ + "y": map[string]any{ + "z": []any{json.Number("1")}, }, }, }, @@ -229,12 +229,12 @@ func TestLoadTarGzsInBundleAndNonBundleMode(t *testing.T) { Manifest: bundle.Manifest{ Roots: &[]string{"b"}, }, - Data: map[string]interface{}{ - "b": map[string]interface{}{ + Data: map[string]any{ + "b": map[string]any{ "foo": "bar2", - "x": map[string]interface{}{ - "y": map[string]interface{}{ - "z": []interface{}{json.Number("1")}, + "x": map[string]any{ + "y": map[string]any{ + "z": []any{json.Number("1")}, }, }, }, @@ -257,12 +257,12 @@ func TestLoadTarGzsInBundleAndNonBundleMode(t *testing.T) { Manifest: bundle.Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "foo1": "bar2", - "x": map[string]interface{}{ - "y": map[string]interface{}{ - "z": []interface{}{json.Number("2")}, + "x": map[string]any{ + "y": map[string]any{ + "z": []any{json.Number("2")}, }, }, }, diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index cff00aba34..81c93a0ed6 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -37,7 +37,7 @@ func Term(params Params) (*ast.Term, error) { if params.Config != nil { - var x interface{} + var x any if err := util.Unmarshal(params.Config, &x); err != nil { return nil, err } diff --git a/internal/storage/mock/mock.go b/internal/storage/mock/mock.go index 4fdcac888e..3c23ad586d 100644 --- a/internal/storage/mock/mock.go +++ b/internal/storage/mock/mock.go @@ -46,7 +46,7 @@ func (t *Transaction) safeToUse() bool { type Store struct { inmem storage.Store storeOpts []inmem.Opt - baseData map[string]interface{} + baseData map[string]any Transactions []*Transaction Reads []*ReadCall Writes []*WriteCall @@ -79,7 +79,7 @@ func New(opt ...inmem.Opt) *Store { } // NewWithData creates a store with some initial data -func NewWithData(data map[string]interface{}, opt ...inmem.Opt) *Store { +func NewWithData(data map[string]any, opt ...inmem.Opt) *Store { s := &Store{ baseData: data, storeOpts: opt, @@ -194,7 +194,7 @@ func (s *Store) NewTransaction(ctx context.Context, params ...storage.Transactio // add a new entry to the mock store Reads list. If there // is an error are the read is unsafe it will be noted in // the ReadCall. -func (s *Store) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (interface{}, error) { +func (s *Store) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (any, error) { mockTxn := txn.(*Transaction) data, err := s.inmem.Read(ctx, mockTxn.txn, path) @@ -213,7 +213,7 @@ func (s *Store) Read(ctx context.Context, txn storage.Transaction, path storage. // add a new entry to the mock store Writes list. If there // is an error are the write is unsafe it will be noted in // the WriteCall. -func (s *Store) Write(ctx context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value interface{}) error { +func (s *Store) Write(ctx context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value any) error { mockTxn := txn.(*Transaction) err := s.inmem.Write(ctx, mockTxn.txn, op, path, value) diff --git a/internal/strvals/parser.go b/internal/strvals/parser.go index 3b12d9526b..6d867262f5 100644 --- a/internal/strvals/parser.go +++ b/internal/strvals/parser.go @@ -46,8 +46,8 @@ func ToYAML(s string) (string, error) { // Parse parses a set line. // // A set line is of the form name1=value1,name2=value2 -func Parse(s string) (map[string]interface{}, error) { - vals := map[string]interface{}{} +func Parse(s string) (map[string]any, error) { + vals := map[string]any{} scanner := bytes.NewBufferString(s) t := newParser(scanner, vals, false) err := t.parse() @@ -57,8 +57,8 @@ func Parse(s string) (map[string]interface{}, error) { // ParseString parses a set line and forces a string value. // // A set line is of the form name1=value1,name2=value2 -func ParseString(s string) (map[string]interface{}, error) { - vals := map[string]interface{}{} +func ParseString(s string) (map[string]any, error) { + vals := map[string]any{} scanner := bytes.NewBufferString(s) t := newParser(scanner, vals, true) err := t.parse() @@ -69,7 +69,7 @@ func ParseString(s string) (map[string]interface{}, error) { // // If the strval string has a key that exists in dest, it overwrites the // dest version. -func ParseInto(s string, dest map[string]interface{}) error { +func ParseInto(s string, dest map[string]any) error { scanner := bytes.NewBufferString(s) t := newParser(scanner, dest, false) return t.parse() @@ -78,7 +78,7 @@ func ParseInto(s string, dest map[string]interface{}) error { // ParseIntoFile parses a filevals line and merges the result into dest. // // This method always returns a string as the value. -func ParseIntoFile(s string, dest map[string]interface{}, runesToVal runesToVal) error { +func ParseIntoFile(s string, dest map[string]any, runesToVal runesToVal) error { scanner := bytes.NewBufferString(s) t := newFileParser(scanner, dest, runesToVal) return t.parse() @@ -87,7 +87,7 @@ func ParseIntoFile(s string, dest map[string]interface{}, runesToVal runesToVal) // ParseIntoString parses a strvals line and merges the result into dest. // // This method always returns a string as the value. -func ParseIntoString(s string, dest map[string]interface{}) error { +func ParseIntoString(s string, dest map[string]any) error { scanner := bytes.NewBufferString(s) t := newParser(scanner, dest, true) return t.parse() @@ -101,20 +101,20 @@ func ParseIntoString(s string, dest map[string]interface{}) error { // where st is a boolean to figure out if we're forcing it to parse values as string type parser struct { sc *bytes.Buffer - data map[string]interface{} + data map[string]any runesToVal runesToVal } -type runesToVal func([]rune) (interface{}, error) +type runesToVal func([]rune) (any, error) -func newParser(sc *bytes.Buffer, data map[string]interface{}, stringBool bool) *parser { - rs2v := func(rs []rune) (interface{}, error) { +func newParser(sc *bytes.Buffer, data map[string]any, stringBool bool) *parser { + rs2v := func(rs []rune) (any, error) { return typedVal(rs, stringBool), nil } return &parser{sc: sc, data: data, runesToVal: rs2v} } -func newFileParser(sc *bytes.Buffer, data map[string]interface{}, runesToVal runesToVal) *parser { +func newFileParser(sc *bytes.Buffer, data map[string]any, runesToVal runesToVal) *parser { return &parser{sc: sc, data: data, runesToVal: runesToVal} } @@ -139,7 +139,7 @@ func runeSet(r []rune) map[rune]bool { return s } -func (t *parser) key(data map[string]interface{}) error { +func (t *parser) key(data map[string]any) error { stop := runeSet([]rune{'=', '[', ',', '.'}) for { switch k, last, err := runesUntil(t.sc, stop); { @@ -156,9 +156,9 @@ func (t *parser) key(data map[string]interface{}) error { } kk := string(k) // Find or create target list - list := []interface{}{} + list := []any{} if _, ok := data[kk]; ok { - list = data[kk].([]interface{}) + list = data[kk].([]any) } // Now we need to get the value after the ]. @@ -194,9 +194,9 @@ func (t *parser) key(data map[string]interface{}) error { return fmt.Errorf("key %q has no value (cannot end with ,)", string(k)) case last == '.': // First, create or find the target map. - inner := map[string]interface{}{} + inner := map[string]any{} if _, ok := data[string(k)]; ok { - inner = data[string(k)].(map[string]interface{}) + inner = data[string(k)].(map[string]any) } // Recurse @@ -210,7 +210,7 @@ func (t *parser) key(data map[string]interface{}) error { } } -func set(data map[string]interface{}, key string, val interface{}) { +func set(data map[string]any, key string, val any) { // If key is empty, don't set it. if len(key) == 0 { return @@ -218,7 +218,7 @@ func set(data map[string]interface{}, key string, val interface{}) { data[key] = val } -func setIndex(list []interface{}, index int, val interface{}) (l2 []interface{}, err error) { +func setIndex(list []any, index int, val any) (l2 []any, err error) { // There are possible index values that are out of range on a target system // causing a panic. This will catch the panic and return an error instead. // The value of the index that causes a panic varies from system to system. @@ -235,7 +235,7 @@ func setIndex(list []interface{}, index int, val interface{}) (l2 []interface{}, return list, fmt.Errorf("index of %d is greater than maximum supported index of %d", index, MaxIndex) } if len(list) <= index { - newlist := make([]interface{}, index+1) + newlist := make([]any, index+1) copy(newlist, list) list = newlist } @@ -254,7 +254,7 @@ func (t *parser) keyIndex() (int, error) { return strconv.Atoi(string(v)) } -func (t *parser) listItem(list []interface{}, i int) ([]interface{}, error) { +func (t *parser) listItem(list []any, i int) ([]any, error) { if i < 0 { return list, fmt.Errorf("negative %d index not allowed", i) } @@ -298,14 +298,14 @@ func (t *parser) listItem(list []interface{}, i int) ([]interface{}, error) { return setIndex(list, i, list2) case last == '.': // We have a nested object. Send to t.key - inner := map[string]interface{}{} + inner := map[string]any{} if len(list) > i { var ok bool - inner, ok = list[i].(map[string]interface{}) + inner, ok = list[i].(map[string]any) if !ok { // We have indices out of order. Initialize empty value. - list[i] = map[string]interface{}{} - inner = list[i].(map[string]interface{}) + list[i] = map[string]any{} + inner = list[i].(map[string]any) } } @@ -326,21 +326,21 @@ func (t *parser) val() ([]rune, error) { return v, err } -func (t *parser) valList() ([]interface{}, error) { +func (t *parser) valList() ([]any, error) { r, _, e := t.sc.ReadRune() if e != nil { - return []interface{}{}, e + return []any{}, e } if r != '{' { e = t.sc.UnreadRune() if e != nil { - return []interface{}{}, e + return []any{}, e } - return []interface{}{}, ErrNotList + return []any{}, ErrNotList } - list := []interface{}{} + list := []any{} stop := runeSet([]rune{',', '}'}) for { switch rs, last, err := runesUntil(t.sc, stop); { @@ -354,7 +354,7 @@ func (t *parser) valList() ([]interface{}, error) { if r, _, e := t.sc.ReadRune(); e == nil && r != ',' { e = t.sc.UnreadRune() if e != nil { - return []interface{}{}, e + return []any{}, e } } v, e := t.runesToVal(rs) @@ -395,7 +395,7 @@ func inMap(k rune, m map[rune]bool) bool { return ok } -func typedVal(v []rune, st bool) interface{} { +func typedVal(v []rune, st bool) any { val := string(v) if st { diff --git a/internal/strvals/parser_test.go b/internal/strvals/parser_test.go index c395430c84..937400c7a7 100644 --- a/internal/strvals/parser_test.go +++ b/internal/strvals/parser_test.go @@ -25,45 +25,45 @@ import ( func TestSetIndex(t *testing.T) { tests := []struct { name string - initial []interface{} - expect []interface{} + initial []any + expect []any add int val int err bool }{ { name: "short", - initial: []interface{}{0, 1}, - expect: []interface{}{0, 1, 2}, + initial: []any{0, 1}, + expect: []any{0, 1, 2}, add: 2, val: 2, }, { name: "equal", - initial: []interface{}{0, 1}, - expect: []interface{}{0, 2}, + initial: []any{0, 1}, + expect: []any{0, 2}, add: 1, val: 2, }, { name: "long", - initial: []interface{}{0, 1, 2, 3, 4, 5}, - expect: []interface{}{0, 1, 2, 4, 4, 5}, + initial: []any{0, 1, 2, 3, 4, 5}, + expect: []any{0, 1, 2, 4, 4, 5}, add: 3, val: 4, }, { name: "negative", - initial: []interface{}{0, 1, 2, 3, 4, 5}, - expect: []interface{}{0, 1, 2, 3, 4, 5}, + initial: []any{0, 1, 2, 3, 4, 5}, + expect: []any{0, 1, 2, 3, 4, 5}, add: -1, val: 4, err: true, }, { name: "large", - initial: []interface{}{0, 1, 2, 3, 4, 5}, - expect: []interface{}{0, 1, 2, 3, 4, 5}, + initial: []any{0, 1, 2, 3, 4, 5}, + expect: []any{0, 1, 2, 3, 4, 5}, add: MaxIndex + 1, val: 4, err: true, @@ -100,53 +100,53 @@ func TestSetIndex(t *testing.T) { func TestParseSet(t *testing.T) { testsString := []struct { str string - expect map[string]interface{} + expect map[string]any err bool }{ { str: "long_int_string=1234567890", - expect: map[string]interface{}{"long_int_string": "1234567890"}, + expect: map[string]any{"long_int_string": "1234567890"}, err: false, }, { str: "boolean=true", - expect: map[string]interface{}{"boolean": "true"}, + expect: map[string]any{"boolean": "true"}, err: false, }, { str: "is_null=null", - expect: map[string]interface{}{"is_null": "null"}, + expect: map[string]any{"is_null": "null"}, err: false, }, { str: "zero=0", - expect: map[string]interface{}{"zero": "0"}, + expect: map[string]any{"zero": "0"}, err: false, }, } tests := []struct { str string - expect map[string]interface{} + expect map[string]any err bool }{ { "name1=null,f=false,t=true", - map[string]interface{}{"name1": map[string]interface{}{}, "f": false, "t": true}, + map[string]any{"name1": map[string]any{}, "f": false, "t": true}, false, }, { "name1=value1", - map[string]interface{}{"name1": "value1"}, + map[string]any{"name1": "value1"}, false, }, { "name1=value1,name2=value2", - map[string]interface{}{"name1": "value1", "name2": "value2"}, + map[string]any{"name1": "value1", "name2": "value2"}, false, }, { "name1=value1,name2=value2,", - map[string]interface{}{"name1": "value1", "name2": "value2"}, + map[string]any{"name1": "value1", "name2": "value2"}, false, }, { @@ -155,27 +155,27 @@ func TestParseSet(t *testing.T) { }, { str: "name1=,name2=value2", - expect: map[string]interface{}{"name1": "", "name2": "value2"}, + expect: map[string]any{"name1": "", "name2": "value2"}, }, { str: "leading_zeros=00009", - expect: map[string]interface{}{"leading_zeros": "00009"}, + expect: map[string]any{"leading_zeros": "00009"}, }, { str: "zero_int=0", - expect: map[string]interface{}{"zero_int": 0}, + expect: map[string]any{"zero_int": 0}, }, { str: "long_int=1234567890", - expect: map[string]interface{}{"long_int": 1234567890}, + expect: map[string]any{"long_int": 1234567890}, }, { str: "boolean=true", - expect: map[string]interface{}{"boolean": true}, + expect: map[string]any{"boolean": true}, }, { str: "is_null=null", - expect: map[string]interface{}{"is_null": map[string]interface{}{}}, + expect: map[string]any{"is_null": map[string]any{}}, err: false, }, { @@ -196,40 +196,40 @@ func TestParseSet(t *testing.T) { }, { "name1=one\\,two,name2=three\\,four", - map[string]interface{}{"name1": "one,two", "name2": "three,four"}, + map[string]any{"name1": "one,two", "name2": "three,four"}, false, }, { "name1=one\\=two,name2=three\\=four", - map[string]interface{}{"name1": "one=two", "name2": "three=four"}, + map[string]any{"name1": "one=two", "name2": "three=four"}, false, }, { "name1=one two three,name2=three two one", - map[string]interface{}{"name1": "one two three", "name2": "three two one"}, + map[string]any{"name1": "one two three", "name2": "three two one"}, false, }, { "outer.inner=value", - map[string]interface{}{"outer": map[string]interface{}{"inner": "value"}}, + map[string]any{"outer": map[string]any{"inner": "value"}}, false, }, { "outer.middle.inner=value", - map[string]interface{}{"outer": map[string]interface{}{"middle": map[string]interface{}{"inner": "value"}}}, + map[string]any{"outer": map[string]any{"middle": map[string]any{"inner": "value"}}}, false, }, { "outer.inner1=value,outer.inner2=value2", - map[string]interface{}{"outer": map[string]interface{}{"inner1": "value", "inner2": "value2"}}, + map[string]any{"outer": map[string]any{"inner1": "value", "inner2": "value2"}}, false, }, { "outer.inner1=value,outer.middle.inner=value", - map[string]interface{}{ - "outer": map[string]interface{}{ + map[string]any{ + "outer": map[string]any{ "inner1": "value", - "middle": map[string]interface{}{ + "middle": map[string]any{ "inner": "value", }, }, @@ -246,7 +246,7 @@ func TestParseSet(t *testing.T) { }, { str: "name1.name2=", - expect: map[string]interface{}{"name1": map[string]interface{}{"name2": ""}}, + expect: map[string]any{"name1": map[string]any{"name2": ""}}, }, { str: "name1.=name2", @@ -258,12 +258,12 @@ func TestParseSet(t *testing.T) { }, { "name1={value1,value2}", - map[string]interface{}{"name1": []string{"value1", "value2"}}, + map[string]any{"name1": []string{"value1", "value2"}}, false, }, { "name1={value1,value2},name2={value1,value2}", - map[string]interface{}{ + map[string]any{ "name1": []string{"value1", "value2"}, "name2": []string{"value1", "value2"}, }, @@ -271,12 +271,12 @@ func TestParseSet(t *testing.T) { }, { "name1={1021,902}", - map[string]interface{}{"name1": []int{1021, 902}}, + map[string]any{"name1": []int{1021, 902}}, false, }, { "name1.name2={value1,value2}", - map[string]interface{}{"name1": map[string]interface{}{"name2": []string{"value1", "value2"}}}, + map[string]any{"name1": map[string]any{"name2": []string{"value1", "value2"}}}, false, }, { @@ -286,35 +286,35 @@ func TestParseSet(t *testing.T) { // List support { str: "list[0]=foo", - expect: map[string]interface{}{"list": []string{"foo"}}, + expect: map[string]any{"list": []string{"foo"}}, }, { str: "list[0].foo=bar", - expect: map[string]interface{}{ - "list": []interface{}{ - map[string]interface{}{"foo": "bar"}, + expect: map[string]any{ + "list": []any{ + map[string]any{"foo": "bar"}, }, }, }, { str: "list[0].foo=bar,list[0].hello=world", - expect: map[string]interface{}{ - "list": []interface{}{ - map[string]interface{}{"foo": "bar", "hello": "world"}, + expect: map[string]any{ + "list": []any{ + map[string]any{"foo": "bar", "hello": "world"}, }, }, }, { str: "list[0]=foo,list[1]=bar", - expect: map[string]interface{}{"list": []string{"foo", "bar"}}, + expect: map[string]any{"list": []string{"foo", "bar"}}, }, { str: "list[0]=foo,list[1]=bar,", - expect: map[string]interface{}{"list": []string{"foo", "bar"}}, + expect: map[string]any{"list": []string{"foo", "bar"}}, }, { str: "list[0]=foo,list[3]=bar", - expect: map[string]interface{}{"list": []interface{}{"foo", nil, nil, "bar"}}, + expect: map[string]any{"list": []any{"foo", nil, nil, "bar"}}, }, { str: "illegal[0]name.foo=bar", @@ -322,41 +322,41 @@ func TestParseSet(t *testing.T) { }, { str: "noval[0]", - expect: map[string]interface{}{"noval": []interface{}{}}, + expect: map[string]any{"noval": []any{}}, }, { str: "noval[0]=", - expect: map[string]interface{}{"noval": []interface{}{""}}, + expect: map[string]any{"noval": []any{""}}, }, { str: "nested[0][0]=1", - expect: map[string]interface{}{"nested": []interface{}{[]interface{}{1}}}, + expect: map[string]any{"nested": []any{[]any{1}}}, }, { str: "nested[1][1]=1", - expect: map[string]interface{}{"nested": []interface{}{nil, []interface{}{nil, 1}}}, + expect: map[string]any{"nested": []any{nil, []any{nil, 1}}}, }, { str: "name1.name2[0].foo=bar,name1.name2[1].foo=bar", - expect: map[string]interface{}{ - "name1": map[string]interface{}{ - "name2": []map[string]interface{}{{"foo": "bar"}, {"foo": "bar"}}, + expect: map[string]any{ + "name1": map[string]any{ + "name2": []map[string]any{{"foo": "bar"}, {"foo": "bar"}}, }, }, }, { str: "name1.name2[1].foo=bar,name1.name2[0].foo=bar", - expect: map[string]interface{}{ - "name1": map[string]interface{}{ - "name2": []map[string]interface{}{{"foo": "bar"}, {"foo": "bar"}}, + expect: map[string]any{ + "name1": map[string]any{ + "name2": []map[string]any{{"foo": "bar"}, {"foo": "bar"}}, }, }, }, { str: "name1.name2[1].foo=bar", - expect: map[string]interface{}{ - "name1": map[string]interface{}{ - "name2": []map[string]interface{}{nil, {"foo": "bar"}}, + expect: map[string]any{ + "name1": map[string]any{ + "name2": []map[string]any{nil, {"foo": "bar"}}, }, }, }, @@ -415,15 +415,15 @@ func TestParseSet(t *testing.T) { } func TestParseInto(t *testing.T) { - got := map[string]interface{}{ - "outer": map[string]interface{}{ + got := map[string]any{ + "outer": map[string]any{ "inner1": "overwrite", "inner2": "value2", }, } input := "outer.inner1=value1,outer.inner3=value3,outer.inner4=4" - expect := map[string]interface{}{ - "outer": map[string]interface{}{ + expect := map[string]any{ + "outer": map[string]any{ "inner1": "value1", "inner2": "value2", "inner3": "value3", @@ -449,15 +449,15 @@ func TestParseInto(t *testing.T) { } } func TestParseIntoString(t *testing.T) { - got := map[string]interface{}{ - "outer": map[string]interface{}{ + got := map[string]any{ + "outer": map[string]any{ "inner1": "overwrite", "inner2": "value2", }, } input := "outer.inner1=1,outer.inner3=3" - expect := map[string]interface{}{ - "outer": map[string]interface{}{ + expect := map[string]any{ + "outer": map[string]any{ "inner1": "1", "inner2": "value2", "inner3": "3", @@ -483,12 +483,12 @@ func TestParseIntoString(t *testing.T) { } func TestParseIntoFile(t *testing.T) { - got := map[string]interface{}{} + got := map[string]any{} input := "name1=path1" - expect := map[string]interface{}{ + expect := map[string]any{ "name1": "value1", } - rs2v := func(rs []rune) (interface{}, error) { + rs2v := func(rs []rune) (any, error) { v := string(rs) if v != "path1" { t.Errorf("%s: runesToVal: Expected value path1, got %s", input, v) diff --git a/internal/uuid/uuid.go b/internal/uuid/uuid.go index 5d925e68df..a18f024a25 100644 --- a/internal/uuid/uuid.go +++ b/internal/uuid/uuid.go @@ -32,12 +32,12 @@ func New(r io.Reader) (string, error) { // if parsing fails, it will return an empty map. It will fill the map // with some decoded values with fillMap // ref: https://datatracker.ietf.org/doc/html/rfc4122 -func Parse(s string) (map[string]interface{}, error) { +func Parse(s string) (map[string]any, error) { uuid, err := uuid.Parse(s) if err != nil { return nil, err } - out := make(map[string]interface{}, getVersionLen(int(uuid.Version()))) + out := make(map[string]any, getVersionLen(int(uuid.Version()))) fillMap(out, uuid) return out, nil } @@ -46,7 +46,7 @@ func Parse(s string) (map[string]interface{}, error) { // Version 1-2 has decodable values that could be of use, version 4 is random, // and version 3,5 is not feasible to extract data. Generated with either MD5 or SHA1 hash // ref: https://datatracker.ietf.org/doc/html/rfc4122 about creation of UUIDs -func fillMap(m map[string]interface{}, u uuid.UUID) { +func fillMap(m map[string]any, u uuid.UUID) { m["version"] = int(u.Version()) m["variant"] = u.Variant().String() switch version := m["version"]; version { diff --git a/internal/uuid/uuid_test.go b/internal/uuid/uuid_test.go index b62862add9..71686d3c41 100644 --- a/internal/uuid/uuid_test.go +++ b/internal/uuid/uuid_test.go @@ -25,12 +25,12 @@ func TestParseTrue(t *testing.T) { var tests = []struct { name string input string - ans map[string]interface{} + ans map[string]any }{ { "Test uuid 1", "c2fc67c2-47f2-11ee-b67a-9f3619c7493f", - map[string]interface{}{ + map[string]any{ "version": 1, "variant": "RFC4122", "nodeid": "9f-36-19-c7-49-3f", @@ -41,7 +41,7 @@ func TestParseTrue(t *testing.T) { { "Test uuid 2", "000003e8-48b9-21ee-b200-325096b39f47", - map[string]interface{}{ + map[string]any{ "version": 2, "variant": "RFC4122", "nodeid": "32-50-96-b3-9f-47", @@ -55,7 +55,7 @@ func TestParseTrue(t *testing.T) { { "Test uuid 3", "6bea8ef2-d3d3-3cd1-84e0-9bab06a52ece", - map[string]interface{}{ + map[string]any{ "version": 3, "variant": "RFC4122", }, @@ -63,12 +63,12 @@ func TestParseTrue(t *testing.T) { { "Test uuid 4", "00000000-0000-4000-8000-000000000000", - map[string]interface{}{"version": 4, "variant": "RFC4122"}, + map[string]any{"version": 4, "variant": "RFC4122"}, }, { "Test uuid 5", "00000000-0000-5cd1-84e0-9bab06a52ece", - map[string]interface{}{ + map[string]any{ "version": 5, "variant": "RFC4122", }, @@ -76,7 +76,7 @@ func TestParseTrue(t *testing.T) { { "Test future version and variant", "00000000-0000-fcd1-f4e0-9bab06a52ece", - map[string]interface{}{ + map[string]any{ "version": 15, "variant": "Future", }, @@ -84,7 +84,7 @@ func TestParseTrue(t *testing.T) { { "Test urn format", "urn:uuid:c2fc67c2-47f2-11ee-b67a-9f3619c7493f", - map[string]interface{}{ + map[string]any{ "version": 1, "variant": "RFC4122", "nodeid": "9f-36-19-c7-49-3f", @@ -95,7 +95,7 @@ func TestParseTrue(t *testing.T) { { "Test uuid with brackets", "{000003e8-48b9-21ee-b200-325096b39f47}", - map[string]interface{}{ + map[string]any{ "version": 2, "variant": "RFC4122", "nodeid": "32-50-96-b3-9f-47", @@ -109,7 +109,7 @@ func TestParseTrue(t *testing.T) { { "Test uuid without dashes", "00000000000040008000000000000000", - map[string]interface{}{"version": 4, "variant": "RFC4122"}, + map[string]any{"version": 4, "variant": "RFC4122"}, }, } for _, tt := range tests { diff --git a/internal/version/version.go b/internal/version/version.go index dc52733fc2..1264278e44 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -24,7 +24,7 @@ func Write(ctx context.Context, store storage.Store, txn storage.Transaction) er return err } - return store.Write(ctx, txn, storage.AddOp, versionPath, map[string]interface{}{ + return store.Write(ctx, txn, storage.AddOp, versionPath, map[string]any{ "version": version.Version, "build_commit": version.Vcs, "build_timestamp": version.Timestamp, diff --git a/internal/wasm/instruction/control.go b/internal/wasm/instruction/control.go index 38f030982d..0b2805247f 100644 --- a/internal/wasm/instruction/control.go +++ b/internal/wasm/instruction/control.go @@ -112,8 +112,8 @@ func (Br) Op() opcode.Opcode { } // ImmediateArgs returns the block index to break to. -func (i Br) ImmediateArgs() []interface{} { - return []interface{}{i.Index} +func (i Br) ImmediateArgs() []any { + return []any{i.Index} } // BrIf represents a WASM br_if instruction. @@ -127,8 +127,8 @@ func (BrIf) Op() opcode.Opcode { } // ImmediateArgs returns the block index to break to. -func (i BrIf) ImmediateArgs() []interface{} { - return []interface{}{i.Index} +func (i BrIf) ImmediateArgs() []any { + return []any{i.Index} } // Call represents a WASM call instruction. @@ -142,8 +142,8 @@ func (Call) Op() opcode.Opcode { } // ImmediateArgs returns the function index. -func (i Call) ImmediateArgs() []interface{} { - return []interface{}{i.Index} +func (i Call) ImmediateArgs() []any { + return []any{i.Index} } // CallIndirect represents a WASM call_indirect instruction. @@ -158,8 +158,8 @@ func (CallIndirect) Op() opcode.Opcode { } // ImmediateArgs returns the function index. -func (i CallIndirect) ImmediateArgs() []interface{} { - return []interface{}{i.Index, i.Reserved} +func (i CallIndirect) ImmediateArgs() []any { + return []any{i.Index, i.Reserved} } // Return represents a WASM return instruction. diff --git a/internal/wasm/instruction/instruction.go b/internal/wasm/instruction/instruction.go index 066be77c44..a0ab5953b8 100644 --- a/internal/wasm/instruction/instruction.go +++ b/internal/wasm/instruction/instruction.go @@ -15,14 +15,14 @@ type NoImmediateArgs struct { } // ImmediateArgs returns the immedate arguments of an instruction. -func (NoImmediateArgs) ImmediateArgs() []interface{} { +func (NoImmediateArgs) ImmediateArgs() []any { return nil } // Instruction represents a single WASM instruction. type Instruction interface { Op() opcode.Opcode - ImmediateArgs() []interface{} + ImmediateArgs() []any } // StructuredInstruction represents a structured control instruction like br_if. diff --git a/internal/wasm/instruction/memory.go b/internal/wasm/instruction/memory.go index c449cb1b6a..5a052bb764 100644 --- a/internal/wasm/instruction/memory.go +++ b/internal/wasm/instruction/memory.go @@ -18,8 +18,8 @@ func (I32Load) Op() opcode.Opcode { } // ImmediateArgs returns the static offset and alignment operands. -func (i I32Load) ImmediateArgs() []interface{} { - return []interface{}{i.Align, i.Offset} +func (i I32Load) ImmediateArgs() []any { + return []any{i.Align, i.Offset} } // I32Store represents the WASM i32.store instruction. @@ -34,6 +34,6 @@ func (I32Store) Op() opcode.Opcode { } // ImmediateArgs returns the static offset and alignment operands. -func (i I32Store) ImmediateArgs() []interface{} { - return []interface{}{i.Align, i.Offset} +func (i I32Store) ImmediateArgs() []any { + return []any{i.Align, i.Offset} } diff --git a/internal/wasm/instruction/numeric.go b/internal/wasm/instruction/numeric.go index 03f33752a2..bbba1f0bcb 100644 --- a/internal/wasm/instruction/numeric.go +++ b/internal/wasm/instruction/numeric.go @@ -19,8 +19,8 @@ func (I32Const) Op() opcode.Opcode { } // ImmediateArgs returns the i32 value to push onto the stack. -func (i I32Const) ImmediateArgs() []interface{} { - return []interface{}{i.Value} +func (i I32Const) ImmediateArgs() []any { + return []any{i.Value} } // I64Const represents the WASM i64.const instruction. @@ -34,8 +34,8 @@ func (I64Const) Op() opcode.Opcode { } // ImmediateArgs returns the i64 value to push onto the stack. -func (i I64Const) ImmediateArgs() []interface{} { - return []interface{}{i.Value} +func (i I64Const) ImmediateArgs() []any { + return []any{i.Value} } // F32Const represents the WASM f32.const instruction. @@ -49,8 +49,8 @@ func (F32Const) Op() opcode.Opcode { } // ImmediateArgs returns the f32 value to push onto the stack. -func (i F32Const) ImmediateArgs() []interface{} { - return []interface{}{i.Value} +func (i F32Const) ImmediateArgs() []any { + return []any{i.Value} } // F64Const represents the WASM f64.const instruction. @@ -64,8 +64,8 @@ func (F64Const) Op() opcode.Opcode { } // ImmediateArgs returns the f64 value to push onto the stack. -func (i F64Const) ImmediateArgs() []interface{} { - return []interface{}{i.Value} +func (i F64Const) ImmediateArgs() []any { + return []any{i.Value} } // I32Eqz represents the WASM i32.eqz instruction. diff --git a/internal/wasm/instruction/variable.go b/internal/wasm/instruction/variable.go index 063ffdb96d..68be486af1 100644 --- a/internal/wasm/instruction/variable.go +++ b/internal/wasm/instruction/variable.go @@ -17,8 +17,8 @@ func (GetLocal) Op() opcode.Opcode { } // ImmediateArgs returns the index of the local variable to push onto the stack. -func (i GetLocal) ImmediateArgs() []interface{} { - return []interface{}{i.Index} +func (i GetLocal) ImmediateArgs() []any { + return []any{i.Index} } // SetLocal represents the WASM set_local instruction. @@ -33,8 +33,8 @@ func (SetLocal) Op() opcode.Opcode { // ImmediateArgs returns the index of the local variable to set with the top of // the stack. -func (i SetLocal) ImmediateArgs() []interface{} { - return []interface{}{i.Index} +func (i SetLocal) ImmediateArgs() []any { + return []any{i.Index} } // TeeLocal represents the WASM tee_local instruction. @@ -49,6 +49,6 @@ func (TeeLocal) Op() opcode.Opcode { // ImmediateArgs returns the index of the local variable to "tee" with the top of // the stack (like set, but retaining the top of the stack). -func (i TeeLocal) ImmediateArgs() []interface{} { - return []interface{}{i.Index} +func (i TeeLocal) ImmediateArgs() []any { + return []any{i.Index} } diff --git a/internal/wasm/sdk/examples/basic/main.go b/internal/wasm/sdk/examples/basic/main.go index 3ddfcdcb82..62c9ce69f8 100644 --- a/internal/wasm/sdk/examples/basic/main.go +++ b/internal/wasm/sdk/examples/basic/main.go @@ -41,7 +41,7 @@ func main() { // Evaluate the policy once. - var input interface{} = map[string]interface{}{ + var input any = map[string]any{ "foo": true, "bar": false, } diff --git a/internal/wasm/sdk/examples/loaders/main.go b/internal/wasm/sdk/examples/loaders/main.go index a499aab436..008706fc12 100644 --- a/internal/wasm/sdk/examples/loaders/main.go +++ b/internal/wasm/sdk/examples/loaders/main.go @@ -45,7 +45,7 @@ func main() { // Evaluate the policy. - var input interface{} = map[string]interface{}{ + var input any = map[string]any{ "foo": true, } diff --git a/internal/wasm/sdk/internal/wasm/pool.go b/internal/wasm/sdk/internal/wasm/pool.go index 7cbbc0bb90..6bc16c9b1f 100644 --- a/internal/wasm/sdk/internal/wasm/pool.go +++ b/internal/wasm/sdk/internal/wasm/pool.go @@ -217,7 +217,7 @@ func (p *Pool) SetPolicyData(ctx context.Context, policy []byte, data []byte) er // SetDataPath will update the current data on the VMs by setting the value at the // specified path. If an error occurs the instance is still in a valid state, however // the data will not have been modified. -func (p *Pool) SetDataPath(ctx context.Context, path []string, value interface{}) error { +func (p *Pool) SetDataPath(ctx context.Context, path []string, value any) error { p.dataMtx.Lock() defer p.dataMtx.Unlock() return p.updateVMs(func(vm *VM, _ vmOpts) error { diff --git a/internal/wasm/sdk/internal/wasm/pool_test.go b/internal/wasm/sdk/internal/wasm/pool_test.go index fe1ac18e0f..526b87639b 100644 --- a/internal/wasm/sdk/internal/wasm/pool_test.go +++ b/internal/wasm/sdk/internal/wasm/pool_test.go @@ -32,7 +32,7 @@ func TestOpaEvalGrowMemoryForLargeInput(t *testing.T) { ` data := []byte(`{}`) s := strings.Repeat("a", 16*wasm_util.PageSize) - input := interface{}([]byte(s)) + input := any([]byte(s)) poolSize := 1 testPool := initPoolWithData(t, uint32(poolSize), module, "test/p", data) @@ -115,7 +115,7 @@ func TestPoolCopyParsedDataUpdatePartial(t *testing.T) { // Each case is applied in order to the original dataset cases := []struct { note string - update interface{} + update any path []string remove bool expected string @@ -165,7 +165,7 @@ func TestPoolCopyParsedDataUpdatePartial(t *testing.T) { } } -func ensurePoolResults(t *testing.T, ctx context.Context, testPool *wasm.Pool, poolSize int, input *interface{}, expected string) { +func ensurePoolResults(t *testing.T, ctx context.Context, testPool *wasm.Pool, poolSize int, input *any, expected string) { t.Helper() var toRelease []*wasm.VM for i := 0; i < poolSize; i++ { diff --git a/internal/wasm/sdk/internal/wasm/vm.go b/internal/wasm/sdk/internal/wasm/vm.go index c0a4510cdd..73a46cc0db 100644 --- a/internal/wasm/sdk/internal/wasm/vm.go +++ b/internal/wasm/sdk/internal/wasm/vm.go @@ -228,7 +228,7 @@ func newVM(opts vmOpts, engine *wasmtime.Engine) (*VM, error) { builtinMap := map[int32]topdown.BuiltinFunc{} - for name, id := range builtins.(map[string]interface{}) { + for name, id := range builtins.(map[string]any) { f := topdown.GetBuiltin(name) if f == nil { return nil, fmt.Errorf("builtin '%s' not found", name) @@ -255,7 +255,7 @@ func newVM(opts vmOpts, engine *wasmtime.Engine) (*VM, error) { return nil, err } - for ep, value := range epMap.(map[string]interface{}) { + for ep, value := range epMap.(map[string]any) { id, err := value.(json.Number).Int64() if err != nil { return nil, err @@ -283,7 +283,7 @@ func getABIVersion(i *wasmtime.Instance, store wasmtime.Storelike) (int32, int32 // input, and returns the resulting value dumped to a string. func (i *VM) Eval(ctx context.Context, entrypoint int32, - input *interface{}, + input *any, metrics metrics.Metrics, seed io.Reader, ns time.Time, @@ -367,7 +367,7 @@ func (i *VM) Eval(ctx context.Context, // Wasm modules lacking the needed export (i.e., ABI 1.1). func (i *VM) evalCompat(ctx context.Context, entrypoint int32, - input *interface{}, + input *any, metrics metrics.Metrics, seed io.Reader, ns time.Time, @@ -546,7 +546,7 @@ func (i *VM) Entrypoints() map[string]int32 { // SetDataPath will update the current data on the VM by setting the value at the // specified path. If an error occurs the instance is still in a valid state, however // the data will not have been modified. -func (i *VM) SetDataPath(ctx context.Context, path []string, value interface{}) error { +func (i *VM) SetDataPath(ctx context.Context, path []string, value any) error { // Reset the heap ptr before patching the vm to try and keep any // new allocations safe from subsequent heap resets on eval. if err := i.setHeapState(ctx, i.evalHeapPtr); err != nil { @@ -649,7 +649,7 @@ func (i *VM) RemoveDataPath(ctx context.Context, path []string) error { // fromRegoJSON parses serialized JSON from the Wasm memory buffer into // native go types. -func (i *VM) fromRegoJSON(ctx context.Context, addr int32, free bool) (interface{}, error) { +func (i *VM) fromRegoJSON(ctx context.Context, addr int32, free bool) (any, error) { serialized, err := i.jsonDump(ctx, addr) if err != nil { return nil, err @@ -666,7 +666,7 @@ func (i *VM) fromRegoJSON(ctx context.Context, addr int32, free bool) (interface decoder := json.NewDecoder(bytes.NewReader(data[0:n])) decoder.UseNumber() - var result interface{} + var result any if err := decoder.Decode(&result); err != nil { return nil, err } @@ -682,7 +682,7 @@ func (i *VM) fromRegoJSON(ctx context.Context, addr int32, free bool) (interface // toRegoJSON converts go native JSON to Rego JSON. If the value is // an AST type it will be dumped using its stringer. -func (i *VM) toRegoJSON(ctx context.Context, v interface{}, free bool) (int32, error) { +func (i *VM) toRegoJSON(ctx context.Context, v any, free bool) (int32, error) { var raw []byte switch v := v.(type) { case []byte: @@ -751,8 +751,8 @@ func callVoid(ctx context.Context, vm *VM, name string, args ...int32) error { return err } -func callOrCancel(ctx context.Context, vm *VM, name string, args ...int32) (interface{}, error) { - sl := make([]interface{}, len(args)) +func callOrCancel(ctx context.Context, vm *VM, name string, args ...int32) (any, error) { + sl := make([]any, len(args)) for i := range sl { sl[i] = args[i] } @@ -780,7 +780,7 @@ func callOrCancel(ctx context.Context, vm *VM, name string, args ...int32) (inte // If this call into the VM ends up calling host functions (builtins not // implemented in Wasm), and those panic, wasmtime will re-throw them, // and this is where we deal with that: - res, err := func() (res interface{}, err error) { + res, err := func() (res any, err error) { defer close(done) defer func() { if e := recover(); e != nil { diff --git a/internal/wasm/sdk/opa/config.go b/internal/wasm/sdk/opa/config.go index 2d2713f58b..8c9859cd17 100644 --- a/internal/wasm/sdk/opa/config.go +++ b/internal/wasm/sdk/opa/config.go @@ -49,7 +49,7 @@ func (o *OPA) WithDataBytes(data []byte) *OPA { } // WithDataJSON configures the JSON data to load. -func (o *OPA) WithDataJSON(data interface{}) *OPA { +func (o *OPA) WithDataJSON(data any) *OPA { v, err := json.Marshal(data) if err != nil { o.configErr = errors.New(errors.InvalidConfigErr, err.Error()) diff --git a/internal/wasm/sdk/opa/loader/file/loader.go b/internal/wasm/sdk/opa/loader/file/loader.go index b33b440cf5..bc53abdae6 100644 --- a/internal/wasm/sdk/opa/loader/file/loader.go +++ b/internal/wasm/sdk/opa/loader/file/loader.go @@ -40,7 +40,7 @@ type Loader struct { // policyData captures the functions used in setting the policy and data. type policyData interface { - SetPolicyData(ctx context.Context, policy []byte, data *interface{}) error + SetPolicyData(ctx context.Context, policy []byte, data *any) error } // New constructs a new file loader periodically reloading the bundle @@ -139,9 +139,9 @@ func (l *Loader) Load(ctx context.Context) error { return errors.New(errors.InvalidBundleErr, "missing wasm") } - var data *interface{} + var data *any if b.Data != nil { - var v interface{} = b.Data + var v any = b.Data data = &v } diff --git a/internal/wasm/sdk/opa/loader/file/loader_test.go b/internal/wasm/sdk/opa/loader/file/loader_test.go index 0306d327b5..22f567fcf5 100644 --- a/internal/wasm/sdk/opa/loader/file/loader_test.go +++ b/internal/wasm/sdk/opa/loader/file/loader_test.go @@ -43,7 +43,7 @@ func TestFileLoader(t *testing.T) { } policy := "wasm-policy" - var data interface{} = map[string]interface{}{ + var data any = map[string]any{ "foo": "bar", } @@ -60,7 +60,7 @@ func TestFileLoader(t *testing.T) { // Reload with updated contents. policy = "wasm-policy-modified" - data = map[string]interface{}{ + data = map[string]any{ "bar": "foo", } @@ -75,11 +75,11 @@ func TestFileLoader(t *testing.T) { type testPolicyData struct { sync.Mutex policy []byte - data *interface{} + data *any updated chan struct{} } -func (pd *testPolicyData) SetPolicyData(_ context.Context, policy []byte, data *interface{}) error { +func (pd *testPolicyData) SetPolicyData(_ context.Context, policy []byte, data *any) error { pd.Lock() defer pd.Unlock() @@ -92,7 +92,7 @@ func (pd *testPolicyData) SetPolicyData(_ context.Context, policy []byte, data * return nil } -func (pd *testPolicyData) CheckEqual(t *testing.T, policy string, data *interface{}) { +func (pd *testPolicyData) CheckEqual(t *testing.T, policy string, data *any) { pd.Lock() defer pd.Unlock() @@ -113,9 +113,9 @@ func (pd *testPolicyData) WaitUpdate() { pd.Unlock() } -func writeBundle(name string, policy string, data interface{}) { +func writeBundle(name string, policy string, data any) { b := bundle.Bundle{ - Data: data.(map[string]interface{}), + Data: data.(map[string]any), Wasm: []byte(policy), } diff --git a/internal/wasm/sdk/opa/loader/http/loader.go b/internal/wasm/sdk/opa/loader/http/loader.go index e7577c1132..42fa818b28 100644 --- a/internal/wasm/sdk/opa/loader/http/loader.go +++ b/internal/wasm/sdk/opa/loader/http/loader.go @@ -54,7 +54,7 @@ type Loader struct { // policyData captures the functions used in setting the policy and data. type policyData interface { - SetPolicyData(ctx context.Context, policy []byte, data *interface{}) error + SetPolicyData(ctx context.Context, policy []byte, data *any) error } // New constructs a new HTTP loader periodically downloading a bundle @@ -199,9 +199,9 @@ func (l *Loader) Load(ctx context.Context) error { return werrors.New(werrors.InvalidBundleErr, "missing wasm") } - var data *interface{} + var data *any if bundle.Data != nil { - var v interface{} = bundle.Data + var v any = bundle.Data data = &v } diff --git a/internal/wasm/sdk/opa/loader/http/loader_test.go b/internal/wasm/sdk/opa/loader/http/loader_test.go index 0fd1cfb353..279dce1554 100644 --- a/internal/wasm/sdk/opa/loader/http/loader_test.go +++ b/internal/wasm/sdk/opa/loader/http/loader_test.go @@ -43,7 +43,7 @@ func TestHTTPLoader(t *testing.T) { var mutex sync.Mutex policy := "wasm-policy" - var data interface{} = map[string]interface{}{ + var data any = map[string]any{ "foo": "bar", } @@ -52,7 +52,7 @@ func TestHTTPLoader(t *testing.T) { defer mutex.Unlock() if err := bundle.Write(w, bundle.Bundle{ - Data: data.(map[string]interface{}), + Data: data.(map[string]any), Wasm: []byte(policy), }); err != nil { panic(err) @@ -76,7 +76,7 @@ func TestHTTPLoader(t *testing.T) { mutex.Lock() policy = "wasm-policy-modified" - data = map[string]interface{}{ + data = map[string]any{ "bar": "foo", } mutex.Unlock() @@ -90,11 +90,11 @@ func TestHTTPLoader(t *testing.T) { type testPolicyData struct { sync.Mutex policy []byte - data *interface{} + data *any updated chan struct{} } -func (pd *testPolicyData) SetPolicyData(_ context.Context, policy []byte, data *interface{}) error { +func (pd *testPolicyData) SetPolicyData(_ context.Context, policy []byte, data *any) error { pd.Lock() defer pd.Unlock() @@ -107,7 +107,7 @@ func (pd *testPolicyData) SetPolicyData(_ context.Context, policy []byte, data * return nil } -func (pd *testPolicyData) CheckEqual(t *testing.T, policy string, data *interface{}) { +func (pd *testPolicyData) CheckEqual(t *testing.T, policy string, data *any) { pd.Lock() defer pd.Unlock() diff --git a/internal/wasm/sdk/opa/opa.go b/internal/wasm/sdk/opa/opa.go index 8b6b9db5c6..a404dbd158 100644 --- a/internal/wasm/sdk/opa/opa.go +++ b/internal/wasm/sdk/opa/opa.go @@ -80,7 +80,7 @@ func (o *OPA) Init() (*OPA, error) { // SetData updates the data for the subsequent Eval calls. Returns // either ErrNotReady, ErrInvalidPolicyOrData, or ErrInternal if an // error occurs. -func (o *OPA) SetData(ctx context.Context, v interface{}) error { +func (o *OPA) SetData(ctx context.Context, v any) error { if o.pool == nil { return errNotReady } @@ -99,7 +99,7 @@ func (o *OPA) SetData(ctx context.Context, v interface{}) error { // SetDataPath will update the current data on the VMs by setting the value at the // specified path. If an error occurs the instance is still in a valid state, however // the data will not have been modified. -func (o *OPA) SetDataPath(ctx context.Context, path []string, value interface{}) error { +func (o *OPA) SetDataPath(ctx context.Context, path []string, value any) error { return o.pool.SetDataPath(ctx, path, value) } @@ -127,7 +127,7 @@ func (o *OPA) SetPolicy(ctx context.Context, p []byte) error { // SetPolicyData updates both the policy and data for the subsequent // Eval calls. Returns either ErrNotReady, ErrInvalidPolicyOrData, or // ErrInternal if an error occurs. -func (o *OPA) SetPolicyData(ctx context.Context, policy []byte, data *interface{}) error { +func (o *OPA) SetPolicyData(ctx context.Context, policy []byte, data *any) error { if o.pool == nil { return errNotReady } @@ -160,7 +160,7 @@ func (o *OPA) setPolicyData(ctx context.Context, policy []byte, data []byte) err // EvalOpts define options for performing an evaluation type EvalOpts struct { Entrypoint int32 - Input *interface{} + Input *any Metrics metrics.Metrics Time time.Time Seed io.Reader diff --git a/internal/wasm/sdk/opa/opa_bench_test.go b/internal/wasm/sdk/opa/opa_bench_test.go index b707bb3cc0..85d313a142 100644 --- a/internal/wasm/sdk/opa/opa_bench_test.go +++ b/internal/wasm/sdk/opa/opa_bench_test.go @@ -29,7 +29,7 @@ func BenchmarkWasmRego(b *testing.B) { b.ResetTimer() ctx := context.Background() - var input interface{} = make(map[string]interface{}) + var input any = make(map[string]any) for i := 0; i < b.N; i++ { if _, err := instance.Eval(ctx, opa.EvalOpts{Input: &input}); err != nil { @@ -47,7 +47,7 @@ a = true`, "data.p.a = x") b.ResetTimer() ctx := context.Background() - input := make(map[string]interface{}) + input := make(map[string]any) for i := 0; i < b.N; i++ { if _, err := pq.Eval(ctx, rego.EvalInput(input)); err != nil { @@ -106,7 +106,7 @@ func benchmarkIteration(b *testing.B, module string) { b.ResetTimer() ctx := context.Background() - var input interface{} = make(map[string]interface{}) + var input any = make(map[string]any) for i := 0; i < b.N; i++ { r, err = instance.Eval(ctx, opa.EvalOpts{Input: &input}) @@ -147,7 +147,7 @@ func BenchmarkWASMLargeJSON(b *testing.B) { } b.ResetTimer() - var input interface{} = make(map[string]interface{}) + var input any = make(map[string]any) for i := 0; i < b.N; i++ { r, err = instance.Eval(ctx, opa.EvalOpts{Input: &input}) @@ -195,7 +195,7 @@ func runVirtualDocsBenchmark(b *testing.B, numTotalRules, numHitRules int) { } b.ResetTimer() - var inp interface{} = input + var inp any = input for i := 0; i < b.N; i++ { r, err = instance.Eval(ctx, opa.EvalOpts{Input: &inp}) diff --git a/internal/wasm/sdk/opa/opa_test.go b/internal/wasm/sdk/opa/opa_test.go index 8a6935eb20..8dbc261ece 100644 --- a/internal/wasm/sdk/opa/opa_test.go +++ b/internal/wasm/sdk/opa/opa_test.go @@ -438,7 +438,7 @@ func compileRego(module string, query string) rego.PreparedEvalQuery { return pq } -func parseJSON(s string) *interface{} { +func parseJSON(s string) *any { if s == "" { return nil } diff --git a/internal/wasm/sdk/test/e2e/external_test.go b/internal/wasm/sdk/test/e2e/external_test.go index cde1a0af3b..00d6e20347 100644 --- a/internal/wasm/sdk/test/e2e/external_test.go +++ b/internal/wasm/sdk/test/e2e/external_test.go @@ -97,10 +97,10 @@ func TestWasmE2E(t *testing.T) { t.Fatal(err) } - var input *interface{} + var input *any if tc.InputTerm != nil { - var x interface{} = ast.MustParseTerm(*tc.InputTerm) + var x any = ast.MustParseTerm(*tc.InputTerm) input = &x } else if tc.Input != nil { input = tc.Input @@ -167,7 +167,7 @@ func (x defined) String() string { func assertDefined(t *testing.T, want defined, result *opa.Result) { t.Helper() - var rs []interface{} + var rs []any if err := util.NewJSONDecoder(bytes.NewReader(result.Result)).Decode(&rs); err != nil { t.Fatal(err) } @@ -181,10 +181,10 @@ func assertEmptyResultSet(t *testing.T, result *opa.Result) { if result == nil { t.Fatal("unexpected nil result") } - assertResultSet(t, []map[string]interface{}{}, false, result) + assertResultSet(t, []map[string]any{}, false, result) } -func assertResultSet(t *testing.T, want []map[string]interface{}, sortBindings bool, result *opa.Result) { +func assertResultSet(t *testing.T, want []map[string]any, sortBindings bool, result *opa.Result) { t.Helper() exp := ast.NewSet() @@ -240,7 +240,7 @@ func assertErrorCode(t *testing.T, expected string, actual error) { } } -func toAST(a interface{}) *ast.Term { +func toAST(a any) *ast.Term { if bs, ok := a.([]byte); ok { return ast.MustParseTerm(string(bs)) diff --git a/ir/pretty.go b/ir/pretty.go index 2fb6af0538..59be4a3320 100644 --- a/ir/pretty.go +++ b/ir/pretty.go @@ -11,6 +11,6 @@ import ( ) // Pretty writes a human-readable representation of an IR object to w. -func Pretty(w io.Writer, x interface{}) error { +func Pretty(w io.Writer, x any) error { return v1.Pretty(w, x) } diff --git a/ir/walk.go b/ir/walk.go index 9af8c2eaff..5bd74c7a5f 100644 --- a/ir/walk.go +++ b/ir/walk.go @@ -10,6 +10,6 @@ import v1 "github.com/open-policy-agent/opa/v1/ir" type Visitor = v1.Visitor // Walk invokes the visitor for nodes under x. -func Walk(vis Visitor, x interface{}) error { +func Walk(vis Visitor, x any) error { return v1.Walk(vis, x) } diff --git a/metrics/metrics.go b/metrics/metrics.go index 2d2ae78b1a..8f2f6c4435 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -52,6 +52,6 @@ type Histogram = v1.Histogram // Counter defines the interface for a monotonic increasing counter. type Counter = v1.Counter -func Statistics(num ...int64) interface{} { +func Statistics(num ...int64) any { return v1.Statistics(num...) } diff --git a/plugins/discovery/discovery.go b/plugins/discovery/discovery.go index 8ab4a1f9b6..696fed91ee 100644 --- a/plugins/discovery/discovery.go +++ b/plugins/discovery/discovery.go @@ -37,7 +37,7 @@ func Hooks(hs hooks.Hooks) func(*Discovery) { return v1.Hooks(hs) } -func BootConfig(bootConfig map[string]interface{}) func(*Discovery) { +func BootConfig(bootConfig map[string]any) func(*Discovery) { return v1.BootConfig(bootConfig) } diff --git a/rego/rego.go b/rego/rego.go index e6af30c39c..bdcf6c291a 100644 --- a/rego/rego.go +++ b/rego/rego.go @@ -43,7 +43,7 @@ type EvalContext = v1.EvalContext type EvalOption = v1.EvalOption // EvalInput configures the input for a Prepared Query's evaluation -func EvalInput(input interface{}) EvalOption { +func EvalInput(input any) EvalOption { return v1.EvalInput(input) } @@ -155,7 +155,7 @@ func EvalSortSets(yes bool) EvalOption { return v1.EvalSortSets(yes) } -// EvalCopyMaps causes the evaluator to copy `map[string]interface{}`s before returning them. +// EvalCopyMaps causes the evaluator to copy `map[string]any`s before returning them. func EvalCopyMaps(yes bool) EvalOption { return v1.EvalCopyMaps(yes) } @@ -312,7 +312,7 @@ func ParsedImports(imp []*ast.Import) func(r *Rego) { // Input returns an argument that sets the Rego input document. Input should be // a native Go value representing the input document. -func Input(x interface{}) func(r *Rego) { +func Input(x any) func(r *Rego) { return v1.Input(x) } @@ -545,7 +545,7 @@ func Target(t string) func(r *Rego) { } // GenerateJSON sets the AST to JSON converter for the results. -func GenerateJSON(f func(*ast.Term, *EvalContext) (interface{}, error)) func(r *Rego) { +func GenerateJSON(f func(*ast.Term, *EvalContext) (any, error)) func(r *Rego) { return v1.GenerateJSON(f) } diff --git a/rego/rego_test.go b/rego/rego_test.go index 7719edf008..12c95af999 100644 --- a/rego/rego_test.go +++ b/rego/rego_test.go @@ -17,7 +17,7 @@ func TestRegoEval_DefaultRegoVersion(t *testing.T) { tests := []struct { note string module string - expResult interface{} + expResult any expErrs []string }{ { diff --git a/repl/repl_test.go b/repl/repl_test.go index c2bb5c279f..824b23c174 100644 --- a/repl/repl_test.go +++ b/repl/repl_test.go @@ -152,7 +152,7 @@ func newTestStore() storage.Store { ] } ` - var data map[string]interface{} + var data map[string]any err := util.UnmarshalJSON([]byte(input), &data) if err != nil { panic(err) diff --git a/resolver/wasm/wasm.go b/resolver/wasm/wasm.go index ff8b9b8208..65311077f7 100644 --- a/resolver/wasm/wasm.go +++ b/resolver/wasm/wasm.go @@ -11,7 +11,7 @@ import ( // New creates a new Resolver instance which is using the Wasm module // policy for the given entrypoint ref. -func New(entrypoints []ast.Ref, policy []byte, data interface{}) (*Resolver, error) { +func New(entrypoints []ast.Ref, policy []byte, data any) (*Resolver, error) { return v1.New(entrypoints, policy, data) } diff --git a/sdk/opa_test.go b/sdk/opa_test.go index 684f3c9a0a..be2fc91ef4 100644 --- a/sdk/opa_test.go +++ b/sdk/opa_test.go @@ -77,9 +77,9 @@ loopback = input t.Fatal(`expected "foo" but got:`, decision) } - exp := map[string]interface{}{"foo": "bar"} + exp := map[string]any{"foo": "bar"} - if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/loopback", Input: map[string]interface{}{"foo": "bar"}}); err != nil { + if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/loopback", Input: map[string]any{"foo": "bar"}}); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(result.Result, exp) { t.Fatalf("expected %v but got %v", exp, result.Result) diff --git a/server/authorizer/authorizer.go b/server/authorizer/authorizer.go index c0ffcc736f..c0aed22856 100644 --- a/server/authorizer/authorizer.go +++ b/server/authorizer/authorizer.go @@ -60,12 +60,12 @@ func NewBasic(inner http.Handler, compiler func() *ast.Compiler, store storage.S // SetBodyOnContext adds the parsed input value to the context. This function is only // exposed for test purposes. -func SetBodyOnContext(ctx context.Context, x interface{}) context.Context { +func SetBodyOnContext(ctx context.Context, x any) context.Context { return v1.SetBodyOnContext(ctx, x) } // GetBodyOnContext returns the parsed input from the request context if it exists. // The authorizer saves the parsed input on the context when it runs. -func GetBodyOnContext(ctx context.Context) (interface{}, bool) { +func GetBodyOnContext(ctx context.Context) (any, bool) { return v1.GetBodyOnContext(ctx) } diff --git a/server/types/types.go b/server/types/types.go index deda9dc7ad..c8224b13fc 100644 --- a/server/types/types.go +++ b/server/types/types.go @@ -27,7 +27,7 @@ const ( type ErrorV1 = v1.ErrorV1 // NewErrorV1 returns a new ErrorV1 object. -func NewErrorV1(code, f string, a ...interface{}) *ErrorV1 { +func NewErrorV1(code, f string, a ...any) *ErrorV1 { return v1.NewErrorV1(code, f, a...) } diff --git a/server/writer/writer.go b/server/writer/writer.go index 2994fbf1a1..2dc464ec47 100644 --- a/server/writer/writer.go +++ b/server/writer/writer.go @@ -40,12 +40,12 @@ func Error(w http.ResponseWriter, status int, err *types.ErrorV1) { // Deprecated: This method is problematic when using a non-200 status `code`: if // encoding the payload fails, it'll print "superfluous call to WriteHeader()" // logs. -func JSON(w http.ResponseWriter, code int, v interface{}, pretty bool) { +func JSON(w http.ResponseWriter, code int, v any, pretty bool) { v1.JSON(w, code, v, pretty) } // JSONOK is a helper for status "200 OK" responses -func JSONOK(w http.ResponseWriter, v interface{}, pretty bool) { +func JSONOK(w http.ResponseWriter, v any, pretty bool) { v1.JSONOK(w, v, pretty) } diff --git a/storage/inmem/inmem.go b/storage/inmem/inmem.go index 0a41b9d0da..dabedd4ef8 100644 --- a/storage/inmem/inmem.go +++ b/storage/inmem/inmem.go @@ -33,13 +33,13 @@ func NewWithOpts(opts ...Opt) storage.Store { } // NewFromObject returns a new in-memory store from the supplied data object. -func NewFromObject(data map[string]interface{}) storage.Store { +func NewFromObject(data map[string]any) storage.Store { return v1.NewFromObject(data) } // NewFromObjectWithOpts returns a new in-memory store from the supplied data object, with the // options passed. -func NewFromObjectWithOpts(data map[string]interface{}, opts ...Opt) storage.Store { +func NewFromObjectWithOpts(data map[string]any, opts ...Opt) storage.Store { return v1.NewFromObjectWithOpts(data, opts...) } diff --git a/storage/inmem/test/testutil.go b/storage/inmem/test/testutil.go index dda9eb8f69..14cd901428 100644 --- a/storage/inmem/test/testutil.go +++ b/storage/inmem/test/testutil.go @@ -17,6 +17,6 @@ func New() storage.Store { // NewFromObject returns an inmem store from the passed object, with some // common options set: opt-out of write roundtripping. -func NewFromObject(x map[string]interface{}) storage.Store { +func NewFromObject(x map[string]any) storage.Store { return v1.NewFromObject(x) } diff --git a/storage/storage.go b/storage/storage.go index c02773d985..d1abc1046d 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -20,14 +20,14 @@ func NewTransactionOrDie(ctx context.Context, store Store, params ...Transaction // ReadOne is a convenience function to read a single value from the provided Store. It // will create a new Transaction to perform the read with, and clean up after itself // should an error occur. -func ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) { +func ReadOne(ctx context.Context, store Store, path Path) (any, error) { return v1.ReadOne(ctx, store, path) } // WriteOne is a convenience function to write a single value to the provided Store. It // will create a new Transaction to perform the write with, and clean up after itself // should an error occur. -func WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value interface{}) error { +func WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value any) error { return v1.WriteOne(ctx, store, op, path, value) } diff --git a/test/authz/testing.go b/test/authz/testing.go index 8f2bd570b7..e8ffaf9d81 100644 --- a/test/authz/testing.go +++ b/test/authz/testing.go @@ -33,11 +33,11 @@ const ( ) // GenerateInput will use a dataset profile and desired InputMode to generate inputs for testing -func GenerateInput(profile DataSetProfile, mode InputMode) (interface{}, interface{}) { +func GenerateInput(profile DataSetProfile, mode InputMode) (any, any) { return v1.GenerateInput(profile, mode) } // GenerateDataset will generate a dataset for the given DatasetProfile -func GenerateDataset(profile DataSetProfile) map[string]interface{} { +func GenerateDataset(profile DataSetProfile) map[string]any { return v1.GenerateDataset(profile) } diff --git a/topdown/builtins/builtins.go b/topdown/builtins/builtins.go index 152c37717a..5f605a1722 100644 --- a/topdown/builtins/builtins.go +++ b/topdown/builtins/builtins.go @@ -27,7 +27,7 @@ type NDBCache = v1.NDBCache type ErrOperand = v1.ErrOperand // NewOperandErr returns a generic operand error. -func NewOperandErr(pos int, f string, a ...interface{}) error { +func NewOperandErr(pos int, f string, a ...any) error { return v1.NewOperandErr(pos, f, a...) } diff --git a/topdown/graphql.go b/topdown/graphql.go index 6b52705620..d2254df1f0 100644 --- a/topdown/graphql.go +++ b/topdown/graphql.go @@ -100,7 +100,7 @@ func convertSchema(schemaDoc *gqlast.SchemaDocument) (*gqlast.Schema, error) { // Converts an ast.Object into a gqlast.QueryDocument object. func objectToQueryDocument(value ast.Object) (*gqlast.QueryDocument, error) { - // Convert ast.Term to interface{} for JSON encoding below. + // Convert ast.Term to any for JSON encoding below. asJSON, err := ast.JSON(value) if err != nil { return nil, err @@ -121,7 +121,7 @@ func objectToQueryDocument(value ast.Object) (*gqlast.QueryDocument, error) { // Converts an ast.Object into a gqlast.SchemaDocument object. func objectToSchemaDocument(value ast.Object) (*gqlast.SchemaDocument, error) { - // Convert ast.Term to interface{} for JSON encoding below. + // Convert ast.Term to any for JSON encoding below. asJSON, err := ast.JSON(value) if err != nil { return nil, err diff --git a/tracing/tracing.go b/tracing/tracing.go index ad6ac668ed..d43635431f 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -18,7 +18,7 @@ import ( type Options = v1.Options // NewOptions is a helper method for constructing `tracing.Options` -func NewOptions(opts ...interface{}) Options { +func NewOptions(opts ...any) Options { return v1.NewOptions(opts...) } diff --git a/types/types.go b/types/types.go index b888b27b60..0dd428de7f 100644 --- a/types/types.go +++ b/types/types.go @@ -90,7 +90,7 @@ func NewSet(of Type) *Set { type StaticProperty = v1.StaticProperty // NewStaticProperty returns a new StaticProperty object. -func NewStaticProperty(key interface{}, value Type) *StaticProperty { +func NewStaticProperty(key any, value Type) *StaticProperty { return v1.NewStaticProperty(key, value) } @@ -173,7 +173,7 @@ func Or(a, b Type) Type { } // Select returns a property or item of a. -func Select(a Type, x interface{}) Type { +func Select(a Type, x any) Type { return v1.Select(a, x) } @@ -195,6 +195,6 @@ func Nil(a Type) bool { } // TypeOf returns the type of the Golang native value. -func TypeOf(x interface{}) Type { +func TypeOf(x any) Type { return v1.TypeOf(x) } diff --git a/util/compare.go b/util/compare.go index e74d1d49b8..e3ce2475fc 100644 --- a/util/compare.go +++ b/util/compare.go @@ -11,9 +11,9 @@ import ( // Compare returns 0 if a equals b, -1 if a is less than b, and 1 if b is than a. // // For comparison between values of different types, the following ordering is used: -// nil < bool < int, float64 < string < []interface{} < map[string]interface{}. Slices and maps +// nil < bool < int, float64 < string < []any < map[string]any. Slices and maps // are compared recursively. If one slice or map is a subset of the other slice or map // it is considered "less than". Nil is always equal to nil. -func Compare(a, b interface{}) int { +func Compare(a, b any) int { return v1.Compare(a, b) } diff --git a/util/json.go b/util/json.go index 9b19a967ba..0a91970899 100644 --- a/util/json.go +++ b/util/json.go @@ -16,7 +16,7 @@ import ( // // This function is intended to be used in place of the standard json.Marshal // function when json.Number is required. -func UnmarshalJSON(bs []byte, x interface{}) error { +func UnmarshalJSON(bs []byte, x any) error { return v1.UnmarshalJSON(bs, x) } @@ -32,7 +32,7 @@ func NewJSONDecoder(r io.Reader) *json.Decoder { // // If the data cannot be decoded, this function will panic. This function is for // test purposes. -func MustUnmarshalJSON(bs []byte) interface{} { +func MustUnmarshalJSON(bs []byte) any { return v1.MustUnmarshalJSON(bs) } @@ -40,7 +40,7 @@ func MustUnmarshalJSON(bs []byte) interface{} { // // If the data cannot be encoded, this function will panic. This function is for // test purposes. -func MustMarshalJSON(x interface{}) []byte { +func MustMarshalJSON(x any) []byte { return v1.MustMarshalJSON(x) } @@ -49,7 +49,7 @@ func MustMarshalJSON(x interface{}) []byte { // Thereby, it is converting its argument to the representation expected by // rego.Input and inmem's Write operations. Works with both references and // values. -func RoundTrip(x *interface{}) error { +func RoundTrip(x *any) error { return v1.RoundTrip(x) } @@ -58,11 +58,11 @@ func RoundTrip(x *interface{}) error { // // Used for preparing Go types (including pointers to structs) into values to be // put through util.RoundTrip(). -func Reference(x interface{}) *interface{} { +func Reference(x any) *any { return v1.Reference(x) } // Unmarshal decodes a YAML, JSON or JSON extension value into the specified type. -func Unmarshal(bs []byte, v interface{}) error { +func Unmarshal(bs []byte, v any) error { return v1.Unmarshal(bs, v) } diff --git a/util/test/benchmark.go b/util/test/benchmark.go index d73c437aca..18f1a85690 100644 --- a/util/test/benchmark.go +++ b/util/test/benchmark.go @@ -34,25 +34,25 @@ func ObjectIterationBenchmarkModule(n int) string { // GenerateLargeJSONBenchmarkData returns a map of 100 keys and 100.000 key/value // pairs. -func GenerateLargeJSONBenchmarkData() map[string]interface{} { +func GenerateLargeJSONBenchmarkData() map[string]any { return v1.GenerateLargeJSONBenchmarkData() } // GenerateJSONBenchmarkData returns a map of `k` keys and `v` key/value pairs. -func GenerateJSONBenchmarkData(k, v int) map[string]interface{} { +func GenerateJSONBenchmarkData(k, v int) map[string]any { return v1.GenerateJSONBenchmarkData(k, v) } // GenerateConcurrencyBenchmarkData returns a module and data; the module // checks some input parameters against that data in a simple API authz // scheme. -func GenerateConcurrencyBenchmarkData() (string, map[string]interface{}) { +func GenerateConcurrencyBenchmarkData() (string, map[string]any) { return v1.GenerateConcurrencyBenchmarkData() } // GenerateVirtualDocsBenchmarkData generates a module and input; the // numTotalRules and numHitRules create as many rules in the module to // match/miss the returned input. -func GenerateVirtualDocsBenchmarkData(numTotalRules, numHitRules int) (string, map[string]interface{}) { +func GenerateVirtualDocsBenchmarkData(numTotalRules, numHitRules int) (string, map[string]any) { return v1.GenerateVirtualDocsBenchmarkData(numTotalRules, numHitRules) } diff --git a/v1/ast/annotations.go b/v1/ast/annotations.go index def7604edf..1f92c5a6c9 100644 --- a/v1/ast/annotations.go +++ b/v1/ast/annotations.go @@ -55,7 +55,7 @@ type ( RelatedResources []*RelatedResourceAnnotation `json:"related_resources,omitempty"` Authors []*AuthorAnnotation `json:"authors,omitempty"` Schemas []*SchemaAnnotation `json:"schemas,omitempty"` - Custom map[string]interface{} `json:"custom,omitempty"` + Custom map[string]any `json:"custom,omitempty"` Location *Location `json:"location,omitempty"` comments []*Comment @@ -64,9 +64,9 @@ type ( // SchemaAnnotation contains a schema declaration for the document identified by the path. SchemaAnnotation struct { - Path Ref `json:"path"` - Schema Ref `json:"schema,omitempty"` - Definition *interface{} `json:"definition,omitempty"` + Path Ref `json:"path"` + Schema Ref `json:"schema,omitempty"` + Definition *any `json:"definition,omitempty"` } AuthorAnnotation struct { @@ -203,7 +203,7 @@ func (a *Annotations) MarshalJSON() ([]byte, error) { return []byte(`{"scope":""}`), nil } - data := map[string]interface{}{ + data := map[string]any{ "scope": a.Scope, } @@ -283,7 +283,7 @@ func (ar *AnnotationsRef) GetRule() *Rule { } func (ar *AnnotationsRef) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "path": ar.Path, } @@ -696,7 +696,7 @@ func (rr *RelatedResourceAnnotation) String() string { } func (rr *RelatedResourceAnnotation) MarshalJSON() ([]byte, error) { - d := map[string]interface{}{ + d := map[string]any{ "ref": rr.Ref.String(), } diff --git a/v1/ast/annotations_test.go b/v1/ast/annotations_test.go index 444d32d651..cf8c5a9fd6 100644 --- a/v1/ast/annotations_test.go +++ b/v1/ast/annotations_test.go @@ -267,11 +267,11 @@ p = 1`, }, }, Schemas: []*SchemaAnnotation{ - schemaAnnotationFromMap("input", map[string]interface{}{ + schemaAnnotationFromMap("input", map[string]any{ "type": "boolean", }), }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "pkg": "pkg", }, }, @@ -295,11 +295,11 @@ p = 1`, }, }, Schemas: []*SchemaAnnotation{ - schemaAnnotationFromMap("input", map[string]interface{}{ + schemaAnnotationFromMap("input", map[string]any{ "type": "integer", }), }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "doc": "doc", }, }, @@ -323,11 +323,11 @@ p = 1`, }, }, Schemas: []*SchemaAnnotation{ - schemaAnnotationFromMap("input", map[string]interface{}{ + schemaAnnotationFromMap("input", map[string]any{ "type": "string", }), }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "rule": "rule", }, }, @@ -630,11 +630,11 @@ p = 1`, }, }, Schemas: []*SchemaAnnotation{ - schemaAnnotationFromMap("input.baz", map[string]interface{}{ + schemaAnnotationFromMap("input.baz", map[string]any{ "type": "string", }), }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "rule": "rule", }, }, @@ -658,11 +658,11 @@ p = 1`, }, }, Schemas: []*SchemaAnnotation{ - schemaAnnotationFromMap("input.bar", map[string]interface{}{ + schemaAnnotationFromMap("input.bar", map[string]any{ "type": "integer", }), }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "doc": "doc", }, }, @@ -686,11 +686,11 @@ p = 1`, }, }, Schemas: []*SchemaAnnotation{ - schemaAnnotationFromMap("input.foo", map[string]interface{}{ + schemaAnnotationFromMap("input.foo", map[string]any{ "type": "boolean", }), }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "pkg": "pkg", }, }, @@ -1047,43 +1047,43 @@ func TestAnnotations_toObject(t *testing.T) { Path: MustParseRef("input.foo"), Schema: MustParseRef("schema.a"), }, - schemaAnnotationFromMap("input.bar", map[string]interface{}{ + schemaAnnotationFromMap("input.bar", map[string]any{ "type": "boolean", }), }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "number": 42, "float": 2.2, "string": "foo bar baz", "bool": true, - "list": []interface{}{ + "list": []any{ "a", "b", }, - "list_of_lists": []interface{}{ - []interface{}{ + "list_of_lists": []any{ + []any{ "a", "b", }, - []interface{}{ + []any{ "b", "c", }, }, - "list_of_maps": []interface{}{ - map[string]interface{}{ + "list_of_maps": []any{ + map[string]any{ "one": 1, "two": 2, }, - map[string]interface{}{ + map[string]any{ "two": 2, "three": 3, }, }, - "map": map[string]interface{}{ + "map": map[string]any{ "nested_number": 1, - "nested_map": map[string]interface{}{ + "nested_map": map[string]any{ "do": "re", "mi": "fa", }, - "nested_list": []interface{}{ + "nested_list": []any{ 1, 2, 3, }, }, @@ -1186,12 +1186,12 @@ func TestAnnotations_toObject(t *testing.T) { } } -func toJSON(v interface{}) string { +func toJSON(v any) string { b, _ := json.MarshalIndent(v, "", " ") return string(b) } -func schemaAnnotationFromMap(path string, def map[string]interface{}) *SchemaAnnotation { - var p interface{} = def +func schemaAnnotationFromMap(path string, def map[string]any) *SchemaAnnotation { + var p any = def return &SchemaAnnotation{Path: MustParseRef(path), Definition: &p} } diff --git a/v1/ast/check.go b/v1/ast/check.go index ecfb320649..ca48ea58b2 100644 --- a/v1/ast/check.go +++ b/v1/ast/check.go @@ -179,7 +179,7 @@ func (tc *typeChecker) CheckTypes(env *TypeEnv, sorted []util.T, as *AnnotationS func (tc *typeChecker) checkClosures(env *TypeEnv, expr *Expr) Errors { var result Errors - WalkClosures(expr, func(x interface{}) bool { + WalkClosures(expr, func(x any) bool { switch x := x.(type) { case *ArrayComprehension: _, errs := tc.copy().CheckBody(env, x.Body) @@ -702,7 +702,7 @@ func newRefChecker(env *TypeEnv, f varRewriter) *refChecker { } } -func (rc *refChecker) Visit(x interface{}) bool { +func (rc *refChecker) Visit(x any) bool { switch x := x.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension: return true @@ -1247,8 +1247,8 @@ func override(ref Ref, t types.Type, o types.Type, rule *Rule) (types.Type, *Err return types.NewObject(newStaticProps, obj.DynamicProperties()), nil } -func getKeys(ref Ref, rule *Rule) ([]interface{}, *Error) { - keys := []interface{}{} +func getKeys(ref Ref, rule *Rule) ([]any, *Error) { + keys := []any{} for _, refElem := range ref { key, err := JSON(refElem.Value) if err != nil { @@ -1259,7 +1259,7 @@ func getKeys(ref Ref, rule *Rule) ([]interface{}, *Error) { return keys, nil } -func getObjectTypeRec(keys []interface{}, o types.Type, d *types.DynamicProperty) *types.Object { +func getObjectTypeRec(keys []any, o types.Type, d *types.DynamicProperty) *types.Object { if len(keys) == 1 { staticProps := []*types.StaticProperty{types.NewStaticProperty(keys[0], o)} return types.NewObject(staticProps, d) @@ -1300,7 +1300,7 @@ func getRuleAnnotation(as *AnnotationSet, rule *Rule) (result []*SchemaAnnotatio func processAnnotation(ss *SchemaSet, annot *SchemaAnnotation, rule *Rule, allowNet []string) (types.Type, *Error) { - var schema interface{} + var schema any if annot.Schema != nil { if ss == nil { diff --git a/v1/ast/check_test.go b/v1/ast/check_test.go index 9fb9c5d3b9..17074f0cba 100644 --- a/v1/ast/check_test.go +++ b/v1/ast/check_test.go @@ -104,7 +104,7 @@ func TestCheckInference(t *testing.T) { {"object-object-key", `x = {{{}: 1}: 1}`, map[Var]types.Type{ Var("x"): types.NewObject( []*types.StaticProperty{types.NewStaticProperty( - map[string]interface{}{ + map[string]any{ "{}": json.Number("1"), }, types.N, @@ -115,7 +115,7 @@ func TestCheckInference(t *testing.T) { {"object-composite-ref-operand", `x = {{}: 1}; x[{}] = y`, map[Var]types.Type{ Var("x"): types.NewObject( []*types.StaticProperty{types.NewStaticProperty( - map[string]interface{}{}, + map[string]any{}, types.N, )}, nil, @@ -2402,7 +2402,7 @@ q = p`, for k, v := range tc.schemas { ref := MustParseRef(k) - var schema interface{} + var schema any err = util.Unmarshal([]byte(v), &schema) if err != nil { t.Fatal(err) diff --git a/v1/ast/compare.go b/v1/ast/compare.go index 452c6365a3..b5d8ca7670 100644 --- a/v1/ast/compare.go +++ b/v1/ast/compare.go @@ -36,7 +36,7 @@ import ( // Sets are considered equal if and only if the symmetric difference of a and b // is empty. // Other comparisons are consistent but not defined. -func Compare(a, b interface{}) int { +func Compare(a, b any) int { if t, ok := a.(*Term); ok { if t == nil { @@ -239,7 +239,7 @@ func (s termSlice) Less(i, j int) bool { return Compare(s[i].Value, s[j].Value) func (s termSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s termSlice) Len() int { return len(s) } -func sortOrder(x interface{}) int { +func sortOrder(x any) int { switch x.(type) { case Null: return 0 diff --git a/v1/ast/compare_test.go b/v1/ast/compare_test.go index daa2683bbb..ee5812be01 100644 --- a/v1/ast/compare_test.go +++ b/v1/ast/compare_test.go @@ -66,7 +66,7 @@ func TestCompare(t *testing.T) { {`a = b; b = a`, `a = b`, 1}, } for _, tc := range tests { - var a, b interface{} + var a, b any if len(tc.a) > 0 { a = MustParseStatement(tc.a) } diff --git a/v1/ast/compile.go b/v1/ast/compile.go index e8e8abf927..81464e5cad 100644 --- a/v1/ast/compile.go +++ b/v1/ast/compile.go @@ -1085,7 +1085,7 @@ func (c *Compiler) checkSelfPath(loc *Location, eq func(a, b util.T) bool, a, b } } -func astNodeToString(x interface{}) string { +func astNodeToString(x any) string { return x.(*Rule).Ref().String() } @@ -1232,7 +1232,7 @@ func (c *Compiler) checkUndefinedFuncs() { } } -func checkUndefinedFuncs(env *TypeEnv, x interface{}, arity func(Ref) int, rwVars map[Var]Var) Errors { +func checkUndefinedFuncs(env *TypeEnv, x any, arity func(Ref) int, rwVars map[Var]Var) Errors { var errs Errors @@ -1337,7 +1337,7 @@ func (c *Compiler) checkSafetyRuleHeads() { } } -func compileSchema(goSchema interface{}, allowNet []string) (*gojsonschema.Schema, error) { +func compileSchema(goSchema any, allowNet []string) (*gojsonschema.Schema, error) { gojsonschema.SetAllowNet(allowNet) var refLoader gojsonschema.JSONLoader @@ -1410,11 +1410,11 @@ func newSchemaParser() *schemaParser { } } -func (parser *schemaParser) parseSchema(schema interface{}) (types.Type, error) { +func (parser *schemaParser) parseSchema(schema any) (types.Type, error) { return parser.parseSchemaWithPropertyKey(schema, "") } -func (parser *schemaParser) parseSchemaWithPropertyKey(schema interface{}, propertyKey string) (types.Type, error) { +func (parser *schemaParser) parseSchemaWithPropertyKey(schema any, propertyKey string) (types.Type, error) { subSchema, ok := schema.(*gojsonschema.SubSchema) if !ok { return nil, fmt.Errorf("unexpected schema type %v", subSchema) @@ -2061,7 +2061,7 @@ func (c *Compiler) rewritePrintCalls() { // checkVoidCalls returns errors for any expressions that treat void function // calls as values. The only void functions in Rego are specific built-ins like // print(). -func checkVoidCalls(env *TypeEnv, x interface{}) Errors { +func checkVoidCalls(env *TypeEnv, x any) Errors { var errs Errors WalkTerms(x, func(x *Term) bool { if call, ok := x.Value.(Call); ok { @@ -2097,7 +2097,7 @@ func rewritePrintCalls(gen *localVarGenerator, getArity func(Ref) int, globals V if ContainsClosures(body[i]) { safe := outputVarsForBody(body[:i], getArity, globals) safe.Update(globals) - WalkClosures(body[i], func(x interface{}) bool { + WalkClosures(body[i], func(x any) bool { var modrec bool var errsrec Errors switch x := x.(type) { @@ -2166,9 +2166,9 @@ func rewritePrintCalls(gen *localVarGenerator, getArity func(Ref) int, globals V return modified, nil } -func erasePrintCalls(node interface{}) bool { +func erasePrintCalls(node any) bool { var modified bool - NewGenericVisitor(func(x interface{}) bool { + NewGenericVisitor(func(x any) bool { var modrec bool switch x := x.(type) { case *Rule: @@ -2217,7 +2217,7 @@ func erasePrintCallsInBody(x Body) (bool, Body) { return true, cpy } -func containsPrintCall(x interface{}) bool { +func containsPrintCall(x any) bool { var found bool WalkExprs(x, func(expr *Expr) bool { if !found { @@ -2478,7 +2478,7 @@ func getPrimaryRuleAnnotations(as *AnnotationSet, rule *Rule) *Annotations { func rewriteRegoMetadataCalls(metadataChainVar *Var, metadataRuleVar *Var, body Body, rewrittenVars *map[Var]Var) Errors { var errs Errors - WalkClosures(body, func(x interface{}) bool { + WalkClosures(body, func(x any) bool { switch x := x.(type) { case *ArrayComprehension: errs = rewriteRegoMetadataCalls(metadataChainVar, metadataRuleVar, x.Body, rewrittenVars) @@ -2694,7 +2694,7 @@ type rewriteNestedHeadVarLocalTransform struct { strict bool } -func (xform *rewriteNestedHeadVarLocalTransform) Visit(x interface{}) bool { +func (xform *rewriteNestedHeadVarLocalTransform) Visit(x any) bool { if term, ok := x.(*Term); ok { @@ -2743,7 +2743,7 @@ type rewriteHeadVarLocalTransform struct { declared map[Var]Var } -func (xform rewriteHeadVarLocalTransform) Transform(x interface{}) (interface{}, error) { +func (xform rewriteHeadVarLocalTransform) Transform(x any) (any, error) { if v, ok := x.(Var); ok { if gv, ok := xform.declared[v]; ok { return gv, nil @@ -2774,7 +2774,7 @@ type ruleArgLocalRewriter struct { errs []*Error } -func (vis *ruleArgLocalRewriter) Visit(x interface{}) Visitor { +func (vis *ruleArgLocalRewriter) Visit(x any) Visitor { t, ok := x.(*Term) if !ok { @@ -2821,7 +2821,7 @@ func (c *Compiler) rewriteWithModifiers() { f := newEqualityFactory(c.localvargen) for _, name := range c.sorted { mod := c.Modules[name] - t := NewGenericTransformer(func(x interface{}) (interface{}, error) { + t := NewGenericTransformer(func(x any) (any, error) { body, ok := x.(Body) if !ok { return x, nil @@ -3174,7 +3174,7 @@ func (ci *ComprehensionIndex) String() string { return fmt.Sprintf("", NewArray(ci.Keys...)) } -func buildComprehensionIndices(dbg debug.Debug, arity func(Ref) int, candidates VarSet, rwVars map[Var]Var, node interface{}, result map[*Term]*ComprehensionIndex) uint64 { +func buildComprehensionIndices(dbg debug.Debug, arity func(Ref) int, candidates VarSet, rwVars map[Var]Var, node any, result map[*Term]*ComprehensionIndex) uint64 { var n uint64 cpy := candidates.Copy() WalkBodies(node, func(b Body) bool { @@ -3327,11 +3327,11 @@ func newComprehensionIndexRegressionCheckVisitor(candidates VarSet) *comprehensi } } -func (vis *comprehensionIndexRegressionCheckVisitor) Walk(x interface{}) { +func (vis *comprehensionIndexRegressionCheckVisitor) Walk(x any) { NewGenericVisitor(vis.visit).Walk(x) } -func (vis *comprehensionIndexRegressionCheckVisitor) visit(x interface{}) bool { +func (vis *comprehensionIndexRegressionCheckVisitor) visit(x any) bool { if !vis.worse { switch x := x.(type) { case *Expr: @@ -3371,11 +3371,11 @@ func newComprehensionIndexNestedCandidateVisitor(candidates VarSet) *comprehensi } } -func (vis *comprehensionIndexNestedCandidateVisitor) Walk(x interface{}) { +func (vis *comprehensionIndexNestedCandidateVisitor) Walk(x any) { NewGenericVisitor(vis.visit).Walk(x) } -func (vis *comprehensionIndexNestedCandidateVisitor) visit(x interface{}) bool { +func (vis *comprehensionIndexNestedCandidateVisitor) visit(x any) bool { if vis.found { return true @@ -3676,7 +3676,7 @@ func NewGraph(modules map[string]*Module, list func(Ref) []*Rule) *Graph { // each dependency. vis := func(a *Rule) *GenericVisitor { stop := false - return NewGenericVisitor(func(x interface{}) bool { + return NewGenericVisitor(func(x any) bool { switch x := x.(type) { case Ref: for _, b := range list(x) { @@ -4001,7 +4001,7 @@ type bodySafetyTransformer struct { unsafe unsafeVars } -func (xform *bodySafetyTransformer) Visit(x interface{}) bool { +func (xform *bodySafetyTransformer) Visit(x any) bool { switch term := x.(type) { case *Term: switch x := term.Value.(type) { @@ -4078,7 +4078,7 @@ func (xform *bodySafetyTransformer) reorderSetComprehensionSafety(sc *SetCompreh // this expression. func unsafeVarsInClosures(e *Expr) VarSet { vs := VarSet{} - WalkClosures(e, func(x interface{}) bool { + WalkClosures(e, func(x any) bool { vis := &VarVisitor{vars: vs} if ev, ok := x.(*Every); ok { vis.Walk(ev.Body) @@ -4198,7 +4198,7 @@ func outputVarsForExprCall(expr *Expr, arity int, safe VarSet, terms []*Term) Va return output } -func outputVarsForTerms(expr interface{}, safe VarSet) VarSet { +func outputVarsForTerms(expr any, safe VarSet) VarSet { output := VarSet{} WalkTerms(expr, func(x *Term) bool { switch r := x.Value.(type) { @@ -4250,7 +4250,7 @@ func newLocalVarGeneratorForModuleSet(sorted []string, modules map[string]*Modul return &localVarGenerator{exclude: exclude, next: 0} } -func newLocalVarGenerator(suffix string, node interface{}) *localVarGenerator { +func newLocalVarGenerator(suffix string, node any) *localVarGenerator { exclude := NewVarSet() vis := &VarVisitor{vars: exclude} vis.Walk(node) @@ -4340,7 +4340,7 @@ func resolveRefsInRule(globals map[Var]*usedRef, rule *Rule) error { // Walk args to collect vars and transform body so that callers can shadow // root documents. - vis = NewGenericVisitor(func(x interface{}) bool { + vis = NewGenericVisitor(func(x any) bool { if err != nil { return true } @@ -4561,9 +4561,9 @@ func (s *declaredVarStack) Pop() { *s = curr[:len(curr)-1] } -func declaredVars(x interface{}) VarSet { +func declaredVars(x any) VarSet { vars := NewVarSet() - vis := NewGenericVisitor(func(x interface{}) bool { + vis := NewGenericVisitor(func(x any) bool { switch x := x.(type) { case *Expr: if x.IsAssignment() && validEqAssignArgCount(x) { @@ -4612,8 +4612,8 @@ func declaredVars(x interface{}) VarSet { // The comprehension would be rewritten as: // // [__local0__ | x = y[_]; y = [1,2,3]; __local0__ = x[0]] -func rewriteComprehensionTerms(f *equalityFactory, node interface{}) (interface{}, error) { - return TransformComprehensions(node, func(x interface{}) (Value, error) { +func rewriteComprehensionTerms(f *equalityFactory, node any) (any, error) { + return TransformComprehensions(node, func(x any) (Value, error) { switch x := x.(type) { case *ArrayComprehension: if requiresEval(x.Term) { @@ -4659,10 +4659,10 @@ func rewriteComprehensionTerms(f *equalityFactory, node interface{}) (interface{ // result back whereas with = the result is only ever true/undefined. For // partial evaluation cases we do want to rewrite == to = to simplify the // result. -func rewriteEquals(x interface{}) (modified bool) { +func rewriteEquals(x any) (modified bool) { doubleEq := Equal.Ref() unifyOp := Equality.Ref() - t := NewGenericTransformer(func(x interface{}) (interface{}, error) { + t := NewGenericTransformer(func(x any) (any, error) { if x, ok := x.(*Expr); ok && x.IsCall() { operator := x.Operator() if operator.Equal(doubleEq) && len(x.Operands()) == 2 { @@ -5429,7 +5429,7 @@ func rewriteSomeDeclStatement(g *localVarGenerator, stack *localDeclaredVars, ex } func rewriteDeclaredVarsInExpr(g *localVarGenerator, stack *localDeclaredVars, expr *Expr, errs Errors, strict bool) (*Expr, Errors) { - vis := NewGenericVisitor(func(x interface{}) bool { + vis := NewGenericVisitor(func(x any) bool { var stop bool switch x := x.(type) { case *Term: @@ -5906,7 +5906,7 @@ func safetyErrorSlice(unsafe unsafeVars, rewritten map[Var]Var) (result Errors) return } -func checkUnsafeBuiltins(unsafeBuiltinsMap map[string]struct{}, node interface{}) Errors { +func checkUnsafeBuiltins(unsafeBuiltinsMap map[string]struct{}, node any) Errors { errs := make(Errors, 0) WalkExprs(node, func(x *Expr) bool { if x.IsCall() { diff --git a/v1/ast/compile_test.go b/v1/ast/compile_test.go index 963dcc0952..48d6606731 100644 --- a/v1/ast/compile_test.go +++ b/v1/ast/compile_test.go @@ -2647,7 +2647,7 @@ func TestCompilerRewriteExprTerms(t *testing.T) { cases := []struct { note string module string - expected interface{} + expected any }{ { note: "base", @@ -5019,7 +5019,7 @@ func TestCompilerRewriteLocalAssignments(t *testing.T) { tests := []struct { module string - exp interface{} + exp any expRewrittenMap map[Var]Var regoVersion RegoVersion }{ @@ -8709,7 +8709,7 @@ p contains 2 if { true }`, tests := []struct { note string - ref interface{} + ref any expected []*Rule }{ {"exact", "data.a.b.c.p", []*Rule{ @@ -8768,7 +8768,7 @@ p contains 2 if { true }`, tests := []struct { note string - ref interface{} + ref any expected []*Rule }{ {"exact", "data.a.b.c.p", []*Rule{ @@ -8832,7 +8832,7 @@ q contains 3 if { true }`, tests := []struct { note string - ref interface{} + ref any expected []*Rule }{ {"exact", "data.a.b.c.p", []*Rule{ @@ -9788,7 +9788,7 @@ func TestQueryCompiler(t *testing.T) { imports []string input string regoVersion RegoVersion - expected interface{} + expected any }{ { note: "empty query", @@ -10373,7 +10373,7 @@ func compilerErrsToStringSlice(errors []*Error) []string { return result } -func runQueryCompilerTest(q string, popts ParserOptions, pkg string, imports []string, expected interface{}) func(*testing.T) { +func runQueryCompilerTest(q string, popts ParserOptions, pkg string, imports []string, expected any) func(*testing.T) { return func(t *testing.T) { t.Helper() c := NewCompiler().WithEnablePrintStatements(false) @@ -11073,7 +11073,7 @@ deny if { ` c := NewCompiler() - var schema interface{} + var schema any if err := json.Unmarshal([]byte(jsonSchema), &schema); err != nil { t.Fatal(err) } @@ -11137,7 +11137,7 @@ deny if { c := NewCompiler(). WithUseTypeCheckAnnotations(true) - var schema interface{} + var schema any if err := json.Unmarshal([]byte(jsonSchema), &schema); err != nil { t.Fatal(err) } @@ -11284,7 +11284,7 @@ deny if { ` c := NewCompiler() - var schema interface{} + var schema any if err := json.Unmarshal([]byte(jsonSchema), &schema); err != nil { t.Fatal(err) } diff --git a/v1/ast/env.go b/v1/ast/env.go index 9bffd03e0a..12d4be8918 100644 --- a/v1/ast/env.go +++ b/v1/ast/env.go @@ -30,7 +30,7 @@ func newTypeEnv(f func() *typeChecker) *TypeEnv { // Get returns the type of x. // Deprecated: Use GetByValue or GetByRef instead, as they are more efficient. -func (env *TypeEnv) Get(x interface{}) types.Type { +func (env *TypeEnv) Get(x any) types.Type { if term, ok := x.(*Term); ok { x = term.Value } diff --git a/v1/ast/errors.go b/v1/ast/errors.go index c7aab71141..75160afc6e 100644 --- a/v1/ast/errors.go +++ b/v1/ast/errors.go @@ -115,7 +115,7 @@ func (e *Error) Error() string { } // NewError returns a new Error object. -func NewError(code string, loc *Location, f string, a ...interface{}) *Error { +func NewError(code string, loc *Location, f string, a ...any) *Error { return &Error{ Code: code, Location: loc, diff --git a/v1/ast/index.go b/v1/ast/index.go index 722b70e57e..8eb52de784 100644 --- a/v1/ast/index.go +++ b/v1/ast/index.go @@ -253,7 +253,7 @@ type ruleWalker struct { result *trieTraversalResult } -func (r *ruleWalker) Do(x interface{}) trieWalker { +func (r *ruleWalker) Do(x any) trieWalker { tn := x.(*trieNode) r.result.Add(tn) return r @@ -454,7 +454,7 @@ func (i *refindices) index(rule *Rule, ref Ref) *refindex { } type trieWalker interface { - Do(x interface{}) trieWalker + Do(x any) trieWalker } type trieTraversalResult struct { @@ -850,7 +850,7 @@ func indexValue(b *Term) (Value, bool) { case *Array: stop := false first := true - vis := NewGenericVisitor(func(x interface{}) bool { + vis := NewGenericVisitor(func(x any) bool { if first { first = false return false diff --git a/v1/ast/index_test.go b/v1/ast/index_test.go index cac85a2e4c..477ad53e71 100644 --- a/v1/ast/index_test.go +++ b/v1/ast/index_test.go @@ -238,7 +238,7 @@ func TestBaseDocEqIndexing(t *testing.T) { input string unknowns []string args []Value - expectedRS interface{} + expectedRS any expectedDR *Rule checkResult func(*testing.T, *IndexResult) }{ @@ -1043,7 +1043,7 @@ func TestBaseDocIndexResultEarlyExit(t *testing.T) { module *Module input string disableIndexing bool - expectedRS interface{} + expectedRS any expectedDR *Rule expectedEE bool }{ diff --git a/v1/ast/location/location.go b/v1/ast/location/location.go index 716aad6930..6d1b16cdfc 100644 --- a/v1/ast/location/location.go +++ b/v1/ast/location/location.go @@ -36,18 +36,18 @@ func (loc *Location) Equal(other *Location) bool { // Errorf returns a new error value with a message formatted to include the location // info (e.g., line, column, filename, etc.) -func (loc *Location) Errorf(f string, a ...interface{}) error { +func (loc *Location) Errorf(f string, a ...any) error { return errors.New(loc.Format(f, a...)) } // Wrapf returns a new error value that wraps an existing error with a message formatted // to include the location info (e.g., line, column, filename, etc.) -func (loc *Location) Wrapf(err error, f string, a ...interface{}) error { +func (loc *Location) Wrapf(err error, f string, a ...any) error { return fmt.Errorf(loc.Format(f, a...)+": %w", err) } // Format returns a formatted string prefixed with the location information. -func (loc *Location) Format(f string, a ...interface{}) string { +func (loc *Location) Format(f string, a ...any) string { if len(loc.File) > 0 { f = fmt.Sprintf("%v:%v: %v", loc.File, loc.Row, f) } else { diff --git a/v1/ast/map.go b/v1/ast/map.go index d0aa43755f..31cad4d611 100644 --- a/v1/ast/map.go +++ b/v1/ast/map.go @@ -26,9 +26,9 @@ func NewValueMap() *ValueMap { // MarshalJSON provides a custom marshaller for the ValueMap which // will include the key, value, and value type. func (vs *ValueMap) MarshalJSON() ([]byte, error) { - var tmp []map[string]interface{} + var tmp []map[string]any vs.Iter(func(k Value, v Value) bool { - tmp = append(tmp, map[string]interface{}{ + tmp = append(tmp, map[string]any{ "name": k.String(), "type": ValueName(v), "value": v, diff --git a/v1/ast/marshal_test.go b/v1/ast/marshal_test.go index 28c26b7f9a..a748d1a76a 100644 --- a/v1/ast/marshal_test.go +++ b/v1/ast/marshal_test.go @@ -468,7 +468,7 @@ func TestRule_MarshalJSON(t *testing.T) { Entrypoint: true, Organizations: []string{"org1"}, Description: "My desc", - Custom: map[string]interface{}{ + Custom: map[string]any{ "foo": "bar", }}} return r @@ -900,7 +900,7 @@ func TestAnnotations_MarshalJSON(t *testing.T) { Entrypoint: true, Organizations: []string{"org1"}, Description: "My desc", - Custom: map[string]interface{}{ + Custom: map[string]any{ "foo": "bar", }, Location: NewLocation([]byte{}, "example.rego", 1, 4), @@ -914,7 +914,7 @@ func TestAnnotations_MarshalJSON(t *testing.T) { Entrypoint: true, Organizations: []string{"org1"}, Description: "My desc", - Custom: map[string]interface{}{ + Custom: map[string]any{ "foo": "bar", }, Location: NewLocation([]byte{}, "example.rego", 1, 4), @@ -933,7 +933,7 @@ func TestAnnotations_MarshalJSON(t *testing.T) { Entrypoint: true, Organizations: []string{"org1"}, Description: "My desc", - Custom: map[string]interface{}{ + Custom: map[string]any{ "foo": "bar", }, Location: NewLocation([]byte{}, "example.rego", 1, 4), diff --git a/v1/ast/parser.go b/v1/ast/parser.go index 66779b8d75..678466d58a 100644 --- a/v1/ast/parser.go +++ b/v1/ast/parser.go @@ -2115,7 +2115,7 @@ func (p *Parser) error(loc *location.Location, reason string) { p.errorf(loc, reason) //nolint:govet } -func (p *Parser) errorf(loc *location.Location, f string, a ...interface{}) { +func (p *Parser) errorf(loc *location.Location, f string, a ...any) { msg := strings.Builder{} msg.WriteString(fmt.Sprintf(f, a...)) @@ -2145,11 +2145,11 @@ func (p *Parser) errorf(loc *location.Location, f string, a ...interface{}) { p.s.hints = nil } -func (p *Parser) hint(f string, a ...interface{}) { +func (p *Parser) hint(f string, a ...any) { p.s.hints = append(p.s.hints, fmt.Sprintf(f, a...)) } -func (p *Parser) illegal(note string, a ...interface{}) { +func (p *Parser) illegal(note string, a ...any) { tok := p.s.tok.String() if p.s.tok == tokens.Illegal { @@ -2251,8 +2251,8 @@ func (p *Parser) restore(s *state) { p.s = s } -func setLocRecursive(x interface{}, loc *location.Location) { - NewGenericVisitor(func(x interface{}) bool { +func setLocRecursive(x any, loc *location.Location) { + NewGenericVisitor(func(x any) bool { if node, ok := x.(Node); ok { node.SetLoc(loc) } @@ -2276,7 +2276,7 @@ func (p *Parser) validateDefaultRuleValue(rule *Rule) bool { } valid := true - vis := NewGenericVisitor(func(x interface{}) bool { + vis := NewGenericVisitor(func(x any) bool { switch x.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension: // skip closures return true @@ -2297,7 +2297,7 @@ func (p *Parser) validateDefaultRuleArgs(rule *Rule) bool { valid := true vars := NewVarSet() - vis := NewGenericVisitor(func(x interface{}) bool { + vis := NewGenericVisitor(func(x any) bool { switch x := x.(type) { case Var: if vars.Contains(x) { @@ -2327,15 +2327,15 @@ func (p *Parser) validateDefaultRuleArgs(rule *Rule) bool { // We explicitly use yaml unmarshalling, to accommodate for the '_' in 'related_resources', // which isn't handled properly by json for some reason. type rawAnnotation struct { - Scope string `yaml:"scope"` - Title string `yaml:"title"` - Entrypoint bool `yaml:"entrypoint"` - Description string `yaml:"description"` - Organizations []string `yaml:"organizations"` - RelatedResources []interface{} `yaml:"related_resources"` - Authors []interface{} `yaml:"authors"` - Schemas []map[string]any `yaml:"schemas"` - Custom map[string]interface{} `yaml:"custom"` + Scope string `yaml:"scope"` + Title string `yaml:"title"` + Entrypoint bool `yaml:"entrypoint"` + Description string `yaml:"description"` + Organizations []string `yaml:"organizations"` + RelatedResources []any `yaml:"related_resources"` + Authors []any `yaml:"authors"` + Schemas []map[string]any `yaml:"schemas"` + Custom map[string]any `yaml:"custom"` } type metadataParser struct { @@ -2440,7 +2440,7 @@ func (b *metadataParser) Parse() (*Annotations, error) { result.Authors = append(result.Authors, author) } - result.Custom = make(map[string]interface{}) + result.Custom = make(map[string]any) for k, v := range raw.Custom { val, err := convertYAMLMapKeyTypes(v, nil) if err != nil { @@ -2503,7 +2503,7 @@ func augmentYamlError(err error, comments []*Comment) error { return err } -func unwrapPair(pair map[string]interface{}) (string, interface{}) { +func unwrapPair(pair map[string]any) (string, any) { for k, v := range pair { return k, v } @@ -2534,7 +2534,7 @@ func parseSchemaRef(s string) (Ref, error) { return nil, errInvalidSchemaRef } -func parseRelatedResource(rr interface{}) (*RelatedResourceAnnotation, error) { +func parseRelatedResource(rr any) (*RelatedResourceAnnotation, error) { rr, err := convertYAMLMapKeyTypes(rr, nil) if err != nil { return nil, err @@ -2550,7 +2550,7 @@ func parseRelatedResource(rr interface{}) (*RelatedResourceAnnotation, error) { return &RelatedResourceAnnotation{Ref: *u}, nil } return nil, errors.New("ref URL may not be empty string") - case map[string]interface{}: + case map[string]any: description := strings.TrimSpace(getSafeString(rr, "description")) ref := strings.TrimSpace(getSafeString(rr, "ref")) if len(ref) > 0 { @@ -2566,7 +2566,7 @@ func parseRelatedResource(rr interface{}) (*RelatedResourceAnnotation, error) { return nil, errors.New("invalid value type, must be string or map") } -func parseAuthor(a interface{}) (*AuthorAnnotation, error) { +func parseAuthor(a any) (*AuthorAnnotation, error) { a, err := convertYAMLMapKeyTypes(a, nil) if err != nil { return nil, err @@ -2575,7 +2575,7 @@ func parseAuthor(a interface{}) (*AuthorAnnotation, error) { switch a := a.(type) { case string: return parseAuthorString(a) - case map[string]interface{}: + case map[string]any: name := strings.TrimSpace(getSafeString(a, "name")) email := strings.TrimSpace(getSafeString(a, "email")) if len(name) > 0 || len(email) > 0 { @@ -2587,7 +2587,7 @@ func parseAuthor(a interface{}) (*AuthorAnnotation, error) { return nil, errors.New("invalid value type, must be string or map") } -func getSafeString(m map[string]interface{}, k string) string { +func getSafeString(m map[string]any, k string) string { if v, found := m[k]; found { if s, ok := v.(string); ok { return s diff --git a/v1/ast/parser_bench_test.go b/v1/ast/parser_bench_test.go index 3dd08d5015..1a6239f444 100644 --- a/v1/ast/parser_bench_test.go +++ b/v1/ast/parser_bench_test.go @@ -195,8 +195,8 @@ func generateObjectStatement(width, depth int) string { return string(util.MustMarshalJSON(o)) } -func generateObject(width, depth int) map[string]interface{} { - o := map[string]interface{}{} +func generateObject(width, depth int) map[string]any { + o := map[string]any{} for i := range width { key := fmt.Sprintf("entry-%d", i) if depth <= 1 { diff --git a/v1/ast/parser_test.go b/v1/ast/parser_test.go index af24ecaae5..4124103062 100644 --- a/v1/ast/parser_test.go +++ b/v1/ast/parser_test.go @@ -4813,10 +4813,10 @@ func TestAnnotations(t *testing.T) { schemaNetworks := MustParseRef("schema.networks") schemaPorts := MustParseRef("schema.ports") - stringSchemaAsMap := map[string]interface{}{ + stringSchemaAsMap := map[string]any{ "type": "string", } - var stringSchema interface{} = stringSchemaAsMap + var stringSchema any = stringSchemaAsMap tests := []struct { note string @@ -5366,14 +5366,14 @@ p if { input = "str" }`, Email: "jane@example.com", }, }, - Custom: map[string]interface{}{ - "list": []interface{}{ + Custom: map[string]any{ + "list": []any{ "a", "b", }, - "map": map[string]interface{}{ + "map": map[string]any{ "a": 1, "b": 2.2, - "c": map[string]interface{}{ + "c": map[string]any{ "3": "d", "4": "e", }, @@ -6096,8 +6096,8 @@ package foo` func TestAuthorAnnotation(t *testing.T) { tests := []struct { note string - raw interface{} - expected interface{} + raw any + expected any }{ { note: "no name", @@ -6146,21 +6146,21 @@ func TestAuthorAnnotation(t *testing.T) { }, { note: "map with name", - raw: map[string]interface{}{ + raw: map[string]any{ "name": "John Doe", }, expected: AuthorAnnotation{Name: "John Doe"}, }, { note: "map with email", - raw: map[string]interface{}{ + raw: map[string]any{ "email": "john@example.com", }, expected: AuthorAnnotation{Email: "john@example.com"}, }, { note: "map with name and email", - raw: map[string]interface{}{ + raw: map[string]any{ "name": "John Doe", "email": "john@example.com", }, @@ -6168,7 +6168,7 @@ func TestAuthorAnnotation(t *testing.T) { }, { note: "map with extra entry", - raw: map[string]interface{}{ + raw: map[string]any{ "name": "John Doe", "email": "john@example.com", "foo": "bar", @@ -6177,19 +6177,19 @@ func TestAuthorAnnotation(t *testing.T) { }, { note: "empty map", - raw: map[string]interface{}{}, + raw: map[string]any{}, expected: errors.New("'name' and/or 'email' values required in object"), }, { note: "map with empty name", - raw: map[string]interface{}{ + raw: map[string]any{ "name": "", }, expected: errors.New("'name' and/or 'email' values required in object"), }, { note: "map with email and empty name", - raw: map[string]interface{}{ + raw: map[string]any{ "name": "", "email": "john@example.com", }, @@ -6197,14 +6197,14 @@ func TestAuthorAnnotation(t *testing.T) { }, { note: "map with empty email", - raw: map[string]interface{}{ + raw: map[string]any{ "email": "", }, expected: errors.New("'name' and/or 'email' values required in object"), }, { note: "map with name and empty email", - raw: map[string]interface{}{ + raw: map[string]any{ "name": "John Doe", "email": "", }, @@ -6243,8 +6243,8 @@ func TestAuthorAnnotation(t *testing.T) { func TestRelatedResourceAnnotation(t *testing.T) { tests := []struct { note string - raw interface{} - expected interface{} + raw any + expected any }{ { note: "empty ref URL", @@ -6268,21 +6268,21 @@ func TestRelatedResourceAnnotation(t *testing.T) { }, { note: "map with only ref", - raw: map[string]interface{}{ + raw: map[string]any{ "ref": "https://example.com/foo?bar#baz", }, expected: RelatedResourceAnnotation{Ref: mustParseURL("https://example.com/foo?bar#baz")}, }, { note: "map with only description", - raw: map[string]interface{}{ + raw: map[string]any{ "description": "foo bar", }, expected: errors.New("'ref' value required in object"), }, { note: "map with ref and description", - raw: map[string]interface{}{ + raw: map[string]any{ "ref": "https://example.com/foo?bar#baz", "description": "foo bar", }, @@ -6293,7 +6293,7 @@ func TestRelatedResourceAnnotation(t *testing.T) { }, { note: "map with ref and description", - raw: map[string]interface{}{ + raw: map[string]any{ "ref": "https://example.com/foo?bar#baz", "description": "foo bar", "foo": "bar", @@ -6305,19 +6305,19 @@ func TestRelatedResourceAnnotation(t *testing.T) { }, { note: "empty map", - raw: map[string]interface{}{}, + raw: map[string]any{}, expected: errors.New("'ref' value required in object"), }, { note: "map with empty ref", - raw: map[string]interface{}{ + raw: map[string]any{ "ref": "", }, expected: errors.New("'ref' value required in object"), }, { note: "map with only whitespace in ref", - raw: map[string]interface{}{ + raw: map[string]any{ "ref": " \t", }, expected: errors.New("'ref' value required in object"), @@ -6429,7 +6429,7 @@ func assertParseErrorFunc(t *testing.T, msg string, input string, f func(string) func assertParseImport(t *testing.T, msg string, input string, correct *Import, opts ...ParserOptions) { t.Helper() - assertParseOne(t, msg, input, func(parsed interface{}) { + assertParseOne(t, msg, input, func(parsed any) { t.Helper() imp := parsed.(*Import) if !imp.Equal(correct) { @@ -6465,7 +6465,7 @@ func assertParseModuleError(t *testing.T, msg, input string) { } func assertParsePackage(t *testing.T, msg string, input string, correct *Package) { - assertParseOne(t, msg, input, func(parsed interface{}) { + assertParseOne(t, msg, input, func(parsed any) { pkg := parsed.(*Package) if !pkg.Equal(correct) { t.Errorf("Error on test \"%s\": packages not equal: %v (parsed), %v (correct)", msg, pkg, correct) @@ -6473,7 +6473,7 @@ func assertParsePackage(t *testing.T, msg string, input string, correct *Package }) } -func assertParseOne(t *testing.T, msg string, input string, correct func(interface{}), opts ...ParserOptions) { +func assertParseOne(t *testing.T, msg string, input string, correct func(any), opts ...ParserOptions) { t.Helper() opt := ParserOptions{} if len(opts) == 1 { @@ -6504,7 +6504,7 @@ func assertParseOneBody(t *testing.T, msg string, input string, correct Body) { func assertParseOneExpr(t *testing.T, msg string, input string, correct *Expr, opts ...ParserOptions) { t.Helper() - assertParseOne(t, msg, input, func(parsed interface{}) { + assertParseOne(t, msg, input, func(parsed any) { t.Helper() body := parsed.(Body) if len(body) != 1 { @@ -6537,7 +6537,7 @@ func assertParseOneTermNegated(t *testing.T, msg string, input string, correct * func assertParseRule(t *testing.T, msg string, input string, correct *Rule, opts ...ParserOptions) { t.Helper() - assertParseOne(t, msg, input, func(parsed interface{}) { + assertParseOne(t, msg, input, func(parsed any) { t.Helper() rule := parsed.(*Rule) if rule.Head.Name != correct.Head.Name { diff --git a/v1/ast/policy.go b/v1/ast/policy.go index 978de9441b..cf8e1970c3 100644 --- a/v1/ast/policy.go +++ b/v1/ast/policy.go @@ -265,12 +265,12 @@ type ( // Expr represents a single expression contained inside the body of a rule. Expr struct { - With []*With `json:"with,omitempty"` - Terms interface{} `json:"terms"` - Index int `json:"index"` - Generated bool `json:"generated,omitempty"` - Negated bool `json:"negated,omitempty"` - Location *Location `json:"location,omitempty"` + With []*With `json:"with,omitempty"` + Terms any `json:"terms"` + Index int `json:"index"` + Generated bool `json:"generated,omitempty"` + Negated bool `json:"negated,omitempty"` + Location *Location `json:"location,omitempty"` generatedFrom *Expr generates []*Expr @@ -537,7 +537,7 @@ func (pkg *Package) String() string { } func (pkg *Package) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "path": pkg.Path, } @@ -644,7 +644,7 @@ func (imp *Import) String() string { } func (imp *Import) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "path": imp.Path, } @@ -792,7 +792,7 @@ func (rule *Rule) isFunction() bool { } func (rule *Rule) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "head": rule.Head, "body": rule.Body, } @@ -1256,7 +1256,7 @@ func (body Body) Vars(params VarVisitorParams) VarSet { } // NewExpr returns a new Expr object. -func NewExpr(terms interface{}) *Expr { +func NewExpr(terms any) *Expr { switch terms.(type) { case *SomeDecl, *Every, *Term, []*Term: // ok default: @@ -1578,7 +1578,7 @@ func (expr *Expr) String() string { } func (expr *Expr) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "terms": expr.Terms, "index": expr.Index, } @@ -1606,7 +1606,7 @@ func (expr *Expr) MarshalJSON() ([]byte, error) { // UnmarshalJSON parses the byte array and stores the result in expr. func (expr *Expr) UnmarshalJSON(bs []byte) error { - v := map[string]interface{}{} + v := map[string]any{} if err := util.UnmarshalJSON(bs, &v); err != nil { return err } @@ -1710,7 +1710,7 @@ func (d *SomeDecl) Hash() int { } func (d *SomeDecl) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "symbols": d.Symbols, } @@ -1780,7 +1780,7 @@ func (q *Every) KeyValueVars() VarSet { } func (q *Every) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "key": q.Key, "value": q.Value, "domain": q.Domain, @@ -1855,7 +1855,7 @@ func (w *With) SetLoc(loc *Location) { } func (w *With) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{ + data := map[string]any{ "target": w.Target, "value": w.Value, } @@ -1870,7 +1870,7 @@ func (w *With) MarshalJSON() ([]byte, error) { } // Copy returns a deep copy of the AST node x. If x is not an AST node, x is returned unmodified. -func Copy(x interface{}) interface{} { +func Copy(x any) any { switch x := x.(type) { case *Module: return x.Copy() diff --git a/v1/ast/policy_test.go b/v1/ast/policy_test.go index 5e2c415ff9..3a86c23669 100644 --- a/v1/ast/policy_test.go +++ b/v1/ast/policy_test.go @@ -864,13 +864,13 @@ func TestAnnotationsString(t *testing.T) { Schema: MustParseRef("schema.baz"), }, }, - Custom: map[string]interface{}{ + Custom: map[string]any{ "list": []int{ 1, 2, 3, }, - "map": map[string]interface{}{ + "map": map[string]any{ "one": 1, - "two": map[int]interface{}{ + "two": map[int]any{ 3: "three", }, }, diff --git a/v1/ast/pretty.go b/v1/ast/pretty.go index b4f05ad501..aa34f37471 100644 --- a/v1/ast/pretty.go +++ b/v1/ast/pretty.go @@ -13,7 +13,7 @@ import ( // Pretty writes a pretty representation of the AST rooted at x to w. // // This is function is intended for debug purposes when inspecting ASTs. -func Pretty(w io.Writer, x interface{}) { +func Pretty(w io.Writer, x any) { pp := &prettyPrinter{ depth: -1, w: w, @@ -26,7 +26,7 @@ type prettyPrinter struct { w io.Writer } -func (pp *prettyPrinter) Before(x interface{}) bool { +func (pp *prettyPrinter) Before(x any) bool { switch x.(type) { case *Term: default: @@ -56,7 +56,7 @@ func (pp *prettyPrinter) Before(x interface{}) bool { return false } -func (pp *prettyPrinter) After(x interface{}) { +func (pp *prettyPrinter) After(x any) { switch x.(type) { case *Term: default: @@ -64,19 +64,19 @@ func (pp *prettyPrinter) After(x interface{}) { } } -func (pp *prettyPrinter) writeValue(x interface{}) { +func (pp *prettyPrinter) writeValue(x any) { pp.writeIndent(fmt.Sprint(x)) } -func (pp *prettyPrinter) writeType(x interface{}) { +func (pp *prettyPrinter) writeType(x any) { pp.writeIndent(TypeName(x)) } -func (pp *prettyPrinter) writeIndent(f string, a ...interface{}) { +func (pp *prettyPrinter) writeIndent(f string, a ...any) { pad := strings.Repeat(" ", pp.depth) pp.write(pad+f, a...) } -func (pp *prettyPrinter) write(f string, a ...interface{}) { +func (pp *prettyPrinter) write(f string, a ...any) { fmt.Fprintf(pp.w, f+"\n", a...) } diff --git a/v1/ast/rego_v1.go b/v1/ast/rego_v1.go index 8b757ecc3c..883e026e19 100644 --- a/v1/ast/rego_v1.go +++ b/v1/ast/rego_v1.go @@ -23,7 +23,7 @@ func checkDuplicateImports(modules []*Module) (errors Errors) { return } -func checkRootDocumentOverrides(node interface{}) Errors { +func checkRootDocumentOverrides(node any) Errors { errors := Errors{} WalkRules(node, func(rule *Rule) bool { @@ -64,8 +64,8 @@ func checkRootDocumentOverrides(node interface{}) Errors { return errors } -func walkCalls(node interface{}, f func(interface{}) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func walkCalls(node any, f func(any) bool) { + vis := &GenericVisitor{func(x any) bool { switch x := x.(type) { case Call: return f(x) @@ -82,10 +82,10 @@ func walkCalls(node interface{}, f func(interface{}) bool) { vis.Walk(node) } -func checkDeprecatedBuiltins(deprecatedBuiltinsMap map[string]struct{}, node interface{}) Errors { +func checkDeprecatedBuiltins(deprecatedBuiltinsMap map[string]struct{}, node any) Errors { errs := make(Errors, 0) - walkCalls(node, func(x interface{}) bool { + walkCalls(node, func(x any) bool { var operator string var loc *Location @@ -113,7 +113,7 @@ func checkDeprecatedBuiltins(deprecatedBuiltinsMap map[string]struct{}, node int return errs } -func checkDeprecatedBuiltinsForCurrentVersion(node interface{}) Errors { +func checkDeprecatedBuiltinsForCurrentVersion(node any) Errors { deprecatedBuiltins := make(map[string]struct{}) capabilities := CapabilitiesForThisVersion() for _, bi := range capabilities.Builtins { @@ -150,11 +150,11 @@ func NewRegoCheckOptions() RegoCheckOptions { // CheckRegoV1 checks the given module or rule for errors that are specific to Rego v1. // Passing something other than an *ast.Rule or *ast.Module is considered a programming error, and will cause a panic. -func CheckRegoV1(x interface{}) Errors { +func CheckRegoV1(x any) Errors { return CheckRegoV1WithOptions(x, NewRegoCheckOptions()) } -func CheckRegoV1WithOptions(x interface{}, opts RegoCheckOptions) Errors { +func CheckRegoV1WithOptions(x any, opts RegoCheckOptions) Errors { switch x := x.(type) { case *Module: return checkRegoV1Module(x, opts) diff --git a/v1/ast/schema_test.go b/v1/ast/schema_test.go index 2f0364c20a..a8ba33185b 100644 --- a/v1/ast/schema_test.go +++ b/v1/ast/schema_test.go @@ -20,7 +20,7 @@ import ( func testParseSchema(t *testing.T, schema string, expectedType types.Type, expectedError error) { t.Helper() - var sch interface{} + var sch any err := util.Unmarshal([]byte(schema), &sch) if err != nil { t.Fatalf("unexpected error: %s", err) @@ -56,7 +56,7 @@ func TestParseSchemaObject(t *testing.T) { } func TestSetTypesWithSchemaRef(t *testing.T) { - var sch interface{} + var sch any ts := kubeSchemaServer(t) t.Cleanup(ts.Close) @@ -116,7 +116,7 @@ func TestSetTypesWithSchemaRef(t *testing.T) { } func TestSetTypesWithPodSchema(t *testing.T) { - var sch interface{} + var sch any ts := kubeSchemaServer(t) t.Cleanup(ts.Close) @@ -439,7 +439,7 @@ func TestParseSchemaBasics(t *testing.T) { func TestCompileSchemaEmptySchema(t *testing.T) { schema := "" - var sch interface{} + var sch any err := util.Unmarshal([]byte(schema), &sch) if err != nil { t.Fatalf("unexpected error: %s", err) @@ -451,7 +451,7 @@ func TestCompileSchemaEmptySchema(t *testing.T) { } func TestParseSchemaWithSchemaBadSchema(t *testing.T) { - var sch interface{} + var sch any err := util.Unmarshal([]byte(objectSchema), &sch) if err != nil { t.Fatalf("unexpected error: %s", err) @@ -581,7 +581,7 @@ func kubeSchemaServer(t *testing.T) *httptest.Server { func TestCompilerCheckTypesWithSchema(t *testing.T) { c := NewCompiler() - var schema interface{} + var schema any err := util.Unmarshal([]byte(objectSchema), &schema) if err != nil { t.Fatal("Unexpected error:", err) @@ -595,7 +595,7 @@ func TestCompilerCheckTypesWithSchema(t *testing.T) { func TestCompilerCheckTypesWithRegexPatternInSchema(t *testing.T) { c := NewCompiler() - var schema interface{} + var schema any // Negative lookahead is not supported in the Go regex dialect, but this is still a valid // JSON schema. Since we don't rely on the "pattern" attribute for type checking, ensure // that this still works (by being ignored) @@ -734,7 +734,7 @@ func TestCompilerCheckTypesWithAllOfSchema(t *testing.T) { for _, tc := range tests { t.Run(tc.note, func(t *testing.T) { c := NewCompiler() - var schema interface{} + var schema any err := util.Unmarshal([]byte(tc.schema), &schema) if err != nil { t.Fatal("Unexpected error:", err) diff --git a/v1/ast/strings.go b/v1/ast/strings.go index 40d66753f5..8447522412 100644 --- a/v1/ast/strings.go +++ b/v1/ast/strings.go @@ -10,7 +10,7 @@ import ( ) // TypeName returns a human readable name for the AST element type. -func TypeName(x interface{}) string { +func TypeName(x any) string { if _, ok := x.(*lazyObj); ok { return "object" } diff --git a/v1/ast/term.go b/v1/ast/term.go index 588699eec4..ab1e5bbc54 100644 --- a/v1/ast/term.go +++ b/v1/ast/term.go @@ -54,7 +54,7 @@ type Value interface { } // InterfaceToValue converts a native Go value x to a Value. -func InterfaceToValue(x interface{}) (Value, error) { +func InterfaceToValue(x any) (Value, error) { switch x := x.(type) { case Value: return x, nil @@ -127,7 +127,7 @@ func InterfaceToValue(x interface{}) (Value, error) { // ValueFromReader returns an AST value from a JSON serialized value in the reader. func ValueFromReader(r io.Reader) (Value, error) { - var x interface{} + var x any if err := util.NewJSONDecoder(r).Decode(&x); err != nil { return nil, err } @@ -135,13 +135,13 @@ func ValueFromReader(r io.Reader) (Value, error) { } // As converts v into a Go native type referred to by x. -func As(v Value, x interface{}) error { +func As(v Value, x any) error { return util.NewJSONDecoder(strings.NewReader(v.String())).Decode(x) } // Resolver defines the interface for resolving references to native Go values. type Resolver interface { - Resolve(Ref) (interface{}, error) + Resolve(Ref) (any, error) } // ValueResolver defines the interface for resolving references to AST values. @@ -165,18 +165,18 @@ func IsUnknownValueErr(err error) bool { type illegalResolver struct{} -func (illegalResolver) Resolve(ref Ref) (interface{}, error) { +func (illegalResolver) Resolve(ref Ref) (any, error) { return nil, fmt.Errorf("illegal value: %v", ref) } // ValueToInterface returns the Go representation of an AST value. The AST // value should not contain any values that require evaluation (e.g., vars, // comprehensions, etc.) -func ValueToInterface(v Value, resolver Resolver) (interface{}, error) { +func ValueToInterface(v Value, resolver Resolver) (any, error) { return valueToInterface(v, resolver, JSONOpt{}) } -func valueToInterface(v Value, resolver Resolver, opt JSONOpt) (interface{}, error) { +func valueToInterface(v Value, resolver Resolver, opt JSONOpt) (any, error) { switch v := v.(type) { case Null: return nil, nil @@ -187,7 +187,7 @@ func valueToInterface(v Value, resolver Resolver, opt JSONOpt) (interface{}, err case String: return string(v), nil case *Array: - buf := []interface{}{} + buf := []any{} for i := range v.Len() { x1, err := valueToInterface(v.Elem(i).Value, resolver, opt) if err != nil { @@ -197,7 +197,7 @@ func valueToInterface(v Value, resolver Resolver, opt JSONOpt) (interface{}, err } return buf, nil case *object: - buf := make(map[string]interface{}, v.Len()) + buf := make(map[string]any, v.Len()) err := v.Iter(func(k, v *Term) error { ki, err := valueToInterface(k.Value, resolver, opt) if err != nil { @@ -229,7 +229,7 @@ func valueToInterface(v Value, resolver Resolver, opt JSONOpt) (interface{}, err } return v.native, nil case Set: - buf := []interface{}{} + buf := []any{} iter := func(x *Term) error { x1, err := valueToInterface(x.Value, resolver, opt) if err != nil { @@ -257,19 +257,19 @@ func valueToInterface(v Value, resolver Resolver, opt JSONOpt) (interface{}, err // JSON returns the JSON representation of v. The value must not contain any // refs or terms that require evaluation (e.g., vars, comprehensions, etc.) -func JSON(v Value) (interface{}, error) { +func JSON(v Value) (any, error) { return JSONWithOpt(v, JSONOpt{}) } // JSONOpt defines parameters for AST to JSON conversion. type JSONOpt struct { SortSets bool // sort sets before serializing (this makes conversion more expensive) - CopyMaps bool // enforces copying of map[string]interface{} read from the store + CopyMaps bool // enforces copying of map[string]any read from the store } // JSONWithOpt returns the JSON representation of v. The value must not contain any // refs or terms that require evaluation (e.g., vars, comprehensions, etc.) -func JSONWithOpt(v Value, opt JSONOpt) (interface{}, error) { +func JSONWithOpt(v Value, opt JSONOpt) (any, error) { return valueToInterface(v, illegalResolver{}, opt) } @@ -277,7 +277,7 @@ func JSONWithOpt(v Value, opt JSONOpt) (interface{}, error) { // refs or terms that require evaluation (e.g., vars, comprehensions, etc.) If // the conversion fails, this function will panic. This function is mostly for // test purposes. -func MustJSON(v Value) interface{} { +func MustJSON(v Value) any { r, err := JSON(v) if err != nil { panic(err) @@ -288,7 +288,7 @@ func MustJSON(v Value) interface{} { // MustInterfaceToValue converts a native Go value x to a Value. If the // conversion fails, this function will panic. This function is mostly for test // purposes. -func MustInterfaceToValue(x interface{}) Value { +func MustInterfaceToValue(x any) Value { v, err := InterfaceToValue(x) if err != nil { panic(err) @@ -410,7 +410,7 @@ func (term *Term) IsGround() bool { // // Specialized marshalling logic is required to include a type hint for Value. func (term *Term) MarshalJSON() ([]byte, error) { - d := map[string]interface{}{ + d := map[string]any{ "type": ValueName(term.Value), "value": term.Value, } @@ -430,7 +430,7 @@ func (term *Term) String() string { // UnmarshalJSON parses the byte array and stores the result in term. // Specialized unmarshalling is required to handle Value and Location. func (term *Term) UnmarshalJSON(bs []byte) error { - v := map[string]interface{}{} + v := map[string]any{} if err := util.UnmarshalJSON(bs, &v); err != nil { return err } @@ -440,7 +440,7 @@ func (term *Term) UnmarshalJSON(bs []byte) error { } term.Value = val - if loc, ok := v["location"].(map[string]interface{}); ok { + if loc, ok := v["location"].(map[string]any); ok { term.Location = &Location{} err := unmarshalLocation(term.Location, loc) if err != nil { @@ -461,7 +461,7 @@ func (term *Term) Vars() VarSet { func IsConstant(v Value) bool { found := false vis := GenericVisitor{ - func(x interface{}) bool { + func(x any) bool { switch x.(type) { case Var, Ref, *ArrayComprehension, *ObjectComprehension, *SetComprehension, Call: found = true @@ -484,7 +484,7 @@ func IsComprehension(x Value) bool { } // ContainsRefs returns true if the Value v contains refs. -func ContainsRefs(v interface{}) bool { +func ContainsRefs(v any) bool { found := false WalkRefs(v, func(Ref) bool { found = true @@ -494,9 +494,9 @@ func ContainsRefs(v interface{}) bool { } // ContainsComprehensions returns true if the Value v contains comprehensions. -func ContainsComprehensions(v interface{}) bool { +func ContainsComprehensions(v any) bool { found := false - WalkClosures(v, func(x interface{}) bool { + WalkClosures(v, func(x any) bool { switch x.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension: found = true @@ -508,9 +508,9 @@ func ContainsComprehensions(v interface{}) bool { } // ContainsClosures returns true if the Value v contains closures. -func ContainsClosures(v interface{}) bool { +func ContainsClosures(v any) bool { found := false - WalkClosures(v, func(x interface{}) bool { + WalkClosures(v, func(x any) bool { switch x.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension, *Every: found = true @@ -804,7 +804,7 @@ func (str String) Equal(other Value) bool { func (str String) Compare(other Value) int { // Optimize for the common case of one string being compared to another by // using a direct comparison of values. This avoids the allocation performed - // when calling Compare and its interface{} argument conversion. + // when calling Compare and its any argument conversion. if otherStr, ok := other.(String); ok { if str == otherStr { return 0 @@ -2008,14 +2008,14 @@ func ObjectTerm(o ...[2]*Term) *Term { return &Term{Value: NewObject(o...)} } -func LazyObject(blob map[string]interface{}) Object { +func LazyObject(blob map[string]any) Object { return &lazyObj{native: blob, cache: map[string]Value{}} } type lazyObj struct { strict Object cache map[string]Value - native map[string]interface{} + native map[string]any } func (l *lazyObj) force() Object { @@ -2112,7 +2112,7 @@ func (l *lazyObj) Get(k *Term) *Term { if val, ok := l.native[string(s)]; ok { var converted Value switch val := val.(type) { - case map[string]interface{}: + case map[string]any: converted = LazyObject(val) default: converted = MustInterfaceToValue(val) @@ -2181,7 +2181,7 @@ func (l *lazyObj) Find(path Ref) (Value, error) { if v, ok := l.native[string(p0)]; ok { var converted Value switch v := v.(type) { - case map[string]interface{}: + case map[string]any: converted = LazyObject(v) default: converted = MustInterfaceToValue(v) @@ -3122,10 +3122,10 @@ func isControlOrBackslash(r rune) bool { // on the happy path and treats all errors the same. If better error // reporting is needed, the error paths will need to be fleshed out. -func unmarshalBody(b []interface{}) (Body, error) { +func unmarshalBody(b []any) (Body, error) { buf := Body{} for _, e := range b { - if m, ok := e.(map[string]interface{}); ok { + if m, ok := e.(map[string]any); ok { expr := &Expr{} if err := unmarshalExpr(expr, m); err == nil { buf = append(buf, expr) @@ -3139,7 +3139,7 @@ unmarshal_error: return nil, errors.New("ast: unable to unmarshal body") } -func unmarshalExpr(expr *Expr, v map[string]interface{}) error { +func unmarshalExpr(expr *Expr, v map[string]any) error { if x, ok := v["negated"]; ok { if b, ok := x.(bool); ok { expr.Negated = b @@ -3159,13 +3159,13 @@ func unmarshalExpr(expr *Expr, v map[string]interface{}) error { return err } switch ts := v["terms"].(type) { - case map[string]interface{}: + case map[string]any: t, err := unmarshalTerm(ts) if err != nil { return err } expr.Terms = t - case []interface{}: + case []any: terms, err := unmarshalTermSlice(ts) if err != nil { return err @@ -3175,7 +3175,7 @@ func unmarshalExpr(expr *Expr, v map[string]interface{}) error { return fmt.Errorf(`ast: unable to unmarshal terms field with type: %T (expected {"value": ..., "type": ...} or [{"value": ..., "type": ...}, ...])`, v["terms"]) } if x, ok := v["with"]; ok { - if sl, ok := x.([]interface{}); ok { + if sl, ok := x.([]any); ok { ws := make([]*With, len(sl)) for i := range sl { var err error @@ -3187,7 +3187,7 @@ func unmarshalExpr(expr *Expr, v map[string]interface{}) error { expr.With = ws } } - if loc, ok := v["location"].(map[string]interface{}); ok { + if loc, ok := v["location"].(map[string]any); ok { expr.Location = &Location{} if err := unmarshalLocation(expr.Location, loc); err != nil { return err @@ -3196,7 +3196,7 @@ func unmarshalExpr(expr *Expr, v map[string]interface{}) error { return nil } -func unmarshalLocation(loc *Location, v map[string]interface{}) error { +func unmarshalLocation(loc *Location, v map[string]any) error { if x, ok := v["file"]; ok { if s, ok := x.(string); ok { loc.File = s @@ -3230,7 +3230,7 @@ func unmarshalLocation(loc *Location, v map[string]interface{}) error { return nil } -func unmarshalExprIndex(expr *Expr, v map[string]interface{}) error { +func unmarshalExprIndex(expr *Expr, v map[string]any) error { if x, ok := v["index"]; ok { if n, ok := x.(json.Number); ok { i, err := n.Int64() @@ -3243,7 +3243,7 @@ func unmarshalExprIndex(expr *Expr, v map[string]interface{}) error { return fmt.Errorf("ast: unable to unmarshal index field with type: %T (expected integer)", v["index"]) } -func unmarshalTerm(m map[string]interface{}) (*Term, error) { +func unmarshalTerm(m map[string]any) (*Term, error) { var term Term v, err := unmarshalValue(m) @@ -3252,7 +3252,7 @@ func unmarshalTerm(m map[string]interface{}) (*Term, error) { } term.Value = v - if loc, ok := m["location"].(map[string]interface{}); ok { + if loc, ok := m["location"].(map[string]any); ok { term.Location = &Location{} if err := unmarshalLocation(term.Location, loc); err != nil { return nil, err @@ -3262,10 +3262,10 @@ func unmarshalTerm(m map[string]interface{}) (*Term, error) { return &term, nil } -func unmarshalTermSlice(s []interface{}) ([]*Term, error) { +func unmarshalTermSlice(s []any) ([]*Term, error) { buf := []*Term{} for _, x := range s { - if m, ok := x.(map[string]interface{}); ok { + if m, ok := x.(map[string]any); ok { t, err := unmarshalTerm(m) if err == nil { buf = append(buf, t) @@ -3278,19 +3278,19 @@ func unmarshalTermSlice(s []interface{}) ([]*Term, error) { return buf, nil } -func unmarshalTermSliceValue(d map[string]interface{}) ([]*Term, error) { - if s, ok := d["value"].([]interface{}); ok { +func unmarshalTermSliceValue(d map[string]any) ([]*Term, error) { + if s, ok := d["value"].([]any); ok { return unmarshalTermSlice(s) } return nil, errors.New(`ast: unable to unmarshal term (expected {"value": [...], "type": ...} where type is one of: ref, array, or set)`) } -func unmarshalWith(i interface{}) (*With, error) { - if m, ok := i.(map[string]interface{}); ok { - tgt, _ := m["target"].(map[string]interface{}) +func unmarshalWith(i any) (*With, error) { + if m, ok := i.(map[string]any); ok { + tgt, _ := m["target"].(map[string]any) target, err := unmarshalTerm(tgt) if err == nil { - val, _ := m["value"].(map[string]interface{}) + val, _ := m["value"].(map[string]any) value, err := unmarshalTerm(val) if err == nil { return &With{ @@ -3305,7 +3305,7 @@ func unmarshalWith(i interface{}) (*With, error) { return nil, errors.New(`ast: unable to unmarshal with modifier (expected {"target": {...}, "value": {...}})`) } -func unmarshalValue(d map[string]interface{}) (Value, error) { +func unmarshalValue(d map[string]any) (Value, error) { v := d["value"] switch d["type"] { case "null": @@ -3339,10 +3339,10 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { return NewSet(s...), nil } case "object": - if s, ok := v.([]interface{}); ok { + if s, ok := v.([]any); ok { buf := NewObject() for _, x := range s { - if i, ok := x.([]interface{}); ok && len(i) == 2 { + if i, ok := x.([]any); ok && len(i) == 2 { p, err := unmarshalTermSlice(i) if err == nil { buf.Insert(p[0], p[1]) @@ -3354,8 +3354,8 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { return buf, nil } case "arraycomprehension", "setcomprehension": - if m, ok := v.(map[string]interface{}); ok { - t, ok := m["term"].(map[string]interface{}) + if m, ok := v.(map[string]any); ok { + t, ok := m["term"].(map[string]any) if !ok { goto unmarshal_error } @@ -3365,7 +3365,7 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { goto unmarshal_error } - b, ok := m["body"].([]interface{}) + b, ok := m["body"].([]any) if !ok { goto unmarshal_error } @@ -3381,8 +3381,8 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { return &SetComprehension{Term: term, Body: body}, nil } case "objectcomprehension": - if m, ok := v.(map[string]interface{}); ok { - k, ok := m["key"].(map[string]interface{}) + if m, ok := v.(map[string]any); ok { + k, ok := m["key"].(map[string]any) if !ok { goto unmarshal_error } @@ -3392,7 +3392,7 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { goto unmarshal_error } - v, ok := m["value"].(map[string]interface{}) + v, ok := m["value"].(map[string]any) if !ok { goto unmarshal_error } @@ -3402,7 +3402,7 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { goto unmarshal_error } - b, ok := m["body"].([]interface{}) + b, ok := m["body"].([]any) if !ok { goto unmarshal_error } diff --git a/v1/ast/term_bench_test.go b/v1/ast/term_bench_test.go index 48c80db49a..2e6caaf19c 100644 --- a/v1/ast/term_bench_test.go +++ b/v1/ast/term_bench_test.go @@ -85,7 +85,7 @@ func BenchmarkLazyObjectLookup(b *testing.B) { sizes := []int{5, 50, 500, 5000} for _, n := range sizes { b.Run(strconv.Itoa(n), func(b *testing.B) { - data := make(map[string]interface{}, n) + data := make(map[string]any, n) for i := range n { data[strconv.Itoa(i)] = i } @@ -107,7 +107,7 @@ func BenchmarkLazyObjectFind(b *testing.B) { for _, n := range sizes { for _, m := range sizes { b.Run(fmt.Sprintf("%d_%d", n, m), func(b *testing.B) { - data := make(map[string]interface{}, n) + data := make(map[string]any, n) for i := range n { arr := make([]string, 0, m) for j := range m { @@ -245,7 +245,7 @@ var ( // The difference between these two is relevant for feeding input into the // wasm vm: when calling rego.New(...) with rego.Target("wasm"), it's up to // the caller to provide the input in parsed form (ast.Value), or -// raw (interface{}). +// raw (any). func BenchmarkObjectString(b *testing.B) { var err error sizes := []int{5, 50, 500, 5000} diff --git a/v1/ast/term_test.go b/v1/ast/term_test.go index e9abd271be..c425f1aa04 100644 --- a/v1/ast/term_test.go +++ b/v1/ast/term_test.go @@ -35,7 +35,7 @@ func TestInterfaceToValue(t *testing.T) { ] } ` - var x interface{} + var x any if err := util.UnmarshalJSON([]byte(input), &x); err != nil { t.Fatal(err) } @@ -67,7 +67,7 @@ func TestInterfaceToValue(t *testing.T) { // Test misc. types tests := []struct { - input interface{} + input any expected string }{ {int64(100), "100"}, @@ -326,7 +326,7 @@ func TestFind(t *testing.T) { tests := []struct { path *Term - expected interface{} + expected any }{ {RefTerm(StringTerm("foo"), IntNumberTerm(1), StringTerm("bar")), MustParseTerm(`{2, 3, 4}`)}, {RefTerm(StringTerm("foo"), IntNumberTerm(1), StringTerm("bar"), IntNumberTerm(4)), MustParseTerm(`4`)}, @@ -941,7 +941,7 @@ func TestSetOperations(t *testing.T) { func TestSetCopy(t *testing.T) { orig := MustParseTerm("{1,2,3}") cpy := orig.Copy() - vis := NewGenericVisitor(func(x interface{}) bool { + vis := NewGenericVisitor(func(x any) bool { if Compare(IntNumberTerm(2), x) == 0 { // NOTE(sr): If we mess up the rank, our sort-on-insert approach fails us x.(*Term).Value = Number("2.5") @@ -1182,7 +1182,7 @@ func TestValueToInterface(t *testing.T) { t.Fatalf("Unexpected error while converting term %v to JSON: %v", term, err) } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(`{"foo": [1, "two", true, null, [3]]}`), &expected); err != nil { panic(err) } @@ -1244,11 +1244,11 @@ func TestValueToInterface(t *testing.T) { } // NOTE(sr): Without the opt-out, we don't allocate another object for -// the conversion back to interface{} if it can be avoided. As a result, +// the conversion back to any if it can be avoided. As a result, // the value held by the store could be changed. func TestJSONWithOptLazyObjDefault(t *testing.T) { // would live in the store - m := map[string]interface{}{ + m := map[string]any{ "foo": "bar", } o := LazyObject(m) @@ -1257,7 +1257,7 @@ func TestJSONWithOptLazyObjDefault(t *testing.T) { if err != nil { t.Fatal(err) } - n0, ok := n.(map[string]interface{}) + n0, ok := n.(map[string]any) if !ok { t.Fatalf("expected %T, got %T: %[2]v", n0, n) } @@ -1270,7 +1270,7 @@ func TestJSONWithOptLazyObjDefault(t *testing.T) { func TestJSONWithOptLazyObjOptOut(t *testing.T) { // would live in the store - m := map[string]interface{}{ + m := map[string]any{ "foo": "bar", } o := LazyObject(m) @@ -1279,7 +1279,7 @@ func TestJSONWithOptLazyObjOptOut(t *testing.T) { if err != nil { t.Fatal(err) } - n0, ok := n.(map[string]interface{}) + n0, ok := n.(map[string]any) if !ok { t.Fatalf("expected %T, got %T: %[2]v", n0, n) } @@ -1313,9 +1313,9 @@ func assertToString(t *testing.T, val Value, expected string) { } func TestLazyObjectGet(t *testing.T) { - x := LazyObject(map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + x := LazyObject(map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": true, }, }, @@ -1329,10 +1329,10 @@ func TestLazyObjectGet(t *testing.T) { } func TestLazyObjectGetCache(t *testing.T) { - x := LazyObject(map[string]interface{}{ + x := LazyObject(map[string]any{ "a": true, "b": false, - "d": map[string]interface{}{ + "d": map[string]any{ "e": "f", "f": "g", }, @@ -1370,12 +1370,12 @@ func TestLazyObjectGetCache(t *testing.T) { } func TestLazyObjectFind(t *testing.T) { - x := LazyObject(map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + x := LazyObject(map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": true, }, - "d": []interface{}{true, true, true}, + "d": []any{true, true, true}, }, }) // retrieve object via Find @@ -1401,14 +1401,14 @@ func TestLazyObjectFind(t *testing.T) { } func TestLazyObjectFindCache(t *testing.T) { - x := LazyObject(map[string]interface{}{ + x := LazyObject(map[string]any{ "a": []string{ "b", "c", "d", }, "c": []string{ "d", "e", "f", }, - "d": map[string]interface{}{ + "d": map[string]any{ "e": "f", "f": "g", }, @@ -1459,9 +1459,9 @@ func TestLazyObjectFindCache(t *testing.T) { } func TestLazyObjectCopy(t *testing.T) { - x := LazyObject(map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + x := LazyObject(map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": true, }, }, @@ -1475,9 +1475,9 @@ func TestLazyObjectCopy(t *testing.T) { } func TestLazyObjectLen(t *testing.T) { - x := LazyObject(map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + x := LazyObject(map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": true, }, }, @@ -1489,9 +1489,9 @@ func TestLazyObjectLen(t *testing.T) { } func TestLazyObjectIsGround(t *testing.T) { - x := LazyObject(map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + x := LazyObject(map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": true, }, }, @@ -1503,7 +1503,7 @@ func TestLazyObjectIsGround(t *testing.T) { } func TestLazyObjectInsert(t *testing.T) { - x := LazyObject(map[string]interface{}{ + x := LazyObject(map[string]any{ "a": "b", }) x.Insert(StringTerm("c"), StringTerm("d")) @@ -1517,7 +1517,7 @@ func TestLazyObjectInsert(t *testing.T) { } func TestLazyObjectKeys(t *testing.T) { - x := LazyObject(map[string]interface{}{ + x := LazyObject(map[string]any{ "a": "A", "c": "C", "b": "B", @@ -1531,7 +1531,7 @@ func TestLazyObjectKeys(t *testing.T) { } func TestLazyObjectKeysIterator(t *testing.T) { - x := LazyObject(map[string]interface{}{ + x := LazyObject(map[string]any{ "a": "A", "c": "C", "b": "B", @@ -1549,9 +1549,9 @@ func TestLazyObjectKeysIterator(t *testing.T) { } func TestLazyObjectCompare(t *testing.T) { - x := LazyObject(map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + x := LazyObject(map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": true, }, }, diff --git a/v1/ast/transform.go b/v1/ast/transform.go index e8c9ddcab1..197ab6457d 100644 --- a/v1/ast/transform.go +++ b/v1/ast/transform.go @@ -13,12 +13,12 @@ import ( // be set to nil and no transformations will be applied to children of the // element. type Transformer interface { - Transform(interface{}) (interface{}, error) + Transform(any) (any, error) } // Transform iterates the AST and calls the Transform function on the // Transformer t for x before recursing. -func Transform(t Transformer, x interface{}) (interface{}, error) { +func Transform(t Transformer, x any) (any, error) { if term, ok := x.(*Term); ok { return Transform(t, term.Value) @@ -290,8 +290,8 @@ func Transform(t Transformer, x interface{}) (interface{}, error) { } // TransformRefs calls the function f on all references under x. -func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, error) { - t := &GenericTransformer{func(x interface{}) (interface{}, error) { +func TransformRefs(x any, f func(Ref) (Value, error)) (any, error) { + t := &GenericTransformer{func(x any) (any, error) { if r, ok := x.(Ref); ok { return f(r) } @@ -301,8 +301,8 @@ func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, erro } // TransformVars calls the function f on all vars under x. -func TransformVars(x interface{}, f func(Var) (Value, error)) (interface{}, error) { - t := &GenericTransformer{func(x interface{}) (interface{}, error) { +func TransformVars(x any, f func(Var) (Value, error)) (any, error) { + t := &GenericTransformer{func(x any) (any, error) { if v, ok := x.(Var); ok { return f(v) } @@ -312,8 +312,8 @@ func TransformVars(x interface{}, f func(Var) (Value, error)) (interface{}, erro } // TransformComprehensions calls the functio nf on all comprehensions under x. -func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) (interface{}, error) { - t := &GenericTransformer{func(x interface{}) (interface{}, error) { +func TransformComprehensions(x any, f func(any) (Value, error)) (any, error) { + t := &GenericTransformer{func(x any) (any, error) { switch x := x.(type) { case *ArrayComprehension: return f(x) @@ -330,19 +330,19 @@ func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) // GenericTransformer implements the Transformer interface to provide a utility // to transform AST nodes using a closure. type GenericTransformer struct { - f func(interface{}) (interface{}, error) + f func(any) (any, error) } // NewGenericTransformer returns a new GenericTransformer that will transform // AST nodes using the function f. -func NewGenericTransformer(f func(x interface{}) (interface{}, error)) *GenericTransformer { +func NewGenericTransformer(f func(x any) (any, error)) *GenericTransformer { return &GenericTransformer{ f: f, } } // Transform calls the function f on the GenericTransformer. -func (t *GenericTransformer) Transform(x interface{}) (interface{}, error) { +func (t *GenericTransformer) Transform(x any) (any, error) { return t.f(x) } diff --git a/v1/ast/transform_test.go b/v1/ast/transform_test.go index 189badbd32..9642b3eefc 100644 --- a/v1/ast/transform_test.go +++ b/v1/ast/transform_test.go @@ -28,7 +28,7 @@ a.b.c.this["this"] = d if { d := "this" } `) result, err := Transform(&GenericTransformer{ - func(x interface{}) (interface{}, error) { + func(x any) (any, error) { if s, ok := x.(String); ok && s == String("this") { return String("that"), nil } @@ -81,7 +81,7 @@ p := 7`, ParserOptions{ProcessAnnotation: true}) } result, err := Transform(&GenericTransformer{ - func(x interface{}) (interface{}, error) { + func(x any) (any, error) { if s, ok := x.(*Annotations); ok { cpy := *s cpy.Scope = "deadbeef" diff --git a/v1/ast/visit.go b/v1/ast/visit.go index 0115c4f455..16567014f4 100644 --- a/v1/ast/visit.go +++ b/v1/ast/visit.go @@ -10,7 +10,7 @@ package ast // visited. // Deprecated: use GenericVisitor or another visitor implementation type Visitor interface { - Visit(v interface{}) (w Visitor) + Visit(v any) (w Visitor) } // BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before @@ -18,14 +18,14 @@ type Visitor interface { // Deprecated: use GenericVisitor or another visitor implementation type BeforeAndAfterVisitor interface { Visitor - Before(x interface{}) - After(x interface{}) + Before(x any) + After(x any) } // Walk iterates the AST by calling the Visit function on the Visitor // v for x before recursing. // Deprecated: use GenericVisitor.Walk -func Walk(v Visitor, x interface{}) { +func Walk(v Visitor, x any) { if bav, ok := v.(BeforeAndAfterVisitor); !ok { walk(v, x) } else { @@ -38,11 +38,11 @@ func Walk(v Visitor, x interface{}) { // WalkBeforeAndAfter iterates the AST by calling the Visit function on the // Visitor v for x before recursing. // Deprecated: use GenericVisitor.Walk -func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x interface{}) { +func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any) { Walk(v, x) } -func walk(v Visitor, x interface{}) { +func walk(v Visitor, x any) { w := v.Visit(x) if w == nil { return @@ -154,8 +154,8 @@ func walk(v Visitor, x interface{}) { // WalkVars calls the function f on all vars under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkVars(x interface{}, f func(Var) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkVars(x any, f func(Var) bool) { + vis := &GenericVisitor{func(x any) bool { if v, ok := x.(Var); ok { return f(v) } @@ -166,8 +166,8 @@ func WalkVars(x interface{}, f func(Var) bool) { // WalkClosures calls the function f on all closures under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkClosures(x interface{}, f func(interface{}) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkClosures(x any, f func(any) bool) { + vis := &GenericVisitor{func(x any) bool { switch x := x.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension, *Every: return f(x) @@ -179,8 +179,8 @@ func WalkClosures(x interface{}, f func(interface{}) bool) { // WalkRefs calls the function f on all references under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkRefs(x interface{}, f func(Ref) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkRefs(x any, f func(Ref) bool) { + vis := &GenericVisitor{func(x any) bool { if r, ok := x.(Ref); ok { return f(r) } @@ -191,8 +191,8 @@ func WalkRefs(x interface{}, f func(Ref) bool) { // WalkTerms calls the function f on all terms under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkTerms(x interface{}, f func(*Term) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkTerms(x any, f func(*Term) bool) { + vis := &GenericVisitor{func(x any) bool { if term, ok := x.(*Term); ok { return f(term) } @@ -203,8 +203,8 @@ func WalkTerms(x interface{}, f func(*Term) bool) { // WalkWiths calls the function f on all with modifiers under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkWiths(x interface{}, f func(*With) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkWiths(x any, f func(*With) bool) { + vis := &GenericVisitor{func(x any) bool { if w, ok := x.(*With); ok { return f(w) } @@ -215,8 +215,8 @@ func WalkWiths(x interface{}, f func(*With) bool) { // WalkExprs calls the function f on all expressions under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkExprs(x interface{}, f func(*Expr) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkExprs(x any, f func(*Expr) bool) { + vis := &GenericVisitor{func(x any) bool { if r, ok := x.(*Expr); ok { return f(r) } @@ -227,8 +227,8 @@ func WalkExprs(x interface{}, f func(*Expr) bool) { // WalkBodies calls the function f on all bodies under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkBodies(x interface{}, f func(Body) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkBodies(x any, f func(Body) bool) { + vis := &GenericVisitor{func(x any) bool { if b, ok := x.(Body); ok { return f(b) } @@ -239,8 +239,8 @@ func WalkBodies(x interface{}, f func(Body) bool) { // WalkRules calls the function f on all rules under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkRules(x interface{}, f func(*Rule) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkRules(x any, f func(*Rule) bool) { + vis := &GenericVisitor{func(x any) bool { if r, ok := x.(*Rule); ok { stop := f(r) // NOTE(tsandall): since rules cannot be embedded inside of queries @@ -256,8 +256,8 @@ func WalkRules(x interface{}, f func(*Rule) bool) { // WalkNodes calls the function f on all nodes under x. If the function f // returns true, AST nodes under the last node will not be visited. -func WalkNodes(x interface{}, f func(Node) bool) { - vis := &GenericVisitor{func(x interface{}) bool { +func WalkNodes(x any, f func(Node) bool) { + vis := &GenericVisitor{func(x any) bool { if n, ok := x.(Node); ok { return f(n) } @@ -270,19 +270,19 @@ func WalkNodes(x interface{}, f func(Node) bool) { // closure. If the closure returns true, the visitor will not walk // over AST nodes under x. type GenericVisitor struct { - f func(x interface{}) bool + f func(x any) bool } // NewGenericVisitor returns a new GenericVisitor that will invoke the function // f on AST nodes. -func NewGenericVisitor(f func(x interface{}) bool) *GenericVisitor { +func NewGenericVisitor(f func(x any) bool) *GenericVisitor { return &GenericVisitor{f} } // Walk iterates the AST by calling the function f on the // GenericVisitor before recursing. Contrary to the generic Walk, this // does not require allocating the visitor from heap. -func (vis *GenericVisitor) Walk(x interface{}) { +func (vis *GenericVisitor) Walk(x any) { if vis.f(x) { return } @@ -403,13 +403,13 @@ func (vis *GenericVisitor) Walk(x interface{}) { // walk over AST nodes under x. The after closure is invoked always // after visiting a node. type BeforeAfterVisitor struct { - before func(x interface{}) bool - after func(x interface{}) + before func(x any) bool + after func(x any) } // NewBeforeAfterVisitor returns a new BeforeAndAfterVisitor that // will invoke the functions before and after AST nodes. -func NewBeforeAfterVisitor(before func(x interface{}) bool, after func(x interface{})) *BeforeAfterVisitor { +func NewBeforeAfterVisitor(before func(x any) bool, after func(x any)) *BeforeAfterVisitor { return &BeforeAfterVisitor{before, after} } @@ -417,7 +417,7 @@ func NewBeforeAfterVisitor(before func(x interface{}) bool, after func(x interfa // BeforeAndAfterVisitor before and after recursing. Contrary to the // generic Walk, this does not require allocating the visitor from // heap. -func (vis *BeforeAfterVisitor) Walk(x interface{}) { +func (vis *BeforeAfterVisitor) Walk(x any) { defer vis.after(x) if vis.before(x) { return @@ -576,7 +576,7 @@ func (vis *VarVisitor) Vars() VarSet { // visit determines if the VarVisitor will recurse into x: if it returns `true`, // the visitor will _skip_ that branch of the AST -func (vis *VarVisitor) visit(v interface{}) bool { +func (vis *VarVisitor) visit(v any) bool { if vis.params.SkipObjectKeys { if o, ok := v.(Object); ok { o.Foreach(func(_, v *Term) { @@ -669,7 +669,7 @@ func (vis *VarVisitor) visit(v interface{}) bool { // Walk iterates the AST by calling the function f on the // GenericVisitor before recursing. Contrary to the generic Walk, this // does not require allocating the visitor from heap. -func (vis *VarVisitor) Walk(x interface{}) { +func (vis *VarVisitor) Walk(x any) { if vis.visit(x) { return } diff --git a/v1/ast/visit_test.go b/v1/ast/visit_test.go index f8ae5b0768..790fc706aa 100644 --- a/v1/ast/visit_test.go +++ b/v1/ast/visit_test.go @@ -9,10 +9,10 @@ import ( ) type testVis struct { - elems []interface{} + elems []any } -func (vis *testVis) Visit(x interface{}) bool { +func (vis *testVis) Visit(x any) bool { vis.elems = append(vis.elems, x) return false } @@ -100,8 +100,8 @@ p if { false } else if { false } else if { true } fn([x, y]) = z if { json.unmarshal(x, z); z > y } `) - var elems []interface{} - vis := NewGenericVisitor(func(x interface{}) bool { + var elems []any + vis := NewGenericVisitor(func(x any) bool { elems = append(elems, x) return false }) @@ -132,12 +132,12 @@ p if { false } else if { false } else if { true } fn([x, y]) = z if { json.unmarshal(x, z); z > y } `) - var before, after []interface{} - vis := NewBeforeAfterVisitor(func(x interface{}) bool { + var before, after []any + vis := NewBeforeAfterVisitor(func(x any) bool { before = append(before, x) return false }, - func(x interface{}) { + func(x any) { after = append(after, x) }) vis.Walk(rule) @@ -186,7 +186,7 @@ func TestVarVisitor(t *testing.T) { } func TestGenericVisitorLazyObject(t *testing.T) { - o := LazyObject(map[string]interface{}{"foo": 3}) + o := LazyObject(map[string]any{"foo": 3}) act := 0 WalkTerms(o, func(n *Term) bool { switch n.Value { @@ -204,9 +204,9 @@ func TestGenericVisitorLazyObject(t *testing.T) { } func TestGenericBeforeAfterVisitorLazyObject(t *testing.T) { - o := LazyObject(map[string]interface{}{"foo": 3}) + o := LazyObject(map[string]any{"foo": 3}) act := 0 - vis := NewBeforeAfterVisitor(func(x interface{}) bool { + vis := NewBeforeAfterVisitor(func(x any) bool { t, ok := x.(*Term) if !ok { return false @@ -220,7 +220,7 @@ func TestGenericBeforeAfterVisitorLazyObject(t *testing.T) { return false }, - func(interface{}) {}) + func(any) {}) vis.Walk(o) if exp := 2; exp != act { t.Errorf("expected %v, got %v", exp, act) diff --git a/v1/bundle/bundle.go b/v1/bundle/bundle.go index d6bf846fc4..8efb06a67c 100644 --- a/v1/bundle/bundle.go +++ b/v1/bundle/bundle.go @@ -52,7 +52,7 @@ const ( type Bundle struct { Signatures SignaturesConfig Manifest Manifest - Data map[string]interface{} + Data map[string]any Modules []ModuleFile Wasm []byte // Deprecated. Use WasmModules instead WasmModules []WasmModuleFile @@ -80,9 +80,9 @@ type Patch struct { // PatchOperation models a single patch operation against a document. type PatchOperation struct { - Op string `json:"op"` - Path string `json:"path"` - Value interface{} `json:"value"` + Op string `json:"op"` + Path string `json:"path"` + Value any `json:"value"` } // SignaturesConfig represents an array of JWTs that encapsulate the signatures for the bundle. @@ -137,8 +137,8 @@ type Manifest struct { RegoVersion *int `json:"rego_version,omitempty"` // FileRegoVersions is a map from file paths to Rego versions. // This allows individual files to override the global Rego version specified by RegoVersion. - FileRegoVersions map[string]int `json:"file_rego_versions,omitempty"` - Metadata map[string]interface{} `json:"metadata,omitempty"` + FileRegoVersions map[string]int `json:"file_rego_versions,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` compiledFileRegoVersions []fileRegoVersion } @@ -233,7 +233,7 @@ func (m Manifest) Copy() Manifest { metadata := m.Metadata if metadata != nil { - m.Metadata = make(map[string]interface{}) + m.Metadata = make(map[string]any) for k, v := range metadata { m.Metadata[k] = v } @@ -391,13 +391,13 @@ func (m *Manifest) validateAndInjectDefaults(b Bundle) error { } // Validate data in bundle. - return dfs(b.Data, "", func(path string, node interface{}) (bool, error) { + return dfs(b.Data, "", func(path string, node any) (bool, error) { path = strings.Trim(path, "/") if RootPathsContain(roots, path) { return true, nil } - if _, ok := node.(map[string]interface{}); ok { + if _, ok := node.(map[string]any); ok { for i := range roots { if RootPathsContain(strings.Split(path, "/"), roots[i]) { return false, nil @@ -599,7 +599,7 @@ func (r *Reader) Read() (Bundle, error) { return bundle, err } - bundle.Data = map[string]interface{}{} + bundle.Data = map[string]any{} } var modules []ModuleFile @@ -669,7 +669,7 @@ func (r *Reader) Read() (Bundle, error) { continue } - var value interface{} + var value any r.metrics.Timer(metrics.RegoDataParse).Start() err := util.UnmarshalJSON(buf.Bytes(), &value) @@ -689,7 +689,7 @@ func (r *Reader) Read() (Bundle, error) { continue } - var value interface{} + var value any r.metrics.Timer(metrics.RegoDataParse).Start() err := util.Unmarshal(buf.Bytes(), &value) @@ -778,7 +778,7 @@ func (r *Reader) Read() (Bundle, error) { } if r.includeManifestInData { - var metadata map[string]interface{} + var metadata map[string]any b, err := json.Marshal(&bundle.Manifest) if err != nil { @@ -1069,7 +1069,7 @@ func hashBundleFiles(hash SignatureHasher, b *Bundle) ([]FileInfo, error) { return files, err } - var result map[string]interface{} + var result map[string]any if err := util.Unmarshal(mbs, &result); err != nil { return files, err } @@ -1299,14 +1299,14 @@ func (b Bundle) Equal(other Bundle) bool { func (b Bundle) Copy() Bundle { // Copy data. - var x interface{} = b.Data + var x any = b.Data if err := util.RoundTrip(&x); err != nil { panic(err) } if x != nil { - b.Data = x.(map[string]interface{}) + b.Data = x.(map[string]any) } // Copy modules. @@ -1323,7 +1323,7 @@ func (b Bundle) Copy() Bundle { return b } -func (b *Bundle) insertData(key []string, value interface{}) error { +func (b *Bundle) insertData(key []string, value any) error { // Build an object with the full structure for the value obj, err := mktree(key, value) if err != nil { @@ -1341,13 +1341,13 @@ func (b *Bundle) insertData(key []string, value interface{}) error { return nil } -func (b *Bundle) readData(key []string) *interface{} { +func (b *Bundle) readData(key []string) *any { if len(key) == 0 { if len(b.Data) == 0 { return nil } - var result interface{} = b.Data + var result any = b.Data return &result } @@ -1360,7 +1360,7 @@ func (b *Bundle) readData(key []string) *interface{} { return nil } - childObj, ok := child.(map[string]interface{}) + childObj, ok := child.(map[string]any) if !ok { return nil } @@ -1384,21 +1384,21 @@ func (b *Bundle) Type() string { return SnapshotBundleType } -func mktree(path []string, value interface{}) (map[string]interface{}, error) { +func mktree(path []string, value any) (map[string]any, error) { if len(path) == 0 { // For 0 length path the value is the full tree. - obj, ok := value.(map[string]interface{}) + obj, ok := value.(map[string]any) if !ok { return nil, errors.New("root value must be object") } return obj, nil } - dir := map[string]interface{}{} + dir := map[string]any{} for i := len(path) - 1; i > 0; i-- { dir[path[i]] = value value = dir - dir = map[string]interface{}{} + dir = map[string]any{} } dir[path[0]] = value @@ -1488,7 +1488,7 @@ func MergeWithRegoVersion(bundles []*Bundle, regoVersion ast.RegoVersion, usePat result.SetRegoVersion(result.RegoVersion(regoVersion)) if result.Data == nil { - result.Data = map[string]interface{}{} + result.Data = map[string]any{} } result.Manifest.Roots = &roots @@ -1598,7 +1598,7 @@ func rootContains(root []string, other []string) bool { return true } -func insertValue(b *Bundle, path string, value interface{}) error { +func insertValue(b *Bundle, path string, value any) error { if err := b.insertData(getNormalizedPath(path), value); err != nil { return fmt.Errorf("bundle load failed on %v: %w", path, err) } @@ -1619,13 +1619,13 @@ func getNormalizedPath(path string) []string { return key } -func dfs(value interface{}, path string, fn func(string, interface{}) (bool, error)) error { +func dfs(value any, path string, fn func(string, any) (bool, error)) error { if stop, err := fn(path, value); err != nil { return err } else if stop { return nil } - obj, ok := value.(map[string]interface{}) + obj, ok := value.(map[string]any) if !ok { return nil } diff --git a/v1/bundle/bundle_test.go b/v1/bundle/bundle_test.go index 74e7416c6b..7b9fb5ca2e 100644 --- a/v1/bundle/bundle_test.go +++ b/v1/bundle/bundle_test.go @@ -71,12 +71,12 @@ func TestManifestEqual(t *testing.T) { m.WasmResolvers[0].Module = "yyy" assertEqual() - n.Metadata = map[string]interface{}{ + n.Metadata = map[string]any{ "foo": "bar", } assertNotEqual() - m.Metadata = map[string]interface{}{ + m.Metadata = map[string]any{ "foo": "bar", } assertEqual() @@ -380,19 +380,19 @@ func testReadBundle(t *testing.T, baseDir string, useMemoryFS bool) { exp := Bundle{ Manifest: expManifest, - Data: map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ - "c": []interface{}{json.Number("1"), json.Number("2"), json.Number("3")}, + Data: map[string]any{ + "a": map[string]any{ + "b": map[string]any{ + "c": []any{json.Number("1"), json.Number("2"), json.Number("3")}, "d": true, "g": json.Number("1"), - "y": map[string]interface{}{ + "y": map[string]any{ "foo": json.Number("1"), }, "z": true, }, }, - "x": map[string]interface{}{ + "x": map[string]any{ "y": true, }, }, @@ -456,7 +456,7 @@ func TestManifestMetadata(t *testing.T) { if bundle.Manifest.Metadata["foo"] == nil { t.Fatal("Unexpected nil metadata key") } - data, ok := bundle.Manifest.Metadata["foo"].(map[string]interface{}) + data, ok := bundle.Manifest.Metadata["foo"].(map[string]any) if !ok { t.Fatal("Unexpected structure in metadata") } @@ -475,9 +475,9 @@ func TestReadWithManifestInData(t *testing.T) { t.Fatal(err) } - system := bundle.Data["system"].(map[string]interface{}) - b := system["bundle"].(map[string]interface{}) - m := b["manifest"].(map[string]interface{}) + system := bundle.Data["system"].(map[string]any) + b := system["bundle"].(map[string]any) + m := b["manifest"].(map[string]any) if m["revision"] != "quickbrownfaux" { t.Fatalf("Unexpected manifest.revision value: %v. Expected: %v", m["revision"], "quickbrownfaux") @@ -1141,9 +1141,9 @@ func TestReadErrorBadContents(t *testing.T) { func TestRoundtripDeprecatedWrite(t *testing.T) { bundle := Bundle{ - Data: map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": []interface{}{json.Number("1"), json.Number("2"), json.Number("3")}, + Data: map[string]any{ + "foo": map[string]any{ + "bar": []any{json.Number("1"), json.Number("2"), json.Number("3")}, "baz": true, "qux": "hello", }, @@ -1188,9 +1188,9 @@ func TestRoundtripDeprecatedWrite(t *testing.T) { func TestRoundtrip(t *testing.T) { bundle := Bundle{ - Data: map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": []interface{}{json.Number("1"), json.Number("2"), json.Number("3")}, + Data: map[string]any{ + "foo": map[string]any{ + "bar": []any{json.Number("1"), json.Number("2"), json.Number("3")}, "baz": true, "qux": "hello", }, @@ -1213,7 +1213,7 @@ func TestRoundtrip(t *testing.T) { Manifest: Manifest{ Roots: &[]string{""}, Revision: "quickbrownfaux", - Metadata: map[string]interface{}{"version": "v1", "hello": "world"}, + Metadata: map[string]any{"version": "v1", "hello": "world"}, }, } @@ -1246,7 +1246,7 @@ func TestRoundtrip(t *testing.T) { func TestRoundtripWithPlanModules(t *testing.T) { b := Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, PlanModules: []PlanModuleFile{ { URL: "/plan.json", @@ -1317,7 +1317,7 @@ func TestRoundtripDeltaBundle(t *testing.T) { func TestWriterUsePath(t *testing.T) { bundle := Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []ModuleFile{ { URL: "/url.rego", @@ -1348,7 +1348,7 @@ func TestWriterUsePath(t *testing.T) { func TestWriterSkipEmptyManifest(t *testing.T) { bundle := Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, Manifest: Manifest{}, } @@ -1383,9 +1383,9 @@ func TestGenerateSignature(t *testing.T) { signatures := SignaturesConfig{Signatures: []string{"some_token"}} bundle := Bundle{ - Data: map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": []interface{}{json.Number("1"), json.Number("2"), json.Number("3")}, + Data: map[string]any{ + "foo": map[string]any{ + "bar": []any{json.Number("1"), json.Number("2"), json.Number("3")}, "baz": true, "qux": "hello", }, @@ -1431,9 +1431,9 @@ func TestGenerateSignatureWithPlugin(t *testing.T) { signatures := SignaturesConfig{Signatures: []string{"some_token"}, Plugin: "_foo"} bundle := Bundle{ - Data: map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": []interface{}{json.Number("1"), json.Number("2"), json.Number("3")}, + Data: map[string]any{ + "foo": map[string]any{ + "bar": []any{json.Number("1"), json.Number("2"), json.Number("3")}, "baz": true, "qux": "hello", }, @@ -1571,17 +1571,17 @@ func TestHashBundleFiles(t *testing.T) { h, _ := NewSignatureHasher(SHA256) tests := map[string]struct { - data map[string]interface{} + data map[string]any manifest Manifest wasm []byte plan []byte exp int }{ - "no_content": {map[string]interface{}{}, Manifest{}, nil, nil, 1}, - "data": {map[string]interface{}{"foo": "bar"}, Manifest{}, nil, nil, 1}, - "data_and_manifest": {map[string]interface{}{"foo": "bar"}, Manifest{Revision: "quickbrownfaux"}, []byte{}, nil, 2}, - "data_and_manifest_and_wasm": {map[string]interface{}{"foo": "bar"}, Manifest{Revision: "quickbrownfaux"}, []byte("modules-compiled-as-wasm-binary"), nil, 3}, - "data_and_plan": {map[string]interface{}{"foo": "bar"}, Manifest{Revision: "quickbrownfaux"}, nil, []byte("not a plan but good enough"), 3}, + "no_content": {map[string]any{}, Manifest{}, nil, nil, 1}, + "data": {map[string]any{"foo": "bar"}, Manifest{}, nil, nil, 1}, + "data_and_manifest": {map[string]any{"foo": "bar"}, Manifest{Revision: "quickbrownfaux"}, []byte{}, nil, 2}, + "data_and_manifest_and_wasm": {map[string]any{"foo": "bar"}, Manifest{Revision: "quickbrownfaux"}, []byte("modules-compiled-as-wasm-binary"), nil, 3}, + "data_and_plan": {map[string]any{"foo": "bar"}, Manifest{Revision: "quickbrownfaux"}, nil, []byte("not a plan but good enough"), 3}, } for name, tc := range tests { @@ -1611,7 +1611,7 @@ func TestHashBundleFiles(t *testing.T) { func TestWriterUseURL(t *testing.T) { bundle := Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []ModuleFile{ { URL: "/url.rego", @@ -1824,7 +1824,7 @@ func TestMerge(t *testing.T) { }, RegoVersion: &expRegoVersion, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, }, }, { @@ -1883,7 +1883,7 @@ func TestMerge(t *testing.T) { Raw: []byte("not really wasm, but good enough"), }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, }, }, { @@ -1938,7 +1938,7 @@ func TestMerge(t *testing.T) { Raw: []byte("package baz"), }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, }, }, { @@ -1950,8 +1950,8 @@ func TestMerge(t *testing.T) { "foo/bar", }, }, - Data: map[string]interface{}{ - "foo": map[string]interface{}{ + Data: map[string]any{ + "foo": map[string]any{ "bar": "val1", }, }, @@ -1962,7 +1962,7 @@ func TestMerge(t *testing.T) { "baz", }, }, - Data: map[string]interface{}{ + Data: map[string]any{ "baz": "val2", }, }, @@ -1975,8 +1975,8 @@ func TestMerge(t *testing.T) { }, RegoVersion: &expRegoVersion, }, - Data: map[string]interface{}{ - "foo": map[string]interface{}{ + Data: map[string]any{ + "foo": map[string]any{ "bar": "val1", }, "baz": "val2", @@ -1992,7 +1992,7 @@ func TestMerge(t *testing.T) { "foo/bar", }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, }, { Manifest: Manifest{ @@ -2000,7 +2000,7 @@ func TestMerge(t *testing.T) { "baz", }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, }, }, wantBundle: &Bundle{ @@ -2011,7 +2011,7 @@ func TestMerge(t *testing.T) { }, RegoVersion: &expRegoVersion, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, }, }, { @@ -2043,7 +2043,7 @@ func TestMerge(t *testing.T) { }, }, wantBundle: &Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, Manifest: Manifest{ Roots: &[]string{"a", "b"}, RegoVersion: &expRegoVersion, diff --git a/v1/bundle/hash.go b/v1/bundle/hash.go index ab6fcd0f38..5a62d2dc00 100644 --- a/v1/bundle/hash.go +++ b/v1/bundle/hash.go @@ -41,7 +41,7 @@ func (alg HashingAlgorithm) String() string { // SignatureHasher computes a signature digest for a file with (structured or unstructured) data and policy type SignatureHasher interface { - HashFile(v interface{}) ([]byte, error) + HashFile(v any) ([]byte, error) } type hasher struct { @@ -77,7 +77,7 @@ func NewSignatureHasher(alg HashingAlgorithm) (SignatureHasher, error) { } // HashFile hashes the file content, JSON or binary, both in golang native format. -func (h *hasher) HashFile(v interface{}) ([]byte, error) { +func (h *hasher) HashFile(v any) ([]byte, error) { hf := h.h() walk(v, hf) return hf.Sum(nil), nil @@ -92,10 +92,10 @@ func (h *hasher) HashFile(v interface{}) ([]byte, error) { // object: Hash {, then each key (in alphabetical order) and digest of the value, then comma (between items) and finally }. // // array: Hash [, then digest of the value, then comma (between items) and finally ]. -func walk(v interface{}, h io.Writer) { +func walk(v any, h io.Writer) { switch x := v.(type) { - case map[string]interface{}: + case map[string]any: _, _ = h.Write([]byte("{")) for i, key := range util.KeysSorted(x) { @@ -109,7 +109,7 @@ func walk(v interface{}, h io.Writer) { } _, _ = h.Write([]byte("}")) - case []interface{}: + case []any: _, _ = h.Write([]byte("[")) for i, e := range x { @@ -127,7 +127,7 @@ func walk(v interface{}, h io.Writer) { } } -func encodePrimitive(v interface{}) []byte { +func encodePrimitive(v any) []byte { var buf bytes.Buffer encoder := json.NewEncoder(&buf) encoder.SetEscapeHTML(false) diff --git a/v1/bundle/hash_test.go b/v1/bundle/hash_test.go index 9b8502f626..948426e85a 100644 --- a/v1/bundle/hash_test.go +++ b/v1/bundle/hash_test.go @@ -12,19 +12,19 @@ import ( func TestHashFile(t *testing.T) { - mapInput := map[string]interface{}{ - "key1": []interface{}{ + mapInput := map[string]any{ + "key1": []any{ "element1", "element2", }, - "key2": map[string]interface{}{ + "key2": map[string]any{ "a": 0, "b": 1, "c": json.Number("123.45678911111111111111111111111111111111111111111111111"), }, } - arrayInput := []interface{}{ + arrayInput := []any{ []string{"foo", "bar"}, mapInput, `package example`, @@ -32,7 +32,7 @@ func TestHashFile(t *testing.T) { } tests := map[string]struct { - input interface{} + input any algorithm HashingAlgorithm }{ "map": {mapInput, SHA256}, @@ -69,19 +69,19 @@ func TestHashFile(t *testing.T) { func TestHashFileBytes(t *testing.T) { - mapInput := map[string]interface{}{ - "key1": []interface{}{ + mapInput := map[string]any{ + "key1": []any{ "element1", "element2", }, - "key2": map[string]interface{}{ + "key2": map[string]any{ "a": 0, "b": 1, "c": json.Number("123.45678911111111111111111111111111111111111111111111111"), }, } - arrayInput := []interface{}{ + arrayInput := []any{ []string{"foo", "bar"}, mapInput, `package example`, diff --git a/v1/bundle/keys.go b/v1/bundle/keys.go index aad30a675a..dbd8ff2697 100644 --- a/v1/bundle/keys.go +++ b/v1/bundle/keys.go @@ -105,7 +105,7 @@ func (s *SigningConfig) WithPlugin(plugin string) *SigningConfig { } // GetPrivateKey returns the private key or secret from the signing config -func (s *SigningConfig) GetPrivateKey() (interface{}, error) { +func (s *SigningConfig) GetPrivateKey() (any, error) { block, _ := pem.Decode([]byte(s.Key)) if block != nil { @@ -129,8 +129,8 @@ func (s *SigningConfig) GetPrivateKey() (interface{}, error) { } // GetClaims returns the claims by reading the file specified in the signing config -func (s *SigningConfig) GetClaims() (map[string]interface{}, error) { - var claims map[string]interface{} +func (s *SigningConfig) GetClaims() (map[string]any, error) { + var claims map[string]any bs, err := os.ReadFile(s.ClaimsPath) if err != nil { diff --git a/v1/bundle/sign.go b/v1/bundle/sign.go index 710e296860..0d6a2fae4a 100644 --- a/v1/bundle/sign.go +++ b/v1/bundle/sign.go @@ -89,7 +89,7 @@ func (*DefaultSigner) GenerateSignedToken(files []FileInfo, sc *SigningConfig, k } func generatePayload(files []FileInfo, sc *SigningConfig, keyID string) ([]byte, error) { - payload := make(map[string]interface{}) + payload := make(map[string]any) payload["files"] = files if sc.ClaimsPath != "" { diff --git a/v1/bundle/sign_test.go b/v1/bundle/sign_test.go index 31fc5b936b..93eede412c 100644 --- a/v1/bundle/sign_test.go +++ b/v1/bundle/sign_test.go @@ -96,7 +96,7 @@ func TestGenerateSignedTokenWithClaims(t *testing.T) { } test.WithTempFS(map[string]string{}, func(rootDir string) { - claims := make(map[string]interface{}) + claims := make(map[string]any) claims["scope"] = "read" claimBytes, err := json.Marshal(claims) @@ -161,7 +161,7 @@ func TestGeneratePayload(t *testing.T) { t.Fatalf("Unexpected error %v", err) } - payload := make(map[string]interface{}) + payload := make(map[string]any) if err := util.UnmarshalJSON(bytes, &payload); err != nil { t.Fatalf("Unexpected error %v", err) } @@ -180,7 +180,7 @@ func TestGeneratePayload(t *testing.T) { t.Fatalf("Unexpected error %v", err) } - payload = make(map[string]interface{}) + payload = make(map[string]any) err = util.UnmarshalJSON(bytes, &payload) if err != nil { t.Fatalf("Unexpected error %v", err) diff --git a/v1/bundle/store.go b/v1/bundle/store.go index 363f7664d7..b1031938c2 100644 --- a/v1/bundle/store.go +++ b/v1/bundle/store.go @@ -70,7 +70,7 @@ func moduleInfoPath(id string) storage.Path { return append(ModulesInfoBasePath, strings.Trim(id, "/")) } -func read(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (interface{}, error) { +func read(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (any, error) { value, err := store.Read(ctx, txn, path) if err != nil { return nil, err @@ -93,7 +93,7 @@ func ReadBundleNamesFromStore(ctx context.Context, store storage.Store, txn stor return nil, err } - bundleMap, ok := value.(map[string]interface{}) + bundleMap, ok := value.(map[string]any) if !ok { return nil, errors.New("corrupt manifest roots") } @@ -118,7 +118,7 @@ func WriteEtagToStore(ctx context.Context, store storage.Store, txn storage.Tran return write(ctx, store, txn, EtagStoragePath(name), etag) } -func write(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path, value interface{}) error { +func write(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path, value any) error { if err := util.RoundTrip(&value); err != nil { return err } @@ -218,7 +218,7 @@ func ReadWasmModulesFromStore(ctx context.Context, store storage.Store, txn stor return nil, err } - encodedModules, ok := value.(map[string]interface{}) + encodedModules, ok := value.(map[string]any) if !ok { return nil, errors.New("corrupt wasm modules") } @@ -247,7 +247,7 @@ func ReadBundleRootsFromStore(ctx context.Context, store storage.Store, txn stor return nil, err } - sl, ok := value.([]interface{}) + sl, ok := value.([]any) if !ok { return nil, errors.New("corrupt manifest roots") } @@ -288,17 +288,17 @@ func readRevisionFromStore(ctx context.Context, store storage.Store, txn storage // ReadBundleMetadataFromStore returns the metadata in the specified bundle. // If the bundle is not activated, this function will return // storage NotFound error. -func ReadBundleMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (map[string]interface{}, error) { +func ReadBundleMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (map[string]any, error) { return readMetadataFromStore(ctx, store, txn, metadataPath(name)) } -func readMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (map[string]interface{}, error) { +func readMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (map[string]any, error) { value, err := read(ctx, store, txn, path) if err != nil { return nil, suppressNotFound(err) } - data, ok := value.(map[string]interface{}) + data, ok := value.(map[string]any) if !ok { return nil, errors.New("corrupt manifest metadata") } @@ -451,7 +451,7 @@ func activateBundles(opts *ActivateOpts) error { } // verify valid YAML or JSON value - var x interface{} + var x any err := util.Unmarshal(item.Value, &x) if err != nil { return err @@ -615,7 +615,7 @@ func activateDeltaBundles(opts *ActivateOpts, bundles map[string]*Bundle) error return nil } -func valueToManifest(v interface{}) (Manifest, error) { +func valueToManifest(v any) (Manifest, error) { if astV, ok := v.(ast.Value); ok { var err error v, err = ast.JSON(astV) @@ -902,7 +902,7 @@ func writeDataAndModules(ctx context.Context, store storage.Store, txn storage.T return nil } -func writeData(ctx context.Context, store storage.Store, txn storage.Transaction, roots []string, data map[string]interface{}) error { +func writeData(ctx context.Context, store storage.Store, txn storage.Transaction, roots []string, data map[string]any) error { for _, root := range roots { path, ok := storage.ParsePathEscaped("/" + root) if !ok { @@ -1016,7 +1016,7 @@ func writeModules(ctx context.Context, store storage.Store, txn storage.Transact return nil } -func lookup(path storage.Path, data map[string]interface{}) (interface{}, bool) { +func lookup(path storage.Path, data map[string]any) (any, bool) { if len(path) == 0 { return data, true } @@ -1025,7 +1025,7 @@ func lookup(path storage.Path, data map[string]interface{}) (interface{}, bool) if !ok { return nil, false } - obj, ok := value.(map[string]interface{}) + obj, ok := value.(map[string]any) if !ok { return nil, false } diff --git a/v1/bundle/store_test.go b/v1/bundle/store_test.go index d218b56f0a..bd37388bf4 100644 --- a/v1/bundle/store_test.go +++ b/v1/bundle/store_test.go @@ -317,13 +317,13 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { tests := []struct { note string - updates []interface{} + updates []any runtimeRegoVersion ast.RegoVersion }{ // single v0 bundle { note: "v0 bundle, lazy, read with bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -350,7 +350,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v0 bundle, not lazy, read with bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -377,7 +377,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v0 bundle, lazy, read with NO bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -404,7 +404,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v0 bundle, not lazy, read with NO bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -433,7 +433,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v0 bundle, not lazy, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -460,7 +460,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v0 bundle, lazy, read with bundle name, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -487,7 +487,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v0 bundle, lazy, read with NO bundle name, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -515,7 +515,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { // single v1 bundle { note: "v1 bundle, lazy, read with bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -541,7 +541,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v1 bundle, not lazy, read with bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -567,7 +567,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v1 bundle, lazy, read with NO bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -593,7 +593,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v1 bundle, not lazy, read with NO bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -621,7 +621,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v1 bundle, not lazy, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -649,7 +649,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v1 bundle, lazy, read with bundle name, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -677,7 +677,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v1 bundle, lazy, read with NO bundle name, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -705,7 +705,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "custom bundle without rego-version, lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -747,7 +747,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "custom bundle without rego-version, lazy, v1 runtime (explicit)", runtimeRegoVersion: ast.RegoV1, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -789,7 +789,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "custom bundle without rego-version, lazy, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -831,7 +831,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "custom bundle without rego-version, not lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -873,7 +873,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "custom bundle without rego-version, not lazy, v1 runtime (explicit)", runtimeRegoVersion: ast.RegoV1, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -915,7 +915,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "custom bundle without rego-version, not lazy, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -957,7 +957,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v0, lazy replaced by non-lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1001,7 +1001,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v0 bundle replaced by v1 bundle, lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1044,7 +1044,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v0 bundle replaced by v1 bundle, not lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1087,7 +1087,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v0 bundle replaced by custom bundle, not lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1131,7 +1131,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v1 bundle replaced by v0 bundle, lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1173,7 +1173,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "v1 bundle replaced by v0 bundle, not lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1215,7 +1215,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "custom bundle replaced by v0 bundle, lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1258,7 +1258,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "multiple v0 bundles, all dropped", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1293,7 +1293,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "multiple v0 bundles, one dropped", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1335,7 +1335,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "v0 bundle with v1 bundle added", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1382,7 +1382,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "mixed-version bundles, lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1456,7 +1456,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "mixed-version bundles, lazy, read with NO bundle name", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1530,7 +1530,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { }, { note: "mixed-version bundles, not lazy", - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1606,7 +1606,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "mixed-version bundles, lazy, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1681,7 +1681,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "mixed-version bundles, lazy, read with NO bundle name, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -1756,7 +1756,7 @@ func TestBundleLifecycle_ModuleRegoVersions(t *testing.T) { { note: "mixed-version bundles, not lazy, --v0-compatible", runtimeRegoVersion: ast.RegoV0, - updates: []interface{}{ + updates: []any{ activation{ bundles: bundles{ "bundle1": { @@ -2770,10 +2770,10 @@ func TestBundleLazyModeLifecycleNoBundleRoots(t *testing.T) { b := Bundle{ Manifest: Manifest{Revision: "rev-1"}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -2863,8 +2863,8 @@ func TestBundleLazyModeLifecycleNoBundleRoots(t *testing.T) { // add a new bundle with no roots. this means all the data from the currently activated should be removed b = Bundle{ Manifest: Manifest{Revision: "rev-2"}, - Data: map[string]interface{}{ - "c": map[string]interface{}{ + Data: map[string]any{ + "c": map[string]any{ "hello": "world", }, }, @@ -2958,10 +2958,10 @@ func TestBundleLazyModeLifecycleNoBundleRootsDiskStorage(t *testing.T) { b := Bundle{ Manifest: Manifest{Revision: "rev-1"}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -3073,8 +3073,8 @@ func TestBundleLazyModeLifecycleNoBundleRootsDiskStorage(t *testing.T) { // add a new bundle with no roots. this means all the data from the currently activated should be removed b = Bundle{ Manifest: Manifest{Revision: "rev-2"}, - Data: map[string]interface{}{ - "c": map[string]interface{}{ + Data: map[string]any{ + "c": map[string]any{ "hello": "world", }, }, @@ -3173,10 +3173,10 @@ func TestBundleLazyModeLifecycleMixBundleTypeActivationDiskStorage(t *testing.T) Revision: "snap-1", Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -3323,10 +3323,10 @@ func TestBundleLazyModeLifecycleOldBundleEraseDiskStorage(t *testing.T) { b := Bundle{ Manifest: Manifest{Revision: "rev-1", Roots: &[]string{"a"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -3438,8 +3438,8 @@ func TestBundleLazyModeLifecycleOldBundleEraseDiskStorage(t *testing.T) { // add a new bundle and verify data from the currently activated is removed b = Bundle{ Manifest: Manifest{Revision: "rev-2", Roots: &[]string{"c"}}, - Data: map[string]interface{}{ - "c": map[string]interface{}{ + Data: map[string]any{ + "c": map[string]any{ "hello": "world", }, }, @@ -3535,10 +3535,10 @@ func TestBundleLazyModeLifecycleRestoreBackupDB(t *testing.T) { b := Bundle{ Manifest: Manifest{Revision: "rev-1", Roots: &[]string{"a"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -3650,8 +3650,8 @@ func TestBundleLazyModeLifecycleRestoreBackupDB(t *testing.T) { // add a new bundle but abort the transaction and verify only old the bundle data is kept in store b = Bundle{ Manifest: Manifest{Revision: "rev-2", Roots: &[]string{"c"}}, - Data: map[string]interface{}{ - "c": map[string]interface{}{ + Data: map[string]any{ + "c": map[string]any{ "hello": "world", }, }, @@ -3762,10 +3762,10 @@ func TestDeltaBundleLazyModeLifecycleDiskStorage(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -3919,8 +3919,8 @@ func TestDeltaBundleLazyModeLifecycleDiskStorage(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"d"}, }, - Data: map[string]interface{}{ - "d": map[string]interface{}{ + Data: map[string]any{ + "d": map[string]any{ "e": "foo", }, }, @@ -4026,10 +4026,10 @@ func TestBundleLazyModeLifecycleOverlappingBundleRoots(t *testing.T) { Revision: "foo", Roots: &[]string{"a/b", "a/c", "a/d"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "c": map[string]interface{}{ + "c": map[string]any{ "d": "bar", }, "d": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -4052,9 +4052,9 @@ func TestBundleLazyModeLifecycleOverlappingBundleRoots(t *testing.T) { Revision: "bar", Roots: &[]string{"a/e"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ - "e": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ + "e": map[string]any{ "f": "bar", }, }, @@ -4182,9 +4182,9 @@ func TestBundleLazyModeLifecycleOverlappingBundleRootsDiskStorage(t *testing.T) Revision: "foo", Roots: &[]string{"a/b/c", "a/b/d", "a/b/e"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": "bar", "d": []map[string]string{{"name": "john"}, {"name": "jane"}}, "e": []string{"foo", "bar"}, @@ -4208,10 +4208,10 @@ func TestBundleLazyModeLifecycleOverlappingBundleRootsDiskStorage(t *testing.T) Revision: "bar", Roots: &[]string{"a/b/f"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ - "f": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ + "b": map[string]any{ + "f": map[string]any{ "hello": "world", }, }, @@ -4604,10 +4604,10 @@ func TestDeltaBundleLazyModeLifecycle(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -4782,8 +4782,8 @@ func TestDeltaBundleLazyModeLifecycle(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"d"}, }, - Data: map[string]interface{}{ - "d": map[string]interface{}{ + Data: map[string]any{ + "d": map[string]any{ "e": "foo", }, }, @@ -4890,10 +4890,10 @@ func TestDeltaBundleLazyModeWithDefaultRules(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -5068,8 +5068,8 @@ func TestDeltaBundleLazyModeWithDefaultRules(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"d"}, }, - Data: map[string]interface{}{ - "d": map[string]interface{}{ + Data: map[string]any{ + "d": map[string]any{ "e": "foo", }, }, @@ -5201,8 +5201,8 @@ func TestBundleLifecycle(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", }, }, @@ -5391,10 +5391,10 @@ func TestDeltaBundleLifecycle(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": "foo", - "e": map[string]interface{}{ + "e": map[string]any{ "f": "bar", }, "x": []map[string]string{{"name": "john"}, {"name": "jane"}}, @@ -5541,8 +5541,8 @@ func TestDeltaBundleLifecycle(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"d"}, }, - Data: map[string]interface{}{ - "d": map[string]interface{}{ + Data: map[string]any{ + "d": map[string]any{ "e": "foo", }, }, @@ -5760,7 +5760,7 @@ func TestDeltaBundleActivate(t *testing.T) { } } -func assertEqual(t *testing.T, expectAst bool, expected string, actual interface{}) { +func assertEqual(t *testing.T, expectAst bool, expected string, actual any) { t.Helper() if expectAst { @@ -5896,15 +5896,15 @@ func TestEraseData(t *testing.T) { ctx := context.Background() cases := []struct { note string - initialData map[string]interface{} + initialData map[string]any roots []string expectErr bool expected string }{ { note: "erase all", - initialData: map[string]interface{}{ - "a": map[string]interface{}{ + initialData: map[string]any{ + "a": map[string]any{ "b": "foo", }, "b": "bar", @@ -5915,8 +5915,8 @@ func TestEraseData(t *testing.T) { }, { note: "erase none", - initialData: map[string]interface{}{ - "a": map[string]interface{}{ + initialData: map[string]any{ + "a": map[string]any{ "b": "foo", }, "b": "bar", @@ -5927,8 +5927,8 @@ func TestEraseData(t *testing.T) { }, { note: "erase partial", - initialData: map[string]interface{}{ - "a": map[string]interface{}{ + initialData: map[string]any{ + "a": map[string]any{ "b": "foo", }, "b": "bar", @@ -5939,10 +5939,10 @@ func TestEraseData(t *testing.T) { }, { note: "erase partial path", - initialData: map[string]interface{}{ - "a": map[string]interface{}{ + initialData: map[string]any{ + "a": map[string]any{ "b": "foo", - "c": map[string]interface{}{ + "c": map[string]any{ "d": 123, }, }, @@ -6133,18 +6133,18 @@ func TestWriteData(t *testing.T) { ctx := context.Background() cases := []struct { note string - existingData map[string]interface{} + existingData map[string]any roots []string - data map[string]interface{} + data map[string]any expected string expectErr bool }{ { note: "single root", roots: []string{"a"}, - data: map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ + data: map[string]any{ + "a": map[string]any{ + "b": map[string]any{ "c": 123, }, }, @@ -6155,10 +6155,10 @@ func TestWriteData(t *testing.T) { { note: "multiple roots", roots: []string{"a", "b/c/d"}, - data: map[string]interface{}{ + data: map[string]any{ "a": "foo", - "b": map[string]interface{}{ - "c": map[string]interface{}{ + "b": map[string]any{ + "c": map[string]any{ "d": "bar", }, }, @@ -6169,10 +6169,10 @@ func TestWriteData(t *testing.T) { { note: "data not in roots", roots: []string{"a"}, - data: map[string]interface{}{ + data: map[string]any{ "a": "foo", - "b": map[string]interface{}{ - "c": map[string]interface{}{ + "b": map[string]any{ + "c": map[string]any{ "d": "bar", }, }, @@ -6183,30 +6183,30 @@ func TestWriteData(t *testing.T) { { note: "no data", roots: []string{"a"}, - existingData: map[string]interface{}{}, - data: map[string]interface{}{}, + existingData: map[string]any{}, + data: map[string]any{}, expected: `{}`, expectErr: false, }, { note: "no new data", roots: []string{"a"}, - existingData: map[string]interface{}{ + existingData: map[string]any{ "a": "foo", }, - data: map[string]interface{}{}, + data: map[string]any{}, expected: `{"a": "foo"}`, expectErr: false, }, { note: "overwrite data", roots: []string{"a"}, - existingData: map[string]interface{}{ - "a": map[string]interface{}{ + existingData: map[string]any{ + "a": map[string]any{ "b": "foo", }, }, - data: map[string]interface{}{ + data: map[string]any{ "a": "bar", }, expected: `{"a": "bar"}`, @@ -6246,21 +6246,21 @@ func TestWriteData(t *testing.T) { } } -func loadExpectedResult(input string) interface{} { +func loadExpectedResult(input string) any { if len(input) == 0 { return nil } - var data interface{} + var data any if err := util.UnmarshalJSON([]byte(input), &data); err != nil { panic(err) } return data } -func loadExpectedSortedResult(input string) interface{} { +func loadExpectedSortedResult(input string) any { data := loadExpectedResult(input) switch data := data.(type) { - case []interface{}: + case []any: return data default: return data @@ -6272,7 +6272,7 @@ type testWriteModuleCase struct { bundles map[string]*Bundle // Only need to give raw text and path for modules extraMods map[string]*ast.Module compilerMods map[string]*ast.Module - storeData map[string]interface{} + storeData map[string]any expectErr bool } @@ -6363,8 +6363,8 @@ func TestWriteModules(t *testing.T) { }, }, }, - storeData: map[string]interface{}{ - "a": map[string]interface{}{ + storeData: map[string]any{ + "a": map[string]any{ "p": "foo", }, }, @@ -6746,7 +6746,7 @@ func TestBundleStoreHelpers(t *testing.T) { Manifest: Manifest{ Roots: &[]string{"a"}, Revision: "foo", - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "a": "b", }, WasmResolvers: []WasmResolver{ diff --git a/v1/bundle/verify.go b/v1/bundle/verify.go index 0645d3aafb..829e98acdf 100644 --- a/v1/bundle/verify.go +++ b/v1/bundle/verify.go @@ -178,7 +178,7 @@ func VerifyBundleFile(path string, data bytes.Buffer, files map[string]FileInfo) // then recursively order the fields of all objects alphabetically and then apply // the hash function to result to compute the hash. This ensures that the digital signature is // independent of whitespace and other non-semantic JSON features. - var value interface{} + var value any if IsStructuredDoc(path) { err := util.Unmarshal(data.Bytes(), &value) if err != nil { diff --git a/v1/capabilities/capabilities_test.go b/v1/capabilities/capabilities_test.go index e8e2f78688..789a4be961 100644 --- a/v1/capabilities/capabilities_test.go +++ b/v1/capabilities/capabilities_test.go @@ -27,7 +27,7 @@ func TestCapabilitiesEmbedded(t *testing.T) { if err != nil { t.Errorf("file %v: %v", ent.Name(), err) } - var x interface{} + var x any err = util.UnmarshalJSON(cont, &x) if err != nil { t.Errorf("file %v: %v", ent.Name(), err) diff --git a/v1/compile/compile.go b/v1/compile/compile.go index dac4e59491..57f980ed84 100644 --- a/v1/compile/compile.go +++ b/v1/compile/compile.go @@ -80,7 +80,7 @@ type Compiler struct { bvc *bundle.VerificationConfig // represents the key configuration used to verify a signed bundle bsc *bundle.SigningConfig // represents the key configuration used to generate a signed bundle keyID string // represents the name of the default key used to verify a signed bundle - metadata *map[string]interface{} // represents additional data included in .manifest file + metadata *map[string]any // represents additional data included in .manifest file fsys fs.FS // file system to use when loading paths ns string regoVersion ast.RegoVersion @@ -228,7 +228,7 @@ func (c *Compiler) WithFollowSymlinks(yes bool) *Compiler { } // WithMetadata sets the additional data to be included in .manifest -func (c *Compiler) WithMetadata(metadata *map[string]interface{}) *Compiler { +func (c *Compiler) WithMetadata(metadata *map[string]any) *Compiler { c.metadata = metadata return c } @@ -960,7 +960,7 @@ func (o *optimizer) Do(ctx context.Context) error { // initialize other inputs to the optimization process (store, symbols, etc.) data := o.bundle.Data if data == nil { - data = map[string]interface{}{} + data = map[string]any{} } store := inmem.NewFromObjectWithOpts(data, inmem.OptRoundTripOnWrite(false)) diff --git a/v1/compile/compile_test.go b/v1/compile/compile_test.go index 3147302e1f..53d7002510 100644 --- a/v1/compile/compile_test.go +++ b/v1/compile/compile_test.go @@ -509,7 +509,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Manifest: bundle.Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, }, @@ -524,7 +524,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, }, @@ -538,14 +538,14 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Manifest: bundle.Manifest{ Roots: &[]string{"a"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, { Manifest: bundle.Manifest{ Roots: &[]string{"b"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, }, }, @@ -560,7 +560,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -575,7 +575,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"b"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/test1.rego", @@ -602,7 +602,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV0, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -617,7 +617,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"b"}, RegoVersion: ®oV0, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/test1.rego", @@ -644,7 +644,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV0, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -659,7 +659,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"b"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/test1.rego", @@ -685,7 +685,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { Roots: &[]string{"a"}, RegoVersion: ®oV1, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/test1.rego", @@ -709,7 +709,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { "/test1.rego": 0, }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { // we don't expect this file to get an individual rego-version in the result, as @@ -732,7 +732,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { RegoVersion: ®oV0, Roots: &[]string{"c"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ // we don't expect these files to get individual rego-versions in the result, // as they have the same rego-version as the global rego-version @@ -772,7 +772,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { "a/*": 1, }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "a/foo/test.rego", @@ -800,7 +800,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) { "*/bar/*": 0, }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "b/foo/test.rego", @@ -2786,7 +2786,7 @@ func TestCompilerSetMetadata(t *testing.T) { for _, useMemoryFS := range []bool{false, true} { test.WithTestFS(files, useMemoryFS, func(root string, fsys fs.FS) { - metadata := map[string]interface{}{"OPA version": "0.36.1"} + metadata := map[string]any{"OPA version": "0.36.1"} compiler := New(). WithFS(fsys). WithPaths(root). @@ -3605,7 +3605,7 @@ func getOptimizer(modules map[string]string, data string, entries []string, root } if data != "" { - b.Data = util.MustUnmarshalJSON([]byte(data)).(map[string]interface{}) + b.Data = util.MustUnmarshalJSON([]byte(data)).(map[string]any) } if len(roots) > 0 { diff --git a/v1/config/config.go b/v1/config/config.go index 490f90b905..62bfc65537 100644 --- a/v1/config/config.go +++ b/v1/config/config.go @@ -168,13 +168,13 @@ func (c Config) GetPersistenceDirectory() (string, error) { // ActiveConfig returns OPA's active configuration // with the credentials and crypto keys removed -func (c *Config) ActiveConfig() (interface{}, error) { +func (c *Config) ActiveConfig() (any, error) { bs, err := json.Marshal(c) if err != nil { return nil, err } - var result map[string]interface{} + var result map[string]any if err := util.UnmarshalJSON(bs, &result); err != nil { return nil, err } @@ -197,11 +197,11 @@ func (c *Config) ActiveConfig() (interface{}, error) { return result, nil } -func removeServiceCredentials(x interface{}) error { +func removeServiceCredentials(x any) error { switch x := x.(type) { case nil: return nil - case []interface{}: + case []any: for _, v := range x { err := removeKey(v, "credentials") if err != nil { @@ -209,7 +209,7 @@ func removeServiceCredentials(x interface{}) error { } } - case map[string]interface{}: + case map[string]any: for _, v := range x { err := removeKey(v, "credentials") if err != nil { @@ -223,11 +223,11 @@ func removeServiceCredentials(x interface{}) error { return nil } -func removeCryptoKeys(x interface{}) error { +func removeCryptoKeys(x any) error { switch x := x.(type) { case nil: return nil - case map[string]interface{}: + case map[string]any: for _, v := range x { err := removeKey(v, "key", "private_key") if err != nil { @@ -241,8 +241,8 @@ func removeCryptoKeys(x interface{}) error { return nil } -func removeKey(x interface{}, keys ...string) error { - val, ok := x.(map[string]interface{}) +func removeKey(x any, keys ...string) error { + val, ok := x.(map[string]any) if !ok { return errors.New("type assertion error") } diff --git a/v1/config/config_test.go b/v1/config/config_test.go index 86040c5420..7d1ff51a79 100644 --- a/v1/config/config_test.go +++ b/v1/config/config_test.go @@ -392,7 +392,7 @@ func TestActiveConfig(t *testing.T) { t.Fatalf("Unexpected error %v", err) } - var expected map[string]interface{} + var expected map[string]any if err := util.Unmarshal(tc.expected, &expected); err != nil { t.Fatal(err) } diff --git a/v1/debug/debugger.go b/v1/debug/debugger.go index 93caf4f8b5..b9feaf12d0 100644 --- a/v1/debug/debugger.go +++ b/v1/debug/debugger.go @@ -198,7 +198,7 @@ func SetEventHandler(handler EventHandler) DebuggerOption { type LaunchEvalProperties struct { LaunchProperties Query string - Input interface{} + Input any InputPath string } diff --git a/v1/debug/debugger_test.go b/v1/debug/debugger_test.go index 6c483d6dcb..5b23930f54 100644 --- a/v1/debug/debugger_test.go +++ b/v1/debug/debugger_test.go @@ -1621,7 +1621,7 @@ func TestDebuggerScopeVariables(t *testing.T) { input *ast.Term locals map[ast.Var]ast.Value virtualCache map[string]ast.Value - data map[string]interface{} + data map[string]any result *rego.ResultSet expScopes map[string]scopeInfo }{ @@ -1827,7 +1827,7 @@ func TestDebuggerScopeVariables(t *testing.T) { Text: "x = data.test.allow", }, }, - Bindings: map[string]interface{}{ + Bindings: map[string]any{ "x": ast.Boolean(true), }, }, @@ -1926,7 +1926,7 @@ func TestDebuggerScopeVariables(t *testing.T) { }, { note: "data", - data: map[string]interface{}{ + data: map[string]any{ "foo": "bar", "baz": 42, }, diff --git a/v1/debug/thread.go b/v1/debug/thread.go index 06d1d2e9c5..76f8557c73 100644 --- a/v1/debug/thread.go +++ b/v1/debug/thread.go @@ -18,7 +18,7 @@ import ( "github.com/open-policy-agent/opa/v1/topdown" ) -type threadState interface{} +type threadState any type eventAction string diff --git a/v1/dependencies/deps.go b/v1/dependencies/deps.go index ac8a1ecae7..1635e41545 100644 --- a/v1/dependencies/deps.go +++ b/v1/dependencies/deps.go @@ -13,7 +13,7 @@ import ( ) // All returns the list of data ast.Refs that the given AST element depends on. -func All(x interface{}) (resolved []ast.Ref, err error) { +func All(x any) (resolved []ast.Ref, err error) { var rawResolved []ast.Ref switch x := x.(type) { case *ast.Module, *ast.Package, *ast.Import, *ast.Rule, *ast.Head, ast.Body, *ast.Expr, *ast.With, *ast.Term, ast.Ref, ast.Object, *ast.Array, ast.Set, *ast.ArrayComprehension: @@ -21,7 +21,7 @@ func All(x interface{}) (resolved []ast.Ref, err error) { return nil, fmt.Errorf("not an ast element: %v", x) } - visitor := ast.NewGenericVisitor(func(x interface{}) bool { + visitor := ast.NewGenericVisitor(func(x any) bool { switch x := x.(type) { case *ast.Package, *ast.Import: return true @@ -69,7 +69,7 @@ func All(x interface{}) (resolved []ast.Ref, err error) { // // As an example, if an element depends on data.x and data.x.y, only data.x will // be in the returned list. -func Minimal(x interface{}) (resolved []ast.Ref, err error) { +func Minimal(x any) (resolved []ast.Ref, err error) { rawResolved, err := All(x) if err != nil { return nil, err @@ -88,7 +88,7 @@ func Minimal(x interface{}) (resolved []ast.Ref, err error) { // // The returned refs are always constant and are truncated at any point where they become // dynamic. That is, a ref like data.a.b[x] will be truncated to data.a.b. -func Base(compiler *ast.Compiler, x interface{}) ([]ast.Ref, error) { +func Base(compiler *ast.Compiler, x any) ([]ast.Ref, error) { baseRefs := newRefSet() err := base(compiler, x, baseRefs) if err != nil { @@ -98,7 +98,7 @@ func Base(compiler *ast.Compiler, x interface{}) ([]ast.Ref, error) { return dedup(baseRefs.toSlice()), nil } -func base(compiler *ast.Compiler, x interface{}, baseRefs *dependencies) error { +func base(compiler *ast.Compiler, x any, baseRefs *dependencies) error { refs, err := Minimal(x) if err != nil { return err @@ -130,7 +130,7 @@ func base(compiler *ast.Compiler, x interface{}, baseRefs *dependencies) error { // // The returned refs are always constant and are truncated at any point where they become // dynamic. That is, a ref like data.a.b[x] will be truncated to data.a.b. -func Virtual(compiler *ast.Compiler, x interface{}) ([]ast.Ref, error) { +func Virtual(compiler *ast.Compiler, x any) ([]ast.Ref, error) { virtualRefs := newRefSet() err := virtual(compiler, x, virtualRefs) if err != nil { @@ -140,7 +140,7 @@ func Virtual(compiler *ast.Compiler, x interface{}) ([]ast.Ref, error) { return dedup(virtualRefs.toSlice()), nil } -func virtual(compiler *ast.Compiler, x interface{}, virtualRefs *dependencies) error { +func virtual(compiler *ast.Compiler, x any, virtualRefs *dependencies) error { refs, err := Minimal(x) if err != nil { return err @@ -452,7 +452,7 @@ type skipVisitor struct { skipped bool } -func (sv *skipVisitor) Visit(v interface{}) bool { +func (sv *skipVisitor) Visit(v any) bool { if sv.skipped { if r, ok := v.(ast.Ref); ok { return sv.fn(r) diff --git a/v1/dependencies/deps_test.go b/v1/dependencies/deps_test.go index b46dc2feee..8d260f9c04 100644 --- a/v1/dependencies/deps_test.go +++ b/v1/dependencies/deps_test.go @@ -490,7 +490,7 @@ func TestBase(t *testing.T) { } -func runDeps(t *testing.T, x interface{}) (min, full []ast.Ref) { +func runDeps(t *testing.T, x any) (min, full []ast.Ref) { min, err := Minimal(x) if err != nil { t.Fatalf("Unexpected dependency error: %v", err) diff --git a/v1/download/download.go b/v1/download/download.go index b318aa5ce2..c17e4a19a5 100644 --- a/v1/download/download.go +++ b/v1/download/download.go @@ -98,7 +98,7 @@ func (d *Downloader) WithCallback(f func(context.Context, Update)) *Downloader { // WithLogAttrs sets an optional set of key/value pair attributes to include in // log messages emitted by the downloader. -func (d *Downloader) WithLogAttrs(attrs map[string]interface{}) *Downloader { +func (d *Downloader) WithLogAttrs(attrs map[string]any) *Downloader { d.logger = d.logger.WithFields(attrs) return d } diff --git a/v1/download/download_test.go b/v1/download/download_test.go index 86f682409b..9b8143b488 100644 --- a/v1/download/download_test.go +++ b/v1/download/download_test.go @@ -691,7 +691,7 @@ p contains 1 if { fixture.server.bundles["custom"] = bundle.Bundle{ Manifest: bundle.Manifest{RegoVersion: &tc.bundleRegoVersion}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "test.rego", diff --git a/v1/download/oci_download.go b/v1/download/oci_download.go index 5a680ed4ed..8c710e71d4 100644 --- a/v1/download/oci_download.go +++ b/v1/download/oci_download.go @@ -60,7 +60,7 @@ func (d *OCIDownloader) WithCallback(f func(context.Context, Update)) *OCIDownlo // WithLogAttrs sets an optional set of key/value pair attributes to include in // log messages emitted by the downloader. -func (d *OCIDownloader) WithLogAttrs(attrs map[string]interface{}) *OCIDownloader { +func (d *OCIDownloader) WithLogAttrs(attrs map[string]any) *OCIDownloader { d.logger = d.logger.WithFields(attrs) return d } diff --git a/v1/download/oci_download_unavailable.go b/v1/download/oci_download_unavailable.go index ad22fca9be..f0bef46620 100644 --- a/v1/download/oci_download_unavailable.go +++ b/v1/download/oci_download_unavailable.go @@ -18,7 +18,7 @@ func (d *OCIDownloader) WithCallback(f func(context.Context, Update)) *OCIDownlo panic("built without OCI support") } -func (d *OCIDownloader) WithLogAttrs(map[string]interface{}) *OCIDownloader { +func (d *OCIDownloader) WithLogAttrs(map[string]any) *OCIDownloader { panic("built without OCI support") } diff --git a/v1/download/testharness.go b/v1/download/testharness.go index deb1b055eb..654d447aac 100644 --- a/v1/download/testharness.go +++ b/v1/download/testharness.go @@ -275,8 +275,8 @@ func newTestServer(t *testing.T) *testServer { Manifest: bundle.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{ - "foo": map[string]interface{}{ + Data: map[string]any{ + "foo": map[string]any{ "bar": json.Number("1"), "baz": "qux", }, @@ -304,7 +304,7 @@ func newTestServer(t *testing.T) *testServer { Manifest: bundle.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: `/example.rego`, @@ -321,7 +321,7 @@ p contains 1 if { Manifest: bundle.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: `/example.rego`, @@ -339,7 +339,7 @@ p contains 1 if { Manifest: bundle.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: `/example.rego`, diff --git a/v1/features/wasm/wasm.go b/v1/features/wasm/wasm.go index 23d03e95f6..382527d78d 100644 --- a/v1/features/wasm/wasm.go +++ b/v1/features/wasm/wasm.go @@ -36,7 +36,7 @@ func (o *OPA) WithPolicyBytes(policy []byte) opa.EvalEngine { } // WithDataJSON configures the JSON data to load. -func (o *OPA) WithDataJSON(data interface{}) opa.EvalEngine { +func (o *OPA) WithDataJSON(data any) opa.EvalEngine { o.opa = o.opa.WithDataJSON(data) return o } @@ -77,11 +77,11 @@ func (o *OPA) Eval(ctx context.Context, opts opa.EvalOpts) (*opa.Result, error) return &opa.Result{Result: res.Result}, nil } -func (o *OPA) SetData(ctx context.Context, data interface{}) error { +func (o *OPA) SetData(ctx context.Context, data any) error { return o.opa.SetData(ctx, data) } -func (o *OPA) SetDataPath(ctx context.Context, path []string, data interface{}) error { +func (o *OPA) SetDataPath(ctx context.Context, path []string, data any) error { return o.opa.SetDataPath(ctx, path, data) } diff --git a/v1/format/format.go b/v1/format/format.go index 2b0f2af15a..815b7ca9d9 100644 --- a/v1/format/format.go +++ b/v1/format/format.go @@ -101,7 +101,7 @@ func SourceWithOpts(filename string, src []byte, opts Opts) ([]byte, error) { // MustAst is a helper function to format a Rego AST element. If any errors // occur this function will panic. This is mostly used for test -func MustAst(x interface{}) []byte { +func MustAst(x any) []byte { bs, err := Ast(x) if err != nil { panic(err) @@ -111,7 +111,7 @@ func MustAst(x interface{}) []byte { // MustAstWithOpts is a helper function to format a Rego AST element. If any errors // occur this function will panic. This is mostly used for test -func MustAstWithOpts(x interface{}, opts Opts) []byte { +func MustAstWithOpts(x any, opts Opts) []byte { bs, err := AstWithOpts(x, opts) if err != nil { panic(err) @@ -122,7 +122,7 @@ func MustAstWithOpts(x interface{}, opts Opts) []byte { // Ast formats a Rego AST element. If the passed value is not a valid AST // element, Ast returns nil and an error. If AST nodes are missing locations // an arbitrary location will be used. -func Ast(x interface{}) ([]byte, error) { +func Ast(x any) ([]byte, error) { return AstWithOpts(x, Opts{}) } @@ -156,7 +156,7 @@ func (o fmtOpts) keywords() []string { return append(kws, o.futureKeywords...) } -func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { +func AstWithOpts(x any, opts Opts) ([]byte, error) { // The node has to be deep copied because it may be mutated below. Alternatively, // we could avoid the copy by checking if mutation will occur first. For now, // since format is not latency sensitive, just deep copy in all cases. @@ -384,9 +384,9 @@ type writer struct { func (w *writer) writeModule(module *ast.Module) error { var pkg *ast.Package - var others []interface{} + var others []any var comments []*ast.Comment - visitor := ast.NewGenericVisitor(func(x interface{}) bool { + visitor := ast.NewGenericVisitor(func(x any) bool { switch x := x.(type) { case *ast.Comment: comments = append(comments, x) @@ -759,7 +759,7 @@ func (w *writer) writeHead(head *ast.Head, isDefault bool, isExpandedConst bool, if len(head.Args) > 0 { w.write("(") - var args []interface{} + var args []any for _, arg := range head.Args { args = append(args, arg) } @@ -1072,7 +1072,7 @@ func (w *writer) writeFunctionCall(expr *ast.Expr, comments []*ast.Comment) ([]* func (w *writer) writeFunctionCallPlain(terms []*ast.Term, comments []*ast.Comment) ([]*ast.Comment, error) { w.write(terms[0].String() + "(") defer w.write(")") - args := make([]interface{}, len(terms)-1) + args := make([]any, len(terms)-1) for i, t := range terms[1:] { args[i] = t } @@ -1405,7 +1405,7 @@ func (w *writer) writeObject(obj ast.Object, loc *ast.Location, comments []*ast. w.write("{") defer w.write("}") - var s []interface{} + var s []any obj.Foreach(func(k, v *ast.Term) { s = append(s, ast.Item(k, v)) }) @@ -1416,7 +1416,7 @@ func (w *writer) writeArray(arr *ast.Array, loc *ast.Location, comments []*ast.C w.write("[") defer w.write("]") - var s []interface{} + var s []any arr.Foreach(func(t *ast.Term) { s = append(s, t) }) @@ -1443,7 +1443,7 @@ func (w *writer) writeSet(set ast.Set, loc *ast.Location, comments []*ast.Commen w.write("{") defer w.write("}") - var s []interface{} + var s []any set.Foreach(func(t *ast.Term) { s = append(s, t) }) @@ -1510,7 +1510,7 @@ func (w *writer) writeComprehension(openChar, closeChar byte, term *ast.Term, bo } func (w *writer) writeComprehensionBody(openChar, closeChar byte, body ast.Body, term, compr *ast.Location, comments []*ast.Comment) ([]*ast.Comment, error) { - exprs := make([]interface{}, 0, len(body)) + exprs := make([]any, 0, len(body)) for _, expr := range body { exprs = append(exprs, expr) } @@ -1613,9 +1613,9 @@ func (w *writer) writeImport(imp *ast.Import) error { return nil } -type entryWriter func(interface{}, []*ast.Comment) ([]*ast.Comment, error) +type entryWriter func(any, []*ast.Comment) ([]*ast.Comment, error) -func (w *writer) writeIterable(elements []interface{}, last *ast.Location, close *ast.Location, comments []*ast.Comment, fn entryWriter) ([]*ast.Comment, error) { +func (w *writer) writeIterable(elements []any, last *ast.Location, close *ast.Location, comments []*ast.Comment, fn entryWriter) ([]*ast.Comment, error) { lines, err := w.groupIterable(elements, last) if err != nil { return nil, err @@ -1658,7 +1658,7 @@ func (w *writer) writeIterable(elements []interface{}, last *ast.Location, close return comments, nil } -func (w *writer) writeIterableLine(elements []interface{}, comments []*ast.Comment, fn entryWriter) ([]*ast.Comment, error) { +func (w *writer) writeIterableLine(elements []any, comments []*ast.Comment, fn entryWriter) ([]*ast.Comment, error) { if len(elements) == 0 { return comments, nil } @@ -1677,7 +1677,7 @@ func (w *writer) writeIterableLine(elements []interface{}, comments []*ast.Comme } func (w *writer) objectWriter() entryWriter { - return func(x interface{}, comments []*ast.Comment) ([]*ast.Comment, error) { + return func(x any, comments []*ast.Comment) ([]*ast.Comment, error) { entry := x.([2]*ast.Term) call, isCall := entry[0].Value.(ast.Call) @@ -1710,7 +1710,7 @@ func (w *writer) objectWriter() entryWriter { } func (w *writer) listWriter() entryWriter { - return func(x interface{}, comments []*ast.Comment) ([]*ast.Comment, error) { + return func(x any, comments []*ast.Comment) ([]*ast.Comment, error) { t, ok := x.(*ast.Term) if ok { call, isCall := t.Value.(ast.Call) @@ -1726,7 +1726,7 @@ func (w *writer) listWriter() entryWriter { // groupIterable will group the `elements` slice into slices according to their // location: anything on the same line will be put into a slice. -func (w *writer) groupIterable(elements []interface{}, last *ast.Location) ([][]interface{}, error) { +func (w *writer) groupIterable(elements []any, last *ast.Location) ([][]any, error) { // Generated vars occur in the AST when we're rendering the result of // partial evaluation in a bundle build with optimization. // Those variables, and wildcard variables have the "default location", @@ -1753,7 +1753,7 @@ func (w *writer) groupIterable(elements []interface{}, last *ast.Location) ([][] return false }) if def { // return as-is - return [][]interface{}{elements}, nil + return [][]any{elements}, nil } } @@ -1765,8 +1765,8 @@ func (w *writer) groupIterable(elements []interface{}, last *ast.Location) ([][] return l }) - var lines [][]interface{} - cur := make([]interface{}, 0, len(elements)) + var lines [][]any + cur := make([]any, 0, len(elements)) for i, t := range elements { elem := t loc, err := getLoc(elem) @@ -1876,7 +1876,7 @@ func partitionComments(comments []*ast.Comment, l *ast.Location) ([]*ast.Comment return before, at, after } -func gatherImports(others []interface{}) (imports []*ast.Import, rest []interface{}) { +func gatherImports(others []any) (imports []*ast.Import, rest []any) { i := 0 loop: for ; i < len(others); i++ { @@ -1890,7 +1890,7 @@ loop: return imports, others[i:] } -func gatherRules(others []interface{}) (rules []*ast.Rule, rest []interface{}) { +func gatherRules(others []any) (rules []*ast.Rule, rest []any) { i := 0 loop: for ; i < len(others); i++ { @@ -1904,12 +1904,12 @@ loop: return rules, others[i:] } -func locLess(a, b interface{}) (bool, error) { +func locLess(a, b any) (bool, error) { c, err := locCmp(a, b) return c < 0, err } -func locCmp(a, b interface{}) (int, error) { +func locCmp(a, b any) (int, error) { al, err := getLoc(a) if err != nil { return 0, err @@ -1934,7 +1934,7 @@ func locCmp(a, b interface{}) (int, error) { return al.Col - bl.Col, nil } -func getLoc(x interface{}) (*ast.Location, error) { +func getLoc(x any) (*ast.Location, error) { switch x := x.(type) { case ast.Node: // *ast.Head, *ast.Expr, *ast.With, *ast.Term return x.Loc(), nil diff --git a/v1/format/format_test.go b/v1/format/format_test.go index 1b2af439a8..29a94ff5c5 100644 --- a/v1/format/format_test.go +++ b/v1/format/format_test.go @@ -293,7 +293,7 @@ func TestFormatAST(t *testing.T) { cases := []struct { note string regoVersion ast.RegoVersion - toFmt interface{} + toFmt any expected string }{ { @@ -675,7 +675,7 @@ func TestFormatAST_Error(t *testing.T) { cases := []struct { note string regoVersion ast.RegoVersion - toFmt interface{} + toFmt any expErr string }{ { diff --git a/v1/ir/pretty.go b/v1/ir/pretty.go index 6102c5a911..53d7cbae88 100644 --- a/v1/ir/pretty.go +++ b/v1/ir/pretty.go @@ -11,7 +11,7 @@ import ( ) // Pretty writes a human-readable representation of an IR object to w. -func Pretty(w io.Writer, x interface{}) error { +func Pretty(w io.Writer, x any) error { pp := &prettyPrinter{ depth: -1, @@ -25,20 +25,20 @@ type prettyPrinter struct { w io.Writer } -func (pp *prettyPrinter) Before(_ interface{}) { +func (pp *prettyPrinter) Before(_ any) { pp.depth++ } -func (pp *prettyPrinter) After(_ interface{}) { +func (pp *prettyPrinter) After(_ any) { pp.depth-- } -func (pp *prettyPrinter) Visit(x interface{}) (Visitor, error) { +func (pp *prettyPrinter) Visit(x any) (Visitor, error) { pp.writeIndent("%T %+v", x, x) return pp, nil } -func (pp *prettyPrinter) writeIndent(f string, a ...interface{}) { +func (pp *prettyPrinter) writeIndent(f string, a ...any) { pad := strings.Repeat("| ", pp.depth) fmt.Fprintf(pp.w, pad+f+"\n", a...) } diff --git a/v1/ir/walk.go b/v1/ir/walk.go index 08a8f42440..788f36cd8e 100644 --- a/v1/ir/walk.go +++ b/v1/ir/walk.go @@ -6,13 +6,13 @@ package ir // Visitor defines the interface for visiting IR nodes. type Visitor interface { - Before(x interface{}) - Visit(x interface{}) (Visitor, error) - After(x interface{}) + Before(x any) + Visit(x any) (Visitor, error) + After(x any) } // Walk invokes the visitor for nodes under x. -func Walk(vis Visitor, x interface{}) error { +func Walk(vis Visitor, x any) error { impl := walkerImpl{ vis: vis, } @@ -25,7 +25,7 @@ type walkerImpl struct { err error } -func (w *walkerImpl) walk(x interface{}) { +func (w *walkerImpl) walk(x any) { if w.err != nil { // abort on error return } diff --git a/v1/loader/loader.go b/v1/loader/loader.go index 5e2217473a..d7a70ab781 100644 --- a/v1/loader/loader.go +++ b/v1/loader/loader.go @@ -30,7 +30,7 @@ import ( // Result represents the result of successfully loading zero or more files. type Result struct { - Documents map[string]interface{} + Documents map[string]any Modules map[string]*RegoFile path []string } @@ -468,13 +468,13 @@ func getSchemaSetByPathKey(path string) ast.Ref { return key } -func loadOneSchema(path string) (interface{}, error) { +func loadOneSchema(path string) (any, error) { bs, err := os.ReadFile(path) if err != nil { return nil, err } - var schema interface{} + var schema any if err := util.Unmarshal(bs, &schema); err != nil { return nil, fmt.Errorf("%s: %w", path, err) } @@ -584,7 +584,7 @@ func SplitPrefix(path string) ([]string, string) { return nil, path } -func (l *Result) merge(path string, result interface{}) error { +func (l *Result) merge(path string, result any) error { switch result := result.(type) { case bundle.Bundle: for _, module := range result.Modules { @@ -603,7 +603,7 @@ func (l *Result) merge(path string, result interface{}) error { } } -func (l *Result) mergeDocument(path string, doc interface{}) error { +func (l *Result) mergeDocument(path string, doc any) error { obj, ok := makeDir(l.path, doc) if !ok { return unsupportedDocumentType(path) @@ -629,7 +629,7 @@ func (l *Result) withParent(p string) *Result { func newResult() *Result { return &Result{ - Documents: map[string]interface{}{}, + Documents: map[string]any{}, Modules: map[string]*RegoFile{}, } } @@ -719,7 +719,7 @@ func allRec(fsys fs.FS, path string, filter Filter, errors *Errors, loaded *Resu } } -func loadKnownTypes(path string, bs []byte, m metrics.Metrics, opts ast.ParserOptions) (interface{}, error) { +func loadKnownTypes(path string, bs []byte, m metrics.Metrics, opts ast.ParserOptions) (any, error) { switch filepath.Ext(path) { case ".json": return loadJSON(path, bs, m) @@ -739,7 +739,7 @@ func loadKnownTypes(path string, bs []byte, m metrics.Metrics, opts ast.ParserOp return nil, unrecognizedFile(path) } -func loadFileForAnyType(path string, bs []byte, m metrics.Metrics, opts ast.ParserOptions) (interface{}, error) { +func loadFileForAnyType(path string, bs []byte, m metrics.Metrics, opts ast.ParserOptions) (any, error) { module, err := loadRego(path, bs, m, opts) if err == nil { return module, nil @@ -784,9 +784,9 @@ func loadRego(path string, bs []byte, m metrics.Metrics, opts ast.ParserOptions) return result, nil } -func loadJSON(path string, bs []byte, m metrics.Metrics) (interface{}, error) { +func loadJSON(path string, bs []byte, m metrics.Metrics) (any, error) { m.Timer(metrics.RegoDataParse).Start() - var x interface{} + var x any err := util.UnmarshalJSON(bs, &x) m.Timer(metrics.RegoDataParse).Stop() @@ -796,7 +796,7 @@ func loadJSON(path string, bs []byte, m metrics.Metrics) (interface{}, error) { return x, nil } -func loadYAML(path string, bs []byte, m metrics.Metrics) (interface{}, error) { +func loadYAML(path string, bs []byte, m metrics.Metrics) (any, error) { m.Timer(metrics.RegoDataParse).Start() bs, err := yaml.YAMLToJSON(bs) m.Timer(metrics.RegoDataParse).Stop() @@ -806,15 +806,15 @@ func loadYAML(path string, bs []byte, m metrics.Metrics) (interface{}, error) { return loadJSON(path, bs, m) } -func makeDir(path []string, x interface{}) (map[string]interface{}, bool) { +func makeDir(path []string, x any) (map[string]any, bool) { if len(path) == 0 { - obj, ok := x.(map[string]interface{}) + obj, ok := x.(map[string]any) if !ok { return nil, false } return obj, true } - return makeDir(path[:len(path)-1], map[string]interface{}{path[len(path)-1]: x}) + return makeDir(path[:len(path)-1], map[string]any{path[len(path)-1]: x}) } // isUNC reports whether path is a UNC path. diff --git a/v1/loader/loader_test.go b/v1/loader/loader_test.go index 1f5b87ffdc..bddb1ab872 100644 --- a/v1/loader/loader_test.go +++ b/v1/loader/loader_test.go @@ -567,8 +567,8 @@ func TestGetBundleDirectoryLoader(t *testing.T) { Roots: &[]string{"a", "b/c"}, Revision: "123", }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": []int{4, 5, 6}, }, }, @@ -640,7 +640,7 @@ func TestLoadBundle(t *testing.T) { p = 1`), }, }, - Data: map[string]interface{}{ + Data: map[string]any{ "foo": "bar", }, Manifest: bundle.Manifest{ @@ -660,7 +660,7 @@ func TestLoadBundle(t *testing.T) { } actualData := testBundle.Data - actualData["system"] = map[string]interface{}{"bundle": map[string]interface{}{"manifest": map[string]interface{}{"revision": "", "roots": []interface{}{""}}}} + actualData["system"] = map[string]any{"bundle": map[string]any{"manifest": map[string]any{"revision": "", "roots": []any{""}}}} if !reflect.DeepEqual(actualData, loaded.Documents) { t.Fatalf("Expected %v but got: %v", actualData, loaded.Documents) @@ -685,7 +685,7 @@ func TestLoadBundleWithReader(t *testing.T) { p = 1`), }, }, - Data: map[string]interface{}{ + Data: map[string]any{ "foo": "bar", }, Manifest: bundle.Manifest{ @@ -750,7 +750,7 @@ func TestLoadBundleSubDir(t *testing.T) { p = 1`), }, }, - Data: map[string]interface{}{ + Data: map[string]any{ "foo": "bar", }, Manifest: bundle.Manifest{ @@ -770,9 +770,9 @@ func TestLoadBundleSubDir(t *testing.T) { } actualData := testBundle.Data - actualData["system"] = map[string]interface{}{"bundle": map[string]interface{}{"manifest": map[string]interface{}{"revision": "", "roots": []interface{}{""}}}} + actualData["system"] = map[string]any{"bundle": map[string]any{"manifest": map[string]any{"revision": "", "roots": []any{""}}}} - if !reflect.DeepEqual(map[string]interface{}{"b": testBundle.Data}, loaded.Documents) { + if !reflect.DeepEqual(map[string]any{"b": testBundle.Data}, loaded.Documents) { t.Fatalf("Expected %v but got: %v", testBundle.Data, loaded.Documents) } @@ -890,8 +890,8 @@ func TestAsBundleWithFile(t *testing.T) { Roots: &[]string{"a", "b/c"}, Revision: "123", }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b": []int{4, 5, 6}, }, }, @@ -919,7 +919,7 @@ func TestAsBundleWithFile(t *testing.T) { t.Fatalf("Unexpected error: %s", err) } - var tmp interface{} = b + var tmp any = b err = util.RoundTrip(&tmp) if err != nil { t.Fatalf("Unexpected error: %s", err) @@ -1283,7 +1283,7 @@ func TestLoadRegos(t *testing.T) { }) } -func parseJSON(x string) interface{} { +func parseJSON(x string) any { return util.MustUnmarshalJSON([]byte(x)) } @@ -1385,7 +1385,7 @@ func TestSchemas(t *testing.T) { } else { key = ast.MustParseRef(k) } - var schema interface{} + var schema any err = util.Unmarshal([]byte(v), &schema) if err != nil { t.Fatalf("Unexpected error: %v", err) diff --git a/v1/logging/logging.go b/v1/logging/logging.go index 7a1edfb563..707854c5bc 100644 --- a/v1/logging/logging.go +++ b/v1/logging/logging.go @@ -24,12 +24,12 @@ const ( // Logger provides interface for OPA logger implementations type Logger interface { - Debug(fmt string, a ...interface{}) - Info(fmt string, a ...interface{}) - Error(fmt string, a ...interface{}) - Warn(fmt string, a ...interface{}) + Debug(fmt string, a ...any) + Info(fmt string, a ...any) + Error(fmt string, a ...any) + Warn(fmt string, a ...any) - WithFields(map[string]interface{}) Logger + WithFields(map[string]any) Logger GetLevel() Level SetLevel(Level) @@ -38,7 +38,7 @@ type Logger interface { // StandardLogger is the default OPA logger implementation. type StandardLogger struct { logger *logrus.Logger - fields map[string]interface{} + fields map[string]any } // New returns a new standard logger. @@ -68,9 +68,9 @@ func (l *StandardLogger) SetFormatter(formatter logrus.Formatter) { } // WithFields provides additional fields to include in log output -func (l *StandardLogger) WithFields(fields map[string]interface{}) Logger { +func (l *StandardLogger) WithFields(fields map[string]any) Logger { cp := *l - cp.fields = make(map[string]interface{}) + cp.fields = make(map[string]any) for k, v := range l.fields { cp.fields[k] = v } @@ -81,7 +81,7 @@ func (l *StandardLogger) WithFields(fields map[string]interface{}) Logger { } // getFields returns additional fields of this logger -func (l *StandardLogger) getFields() map[string]interface{} { +func (l *StandardLogger) getFields() map[string]any { return l.fields } @@ -126,7 +126,7 @@ func (l *StandardLogger) GetLevel() Level { } // Debug logs at debug level -func (l *StandardLogger) Debug(fmt string, a ...interface{}) { +func (l *StandardLogger) Debug(fmt string, a ...any) { if len(a) == 0 { l.logger.WithFields(l.getFields()).Debug(fmt) return @@ -135,7 +135,7 @@ func (l *StandardLogger) Debug(fmt string, a ...interface{}) { } // Info logs at info level -func (l *StandardLogger) Info(fmt string, a ...interface{}) { +func (l *StandardLogger) Info(fmt string, a ...any) { if len(a) == 0 { l.logger.WithFields(l.getFields()).Info(fmt) return @@ -144,7 +144,7 @@ func (l *StandardLogger) Info(fmt string, a ...interface{}) { } // Error logs at error level -func (l *StandardLogger) Error(fmt string, a ...interface{}) { +func (l *StandardLogger) Error(fmt string, a ...any) { if len(a) == 0 { l.logger.WithFields(l.getFields()).Error(fmt) return @@ -153,7 +153,7 @@ func (l *StandardLogger) Error(fmt string, a ...interface{}) { } // Warn logs at warn level -func (l *StandardLogger) Warn(fmt string, a ...interface{}) { +func (l *StandardLogger) Warn(fmt string, a ...any) { if len(a) == 0 { l.logger.WithFields(l.getFields()).Warn(fmt) return @@ -164,7 +164,7 @@ func (l *StandardLogger) Warn(fmt string, a ...interface{}) { // NoOpLogger logging implementation that does nothing type NoOpLogger struct { level Level - fields map[string]interface{} + fields map[string]any } // NewNoOpLogger instantiates new NoOpLogger @@ -176,23 +176,23 @@ func NewNoOpLogger() *NoOpLogger { // WithFields provides additional fields to include in log output. // Implemented here primarily to be able to switch between implementations without loss of data. -func (l *NoOpLogger) WithFields(fields map[string]interface{}) Logger { +func (l *NoOpLogger) WithFields(fields map[string]any) Logger { cp := *l cp.fields = fields return &cp } // Debug noop -func (*NoOpLogger) Debug(string, ...interface{}) {} +func (*NoOpLogger) Debug(string, ...any) {} // Info noop -func (*NoOpLogger) Info(string, ...interface{}) {} +func (*NoOpLogger) Info(string, ...any) {} // Error noop -func (*NoOpLogger) Error(string, ...interface{}) {} +func (*NoOpLogger) Error(string, ...any) {} // Warn noop -func (*NoOpLogger) Warn(string, ...interface{}) {} +func (*NoOpLogger) Warn(string, ...any) {} // SetLevel set log level func (l *NoOpLogger) SetLevel(level Level) { diff --git a/v1/logging/logging_test.go b/v1/logging/logging_test.go index 6738c578a2..120ef382e8 100644 --- a/v1/logging/logging_test.go +++ b/v1/logging/logging_test.go @@ -12,9 +12,9 @@ import ( ) func TestWithFields(t *testing.T) { - logger := New().WithFields(map[string]interface{}{"context": "contextvalue"}) + logger := New().WithFields(map[string]any{"context": "contextvalue"}) - var fieldvalue interface{} + var fieldvalue any var ok bool if fieldvalue, ok = logger.(*StandardLogger).fields["context"]; !ok { @@ -80,10 +80,10 @@ func TestNoFormattingForSingleString(t *testing.T) { func TestWithFieldsOverrides(t *testing.T) { logger := New(). - WithFields(map[string]interface{}{"context": "contextvalue"}). - WithFields(map[string]interface{}{"context": "changedcontextvalue"}) + WithFields(map[string]any{"context": "contextvalue"}). + WithFields(map[string]any{"context": "changedcontextvalue"}) - var fieldvalue interface{} + var fieldvalue any var ok bool if fieldvalue, ok = logger.(*StandardLogger).fields["context"]; !ok { @@ -97,10 +97,10 @@ func TestWithFieldsOverrides(t *testing.T) { func TestWithFieldsMerges(t *testing.T) { logger := New(). - WithFields(map[string]interface{}{"context": "contextvalue"}). - WithFields(map[string]interface{}{"anothercontext": "anothercontextvalue"}) + WithFields(map[string]any{"context": "contextvalue"}). + WithFields(map[string]any{"anothercontext": "anothercontextvalue"}) - var fieldvalue interface{} + var fieldvalue any var ok bool if fieldvalue, ok = logger.(*StandardLogger).fields["context"]; !ok { @@ -128,7 +128,7 @@ func TestRequestContextFields(t *testing.T) { ReqPath: "/test", }.Fields() - var fieldvalue interface{} + var fieldvalue any var ok bool if fieldvalue, ok = fields["client_addr"]; !ok { diff --git a/v1/logging/test/test.go b/v1/logging/test/test.go index 73588a2dcd..d216cdde87 100644 --- a/v1/logging/test/test.go +++ b/v1/logging/test/test.go @@ -10,14 +10,14 @@ import ( // LogEntry represents a log message. type LogEntry struct { Level logging.Level - Fields map[string]interface{} + Fields map[string]any Message string } // Logger implementation that buffers messages for test purposes. type Logger struct { level logging.Level - fields map[string]interface{} + fields map[string]any entries *[]LogEntry mtx *sync.Mutex } @@ -33,7 +33,7 @@ func New() *Logger { // WithFields provides additional fields to include in log output. // Implemented here primarily to be able to switch between implementations without loss of data. -func (l *Logger) WithFields(fields map[string]interface{}) logging.Logger { +func (l *Logger) WithFields(fields map[string]any) logging.Logger { l.mtx.Lock() defer l.mtx.Unlock() cp := Logger{ @@ -42,7 +42,7 @@ func (l *Logger) WithFields(fields map[string]interface{}) logging.Logger { fields: l.fields, mtx: l.mtx, } - flds := make(map[string]interface{}) + flds := make(map[string]any) for k, v := range cp.fields { flds[k] = v } @@ -54,22 +54,22 @@ func (l *Logger) WithFields(fields map[string]interface{}) logging.Logger { } // Debug buffers a log message. -func (l *Logger) Debug(f string, a ...interface{}) { +func (l *Logger) Debug(f string, a ...any) { l.append(logging.Debug, f, a...) } // Info buffers a log message. -func (l *Logger) Info(f string, a ...interface{}) { +func (l *Logger) Info(f string, a ...any) { l.append(logging.Info, f, a...) } // Error buffers a log message. -func (l *Logger) Error(f string, a ...interface{}) { +func (l *Logger) Error(f string, a ...any) { l.append(logging.Error, f, a...) } // Warn buffers a log message. -func (l *Logger) Warn(f string, a ...interface{}) { +func (l *Logger) Warn(f string, a ...any) { l.append(logging.Warn, f, a...) } @@ -90,7 +90,7 @@ func (l *Logger) Entries() []LogEntry { return *l.entries } -func (l *Logger) append(lvl logging.Level, f string, a ...interface{}) { +func (l *Logger) append(lvl logging.Level, f string, a ...any) { l.mtx.Lock() defer l.mtx.Unlock() *l.entries = append(*l.entries, LogEntry{ diff --git a/v1/metrics/metrics.go b/v1/metrics/metrics.go index f1038e8bcb..19d9c7d372 100644 --- a/v1/metrics/metrics.go +++ b/v1/metrics/metrics.go @@ -48,13 +48,13 @@ type Metrics interface { Timer(name string) Timer Histogram(name string) Histogram Counter(name string) Counter - All() map[string]interface{} + All() map[string]any Clear() json.Marshaler } type TimerMetrics interface { - Timers() map[string]interface{} + Timers() map[string]any } type metrics struct { @@ -73,7 +73,7 @@ func New() Metrics { type metric struct { Key string - Value interface{} + Value any } func (*metrics) Info() Info { @@ -144,10 +144,10 @@ func (m *metrics) Counter(name string) Counter { return c } -func (m *metrics) All() map[string]interface{} { +func (m *metrics) All() map[string]any { m.mtx.Lock() defer m.mtx.Unlock() - result := map[string]interface{}{} + result := map[string]any{} for name, timer := range m.timers { result[m.formatKey(name, timer)] = timer.Value() } @@ -160,10 +160,10 @@ func (m *metrics) All() map[string]interface{} { return result } -func (m *metrics) Timers() map[string]interface{} { +func (m *metrics) Timers() map[string]any { m.mtx.Lock() defer m.mtx.Unlock() - ts := map[string]interface{}{} + ts := map[string]any{} for n, t := range m.timers { ts[m.formatKey(n, t)] = t.Value() } @@ -178,7 +178,7 @@ func (m *metrics) Clear() { m.counters = map[string]Counter{} } -func (*metrics) formatKey(name string, metrics interface{}) string { +func (*metrics) formatKey(name string, metrics any) string { switch metrics.(type) { case Timer: return "timer_" + name + "_ns" @@ -194,7 +194,7 @@ func (*metrics) formatKey(name string, metrics interface{}) string { // Timer defines the interface for a restartable timer that accumulates elapsed // time. type Timer interface { - Value() interface{} + Value() any Int64() int64 Start() Stop() int64 @@ -220,7 +220,7 @@ func (t *timer) Stop() int64 { return delta } -func (t *timer) Value() interface{} { +func (t *timer) Value() any { return t.Int64() } @@ -232,7 +232,7 @@ func (t *timer) Int64() int64 { // Histogram defines the interface for a histogram with hardcoded percentiles. type Histogram interface { - Value() interface{} + Value() any Update(int64) } @@ -253,8 +253,8 @@ func (h *histogram) Update(v int64) { h.hist.Update(v) } -func (h *histogram) Value() interface{} { - values := map[string]interface{}{} +func (h *histogram) Value() any { + values := map[string]any{} snap := h.hist.Snapshot() percentiles := snap.Percentiles([]float64{ 0.5, @@ -282,7 +282,7 @@ func (h *histogram) Value() interface{} { // Counter defines the interface for a monotonic increasing counter. type Counter interface { - Value() interface{} + Value() any Incr() Add(n uint64) } @@ -299,11 +299,11 @@ func (c *counter) Add(n uint64) { atomic.AddUint64(&c.c, n) } -func (c *counter) Value() interface{} { +func (c *counter) Value() any { return atomic.LoadUint64(&c.c) } -func Statistics(num ...int64) interface{} { +func Statistics(num ...int64) any { t := newHistogram() for _, n := range num { t.Update(n) diff --git a/v1/plugins/bundle/plugin.go b/v1/plugins/bundle/plugin.go index 422dbe9626..fe65fda63f 100644 --- a/v1/plugins/bundle/plugin.go +++ b/v1/plugins/bundle/plugin.go @@ -57,11 +57,11 @@ type Loader interface { // Plugin implements bundle activation. type Plugin struct { config Config - manager *plugins.Manager // plugin manager for storage and service clients - status map[string]*Status // current status for each bundle - etags map[string]string // etag on last successful activation - listeners map[interface{}]func(Status) // listeners to send status updates to - bulkListeners map[interface{}]func(map[string]*Status) // listeners to send aggregated status updates to + manager *plugins.Manager // plugin manager for storage and service clients + status map[string]*Status // current status for each bundle + etags map[string]string // etag on last successful activation + listeners map[any]func(Status) // listeners to send status updates to + bulkListeners map[any]func(map[string]*Status) // listeners to send aggregated status updates to downloaders map[string]Loader logger logging.Logger mtx sync.Mutex @@ -149,7 +149,7 @@ func (p *Plugin) Stop(ctx context.Context) { // Reconfigure notifies the plugin that it's configuration has changed. // Any bundle configs that have changed or been added/removed will take // affect. -func (p *Plugin) Reconfigure(ctx context.Context, config interface{}) { +func (p *Plugin) Reconfigure(ctx context.Context, config any) { // Reconfiguring should not occur in parallel, lock to ensure // nothing swaps underneath us with the current p.config and the updated one. // Use p.cfgMtx instead of p.mtx to not block any bundle downloads/activations @@ -288,19 +288,19 @@ func (p *Plugin) Trigger(ctx context.Context) error { // Register a listener to receive status updates. The name must be comparable. // The listener will receive a status update for each bundle configured, they are // not going to be aggregated. For all status updates use `RegisterBulkListener`. -func (p *Plugin) Register(name interface{}, listener func(Status)) { +func (p *Plugin) Register(name any, listener func(Status)) { p.mtx.Lock() defer p.mtx.Unlock() if p.listeners == nil { - p.listeners = map[interface{}]func(Status){} + p.listeners = map[any]func(Status){} } p.listeners[name] = listener } // Unregister a listener to stop receiving status updates. -func (p *Plugin) Unregister(name interface{}) { +func (p *Plugin) Unregister(name any) { p.mtx.Lock() defer p.mtx.Unlock() @@ -308,19 +308,19 @@ func (p *Plugin) Unregister(name interface{}) { } // RegisterBulkListener registers a listener to receive bulk (aggregated) status updates. The name must be comparable. -func (p *Plugin) RegisterBulkListener(name interface{}, listener func(map[string]*Status)) { +func (p *Plugin) RegisterBulkListener(name any, listener func(map[string]*Status)) { p.mtx.Lock() defer p.mtx.Unlock() if p.bulkListeners == nil { - p.bulkListeners = map[interface{}]func(map[string]*Status){} + p.bulkListeners = map[any]func(map[string]*Status){} } p.bulkListeners[name] = listener } // UnregisterBulkListener unregisters a listener to stop receiving aggregated status updates. -func (p *Plugin) UnregisterBulkListener(name interface{}) { +func (p *Plugin) UnregisterBulkListener(name any) { p.mtx.Lock() defer p.mtx.Unlock() @@ -755,7 +755,7 @@ func (p *Plugin) log(name string) logging.Logger { if p.logger == nil { p.logger = logging.Get() } - return p.logger.WithFields(map[string]interface{}{"name": name, "plugin": Name}) + return p.logger.WithFields(map[string]any{"name": name, "plugin": Name}) } func (p *Plugin) getBundlePersistPath() (string, error) { diff --git a/v1/plugins/bundle/plugin_test.go b/v1/plugins/bundle/plugin_test.go index 9711397cb3..e58617aca0 100644 --- a/v1/plugins/bundle/plugin_test.go +++ b/v1/plugins/bundle/plugin_test.go @@ -62,7 +62,7 @@ func TestPluginOneShot(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { Path: "/foo/bar", @@ -134,7 +134,7 @@ func TestPluginOneShotWithAstStore(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Etag: "foo", } @@ -234,7 +234,7 @@ corge contains 1 if { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo/bar", @@ -482,7 +482,7 @@ corge contains 1 if { } b := bundle.Bundle{ Manifest: m, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo/bar", @@ -589,7 +589,7 @@ func TestPluginOneShotWithAuthzSchemaVerification(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "/authz.rego", @@ -639,7 +639,7 @@ func TestPluginOneShotWithAuthzSchemaVerification(t *testing.T) { b = bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "/authz.rego", @@ -748,7 +748,7 @@ func TestPluginOneShotWithAuthzSchemaVerificationNonDefaultAuthzPath(t *testing. b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "/authz.rego", @@ -777,7 +777,7 @@ func TestPluginOneShotWithAuthzSchemaVerificationNonDefaultAuthzPath(t *testing. // no authz policy b = bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo/bar", @@ -823,7 +823,7 @@ func TestPluginStartLazyLoadInMem(t *testing.T) { // setup fake http server with mock bundle mockBundle1 := bundle.Bundle{ - Data: map[string]interface{}{"p": "x1"}, + Data: map[string]any{"p": "x1"}, Modules: []bundle.ModuleFile{ { URL: "/bar/policy.rego", @@ -845,7 +845,7 @@ func TestPluginStartLazyLoadInMem(t *testing.T) { })) mockBundle2 := bundle.Bundle{ - Data: map[string]interface{}{"q": "x2"}, + Data: map[string]any{"q": "x2"}, Modules: []bundle.ModuleFile{}, Manifest: bundle.Manifest{ Roots: &[]string{"q"}, @@ -1011,7 +1011,7 @@ func TestPluginOneShotDiskStorageMetrics(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { Path: "/foo/bar", @@ -1110,8 +1110,8 @@ func TestPluginOneShotDeltaBundle(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"a"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "baz": "qux", }, }, @@ -1141,7 +1141,7 @@ func TestPluginOneShotDeltaBundle(t *testing.T) { p2 := bundle.PatchOperation{ Op: "upsert", Path: "/a/foo", - Value: []interface{}{"hello", "world"}, + Value: []any{"hello", "world"}, } b2 := bundle.Bundle{ @@ -1214,8 +1214,8 @@ func TestPluginOneShotDeltaBundleWithAstStore(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"a"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "baz": "qux", }, }, @@ -1245,7 +1245,7 @@ func TestPluginOneShotDeltaBundleWithAstStore(t *testing.T) { p2 := bundle.PatchOperation{ Op: "upsert", Path: "/a/foo", - Value: []interface{}{"hello", "world"}, + Value: []any{"hello", "world"}, } b2 := bundle.Bundle{ @@ -1423,7 +1423,7 @@ func TestPluginOneShotBundlePersistence(t *testing.T) { module := "package foo\n\ncorge=1" b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { URL: "/foo/bar.rego", @@ -1588,7 +1588,7 @@ corge contains 1 if { // download a bundle and persist to disk. Then verify the bundle persisted to disk b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { URL: "/foo/bar.rego", @@ -1881,7 +1881,7 @@ corge contains 1 if { } b := bundle.Bundle{ Manifest: m, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { URL: "/foo/bar.rego", @@ -2118,7 +2118,7 @@ func TestLoadAndActivateBundlesFromDisk(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { URL: "/foo/bar.rego", @@ -2203,7 +2203,7 @@ func TestLoadAndActivateBundlesFromDiskReservedChars(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { URL: "/foo/bar.rego", @@ -2425,7 +2425,7 @@ corge contains 2 if { // persist a bundle to disk and then load it b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), } for url, module := range update.modules { b.Modules = append(b.Modules, bundle.ModuleFile{ @@ -2648,7 +2648,7 @@ corge contains 1 if { } b := bundle.Bundle{ Manifest: m, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { URL: "/foo/bar.rego", @@ -2821,7 +2821,7 @@ is_one(x) if { b1 := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfauxbar", Roots: &[]string{"bar"}}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "/bar/policy.rego", @@ -2836,7 +2836,7 @@ is_one(x) if { b2 := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfauxfoo", Roots: &[]string{"foo"}}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "/foo/policy.rego", @@ -2915,7 +2915,7 @@ allow if { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"bar"}}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "/bar/policy.rego", @@ -2969,7 +2969,7 @@ import rego.v1 p contains x if { x = 1 }` b1 := &bundle.Bundle{ - Data: map[string]interface{}{"a": "b"}, + Data: map[string]any{"a": "b"}, Modules: []bundle.ModuleFile{ { Path: "/example.rego", @@ -2985,7 +2985,7 @@ p contains x if { x = 1 }` ensurePluginState(t, plugin, plugins.StateOK) b2 := &bundle.Bundle{ - Data: map[string]interface{}{"a": "b"}, + Data: map[string]any{"a": "b"}, Modules: []bundle.ModuleFile{ { Path: "/example2.rego", @@ -3017,7 +3017,7 @@ p contains x`), manager.Store.Abort(ctx, txn) b3 := &bundle.Bundle{ - Data: map[string]interface{}{"foo": map[string]interface{}{"p": "a"}}, + Data: map[string]any{"foo": map[string]any{"p": "a"}}, Modules: []bundle.ModuleFile{ { Path: "/example3.rego", @@ -3067,7 +3067,7 @@ func TestPluginOneShotHTTPError(t *testing.T) { module := "package foo\n\ncorge=1" b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(`{"foo": {"bar": 1, "baz": "qux"}}`)).(map[string]any), Modules: []bundle.ModuleFile{ { Path: "/foo/bar", @@ -3102,7 +3102,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) { p = 1` b1 := bundle.Bundle{ - Data: map[string]interface{}{ + Data: map[string]any{ "foo": "bar", }, Modules: []bundle.ModuleFile{ @@ -3124,7 +3124,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) { p = 2` b2 := bundle.Bundle{ - Data: map[string]interface{}{ + Data: map[string]any{ "baz": "qux", }, Modules: []bundle.ModuleFile{ @@ -3150,10 +3150,10 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) { } data, err := manager.Store.Read(ctx, txn, storage.Path{}) // remove system key to make comparison simpler - delete(data.(map[string]interface{}), "system") + delete(data.(map[string]any), "system") if err != nil { return err - } else if !reflect.DeepEqual(data, map[string]interface{}{"baz": "qux"}) { + } else if !reflect.DeepEqual(data, map[string]any{"baz": "qux"}) { return errors.New("expected updated data") } return nil @@ -3317,7 +3317,7 @@ p contains x if { x = 1 }` Manifest: bundle.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo.rego", @@ -3426,7 +3426,7 @@ func TestPluginListenerErrorClearedOn304(t *testing.T) { Manifest: bundle.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{"foo": "bar"}, + Data: map[string]any{"foo": "bar"}, } b.Manifest.Init() @@ -3497,7 +3497,7 @@ p contains x if { x = 1 }` Revision: "quickbrownfaux", Roots: &[]string{"gork"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo.rego", @@ -3616,7 +3616,7 @@ p contains x if { x = 1 }` Revision: "123", Roots: &[]string{"p1"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo1.rego", @@ -3695,7 +3695,7 @@ p contains x if { x = 1 }` Revision: "quickbrownfaux", Roots: &[]string{"gork"}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo.rego", @@ -3759,7 +3759,7 @@ func TestPluginActivateScopedBundle(t *testing.T) { // odd paths are raw JSON. if err := storage.Txn(ctx, manager.Store, storage.WriteParams, func(txn storage.Transaction) error { - externalData := map[string]interface{}{"a": map[string]interface{}{"a1": "x1", "a3": "x2", "a5": "x3"}} + externalData := map[string]any{"a": map[string]any{"a1": "x1", "a3": "x2", "a5": "x3"}} if err := manager.Store.Write(ctx, txn, storage.AddOp, storage.Path{}, externalData); err != nil { return err @@ -3782,8 +3782,8 @@ func TestPluginActivateScopedBundle(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"a/a1", "a/a2"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "a1": "foo", }, }, @@ -3803,7 +3803,7 @@ 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. exp := `{"a1": "foo", "a3": "x2", "a5": "x3"}` - var expData interface{} + var expData any if rm.readAst { expData = ast.MustParseTerm(exp).Value } else { @@ -3819,14 +3819,14 @@ func TestPluginActivateScopedBundle(t *testing.T) { b = bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux-2", Roots: &[]string{"a/a3", "a/a4"}, - Metadata: map[string]interface{}{ - "a": map[string]interface{}{ + Metadata: map[string]any{ + "a": map[string]any{ "a1": "deadbeef", }, }, }, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "a3": "foo", }, }, @@ -3851,8 +3851,8 @@ func TestPluginActivateScopedBundle(t *testing.T) { } 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"}, + map[string]any{ + "a": map[string]any{"a1": "deadbeef"}, }) // Upsert policy outside of bundle scope that depends on bundle. @@ -3864,7 +3864,7 @@ func TestPluginActivateScopedBundle(t *testing.T) { b = bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux-3", Roots: &[]string{"a/a3", "a/a4"}}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{}, } @@ -3875,8 +3875,8 @@ func TestPluginActivateScopedBundle(t *testing.T) { // still active. 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"}, + map[string]any{ + "a": map[string]any{"a1": "deadbeef"}, }) }) } @@ -3905,7 +3905,7 @@ func TestPluginSetCompilerOnContext(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux"}, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/test.rego", @@ -4563,8 +4563,8 @@ func TestUpgradeLegacyBundleToMuiltiBundleSameBundle(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"a/a1", "a/a2"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "a2": "foo", }, }, @@ -4684,8 +4684,8 @@ func TestUpgradeLegacyBundleToMultiBundleNewBundles(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"a/a1", "a/a2"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "a2": "foo", }, }, @@ -4728,8 +4728,8 @@ func TestUpgradeLegacyBundleToMultiBundleNewBundles(t *testing.T) { module = "package a.c\n\nbar=1" b = bundle.Bundle{ Manifest: bundle.Manifest{Revision: "b2-1", Roots: &[]string{"a/b2", "a/c"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "b2": "foo", }, }, @@ -4841,8 +4841,8 @@ func TestLegacyBundleDataRead(t *testing.T) { b := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"a/a1", "a/a2"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "a2": "foo", }, }, @@ -4864,7 +4864,7 @@ func TestLegacyBundleDataRead(t *testing.T) { plugin.oneShot(ctx, bundleName, download.Update{Bundle: &b}) exp := `{"a2": "foo"}` - var expData interface{} + var expData any if rm.readAst { expData = ast.MustParseTerm(exp).Value } else { @@ -4947,8 +4947,8 @@ func TestSaveBundleToDiskOverWrite(t *testing.T) { newBundle := bundle.Bundle{ Manifest: bundle.Manifest{Revision: "quickbrownfaux", Roots: &[]string{"a/a1", "a/a2"}}, - Data: map[string]interface{}{ - "a": map[string]interface{}{ + Data: map[string]any{ + "a": map[string]any{ "a2": "foo", }, }, @@ -5080,7 +5080,7 @@ p contains 1 if { Parsed: ast.MustParseModuleWithOpts(policy, popts), }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, } b.Manifest.Init() @@ -5185,7 +5185,7 @@ func TestPluginUsingFileLoader(t *testing.T) { test.WithTempFS(map[string]string{}, func(dir string) { b := bundle.Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "test.rego", @@ -5356,7 +5356,7 @@ p contains 7 if { test.WithTempFS(map[string]string{}, func(dir string) { b := bundle.Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "test.rego", @@ -5669,7 +5669,7 @@ p contains 7 if { manifest.SetRegoVersion(tc.bundleRegoVersion) b := bundle.Bundle{ Manifest: manifest, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { URL: "test.rego", @@ -6239,7 +6239,7 @@ func TestPluginReadBundleEtagFromDiskStore(t *testing.T) { // setup fake http server with mock bundle mockBundle := bundle.Bundle{ - Data: map[string]interface{}{"p": "x1"}, + Data: map[string]any{"p": "x1"}, Modules: []bundle.ModuleFile{}, } @@ -6418,21 +6418,21 @@ func TestPluginStateReconciliationOnReconfigure(t *testing.T) { // setup fake http server with mock bundle mockBundles := map[string]bundle.Bundle{ "b1": { - Data: map[string]interface{}{"b1": "x1"}, + Data: map[string]any{"b1": "x1"}, Modules: []bundle.ModuleFile{}, Manifest: bundle.Manifest{ Roots: &[]string{"b1"}, }, }, "b2": { - Data: map[string]interface{}{"b2": "x1"}, + Data: map[string]any{"b2": "x1"}, Modules: []bundle.ModuleFile{}, Manifest: bundle.Manifest{ Roots: &[]string{"b2"}, }, }, "b3_frequently_changing": { - Data: map[string]interface{}{"b3": "x1"}, + Data: map[string]any{"b3": "x1"}, Modules: []bundle.ModuleFile{}, Manifest: bundle.Manifest{ Roots: &[]string{"b3"}, @@ -6618,7 +6618,7 @@ func TestPluginManualTrigger(t *testing.T) { // setup fake http server with mock bundle mockBundle := bundle.Bundle{ - Data: map[string]interface{}{"p": "x1"}, + Data: map[string]any{"p": "x1"}, Modules: []bundle.ModuleFile{}, } @@ -6709,7 +6709,7 @@ func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) { // setup fake http server with mock bundle mockBundle1 := bundle.Bundle{ - Data: map[string]interface{}{"p": "x1"}, + Data: map[string]any{"p": "x1"}, Modules: []bundle.ModuleFile{ { URL: "/bar/policy.rego", @@ -6731,7 +6731,7 @@ func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) { })) mockBundle2 := bundle.Bundle{ - Data: map[string]interface{}{"q": "x2"}, + Data: map[string]any{"q": "x2"}, Modules: []bundle.ModuleFile{}, Manifest: bundle.Manifest{ Roots: &[]string{"q"}, @@ -6862,7 +6862,7 @@ func TestPluginManualTriggerMultiple(t *testing.T) { // setup fake http server with mock bundle mockBundle1 := bundle.Bundle{ - Data: map[string]interface{}{"p": "x1"}, + Data: map[string]any{"p": "x1"}, Modules: []bundle.ModuleFile{}, Manifest: bundle.Manifest{ Roots: &[]string{"p"}, @@ -6877,7 +6877,7 @@ func TestPluginManualTriggerMultiple(t *testing.T) { })) mockBundle2 := bundle.Bundle{ - Data: map[string]interface{}{"q": "x2"}, + Data: map[string]any{"q": "x2"}, Modules: []bundle.ModuleFile{}, Manifest: bundle.Manifest{ Roots: &[]string{"q"}, @@ -7271,7 +7271,7 @@ func getTestBundleWithData(roots []string, data []byte, modules []testModule) bu } if len(data) > 0 { - b.Data = util.MustUnmarshalJSON(data).(map[string]interface{}) + b.Data = util.MustUnmarshalJSON(data).(map[string]any) } for _, m := range modules { @@ -7354,7 +7354,7 @@ p contains x if { x = 1 }` Manifest: bundle.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: []bundle.ModuleFile{ { Path: "/foo.rego", @@ -7393,7 +7393,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 any, expIDs []string, expBundleName string, expBundleRev string, expMetadata map[string]any) { t.Helper() if err := storage.Txn(ctx, store, storage.TransactionParams{}, func(txn storage.Transaction) error { value, err := store.Read(ctx, txn, storage.MustParsePath(root)) diff --git a/v1/plugins/discovery/discovery.go b/v1/plugins/discovery/discovery.go index a061191567..117bb53df5 100644 --- a/v1/plugins/discovery/discovery.go +++ b/v1/plugins/discovery/discovery.go @@ -54,17 +54,17 @@ type Discovery struct { manager *plugins.Manager config *Config factories map[string]plugins.Factory - downloader bundle.Loader // discovery bundle downloader - status *bundle.Status // discovery status - listenersMtx sync.Mutex // lock for listener map - listeners map[interface{}]func(bundle.Status) // listeners for discovery update events - etag string // discovery bundle etag for caching purposes + downloader bundle.Loader // discovery bundle downloader + status *bundle.Status // discovery status + listenersMtx sync.Mutex // lock for listener map + listeners map[any]func(bundle.Status) // listeners for discovery update events + etag string // discovery bundle etag for caching purposes metrics metrics.Metrics readyOnce sync.Once logger logging.Logger bundlePersistPath string hooks hooks.Hooks - bootConfig map[string]interface{} + bootConfig map[string]any overriddenConfigKeys []string } @@ -89,7 +89,7 @@ func Hooks(hs hooks.Hooks) func(*Discovery) { } } -func BootConfig(bootConfig map[string]interface{}) func(*Discovery) { +func BootConfig(bootConfig map[string]any) func(*Discovery) { return func(d *Discovery) { d.bootConfig = bootConfig } @@ -141,7 +141,7 @@ func New(manager *plugins.Manager, opts ...func(*Discovery)) (*Discovery, error) Name: Name, } - result.logger = manager.Logger().WithFields(map[string]interface{}{"plugin": Name}) + result.logger = manager.Logger().WithFields(map[string]any{"plugin": Name}) manager.UpdatePluginStatus(Name, &plugins.Status{State: plugins.StateNotReady}) return result, nil @@ -177,7 +177,7 @@ func (c *Discovery) Stop(ctx context.Context) { } // Reconfigure is a no-op on discovery. -func (*Discovery) Reconfigure(context.Context, interface{}) { +func (*Discovery) Reconfigure(context.Context, any) { } // Lookup returns the discovery plugin registered with the manager. @@ -202,19 +202,19 @@ func (c *Discovery) Trigger(ctx context.Context) error { return c.downloader.Trigger(ctx) } -func (c *Discovery) RegisterListener(name interface{}, f func(bundle.Status)) { +func (c *Discovery) RegisterListener(name any, f func(bundle.Status)) { c.listenersMtx.Lock() defer c.listenersMtx.Unlock() if c.listeners == nil { - c.listeners = map[interface{}]func(bundle.Status){} + c.listeners = map[any]func(bundle.Status){} } c.listeners[name] = f } // Unregister a listener to stop receiving status updates. -func (c *Discovery) Unregister(name interface{}) { +func (c *Discovery) Unregister(name any) { c.listenersMtx.Lock() defer c.listenersMtx.Unlock() @@ -422,7 +422,7 @@ func (c *Discovery) applyLocalPluginConfigOverride(conf *config.Config) (*config return nil, nil, err } - var newConfig map[string]interface{} + var newConfig map[string]any err = util.Unmarshal(raw, &newConfig) if err != nil { return nil, nil, err @@ -574,14 +574,14 @@ type pluginSet struct { } type pluginreconfig struct { - Config interface{} + Config any Plugin plugins.Plugin } type pluginfactory struct { name string factory plugins.Factory - config interface{} + config any } func getPluginSet(factories map[string]plugins.Factory, manager *plugins.Manager, config *config.Config, m metrics.Metrics, trigger *plugins.TriggerMode) (*pluginSet, error) { @@ -743,7 +743,7 @@ func registerBundleStatusUpdates(m *plugins.Manager) { // mergeValuesAndListOverrides will merge source and destination map, preferring values from the source map. // It will also return a list of keys in the destination map which were overridden by those in the source map -func mergeValuesAndListOverrides(dest map[string]interface{}, src map[string]interface{}, prefix string) (map[string]interface{}, []string) { +func mergeValuesAndListOverrides(dest map[string]any, src map[string]any, prefix string) (map[string]any, []string) { overriddenKeys := []string{} for k, v := range src { @@ -758,7 +758,7 @@ func mergeValuesAndListOverrides(dest map[string]interface{}, src map[string]int fullKey = fmt.Sprintf("%v.%v", prefix, k) } - nextMap, ok := v.(map[string]interface{}) + nextMap, ok := v.(map[string]any) // If it isn't another map, overwrite the value if !ok { if !reflect.DeepEqual(dest[k], v) { @@ -768,7 +768,7 @@ func mergeValuesAndListOverrides(dest map[string]interface{}, src map[string]int continue } // Edge case: If the key exists in the destination, but isn't a map - destMap, isMap := dest[k].(map[string]interface{}) + destMap, isMap := dest[k].(map[string]any) // If the source map has a map for this key, prefer it if !isMap { dest[k] = v diff --git a/v1/plugins/discovery/discovery_test.go b/v1/plugins/discovery/discovery_test.go index 72b88e8905..464c68708a 100644 --- a/v1/plugins/discovery/discovery_test.go +++ b/v1/plugins/discovery/discovery_test.go @@ -71,10 +71,10 @@ func TestEvaluateBundle(t *testing.T) { Manifest: bundleApi.Manifest{ Revision: "quickbrownfaux", }, - Data: map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": map[string]interface{}{ - "status": map[string]interface{}{}, + Data: map[string]any{ + "foo": map[string]any{ + "bar": map[string]any{ + "status": map[string]any{}, }, }, }, @@ -468,10 +468,10 @@ func TestProcessBundleWithActiveConfig(t *testing.T) { assertConfig(t, actual, expectedConfig2) } -func assertConfig(t *testing.T, actualConfig interface{}, expectedConfig string) { +func assertConfig(t *testing.T, actualConfig any, expectedConfig string) { t.Helper() - var expected map[string]interface{} + var expected map[string]any if err := util.Unmarshal([]byte(expectedConfig), &expected); err != nil { t.Fatal(err) } @@ -485,11 +485,11 @@ type testFactory struct { p *reconfigureTestPlugin } -func (testFactory) Validate(*plugins.Manager, []byte) (interface{}, error) { +func (testFactory) Validate(*plugins.Manager, []byte) (any, error) { return nil, nil } -func (f testFactory) New(*plugins.Manager, interface{}) plugins.Plugin { +func (f testFactory) New(*plugins.Manager, any) plugins.Plugin { return f.p } @@ -505,7 +505,7 @@ func (r *reconfigureTestPlugin) Start(context.Context) error { func (*reconfigureTestPlugin) Stop(context.Context) { } -func (r *reconfigureTestPlugin) Reconfigure(_ context.Context, _ interface{}) { +func (r *reconfigureTestPlugin) Reconfigure(_ context.Context, _ any) { r.counts["reconfig"]++ } @@ -1733,7 +1733,7 @@ func TestReconfigureWithLocalOverride(t *testing.T) { t.Fatal(err) } - var bootConfig map[string]interface{} + var bootConfig map[string]any err = util.Unmarshal(bootConfigRaw, &bootConfig) if err != nil { t.Fatal(err) @@ -1966,7 +1966,7 @@ func TestReconfigureWithLocalOverride(t *testing.T) { disco.oneShot(ctx, download.Update{Bundle: serviceBundle}) - var dtConfig map[string]interface{} + var dtConfig map[string]any err = util.Unmarshal(manager.Config.DistributedTracing, &dtConfig) if err != nil { t.Fatal(err) @@ -1985,22 +1985,22 @@ func TestReconfigureWithLocalOverride(t *testing.T) { func TestMergeValuesAndListOverrides(t *testing.T) { tests := []struct { name string - dest map[string]interface{} - src map[string]interface{} - expected map[string]interface{} + dest map[string]any + src map[string]any + expected map[string]any override []string }{ { name: "Simple merge", - dest: map[string]interface{}{ + dest: map[string]any{ "a": 1, "b": 2, }, - src: map[string]interface{}{ + src: map[string]any{ "c": 3, "d": 4, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": 1, "b": 2, "c": 3, @@ -2010,27 +2010,27 @@ func TestMergeValuesAndListOverrides(t *testing.T) { }, { name: "Nested merge", - dest: map[string]interface{}{ + dest: map[string]any{ "a": 1, - "b": map[string]interface{}{ + "b": map[string]any{ "ba": 10, }, }, - src: map[string]interface{}{ - "b": map[string]interface{}{ + src: map[string]any{ + "b": map[string]any{ "bb": 20, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 30, }, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": 1, - "b": map[string]interface{}{ + "b": map[string]any{ "ba": 10, "bb": 20, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 30, }, }, @@ -2038,14 +2038,14 @@ func TestMergeValuesAndListOverrides(t *testing.T) { }, { name: "Simple Non-map override -1", - dest: map[string]interface{}{ - "a": []interface{}{"bar"}, + dest: map[string]any{ + "a": []any{"bar"}, "b": 2, }, - src: map[string]interface{}{ + src: map[string]any{ "a": 3, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": 3, "b": 2, }, @@ -2053,29 +2053,29 @@ func TestMergeValuesAndListOverrides(t *testing.T) { }, { name: "Simple Non-map override -2", - dest: map[string]interface{}{ + dest: map[string]any{ "a": 3, "b": 2, }, - src: map[string]interface{}{ - "a": []interface{}{"bar"}, + src: map[string]any{ + "a": []any{"bar"}, }, - expected: map[string]interface{}{ - "a": []interface{}{"bar"}, + expected: map[string]any{ + "a": []any{"bar"}, "b": 2, }, override: []string{"a"}, }, { name: "Non-map override -1", - dest: map[string]interface{}{ - "a": []interface{}{"bar"}, + dest: map[string]any{ + "a": []any{"bar"}, "b": 2, }, - src: map[string]interface{}{ + src: map[string]any{ "a": []string{"foo"}, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": []string{"foo"}, "b": 2, }, @@ -2083,33 +2083,33 @@ func TestMergeValuesAndListOverrides(t *testing.T) { }, { name: "Non-map override -2", - dest: map[string]interface{}{ - "a": map[string]interface{}{ + dest: map[string]any{ + "a": map[string]any{ "aa": 10, "ab": 20, }, "b": 2, }, - src: map[string]interface{}{ - "a": []interface{}{"foo"}, + src: map[string]any{ + "a": []any{"foo"}, }, - expected: map[string]interface{}{ - "a": []interface{}{"foo"}, + expected: map[string]any{ + "a": []any{"foo"}, "b": 2, }, override: []string{"a"}, }, { name: "Simple overridden keys", - dest: map[string]interface{}{ + dest: map[string]any{ "a": 1, "b": 2, }, - src: map[string]interface{}{ + src: map[string]any{ "b": 20, "c": 3, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": 1, "b": 20, "c": 3, @@ -2118,30 +2118,30 @@ func TestMergeValuesAndListOverrides(t *testing.T) { }, { name: "Nested overridden keys", - dest: map[string]interface{}{ + dest: map[string]any{ "a": 1, - "b": map[string]interface{}{ + "b": map[string]any{ "ba": 10, "bb": 20, }, }, - src: map[string]interface{}{ - "b": map[string]interface{}{ + src: map[string]any{ + "b": map[string]any{ "bb": 200, "bc": 300, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 30, }, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": 1, - "b": map[string]interface{}{ + "b": map[string]any{ "ba": 10, "bb": 200, "bc": 300, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 30, }, }, @@ -2149,36 +2149,36 @@ func TestMergeValuesAndListOverrides(t *testing.T) { }, { name: "Multiple Nested overridden keys", - dest: map[string]interface{}{ + dest: map[string]any{ "a": 1, - "b": map[string]interface{}{ + "b": map[string]any{ "ba": 10, "bb": 20, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 10, "cb": 20, "cc": 30, }, }, - src: map[string]interface{}{ - "b": map[string]interface{}{ + src: map[string]any{ + "b": map[string]any{ "bb": 200, "bc": 300, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 300, "cd": 400, }, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": 1, - "b": map[string]interface{}{ + "b": map[string]any{ "ba": 10, "bb": 200, "bc": 300, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 300, "cb": 20, "cc": 30, @@ -2189,27 +2189,27 @@ func TestMergeValuesAndListOverrides(t *testing.T) { }, { name: "Nested overridden keys - 2", - dest: map[string]interface{}{ + dest: map[string]any{ "a": 1, - "b": map[string]interface{}{ - "ba": map[string]interface{}{"bba": "1"}, + "b": map[string]any{ + "ba": map[string]any{"bba": "1"}, }, "c": 2, }, - src: map[string]interface{}{ - "b": map[string]interface{}{ - "ba": map[string]interface{}{"bba": "2"}, + src: map[string]any{ + "b": map[string]any{ + "ba": map[string]any{"bba": "2"}, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 30, }, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": 1, - "b": map[string]interface{}{ - "ba": map[string]interface{}{"bba": "2"}, + "b": map[string]any{ + "ba": map[string]any{"bba": "2"}, }, - "c": map[string]interface{}{ + "c": map[string]any{ "ca": 30, }, }, @@ -2275,7 +2275,7 @@ func TestReconfigureWithUpdates(t *testing.T) { t.Fatal(err) } - var bootConfig map[string]interface{} + var bootConfig map[string]any err = util.Unmarshal(bootConfigRaw, &bootConfig) if err != nil { t.Fatal(err) @@ -2827,16 +2827,16 @@ func TestStatusUpdatesFromPersistedBundlesDontDelayBoot(t *testing.T) { // write the disco bundle to disk discoBundle := bundleApi.Bundle{ - Data: map[string]interface{}{ - "discovery": map[string]interface{}{ - "bundles": map[string]interface{}{ - "main": map[string]interface{}{ + Data: map[string]any{ + "discovery": map[string]any{ + "bundles": map[string]any{ + "main": map[string]any{ "persist": true, "resource": "/bundle", "service": "localhost", }, }, - "status": map[string]interface{}{ + "status": map[string]any{ "service": "localhost", }, }, @@ -2862,7 +2862,7 @@ func TestStatusUpdatesFromPersistedBundlesDontDelayBoot(t *testing.T) { // write an example data bundle ('main') to disk mainBundle := bundleApi.Bundle{ - Data: map[string]interface{}{ + Data: map[string]any{ "foo": "bar", }, } @@ -3063,8 +3063,8 @@ func TestStatusMetricsForLogDrops(t *testing.T) { t.Fatal("Expected decision log plugin registered on manager") } - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false event1 := &server.Info{ DecisionID: "abc", @@ -3115,8 +3115,8 @@ func TestStatusMetricsForLogDrops(t *testing.T) { t.Fatal("Expected metrics") } - builtInMet := e.Fields["metrics"].(map[string]interface{})[""] - dropCount := builtInMet.(map[string]interface{})["counter_decision_logs_dropped_rate_limit_exceeded"] + builtInMet := e.Fields["metrics"].(map[string]any)[""] + dropCount := builtInMet.(map[string]any)["counter_decision_logs_dropped_rate_limit_exceeded"] actual, err := dropCount.(json.Number).Int64() if err != nil { @@ -3133,7 +3133,7 @@ func TestStatusMetricsForLogDrops(t *testing.T) { func makeDataBundle(n int, s string) *bundleApi.Bundle { return &bundleApi.Bundle{ Manifest: bundleApi.Manifest{Revision: fmt.Sprintf("test-revision-%v", n)}, - Data: util.MustUnmarshalJSON([]byte(s)).(map[string]interface{}), + Data: util.MustUnmarshalJSON([]byte(s)).(map[string]any), } } @@ -3148,7 +3148,7 @@ func makeModuleBundle(n int, s string, popts ast.ParserOptions) *bundleApi.Bundl Parsed: ast.MustParseModuleWithOpts(s, popts), }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, } } @@ -3172,7 +3172,7 @@ func makeModuleBundleWithRegoVersion(revision int, bundle string, regoVersion in Parsed: ast.MustParseModuleWithOpts(bundle, popts), }, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, } } @@ -3188,7 +3188,7 @@ func makeBundleWithRegoVersion(revision int, bundleRegoVersion int, modules map[ RegoVersion: &bundleRegoVersion, FileRegoVersions: map[string]int{}, }, - Data: map[string]interface{}{}, + Data: map[string]any{}, } for k, v := range modules { @@ -3694,8 +3694,8 @@ func TestPluginManualTriggerLifecycle(t *testing.T) { } // trigger the bundle plugin - fixture.server.bundleData = map[string]interface{}{ - "foo": map[string]interface{}{ + fixture.server.bundleData = map[string]any{ + "foo": map[string]any{ "bar": "hello", }, } @@ -3795,8 +3795,8 @@ func TestPluginManualTriggerLifecycle(t *testing.T) { } // check for error in the last update corresponding to the bad service bundle config - disco, _ := fixture.server.statusEvent[2].(map[string]interface{}) - errMsg := disco["discovery"].(map[string]interface{})["message"] + disco, _ := fixture.server.statusEvent[2].(map[string]any) + errMsg := disco["discovery"].(map[string]any)["message"] expErrMsg := "invalid configuration for bundle \"authz\": trigger mode mismatch: manual and periodic (hint: check discovery configuration)" if errMsg != expErrMsg { @@ -3869,7 +3869,7 @@ type testFixture struct { func newTestFixture(t *testing.T) *testFixture { ts := testFixtureServer{ t: t, - statusEvent: []interface{}{}, + statusEvent: []any{}, logEvent: []logs.EventV1{}, } @@ -3948,7 +3948,7 @@ func (t *testFixture) loop(ctx context.Context) { } } -func (t *testFixture) runQuery(ctx context.Context, query string, m metrics.Metrics) (interface{}, error) { +func (t *testFixture) runQuery(ctx context.Context, query string, m metrics.Metrics) (any, error) { r := rego.New( rego.Query(query), rego.Store(t.manager.Store), @@ -3968,7 +3968,7 @@ func (t *testFixture) runQuery(ctx context.Context, query string, m metrics.Metr return rs[0].Expressions[0].Value, nil } -func (t *testFixture) log(ctx context.Context, query string, m metrics.Metrics, result *interface{}) error { +func (t *testFixture) log(ctx context.Context, query string, m metrics.Metrics, result *any) error { record := server.Info{ Timestamp: time.Now(), @@ -3986,8 +3986,8 @@ func (t *testFixture) log(ctx context.Context, query string, m metrics.Metrics, } func (t *testFixture) testServiceBundleUpdateScenario(ctx context.Context, m metrics.Metrics) { - t.server.bundleData = map[string]interface{}{ - "foo": map[string]interface{}{ + t.server.bundleData = map[string]any{ + "foo": map[string]any{ "bar": "world", }, } @@ -4040,8 +4040,8 @@ func (t *testFixture) testServiceBundleUpdateScenario(ctx context.Context, m met } // verify the updated bundle revision in the last status update - bundles, _ := t.server.statusEvent[1].(map[string]interface{}) - actual := bundles["bundles"].(map[string]interface{})["authz"].(map[string]interface{})["active_revision"] + bundles, _ := t.server.statusEvent[1].(map[string]any) + actual := bundles["bundles"].(map[string]any)["authz"].(map[string]any)["active_revision"] if actual != t.server.bundleRevision { t.server.t.Fatalf("Expected revision %v but got %v", t.server.bundleRevision, actual) @@ -4071,8 +4071,8 @@ func (t *testFixture) testDiscoReconfigurationScenario(ctx context.Context, m me <-trigger // trigger the bundle plugin - t.server.bundleData = map[string]interface{}{ - "bux": map[string]interface{}{ + t.server.bundleData = map[string]any{ + "bux": map[string]any{ "qux": "hello again!", }, } @@ -4104,15 +4104,15 @@ func (t *testFixture) testDiscoReconfigurationScenario(ctx context.Context, m me } // verify the updated discovery and service bundle revisions in the last status update - bundles, _ := t.server.statusEvent[3].(map[string]interface{}) - actual := bundles["bundles"].(map[string]interface{})["authz"].(map[string]interface{})["active_revision"] + bundles, _ := t.server.statusEvent[3].(map[string]any) + actual := bundles["bundles"].(map[string]any)["authz"].(map[string]any)["active_revision"] if actual != t.server.bundleRevision { t.server.t.Fatalf("Expected revision %v but got %v", t.server.bundleRevision, actual) } - disco, _ := t.server.statusEvent[3].(map[string]interface{}) - actual = disco["discovery"].(map[string]interface{})["active_revision"] + disco, _ := t.server.statusEvent[3].(map[string]any) + actual = disco["discovery"].(map[string]any)["active_revision"] expectedRev := fmt.Sprintf("test-revision-%v", t.server.dicsoBundleRev) if actual != expectedRev { @@ -4133,9 +4133,9 @@ type testFixtureServer struct { server *httptest.Server discoConfig string dicsoBundleRev int - bundleData map[string]interface{} + bundleData map[string]any bundleRevision string - statusEvent []interface{} + statusEvent []any logEvent []logs.EventV1 } @@ -4163,7 +4163,7 @@ func (t *testFixtureServer) handle(w http.ResponseWriter, r *http.Request) { } } else if r.URL.Path == "/status" || r.URL.Path == "/status/new" { - var event interface{} + var event any if err := util.NewJSONDecoder(r.Body).Decode(&event); err != nil { t.t.Fatal(err) diff --git a/v1/plugins/logs/encoder_test.go b/v1/plugins/logs/encoder_test.go index 445d9cabbb..0c33e5051f 100644 --- a/v1/plugins/logs/encoder_test.go +++ b/v1/plugins/logs/encoder_test.go @@ -15,8 +15,8 @@ import ( func TestChunkEncoder(t *testing.T) { enc := newChunkEncoder(1000) - var result interface{} = false - var expInput interface{} = map[string]interface{}{"method": "GET"} + var result any = false + var expInput any = map[string]any{"method": "GET"} ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { panic(err) @@ -55,8 +55,8 @@ func TestChunkEncoder(t *testing.T) { func TestChunkEncoderSizeLimit(t *testing.T) { enc := newChunkEncoder(1).WithMetrics(metrics.New()) - var result interface{} = false - var expInput interface{} = map[string]interface{}{"method": "GET"} + var result any = false + var expInput any = map[string]any{"method": "GET"} ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { t.Fatal(err) @@ -86,8 +86,8 @@ func TestChunkEncoderSizeLimit(t *testing.T) { func TestChunkEncoderAdaptive(t *testing.T) { enc := newChunkEncoder(1000).WithMetrics(metrics.New()) - var result interface{} = false - var expInput interface{} = map[string]interface{}{"method": "GET"} + var result any = false + var expInput any = map[string]any{"method": "GET"} ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { panic(err) diff --git a/v1/plugins/logs/eventBuffer.go b/v1/plugins/logs/eventBuffer.go index c4e3dfa264..3546120831 100644 --- a/v1/plugins/logs/eventBuffer.go +++ b/v1/plugins/logs/eventBuffer.go @@ -57,7 +57,7 @@ func (b *eventBuffer) incrMetric(name string) { } } -func (b *eventBuffer) logError(fmt string, a ...interface{}) { +func (b *eventBuffer) logError(fmt string, a ...any) { if b.logger != nil { b.logger.Error(fmt, a) } diff --git a/v1/plugins/logs/eventBuffer_test.go b/v1/plugins/logs/eventBuffer_test.go index 193ab79656..9159dbd00d 100644 --- a/v1/plugins/logs/eventBuffer_test.go +++ b/v1/plugins/logs/eventBuffer_test.go @@ -182,8 +182,8 @@ func TestEventBuffer_Upload(t *testing.T) { } func newTestEvent(t *testing.T, id string, enableNDCache bool) *EventV1 { - var result interface{} = false - var expInput interface{} = map[string]interface{}{"method": "GET"} + var result any = false + var expInput any = map[string]any{"method": "GET"} timestamp, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { t.Fatal(err) diff --git a/v1/plugins/logs/mask.go b/v1/plugins/logs/mask.go index 8a03e1f1f7..ec28c0eb66 100644 --- a/v1/plugins/logs/mask.go +++ b/v1/plugins/logs/mask.go @@ -28,9 +28,9 @@ const ( var errMaskInvalidObject = errors.New("mask upsert invalid object") type maskRule struct { - OP maskOP `json:"op"` - Path string `json:"path"` - Value interface{} `json:"value"` + OP maskOP `json:"op"` + Path string `json:"path"` + Value any `json:"value"` escapedParts []string modifyFullObj bool failUndefinedPath bool @@ -110,7 +110,7 @@ func withOP(op maskOP) maskRuleOption { } } -func withValue(val interface{}) maskRuleOption { +func withValue(val any) maskRuleOption { return func(r *maskRule) error { r.Value = val return nil @@ -125,8 +125,8 @@ func withFailUndefinedPath() maskRuleOption { } func (r maskRule) Mask(event *EventV1) error { - var maskObj *interface{} // pointer to event Input|Result|NDBCache object - var maskObjPtr **interface{} // pointer to the event Input|Result|NDBCache pointer itself + var maskObj *any // pointer to event Input|Result|NDBCache object + var maskObjPtr **any // pointer to the event Input|Result|NDBCache pointer itself switch p := r.escapedParts[0]; p { case partInput: @@ -179,7 +179,7 @@ func (r maskRule) Mask(event *EventV1) error { if r.modifyFullObj { *maskObjPtr = &r.Value } else { - inputObj, ok := (*maskObj).(map[string]interface{}) + inputObj, ok := (*maskObj).(map[string]any) if !ok { return nil } @@ -201,7 +201,7 @@ func (r maskRule) Mask(event *EventV1) error { return nil } -func (maskRule) removeValue(p []string, node interface{}) error { +func (maskRule) removeValue(p []string, node any) error { if len(p) == 0 { return nil } @@ -211,7 +211,7 @@ func (maskRule) removeValue(p []string, node interface{}) error { // nodeParent stores the parent of the node to be modified during the // removal, this is only needed when the node is a slice - var nodeParent interface{} + var nodeParent any // nodeKey stores the key of the node to be modified relative to the parent var nodeKey string @@ -219,7 +219,7 @@ func (maskRule) removeValue(p []string, node interface{}) error { // support removing of slice values for i := range len(p) - 1 { switch v := node.(type) { - case map[string]interface{}: + case map[string]any: child, ok := v[p[i]] if !ok { return errMaskInvalidObject @@ -228,7 +228,7 @@ func (maskRule) removeValue(p []string, node interface{}) error { nodeKey = p[i] node = child - case []interface{}: + case []any: index, err := strconv.Atoi(p[i]) if err != nil || index < 0 || index >= len(v) { return errMaskInvalidObject @@ -243,14 +243,14 @@ func (maskRule) removeValue(p []string, node interface{}) error { } switch v := node.(type) { - case map[string]interface{}: + case map[string]any: if _, ok := v[targetKey]; !ok { return errMaskInvalidObject } delete(v, targetKey) - case []interface{}: + case []any: // first, check the targetKey is a valid index targetIndex, err := strconv.Atoi(targetKey) if err != nil || targetIndex < 0 || targetIndex >= len(v) { @@ -258,7 +258,7 @@ func (maskRule) removeValue(p []string, node interface{}) error { } switch nodeParent := nodeParent.(type) { - case []interface{}: + case []any: // update the target's grandparent slice with a new slice index, err := strconv.Atoi(nodeKey) if err != nil { @@ -267,7 +267,7 @@ func (maskRule) removeValue(p []string, node interface{}) error { nodeParent[index] = append(v[:targetIndex], v[targetIndex+1:]...) - case map[string]interface{}: + case map[string]any: nodeParent[nodeKey] = append(v[:targetIndex], v[targetIndex+1:]...) default: @@ -281,23 +281,23 @@ func (maskRule) removeValue(p []string, node interface{}) error { return nil } -func (maskRule) mkdirp(node interface{}, path []string, value interface{}) error { +func (maskRule) mkdirp(node any, path []string, value any) error { if len(path) == 0 { return nil } for i := range len(path) - 1 { switch v := node.(type) { - case map[string]interface{}: + case map[string]any: child, ok := v[path[i]] if !ok { - child = map[string]interface{}{} + child = map[string]any{} v[path[i]] = child } node = child - case []interface{}: + case []any: idx, err := strconv.Atoi(path[i]) if err != nil || idx < 0 { return errMaskInvalidObject @@ -315,10 +315,10 @@ func (maskRule) mkdirp(node interface{}, path []string, value interface{}) error } switch v := node.(type) { - case map[string]interface{}: + case map[string]any: v[path[len(path)-1]] = value - case []interface{}: + case []any: idx, err := strconv.Atoi(path[len(path)-1]) if err != nil || idx < 0 || idx >= len(v) { return errMaskInvalidObject @@ -332,11 +332,11 @@ func (maskRule) mkdirp(node interface{}, path []string, value interface{}) error return nil } -func newMaskRuleSet(rv interface{}, onRuleError func(*maskRule, error)) (*maskRuleSet, error) { +func newMaskRuleSet(rv any, onRuleError func(*maskRule, error)) (*maskRuleSet, error) { mRuleSet := &maskRuleSet{ OnRuleError: onRuleError, } - rawRules, ok := rv.([]interface{}) + rawRules, ok := rv.([]any) if !ok { return nil, fmt.Errorf("unexpected rule format %v (%[1]T)", rv) } @@ -354,7 +354,7 @@ func newMaskRuleSet(rv interface{}, onRuleError func(*maskRule, error)) (*maskRu mRuleSet.Rules = append(mRuleSet.Rules, rule) - case map[string]interface{}: + case map[string]any: rule := &maskRule{} op, set := getString(v, "op") if set && op == "" { diff --git a/v1/plugins/logs/mask_test.go b/v1/plugins/logs/mask_test.go index e9ad0a1311..5a24533039 100644 --- a/v1/plugins/logs/mask_test.go +++ b/v1/plugins/logs/mask_test.go @@ -654,18 +654,18 @@ func TestMaskRuleMask(t *testing.T) { func TestNewMaskRuleSet(t *testing.T) { tests := []struct { note string - value interface{} + value any exp *maskRuleSet err error }{ { - note: "invalid format: not []interface{}", + note: "invalid format: not []any", value: map[string]int{"invalid": 1}, err: errors.New("unexpected rule format map[invalid:1] (map[string]int)"), }, { - note: "invalid format: nested type not string or map[string]interface{}", - value: []interface{}{ + note: "invalid format: nested type not string or map[string]any", + value: []any{ []int{1, 2}, }, err: errors.New("invalid mask rule format encountered: []int"), diff --git a/v1/plugins/logs/plugin.go b/v1/plugins/logs/plugin.go index 5893afee1c..3d2150c49a 100644 --- a/v1/plugins/logs/plugin.go +++ b/v1/plugins/logs/plugin.go @@ -55,16 +55,16 @@ type EventV1 struct { Bundles map[string]BundleInfoV1 `json:"bundles,omitempty"` Path string `json:"path,omitempty"` Query string `json:"query,omitempty"` - Input *interface{} `json:"input,omitempty"` - Result *interface{} `json:"result,omitempty"` - MappedResult *interface{} `json:"mapped_result,omitempty"` - NDBuiltinCache *interface{} `json:"nd_builtin_cache,omitempty"` + Input *any `json:"input,omitempty"` + Result *any `json:"result,omitempty"` + MappedResult *any `json:"mapped_result,omitempty"` + NDBuiltinCache *any `json:"nd_builtin_cache,omitempty"` Erased []string `json:"erased,omitempty"` Masked []string `json:"masked,omitempty"` Error error `json:"error,omitempty"` RequestedBy string `json:"requested_by,omitempty"` Timestamp time.Time `json:"timestamp"` - Metrics map[string]interface{} `json:"metrics,omitempty"` + Metrics map[string]any `json:"metrics,omitempty"` RequestID uint64 `json:"req_id,omitempty"` RequestContext *RequestContext `json:"request_context,omitempty"` @@ -236,10 +236,10 @@ func (e *EventV1) AST() (ast.Value, error) { return event, nil } -func roundtripJSONToAST(x interface{}) (ast.Value, error) { +func roundtripJSONToAST(x any) (ast.Value, error) { rawPtr := util.Reference(x) // roundtrip through json: this turns slices (e.g. []string, []bool) into - // []interface{}, the only array type ast.InterfaceToValue can work with + // []any, the only array type ast.InterfaceToValue can work with if err := util.RoundTrip(rawPtr); err != nil { return nil, err } @@ -490,7 +490,7 @@ func (po *prepareOnce) prepareOnce(f func() (*rego.PreparedEvalQuery, error)) (* } type reconfigure struct { - config interface{} + config any done chan struct{} } @@ -575,7 +575,7 @@ func New(parsedConfig *Config, manager *plugins.Manager) *Plugin { stop: make(chan chan struct{}), enc: newChunkEncoder(*parsedConfig.Reporting.UploadSizeLimitBytes), reconfig: make(chan reconfigure), - logger: manager.Logger().WithFields(map[string]interface{}{"plugin": Name}), + logger: manager.Logger().WithFields(map[string]any{"plugin": Name}), status: &lstat.Status{}, preparedDrop: *newPrepareOnce(), preparedMask: *newPrepareOnce(), @@ -777,7 +777,7 @@ func (p *Plugin) Log(ctx context.Context, decision *server.Info) error { } // Reconfigure notifies the plugin with a new configuration. -func (p *Plugin) Reconfigure(_ context.Context, config interface{}) { +func (p *Plugin) Reconfigure(_ context.Context, config any) { done := make(chan struct{}) p.reconfig <- reconfigure{config: config, done: done} @@ -956,7 +956,7 @@ func (p *Plugin) oneShot(ctx context.Context) error { return err } -func (p *Plugin) reconfigure(ctx context.Context, config interface{}) { +func (p *Plugin) reconfigure(ctx context.Context, config any) { newConfig := config.(*Config) if reflect.DeepEqual(p.config, *newConfig) { @@ -1205,12 +1205,12 @@ func (p *Plugin) logEvent(event EventV1) error { if err != nil { return err } - fields := map[string]interface{}{} + fields := map[string]any{} err = util.UnmarshalJSON(eventBuf, &fields) if err != nil { return err } - p.manager.ConsoleLogger().WithFields(fields).WithFields(map[string]interface{}{ + p.manager.ConsoleLogger().WithFields(fields).WithFields(map[string]any{ "type": "openpolicyagent.org/decision_logs", }).Info("Decision Log") return nil diff --git a/v1/plugins/logs/plugin_test.go b/v1/plugins/logs/plugin_test.go index dd3820e9e2..f567fc8e97 100644 --- a/v1/plugins/logs/plugin_test.go +++ b/v1/plugins/logs/plugin_test.go @@ -56,7 +56,7 @@ func (p *testPlugin) Start(context.Context) error { func (p *testPlugin) Stop(context.Context) { } -func (p *testPlugin) Reconfigure(context.Context, interface{}) { +func (p *testPlugin) Reconfigure(context.Context, any) { } func (p *testPlugin) Log(_ context.Context, event EventV1) error { @@ -107,10 +107,10 @@ func TestPluginCustomBackendAndHTTPServiceAndConsole(t *testing.T) { fixture := newTestFixture(t, testFixtureOptions{ ConsoleLogger: testLogger, - ExtraManagerConfig: map[string]interface{}{ - "plugins": map[string]interface{}{"test_plugin": struct{}{}}, + ExtraManagerConfig: map[string]any{ + "plugins": map[string]any{"test_plugin": struct{}{}}, }, - ExtraConfig: map[string]interface{}{ + ExtraConfig: map[string]any{ "plugin": "test_plugin", "console": true, }, @@ -409,7 +409,7 @@ func TestPluginStartSameInput(t *testing.T) { defer fixture.server.stop() fixture.server.ch = make(chan []EventV1, 3) - var result interface{} = false + var result any = false ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { @@ -418,7 +418,7 @@ func TestPluginStartSameInput(t *testing.T) { testMetrics := getWellKnownMetrics() - var input interface{} = map[string]interface{}{"method": "GET"} + var input any = map[string]any{"method": "GET"} for i := 0; i < 400; i++ { fixture.plugin.Log(ctx, &server.Info{ @@ -449,9 +449,9 @@ func TestPluginStartSameInput(t *testing.T) { t.Fatalf("Expected chunk lens %v, %v, and %v but got: %v, %v, and %v", expLen1, expLen2, expLen3, len(chunk1), len(chunk2), len(chunk3)) } - var expInput interface{} = map[string]interface{}{"method": "GET"} + var expInput any = map[string]any{"method": "GET"} - msAsFloat64 := map[string]interface{}{} + msAsFloat64 := map[string]any{} for k, v := range testMetrics.All() { msAsFloat64[k] = float64(v.(uint64)) } @@ -490,17 +490,17 @@ func TestPluginStartChangingInputValues(t *testing.T) { defer fixture.server.stop() fixture.server.ch = make(chan []EventV1, 3) - var result interface{} = false + var result any = false ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { panic(err) } - var input interface{} + var input any for i := 0; i < 400; i++ { - input = map[string]interface{}{"method": getValueForMethod(i), "path": getValueForPath(i), "user": getValueForUser(i)} + input = map[string]any{"method": getValueForMethod(i), "path": getValueForPath(i), "user": getValueForUser(i)} fixture.plugin.Log(ctx, &server.Info{ Revision: fmt.Sprint(i), @@ -558,14 +558,14 @@ func TestPluginStartChangingInputKeysAndValues(t *testing.T) { defer fixture.server.stop() fixture.server.ch = make(chan []EventV1, 5) - var result interface{} = false + var result any = false ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { panic(err) } - var input interface{} + var input any for i := 0; i < 250; i++ { input = generateInputMap(i) @@ -635,8 +635,8 @@ func TestPluginRequeue(t *testing.T) { fixture.server.ch = make(chan []EventV1, 1) - var input interface{} = map[string]interface{}{"method": "GET"} - var result1 interface{} = false + var input any = map[string]any{"method": "GET"} + var result1 any = false if err := fixture.plugin.Log(ctx, &server.Info{ DecisionID: "abc", @@ -699,8 +699,8 @@ func TestPluginRequeueBufferPreserved(t *testing.T) { fixture.server.ch = make(chan []EventV1, 3) - var input interface{} = map[string]interface{}{"method": "GET"} - var result1 interface{} = false + var input any = map[string]any{"method": "GET"} + var result1 any = false _ = fixture.plugin.Log(ctx, logServerInfo("abc", input, result1)) _ = fixture.plugin.Log(ctx, logServerInfo("def", input, result1)) @@ -758,8 +758,8 @@ func TestPluginRateLimitInt(t *testing.T) { }) defer fixture.server.stop() - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false eventSize := 218 event1 := &server.Info{ @@ -914,8 +914,8 @@ func TestPluginRateLimitFloat(t *testing.T) { }) defer fixture.server.stop() - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false eventSize := 218 event1 := &server.Info{ @@ -1068,7 +1068,7 @@ func TestPluginStatusUpdateHTTPError(t *testing.T) { fixture.server.ch = make(chan []EventV1, 3) - input := map[string]interface{}{"method": "GET"} + input := map[string]any{"method": "GET"} var result1 bool if err := fixture.plugin.Log(ctx, logServerInfo("abc", input, result1)); err != nil { @@ -1128,8 +1128,8 @@ func TestPluginStatusUpdateEncodingFailure(t *testing.T) { fixture.plugin.metrics = m fixture.plugin.enc.metrics = m - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false event := &server.Info{ DecisionID: "abc", @@ -1189,7 +1189,7 @@ func TestPluginStatusUpdateEncodingFailure(t *testing.T) { fmt.Println(e.Fields["metrics"]) - exp := map[string]interface{}{"": map[string]interface{}{"counter_decision_logs_encoding_failure": json.Number("1"), + exp := map[string]any{"": map[string]any{"counter_decision_logs_encoding_failure": json.Number("1"), "counter_enc_log_exceeded_upload_size_limit_bytes": json.Number("1")}} if !reflect.DeepEqual(e.Fields["metrics"], exp) { @@ -1219,8 +1219,8 @@ func TestPluginStatusUpdateBufferSizeExceeded(t *testing.T) { fixture.plugin.metrics = metrics.New() - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false event1 := &server.Info{ DecisionID: "abc", @@ -1306,7 +1306,7 @@ func TestPluginStatusUpdateBufferSizeExceeded(t *testing.T) { t.Fatal("Expected metrics field in status update") } - exp := map[string]interface{}{"": map[string]interface{}{ + exp := map[string]any{"": map[string]any{ "counter_decision_logs_dropped_buffer_size_limit_bytes_exceeded": json.Number("1"), "counter_decision_logs_dropped_buffer_size_limit_exceeded": json.Number("1"), }} @@ -1339,8 +1339,8 @@ func TestPluginStatusUpdateRateLimitExceeded(t *testing.T) { fixture.plugin.metrics = metrics.New() - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false event1 := &server.Info{ DecisionID: "abc", @@ -1418,7 +1418,7 @@ func TestPluginStatusUpdateRateLimitExceeded(t *testing.T) { t.Fatal("Expected metrics field in status update") } - exp := map[string]interface{}{"": map[string]interface{}{"counter_decision_logs_dropped_rate_limit_exceeded": json.Number("2")}} + exp := map[string]any{"": map[string]any{"counter_decision_logs_dropped_rate_limit_exceeded": json.Number("2")}} if !reflect.DeepEqual(e.Fields["metrics"], exp) { t.Fatalf("Expected %v but got %v", exp, e.Fields["metrics"]) @@ -1455,8 +1455,8 @@ func TestPluginRateLimitRequeue(t *testing.T) { fixture.server.ch = make(chan []EventV1, 3) - var input interface{} = map[string]interface{}{"method": "GET"} - var result1 interface{} = false + var input any = map[string]any{"method": "GET"} + var result1 any = false if err := fixture.plugin.Log(ctx, logServerInfo("abc", input, result1)); err != nil { t.Fatal(err) @@ -1576,7 +1576,7 @@ func TestPluginRateLimitDropCountStatus(t *testing.T) { fixture.plugin.metrics = metrics.New() - var input any = map[string]interface{}{"method": "GET"} + var input any = map[string]any{"method": "GET"} var result any = false event1 := &server.Info{ @@ -1658,7 +1658,7 @@ func TestPluginRateLimitDropCountStatus(t *testing.T) { t.Fatal("Expected metrics") } - exp := map[string]interface{}{"": map[string]interface{}{"counter_decision_logs_dropped_rate_limit_exceeded": json.Number("2")}} + exp := map[string]any{"": map[string]any{"counter_decision_logs_dropped_rate_limit_exceeded": json.Number("2")}} if !reflect.DeepEqual(e.Fields["metrics"], exp) { t.Fatalf("Expected %v but got %v", exp, e.Fields["metrics"]) @@ -1687,11 +1687,11 @@ func TestChunkMaxUploadSizeLimitNDBCacheDropping(t *testing.T) { fixture.plugin.metrics = metrics.New() - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false // Purposely oversized NDBCache entry will force dropping during Log(). - var ndbCacheExample interface{} = ast.MustJSON(builtins.NDBCache{ + var ndbCacheExample any = ast.MustJSON(builtins.NDBCache{ "test.custom_space_waster": ast.NewObject([2]*ast.Term{ ast.ArrayTerm(), ast.StringTerm(strings.Repeat("Wasted space... ", 200)), @@ -1853,13 +1853,13 @@ func TestPluginTriggerManual(t *testing.T) { } testMetrics := getWellKnownMetrics() - msAsFloat64 := map[string]interface{}{} + msAsFloat64 := map[string]any{} for k, v := range testMetrics.All() { msAsFloat64[k] = float64(v.(uint64)) } - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { @@ -1951,7 +1951,7 @@ func TestPluginTriggerManualWithTimeout(t *testing.T) { t.Fatal(err) } - pluginConfig := make(map[string]interface{}) + pluginConfig := make(map[string]any) pluginConfig["service"] = "example" pluginConfig["resource"] = "/" @@ -1978,8 +1978,8 @@ func TestPluginTriggerManualWithTimeout(t *testing.T) { t.Fatal(err) } - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false ts, err := time.Parse(time.RFC3339Nano, "2018-01-01T12:00:00.123456Z") if err != nil { @@ -2032,8 +2032,8 @@ func TestPluginGracefulShutdownFlushesDecisions(t *testing.T) { t.Fatal(err) } - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false logsSent := 200 for i := 0; i < logsSent; i++ { @@ -2073,8 +2073,8 @@ func TestPluginTerminatesAfterGracefulShutdownPeriod(t *testing.T) { t.Fatal(err) } - var input interface{} = map[string]interface{}{"method": "GET"} - var result interface{} = false + var input any = map[string]any{"method": "GET"} + var result any = false input = generateInputMap(0) _ = fixture.plugin.Log(ctx, logServerInfo("abc", input, result)) @@ -2258,10 +2258,10 @@ func TestPluginMasking(t *testing.T) { expPrinted []string errManager error expErr error - input interface{} - expected interface{} - ndbcache interface{} - ndbc_expected interface{} + input any + expected any + ndbcache any + ndbc_expected any reconfigure bool }{ { @@ -2273,11 +2273,11 @@ func TestPluginMasking(t *testing.T) { input.input.is_sensitive }`), expErased: []string{"/input/password"}, - input: map[string]interface{}{ + input: map[string]any{ "is_sensitive": true, "password": "secret", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_sensitive": true, }, }, @@ -2290,11 +2290,11 @@ func TestPluginMasking(t *testing.T) { input.input.is_sensitive }`), expErased: []string{"/input/password"}, - input: map[string]interface{}{ + input: map[string]any{ "is_sensitive": true, "password": "secret", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_sensitive": true, }, reconfigure: true, @@ -2309,11 +2309,11 @@ func TestPluginMasking(t *testing.T) { x := "**REDACTED**" }`), expMasked: []string{"/input/password"}, - input: map[string]interface{}{ + input: map[string]any{ "is_sensitive": true, "password": "mySecretPassword", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_sensitive": true, "password": "**REDACTED**", }, @@ -2328,11 +2328,11 @@ func TestPluginMasking(t *testing.T) { x := "**REDACTED**" }`), expErased: []string{"/input/password"}, - input: map[string]interface{}{ + input: map[string]any{ "is_sensitive": true, "password": "mySecretPassword", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_sensitive": true, }, }, @@ -2345,11 +2345,11 @@ func TestPluginMasking(t *testing.T) { input.input.password }`), expErased: []string{"/input/password"}, - input: map[string]interface{}{ + input: map[string]any{ "is_sensitive": true, "password": "mySecretPassword", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_sensitive": true, }, }, @@ -2370,11 +2370,11 @@ func TestPluginMasking(t *testing.T) { mask["/input/password"] { input.input.is_sensitive }`), - input: map[string]interface{}{ + input: map[string]any{ "is_not_sensitive": true, "password": "secret", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_not_sensitive": true, "password": "secret", }, @@ -2390,23 +2390,23 @@ func TestPluginMasking(t *testing.T) { {"nabs": 1} ] }`), - input: map[string]interface{}{ + input: map[string]any{ "bar": 1, - "foo": []map[string]interface{}{{"baz": 1}}, + "foo": []map[string]any{{"baz": 1}}, }, // Due to ast.JSON() parsing as part of rego.eval, internal mapped // types from mask rule valuations (for numbers) will be json.Number. - // This affects explicitly providing the expected interface{} value. + // This affects explicitly providing the expected any value. // // See TestMaksRuleErase where tests are written to confirm json marshalled // output is as expected. - expected: map[string]interface{}{ + expected: map[string]any{ "bar": 1, - "foo": []interface{}{map[string]interface{}{"nabs": json.Number("1")}}, + "foo": []any{map[string]any{"nabs": json.Number("1")}}, }, }, { - note: "upsert failure: unsupported type []map[string]interface{}", + note: "upsert failure: unsupported type []map[string]any", rawPolicy: []byte(` package system.log mask[{"op": "upsert", "path": "/input/foo/boo", "value": x}] { @@ -2414,13 +2414,13 @@ func TestPluginMasking(t *testing.T) { {"nabs": 1} ] }`), - input: map[string]interface{}{ + input: map[string]any{ "bar": json.Number("1"), - "foo": []map[string]interface{}{{"baz": json.Number("1")}}, + "foo": []map[string]any{{"baz": json.Number("1")}}, }, - expected: map[string]interface{}{ + expected: map[string]any{ "bar": json.Number("1"), - "foo": []map[string]interface{}{{"baz": json.Number("1")}}, + "foo": []map[string]any{{"baz": json.Number("1")}}, }, }, { @@ -2456,18 +2456,18 @@ func TestPluginMasking(t *testing.T) { {"changed": 1} ] }`), - input: map[string]interface{}{ + input: map[string]any{ "is_sensitive": true, "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.cThIIoDvwdueQB468K5xDc5633seEFoqwxjF_xSJyQQ", "bar": 1, - "foo": []map[string]interface{}{{"baz": 1}}, + "foo": []map[string]any{{"baz": 1}}, "password": "mySecretPassword", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_sensitive": true, "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.KipSRURBQ1RFRCoq", "bar": 1, - "foo": []interface{}{map[string]interface{}{"changed": json.Number("1")}}, + "foo": []any{map[string]any{"changed": json.Number("1")}}, }, }, { @@ -2480,11 +2480,11 @@ func TestPluginMasking(t *testing.T) { input.input.is_sensitive }`), expErased: []string{"/input/password"}, - input: map[string]interface{}{ + input: map[string]any{ "is_sensitive": true, "password": "secret", }, - expected: map[string]interface{}{ + expected: map[string]any{ "is_sensitive": true, }, expPrinted: []string{"Erasing /input/password"}, @@ -2499,11 +2499,11 @@ func TestPluginMasking(t *testing.T) { x := "**REDACTED**" }`), expMasked: []string{"/nd_builtin_cache/rand.intn"}, - ndbcache: map[string]interface{}{ + ndbcache: map[string]any{ // Simulate rand.intn("z", 15) call, with output of 7. - "rand.intn": map[string]interface{}{"[\"z\",15]": json.Number("7")}, + "rand.intn": map[string]any{"[\"z\",15]": json.Number("7")}, }, - ndbc_expected: map[string]interface{}{ + ndbc_expected: map[string]any{ "rand.intn": "**REDACTED**", }, }, @@ -2524,19 +2524,19 @@ func TestPluginMasking(t *testing.T) { } `), expMasked: []string{"/nd_builtin_cache/net.lookup_ip_addr", "/nd_builtin_cache/rand.intn"}, - ndbcache: map[string]interface{}{ + ndbcache: map[string]any{ // Simulate rand.intn("z", 15) call, with output of 7. - "rand.intn": map[string]interface{}{"[\"z\",15]": json.Number("7")}, - "net.lookup_ip_addr": map[string]interface{}{ + "rand.intn": map[string]any{"[\"z\",15]": json.Number("7")}, + "net.lookup_ip_addr": map[string]any{ "[\"1.1.1.1\"]": "1.1.1.1", "[\"2.2.2.2\"]": "2.2.2.2", "[\"3.3.3.3\"]": "3.3.3.3", "[\"4.4.4.4\"]": "4.4.4.4", }, }, - ndbc_expected: map[string]interface{}{ + ndbc_expected: map[string]any{ "rand.intn": "**REDACTED**", - "net.lookup_ip_addr": map[string]interface{}{ + "net.lookup_ip_addr": map[string]any{ "[\"1.1.1.1\"]": "1.1.1.1", "[\"2.2.2.2\"]": "2.2.2.2", "[\"3.3.3.3\"]": "3.3.3.3", @@ -2923,8 +2923,8 @@ type testFixtureOptions struct { Resource *string TestServerPath *string PartitionName *string - ExtraConfig map[string]interface{} - ExtraManagerConfig map[string]interface{} + ExtraConfig map[string]any + ExtraManagerConfig map[string]any ManagerInit func(*plugins.Manager) } @@ -2965,7 +2965,7 @@ func newTestFixture(t *testing.T, opts ...testFixtureOptions) testFixture { } ]}`, ts.server.URL)) - mgrCfg := make(map[string]interface{}) + mgrCfg := make(map[string]any) err := json.Unmarshal(managerConfig, &mgrCfg) if err != nil { t.Fatal(err) @@ -2991,7 +2991,7 @@ func newTestFixture(t *testing.T, opts ...testFixtureOptions) testFixture { init(manager) } - pluginConfig := map[string]interface{}{ + pluginConfig := map[string]any{ "service": "example", } @@ -3172,13 +3172,13 @@ func TestEventV1ToAST(t *testing.T) { t.Parallel() input := `{"foo": [{"bar": 1, "baz": {"2": 3.3333333, "4": null}}]}` - var goInput interface{} = string(util.MustMarshalJSON(input)) + var goInput any = string(util.MustMarshalJSON(input)) astInput, err := roundtripJSONToAST(goInput) if err != nil { t.Fatalf("Unexpected error: %s", err) } - var result interface{} = map[string]interface{}{ + var result any = map[string]any{ "x": true, } @@ -3187,7 +3187,7 @@ func TestEventV1ToAST(t *testing.T) { t.Fatalf("Unexpected error: %s", err) } - var ndbCacheExample interface{} = ast.MustJSON(builtins.NDBCache{ + var ndbCacheExample any = ast.MustJSON(builtins.NDBCache{ "time.now_ns": ast.NewObject([2]*ast.Term{ ast.ArrayTerm(), ast.NumberTerm("1663803565571081429"), @@ -3404,8 +3404,8 @@ func TestPluginDefaultResourcePath(t *testing.T) { fixture.server.ch = make(chan []EventV1, 1) - var input interface{} = map[string]interface{}{"method": "GET"} - var result1 interface{} = false + var input any = map[string]any{"method": "GET"} + var result1 any = false if err := fixture.plugin.Log(ctx, &server.Info{ DecisionID: "abc", @@ -3466,8 +3466,8 @@ func TestPluginResourcePathAndPartitionName(t *testing.T) { fixture.server.ch = make(chan []EventV1, 1) - var input interface{} = map[string]interface{}{"method": "GET"} - var result1 interface{} = false + var input any = map[string]any{"method": "GET"} + var result1 any = false if err := fixture.plugin.Log(ctx, &server.Info{ DecisionID: "abc", @@ -3527,8 +3527,8 @@ func TestPluginResourcePath(t *testing.T) { fixture.server.ch = make(chan []EventV1, 1) - var input interface{} = map[string]interface{}{"method": "GET"} - var result1 interface{} = false + var input any = map[string]any{"method": "GET"} + var result1 any = false if err := fixture.plugin.Log(ctx, &server.Info{ DecisionID: "abc", @@ -3612,9 +3612,9 @@ func getValueForUser(idx int) string { return users[idx%len(users)] } -func generateInputMap(idx int) map[string]interface{} { +func generateInputMap(idx int) map[string]any { var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - result := make(map[string]interface{}) + result := make(map[string]any) for range 20 { n := idx % len(letters) diff --git a/v1/plugins/plugins.go b/v1/plugins/plugins.go index 7e8b900bfc..8040eb3e8c 100644 --- a/v1/plugins/plugins.go +++ b/v1/plugins/plugins.go @@ -85,8 +85,8 @@ import ( // After a plugin has been created subsequent status updates can be // send anytime the plugin enters a ready or error state. type Factory interface { - Validate(manager *Manager, config []byte) (interface{}, error) - New(manager *Manager, config interface{}) Plugin + Validate(manager *Manager, config []byte) (any, error) + New(manager *Manager, config any) Plugin } // Plugin defines the interface OPA uses to manage your plugin. @@ -104,7 +104,7 @@ type Factory interface { type Plugin interface { Start(ctx context.Context) error Stop(ctx context.Context) - Reconfigure(ctx context.Context, config interface{}) + Reconfigure(ctx context.Context, config any) } // Triggerable defines the interface plugins use for manual plugin triggers. @@ -1097,7 +1097,7 @@ func (m *Manager) sendOPAUpdateLoop(ctx context.Context) { opaReportNotify = false _, err := m.reporter.SendReport(ctx) if err != nil { - m.logger.WithFields(map[string]interface{}{"err": err}).Debug("Unable to send OPA telemetry report.") + m.logger.WithFields(map[string]any{"err": err}).Debug("Unable to send OPA telemetry report.") } } diff --git a/v1/plugins/plugins_test.go b/v1/plugins/plugins_test.go index 9112192fd1..c553393ce5 100644 --- a/v1/plugins/plugins_test.go +++ b/v1/plugins/plugins_test.go @@ -351,7 +351,7 @@ func (p *testPlugin) Stop(context.Context) { p.m.UpdatePluginStatus("p1", &Status{State: StateNotReady}) } -func (p *testPlugin) Reconfigure(context.Context, interface{}) { +func (p *testPlugin) Reconfigure(context.Context, any) { p.m.UpdatePluginStatus("p1", &Status{State: StateNotReady}) } @@ -488,8 +488,8 @@ func (m *mockForInitStartOrdering) Start(_ context.Context) error { return errors.New("expected manager to be initialized") } -func (*mockForInitStartOrdering) Stop(context.Context) {} -func (*mockForInitStartOrdering) Reconfigure(context.Context, interface{}) {} +func (*mockForInitStartOrdering) Stop(context.Context) {} +func (*mockForInitStartOrdering) Reconfigure(context.Context, any) {} func TestPluginManagerAuthPlugin(t *testing.T) { m, err := New([]byte(`{"plugins": {"someplugin": {}}}`), "test", inmem.New()) @@ -521,7 +521,7 @@ func TestPluginManagerAuthPlugin(t *testing.T) { func TestPluginManagerLogger(t *testing.T) { - logger := logging.Get().WithFields(map[string]interface{}{"context": "myloggincontext"}) + logger := logging.Get().WithFields(map[string]any{"context": "myloggincontext"}) m, err := New([]byte(`{}`), "test", inmem.New(), Logger(logger)) if err != nil { @@ -543,14 +543,14 @@ func TestPluginManagerConsoleLogger(t *testing.T) { const fieldKey = "foo" const fieldValue = "bar" - mgr.ConsoleLogger().WithFields(map[string]interface{}{fieldKey: fieldValue}).Info("Some message") + mgr.ConsoleLogger().WithFields(map[string]any{fieldKey: fieldValue}).Info("Some message") entries := consoleLogger.Entries() exp := []test.LogEntry{ { Level: logging.Info, - Fields: map[string]interface{}{fieldKey: fieldValue}, + Fields: map[string]any{fieldKey: fieldValue}, Message: "Some message", }, } @@ -643,7 +643,7 @@ func (*myAuthPluginMock) Start(context.Context) error { } func (*myAuthPluginMock) Stop(context.Context) { } -func (*myAuthPluginMock) Reconfigure(context.Context, interface{}) { +func (*myAuthPluginMock) Reconfigure(context.Context, any) { } type prometheusRegisterMock struct { diff --git a/v1/plugins/rest/auth.go b/v1/plugins/rest/auth.go index 28ec53562b..e94e99cd8a 100644 --- a/v1/plugins/rest/auth.go +++ b/v1/plugins/rest/auth.go @@ -282,25 +282,25 @@ func messageDigest(message []byte, alg string) ([]byte, error) { // oauth2ClientCredentialsAuthPlugin represents authentication via a bearer token in the HTTP Authorization header // obtained through the OAuth2 client credentials flow type oauth2ClientCredentialsAuthPlugin struct { - GrantType string `json:"grant_type"` - TokenURL string `json:"token_url"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - SigningKeyID string `json:"signing_key"` - Thumbprint string `json:"thumbprint"` - Claims map[string]interface{} `json:"additional_claims"` - IncludeJti bool `json:"include_jti_claim"` - Scopes []string `json:"scopes,omitempty"` - AdditionalHeaders map[string]string `json:"additional_headers,omitempty"` - AdditionalParameters map[string]string `json:"additional_parameters,omitempty"` - AWSKmsKey *awsKmsKeyConfig `json:"aws_kms,omitempty"` - AWSSigningPlugin *awsSigningAuthPlugin `json:"aws_signing,omitempty"` - ClientAssertionType string `json:"client_assertion_type"` - ClientAssertion string `json:"client_assertion"` - ClientAssertionPath string `json:"client_assertion_path"` + GrantType string `json:"grant_type"` + TokenURL string `json:"token_url"` + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + SigningKeyID string `json:"signing_key"` + Thumbprint string `json:"thumbprint"` + Claims map[string]any `json:"additional_claims"` + IncludeJti bool `json:"include_jti_claim"` + Scopes []string `json:"scopes,omitempty"` + AdditionalHeaders map[string]string `json:"additional_headers,omitempty"` + AdditionalParameters map[string]string `json:"additional_parameters,omitempty"` + AWSKmsKey *awsKmsKeyConfig `json:"aws_kms,omitempty"` + AWSSigningPlugin *awsSigningAuthPlugin `json:"aws_signing,omitempty"` + ClientAssertionType string `json:"client_assertion_type"` + ClientAssertion string `json:"client_assertion"` + ClientAssertionPath string `json:"client_assertion_path"` signingKey *keys.Config - signingKeyParsed interface{} + signingKeyParsed any tokenCache *oauth2Token tlsSkipVerify bool logger logging.Logger @@ -311,9 +311,9 @@ type oauth2Token struct { ExpiresAt time.Time } -func (ap *oauth2ClientCredentialsAuthPlugin) createAuthJWT(ctx context.Context, extClaims map[string]interface{}, signingKey interface{}) (*string, error) { +func (ap *oauth2ClientCredentialsAuthPlugin) createAuthJWT(ctx context.Context, extClaims map[string]any, signingKey any) (*string, error) { now := time.Now() - claims := map[string]interface{}{ + claims := map[string]any{ "iat": now.Unix(), "exp": now.Add(10 * time.Minute).Unix(), } diff --git a/v1/plugins/rest/rest.go b/v1/plugins/rest/rest.go index e5d8e0f0d6..f8be30af5e 100644 --- a/v1/plugins/rest/rest.go +++ b/v1/plugins/rest/rest.go @@ -133,12 +133,12 @@ func (c *Config) authPrepare(req *http.Request, lookup AuthPluginLookupFunc) err // services. type Client struct { bytes *[]byte - json *interface{} + json *any config Config headers map[string]string authPluginLookup AuthPluginLookupFunc logger logging.Logger - loggerFields map[string]interface{} + loggerFields map[string]any distributedTacingOpts tracing.Options } @@ -234,7 +234,7 @@ func (c Client) Logger() logging.Logger { } // LoggerFields returns the fields used for log statements used by Client -func (c Client) LoggerFields() map[string]interface{} { +func (c Client) LoggerFields() map[string]any { return c.loggerFields } @@ -254,7 +254,7 @@ func (c Client) WithHeader(k, v string) Client { // WithJSON returns a shallow copy of the client with the JSON value set as the // message body to include the requests. This function sets the Content-Type // header. -func (c Client) WithJSON(body interface{}) Client { +func (c Client) WithJSON(body any) Client { c = c.WithHeader("Content-Type", "application/json") c.json = &body return c @@ -318,7 +318,7 @@ func (c Client) Do(ctx context.Context, method, path string) (*http.Response, er } if c.logger.GetLevel() >= logging.Debug { - c.loggerFields = map[string]interface{}{ + c.loggerFields = map[string]any{ "method": method, "url": url, "headers": withMaskedHeaders(req.Header), diff --git a/v1/plugins/rest/rest_test.go b/v1/plugins/rest/rest_test.go index 48ab617ebd..67f5561da5 100644 --- a/v1/plugins/rest/rest_test.go +++ b/v1/plugins/rest/rest_test.go @@ -2135,7 +2135,7 @@ type oauth2TestServer struct { tokenType string tokenTTL int64 invocations int32 - verificationKey interface{} + verificationKey any } func newOauth2TestClient(t *testing.T, ts *testServer, ots *oauth2TestServer, options ...testPluginCustomizer) *Client { @@ -2503,7 +2503,7 @@ func certTemplate() (*x509.Certificate, error) { return &tmpl, nil } -func createCert(template, parent *x509.Certificate, pub interface{}, parentPriv interface{}) ( +func createCert(template, parent *x509.Certificate, pub any, parentPriv any) ( cert *x509.Certificate, certPEM []byte, err error) { certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv) diff --git a/v1/plugins/status/plugin.go b/v1/plugins/status/plugin.go index f80b5664c1..ecfc3abff8 100644 --- a/v1/plugins/status/plugin.go +++ b/v1/plugins/status/plugin.go @@ -43,7 +43,7 @@ type UpdateRequestV1 struct { Bundles map[string]*bundle.Status `json:"bundles,omitempty"` Discovery *bundle.Status `json:"discovery,omitempty"` DecisionLogs *lstat.Status `json:"decision_logs,omitempty"` - Metrics map[string]interface{} `json:"metrics,omitempty"` + Metrics map[string]any `json:"metrics,omitempty"` Plugins map[string]*plugins.Status `json:"plugins,omitempty"` } @@ -87,7 +87,7 @@ type BundleLoadDurationNanoseconds struct { } type reconfigure struct { - config interface{} + config any done chan struct{} } @@ -222,7 +222,7 @@ func New(parsedConfig *Config, manager *plugins.Manager) *Plugin { // when updating statuses pluginStatusCh: make(chan map[string]*plugins.Status, 1), queryCh: make(chan chan *UpdateRequestV1), - logger: manager.Logger().WithFields(map[string]interface{}{"plugin": Name}), + logger: manager.Logger().WithFields(map[string]any{"plugin": Name}), trigger: make(chan trigger), collectors: newCollectors(parsedConfig.PrometheusConfig), } @@ -307,7 +307,7 @@ func (p *Plugin) UpdatePluginStatus(status map[string]*plugins.Status) { } // Reconfigure notifies the plugin with a new configuration. -func (p *Plugin) Reconfigure(_ context.Context, config interface{}) { +func (p *Plugin) Reconfigure(_ context.Context, config any) { done := make(chan struct{}) p.reconfig <- reconfigure{config: config, done: done} <-done @@ -466,7 +466,7 @@ func (p *Plugin) oneShot(ctx context.Context) error { return nil } -func (p *Plugin) reconfigure(config interface{}) { +func (p *Plugin) reconfigure(config any) { newConfig := config.(*Config) if reflect.DeepEqual(p.config, *newConfig) { @@ -500,7 +500,7 @@ func (p *Plugin) snapshot() *UpdateRequestV1 { } if p.metrics != nil { - s.Metrics = map[string]interface{}{p.metrics.Info().Name: p.metrics.All()} + s.Metrics = map[string]any{p.metrics.Info().Name: p.metrics.All()} } return s @@ -511,12 +511,12 @@ func (p *Plugin) logUpdate(update *UpdateRequestV1) error { if err != nil { return err } - fields := map[string]interface{}{} + fields := map[string]any{} err = util.UnmarshalJSON(eventBuf, &fields) if err != nil { return err } - p.manager.ConsoleLogger().WithFields(fields).WithFields(map[string]interface{}{ + p.manager.ConsoleLogger().WithFields(fields).WithFields(map[string]any{ "type": "openpolicyagent.org/status", }).Info("Status Log") return nil @@ -560,7 +560,7 @@ func (u UpdateRequestV1) Equal(other UpdateRequestV1) bool { nullSafeDeepEqual(u.Metrics, other.Metrics) } -func nullSafeDeepEqual(a, b interface{}) bool { +func nullSafeDeepEqual(a, b any) bool { if a == nil && b == nil { return true } diff --git a/v1/plugins/status/plugin_test.go b/v1/plugins/status/plugin_test.go index 0a3ae7dae1..3c9582b349 100644 --- a/v1/plugins/status/plugin_test.go +++ b/v1/plugins/status/plugin_test.go @@ -1011,7 +1011,7 @@ func TestMetrics(t *testing.T) { fixture.plugin.BulkUpdateBundleStatus(map[string]*bundle.Status{"bundle": status}) result := <-fixture.server.ch - exp := map[string]interface{}{"": map[string]interface{}{}} + exp := map[string]any{"": map[string]any{}} if !reflect.DeepEqual(result.Metrics, exp) { t.Fatalf("Expected %v but got %v", exp, result.Metrics) @@ -1247,7 +1247,7 @@ func (*testPlugin) Start(context.Context) error { func (*testPlugin) Stop(context.Context) { } -func (*testPlugin) Reconfigure(context.Context, interface{}) { +func (*testPlugin) Reconfigure(context.Context, any) { } func (p *testPlugin) Log(_ context.Context, req *UpdateRequestV1) error { diff --git a/v1/profiler/profiler.go b/v1/profiler/profiler.go index 1aeac83eaf..adc071598b 100644 --- a/v1/profiler/profiler.go +++ b/v1/profiler/profiler.go @@ -281,7 +281,7 @@ type ExprStats struct { // ExprStatsAggregated represents the result of profiling an expression // by aggregating `n` profiles. type ExprStatsAggregated struct { - ExprTimeNsStats interface{} `json:"total_time_ns_stats"` + ExprTimeNsStats any `json:"total_time_ns_stats"` NumEval int `json:"num_eval"` NumRedo int `json:"num_redo"` NumGenExpr int `json:"num_gen_expr"` diff --git a/v1/refactor/refactor.go b/v1/refactor/refactor.go index 92633332a5..1d6c165566 100644 --- a/v1/refactor/refactor.go +++ b/v1/refactor/refactor.go @@ -72,7 +72,7 @@ func (mqr *MoveQueryResult) validate() error { func (*Refactor) Move(q MoveQuery) (*MoveQueryResult, error) { for _, module := range q.Modules { - t := ast.NewGenericTransformer(func(x interface{}) (interface{}, error) { + t := ast.NewGenericTransformer(func(x any) (any, error) { if s, ok := x.(ast.Ref); ok { for k, v := range q.SrcDstMapping { other, err := ast.ParseRef(k) diff --git a/v1/rego/example_test.go b/v1/rego/example_test.go index 0ebe9ae392..99d596dcee 100644 --- a/v1/rego/example_test.go +++ b/v1/rego/example_test.go @@ -59,7 +59,7 @@ func ExampleRego_Eval_input() { // Numeric values must be represented using json.Number. d.UseNumber() - var input interface{} + var input any if err := d.Decode(&input); err != nil { panic(err) @@ -168,7 +168,7 @@ allow if { input.open == "sesame" }`, ), - rego.Input(map[string]interface{}{"open": "sesame"}), + rego.Input(map[string]any{"open": "sesame"}), ) // Run evaluation. @@ -252,7 +252,7 @@ func ExampleRego_Eval_compiler() { rego.Query("data.example.allow"), rego.Compiler(compiler), rego.Input( - map[string]interface{}{ + map[string]any{ "identity": "bob", "method": "GET", }, @@ -297,7 +297,7 @@ func ExampleRego_Eval_storage() { } }` - var json map[string]interface{} + var json map[string]any err := util.UnmarshalJSON([]byte(data), &json) if err != nil { @@ -344,7 +344,7 @@ func ExampleRego_Eval_persistent_storage() { } }` - var json map[string]interface{} + var json map[string]any err := util.UnmarshalJSON([]byte(data), &json) if err != nil { @@ -610,25 +610,25 @@ func ExampleRego_PartialResult() { // Define example inputs (representing requests) that will be used to test // the policy. - examples := []map[string]interface{}{ + examples := []map[string]any{ { "resource": "documentA", "operation": "write", - "subject": map[string]interface{}{ + "subject": map[string]any{ "user": "bob", }, }, { "resource": "documentB", "operation": "write", - "subject": map[string]interface{}{ + "subject": map[string]any{ "user": "alice", }, }, { "resource": "documentB", "operation": "read", - "subject": map[string]interface{}{ + "subject": map[string]any{ "user": "alice", }, }, @@ -769,7 +769,7 @@ func ExampleRego_PrepareForEval() { } // Raw input data that will be used in the first evaluation - input := map[string]interface{}{"x": 2} + input := map[string]any{"x": 2} // Run the evaluation rs, err := pq.Eval(ctx, rego.EvalInput(input)) @@ -1071,7 +1071,7 @@ func ExampleRego_print_statements() { print("input.foo is:", input.foo, "and input.bar is:", input.bar) } `), - rego.Input(map[string]interface{}{ + rego.Input(map[string]any{ "foo": 7, }), rego.EnablePrintStatements(true), diff --git a/v1/rego/plugins_test.go b/v1/rego/plugins_test.go index e9749cfd06..0c36696154 100644 --- a/v1/rego/plugins_test.go +++ b/v1/rego/plugins_test.go @@ -29,7 +29,7 @@ func (*testPlugin) Start(context.Context) error { func (*testPlugin) Stop(context.Context) { } -func (*testPlugin) Reconfigure(context.Context, interface{}) { +func (*testPlugin) Reconfigure(context.Context, any) { } func (*testPlugin) IsTarget(t string) bool { diff --git a/v1/rego/rego.go b/v1/rego/rego.go index c3a16c2be6..2c7abc9098 100644 --- a/v1/rego/rego.go +++ b/v1/rego/rego.go @@ -99,7 +99,7 @@ type EvalContext struct { hasInput bool time time.Time seed io.Reader - rawInput *interface{} + rawInput *any parsedInput ast.Value metrics metrics.Metrics txn storage.Transaction @@ -128,7 +128,7 @@ type EvalContext struct { baseCache topdown.BaseCache } -func (e *EvalContext) RawInput() *interface{} { +func (e *EvalContext) RawInput() *any { return e.rawInput } @@ -184,7 +184,7 @@ func (e *EvalContext) Transaction() storage.Transaction { type EvalOption func(*EvalContext) // EvalInput configures the input for a Prepared Query's evaluation -func EvalInput(input interface{}) EvalOption { +func EvalInput(input any) EvalOption { return func(e *EvalContext) { e.rawInput = &input e.hasInput = true @@ -349,7 +349,7 @@ func EvalSortSets(yes bool) EvalOption { } } -// EvalCopyMaps causes the evaluator to copy `map[string]interface{}`s before returning them. +// EvalCopyMaps causes the evaluator to copy `map[string]any`s before returning them. func EvalCopyMaps(yes bool) EvalOption { return func(e *EvalContext) { e.copyMaps = yes @@ -591,7 +591,7 @@ type Rego struct { parsedPackage *ast.Package imports []string parsedImports []*ast.Import - rawInput *interface{} + rawInput *any parsedInput ast.Value unknowns []string parsedUnknowns []*ast.Term @@ -636,7 +636,7 @@ type Rego struct { schemaSet *ast.SchemaSet target string // target type (wasm, rego, etc.) opa opa.EvalEngine - generateJSON func(*ast.Term, *EvalContext) (interface{}, error) + generateJSON func(*ast.Term, *EvalContext) (any, error) printHook print.Hook enablePrintStatements bool distributedTacingOpts tracing.Options @@ -904,7 +904,7 @@ func ParsedImports(imp []*ast.Import) func(r *Rego) { // Input returns an argument that sets the Rego input document. Input should be // a native Go value representing the input document. -func Input(x interface{}) func(r *Rego) { +func Input(x any) func(r *Rego) { return func(r *Rego) { r.rawInput = &x } @@ -1237,7 +1237,7 @@ func Target(t string) func(r *Rego) { } // GenerateJSON sets the AST to JSON converter for the results. -func GenerateJSON(f func(*ast.Term, *EvalContext) (interface{}, error)) func(r *Rego) { +func GenerateJSON(f func(*ast.Term, *EvalContext) (any, error)) func(r *Rego) { return func(r *Rego) { r.generateJSON = f } @@ -1985,7 +1985,7 @@ func (r *Rego) parseInput() (ast.Value, error) { return r.parseRawInput(r.rawInput, r.metrics) } -func (*Rego) parseRawInput(rawInput *interface{}, m metrics.Metrics) (ast.Value, error) { +func (*Rego) parseRawInput(rawInput *any, m metrics.Metrics) (ast.Value, error) { var input ast.Value if rawInput == nil { @@ -1998,7 +1998,7 @@ func (*Rego) parseRawInput(rawInput *interface{}, m metrics.Metrics) (ast.Value, rawPtr := util.Reference(rawInput) // roundtrip through json: this turns slices (e.g. []string, []bool) into - // []interface{}, the only array type ast.InterfaceToValue can work with + // []any, the only array type ast.InterfaceToValue can work with if err := util.RoundTrip(rawPtr); err != nil { return nil, err } @@ -2248,7 +2248,7 @@ func (r *Rego) eval(ctx context.Context, ectx *EvalContext) (ResultSet, error) { func (r *Rego) evalWasm(ctx context.Context, ectx *EvalContext) (ResultSet, error) { input := ectx.rawInput if ectx.parsedInput != nil { - i := interface{}(ectx.parsedInput) + i := any(ectx.parsedInput) input = &i } result, err := r.opa.Eval(ctx, opa.EvalOpts{ @@ -2796,11 +2796,11 @@ type refResolver struct { r resolver.Resolver } -func iteration(x interface{}) bool { +func iteration(x any) bool { var stopped bool - vis := ast.NewGenericVisitor(func(x interface{}) bool { + vis := ast.NewGenericVisitor(func(x any) bool { switch x := x.(type) { case *ast.Term: if ast.IsComprehension(x.Value) { @@ -2896,7 +2896,7 @@ func newFunction(decl *Function, f topdown.BuiltinFunc) func(*Rego) { } } -func generateJSON(term *ast.Term, ectx *EvalContext) (interface{}, error) { +func generateJSON(term *ast.Term, ectx *EvalContext) (any, error) { return ast.JSONWithOpt(term.Value, ast.JSONOpt{ SortSets: ectx.sortSets, diff --git a/v1/rego/rego_bench_test.go b/v1/rego/rego_bench_test.go index d35599c126..5777c1cec3 100644 --- a/v1/rego/rego_bench_test.go +++ b/v1/rego/rego_bench_test.go @@ -22,11 +22,11 @@ func BenchmarkPartialObjectRuleCrossModule(b *testing.B) { for _, n := range sizes { b.Run(strconv.Itoa(n), func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{}) + store := inmem.NewFromObject(map[string]any{}) mods := test.PartialObjectBenchmarkCrossModule(n) query := "data.test.foo" - input := make(map[string]interface{}) + input := make(map[string]any) for idx := range 4 { input[fmt.Sprintf("test_input_%d", idx)] = "test_input_10" } diff --git a/v1/rego/rego_test.go b/v1/rego/rego_test.go index c089b67b7a..01c5096b69 100644 --- a/v1/rego/rego_test.go +++ b/v1/rego/rego_test.go @@ -41,7 +41,7 @@ func TestRegoEval_DefaultRegoVersion(t *testing.T) { tests := []struct { note string module string - expResult interface{} + expResult any expErrs []string }{ { @@ -143,7 +143,7 @@ func TestRegoEval_Capabilities(t *testing.T) { regoVersion ast.RegoVersion capabilities *ast.Capabilities module string - expResult interface{} + expResult any expErrs []string }{ { @@ -412,10 +412,10 @@ func assertPreparedEvalQueryEval(t *testing.T, pq PreparedEvalQuery, options []E func assertResultSet(t *testing.T, rs ResultSet, expected string) { t.Helper() - result := []interface{}{} + result := []any{} for i := range rs { - values := []interface{}{} + values := []any{} for j := range rs[i].Expressions { values = append(values, rs[i].Expressions[j].Value) } @@ -519,7 +519,7 @@ func TestRegoEvalExpressionValue(t *testing.T) { func TestRegoInputs(t *testing.T) { tests := map[string]struct { - input interface{} + input any expected string }{ "map": {map[string]bool{"foo": true}, `[[{"foo": true}]]`}, @@ -532,7 +532,7 @@ func TestRegoInputs(t *testing.T) { Foo string `json:"baz"` }{"bar"}, `[[{"baz":"bar"}]]`}, "pointer to pointer to struct": { - func() interface{} { + func() any { a := &struct { Foo string `json:"baz"` }{"bar"} @@ -540,7 +540,7 @@ func TestRegoInputs(t *testing.T) { }(), `[[{"baz":"bar"}]]`}, "slice": {[]string{"a", "b"}, `[[["a", "b"]]]`}, "nil": {nil, `[[null]]`}, - "slice of interface": {[]interface{}{"a", 2, true}, `[[["a", 2, true]]]`}, + "slice of interface": {[]any{"a", 2, true}, `[[["a", 2, true]]]`}, } for desc, tc := range tests { @@ -863,7 +863,7 @@ func TestPreparedRegoTracerNoPropagate(t *testing.T) { Query("data"), Module("foo.rego", mod), Tracer(tracer), - Input(map[string]interface{}{"x": 10})).PrepareForEval(context.Background()) + Input(map[string]any{"x": 10})).PrepareForEval(context.Background()) if err != nil { t.Fatalf("unexpected error %s", err) } @@ -891,7 +891,7 @@ func TestPreparedRegoQueryTracerNoPropagate(t *testing.T) { Query("data"), Module("foo.rego", mod), QueryTracer(tracer), - Input(map[string]interface{}{"x": 10})).PrepareForEval(context.Background()) + Input(map[string]any{"x": 10})).PrepareForEval(context.Background()) if err != nil { t.Fatalf("unexpected error %s", err) } @@ -932,7 +932,7 @@ func TestRegoDisableIndexing(t *testing.T) { context.Background(), EvalQueryTracer(tracer), EvalRuleIndexing(false), - EvalInput(map[string]interface{}{"x": 10}), + EvalInput(map[string]any{"x": 10}), ) if err != nil { t.Fatalf("unexpected error %s", err) @@ -990,7 +990,7 @@ func TestRegoDisableIndexingWithMatch(t *testing.T) { context.Background(), EvalQueryTracer(tracer), EvalRuleIndexing(false), - EvalInput(map[string]interface{}{"x": 1}), + EvalInput(map[string]any{"x": 1}), ) if err != nil { t.Fatalf("unexpected error %s", err) @@ -1028,8 +1028,8 @@ func TestRegoCatchPathConflicts(t *testing.T) { r := New( Query("data"), Module("test.rego", "package x\np=1"), - Store(inmem.NewFromObject(map[string]interface{}{ - "x": map[string]interface{}{"p": 1}, + Store(inmem.NewFromObject(map[string]any{ + "x": map[string]any{"p": 1}, })), ) @@ -1221,7 +1221,7 @@ func TestPrepareAndEvalTransaction(t *testing.T) { t.Fatalf("Unexpected error writing to store: %s", err.Error()) } - err = store.Write(ctx, txn, storage.AddOp, path, map[string]interface{}{"y": 1}) + err = store.Write(ctx, txn, storage.AddOp, path, map[string]any{"y": 1}) if err != nil { t.Fatalf("Unexpected error writing to store: %s", err.Error()) } @@ -1253,7 +1253,7 @@ func TestPrepareAndEvalTransaction(t *testing.T) { // Case with an update to the store and a new transaction txn = storage.NewTransactionOrDie(ctx, store, storage.WriteParams) - err = store.Write(ctx, txn, storage.AddOp, path, map[string]interface{}{"y": 2}) + err = store.Write(ctx, txn, storage.AddOp, path, map[string]any{"y": 2}) if err != nil { t.Fatalf("Unexpected error writing to store: %s", err.Error()) } @@ -1278,7 +1278,7 @@ func TestPrepareAndEvalTransaction(t *testing.T) { // Case with no transaction provided, should create a new one and see the latest value txn = storage.NewTransactionOrDie(ctx, store, storage.WriteParams) - err = store.Write(ctx, txn, storage.AddOp, path, map[string]interface{}{"y": 3}) + err = store.Write(ctx, txn, storage.AddOp, path, map[string]any{"y": 3}) if err != nil { t.Fatalf("Unexpected error writing to store: %s", err.Error()) } @@ -2576,7 +2576,7 @@ func TestRegoCustomBuiltinPartialPropagate(t *testing.T) { } rs, err := pr.Rego( - Input(map[string]interface{}{"foo": "/foo/bar/baz/"}), + Input(map[string]any{"foo": "/foo/bar/baz/"}), ).Eval(context.Background()) if err != nil { @@ -3110,7 +3110,7 @@ func TestPrepareAndCompileWithSchema(t *testing.T) { "additionalProperties": false }` - var schema interface{} + var schema any err := util.Unmarshal([]byte(schemaBytes), &schema) if err != nil { t.Fatal(err) @@ -3178,7 +3178,7 @@ func TestGenerateJSON(t *testing.T) { r := New( Query("input"), Input("original-input"), - GenerateJSON(func(*ast.Term, *EvalContext) (interface{}, error) { + GenerateJSON(func(*ast.Term, *EvalContext) (any, error) { return "converted-input", nil }), ) @@ -3186,8 +3186,8 @@ func TestGenerateJSON(t *testing.T) { } func TestRegoLazyObjDefault(t *testing.T) { - foo := map[string]interface{}{"foo": "bar", "other": 1} - store := inmem.NewFromObjectWithOpts(map[string]interface{}{ + foo := map[string]any{"foo": "bar", "other": 1} + store := inmem.NewFromObjectWithOpts(map[string]any{ "stored": foo, }) r := New( @@ -3204,7 +3204,7 @@ func TestRegoLazyObjDefault(t *testing.T) { if !ok { t.Fatalf("expected binding for \"x\", got %v", rs[0].Bindings) } - m, ok := act.(map[string]interface{}) + m, ok := act.(map[string]any) if !ok { t.Fatalf("expected %T, got %T: %[2]v", m, act) } @@ -3216,8 +3216,8 @@ func TestRegoLazyObjDefault(t *testing.T) { } func TestRegoLazyObjNoRoundTripOnWrite(t *testing.T) { - foo := map[string]interface{}{"foo": "bar", "other": 1} - store := inmem.NewFromObjectWithOpts(map[string]interface{}{ + foo := map[string]any{"foo": "bar", "other": 1} + store := inmem.NewFromObjectWithOpts(map[string]any{ "stored": foo, }, inmem.OptRoundTripOnWrite(false)) r := New( @@ -3234,7 +3234,7 @@ func TestRegoLazyObjNoRoundTripOnWrite(t *testing.T) { if !ok { t.Fatalf("expected binding for \"x\", got %v", rs[0].Bindings) } - m, ok := act.(map[string]interface{}) + m, ok := act.(map[string]any) if !ok { t.Fatalf("expected %T, got %T: %[2]v", m, act) } @@ -3246,8 +3246,8 @@ func TestRegoLazyObjNoRoundTripOnWrite(t *testing.T) { } func TestRegoLazyObjCopyMaps(t *testing.T) { - foo := map[string]interface{}{"foo": "bar", "other": 1} - store := inmem.NewFromObjectWithOpts(map[string]interface{}{ + foo := map[string]any{"foo": "bar", "other": 1} + store := inmem.NewFromObjectWithOpts(map[string]any{ "stored": foo, }, inmem.OptRoundTripOnWrite(false)) r := New( @@ -3268,7 +3268,7 @@ func TestRegoLazyObjCopyMaps(t *testing.T) { if !ok { t.Fatalf("expected binding for \"x\", got %v", rs[0].Bindings) } - m, ok := act.(map[string]interface{}) + m, ok := act.(map[string]any) if !ok { t.Fatalf("expected %T, got %T: %[2]v", m, act) } diff --git a/v1/rego/rego_wasmtarget_test.go b/v1/rego/rego_wasmtarget_test.go index ee774a2390..bb6e090b78 100644 --- a/v1/rego/rego_wasmtarget_test.go +++ b/v1/rego/rego_wasmtarget_test.go @@ -108,8 +108,8 @@ func TestPrepareAndEvalWithWasmTargetModulesOnCompiler(t *testing.T) { Compiler(compiler), Query("data.test.p"), Target("wasm"), - Store(inmem.NewFromObject(map[string]interface{}{ - "x": map[string]interface{}{"p": 1}, + Store(inmem.NewFromObject(map[string]any{ + "x": map[string]any{"p": 1}, })), ).PrepareForEval(ctx) @@ -312,7 +312,7 @@ func TestCompatWithABIMinorVersion1(t *testing.T) { t.Fatalf("Unexpected error: %s", err) } - rs, err := pq.Eval(ctx, EvalInput(map[string]interface{}{"x": "x"})) + rs, err := pq.Eval(ctx, EvalInput(map[string]any{"x": "x"})) if err != nil { t.Fatalf("Unexpected error: %s", err) } diff --git a/v1/rego/resultset.go b/v1/rego/resultset.go index cc0710426e..983de2223e 100644 --- a/v1/rego/resultset.go +++ b/v1/rego/resultset.go @@ -12,7 +12,7 @@ type ResultSet []Result // Vars represents a collection of variable bindings. The keys are the variable // names and the values are the binding values. -type Vars map[string]interface{} +type Vars map[string]any // WithoutWildcards returns a copy of v with wildcard variables removed. func (v Vars) WithoutWildcards() Vars { @@ -46,12 +46,12 @@ type Location struct { // ExpressionValue defines the value of an expression in a Rego query. type ExpressionValue struct { - Value interface{} `json:"value"` - Text string `json:"text"` - Location *Location `json:"location"` + Value any `json:"value"` + Text string `json:"text"` + Location *Location `json:"location"` } -func newExpressionValue(expr *ast.Expr, value interface{}) *ExpressionValue { +func newExpressionValue(expr *ast.Expr, value any) *ExpressionValue { result := &ExpressionValue{ Value: value, } diff --git a/v1/repl/errors.go b/v1/repl/errors.go index 3d5cbfe590..e5286a4438 100644 --- a/v1/repl/errors.go +++ b/v1/repl/errors.go @@ -22,7 +22,7 @@ const ( BadArgsErr string = "bad arguments" ) -func newBadArgsErr(f string, a ...interface{}) *Error { +func newBadArgsErr(f string, a ...any) *Error { return &Error{ Code: BadArgsErr, Message: fmt.Sprintf(f, a...), diff --git a/v1/repl/repl.go b/v1/repl/repl.go index e4a98c48fa..c6d6fb0cb9 100644 --- a/v1/repl/repl.go +++ b/v1/repl/repl.go @@ -990,7 +990,7 @@ func (r *REPL) loadInput(ctx context.Context, compiler *ast.Compiler) (ast.Value return qrs[0][ast.Var("x")].Value, nil } -func (r *REPL) evalStatement(ctx context.Context, stmt interface{}) error { +func (r *REPL) evalStatement(ctx context.Context, stmt any) error { switch stmt := stmt.(type) { case ast.Body: compiler, err := r.loadCompiler(ctx) diff --git a/v1/repl/repl_test.go b/v1/repl/repl_test.go index 47d015c9a1..77f81ad75c 100644 --- a/v1/repl/repl_test.go +++ b/v1/repl/repl_test.go @@ -269,7 +269,7 @@ r = 3 if { true }`) func TestDump(t *testing.T) { ctx := context.Background() input := `{"a": [1,2,3,4]}` - var data map[string]interface{} + var data map[string]any err := util.UnmarshalJSON([]byte(input), &data) if err != nil { panic(err) @@ -286,7 +286,7 @@ func TestDump(t *testing.T) { func TestDumpPath(t *testing.T) { ctx := context.Background() input := `{"a": [1,2,3,4]}` - var data map[string]interface{} + var data map[string]any err := util.UnmarshalJSON([]byte(input), &data) if err != nil { panic(err) @@ -309,7 +309,7 @@ func TestDumpPath(t *testing.T) { t.Fatalf("Expected file read to succeed but got: %v", err) } - var result map[string]interface{} + var result map[string]any if err := util.UnmarshalJSON(bs, &result); err != nil { t.Fatalf("Expected json unmarshal to succeed but got: %v", err) } @@ -322,7 +322,7 @@ func TestDumpPath(t *testing.T) { func TestDumpPathCaseSensitive(t *testing.T) { ctx := context.Background() input := `{"a": [1,2,3,4]}` - var data map[string]interface{} + var data map[string]any err := util.UnmarshalJSON([]byte(input), &data) if err != nil { panic(err) @@ -345,7 +345,7 @@ func TestDumpPathCaseSensitive(t *testing.T) { t.Fatalf("Expected file read to succeed but got: %v", err) } - var result map[string]interface{} + var result map[string]any if err := util.UnmarshalJSON(bs, &result); err != nil { t.Fatalf("Expected json unmarshal to succeed but got: %v", err) } @@ -1090,7 +1090,7 @@ func TestOneShotJSON(t *testing.T) { if err := repl.OneShot(ctx, "data.a[i] = x"); err != nil { t.Fatalf("Unexpected error: %v", err) } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(`{ "result": [ { @@ -1146,7 +1146,7 @@ func TestOneShotJSON(t *testing.T) { panic(err) } - var result interface{} + var result any if err := util.UnmarshalJSON(buffer.Bytes(), &result); err != nil { t.Errorf("Unexpected output format: %v", err) @@ -1630,7 +1630,7 @@ p = [1, 2, 3] if { true }`) result := parseJSON(buffer.String()) // Strip REPL documents out as these change depending on build settings. - data := result.(map[string]interface{}) + data := result.(map[string]any) delete(data, "repl") if !reflect.DeepEqual(result, expected) { @@ -1926,7 +1926,7 @@ func TestEvalSingleTermMultiValue(t *testing.T) { ] }` - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(input), &expected); err != nil { panic(err) } @@ -1934,7 +1934,7 @@ func TestEvalSingleTermMultiValue(t *testing.T) { if err := repl.OneShot(ctx, "data.a[i].b.c[_]"); err != nil { t.Fatalf("Unexpected error: %v", err) } - var result interface{} + var result any if err := util.UnmarshalJSON(buffer.Bytes(), &result); err != nil { t.Errorf("Expected valid JSON document: %v: %v", err, buffer.String()) return @@ -3391,7 +3391,7 @@ func newTestStore() storage.Store { ] } ` - var data map[string]interface{} + var data map[string]any err := util.UnmarshalJSON([]byte(input), &data) if err != nil { panic(err) @@ -3399,8 +3399,8 @@ func newTestStore() storage.Store { return inmem.NewFromObject(data) } -func parseJSON(s string) interface{} { - var v interface{} +func parseJSON(s string) any { + var v any if err := util.UnmarshalJSON([]byte(s), &v); err != nil { panic(err) } diff --git a/v1/resolver/wasm/wasm.go b/v1/resolver/wasm/wasm.go index c70daa8db6..90b6c69543 100644 --- a/v1/resolver/wasm/wasm.go +++ b/v1/resolver/wasm/wasm.go @@ -17,7 +17,7 @@ import ( // New creates a new Resolver instance which is using the Wasm module // policy for the given entrypoint ref. -func New(entrypoints []ast.Ref, policy []byte, data interface{}) (*Resolver, error) { +func New(entrypoints []ast.Ref, policy []byte, data any) (*Resolver, error) { e, err := opa.LookupEngine("wasm") if err != nil { return nil, err @@ -97,9 +97,9 @@ func (r *Resolver) Eval(ctx context.Context, input resolver.Input) (resolver.Res return resolver.Result{}, fmt.Errorf("internal error: invalid entrypoint id %s", numValue) } - var in *interface{} + var in *any if input.Input != nil { - var str interface{} = []byte(input.Input.String()) + var str any = []byte(input.Input.String()) in = &str } @@ -122,12 +122,12 @@ func (r *Resolver) Eval(ctx context.Context, input resolver.Input) (resolver.Res } // SetData will update the external data for the Wasm instance. -func (r *Resolver) SetData(ctx context.Context, data interface{}) error { +func (r *Resolver) SetData(ctx context.Context, data any) error { return r.o.SetData(ctx, data) } // SetDataPath will set the provided data on the wasm instance at the specified path. -func (r *Resolver) SetDataPath(ctx context.Context, path []string, data interface{}) error { +func (r *Resolver) SetDataPath(ctx context.Context, path []string, data any) error { return r.o.SetDataPath(ctx, path, data) } diff --git a/v1/runtime/logging.go b/v1/runtime/logging.go index a2d56fd7db..9fb2c16b83 100644 --- a/v1/runtime/logging.go +++ b/v1/runtime/logging.go @@ -128,7 +128,7 @@ func (h *LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if h.loggingEnabled(logging.Info) { - fields := map[string]interface{}{ + fields := map[string]any{ "client_addr": rctx.ClientAddr, "req_id": rctx.ReqID, "req_method": rctx.ReqMethod, diff --git a/v1/runtime/plugins_test.go b/v1/runtime/plugins_test.go index 31cb7ff81d..9626e56f49 100644 --- a/v1/runtime/plugins_test.go +++ b/v1/runtime/plugins_test.go @@ -27,7 +27,7 @@ func (t *Tester) Start(_ context.Context) error { func (*Tester) Stop(_ context.Context) {} -func (*Tester) Reconfigure(_ context.Context, _ interface{}) {} +func (*Tester) Reconfigure(_ context.Context, _ any) {} type Config struct { ConfigErr bool `json:"configerr"` @@ -35,7 +35,7 @@ type Config struct { type Factory struct{} -func (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) { +func (Factory) Validate(_ *plugins.Manager, config []byte) (any, error) { cfg := Config{} @@ -50,7 +50,7 @@ func (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) return cfg, nil } -func (Factory) New(_ *plugins.Manager, _ interface{}) plugins.Plugin { +func (Factory) New(_ *plugins.Manager, _ any) plugins.Plugin { return &Tester{} } diff --git a/v1/runtime/runtime.go b/v1/runtime/runtime.go index d3a27aeeaa..89683a264b 100644 --- a/v1/runtime/runtime.go +++ b/v1/runtime/runtime.go @@ -470,7 +470,7 @@ func NewRuntime(ctx context.Context, params Params) (*Runtime, error) { } } - var bootConfig map[string]interface{} + var bootConfig map[string]any err = util.Unmarshal(config, &bootConfig) if err != nil { return nil, fmt.Errorf("config error: %w", err) @@ -557,7 +557,7 @@ func (rt *Runtime) Serve(ctx context.Context) error { rt.Params.DiagnosticAddrs = &[]string{} } - rt.logger.WithFields(map[string]interface{}{ + rt.logger.WithFields(map[string]any{ "addrs": *rt.Params.Addrs, "diagnostic-addrs": *rt.Params.DiagnosticAddrs, }).Info(serverInitializingMessage) @@ -571,17 +571,17 @@ func (rt *Runtime) Serve(ctx context.Context) error { // NOTE(tsandall): at some point, hopefully we can remove this because the // Go runtime will just do the right thing. Until then, try to set // GOMAXPROCS based on the CPU quota applied to the process. - undo, err := maxprocs.Set(maxprocs.Logger(func(f string, a ...interface{}) { + undo, err := maxprocs.Set(maxprocs.Logger(func(f string, a ...any) { rt.logger.Debug(f, a...) })) if err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Debug("Failed to set GOMAXPROCS from CPU quota.") + rt.logger.WithFields(map[string]any{"err": err}).Debug("Failed to set GOMAXPROCS from CPU quota.") } defer undo() if err := rt.Manager.Start(ctx); err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Failed to start plugins.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Failed to start plugins.") return err } @@ -589,7 +589,7 @@ func (rt *Runtime) Serve(ctx context.Context) error { if rt.traceExporter != nil { if err := rt.traceExporter.Start(ctx); err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Failed to start OpenTelemetry trace exporter.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Failed to start OpenTelemetry trace exporter.") return err } } @@ -648,13 +648,13 @@ func (rt *Runtime) Serve(ctx context.Context) error { defer cancel() rt.server, err = rt.server.Init(ctx) if err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Unable to initialize server.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Unable to initialize server.") return err } if rt.Params.Watch { if err := rt.startWatcher(ctx, rt.Params.Paths, rt.onReloadLogger); err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Unable to open watch.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Unable to open watch.") return err } } @@ -678,13 +678,13 @@ func (rt *Runtime) Serve(ctx context.Context) error { if err := rt.waitPluginsReady( 100*time.Millisecond, time.Second*time.Duration(rt.Params.ReadyTimeout)); err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Failed to wait for plugins activation.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Failed to wait for plugins activation.") return err } loops, err := rt.server.Listeners() if err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Unable to create listeners.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Unable to create listeners.") return err } @@ -719,7 +719,7 @@ func (rt *Runtime) Serve(ctx context.Context) error { case <-signalc: return rt.gracefulServerShutdown(rt.server) case err := <-errc: - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Listener failed.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Listener failed.") os.Exit(1) //nolint:gocritic } } @@ -804,14 +804,14 @@ func (rt *Runtime) checkOPAUpdateLoopDurations(ctx context.Context, done chan st for { resp, err := rt.reporter.SendReport(ctx) if err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Debug("Unable to send OPA version report.") + rt.logger.WithFields(map[string]any{"err": err}).Debug("Unable to send OPA version report.") } else { if resp.Latest.OPAUpToDate { - rt.logger.WithFields(map[string]interface{}{ + rt.logger.WithFields(map[string]any{ "current_version": version.Version, }).Debug("OPA is up to date.") } else { - rt.logger.WithFields(map[string]interface{}{ + rt.logger.WithFields(map[string]any{ "download_opa": resp.Latest.Download, "release_notes": resp.Latest.ReleaseNotes, "current_version": version.Version, @@ -871,7 +871,7 @@ func (rt *Runtime) readWatcher(ctx context.Context, watcher *fsnotify.Watcher, p removalMask := fsnotify.Remove | fsnotify.Rename mask := fsnotify.Create | fsnotify.Write | removalMask if (evt.Op & mask) != 0 { - rt.logger.WithFields(map[string]interface{}{ + rt.logger.WithFields(map[string]any{ "event": evt.String(), }).Debug("Registered file event.") t0 := time.Now() @@ -920,7 +920,7 @@ func (rt *Runtime) gracefulServerShutdown(s *server.Server) error { defer cancel() err := s.Shutdown(ctx) if err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Failed to shutdown server gracefully.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Failed to shutdown server gracefully.") return err } rt.logger.Info("Server shutdown.") @@ -928,7 +928,7 @@ func (rt *Runtime) gracefulServerShutdown(s *server.Server) error { if rt.traceExporter != nil { err = rt.traceExporter.Shutdown(ctx) if err != nil { - rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Failed to shutdown OpenTelemetry trace exporter gracefully.") + rt.logger.WithFields(map[string]any{"err": err}).Error("Failed to shutdown OpenTelemetry trace exporter gracefully.") } } return nil @@ -955,7 +955,7 @@ func (rt *Runtime) waitPluginsReady(checkInterval, timeout time.Duration) error } func (rt *Runtime) onReloadLogger(d time.Duration, err error) { - rt.logger.WithFields(map[string]interface{}{ + rt.logger.WithFields(map[string]any{ "duration": d, "err": err, }).Info("Processed file watch event.") @@ -968,7 +968,7 @@ func (rt *Runtime) getWatcher(rootPaths []string) (*fsnotify.Watcher, error) { } for _, path := range watcher.WatchList() { - rt.logger.WithFields(map[string]interface{}{"path": path}).Debug("watching path") + rt.logger.WithFields(map[string]any{"path": path}).Debug("watching path") } return watcher, nil @@ -993,8 +993,8 @@ func urlPathToConfigOverride(pathCount int, path string) ([]string, error) { }, nil } -func errorLogger(logger logging.Logger) func(attrs map[string]interface{}, f string, a ...interface{}) { - return func(attrs map[string]interface{}, f string, a ...interface{}) { +func errorLogger(logger logging.Logger) func(attrs map[string]any, f string, a ...any) { + return func(attrs map[string]any, f string, a ...any) { logger.WithFields(attrs).Error(f, a...) } } diff --git a/v1/runtime/runtime_test.go b/v1/runtime/runtime_test.go index 63b7fa4a7f..684ddb6099 100644 --- a/v1/runtime/runtime_test.go +++ b/v1/runtime/runtime_test.go @@ -103,7 +103,7 @@ func testRuntimeProcessWatchEvents(t *testing.T, asBundle bool, readAst bool) { t.Fatalf("Unexpected watcher init error: %v", err) } - expected := map[string]interface{}{ + expected := map[string]any{ "hello": "world-2", } @@ -116,7 +116,7 @@ func testRuntimeProcessWatchEvents(t *testing.T, asBundle bool, readAst bool) { // In practice, reload takes ~100us on development machine. maxWaitTime := time.Second * 1 - var val interface{} + var val any for time.Since(t0) < maxWaitTime { time.Sleep(1 * time.Millisecond) @@ -1437,12 +1437,12 @@ func TestUrlPathToConfigOverride(t *testing.T) { t.Fatal(err) } - var serviceConf map[string]interface{} + var serviceConf map[string]any if err = json.Unmarshal(rt.Manager.Config.Services, &serviceConf); err != nil { t.Fatal(err) } - cliService, ok := serviceConf["cli1"].(map[string]interface{}) + cliService, ok := serviceConf["cli1"].(map[string]any) if !ok { t.Fatal("excpected service configuration for 'cli1' service") } @@ -1451,12 +1451,12 @@ func TestUrlPathToConfigOverride(t *testing.T) { t.Error("expected cli1 service url value: 'https://www.example.com'") } - var bundleConf map[string]interface{} + var bundleConf map[string]any if err = json.Unmarshal(rt.Manager.Config.Bundles, &bundleConf); err != nil { t.Fatal(err) } - cliBundle, ok := bundleConf["cli1"].(map[string]interface{}) + cliBundle, ok := bundleConf["cli1"].(map[string]any) if !ok { t.Fatal("excpected bundle configuration for 'cli1' bundle") } @@ -1474,7 +1474,7 @@ func TestUrlPathToConfigOverride(t *testing.T) { } } -func getTestServer(update interface{}, statusCode int) (baseURL string, teardownFn func()) { +func getTestServer(update any, statusCode int) (baseURL string, teardownFn func()) { mux := http.NewServeMux() ts := httptest.NewServer(mux) diff --git a/v1/schemas/schemas_test.go b/v1/schemas/schemas_test.go index 864f26df2f..0bae109d89 100644 --- a/v1/schemas/schemas_test.go +++ b/v1/schemas/schemas_test.go @@ -24,7 +24,7 @@ func TestSchemasEmbedded(t *testing.T) { if err != nil { t.Errorf("file %v: %v", ent.Name(), err) } - var x interface{} + var x any err = util.UnmarshalJSON(cont, &x) if err != nil { t.Errorf("file %v: %v", ent.Name(), err) diff --git a/v1/sdk/RawMapper.go b/v1/sdk/RawMapper.go index e17f6f7ebc..9663eb7d45 100644 --- a/v1/sdk/RawMapper.go +++ b/v1/sdk/RawMapper.go @@ -7,11 +7,11 @@ import ( type RawMapper struct { } -func (*RawMapper) MapResults(pq *rego.PartialQueries) (interface{}, error) { +func (*RawMapper) MapResults(pq *rego.PartialQueries) (any, error) { return pq, nil } -func (*RawMapper) ResultToJSON(results interface{}) (interface{}, error) { +func (*RawMapper) ResultToJSON(results any) (any, error) { return results, nil } diff --git a/v1/sdk/opa.go b/v1/sdk/opa.go index b0730c474b..e5f5b88284 100644 --- a/v1/sdk/opa.go +++ b/v1/sdk/opa.go @@ -185,7 +185,7 @@ func (opa *OPA) configure(ctx context.Context, bs []byte, ready chan struct{}, b close(ready) }) - var bootConfig map[string]interface{} + var bootConfig map[string]any err = util.Unmarshal(opa.config, &bootConfig) if err != nil { return err @@ -310,8 +310,8 @@ func (opa *OPA) Decision(ctx context.Context, options DecisionOptions) (*Decisio type DecisionOptions struct { Now time.Time // specifies wallclock time used for time.now_ns(), decision log timestamp, etc. Path string // specifies name of policy decision to evaluate (e.g., example/allow) - Input interface{} // specifies value of the input document to evaluate policy with - NDBCache interface{} // specifies the non-deterministic builtins cache to use for evaluation. + Input any // specifies value of the input document to evaluate policy with + NDBCache any // specifies the non-deterministic builtins cache to use for evaluation. StrictBuiltinErrors bool // treat built-in function errors as fatal Tracer topdown.QueryTracer // specifies the tracer to use for evaluation, optional Metrics metrics.Metrics // specifies the metrics to use for preparing and evaluation, optional @@ -323,7 +323,7 @@ type DecisionOptions struct { // DecisionResult contains the output of query evaluation. type DecisionResult struct { ID string // provides the identifier for this decision (which is included in the decision log.) - Result interface{} // provides the output of query evaluation. + Result any // provides the output of query evaluation. Provenance types.ProvenanceV1 // wraps the bundle build/version information } @@ -365,8 +365,8 @@ func (opa *OPA) executeTransaction(ctx context.Context, record *server.Info, wor record.Metrics.Timer(metrics.SDKDecisionEval).Stop() if logger := logs.Lookup(s.manager); logger != nil { - // Decision log masking requires the event object to be a map[string]interface{}, - // or a []interface{}, and all internal objects referenced in the mask to be + // Decision log masking requires the event object to be a map[string]any, + // or a []any, and all internal objects referenced in the mask to be // similarly generic. Convert the input AST back into a JSON-representation to // ensure decision logging will work if the input Go type does not fit these requirements. if record.InputAST != nil { @@ -425,9 +425,9 @@ func (opa *OPA) Partial(ctx context.Context, options PartialOptions) (*PartialRe }) if record.Error == nil { result.Result, record.Error = options.Mapper.MapResults(pq) - var pqAst interface{} + var pqAst any if record.Error == nil { - var mappedResults interface{} + var mappedResults any mappedResults, record.Error = options.Mapper.ResultToJSON(result.Result) record.MappedResults = &mappedResults pqAst = pq @@ -450,15 +450,15 @@ func (opa *OPA) Partial(ctx context.Context, options PartialOptions) (*PartialRe type PartialQueryMapper interface { // The first interface being returned is the type that will be used for further processing - MapResults(pq *rego.PartialQueries) (interface{}, error) + MapResults(pq *rego.PartialQueries) (any, error) // This should be able to take the Result object from MapResults and return a type that can be logged as JSON - ResultToJSON(result interface{}) (interface{}, error) + ResultToJSON(result any) (any, error) } // PartialOptions contains parameters for partial query evaluation. type PartialOptions struct { Now time.Time // specifies wallclock time used for time.now_ns(), decision log timestamp, etc. - Input interface{} // specifies value of the input document to evaluate policy with + Input any // specifies value of the input document to evaluate policy with Query string // specifies the query to be partially evaluated Unknowns []string // specifies the unknown elements of the policy Mapper PartialQueryMapper // specifies the mapper to use when processing results @@ -472,7 +472,7 @@ type PartialOptions struct { type PartialResult struct { ID string // decision ID - Result interface{} // mapped result + Result any // mapped result AST *rego.PartialQueries // raw result Provenance types.ProvenanceV1 // wraps the bundle build/version information } @@ -516,7 +516,7 @@ type evalArgs struct { interQueryBuiltinValueCache cache.InterQueryValueCache now time.Time path string - input interface{} + input any ndbcache builtins.NDBCache m metrics.Metrics strictBuiltinErrors bool @@ -525,7 +525,7 @@ type evalArgs struct { instrument bool } -func evaluate(ctx context.Context, args evalArgs) (interface{}, types.ProvenanceV1, ast.Value, map[string]server.BundleInfo, error) { +func evaluate(ctx context.Context, args evalArgs) (any, types.ProvenanceV1, ast.Value, map[string]server.BundleInfo, error) { provenance := types.ProvenanceV1{ Version: version.Version, @@ -606,7 +606,7 @@ type partialEvalArgs struct { unknowns []string query string now time.Time - input interface{} + input any m metrics.Metrics strictBuiltinErrors bool tracer topdown.QueryTracer @@ -714,6 +714,6 @@ type loggingPrintHook struct { } func (h loggingPrintHook) Print(pctx print.Context, msg string) error { - h.logger.WithFields(map[string]interface{}{"line": pctx.Location.String()}).Info(msg) + h.logger.WithFields(map[string]any{"line": pctx.Location.String()}).Info(msg) return nil } diff --git a/v1/sdk/opa_test.go b/v1/sdk/opa_test.go index 68a0074296..365d74d763 100644 --- a/v1/sdk/opa_test.go +++ b/v1/sdk/opa_test.go @@ -107,9 +107,9 @@ loopback = input t.Fatal(`expected "foo" but got:`, decision) } - exp := map[string]interface{}{"foo": "bar"} + exp := map[string]any{"foo": "bar"} - if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/loopback", Input: map[string]interface{}{"foo": "bar"}}); err != nil { + if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/loopback", Input: map[string]any{"foo": "bar"}}); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(result.Result, exp) { t.Fatalf("expected %v but got %v", exp, result.Result) @@ -138,17 +138,17 @@ func (p *plugin) Stop(ctx context.Context) { } } -func (*plugin) Reconfigure(context.Context, interface{}) { +func (*plugin) Reconfigure(context.Context, any) { } -func (f factory) New(manager *plugins.Manager, _ interface{}) plugins.Plugin { +func (f factory) New(manager *plugins.Manager, _ any) plugins.Plugin { return &plugin{ manager: manager, shutdown: f.shutdown, } } -func (factory) Validate(*plugins.Manager, []byte) (interface{}, error) { +func (factory) Validate(*plugins.Manager, []byte) (any, error) { return nil, nil } @@ -326,8 +326,8 @@ main = time.now_ns() entries := testLogger.Entries() - if entries[0].Fields["labels"].(map[string]interface{})["id"] != "164031de-e511-11ec-8fea-0242ac120002" { - t.Fatalf("expected %v but got %v", "164031de-e511-11ec-8fea-0242ac120002", entries[0].Fields["labels"].(map[string]interface{})["id"]) + if entries[0].Fields["labels"].(map[string]any)["id"] != "164031de-e511-11ec-8fea-0242ac120002" { + t.Fatalf("expected %v but got %v", "164031de-e511-11ec-8fea-0242ac120002", entries[0].Fields["labels"].(map[string]any)["id"]) } } @@ -386,9 +386,9 @@ loopback = input t.Fatal(`expected "foo" but got:`, decision) } - exp := map[string]interface{}{"foo": "bar"} + exp := map[string]any{"foo": "bar"} - if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/loopback", Input: map[string]interface{}{"foo": "bar"}}); err != nil { + if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/loopback", Input: map[string]any{"foo": "bar"}}); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(result.Result, exp) { t.Fatalf("expected %v but got %v", exp, result.Result) @@ -1016,7 +1016,7 @@ allow if { defer opa.Stop(ctx) _, err = opa.Partial(ctx, sdk.PartialOptions{ - Input: map[string]interface{}{}, + Input: map[string]any{}, Query: "data.example.allow", Unknowns: []string{}, Mapper: &sdk.RawMapper{}, @@ -1085,7 +1085,7 @@ main if { tracer := topdown.NewBufferTracer() _, err = opa.Partial(ctx, sdk.PartialOptions{ - Input: map[string]interface{}{}, + Input: map[string]any{}, Query: "data.system.main", Unknowns: []string{}, Mapper: &sdk.RawMapper{}, @@ -1639,12 +1639,12 @@ mask contains "/input/dossier/1/highly" defer opa.Stop(ctx) if _, err := opa.Decision(ctx, sdk.DecisionOptions{ - Input: map[string]interface{}{ + Input: map[string]any{ "secret": "foo", "top": map[string]string{ "secret": "bar", }, - "dossier": []map[string]interface{}{ + "dossier": []map[string]any{ { "very": "private", }, @@ -1663,12 +1663,12 @@ mask contains "/input/dossier/1/highly" t.Fatalf("expected 1 entry but got %d", len(entries)) } - expectedErased := []interface{}{ + expectedErased := []any{ "/input/dossier/1/highly", "/input/secret", "/input/top/secret", } - erased := entries[0].Fields["erased"].([]interface{}) + erased := entries[0].Fields["erased"].([]any) stringLess := func(a, b string) bool { return a < b } @@ -1676,16 +1676,16 @@ mask contains "/input/dossier/1/highly" t.Errorf("Did not get expected result for erased field in decision log:\n%s", cmp.Diff(expectedErased, erased, cmpopts.SortSlices(stringLess))) } errMsg := `Expected masked field "%s" to be removed, but it was present.` - input := entries[0].Fields["input"].(map[string]interface{}) + input := entries[0].Fields["input"].(map[string]any) if _, ok := input["secret"]; ok { t.Errorf(errMsg, "/input/secret") } - if _, ok := input["top"].(map[string]interface{})["secret"]; ok { + if _, ok := input["top"].(map[string]any)["secret"]; ok { t.Errorf(errMsg, "/input/top/secret") } - if _, ok := input["dossier"].([]interface{})[1].(map[string]interface{})["highly"]; ok { + if _, ok := input["dossier"].([]any)[1].(map[string]any)["highly"]; ok { t.Errorf(errMsg, "/input/dossier/1/highly") } @@ -1752,11 +1752,11 @@ main = time.now_ns() // Check the contents of the ND builtins cache. if cache, ok := entries[0].Fields["nd_builtin_cache"]; ok { // Ensure the original cache entry for rand.intn is still there. - if _, ok := cache.(map[string]interface{})["rand.intn"]; !ok { + if _, ok := cache.(map[string]any)["rand.intn"]; !ok { t.Fatalf("ND builtins cache was not preserved during evaluation.") } // Ensure time.now_ns entry was picked up correctly. - if _, ok := cache.(map[string]interface{})["time.now_ns"]; !ok { + if _, ok := cache.(map[string]any)["time.now_ns"]; !ok { t.Fatalf("ND builtins cache did not observe time.now_ns call during evaluation.") } } else { @@ -2655,7 +2655,7 @@ result := { defer opa.Stop(ctx) - exp := map[string]interface{}{ + exp := map[string]any{ "service_url": server.URL(), "bundle_resource": testBundleResource, "test_label": testLabel, @@ -2726,7 +2726,7 @@ authenticatedUser := a if { exp := true - input := map[string]interface{}{} + input := map[string]any{} input["token"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWxpY2lhIFNtaXRoc29uaWFuIiwicm9sZXMiOlsicmVhZGVyIiwid3JpdGVyIl0sInVzZXJuYW1lIjoiYWxpY2UifQ.md2KPJFH9OgBq-N0RonGdf5doGYRO_1miN8ugTSeTYc" if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/grant", Input: input}); err != nil { @@ -2795,7 +2795,7 @@ authenticatedUser := a if { exp := true - input := map[string]interface{}{} + input := map[string]any{} input["token"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWxpY2lhIFNtaXRoc29uaWFuIiwicm9sZXMiOlsicmVhZGVyIiwid3JpdGVyIl0sInVzZXJuYW1lIjoiYWxpY2UifQ.md2KPJFH9OgBq-N0RonGdf5doGYRO_1miN8ugTSeTYc" if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/system/grant", Input: input}); err != nil { @@ -2969,7 +2969,7 @@ func TestActivateV1Bundles(t *testing.T) { d, err := opa.Decision(context.Background(), sdk.DecisionOptions{ Path: "v1bundle/authz", - Input: map[string]interface{}{ + Input: map[string]any{ "role": "admin", }, }) diff --git a/v1/sdk/test/test.go b/v1/sdk/test/test.go index 04b9ce66ff..0925513621 100644 --- a/v1/sdk/test/test.go +++ b/v1/sdk/test/test.go @@ -159,7 +159,7 @@ func (s *Server) buildBundles(ref string, policies map[string]string) error { bundleManifest.Init() err := compile.New().WithOutput(buf).WithBundle(&bundle.Bundle{ - Data: map[string]interface{}{}, + Data: map[string]any{}, Modules: modules, Manifest: bundleManifest, }).Build(context.Background()) @@ -399,7 +399,7 @@ func (s *Server) handleBundles(w http.ResponseWriter, r *http.Request) { } // Prepare a mapping to store bundle data - data := map[string]interface{}{} + data := map[string]any{} // Prepare a manifest for use if a .manifest file exists. var manifest bundle.Manifest @@ -433,7 +433,7 @@ func (s *Server) handleBundles(w http.ResponseWriter, r *http.Request) { return } - var d map[string]interface{} + var d map[string]any err := json.Unmarshal([]byte(str), &d) if err != nil { diff --git a/v1/server/authorizer/authorizer.go b/v1/server/authorizer/authorizer.go index f3a0ea2814..23b4b710de 100644 --- a/v1/server/authorizer/authorizer.go +++ b/v1/server/authorizer/authorizer.go @@ -137,7 +137,7 @@ func (h *Basic) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.inner.ServeHTTP(w, r) return } - case map[string]interface{}: + case map[string]any: if decision, ok := allowed["allowed"]; ok { if allow, ok := decision.(bool); ok && allow { h.inner.ServeHTTP(w, r) @@ -158,7 +158,7 @@ func (h *Basic) ServeHTTP(w http.ResponseWriter, r *http.Request) { writer.Error(w, http.StatusUnauthorized, types.NewErrorV1(types.CodeUnauthorized, types.MsgUnauthorizedError)) } -func makeInput(r *http.Request) (*http.Request, interface{}, error) { +func makeInput(r *http.Request) (*http.Request, any, error) { path, err := parsePath(r.URL.Path) if err != nil { return r, nil, err @@ -177,7 +177,7 @@ func makeInput(r *http.Request) (*http.Request, interface{}, error) { } } - input := map[string]interface{}{ + input := map[string]any{ "path": path, "method": method, "params": query, @@ -185,7 +185,7 @@ func makeInput(r *http.Request) (*http.Request, interface{}, error) { } if len(rawBody) > 0 { - var body interface{} + var body any if expectYAML(r) { if err := util.Unmarshal(rawBody, &body); err != nil { return r, nil, err @@ -219,7 +219,7 @@ var dataAPIVersions = map[string]bool{ "v1": true, } -func expectBody(method string, path []interface{}) bool { +func expectBody(method string, path []any) bool { if method == http.MethodPost { if len(path) == 1 { s := path[0].(string) @@ -240,9 +240,9 @@ func expectYAML(r *http.Request) bool { return strings.Contains(r.Header.Get("Content-Type"), "yaml") } -func parsePath(path string) ([]interface{}, error) { +func parsePath(path string) ([]any, error) { if len(path) == 0 { - return []interface{}{}, nil + return []any{}, nil } parts := strings.Split(path[1:], "/") for i := range parts { @@ -252,7 +252,7 @@ func parsePath(path string) ([]interface{}, error) { return nil, err } } - sl := make([]interface{}, len(parts)) + sl := make([]any, len(parts)) for i := range sl { sl[i] = parts[i] } @@ -260,7 +260,7 @@ func parsePath(path string) ([]interface{}, error) { } type authorizerCachedBody struct { - parsed interface{} + parsed any } type authorizerCachedBodyKey string @@ -269,7 +269,7 @@ const ctxkey authorizerCachedBodyKey = "authorizerCachedBodyKey" // SetBodyOnContext adds the parsed input value to the context. This function is only // exposed for test purposes. -func SetBodyOnContext(ctx context.Context, x interface{}) context.Context { +func SetBodyOnContext(ctx context.Context, x any) context.Context { return context.WithValue(ctx, ctxkey, authorizerCachedBody{ parsed: x, }) @@ -277,7 +277,7 @@ func SetBodyOnContext(ctx context.Context, x interface{}) context.Context { // GetBodyOnContext returns the parsed input from the request context if it exists. // The authorizer saves the parsed input on the context when it runs. -func GetBodyOnContext(ctx context.Context) (interface{}, bool) { +func GetBodyOnContext(ctx context.Context) (any, bool) { input, ok := ctx.Value(ctxkey).(authorizerCachedBody) if !ok { return nil, false diff --git a/v1/server/authorizer/authorizer_test.go b/v1/server/authorizer/authorizer_test.go index d7c6229d73..b86eb93bf6 100644 --- a/v1/server/authorizer/authorizer_test.go +++ b/v1/server/authorizer/authorizer_test.go @@ -174,7 +174,7 @@ func TestBasic(t *testing.T) { } `)) - store := inmem.NewFromObject(data.(map[string]interface{})) + store := inmem.NewFromObject(data.(map[string]any)) tests := []struct { note string @@ -235,7 +235,7 @@ func TestBasic(t *testing.T) { // Check code/message if response should be error. if tc.expectedStatus != http.StatusOK { - var x interface{} + var x any if err := util.NewJSONDecoder(recorder.Body).Decode(&x); err != nil { t.Fatalf("Expected JSON response but got: %v", recorder) } @@ -415,7 +415,7 @@ func TestMakeInputWithBody(t *testing.T) { if tc.assertBodyExists { - var want interface{} + var want any if tc.useYAML { if err := util.Unmarshal([]byte(tc.body), &want); err != nil { @@ -425,7 +425,7 @@ func TestMakeInputWithBody(t *testing.T) { want = util.MustUnmarshalJSON([]byte(tc.body)) } - body := input.(map[string]interface{})["body"] + body := input.(map[string]any)["body"] if !reflect.DeepEqual(body, want) { t.Fatalf("expected parsed bodies to be equal but got %v and want %v", body, want) @@ -438,7 +438,7 @@ func TestMakeInputWithBody(t *testing.T) { } if tc.assertBodyDoesNotExist { - _, ok := input.(map[string]interface{})["body"] + _, ok := input.(map[string]any)["body"] if ok { t.Fatal("expected no parsed body in input") } diff --git a/v1/server/buffer.go b/v1/server/buffer.go index 8c805a31c9..4a52e6f0e7 100644 --- a/v1/server/buffer.go +++ b/v1/server/buffer.go @@ -27,11 +27,11 @@ type Info struct { Query string Path string Timestamp time.Time - Input *interface{} + Input *any InputAST ast.Value - Results *interface{} - MappedResults *interface{} - NDBuiltinCache *interface{} + Results *any + MappedResults *any + NDBuiltinCache *any Error error Metrics metrics.Metrics Trace []*topdown.Event diff --git a/v1/server/cache.go b/v1/server/cache.go index ae56386b67..c56ac2e085 100644 --- a/v1/server/cache.go +++ b/v1/server/cache.go @@ -3,7 +3,7 @@ package server import "sync" type cache struct { - data map[string]interface{} + data map[string]any keylist []string idx int maxSize int @@ -12,20 +12,20 @@ type cache struct { func newCache(maxSize int) *cache { return &cache{ - data: map[string]interface{}{}, + data: map[string]any{}, keylist: []string{}, maxSize: maxSize, } } -func (c *cache) Get(k string) (interface{}, bool) { +func (c *cache) Get(k string) (any, bool) { c.mtx.RLock() v, ok := c.data[k] c.mtx.RUnlock() return v, ok } -func (c *cache) Insert(k string, v interface{}) { +func (c *cache) Insert(k string, v any) { // Short path if its already in the cache _, ok := c.Get(k) diff --git a/v1/server/cache_test.go b/v1/server/cache_test.go index 01f6d4872b..06bd22ce12 100644 --- a/v1/server/cache_test.go +++ b/v1/server/cache_test.go @@ -64,7 +64,7 @@ func TestCacheLimit(t *testing.T) { } } -func ensureCacheKey(t *testing.T, c *cache, k string, v interface{}) { +func ensureCacheKey(t *testing.T, c *cache, k string, v any) { t.Helper() actual, ok := c.Get(k) if !ok || v != actual { diff --git a/v1/server/handlers/compress.go b/v1/server/handlers/compress.go index 26cfc02e55..583dd1828e 100644 --- a/v1/server/handlers/compress.go +++ b/v1/server/handlers/compress.go @@ -66,7 +66,7 @@ var gzipPool *sync.Pool func initGzipPool(compressionLevel int) { if gzipPool == nil { gzipPool = &sync.Pool{ - New: func() interface{} { + New: func() any { writer, _ := gzip.NewWriterLevel(io.Discard, compressionLevel) return writer }, diff --git a/v1/server/server.go b/v1/server/server.go index a412561392..021b2ad716 100644 --- a/v1/server/server.go +++ b/v1/server/server.go @@ -608,7 +608,7 @@ func (s *Server) getListener(addr string, h http.Handler, t httpListenerType) ([ loops = []Loop{loop} case "https": loop, listener, err = s.getListenerForHTTPSServer(parsedURL, h, t) - logger := s.manager.Logger().WithFields(map[string]interface{}{ + logger := s.manager.Logger().WithFields(map[string]any{ "cert-file": s.certFile, "cert-key-file": s.certKeyFile, }) @@ -914,7 +914,7 @@ func (s *Server) instrumentHandler(handler func(http.ResponseWriter, *http.Reque return httpHandler } -func (s *Server) execQuery(ctx context.Context, br bundleRevisions, txn storage.Transaction, parsedQuery ast.Body, input ast.Value, rawInput *interface{}, m metrics.Metrics, explainMode types.ExplainModeV1, includeMetrics, includeInstrumentation, pretty bool) (*types.QueryResponseV1, error) { +func (s *Server) execQuery(ctx context.Context, br bundleRevisions, txn storage.Transaction, parsedQuery ast.Body, input ast.Value, rawInput *any, m metrics.Metrics, explainMode types.ExplainModeV1, includeMetrics, includeInstrumentation, pretty bool) (*types.QueryResponseV1, error) { results := types.QueryResponseV1{} logger := s.getDecisionLogger(br) @@ -973,7 +973,7 @@ func (s *Server) execQuery(ctx context.Context, br bundleRevisions, txn storage. results.Explanation = s.getExplainResponse(explainMode, *buf, pretty) } - var x interface{} = results.Result + var x any = results.Result if err := logger.Log(ctx, txn, "", parsedQuery.String(), rawInput, input, &x, ndbCache, nil, m); err != nil { return nil, err } @@ -1294,7 +1294,7 @@ func (s *Server) unversionedGetHealthWithPolicy(w http.ResponseWriter, r *http.R allPluginsOk := true // build input document for health check query - input := func() map[string]interface{} { + input := func() map[string]any { s.mtx.Lock() defer s.mtx.Unlock() @@ -1314,7 +1314,7 @@ func (s *Server) unversionedGetHealthWithPolicy(w http.ResponseWriter, r *http.R s.allPluginsOkOnce = true } - return map[string]interface{}{ + return map[string]any{ "plugin_state": pluginState, "plugins_ready": s.allPluginsOkOnce, } @@ -1448,7 +1448,7 @@ func (s *Server) v1CompilePost(w http.ResponseWriter, r *http.Request) { result.Explanation = s.getExplainResponse(explainMode, *buf, pretty(r)) } - var i interface{} = types.PartialEvaluationResultV1{ + var i any = types.PartialEvaluationResultV1{ Queries: pq.Queries, Support: pq.Support, } @@ -1479,7 +1479,7 @@ func (s *Server) v1DataGet(w http.ResponseWriter, r *http.Request) { inputs := r.URL.Query()[types.ParamInputV1] var input ast.Value - var goInput *interface{} + var goInput *any if len(inputs) > 0 { var err error @@ -1855,7 +1855,7 @@ func (s *Server) v1DataPut(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) m.Timer(metrics.RegoInputParse).Start() - var value interface{} + var value any if err := util.NewJSONDecoder(r.Body).Decode(&value); err != nil { writer.ErrorString(w, http.StatusBadRequest, types.CodeInvalidParameter, err) return @@ -2390,7 +2390,7 @@ func (s *Server) v1StatusGet(w http.ResponseWriter, r *http.Request) { return } - var st interface{} = p.Snapshot() + var st any = p.Snapshot() writer.JSONOK(w, types.StatusResponseV1{Result: &st}, pretty(r)) } @@ -2824,7 +2824,7 @@ func getExplain(p []string, zero types.ExplainModeV1) types.ExplainModeV1 { return zero } -func readInputV0(r *http.Request) (ast.Value, *interface{}, error) { +func readInputV0(r *http.Request) (ast.Value, *any, error) { parsed, ok := authorizer.GetBodyOnContext(r.Context()) if ok { @@ -2838,7 +2838,7 @@ func readInputV0(r *http.Request) (ast.Value, *interface{}, error) { return nil, nil, fmt.Errorf("could not decompress the body: %w", err) } - var x interface{} + var x any if strings.Contains(r.Header.Get("Content-Type"), "yaml") { if len(bodyBytes) > 0 { @@ -2857,8 +2857,8 @@ func readInputV0(r *http.Request) (ast.Value, *interface{}, error) { return v, &x, err } -func readInputGetV1(str string) (ast.Value, *interface{}, error) { - var input interface{} +func readInputGetV1(str string) (ast.Value, *any, error) { + var input any if err := util.UnmarshalJSON([]byte(str), &input); err != nil { return nil, nil, fmt.Errorf("parameter contains malformed input document: %w", err) } @@ -2866,11 +2866,11 @@ func readInputGetV1(str string) (ast.Value, *interface{}, error) { return v, &input, err } -func readInputPostV1(r *http.Request) (ast.Value, *interface{}, error) { +func readInputPostV1(r *http.Request) (ast.Value, *any, error) { parsed, ok := authorizer.GetBodyOnContext(r.Context()) if ok { - if obj, ok := parsed.(map[string]interface{}); ok { + if obj, ok := parsed.(map[string]any); ok { if input, ok := obj["input"]; ok { v, err := ast.InterfaceToValue(input) return v, &input, err @@ -3036,7 +3036,7 @@ type decisionLogger struct { logger func(context.Context, *Info) error } -func (l decisionLogger) Log(ctx context.Context, txn storage.Transaction, path string, query string, goInput *interface{}, astInput ast.Value, goResults *interface{}, ndbCache builtins.NDBCache, err error, m metrics.Metrics) error { +func (l decisionLogger) Log(ctx context.Context, txn storage.Transaction, path string, query string, goInput *any, astInput ast.Value, goResults *any, ndbCache builtins.NDBCache, err error, m metrics.Metrics) error { bundles := map[string]BundleInfo{} for name, rev := range l.revisions { @@ -3100,7 +3100,7 @@ func (l decisionLogger) Log(ctx context.Context, txn storage.Transaction, path s type patchImpl struct { path storage.Path op storage.PatchOp - value interface{} + value any } func parseURL(s string, useHTTPSByDefault bool) (*url.URL, error) { diff --git a/v1/server/server_test.go b/v1/server/server_test.go index 5cc55a5516..8751a9804d 100644 --- a/v1/server/server_test.go +++ b/v1/server/server_test.go @@ -1776,11 +1776,11 @@ func TestConfigV1(t *testing.T) { f.server.manager.Config = conf - expected := map[string]interface{}{ - "result": map[string]interface{}{ - "labels": map[string]interface{}{"id": "foo", "version": version.Version, "region": "west"}, - "keys": map[string]interface{}{"global_key": map[string]interface{}{"algorithm": "HS256"}}, - "services": map[string]interface{}{"acmecorp": map[string]interface{}{"url": "https://example.com/control-plane-api/v1"}}, + expected := map[string]any{ + "result": map[string]any{ + "labels": map[string]any{"id": "foo", "version": version.Version, "region": "west"}, + "keys": map[string]any{"global_key": map[string]any{"algorithm": "HS256"}}, + "services": map[string]any{"acmecorp": map[string]any{"url": "https://example.com/control-plane-api/v1"}}, "default_authorization_decision": "/system/authz/allow", "default_decision": "/system/main", }, @@ -1896,21 +1896,21 @@ func mustGZIPPayload(payload []byte) []byte { // generateJSONBenchmarkData returns a map of `k` keys and `v` key/value pairs. // Taken from topdown/topdown_bench_test.go -func generateJSONBenchmarkData(k, v int) map[string]interface{} { +func generateJSONBenchmarkData(k, v int) map[string]any { // create array of null values that can be iterated over - keys := make([]interface{}, k) + keys := make([]any, k) for i := range keys { keys[i] = nil } // create large JSON object value (100,000 entries is about 2MB on disk) - values := map[string]interface{}{} + values := map[string]any{} for i := range v { values[fmt.Sprintf("key%d", i)] = fmt.Sprintf("value%d", i) } - return map[string]interface{}{ - "input": map[string]interface{}{ + return map[string]any{ + "input": map[string]any{ "keys": keys, "values": values, }, @@ -2356,7 +2356,7 @@ hello if { } } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(`{"hello": true}`), &expected); err != nil { panic(err) } @@ -2445,7 +2445,7 @@ func TestCompileV1CompressedResponse(t *testing.T) { } } - var expected interface{} + var expected any expectedStr := fmt.Sprintf(`{"queries": [%v]}`, string(util.MustMarshalJSON(ast.MustParseBody("input.x = 1")))) if err := util.UnmarshalJSON([]byte(expectedStr), &expected); err != nil { panic(err) @@ -2515,7 +2515,7 @@ hello if { t.Fatalf("Unexpected JSON decode error: %v", err) } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(`{"hello": true}`), &expected); err != nil { panic(err) } @@ -2567,7 +2567,7 @@ func TestCompileV1CompressedRequest(t *testing.T) { t.Fatalf("Unexpected JSON decode error: %v", err) } - var expected interface{} + var expected any expectedStr := fmt.Sprintf(`{"queries": [%v]}`, string(util.MustMarshalJSON(ast.MustParseBody("input.x = 1")))) if err := util.UnmarshalJSON([]byte(expectedStr), &expected); err != nil { panic(err) @@ -2877,7 +2877,7 @@ func TestDataUpdate(t *testing.T) { t.Fatalf("Unexpected JSON decode error: %v", err) } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(putData), &expected); err != nil { t.Fatalf("Unexpected JSON decode error: %v", err) } @@ -2988,13 +2988,13 @@ func TestDataGetExplainFull(t *testing.T) { t.Fatalf("Unexpected JSON decode error: %v", err) } - exp := []interface{}{ + exp := []any{ `query:1 Enter data.x = _`, `query:1 | Eval data.x = _`, `query:1 | Exit data.x = _`, `query:1 Redo data.x = _`, `query:1 | Redo data.x = _`} - actual := util.MustUnmarshalJSON(result.Explanation).([]interface{}) + actual := util.MustUnmarshalJSON(result.Explanation).([]any) if !reflect.DeepEqual(actual, exp) { t.Fatalf(`Expected pretty explanation to be %v, got %v`, exp, actual) } @@ -3028,7 +3028,7 @@ p = [1, 2, 3, 4] if { true }`, 200, "") t.Fatalf("Unexpected JSON decode error: %v", err) } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(`[1,2,3,4]`), &expected); err != nil { panic(err) @@ -3069,7 +3069,7 @@ p = [1, 2, 3, 4] if { true }`, 200, "") t.Fatalf("Expected exactly %d events but got %d", nexpect, len(explain)) } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(`[1,2,3,4]`), &expected); err != nil { panic(err) @@ -3526,7 +3526,7 @@ r contains x if { z[x] = 4 }` f.server.Handler.ServeHTTP(f.recorder, req) - var response map[string]interface{} + var response map[string]any if err := json.NewDecoder(f.recorder.Body).Decode(&response); err != nil { t.Fatalf("Unexpected error while unmarshalling response: %v", err) } @@ -3537,9 +3537,9 @@ r contains x if { z[x] = 4 }` } var errs []string - if errors, ok := response["errors"].([]interface{}); ok { + if errors, ok := response["errors"].([]any); ok { for _, err := range errors { - errs = append(errs, err.(map[string]interface{})["message"].(string)) + errs = append(errs, err.(map[string]any)["message"].(string)) } } @@ -3597,7 +3597,7 @@ func TestPoliciesPutV1ParseError(t *testing.T) { t.Fatalf("Expected bad request but got %v", f.recorder) } - response := map[string]interface{}{} + response := map[string]any{} if err := util.NewJSONDecoder(f.recorder.Body).Decode(&response); err != nil { t.Fatalf("Unexpected JSON decode error: %v", err) @@ -3653,7 +3653,7 @@ q[x] { p[x] }`, t.Fatalf("Expected bad request but got %v", f.recorder) } - response := map[string]interface{}{} + response := map[string]any{} if err := util.NewJSONDecoder(f.recorder.Body).Decode(&response); err != nil { t.Fatalf("Unexpected JSON decode error: %v", err) @@ -3828,7 +3828,7 @@ func TestPoliciesDeleteV1(t *testing.T) { t.Fatalf("Expected success but got %v", f.recorder) } - var response map[string]interface{} + var response map[string]any if err := json.NewDecoder(f.recorder.Body).Decode(&response); err != nil { t.Fatalf("Unexpected unmarshal error: %v", err) } @@ -4028,8 +4028,8 @@ func TestStatusV1MetricsWithSystemAuthzPolicy(t *testing.T) { // Add Prometheus Registerer to be used by plugins inner := metrics.New() - logger := func(logger logging.Logger) func(attrs map[string]interface{}, f string, a ...interface{}) { - return func(attrs map[string]interface{}, f string, a ...interface{}) { + logger := func(logger logging.Logger) func(attrs map[string]any, f string, a ...any) { + return func(attrs map[string]any, f string, a ...any) { logger.WithFields(attrs).Error(f, a...) } }(logging.NewNoOpLogger()) @@ -4130,7 +4130,7 @@ func TestStatusV1MetricsWithSystemAuthzPolicy(t *testing.T) { State string } } - Metrics map[string]interface{} + Metrics map[string]any } } if err := util.NewJSONDecoder(f.recorder.Body).Decode(&resp); err != nil { @@ -4144,30 +4144,30 @@ func TestStatusV1MetricsWithSystemAuthzPolicy(t *testing.T) { t.Fatal("expected prometheus metrics to be present in status") } - promMet, ok := met.(map[string]interface{}) + promMet, ok := met.(map[string]any) if !ok { t.Fatal("expected prometheus metrics to be a map") } - httpMet, ok := promMet["http_request_duration_seconds"].(map[string]interface{}) + httpMet, ok := promMet["http_request_duration_seconds"].(map[string]any) if !ok { t.Fatal("expected http_request_duration_seconds metric to be a map") } - innerMet, ok := httpMet["metric"].([]interface{}) + innerMet, ok := httpMet["metric"].([]any) if !ok { t.Fatal("expected http_request_duration_seconds histogram metric to be a list") } - expected := []interface{}{map[string]interface{}{"name": "code", "value": "401"}, - map[string]interface{}{"name": "handler", "value": "authz"}, - map[string]interface{}{"name": "method", "value": "get"}} + expected := []any{map[string]any{"name": "code", "value": "401"}, + map[string]any{"name": "handler", "value": "authz"}, + map[string]any{"name": "method", "value": "get"}} found := false for _, m := range innerMet { - item, ok := m.(map[string]interface{}) + item, ok := m.(map[string]any) if ok { - if reflect.DeepEqual(item["label"].([]interface{}), expected) { + if reflect.DeepEqual(item["label"].([]any), expected) { found = true break } @@ -5033,8 +5033,8 @@ func TestServerUsesAuthorizerParsedBody(t *testing.T) { } // Set the authorizer's parsed input to the expected message body. - ctx := authorizer.SetBodyOnContext(req.Context(), map[string]interface{}{ - "input": map[string]interface{}{ + ctx := authorizer.SetBodyOnContext(req.Context(), map[string]any{ + "input": map[string]any{ "foo": "good", }, }) @@ -5056,7 +5056,7 @@ func TestServerUsesAuthorizerParsedBody(t *testing.T) { } // Check that v0 reader function behaves correctly. - ctx = authorizer.SetBodyOnContext(req.Context(), map[string]interface{}{ + ctx = authorizer.SetBodyOnContext(req.Context(), map[string]any{ "foo": "good", }) @@ -5144,7 +5144,7 @@ type queryBindingErrStore struct { storage.PolicyNotSupported } -func (*queryBindingErrStore) Read(_ context.Context, _ storage.Transaction, _ storage.Path) (interface{}, error) { +func (*queryBindingErrStore) Read(_ context.Context, _ storage.Transaction, _ storage.Path) (any, error) { return nil, errors.New("expected error") } @@ -5380,11 +5380,11 @@ func (f *fixture) executeRequestForHandler(h http.Handler, req *http.Request, co return fmt.Errorf("Expected code %v from %v %v but got: %+v", code, req.Method, req.URL, f.recorder) } if resp != "" { - var result interface{} + var result any if err := util.UnmarshalJSON(f.recorder.Body.Bytes(), &result); err != nil { return fmt.Errorf("Expected JSON response from %v %v but got: %v", req.Method, req.URL, f.recorder) } - var expected interface{} + var expected any if err := util.UnmarshalJSON([]byte(resp), &expected); err != nil { panic(err) } diff --git a/v1/server/types/types.go b/v1/server/types/types.go index add9d91916..47df8f8765 100644 --- a/v1/server/types/types.go +++ b/v1/server/types/types.go @@ -36,7 +36,7 @@ type ErrorV1 struct { } // NewErrorV1 returns a new ErrorV1 object. -func NewErrorV1(code, f string, a ...interface{}) *ErrorV1 { +func NewErrorV1(code, f string, a ...any) *ErrorV1 { return &ErrorV1{ Code: code, Message: fmt.Sprintf(f, a...), @@ -87,9 +87,9 @@ const ( // PatchV1 models a single patch operation against a document. type PatchV1 struct { - Op string `json:"op"` - Path string `json:"path"` - Value interface{} `json:"value"` + Op string `json:"op"` + Path string `json:"path"` + Value any `json:"value"` } // PolicyListResponseV1 models the response message for the Policy API list operation. @@ -141,7 +141,7 @@ type ProvenanceBundleV1 struct { // DataRequestV1 models the request message for Data API POST operations. type DataRequestV1 struct { - Input *interface{} `json:"input"` + Input *any `json:"input"` } // DataResponseV1 models the response message for Data API read operations. @@ -150,7 +150,7 @@ type DataResponseV1 struct { Provenance *ProvenanceV1 `json:"provenance,omitempty"` Explanation TraceV1 `json:"explanation,omitempty"` Metrics MetricsV1 `json:"metrics,omitempty"` - Result *interface{} `json:"result,omitempty"` + Result *any `json:"result,omitempty"` Warning *Warning `json:"warning,omitempty"` } @@ -172,7 +172,7 @@ func NewWarning(code, message string) *Warning { } // MetricsV1 models a collection of performance metrics. -type MetricsV1 map[string]interface{} +type MetricsV1 map[string]any // QueryResponseV1 models the response message for Query API operations. type QueryResponseV1 struct { @@ -182,7 +182,7 @@ type QueryResponseV1 struct { } // AdhocQueryResultSetV1 models the result of a Query API query. -type AdhocQueryResultSetV1 []map[string]interface{} +type AdhocQueryResultSetV1 []map[string]any // ExplainModeV1 defines supported values for the "explain" query parameter. type ExplainModeV1 string @@ -286,13 +286,13 @@ func newPrettyTraceV1(trace []*topdown.Event) (TraceV1, error) { // TraceEventV1 represents a step in the query evaluation process. type TraceEventV1 struct { - Op string `json:"op"` - QueryID uint64 `json:"query_id"` - ParentID uint64 `json:"parent_id"` - Type string `json:"type"` - Node interface{} `json:"node"` - Locals BindingsV1 `json:"locals"` - Message string `json:"message,omitempty"` + Op string `json:"op"` + QueryID uint64 `json:"query_id"` + ParentID uint64 `json:"parent_id"` + Type string `json:"type"` + Node any `json:"node"` + Locals BindingsV1 `json:"locals"` + Message string `json:"message,omitempty"` } // UnmarshalJSON deserializes a TraceEventV1 object. The Node field is @@ -370,9 +370,9 @@ func NewBindingsV1(locals *ast.ValueMap) (result []*BindingV1) { // CompileRequestV1 models the request message for Compile API operations. type CompileRequestV1 struct { - Input *interface{} `json:"input"` - Query string `json:"query"` - Unknowns *[]string `json:"unknowns"` + Input *any `json:"input"` + Query string `json:"query"` + Unknowns *[]string `json:"unknowns"` Options struct { DisableInlining []string `json:"disableInlining,omitempty"` NondeterministicBuiltins bool `json:"nondeterministicBuiltins"` @@ -381,9 +381,9 @@ type CompileRequestV1 struct { // CompileResponseV1 models the response message for Compile API operations. type CompileResponseV1 struct { - Result *interface{} `json:"result,omitempty"` - Explanation TraceV1 `json:"explanation,omitempty"` - Metrics MetricsV1 `json:"metrics,omitempty"` + Result *any `json:"result,omitempty"` + Explanation TraceV1 `json:"explanation,omitempty"` + Metrics MetricsV1 `json:"metrics,omitempty"` } // PartialEvaluationResultV1 represents the output of partial evaluation and is @@ -395,18 +395,18 @@ type PartialEvaluationResultV1 struct { // QueryRequestV1 models the request message for Query API operations. type QueryRequestV1 struct { - Query string `json:"query"` - Input *interface{} `json:"input"` + Query string `json:"query"` + Input *any `json:"input"` } // ConfigResponseV1 models the response message for Config API operations. type ConfigResponseV1 struct { - Result *interface{} `json:"result,omitempty"` + Result *any `json:"result,omitempty"` } // StatusResponseV1 models the response message for Status API (pull) operations. type StatusResponseV1 struct { - Result *interface{} `json:"result,omitempty"` + Result *any `json:"result,omitempty"` } // HealthResponseV1 models the response message for Health API operations. diff --git a/v1/server/writer/writer.go b/v1/server/writer/writer.go index 8cf1e3090f..eb968adade 100644 --- a/v1/server/writer/writer.go +++ b/v1/server/writer/writer.go @@ -59,7 +59,7 @@ func Error(w http.ResponseWriter, status int, err *types.ErrorV1) { // Deprecated: This method is problematic when using a non-200 status `code`: if // encoding the payload fails, it'll print "superfluous call to WriteHeader()" // logs. -func JSON(w http.ResponseWriter, code int, v interface{}, pretty bool) { +func JSON(w http.ResponseWriter, code int, v any, pretty bool) { enc := json.NewEncoder(w) if pretty { enc.SetIndent("", " ") @@ -75,7 +75,7 @@ func JSON(w http.ResponseWriter, code int, v interface{}, pretty bool) { } // JSONOK is a helper for status "200 OK" responses -func JSONOK(w http.ResponseWriter, v interface{}, pretty bool) { +func JSONOK(w http.ResponseWriter, v any, pretty bool) { enc := json.NewEncoder(w) if pretty { enc.SetIndent("", " ") diff --git a/v1/storage/disk/disk.go b/v1/storage/disk/disk.go index 6db611d5a1..99e0fd155c 100644 --- a/v1/storage/disk/disk.go +++ b/v1/storage/disk/disk.go @@ -217,16 +217,16 @@ type wrap struct { l logging.Logger } -func (w *wrap) debugDo(f func(string, ...interface{}), fmt string, as ...interface{}) { +func (w *wrap) debugDo(f func(string, ...any), fmt string, as ...any) { if w.l.GetLevel() >= logging.Debug { f("badger: "+fmt, as...) } } -func (w *wrap) Debugf(f string, as ...interface{}) { w.debugDo(w.l.Debug, f, as...) } -func (w *wrap) Infof(f string, as ...interface{}) { w.debugDo(w.l.Info, f, as...) } -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...) } +func (w *wrap) Debugf(f string, as ...any) { w.debugDo(w.l.Debug, f, as...) } +func (w *wrap) Infof(f string, as ...any) { w.debugDo(w.l.Info, f, as...) } +func (w *wrap) Warningf(f string, as ...any) { w.debugDo(w.l.Warn, f, as...) } +func (w *wrap) Errorf(f string, as ...any) { w.debugDo(w.l.Error, f, as...) } // NewTransaction implements the storage.Store interface. func (db *Store) NewTransaction(_ context.Context, params ...storage.TransactionParams) (storage.Transaction, error) { @@ -283,7 +283,7 @@ func (db *Store) Truncate(ctx context.Context, txn storage.Transaction, params s return fmt.Errorf("storage path invalid: %v", newPath) } - sTxn, err := db.doTruncateData(ctx, underlyingTxn, db.db, params, newPath, map[string]interface{}{}) + sTxn, err := db.doTruncateData(ctx, underlyingTxn, db.db, params, newPath, map[string]any{}) if err != nil { return wrapError(err) } @@ -387,7 +387,7 @@ func (db *Store) Truncate(ctx context.Context, txn storage.Transaction, params s } func (db *Store) doTruncateData(ctx context.Context, underlying *transaction, badgerdb *badger.DB, - params storage.TransactionParams, path storage.Path, value interface{}) (*transaction, error) { + params storage.TransactionParams, path storage.Path, value any) (*transaction, error) { err := underlying.Write(ctx, storage.AddOp, path, value) if err != nil { @@ -606,7 +606,7 @@ func (db *Store) Register(_ context.Context, txn storage.Transaction, config sto } // Read implements the storage.Store interface. -func (db *Store) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (interface{}, error) { +func (db *Store) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (any, error) { underlying, err := db.underlying(txn) if err != nil { return nil, err @@ -615,7 +615,7 @@ func (db *Store) Read(ctx context.Context, txn storage.Transaction, path storage } // Write implements the storage.Store interface. -func (db *Store) Write(ctx context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value interface{}) error { +func (db *Store) Write(ctx context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value any) error { underlying, err := db.underlying(txn) if err != nil { return err @@ -993,7 +993,7 @@ func createSymlink(target, symlink string) error { return lerr } -func lookup(path storage.Path, data []byte) (interface{}, bool, error) { +func lookup(path storage.Path, data []byte) (any, bool, error) { var obj map[string]json.RawMessage err := util.Unmarshal(data, &obj) if err != nil { diff --git a/v1/storage/disk/disk_test.go b/v1/storage/disk/disk_test.go index 5ace17e03a..cb41938865 100644 --- a/v1/storage/disk/disk_test.go +++ b/v1/storage/disk/disk_test.go @@ -623,12 +623,12 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { tests := []struct { note string partitions []string - sequence []interface{} + sequence []any }{ { note: "exact-match: add", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -644,7 +644,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "exact-match: add: multi-level", partitions: []string{"/foo/bar"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar/baz", @@ -660,7 +660,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "exact-match: unpartitioned", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/deadbeef", @@ -677,7 +677,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "exact-match: remove", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -701,7 +701,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read: sub-field", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -718,7 +718,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: add", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -738,7 +738,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: add: unpartitioned", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/deadbeef", @@ -758,7 +758,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: add: array append", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -778,7 +778,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: add: array append (via last index)", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -798,7 +798,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: add: array insert", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -818,7 +818,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: replace", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -838,7 +838,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: replace: array", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -858,7 +858,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: remove", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -877,7 +877,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: remove: array", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -896,7 +896,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: multi-level: map", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -916,7 +916,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "read-modify-write: multi-level: array", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -936,7 +936,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "prefix", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -960,7 +960,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { }, { note: "prefix: unpartitioned: root", - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/deadbeef", @@ -975,7 +975,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "prefix: unpartitioned: mixed", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/", @@ -1006,7 +1006,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "prefix: overwrite", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/", @@ -1026,7 +1026,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "prefix: remove", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/", @@ -1050,7 +1050,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { }, { note: "issue-3711: string-to-number conversion", - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/", @@ -1067,7 +1067,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "pattern partitions: middle wildcard: match", partitions: []string{"/foo/*/bar"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/a/bar", @@ -1080,7 +1080,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "pattern partitions: middle wildcard: no-match", partitions: []string{"/foo/*/bar"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/b/baz", @@ -1094,7 +1094,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "pattern partitions: middle wildcard: partial match", partitions: []string{"/foo/*/bar"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/b", @@ -1109,7 +1109,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "pattern partitions: 2x middle wildcard: partial match", partitions: []string{"/foo/*/*/bar"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/b/c", @@ -1124,7 +1124,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { { note: "pattern partitions: wildcard at the end", partitions: []string{"/users/*"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/users", @@ -1176,7 +1176,7 @@ func TestDataPartitioningReadsAndWrites(t *testing.T) { if err != nil { t.Fatal(err) } - var exp interface{} + var exp any if x.exp != "" { exp = util.MustUnmarshalJSON([]byte(x.exp)) } @@ -1201,12 +1201,12 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) { tests := []struct { note string partitions []string - sequence []interface{} + sequence []any }{ { note: "unpartitioned: key", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -1220,7 +1220,7 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) { { note: "unpartitioned: nested", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/deadbeef", @@ -1234,7 +1234,7 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) { { note: "unpartitioned: nested: 2-level", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/deadbeef", @@ -1248,7 +1248,7 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) { { note: "partitioned: key", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -1262,7 +1262,7 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) { { note: "partitioned: nested", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -1276,7 +1276,7 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) { { note: "partitioned: nested: 2-level", partitions: []string{"/foo"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -1290,7 +1290,7 @@ func TestDataPartitioningReadNotFoundErrors(t *testing.T) { { note: "partitioned: prefix", partitions: []string{"/foo", "/bar"}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo/bar", @@ -1349,12 +1349,12 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { tests := []struct { note string partitions []string - sequence []interface{} + sequence []any }{ { note: "patch: remove: non-existent key", partitions: []string{}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -1369,7 +1369,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { { note: "patch: replace: non-existent key", partitions: []string{}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -1385,7 +1385,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { { note: "patch: scalar", partitions: []string{}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -1400,7 +1400,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { { note: "patch: array index", partitions: []string{}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -1415,7 +1415,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { { note: "patch: array index: non-leaf", partitions: []string{}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -1430,7 +1430,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { { note: "patch: array: non-existent key", partitions: []string{}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -1445,7 +1445,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { { note: "patch: array: scalar", partitions: []string{}, - sequence: []interface{}{ + sequence: []any{ testWrite{ op: storage.AddOp, path: "/foo", @@ -1483,7 +1483,7 @@ func TestDataPartitioningWriteNotFoundErrors(t *testing.T) { case testWrite: executeTestWrite(ctx, t, s, x) case testWriteError: - var val interface{} + var val any if x.value != "" { val = util.MustUnmarshalJSON([]byte(x.value)) } @@ -1554,7 +1554,7 @@ func TestDataPartitioningWriteInvalidPatchError(t *testing.T) { func executeTestWrite(ctx context.Context, t *testing.T, s storage.Store, x testWrite) { t.Helper() - var val interface{} + var val any if x.value != "" { val = util.MustUnmarshalJSON([]byte(x.value)) } diff --git a/v1/storage/disk/metrics.go b/v1/storage/disk/metrics.go index f7e53eba57..1991a4e633 100644 --- a/v1/storage/disk/metrics.go +++ b/v1/storage/disk/metrics.go @@ -43,7 +43,7 @@ func newHist(name, desc string) prometheus.Histogram { }) } -func forwardMetric(m map[string]interface{}, counter string, hist prometheus.Histogram) { +func forwardMetric(m map[string]any, counter string, hist prometheus.Histogram) { key := "counter_" + counter if s, ok := m[key]; ok { hist.Observe(float64(s.(uint64))) diff --git a/v1/storage/disk/txn.go b/v1/storage/disk/txn.go index 5da0845231..2df10dc891 100644 --- a/v1/storage/disk/txn.go +++ b/v1/storage/disk/txn.go @@ -106,7 +106,7 @@ func (txn *transaction) Abort(context.Context) { txn.underlying.Discard() } -func (txn *transaction) Read(ctx context.Context, path storage.Path) (interface{}, error) { +func (txn *transaction) Read(ctx context.Context, path storage.Path) (any, error) { txn.metrics.Timer(readTimer).Start() defer txn.metrics.Timer(readTimer).Stop() @@ -134,9 +134,9 @@ func (txn *transaction) Read(ctx context.Context, path storage.Path) (interface{ return txn.readMultiple(ctx, i, key) } -func (txn *transaction) readMultiple(ctx context.Context, offset int, prefix []byte) (interface{}, error) { +func (txn *transaction) readMultiple(ctx context.Context, offset int, prefix []byte) (any, error) { - result := map[string]interface{}{} + result := map[string]any{} it := txn.underlying.NewIterator(badger.IteratorOptions{Prefix: prefix}) defer it.Close() @@ -163,7 +163,7 @@ func (txn *transaction) readMultiple(ctx context.Context, offset int, prefix []b } txn.metrics.Counter(readValueBytesCounter).Add(uint64(len(valbuf))) - var value interface{} + var value any if err := deserialize(valbuf, &value); err != nil { return nil, err } @@ -173,10 +173,10 @@ func (txn *transaction) readMultiple(ctx context.Context, offset int, prefix []b for i := offset; i < len(path)-1; i++ { child, ok := node[path[i]] if !ok { - child = map[string]interface{}{} + child = map[string]any{} node[path[i]] = child } - childObj, ok := child.(map[string]interface{}) + childObj, ok := child.(map[string]any) if !ok { return nil, &storage.Error{Code: storage.InternalErr, Message: fmt.Sprintf("corrupt key-value: %s", keybuf)} } @@ -195,7 +195,7 @@ func (txn *transaction) readMultiple(ctx context.Context, offset int, prefix []b return result, nil } -func (txn *transaction) readOne(key []byte) (interface{}, error) { +func (txn *transaction) readOne(key []byte) (any, error) { txn.metrics.Counter(readKeysCounter).Add(1) item, err := txn.underlying.Get(key) @@ -206,7 +206,7 @@ func (txn *transaction) readOne(key []byte) (interface{}, error) { return nil, wrapError(err) } - var val interface{} + var val any err = item.Value(func(bs []byte) error { txn.metrics.Counter(readValueBytesCounter).Add(uint64(len(bs))) @@ -219,11 +219,11 @@ func (txn *transaction) readOne(key []byte) (interface{}, error) { type update struct { key []byte value []byte - data interface{} + data any delete bool } -func (txn *transaction) Write(_ context.Context, op storage.PatchOp, path storage.Path, value interface{}) error { +func (txn *transaction) Write(_ context.Context, op storage.PatchOp, path storage.Path, value any) error { txn.metrics.Timer(writeTimer).Start() defer txn.metrics.Timer(writeTimer).Stop() @@ -254,7 +254,7 @@ func (txn *transaction) Write(_ context.Context, op storage.PatchOp, path storag return nil } -func (txn *transaction) partitionWrite(op storage.PatchOp, path storage.Path, value interface{}) ([]update, error) { +func (txn *transaction) partitionWrite(op storage.PatchOp, path storage.Path, value any) ([]update, error) { if op == storage.RemoveOp && len(path) == 0 { return nil, &storage.Error{ @@ -318,12 +318,12 @@ func (txn *transaction) partitionWrite(op storage.PatchOp, path storage.Path, va return txn.partitionWriteMultiple(node, path, value, updates) } -func (txn *transaction) partitionWriteMultiple(node *partitionTrie, path storage.Path, value interface{}, result []update) ([]update, error) { +func (txn *transaction) partitionWriteMultiple(node *partitionTrie, path storage.Path, value any, result []update) ([]update, error) { // NOTE(tsandall): value must be an object so that it can be partitioned; in // the future, arrays could be supported but that requires investigation. switch v := value.(type) { - case map[string]interface{}: + case map[string]any: bs, err := serialize(v) if err != nil { return nil, err @@ -380,7 +380,7 @@ func (txn *transaction) doPartitionWriteMultiple(node *partitionTrie, path stora return result, nil } -func (txn *transaction) partitionWriteOne(op storage.PatchOp, path storage.Path, value interface{}) ([]update, error) { +func (txn *transaction) partitionWriteOne(op storage.PatchOp, path storage.Path, value any) ([]update, error) { key, err := txn.pm.DataPath2Key(path) if err != nil { return nil, err @@ -461,7 +461,7 @@ func (txn *transaction) DeletePolicy(_ context.Context, id string) error { return nil } -func serialize(value interface{}) ([]byte, error) { +func serialize(value any) ([]byte, error) { val, ok := value.([]byte) if ok { return val, nil @@ -471,12 +471,12 @@ func serialize(value interface{}) ([]byte, error) { return bs, wrapError(err) } -func deserialize(bs []byte, result interface{}) error { +func deserialize(bs []byte, result any) error { d := util.NewJSONDecoder(bytes.NewReader(bs)) return wrapError(d.Decode(&result)) } -func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (interface{}, error) { +func patch(data any, op storage.PatchOp, path storage.Path, idx int, value any) (any, error) { if idx == len(path) { panic("unreachable") } @@ -489,7 +489,7 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val if err == nil { val = obj } else { - var obj interface{} + var obj any err := util.Unmarshal(v, &obj) if err != nil { return nil, err @@ -502,7 +502,7 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val if err == nil { val = obj } else { - var obj interface{} + var obj any err := util.Unmarshal(v, &obj) if err != nil { return nil, err @@ -514,7 +514,7 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val // Base case: mutate the data value in-place. if len(path) == idx+1 { // last element switch x := data.(type) { - case map[string]interface{}: + case map[string]any: key := path[len(path)-1] switch op { case storage.RemoveOp: @@ -533,7 +533,7 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val x[key] = val return x, nil } - case []interface{}: + case []any: switch op { case storage.AddOp: if path[idx] == "-" || path[idx] == strconv.Itoa(len(x)) { @@ -544,7 +544,7 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val return nil, err } // insert at i - return append(x[:i], append([]interface{}{val}, x[i:]...)...), nil + return append(x[:i], append([]any{val}, x[i:]...)...), nil case storage.ReplaceOp: i, err := ptr.ValidateArrayIndexForWrite(x, path[idx], idx, path) if err != nil { @@ -563,7 +563,7 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val panic("unreachable") } case nil: // data wasn't set before - return map[string]interface{}{path[idx]: val}, nil + return map[string]any{path[idx]: val}, nil default: return nil, errors.NewNotFoundError(path) } @@ -573,14 +573,14 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val key := path[idx] switch x := data.(type) { - case map[string]interface{}: + case map[string]any: modified, err := patch(x[key], op, path, idx+1, val) if err != nil { return nil, err } x[key] = modified return x, nil - case []interface{}: + case []any: i, err := ptr.ValidateArrayIndexForWrite(x, path[idx], idx+1, path) if err != nil { return nil, err @@ -592,7 +592,7 @@ func patch(data interface{}, op storage.PatchOp, path storage.Path, idx int, val x[i] = modified return x, nil case nil: // data isn't there yet - y := make(map[string]interface{}, 1) + y := make(map[string]any, 1) modified, err := patch(nil, op, path, idx+1, val) if err != nil { return nil, err diff --git a/v1/storage/disk/txn_test.go b/v1/storage/disk/txn_test.go index aaeceaf9a2..26d67655a6 100644 --- a/v1/storage/disk/txn_test.go +++ b/v1/storage/disk/txn_test.go @@ -27,12 +27,12 @@ func randomString(n int) string { return string(s) } -func fixture(n int) map[string]interface{} { +func fixture(n int) map[string]any { foo := map[string]string{} for i := range n { foo[fmt.Sprintf(`"%d%s"`, i, randomString(4))] = randomString(3) } - return map[string]interface{}{"foo": foo} + return map[string]any{"foo": foo} } func TestSetTxnIsTooBigToFitIntoOneRequestWhenUseDiskStoreReturnsError(t *testing.T) { @@ -105,7 +105,7 @@ func TestDeleteTxnIsTooBigToFitIntoOneRequestWhenUseDiskStore(t *testing.T) { if err != nil { t.Fatal(err) } - if exp, act := nbKeys, len(res.(map[string]interface{})); exp != act { + if exp, act := nbKeys, len(res.(map[string]any)); exp != act { t.Fatalf("expected %d keys, read %d", exp, act) } @@ -125,7 +125,7 @@ func TestDeleteTxnIsTooBigToFitIntoOneRequestWhenUseDiskStore(t *testing.T) { if err != nil { t.Fatal(err) } - if exp, act := nbKeys, len(res.(map[string]interface{})); exp != act { + if exp, act := nbKeys, len(res.(map[string]any)); exp != act { t.Fatalf("expected %d keys, read %d", exp, act) } diff --git a/v1/storage/inmem/ast.go b/v1/storage/inmem/ast.go index 9f14df0e5b..dbd29eb1ec 100644 --- a/v1/storage/inmem/ast.go +++ b/v1/storage/inmem/ast.go @@ -28,7 +28,7 @@ func (u *updateAST) Remove() bool { return u.remove } -func (u *updateAST) Set(v interface{}) { +func (u *updateAST) Set(v any) { if v, ok := v.(ast.Value); ok { u.value = v } else { @@ -36,7 +36,7 @@ func (u *updateAST) Set(v interface{}) { } } -func (u *updateAST) Value() interface{} { +func (u *updateAST) Value() any { return u.value } @@ -46,7 +46,7 @@ func (u *updateAST) Relative(path storage.Path) dataUpdate { return &cpy } -func (u *updateAST) Apply(v interface{}) interface{} { +func (u *updateAST) Apply(v any) any { if len(u.path) == 0 { return u.value } @@ -72,7 +72,7 @@ func (u *updateAST) Apply(v interface{}) interface{} { return newV } -func newUpdateAST(data interface{}, op storage.PatchOp, path storage.Path, idx int, value ast.Value) (*updateAST, error) { +func newUpdateAST(data any, op storage.PatchOp, path storage.Path, idx int, value ast.Value) (*updateAST, error) { switch data.(type) { case ast.Null, ast.Boolean, ast.Number, ast.String: @@ -174,7 +174,7 @@ func newUpdateObjectAST(data ast.Object, op storage.PatchOp, path storage.Path, return nil, errors.NewNotFoundError(path) } -func interfaceToValue(v interface{}) (ast.Value, error) { +func interfaceToValue(v any) (ast.Value, error) { if v, ok := v.(ast.Value); ok { return v, nil } diff --git a/v1/storage/inmem/example_test.go b/v1/storage/inmem/example_test.go index 93bfaa8240..b366e0ca8b 100644 --- a/v1/storage/inmem/example_test.go +++ b/v1/storage/inmem/example_test.go @@ -38,7 +38,7 @@ func Example_read() { } ` - var data map[string]interface{} + var data map[string]any // OPA uses Go's standard JSON library but assumes that numbers have been // decoded as json.Number instead of float64. You MUST decode with UseNumber @@ -102,7 +102,7 @@ func Example_write() { } ` - var data map[string]interface{} + var data map[string]any // OPA uses Go's standard JSON library but assumes that numbers have been // decoded as json.Number instead of float64. You MUST decode with UseNumber @@ -123,7 +123,7 @@ func Example_write() { "latitude": -62.338889 }` - var patch interface{} + var patch any // See comment above regarding decoder usage. decoder = json.NewDecoder(bytes.NewBufferString(examplePatch)) diff --git a/v1/storage/inmem/inmem.go b/v1/storage/inmem/inmem.go index c70d234d74..742d6c167f 100644 --- a/v1/storage/inmem/inmem.go +++ b/v1/storage/inmem/inmem.go @@ -51,20 +51,20 @@ func NewWithOpts(opts ...Opt) storage.Store { if s.returnASTValuesOnRead { s.data = ast.NewObject() } else { - s.data = map[string]interface{}{} + s.data = map[string]any{} } return s } // NewFromObject returns a new in-memory store from the supplied data object. -func NewFromObject(data map[string]interface{}) storage.Store { +func NewFromObject(data map[string]any) storage.Store { return NewFromObjectWithOpts(data) } // NewFromObjectWithOpts returns a new in-memory store from the supplied data object, with the // options passed. -func NewFromObjectWithOpts(data map[string]interface{}, opts ...Opt) storage.Store { +func NewFromObjectWithOpts(data map[string]any, opts ...Opt) storage.Store { db := NewWithOpts(opts...) ctx := context.Background() txn, err := db.NewTransaction(ctx, storage.WriteParams) @@ -90,7 +90,7 @@ func NewFromReader(r io.Reader) storage.Store { // JSON serialized object, with extra options. This function is for test purposes. func NewFromReaderWithOpts(r io.Reader, opts ...Opt) storage.Store { d := util.NewJSONDecoder(r) - var data map[string]interface{} + var data map[string]any if err := d.Decode(&data); err != nil { panic(err) } @@ -101,7 +101,7 @@ type store struct { rmu sync.RWMutex // reader-writer lock wmu sync.Mutex // writer lock xid uint64 // last generated transaction id - data interface{} // raw or AST data + data any // raw or AST data policies map[string][]byte // raw policies triggers map[*handle]storage.TriggerConfig // registered triggers @@ -139,7 +139,7 @@ func (db *store) NewTransaction(_ context.Context, params ...storage.Transaction func (db *store) Truncate(ctx context.Context, txn storage.Transaction, params storage.TransactionParams, it storage.Iterator) error { var update *storage.Update var err error - mergedData := map[string]interface{}{} + mergedData := map[string]any{} underlying, err := db.underlying(txn) if err != nil { @@ -158,7 +158,7 @@ func (db *store) Truncate(ctx context.Context, txn storage.Transaction, params s return err } } else { - var value interface{} + var value any err = util.Unmarshal(update.Value, &value) if err != nil { return err @@ -304,7 +304,7 @@ func (db *store) Register(_ context.Context, txn storage.Transaction, config sto return h, nil } -func (db *store) Read(_ context.Context, txn storage.Transaction, path storage.Path) (interface{}, error) { +func (db *store) Read(_ context.Context, txn storage.Transaction, path storage.Path) (any, error) { underlying, err := db.underlying(txn) if err != nil { return nil, err @@ -318,7 +318,7 @@ func (db *store) Read(_ context.Context, txn storage.Transaction, path storage.P return v, nil } -func (db *store) Write(_ context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value interface{}) error { +func (db *store) Write(_ context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value any) error { underlying, err := db.underlying(txn) if err != nil { return err @@ -382,7 +382,7 @@ func (db *store) runOnCommitTriggers(ctx context.Context, txn storage.Transactio type illegalResolver struct{} -func (illegalResolver) Resolve(ref ast.Ref) (interface{}, error) { +func (illegalResolver) Resolve(ref ast.Ref) (any, error) { return nil, fmt.Errorf("illegal value: %v", ref) } @@ -412,35 +412,35 @@ func (db *store) underlying(txn storage.Transaction) (*transaction, error) { const rootMustBeObjectMsg = "root must be object" const rootCannotBeRemovedMsg = "root cannot be removed" -func invalidPatchError(f string, a ...interface{}) *storage.Error { +func invalidPatchError(f string, a ...any) *storage.Error { return &storage.Error{ Code: storage.InvalidPatchErr, Message: fmt.Sprintf(f, a...), } } -func mktree(path []string, value interface{}) (map[string]interface{}, error) { +func mktree(path []string, value any) (map[string]any, error) { if len(path) == 0 { // For 0 length path the value is the full tree. - obj, ok := value.(map[string]interface{}) + obj, ok := value.(map[string]any) if !ok { return nil, invalidPatchError(rootMustBeObjectMsg) } return obj, nil } - dir := map[string]interface{}{} + dir := map[string]any{} for i := len(path) - 1; i > 0; i-- { dir[path[i]] = value value = dir - dir = map[string]interface{}{} + dir = map[string]any{} } dir[path[0]] = value return dir, nil } -func lookup(path storage.Path, data map[string]interface{}) (interface{}, bool) { +func lookup(path storage.Path, data map[string]any) (any, bool) { if len(path) == 0 { return data, true } @@ -449,7 +449,7 @@ func lookup(path storage.Path, data map[string]interface{}) (interface{}, bool) if !ok { return nil, false } - obj, ok := value.(map[string]interface{}) + obj, ok := value.(map[string]any) if !ok { return nil, false } diff --git a/v1/storage/inmem/inmem_test.go b/v1/storage/inmem/inmem_test.go index fe1495ae80..d385a1999d 100644 --- a/v1/storage/inmem/inmem_test.go +++ b/v1/storage/inmem/inmem_test.go @@ -28,7 +28,7 @@ func TestInMemoryRead(t *testing.T) { var tests = []struct { path string - expected interface{} + expected any }{ {"/a/0", json.Number("1")}, {"/a/3", json.Number("4")}, @@ -38,8 +38,8 @@ func TestInMemoryRead(t *testing.T) { {"/c/0/y/0", nil}, {"/c/0/y/1", json.Number("3.14159")}, {"/d/e/1", "baz"}, - {"/d/e", []interface{}{"bar", "baz"}}, - {"/c/0/z", map[string]interface{}{"p": true, "q": false}}, + {"/d/e", []any{"bar", "baz"}}, + {"/c/0/z", map[string]any{"p": true, "q": false}}, {"/a/0/beef", storageerrors.NewNotFoundError(storage.MustParsePath("/a/0/beef"))}, {"/d/100", storageerrors.NewNotFoundError(storage.MustParsePath("/d/100"))}, {"/dead/beef", storageerrors.NewNotFoundError(storage.MustParsePath("/dead/beef"))}, @@ -78,7 +78,7 @@ func TestInMemoryReadAst(t *testing.T) { var tests = []struct { path string - expected interface{} + expected any }{ {"/a/0", ast.Number("1")}, {"/a/3", ast.Number("4")}, @@ -139,7 +139,7 @@ func TestInMemoryWrite(t *testing.T) { value string expected error getPath string - getExpected interface{} + getExpected any }{ {"add root", "add", "/", `{"a": [1]}`, nil, "/", `{"a": [1]}`}, {"add", "add", "/newroot", `{"a": [[1]]}`, nil, "/newroot", `{"a": [[1]]}`}, @@ -277,13 +277,13 @@ func TestInMemoryWriteOfStruct(t *testing.T) { } cases := map[string]struct { - value interface{} + value any expected string }{ "nested struct": {A{&B{10}}, `{"foo": {"bar": 10 } }`}, "pointer to nested struct": {&A{&B{10}}, `{"foo": {"bar": 10 } }`}, "pointer to pointer to nested struct": { - func() interface{} { + func() any { a := &A{&B{10}} return &a }(), `{"foo": {"bar": 10 } }`}, @@ -322,13 +322,13 @@ func TestInMemoryWriteOfStructAst(t *testing.T) { } cases := map[string]struct { - value interface{} + value any expected string }{ "nested struct": {A{&B{10}}, `{"foo": {"bar": 10 } }`}, "pointer to nested struct": {&A{&B{10}}, `{"foo": {"bar": 10 } }`}, "pointer to pointer to nested struct": { - func() interface{} { + func() any { a := &A{&B{10}} return &a }(), `{"foo": {"bar": 10 } }`}, @@ -409,7 +409,7 @@ func TestInMemoryTxnMultipleWrites(t *testing.T) { } for _, w := range writes { - var jsn interface{} + var jsn any if w.value != "" { jsn = util.MustUnmarshalJSON([]byte(w.value)) } @@ -491,7 +491,7 @@ func TestInMemoryTxnMultipleWritesAst(t *testing.T) { } for _, w := range writes { - var jsn interface{} + var jsn any if w.value != "" { jsn = util.MustUnmarshalJSON([]byte(w.value)) } @@ -535,7 +535,7 @@ func TestTruncateNoExistingPath(t *testing.T) { for _, tc := range cases { t.Run(tc.note, func(t *testing.T) { ctx := context.Background() - store := NewFromObjectWithOpts(map[string]interface{}{}, OptReturnASTValuesOnRead(tc.ast)) + store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(tc.ast)) txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams) var archiveFiles = map[string]string{ @@ -602,7 +602,7 @@ func TestTruncateNoExistingPath(t *testing.T) { func TestTruncate(t *testing.T) { ctx := context.Background() - store := NewFromObject(map[string]interface{}{}) + store := NewFromObject(map[string]any{}) txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams) var archiveFiles = map[string]string{ @@ -700,7 +700,7 @@ func TestTruncate(t *testing.T) { func TestTruncateAst(t *testing.T) { ctx := context.Background() - store := NewFromObjectWithOpts(map[string]interface{}{}, OptReturnASTValuesOnRead(true)) + store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(true)) txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams) var archiveFiles = map[string]string{ @@ -808,7 +808,7 @@ func TestTruncateDataMergeError(t *testing.T) { for _, tc := range cases { t.Run(tc.note, func(t *testing.T) { ctx := context.Background() - store := NewFromObjectWithOpts(map[string]interface{}{}, OptReturnASTValuesOnRead(tc.ast)) + store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(tc.ast)) txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams) var archiveFiles = map[string]string{ @@ -854,7 +854,7 @@ func TestTruncateBadRootWrite(t *testing.T) { for _, tc := range cases { t.Run(tc.note, func(t *testing.T) { ctx := context.Background() - store := NewFromObjectWithOpts(map[string]interface{}{}, OptReturnASTValuesOnRead(tc.ast)) + store := NewFromObjectWithOpts(map[string]any{}, OptReturnASTValuesOnRead(tc.ast)) txn := storage.NewTransactionOrDie(ctx, store, storage.WriteParams) var archiveFiles = map[string]string{ @@ -921,7 +921,7 @@ func TestInMemoryTxnWriteFailures(t *testing.T) { } for _, w := range writes { - var jsn interface{} + var jsn any if w.value != "" { jsn = util.MustUnmarshalJSON([]byte(w.value)) } @@ -1231,29 +1231,29 @@ func TestInMemoryContext(t *testing.T) { } -func loadExpectedResult(input string) interface{} { +func loadExpectedResult(input string) any { if len(input) == 0 { return nil } - var data interface{} + var data any if err := util.UnmarshalJSON([]byte(input), &data); err != nil { panic(err) } return data } -func loadExpectedSortedResult(input string) interface{} { +func loadExpectedSortedResult(input string) any { data := loadExpectedResult(input) switch data := data.(type) { - case []interface{}: + case []any: return data default: return data } } -func loadSmallTestData() map[string]interface{} { - var data map[string]interface{} +func loadSmallTestData() map[string]any { + var data map[string]any err := util.UnmarshalJSON([]byte(`{ "a": [1,2,3,4], "b": { @@ -1288,13 +1288,13 @@ func TestOptRoundTripOnWrite(t *testing.T) { validObject := map[string]string{"foo": "bar"} // self-referential objects are not serializable to JSON. - invalidObject := map[string]interface{}{} + invalidObject := map[string]any{} invalidObject["foo"] = invalidObject tests := []struct { name string opts []Opt - obj interface{} + obj any wantErr bool }{{ name: "success on valid object no Opts", diff --git a/v1/storage/inmem/test/testutil.go b/v1/storage/inmem/test/testutil.go index 5f39d4c8f1..bcf740c52e 100644 --- a/v1/storage/inmem/test/testutil.go +++ b/v1/storage/inmem/test/testutil.go @@ -17,12 +17,12 @@ func New() storage.Store { // NewFromObject returns an inmem store from the passed object, with some // common options set: opt-out of write roundtripping. -func NewFromObject(x map[string]interface{}) storage.Store { +func NewFromObject(x map[string]any) storage.Store { return inmem.NewFromObjectWithOpts(x, inmem.OptRoundTripOnWrite(false)) } // NewFromObjectWithASTRead returns an inmem store from the passed object, with // round-trip on write disabled and AST values returned on read. -func NewFromObjectWithASTRead(x map[string]interface{}) storage.Store { +func NewFromObjectWithASTRead(x map[string]any) storage.Store { return inmem.NewFromObjectWithOpts(x, inmem.OptRoundTripOnWrite(false), inmem.OptReturnASTValuesOnRead(true)) } diff --git a/v1/storage/inmem/txn.go b/v1/storage/inmem/txn.go index f8a7303912..28e68c20f2 100644 --- a/v1/storage/inmem/txn.go +++ b/v1/storage/inmem/txn.go @@ -63,7 +63,7 @@ func (txn *transaction) ID() uint64 { return txn.xid } -func (txn *transaction) Write(op storage.PatchOp, path storage.Path, value interface{}) error { +func (txn *transaction) Write(op storage.PatchOp, path storage.Path, value any) error { if !txn.write { return &storage.Error{ @@ -129,7 +129,7 @@ func (txn *transaction) Write(op storage.PatchOp, path storage.Path, value inter return nil } -func (txn *transaction) updateRoot(op storage.PatchOp, value interface{}) error { +func (txn *transaction) updateRoot(op storage.PatchOp, value any) error { if op == storage.RemoveOp { return invalidPatchError(rootCannotBeRemovedMsg) } @@ -150,7 +150,7 @@ func (txn *transaction) updateRoot(op storage.PatchOp, value interface{}) error value: valueAST, } } else { - if _, ok := value.(map[string]interface{}); !ok { + if _, ok := value.(map[string]any); !ok { return invalidPatchError(rootMustBeObjectMsg) } @@ -194,14 +194,14 @@ func (txn *transaction) Commit() (result storage.TriggerEvent) { return result } -func pointer(v interface{}, path storage.Path) (interface{}, error) { +func pointer(v any, path storage.Path) (any, error) { if v, ok := v.(ast.Value); ok { return ptr.ValuePtr(v, path) } return ptr.Ptr(v, path) } -func deepcpy(v interface{}) interface{} { +func deepcpy(v any) any { if v, ok := v.(ast.Value); ok { var cpy ast.Value @@ -217,7 +217,7 @@ func deepcpy(v interface{}) interface{} { return deepcopy.DeepCopy(v) } -func (txn *transaction) Read(path storage.Path) (interface{}, error) { +func (txn *transaction) Read(path storage.Path) (any, error) { if !txn.write { return pointer(txn.db.data, path) @@ -313,10 +313,10 @@ func (txn *transaction) DeletePolicy(id string) error { type dataUpdate interface { Path() storage.Path Remove() bool - Apply(interface{}) interface{} + Apply(any) any Relative(path storage.Path) dataUpdate - Set(interface{}) - Value() interface{} + Set(any) + Value() any } // update contains state associated with an update to be applied to the @@ -324,10 +324,10 @@ type dataUpdate interface { type updateRaw struct { path storage.Path // data path modified by update remove bool // indicates whether update removes the value at path - value interface{} // value to add/replace at path (ignored if remove is true) + value any // value to add/replace at path (ignored if remove is true) } -func (db *store) newUpdate(data interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { +func (db *store) newUpdate(data any, op storage.PatchOp, path storage.Path, idx int, value any) (dataUpdate, error) { if db.returnASTValuesOnRead { astData, err := interfaceToValue(data) if err != nil { @@ -342,7 +342,7 @@ func (db *store) newUpdate(data interface{}, op storage.PatchOp, path storage.Pa return newUpdateRaw(data, op, path, idx, value) } -func newUpdateRaw(data interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { +func newUpdateRaw(data any, op storage.PatchOp, path storage.Path, idx int, value any) (dataUpdate, error) { switch data.(type) { case nil, bool, json.Number, string: @@ -350,10 +350,10 @@ func newUpdateRaw(data interface{}, op storage.PatchOp, path storage.Path, idx i } switch data := data.(type) { - case map[string]interface{}: + case map[string]any: return newUpdateObject(data, op, path, idx, value) - case []interface{}: + case []any: return newUpdateArray(data, op, path, idx, value) } @@ -363,14 +363,14 @@ func newUpdateRaw(data interface{}, op storage.PatchOp, path storage.Path, idx i } } -func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { +func newUpdateArray(data []any, op storage.PatchOp, path storage.Path, idx int, value any) (dataUpdate, error) { if idx == len(path)-1 { if path[idx] == "-" || path[idx] == strconv.Itoa(len(data)) { if op != storage.AddOp { return nil, invalidPatchError("%v: invalid patch path", path) } - cpy := make([]interface{}, len(data)+1) + cpy := make([]any, len(data)+1) copy(cpy, data) cpy[len(data)] = value return &updateRaw{path[:len(path)-1], false, cpy}, nil @@ -383,20 +383,20 @@ func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, i switch op { case storage.AddOp: - cpy := make([]interface{}, len(data)+1) + cpy := make([]any, len(data)+1) copy(cpy[:pos], data[:pos]) copy(cpy[pos+1:], data[pos:]) cpy[pos] = value return &updateRaw{path[:len(path)-1], false, cpy}, nil case storage.RemoveOp: - cpy := make([]interface{}, len(data)-1) + cpy := make([]any, len(data)-1) copy(cpy[:pos], data[:pos]) copy(cpy[pos:], data[pos+1:]) return &updateRaw{path[:len(path)-1], false, cpy}, nil default: - cpy := make([]interface{}, len(data)) + cpy := make([]any, len(data)) copy(cpy, data) cpy[pos] = value return &updateRaw{path[:len(path)-1], false, cpy}, nil @@ -411,7 +411,7 @@ func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, i return newUpdateRaw(data[pos], op, path, idx+1, value) } -func newUpdateObject(data map[string]interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { +func newUpdateObject(data map[string]any, op storage.PatchOp, path storage.Path, idx int, value any) (dataUpdate, error) { if idx == len(path)-1 { switch op { @@ -438,7 +438,7 @@ func (u *updateRaw) Path() storage.Path { return u.path } -func (u *updateRaw) Apply(data interface{}) interface{} { +func (u *updateRaw) Apply(data any) any { if len(u.path) == 0 { return u.value } @@ -448,17 +448,17 @@ func (u *updateRaw) Apply(data interface{}) interface{} { } key := u.path[len(u.path)-1] if u.remove { - obj := parent.(map[string]interface{}) + obj := parent.(map[string]any) delete(obj, key) return data } switch parent := parent.(type) { - case map[string]interface{}: + case map[string]any: if parent == nil { - parent = make(map[string]interface{}, 1) + parent = make(map[string]any, 1) } parent[key] = u.value - case []interface{}: + case []any: idx, err := strconv.Atoi(key) if err != nil { panic(err) @@ -468,11 +468,11 @@ func (u *updateRaw) Apply(data interface{}) interface{} { return data } -func (u *updateRaw) Set(v interface{}) { +func (u *updateRaw) Set(v any) { u.value = v } -func (u *updateRaw) Value() interface{} { +func (u *updateRaw) Value() any { return u.value } diff --git a/v1/storage/interface.go b/v1/storage/interface.go index 94e02a47bc..1d03567066 100644 --- a/v1/storage/interface.go +++ b/v1/storage/interface.go @@ -25,10 +25,10 @@ type Store interface { NewTransaction(context.Context, ...TransactionParams) (Transaction, error) // Read is called to fetch a document referred to by path. - Read(context.Context, Transaction, Path) (interface{}, error) + Read(context.Context, Transaction, Path) (any, error) // Write is called to modify a document referred to by path. - Write(context.Context, Transaction, PatchOp, Path, interface{}) error + Write(context.Context, Transaction, PatchOp, Path, any) error // Commit is called to finish the transaction. If Commit returns an error, the // transaction must be automatically aborted by the Store implementation. @@ -67,18 +67,18 @@ type TransactionParams struct { // Context is a simple container for key/value pairs. type Context struct { - values map[interface{}]interface{} + values map[any]any } // NewContext returns a new context object. func NewContext() *Context { return &Context{ - values: map[interface{}]interface{}{}, + values: map[any]any{}, } } // Get returns the key value in the context. -func (ctx *Context) Get(key interface{}) interface{} { +func (ctx *Context) Get(key any) any { if ctx == nil { return nil } @@ -86,7 +86,7 @@ func (ctx *Context) Get(key interface{}) interface{} { } // Put adds a key/value pair to the context. -func (ctx *Context) Put(key, value interface{}) { +func (ctx *Context) Put(key, value any) { ctx.values[key] = value } @@ -130,7 +130,7 @@ const ( // interface which may be used if the backend does not support writes. type WritesNotSupported struct{} -func (WritesNotSupported) Write(context.Context, Transaction, PatchOp, Path, interface{}) error { +func (WritesNotSupported) Write(context.Context, Transaction, PatchOp, Path, any) error { return writesNotSupportedError() } @@ -176,7 +176,7 @@ type PolicyEvent struct { // DataEvent describes a change to a base data document. type DataEvent struct { Path Path - Data interface{} + Data any Removed bool } diff --git a/v1/storage/internal/errors/errors.go b/v1/storage/internal/errors/errors.go index 778f30d1f4..d13fff50fc 100644 --- a/v1/storage/internal/errors/errors.go +++ b/v1/storage/internal/errors/errors.go @@ -27,7 +27,7 @@ func NewNotFoundErrorWithHint(path storage.Path, hint string) *storage.Error { } } -func NewNotFoundErrorf(f string, a ...interface{}) *storage.Error { +func NewNotFoundErrorf(f string, a ...any) *storage.Error { msg := fmt.Sprintf(f, a...) return &storage.Error{ Code: storage.NotFoundErr, diff --git a/v1/storage/internal/ptr/ptr.go b/v1/storage/internal/ptr/ptr.go index 902e73546e..c5e380af04 100644 --- a/v1/storage/internal/ptr/ptr.go +++ b/v1/storage/internal/ptr/ptr.go @@ -13,17 +13,17 @@ import ( "github.com/open-policy-agent/opa/v1/storage/internal/errors" ) -func Ptr(data interface{}, path storage.Path) (interface{}, error) { +func Ptr(data any, path storage.Path) (any, error) { node := data for i := range path { key := path[i] switch curr := node.(type) { - case map[string]interface{}: + case map[string]any: var ok bool if node, ok = curr[key]; !ok { return nil, errors.NewNotFoundError(path) } - case []interface{}: + case []any: pos, err := ValidateArrayIndex(curr, key, path) if err != nil { return nil, err @@ -70,7 +70,7 @@ func ValuePtr(data ast.Value, path storage.Path) (ast.Value, error) { return node, nil } -func ValidateArrayIndex(arr []interface{}, s string, path storage.Path) (int, error) { +func ValidateArrayIndex(arr []any, s string, path storage.Path) (int, error) { idx, ok := isInt(s) if !ok { return 0, errors.NewNotFoundErrorWithHint(path, errors.ArrayIndexTypeMsg) @@ -89,7 +89,7 @@ func ValidateASTArrayIndex(arr *ast.Array, s string, path storage.Path) (int, er // ValidateArrayIndexForWrite also checks that `s` is a valid way to address an // array element like `ValidateArrayIndex`, but returns a `resource_conflict` error // if it is not. -func ValidateArrayIndexForWrite(arr []interface{}, s string, i int, path storage.Path) (int, error) { +func ValidateArrayIndexForWrite(arr []any, s string, i int, path storage.Path) (int, error) { idx, ok := isInt(s) if !ok { return 0, errors.NewWriteConflictError(path[:i-1]) @@ -102,12 +102,12 @@ func isInt(s string) (int, bool) { return idx, err == nil } -func inRange(i int, arr interface{}, path storage.Path) (int, error) { +func inRange(i int, arr any, path storage.Path) (int, error) { var arrLen int switch v := arr.(type) { - case []interface{}: + case []any: arrLen = len(v) case *ast.Array: arrLen = v.Len() diff --git a/v1/storage/storage.go b/v1/storage/storage.go index 34305f2912..ecc3829940 100644 --- a/v1/storage/storage.go +++ b/v1/storage/storage.go @@ -24,7 +24,7 @@ func NewTransactionOrDie(ctx context.Context, store Store, params ...Transaction // ReadOne is a convenience function to read a single value from the provided Store. It // will create a new Transaction to perform the read with, and clean up after itself // should an error occur. -func ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) { +func ReadOne(ctx context.Context, store Store, path Path) (any, error) { txn, err := store.NewTransaction(ctx) if err != nil { return nil, err @@ -37,7 +37,7 @@ func ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) { // WriteOne is a convenience function to write a single value to the provided Store. It // will create a new Transaction to perform the write with, and clean up after itself // should an error occur. -func WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value interface{}) error { +func WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value any) error { txn, err := store.NewTransaction(ctx, WriteParams) if err != nil { return err @@ -74,10 +74,10 @@ func MakeDir(ctx context.Context, store Store, txn Transaction, path Path) error return err } - return store.Write(ctx, txn, AddOp, path, map[string]interface{}{}) + return store.Write(ctx, txn, AddOp, path, map[string]any{}) } - if _, ok := node.(map[string]interface{}); ok { + if _, ok := node.(map[string]any); ok { return nil } @@ -122,7 +122,7 @@ func NonEmpty(ctx context.Context, store Store, txn Transaction) func([]string) if err != nil && !IsNotFound(err) { return false, err } else if err == nil { - if _, ok := val.(map[string]interface{}); ok { + if _, ok := val.(map[string]any); ok { return false, nil } if _, ok := val.(ast.Object); ok { diff --git a/v1/test/authz/testing.go b/v1/test/authz/testing.go index 34e75926b6..9b7531f59c 100644 --- a/v1/test/authz/testing.go +++ b/v1/test/authz/testing.go @@ -51,7 +51,7 @@ const ( ) // GenerateInput will use a dataset profile and desired InputMode to generate inputs for testing -func GenerateInput(profile DataSetProfile, mode InputMode) (interface{}, interface{}) { +func GenerateInput(profile DataSetProfile, mode InputMode) (any, any) { var input string var allow bool @@ -95,15 +95,15 @@ func GenerateInput(profile DataSetProfile, mode InputMode) (interface{}, interfa } // GenerateDataset will generate a dataset for the given DatasetProfile -func GenerateDataset(profile DataSetProfile) map[string]interface{} { - return map[string]interface{}{ - "restauthz": map[string]interface{}{ +func GenerateDataset(profile DataSetProfile) map[string]any { + return map[string]any{ + "restauthz": map[string]any{ "tokens": generateTokensJSON(profile), }, } } -func generateTokensJSON(profile DataSetProfile) interface{} { +func generateTokensJSON(profile DataSetProfile) any { tokens := generateTokens(profile) bs, err := json.Marshal(tokens) if err != nil { diff --git a/v1/test/cases/cases.go b/v1/test/cases/cases.go index 14fe270278..a8cab718ae 100644 --- a/v1/test/cases/cases.go +++ b/v1/test/cases/cases.go @@ -35,20 +35,20 @@ func (s Set) Sorted() Set { // TestCase represents a single test case. type TestCase struct { - Filename string `json:"-" yaml:"-"` // name of file that case was loaded from - Note string `json:"note" yaml:"note"` // globally unique identifier for this test case - Query string `json:"query" yaml:"query"` // policy query to execute - Modules []string `json:"modules,omitempty" yaml:"modules,omitempty"` // policies to test against - Data *map[string]interface{} `json:"data,omitempty" yaml:"data,omitempty"` // data to test against - Input *interface{} `json:"input,omitempty" yaml:"input,omitempty"` // parsed input data to use - InputTerm *string `json:"input_term,omitempty" yaml:"input_term,omitempty"` // raw input data (serialized as a string, overrides input) - WantDefined *bool `json:"want_defined,omitempty" yaml:"want_defined,omitempty"` // expect query result to be defined (or not) - WantResult *[]map[string]interface{} `json:"want_result,omitempty" yaml:"want_result,omitempty"` // expect query result (overrides defined) - WantErrorCode *string `json:"want_error_code,omitempty" yaml:"want_error_code,omitempty"` // expect query error code (overrides result) - WantError *string `json:"want_error,omitempty" yaml:"want_error,omitempty"` // expect query error message (overrides error code) - SortBindings bool `json:"sort_bindings,omitempty" yaml:"sort_bindings,omitempty"` // indicates that binding values should be treated as sets - StrictError bool `json:"strict_error,omitempty" yaml:"strict_error,omitempty"` // indicates that the error depends on strict builtin error mode - Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"` // environment variables to be set during the test + Filename string `json:"-" yaml:"-"` // name of file that case was loaded from + Note string `json:"note" yaml:"note"` // globally unique identifier for this test case + Query string `json:"query" yaml:"query"` // policy query to execute + Modules []string `json:"modules,omitempty" yaml:"modules,omitempty"` // policies to test against + Data *map[string]any `json:"data,omitempty" yaml:"data,omitempty"` // data to test against + Input *any `json:"input,omitempty" yaml:"input,omitempty"` // parsed input data to use + InputTerm *string `json:"input_term,omitempty" yaml:"input_term,omitempty"` // raw input data (serialized as a string, overrides input) + WantDefined *bool `json:"want_defined,omitempty" yaml:"want_defined,omitempty"` // expect query result to be defined (or not) + WantResult *[]map[string]any `json:"want_result,omitempty" yaml:"want_result,omitempty"` // expect query result (overrides defined) + WantErrorCode *string `json:"want_error_code,omitempty" yaml:"want_error_code,omitempty"` // expect query error code (overrides result) + WantError *string `json:"want_error,omitempty" yaml:"want_error,omitempty"` // expect query error message (overrides error code) + SortBindings bool `json:"sort_bindings,omitempty" yaml:"sort_bindings,omitempty"` // indicates that binding values should be treated as sets + StrictError bool `json:"strict_error,omitempty" yaml:"strict_error,omitempty"` // indicates that the error depends on strict builtin error mode + Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"` // environment variables to be set during the test } // Load returns a set of built-in test cases. diff --git a/v1/test/e2e/authz/authz_bench_integration_test.go b/v1/test/e2e/authz/authz_bench_integration_test.go index 5ebaeae476..8b3592d1ec 100644 --- a/v1/test/e2e/authz/authz_bench_integration_test.go +++ b/v1/test/e2e/authz/authz_bench_integration_test.go @@ -86,7 +86,7 @@ func runAuthzBenchmark(b *testing.B, mode testAuthz.InputMode, numPaths int) { url := testRuntime.URL() + "/v1/" + queryPath input, expected := testAuthz.GenerateInput(profile, mode) - inputPayload := util.MustMarshalJSON(map[string]interface{}{ + inputPayload := util.MustMarshalJSON(map[string]any{ "input": input, }) inputReader := bytes.NewReader(inputPayload) diff --git a/v1/test/e2e/certrefresh/certrefresh_test.go b/v1/test/e2e/certrefresh/certrefresh_test.go index 93ff84d284..f4c777aa77 100644 --- a/v1/test/e2e/certrefresh/certrefresh_test.go +++ b/v1/test/e2e/certrefresh/certrefresh_test.go @@ -24,7 +24,7 @@ var testRuntime *e2e.TestRuntime var pool *x509.CertPool // print error to stderr, exit 1 -func fatal(err interface{}) { +func fatal(err any) { fmt.Fprintf(os.Stderr, "%s\n", err) os.Exit(1) } diff --git a/v1/test/e2e/distributedtracing/distributedtracing_test.go b/v1/test/e2e/distributedtracing/distributedtracing_test.go index 307342da4e..0185074f1e 100644 --- a/v1/test/e2e/distributedtracing/distributedtracing_test.go +++ b/v1/test/e2e/distributedtracing/distributedtracing_test.go @@ -95,7 +95,7 @@ func TestServerSpan(t *testing.T) { if err != nil { t.Fatal(err) } - expected := []interface{}{ + expected := []any{ attribute.String("net.host.name", u.Hostname()), attribute.Int("net.host.port", port), attribute.String("net.protocol.version", "1.1"), @@ -143,7 +143,7 @@ func TestServerSpan(t *testing.T) { if err != nil { t.Fatal(err) } - expected := []interface{}{ + expected := []any{ attribute.String("net.host.name", u.Hostname()), attribute.Int("net.host.port", port), attribute.String("net.protocol.version", "1.1"), @@ -308,7 +308,7 @@ func TestClientSpan(t *testing.T) { t.Errorf("expected span to be child of %v, got parent %v", expected, got) } - expected := []interface{}{ + expected := []any{ attribute.String("http.method", "GET"), attribute.String("http.url", testRuntime.URL()+"/health"), attribute.Int("http.status_code", 200), @@ -351,7 +351,7 @@ func TestClientSpan(t *testing.T) { t.Errorf("expected span to be child of %v, got parent %v", expected, got) } - expected := []interface{}{ + expected := []any{ attribute.String("http.method", "GET"), attribute.String("http.url", testRuntime.URL()+"/health"), attribute.Int("http.status_code", 200), @@ -362,7 +362,7 @@ func TestClientSpan(t *testing.T) { compareSpanAttributes(t, expected, attribute.NewSet(spans[1].Attributes...)) // The (parent) server span carries the decision ID - expected = []interface{}{ + expected = []any{ attribute.String("opa.decision_id", r.DecisionID), } compareSpanAttributes(t, expected, attribute.NewSet(spans[2].Attributes...)) @@ -401,7 +401,7 @@ func TestClientSpan(t *testing.T) { t.Errorf("expected span to be child of %v, got parent %v", expected, got) } - expected := []interface{}{ + expected := []any{ attribute.String("http.method", "GET"), attribute.String("http.url", testRuntime.URL()+"/health"), attribute.Int("http.status_code", 200), @@ -412,7 +412,7 @@ func TestClientSpan(t *testing.T) { compareSpanAttributes(t, expected, attribute.NewSet(spans[1].Attributes...)) // The (parent) server span carries the decision ID - expected = []interface{}{ + expected = []any{ attribute.String("opa.decision_id", r.DecisionID), } compareSpanAttributes(t, expected, attribute.NewSet(spans[2].Attributes...)) @@ -454,7 +454,7 @@ func TestClientSpan(t *testing.T) { t.Errorf("expected span to be child of %v, got parent %v", expected, got) } - expected := []interface{}{ + expected := []any{ attribute.String("http.method", "GET"), attribute.String("http.url", testRuntime.URL()+"/health"), attribute.Int("http.status_code", 200), @@ -659,7 +659,7 @@ allow if { t.Fatal(err) } - expected := []interface{}{ + expected := []any{ attribute.String("net.host.name", u.Hostname()), attribute.Int("net.host.port", port), attribute.String("net.protocol.version", "1.1"), @@ -780,7 +780,7 @@ func TestControlPlaneSpans(t *testing.T) { u := controlPlaneURL port := controlPlanePort - expected := []interface{}{ + expected := []any{ attribute.String("net.peer.name", u.Hostname()), attribute.Int("net.peer.port", port), attribute.String("http.method", "GET"), @@ -791,7 +791,7 @@ func TestControlPlaneSpans(t *testing.T) { } compareSpanAttributes(t, expected, attribute.NewSet(spans[0].Attributes...)) - expected = []interface{}{ + expected = []any{ attribute.String("net.peer.name", u.Hostname()), attribute.Int("net.peer.port", port), attribute.String("http.method", "GET"), @@ -802,7 +802,7 @@ func TestControlPlaneSpans(t *testing.T) { } compareSpanAttributes(t, expected, attribute.NewSet(spans[1].Attributes...)) - expected = []interface{}{ + expected = []any{ attribute.String("net.peer.name", statusURL.Hostname()), attribute.Int("net.peer.port", statusPort), attribute.String("http.method", "POST"), @@ -856,7 +856,7 @@ func TestControlPlaneSpans(t *testing.T) { t.Fatal(err) } - expected = []interface{}{ + expected = []any{ attribute.String("net.host.name", u.Hostname()), attribute.Int("net.host.port", port), attribute.String("net.protocol.version", "1.1"), @@ -872,7 +872,7 @@ func TestControlPlaneSpans(t *testing.T) { compareSpanAttributes(t, expected, attribute.NewSet(spans[0].Attributes...)) - expected = []interface{}{ + expected = []any{ attribute.String("net.peer.name", controlPlaneURL.Hostname()), attribute.Int("net.peer.port", controlPlanePort), attribute.String("http.method", "POST"), @@ -884,7 +884,7 @@ func TestControlPlaneSpans(t *testing.T) { }) } -func compareSpanAttributes(t *testing.T, expectedAttributes []interface{}, spanAttributes attribute.Set) { +func compareSpanAttributes(t *testing.T, expectedAttributes []any, spanAttributes attribute.Set) { t.Helper() ok := true for _, exp := range expectedAttributes { diff --git a/v1/test/e2e/logs/remote/remote_decision_logger_benchmark_test.go b/v1/test/e2e/logs/remote/remote_decision_logger_benchmark_test.go index 00c95fbcc8..dbead81e13 100644 --- a/v1/test/e2e/logs/remote/remote_decision_logger_benchmark_test.go +++ b/v1/test/e2e/logs/remote/remote_decision_logger_benchmark_test.go @@ -97,7 +97,7 @@ func runAuthzBenchmark(b *testing.B, mode testAuthz.InputMode, numPaths int) { url := testRuntime.URL() + "/v1/" + queryPath input, expected := testAuthz.GenerateInput(profile, mode) - inputPayload := util.MustMarshalJSON(map[string]interface{}{ + inputPayload := util.MustMarshalJSON(map[string]any{ "input": input, }) inputReader := bytes.NewReader(inputPayload) diff --git a/v1/test/e2e/logs/utils.go b/v1/test/e2e/logs/utils.go index 7a3874d8fe..b3451ed657 100644 --- a/v1/test/e2e/logs/utils.go +++ b/v1/test/e2e/logs/utils.go @@ -36,7 +36,7 @@ func RunDecisionLoggerBenchmark(b *testing.B, rt *e2e.TestRuntime) { b.ResetTimer() b.Run(name, func(b *testing.B) { - input := map[string]interface{}{ + input := map[string]any{ "hit": true, "password": "$up3r$Ecr3t", "ssn": "123-45-6789", diff --git a/v1/test/e2e/metrics/metrics_test.go b/v1/test/e2e/metrics/metrics_test.go index 73d23c7223..b4d1ac61c9 100644 --- a/v1/test/e2e/metrics/metrics_test.go +++ b/v1/test/e2e/metrics/metrics_test.go @@ -78,8 +78,8 @@ func TestMetricsEndpoint(t *testing.T) { } type response struct { - Result bool `json:"result"` - Metrics map[string]interface{} `json:"metrics"` + Result bool `json:"result"` + Metrics map[string]any `json:"metrics"` } func TestRequestWithInstrumentationV1DataAPI(t *testing.T) { @@ -156,7 +156,7 @@ func TestRequestWithInstrumentationV1CompileAPI(t *testing.T) { t.Fatal(err) } - var i interface{} = "{\"x\": 4}" + var i any = "{\"x\": 4}" req := types.CompileRequestV1{ Query: "data.test.p == true", Input: &i, @@ -171,7 +171,7 @@ func TestRequestWithInstrumentationV1CompileAPI(t *testing.T) { assertCompileInstrumentationMetricsInMap(t, true, resp.Metrics) } -func assertCompileInstrumentationMetricsInMap(t *testing.T, _ bool, metrics map[string]interface{}) { +func assertCompileInstrumentationMetricsInMap(t *testing.T, _ bool, metrics map[string]any) { expectedKeys := []string{ "histogram_eval_op_plug", "timer_eval_op_plug_ns", @@ -201,7 +201,7 @@ func assertCompileInstrumentationMetricsInMap(t *testing.T, _ bool, metrics map[ } } -func assertDataInstrumentationMetricsInMap(t *testing.T, includeCompile bool, metrics map[string]interface{}) { +func assertDataInstrumentationMetricsInMap(t *testing.T, includeCompile bool, metrics map[string]any) { expectedKeys := []string{ "counter_server_query_cache_hit", "counter_eval_op_virtual_cache_miss", diff --git a/v1/test/e2e/testing.go b/v1/test/e2e/testing.go index b99f3c6eb8..73612ca1ba 100644 --- a/v1/test/e2e/testing.go +++ b/v1/test/e2e/testing.go @@ -388,8 +388,8 @@ func (t *TestRuntime) UploadDataToPath(path string, data io.Reader) error { // GetDataWithInput will use the v1 data API and POST with the given input. The returned // value is the full response body. -func (t *TestRuntime) GetDataWithInput(path string, input interface{}) ([]byte, error) { - inputPayload := util.MustMarshalJSON(map[string]interface{}{ +func (t *TestRuntime) GetDataWithInput(path string, input any) ([]byte, error) { + inputPayload := util.MustMarshalJSON(map[string]any{ "input": input, }) @@ -477,7 +477,7 @@ func (*TestRuntime) request(method, url string, input io.Reader) (io.ReadCloser, } // GetDataWithInputTyped returns an unmarshalled response from GetDataWithInput. -func (t *TestRuntime) GetDataWithInputTyped(path string, input interface{}, response interface{}) error { +func (t *TestRuntime) GetDataWithInputTyped(path string, input any, response any) error { bs, err := t.GetDataWithInput(path, input) if err != nil { diff --git a/v1/test/e2e/tls/tls_test.go b/v1/test/e2e/tls/tls_test.go index 7871b56c41..380b6dc19c 100644 --- a/v1/test/e2e/tls/tls_test.go +++ b/v1/test/e2e/tls/tls_test.go @@ -28,7 +28,7 @@ var minTLSVersions = map[string]uint16{ } // print error to stderr, exit 1 -func fatal(err interface{}) { +func fatal(err any) { fmt.Fprintf(os.Stderr, "%s\n", err) os.Exit(1) } diff --git a/v1/test/e2e/wasm/authz/authz_bench_integration_test.go b/v1/test/e2e/wasm/authz/authz_bench_integration_test.go index 8a33e9c200..54769e3952 100644 --- a/v1/test/e2e/wasm/authz/authz_bench_integration_test.go +++ b/v1/test/e2e/wasm/authz/authz_bench_integration_test.go @@ -144,7 +144,7 @@ func runAuthzBenchmark(b *testing.B, mode testAuthz.InputMode, numPaths int) { url := testRuntime.URL() + "/v1/" + queryPath input, expected := testAuthz.GenerateInput(profile, mode) - inputPayload := util.MustMarshalJSON(map[string]interface{}{ + inputPayload := util.MustMarshalJSON(map[string]any{ "input": input, }) inputReader := bytes.NewReader(inputPayload) diff --git a/v1/test/scheduler/scheduler_bench_test.go b/v1/test/scheduler/scheduler_bench_test.go index 8ad3cdc7a2..cf6264daa5 100644 --- a/v1/test/scheduler/scheduler_bench_test.go +++ b/v1/test/scheduler/scheduler_bench_test.go @@ -31,7 +31,7 @@ func BenchmarkScheduler10x30(b *testing.B) { type benchmarkParams struct { store storage.Store compiler *ast.Compiler - input interface{} + input any } func runSchedulerBenchmark(b *testing.B, nodes int, pods int) { @@ -49,7 +49,7 @@ func runSchedulerBenchmark(b *testing.B, nodes int, pods int) { if err != nil { b.Fatal("unexpected error:", err) } - ws := rs[0].Expressions[0].Value.(map[string]interface{}) + ws := rs[0].Expressions[0].Value.(map[string]any) if len(ws) != nodes { b.Fatal("unexpected query result:", rs) } @@ -110,7 +110,7 @@ func setupNodes(ctx context.Context, store storage.Store, txn storage.Transactio if err != nil { panic(err) } - if err := store.Write(ctx, txn, storage.AddOp, storage.MustParsePath("/nodes"), map[string]interface{}{}); err != nil { + if err := store.Write(ctx, txn, storage.AddOp, storage.MustParsePath("/nodes"), map[string]any{}); err != nil { panic(err) } for i := range n { @@ -131,7 +131,7 @@ func setupRCs(ctx context.Context, store storage.Store, txn storage.Transaction, panic(err) } path := storage.MustParsePath("/replicationcontrollers") - if err := store.Write(ctx, txn, storage.AddOp, path, map[string]interface{}{}); err != nil { + if err := store.Write(ctx, txn, storage.AddOp, path, map[string]any{}); err != nil { panic(err) } for i := range n { @@ -152,7 +152,7 @@ func setupPods(ctx context.Context, store storage.Store, txn storage.Transaction panic(err) } path := storage.MustParsePath("/pods") - if err := store.Write(ctx, txn, storage.AddOp, path, map[string]interface{}{}); err != nil { + if err := store.Write(ctx, txn, storage.AddOp, path, map[string]any{}); err != nil { panic(err) } for i := range n { @@ -168,12 +168,12 @@ func setupPods(ctx context.Context, store storage.Store, txn storage.Transaction } } -func runTemplate(tmpl *template.Template, input interface{}) interface{} { +func runTemplate(tmpl *template.Template, input any) any { var buf bytes.Buffer if err := tmpl.Execute(&buf, input); err != nil { panic(err) } - var v interface{} + var v any if err := util.UnmarshalJSON(buf.Bytes(), &v); err != nil { panic(err) } diff --git a/v1/test/scheduler/scheduler_test.go b/v1/test/scheduler/scheduler_test.go index d8892b5b23..0d096b96fa 100644 --- a/v1/test/scheduler/scheduler_test.go +++ b/v1/test/scheduler/scheduler_test.go @@ -28,7 +28,7 @@ func TestScheduler(t *testing.T) { if err != nil { t.Fatal("unexpected error:", err) } - ws := rs[0].Expressions[0].Value.(map[string]interface{}) + ws := rs[0].Expressions[0].Value.(map[string]any) if len(ws) != 10 { t.Fatal("unexpected query result:", rs) } diff --git a/v1/tester/runner.go b/v1/tester/runner.go index 634ea5508c..696c7eba21 100644 --- a/v1/tester/runner.go +++ b/v1/tester/runner.go @@ -107,7 +107,7 @@ func (srm SubResultMap) update(path []string, i int, trace []*topdown.Event) boo type unknownResolver struct{} -func (unknownResolver) Resolve(_ ast.Ref) (interface{}, error) { +func (unknownResolver) Resolve(_ ast.Ref) (any, error) { return "UNKNOWN", nil } diff --git a/v1/topdown/bindings.go b/v1/topdown/bindings.go index 8c7bfbd178..06d5b09748 100644 --- a/v1/topdown/bindings.go +++ b/v1/topdown/bindings.go @@ -212,7 +212,7 @@ type namespacingVisitor struct { caller *bindings } -func (vis namespacingVisitor) Visit(x interface{}) bool { +func (vis namespacingVisitor) Visit(x any) bool { switch x := x.(type) { case *ast.ArrayComprehension: x.Term = vis.namespaceTerm(x.Term) diff --git a/v1/topdown/builtins/builtins.go b/v1/topdown/builtins/builtins.go index 9fcaea4a23..e65d15b4c7 100644 --- a/v1/topdown/builtins/builtins.go +++ b/v1/topdown/builtins/builtins.go @@ -18,15 +18,15 @@ import ( // Cache defines the built-in cache used by the top-down evaluation. The keys // must be comparable and should not be of type string. -type Cache map[interface{}]interface{} +type Cache map[any]any // Put updates the cache for the named built-in. -func (c Cache) Put(k, v interface{}) { +func (c Cache) Put(k, v any) { c[k] = v } // Get returns the cached value for k. -func (c Cache) Get(k interface{}) (interface{}, bool) { +func (c Cache) Get(k any) (any, bool) { v, ok := c[k] return v, ok } @@ -76,7 +76,7 @@ func (c NDBCache) MarshalJSON() ([]byte, error) { func (c *NDBCache) UnmarshalJSON(data []byte) error { out := map[string]ast.Object{} - var incoming interface{} + var incoming any // Note: We use util.Unmarshal instead of json.Unmarshal to get // correct deserialization of number types. @@ -120,7 +120,7 @@ func (err ErrOperand) Error() string { } // NewOperandErr returns a generic operand error. -func NewOperandErr(pos int, f string, a ...interface{}) error { +func NewOperandErr(pos int, f string, a ...any) error { f = fmt.Sprintf("operand %v ", pos) + f return ErrOperand(fmt.Sprintf(f, a...)) } diff --git a/v1/topdown/copypropagation/copypropagation.go b/v1/topdown/copypropagation/copypropagation.go index 9f4beca54a..e582205f44 100644 --- a/v1/topdown/copypropagation/copypropagation.go +++ b/v1/topdown/copypropagation/copypropagation.go @@ -233,7 +233,7 @@ type bindingPlugTransform struct { pctx *plugContext } -func (t bindingPlugTransform) Transform(x interface{}) (interface{}, error) { +func (t bindingPlugTransform) Transform(x any) (any, error) { switch x := x.(type) { case ast.Var: return t.plugBindingsVar(t.pctx, x), nil @@ -385,11 +385,11 @@ type binding struct { k, v ast.Value } -func containedIn(value ast.Value, x interface{}) bool { +func containedIn(value ast.Value, x any) bool { var stop bool var vis *ast.GenericVisitor - vis = ast.NewGenericVisitor(func(x interface{}) bool { + vis = ast.NewGenericVisitor(func(x any) bool { switch x := x.(type) { case *ast.Every: // skip body vis.Walk(x.Key) diff --git a/v1/topdown/copypropagation/unionfind.go b/v1/topdown/copypropagation/unionfind.go index 528c83a0f4..cac2a3009f 100644 --- a/v1/topdown/copypropagation/unionfind.go +++ b/v1/topdown/copypropagation/unionfind.go @@ -82,10 +82,10 @@ func (uf *unionFind) Merge(a, b ast.Value) (*unionFindRoot, bool) { func (uf *unionFind) String() string { o := struct { - Roots map[string]interface{} + Roots map[string]any Parents map[string]ast.Value }{ - map[string]interface{}{}, + map[string]any{}, map[string]ast.Value{}, } diff --git a/v1/topdown/crypto.go b/v1/topdown/crypto.go index dafbac7850..0d37519bcf 100644 --- a/v1/topdown/crypto.go +++ b/v1/topdown/crypto.go @@ -329,7 +329,7 @@ func builtinCryptoX509ParseCertificateRequest(_ BuiltinContext, operands []*ast. return err } - var x interface{} + var x any if err := util.UnmarshalJSON(bs, &x); err != nil { return err } @@ -343,7 +343,7 @@ func builtinCryptoX509ParseCertificateRequest(_ BuiltinContext, operands []*ast. } func builtinCryptoJWKFromPrivateKey(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - var x interface{} + var x any a := operands[0].Value input, err := builtins.StringOperand(a, 1) @@ -427,7 +427,7 @@ func builtinCryptoParsePrivateKeys(_ BuiltinContext, operands []*ast.Term, iter return err } - var x interface{} + var x any if err := util.UnmarshalJSON(bs, &x); err != nil { return err } diff --git a/v1/topdown/encoding.go b/v1/topdown/encoding.go index a27a9c2450..119ef98aca 100644 --- a/v1/topdown/encoding.go +++ b/v1/topdown/encoding.go @@ -128,7 +128,7 @@ func builtinJSONUnmarshal(_ BuiltinContext, operands []*ast.Term, iter func(*ast return err } - var x interface{} + var x any if err := util.UnmarshalJSON([]byte(str), &x); err != nil { return err @@ -255,7 +255,7 @@ func builtinURLQueryEncodeObject(_ BuiltinContext, operands []*ast.Term, iter fu return err } - inputs, ok := asJSON.(map[string]interface{}) + inputs, ok := asJSON.(map[string]any) if !ok { return builtins.NewOperandTypeErr(1, operands[0].Value, "object") } @@ -266,7 +266,7 @@ func builtinURLQueryEncodeObject(_ BuiltinContext, operands []*ast.Term, iter fu switch vv := v.(type) { case string: query.Set(k, vv) - case []interface{}: + case []any: for _, val := range vv { strVal, ok := val.(string) if !ok { @@ -340,7 +340,7 @@ func builtinYAMLUnmarshal(_ BuiltinContext, operands []*ast.Term, iter func(*ast buf := bytes.NewBuffer(bs) decoder := util.NewJSONDecoder(buf) - var val interface{} + var val any err = decoder.Decode(&val) if err != nil { return err @@ -358,7 +358,7 @@ func builtinYAMLIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.T return iter(ast.InternedBooleanTerm(false)) } - var x interface{} + var x any err = yaml.Unmarshal([]byte(str), &x) return iter(ast.InternedBooleanTerm(err == nil)) } diff --git a/v1/topdown/eval.go b/v1/topdown/eval.go index 221b29d005..90507e7df4 100644 --- a/v1/topdown/eval.go +++ b/v1/topdown/eval.go @@ -214,7 +214,7 @@ func (e *eval) partial() bool { return e.saveSet != nil } -func (e *eval) unknown(x interface{}, b *bindings) bool { +func (e *eval) unknown(x any, b *bindings) bool { if !e.partial() { return false } @@ -1778,9 +1778,9 @@ func (e *eval) resolveReadFromStorage(ref ast.Ref, a ast.Value) (ast.Value, erro if len(path) == 0 { switch obj := blob.(type) { - case map[string]interface{}: + case map[string]any: if len(obj) > 0 { - cpy := make(map[string]interface{}, len(obj)-1) + cpy := make(map[string]any, len(obj)-1) for k, v := range obj { if string(ast.SystemDocumentKey) != k { cpy[k] = v @@ -1799,7 +1799,7 @@ func (e *eval) resolveReadFromStorage(ref ast.Ref, a ast.Value) (ast.Value, erro case ast.Value: v = blob default: - if blob, ok := blob.(map[string]interface{}); ok && !e.strictObjects { + if blob, ok := blob.(map[string]any); ok && !e.strictObjects { v = ast.LazyObject(blob) break } @@ -4079,7 +4079,7 @@ func newNestedCheckVisitor() *nestedCheckVisitor { return v } -func (v *nestedCheckVisitor) visit(x interface{}) bool { +func (v *nestedCheckVisitor) visit(x any) bool { switch x.(type) { case ast.Ref, ast.Call: v.found = true @@ -4170,7 +4170,7 @@ func isOtherRef(term *ast.Term) bool { return !ref.HasPrefix(ast.DefaultRootRef) && !ref.HasPrefix(ast.InputRootRef) } -func isFunction(env *ast.TypeEnv, ref interface{}) bool { +func isFunction(env *ast.TypeEnv, ref any) bool { var r ast.Ref switch v := ref.(type) { case ast.Ref: diff --git a/v1/topdown/eval_test.go b/v1/topdown/eval_test.go index f5967cff61..c1eec80567 100644 --- a/v1/topdown/eval_test.go +++ b/v1/topdown/eval_test.go @@ -277,7 +277,7 @@ func TestTopdownVirtualCache(t *testing.T) { module string query string hit, miss uint64 - exp interface{} // if non-nil, check var `x` + exp any // if non-nil, check var `x` }{ { note: "different args", @@ -375,15 +375,15 @@ func TestTopdownVirtualCache(t *testing.T) { query: `data.p.s.t = x; data.p.s.t`, hit: 1, miss: 1, - exp: map[string]interface{}{ - "foo": map[string]interface{}{ - "v": map[string]interface{}{ + exp: map[string]any{ + "foo": map[string]any{ + "v": map[string]any{ "do": true, "re": true, }, }, - "bar": map[string]interface{}{ - "v": map[string]interface{}{ + "bar": map[string]any{ + "v": map[string]any{ "do": true, "re": true, }, @@ -397,8 +397,8 @@ func TestTopdownVirtualCache(t *testing.T) { query: `data.p.s.t.foo = x; data.p.s.t["foo"]`, hit: 1, miss: 1, - exp: map[string]interface{}{ - "v": map[string]interface{}{ + exp: map[string]any{ + "v": map[string]any{ "do": true, "re": true, }, @@ -411,7 +411,7 @@ func TestTopdownVirtualCache(t *testing.T) { query: `data.p.s.t.foo.v = x; data.p.s.t["foo"].v`, hit: 1, miss: 1, - exp: map[string]interface{}{ + exp: map[string]any{ "do": true, "re": true, }, @@ -468,8 +468,8 @@ func TestTopdownVirtualCache(t *testing.T) { query: `data.p.s.t.foo = x; data.p.s.t.foo.v.do`, hit: 1, miss: 1, - exp: map[string]interface{}{ - "v": map[string]interface{}{ + exp: map[string]any{ + "v": map[string]any{ "do": 0, "re": 1, }, @@ -1559,7 +1559,7 @@ func TestPartialRule(t *testing.T) { t.Fatalf("Unexpected error: %v", err) } - var exp []map[string]interface{} + var exp []map[string]any if err := json.Unmarshal([]byte(tc.exp), &exp); err != nil { t.Fatal("Failed to unmarshal exp") } diff --git a/v1/topdown/example_test.go b/v1/topdown/example_test.go index 69fe5a7a3a..7e676cea40 100644 --- a/v1/topdown/example_test.go +++ b/v1/topdown/example_test.go @@ -30,7 +30,7 @@ func ExampleQuery_Iter() { // Handle error. } - var data map[string]interface{} + var data map[string]any // OPA uses Go's standard JSON library but assumes that numbers have been // decoded as json.Number instead of float64. You MUST decode with UseNumber @@ -63,7 +63,7 @@ func ExampleQuery_Iter() { WithStore(store). WithTransaction(txn) - result := []interface{}{} + result := []any{} // Execute the query and provide a callback function to accumulate the results. err = q.Iter(ctx, func(qr topdown.QueryResult) error { @@ -103,7 +103,7 @@ func ExampleQuery_Run() { // Handle error. } - var data map[string]interface{} + var data map[string]any // OPA uses Go's standard JSON library but assumes that numbers have been // decoded as json.Number instead of float64. You MUST decode with UseNumber @@ -159,7 +159,7 @@ func ExampleQuery_PartialRun() { // context from an input parameter or instantiate their own. ctx := context.Background() - var data map[string]interface{} + var data map[string]any decoder := json.NewDecoder(bytes.NewBufferString(`{ "roles": [ { diff --git a/v1/topdown/exported_test.go b/v1/topdown/exported_test.go index 6f37e81e51..86e34f8548 100644 --- a/v1/topdown/exported_test.go +++ b/v1/topdown/exported_test.go @@ -157,7 +157,7 @@ func testRun(t *testing.T, tc cases.TestCase, regoVersion ast.RegoVersion, opts } } -func testAssertResultSet(t *testing.T, wantResult []map[string]interface{}, rs QueryResultSet, sortBindings bool) { +func testAssertResultSet(t *testing.T, wantResult []map[string]any, rs QueryResultSet, sortBindings bool) { exp := ast.NewSet() @@ -179,7 +179,7 @@ func testAssertResultSet(t *testing.T, wantResult []map[string]interface{}, rs Q t.Fatal(err) } if sortBindings { - sort.Sort(resultSet(v.([]interface{}))) + sort.Sort(resultSet(v.([]any))) } obj.Insert(ast.StringTerm(string(k)), ast.NewTerm(ast.MustInterfaceToValue(v))) } diff --git a/v1/topdown/graphql.go b/v1/topdown/graphql.go index f5b6273ba7..99eb4e7f5f 100644 --- a/v1/topdown/graphql.go +++ b/v1/topdown/graphql.go @@ -101,7 +101,7 @@ func convertSchema(schemaDoc *gqlast.SchemaDocument) (*gqlast.Schema, error) { // Converts an ast.Object into a gqlast.QueryDocument object. func objectToQueryDocument(value ast.Object) (*gqlast.QueryDocument, error) { - // Convert ast.Term to interface{} for JSON encoding below. + // Convert ast.Term to any for JSON encoding below. asJSON, err := ast.JSON(value) if err != nil { return nil, err @@ -122,7 +122,7 @@ func objectToQueryDocument(value ast.Object) (*gqlast.QueryDocument, error) { // Converts an ast.Object into a gqlast.SchemaDocument object. func objectToSchemaDocument(value ast.Object) (*gqlast.SchemaDocument, error) { - // Convert ast.Term to interface{} for JSON encoding below. + // Convert ast.Term to any for JSON encoding below. asJSON, err := ast.JSON(value) if err != nil { return nil, err diff --git a/v1/topdown/http.go b/v1/topdown/http.go index 463f01de22..98720163d1 100644 --- a/v1/topdown/http.go +++ b/v1/topdown/http.go @@ -242,7 +242,7 @@ func getKeyFromRequest(req ast.Object) (ast.Object, error) { if err != nil { return nil, err } - var allHeaders map[string]interface{} + var allHeaders map[string]any err = ast.As(allHeadersTerm.Value, &allHeaders) if err != nil { return nil, err @@ -325,8 +325,8 @@ func validateHTTPRequestOperand(term *ast.Term, pos int) (ast.Object, error) { // canonicalizeHeaders returns a copy of the headers where the keys are in // canonical HTTP form. -func canonicalizeHeaders(headers map[string]interface{}) map[string]interface{} { - canonicalized := map[string]interface{}{} +func canonicalizeHeaders(headers map[string]any) map[string]any { + canonicalized := map[string]any{} for k, v := range headers { canonicalized[http.CanonicalHeaderKey(k)] = v @@ -420,7 +420,7 @@ func createHTTPRequest(bctx BuiltinContext, obj ast.Object) (*http.Request, *htt enableRedirect, tlsInsecureSkipVerify bool tlsUseSystemCerts *bool tlsConfig tls.Config - customHeaders map[string]interface{} + customHeaders map[string]any ) timeout := defaultHTTPRequestTimeout @@ -518,7 +518,7 @@ func createHTTPRequest(bctx BuiltinContext, obj ast.Object) (*http.Request, *htt return nil, nil, err } var ok bool - customHeaders, ok = headersValInterface.(map[string]interface{}) + customHeaders, ok = headersValInterface.(map[string]any) if !ok { return nil, nil, errors.New("invalid type for headers key") } @@ -1387,7 +1387,7 @@ func formatHTTPResponseToAST(resp *http.Response, forceJSONDecode, forceYAMLDeco } func prepareASTResult(headers http.Header, forceJSONDecode, forceYAMLDecode bool, body []byte, status string, statusCode int) (ast.Value, error) { - var resultBody interface{} + var resultBody any // If the response body cannot be JSON/YAML decoded, // an error will not be returned. Instead, the "body" field @@ -1399,7 +1399,7 @@ func prepareASTResult(headers http.Header, forceJSONDecode, forceYAMLDecode bool _ = util.Unmarshal(body, &resultBody) } - result := make(map[string]interface{}) + result := make(map[string]any) result["status"] = status result["status_code"] = statusCode result["body"] = resultBody @@ -1414,10 +1414,10 @@ func prepareASTResult(headers http.Header, forceJSONDecode, forceYAMLDecode bool return resultObj, nil } -func getResponseHeaders(headers http.Header) map[string]interface{} { - respHeaders := map[string]interface{}{} +func getResponseHeaders(headers http.Header) map[string]any { + respHeaders := map[string]any{} for headerName, values := range headers { - var respValues []interface{} + var respValues []any for _, v := range values { respValues = append(respValues, v) } diff --git a/v1/topdown/http_slow_test.go b/v1/topdown/http_slow_test.go index f861ee04c1..6df27658d6 100644 --- a/v1/topdown/http_slow_test.go +++ b/v1/topdown/http_slow_test.go @@ -46,7 +46,7 @@ func TestHTTPSendTimeout(t *testing.T) { defaultTimeout time.Duration evalTimeout time.Duration serverDelay time.Duration - expected interface{} + expected any }{ { note: "no timeout", @@ -116,7 +116,7 @@ func TestHTTPSendTimeout(t *testing.T) { e.Message = strings.ReplaceAll(e.Message, "%URL%", ts.URL) } - runTopDownTestCaseWithContext(ctx, t, map[string]interface{}{}, tc.note, append(httpSendHelperRules, rule), nil, tc.input, tc.expected) + runTopDownTestCaseWithContext(ctx, t, map[string]any{}, tc.note, append(httpSendHelperRules, rule), nil, tc.input, tc.expected) // Put back the default (may not have changed) defaultHTTPRequestTimeout = originalDefaultTimeout diff --git a/v1/topdown/http_test.go b/v1/topdown/http_test.go index de1b8dbc94..26882ea6b4 100644 --- a/v1/topdown/http_test.go +++ b/v1/topdown/http_test.go @@ -65,19 +65,19 @@ func TestHTTPGetRequest(t *testing.T) { defer ts.Close() // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK - var body []interface{} + var body []any bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body expectedResult["raw_body"] = "[{\"id\":\"1\",\"firstname\":\"John\"}]\n" - expectedResult["headers"] = map[string]interface{}{ - "content-length": []interface{}{"32"}, - "content-type": []interface{}{"text/plain; charset=utf-8"}, - "test-header": []interface{}{"test-value"}, + expectedResult["headers"] = map[string]any{ + "content-length": []any{"32"}, + "content-type": []any{"text/plain; charset=utf-8"}, + "test-header": []any{"test-value"}, } resultObj := ast.MustInterfaceToValue(expectedResult) @@ -86,7 +86,7 @@ func TestHTTPGetRequest(t *testing.T) { tests := []struct { note string rules []string - expected interface{} + expected any }{ {"http.send", []string{fmt.Sprintf( `p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true}, resp); x := clean_headers(resp) }`, ts.URL)}, resultObj.String()}, @@ -118,18 +118,18 @@ func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) { defer ts.Close() // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK - var body []interface{} + var body []any bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body expectedResult["raw_body"] = "[{\"id\":\"1\",\"firstname\":\"John\"}]\n" - expectedResult["headers"] = map[string]interface{}{ - "content-length": []interface{}{"32"}, - "content-type": []interface{}{"text/plain; charset=utf-8"}, + expectedResult["headers"] = map[string]any{ + "content-length": []any{"32"}, + "content-type": []any{"text/plain; charset=utf-8"}, } resultObj := ast.MustInterfaceToValue(expectedResult) @@ -137,7 +137,7 @@ func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) { type httpsStruct struct { note string rules []string - expected interface{} + expected any } // run the test @@ -186,29 +186,29 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { defer ts.Close() - body := func(b interface{}) func(map[string]interface{}) { - return func(x map[string]interface{}) { + body := func(b any) func(map[string]any) { + return func(x map[string]any) { x["body"] = b } } - rawBody := func(b interface{}) func(map[string]interface{}) { - return func(x map[string]interface{}) { + rawBody := func(b any) func(map[string]any) { + return func(x map[string]any) { x["raw_body"] = b } } - headers := func(xs ...string) func(map[string]interface{}) { - hdrs := map[string]interface{}{} + headers := func(xs ...string) func(map[string]any) { + hdrs := map[string]any{} for i := range len(xs) / 2 { - hdrs[xs[2*i]] = []interface{}{xs[2*i+1]} + hdrs[xs[2*i]] = []any{xs[2*i+1]} } - return func(x map[string]interface{}) { + return func(x map[string]any) { x["headers"] = hdrs } } - ok := func(and ...func(map[string]interface{})) ast.Value { - o := map[string]interface{}{ + ok := func(and ...func(map[string]any)) ast.Value { + o := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, } @@ -243,7 +243,7 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { note: "json response, proper header", rule: fmt.Sprintf(`p = x { http.send({"method": "get", "url": "%s/json"}, resp); x := clean_headers(resp) }`, ts.URL), expected: ok( - body(map[string]interface{}{"foo": "bar"}), + body(map[string]any{"foo": "bar"}), rawBody(`{"foo":"bar"}`), headers("content-length", "13", "content-type", "application/json"), ), @@ -252,7 +252,7 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { note: "yaml response, proper header", rule: fmt.Sprintf(`p = x { http.send({"method": "get", "url": "%s/yaml"}, resp); x := clean_headers(resp) }`, ts.URL), expected: ok( - body(map[string]interface{}{"foo": "bar"}), + body(map[string]any{"foo": "bar"}), rawBody(`foo: bar`), headers("content-length", "8", "content-type", "application/yaml"), ), @@ -261,7 +261,7 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { note: "yaml response, x-yaml header", rule: fmt.Sprintf(`p = x { http.send({"method": "get", "url": "%s/x-yaml"}, resp); x := clean_headers(resp) }`, ts.URL), expected: ok( - body(map[string]interface{}{"foo": "bar"}), + body(map[string]any{"foo": "bar"}), rawBody(`foo: bar`), headers("content-length", "8", "content-type", "application/x-yaml"), ), @@ -270,7 +270,7 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { note: "json response, no header", rule: fmt.Sprintf(`p = x { http.send({"method": "get", "url": "%s/json-no-header", "force_json_decode": true}, resp); x := clean_headers(resp) }`, ts.URL), expected: ok( - body(map[string]interface{}{"foo": "bar"}), + body(map[string]any{"foo": "bar"}), rawBody(`{"foo":"bar"}`), headers("content-length", "13", "content-type", "text/plain; charset=utf-8"), ), @@ -279,7 +279,7 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { note: "yaml response, no header", rule: fmt.Sprintf(`p = x { http.send({"method": "get", "url": "%s/yaml-no-header", "force_yaml_decode": true}, resp); x := clean_headers(resp) }`, ts.URL), expected: ok( - body(map[string]interface{}{"foo": "bar"}), + body(map[string]any{"foo": "bar"}), rawBody(`foo: bar`), headers("content-length", "8", "content-type", "text/plain; charset=utf-8"), ), @@ -288,7 +288,7 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { note: "json response, no header, yaml decode", rule: fmt.Sprintf(`p = x { http.send({"method": "get", "url": "%s/json-no-header", "force_yaml_decode": true}, resp); x := clean_headers(resp) }`, ts.URL), expected: ok( - body(map[string]interface{}{"foo": "bar"}), + body(map[string]any{"foo": "bar"}), rawBody(`{"foo":"bar"}`), headers("content-length", "13", "content-type", "text/plain; charset=utf-8"), ), @@ -296,7 +296,7 @@ func TestHTTPEnableJSONOrYAMLDecode(t *testing.T) { } for _, tc := range tests { - runTopDownTestCase(t, map[string]interface{}{}, tc.note, append([]string{tc.rule}, httpSendHelperRules...), tc.expected.String()) + runTopDownTestCase(t, map[string]any{}, tc.note, append([]string{tc.rule}, httpSendHelperRules...), tc.expected.String()) } } @@ -320,7 +320,7 @@ func TestHTTPSendCustomRequestHeaders(t *testing.T) { defer ts.Close() // expected result with default User-Agent - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK @@ -350,7 +350,7 @@ func TestHTTPSendCustomRequestHeaders(t *testing.T) { tests := []struct { note string rules []string - expected interface{} + expected any }{ {"http.send custom headers", []string{fmt.Sprintf( `p = x { http.send({"method": "get", "url": "%s", "headers": {"X-Foo": "ISO-8859-1,utf-8;q=0.7,*;q=0.7", "X-Opa": "server"}}, resp); x := remove_headers(resp) }`, ts.URL)}, s}, @@ -377,14 +377,14 @@ func TestHTTPHostHeader(t *testing.T) { defer ts.Close() - expectedResult, err := json.Marshal(map[string]interface{}{ + expectedResult, err := json.Marshal(map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": t.Name(), "raw_body": fmt.Sprintf("\"%s\"\n", t.Name()), - "headers": map[string]interface{}{ - "content-length": []interface{}{"21"}, - "content-type": []interface{}{"application/json"}, + "headers": map[string]any{ + "content-length": []any{"21"}, + "content-type": []any{"application/json"}, }, }) if err != nil { @@ -430,7 +430,7 @@ func TestHTTPPostRequest(t *testing.T) { note string params string respHeaders string - expected interface{} + expected any }{ { note: "basic", @@ -489,7 +489,7 @@ func TestHTTPPostRequest(t *testing.T) { }, } - data := map[string]interface{}{} + data := map[string]any{} for _, tc := range tests { @@ -545,18 +545,18 @@ func TestHTTPDeleteRequest(t *testing.T) { defer ts.Close() // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK - var body []interface{} + var body []any bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body expectedResult["raw_body"] = "[{\"id\":\"1\",\"firstname\":\"John\"}]\n" - expectedResult["headers"] = map[string]interface{}{ - "content-length": []interface{}{"32"}, - "content-type": []interface{}{"application/json"}, + expectedResult["headers"] = map[string]any{ + "content-length": []any{"32"}, + "content-type": []any{"application/json"}, } resultObj := ast.MustInterfaceToValue(expectedResult) @@ -570,7 +570,7 @@ func TestHTTPDeleteRequest(t *testing.T) { tests := []struct { note string rules []string - expected interface{} + expected any }{ {"http.send", []string{fmt.Sprintf( `p = x { http.send({"method": "delete", "url": "%s", "body": %s}, resp); x := clean_headers(resp) }`, ts.URL, b)}, resultObj.String()}, @@ -592,7 +592,7 @@ func TestInvalidKeyError(t *testing.T) { tests := []struct { note string rules []string - expected interface{} + expected any }{ {"invalid keys", []string{`p = x { http.send({"method": "get", "url": "http://127.0.0.1:51113", "bad_key": "bad_value"}, x) }`}, &Error{Code: TypeErr, Message: `invalid request parameters(s): {"bad_key"}`}}, {"missing keys", []string{`p = x { http.send({"method": "get"}, x) }`}, &Error{Code: TypeErr, Message: `missing required request parameters(s): {"url"}`}}, @@ -612,7 +612,7 @@ func TestInvalidRetryParam(t *testing.T) { tests := []struct { note string rules []string - expected interface{} + expected any }{ {"invalid retry param", []string{`p = x { http.send({"method": "get", "url": "http://127.0.0.1:51113", "max_retry_attempts": "bad_value"}, x) }`}, &Error{Code: BuiltinErr, Message: `http.send: invalid value "bad_value" for field "max_retry_attempts"`}}, {"invalid number", []string{`p = x { http.send({"method": "get", "url": "http://127.0.0.1:51113", "max_retry_attempts": 1.2}, x) }`}, &Error{Code: BuiltinErr, Message: `http.send: invalid value 1.2 for field "max_retry_attempts"`}}, @@ -632,7 +632,7 @@ func TestParseTimeout(t *testing.T) { tests := []struct { note string raw ast.Value - expected interface{} + expected any }{ { note: "zero string", @@ -732,15 +732,15 @@ func TestHTTPRedirectDisable(t *testing.T) { defer teardown() // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["body"] = nil expectedResult["raw_body"] = "Moved Permanently.\n\n" expectedResult["status"] = "301 Moved Permanently" expectedResult["status_code"] = http.StatusMovedPermanently - expectedResult["headers"] = map[string]interface{}{ - "content-length": []interface{}{"40"}, - "content-type": []interface{}{"text/html; charset=utf-8"}, - "location": []interface{}{"/test"}, + expectedResult["headers"] = map[string]any{ + "content-length": []any{"40"}, + "content-type": []any{"text/html; charset=utf-8"}, + "location": []any{"/test"}, } resultObj := ast.MustInterfaceToValue(expectedResult) @@ -764,13 +764,13 @@ func TestHTTPRedirectEnable(t *testing.T) { defer teardown() // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK expectedResult["body"] = nil expectedResult["raw_body"] = "" - expectedResult["headers"] = map[string]interface{}{ - "content-length": []interface{}{"0"}, + expectedResult["headers"] = map[string]any{ + "content-length": []any{"0"}, } resultObj := ast.MustInterfaceToValue(expectedResult) @@ -800,7 +800,7 @@ func TestHTTPRedirectAllowNet(t *testing.T) { serverHost := strings.Split(serverURL.Host, ":")[0] // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK expectedResult["body"] = nil @@ -818,7 +818,7 @@ func TestHTTPRedirectAllowNet(t *testing.T) { note string rules []string options func(*Query) *Query - expected interface{} + expected any }{ { "http.send allow_net nil", @@ -860,29 +860,29 @@ func TestHTTPSendRaiseError(t *testing.T) { baseURL, teardown := getTestServer() defer teardown() - networkErrObj := make(map[string]interface{}) + networkErrObj := make(map[string]any) networkErrObj["code"] = HTTPSendNetworkErr networkErrObj["message"] = "Get \"foo://foo.com\": unsupported protocol scheme \"foo\"" networkErr := ast.MustInterfaceToValue(networkErrObj) - internalErrObj := make(map[string]interface{}) + internalErrObj := make(map[string]any) internalErrObj["code"] = HTTPSendInternalErr internalErrObj["message"] = fmt.Sprintf(`http.send({"method": "get", "url": "%s", "force_json_decode": true, "raise_error": false, "force_cache": true}): eval_builtin_error: http.send: 'force_cache' set but 'force_cache_duration_seconds' parameter is missing`, baseURL) internalErr := ast.MustInterfaceToValue(internalErrObj) - responseObj := make(map[string]interface{}) + responseObj := make(map[string]any) responseObj["status_code"] = 0 responseObj["error"] = internalErrObj response := ast.MustInterfaceToValue(responseObj) - inputValidationErrObj := make(map[string]interface{}) + inputValidationErrObj := make(map[string]any) inputValidationErrObj["code"] = HTTPSendInternalErr inputValidationErrObj["message"] = fmt.Sprintf(`http.send({"url": "%s", "raise_error": false}): eval_type_error: http.send: operand 1 missing required request parameters(s): {"method"}`, baseURL) - responseObjInputValidationErr := make(map[string]interface{}) + responseObjInputValidationErr := make(map[string]any) responseObjInputValidationErr["status_code"] = 0 responseObjInputValidationErr["error"] = inputValidationErrObj @@ -892,7 +892,7 @@ func TestHTTPSendRaiseError(t *testing.T) { note string ruleTemplate string body string - response interface{} + response any }{ { note: "http.send invalid url (don't raise error, check response body)", @@ -1287,7 +1287,7 @@ func TestHTTPSendIntraQueryCaching(t *testing.T) { t.Fatalf("Expected to get %d requests, got %d", tc.expectedReqCount, actualCount) } - var x interface{} + var x any if err := util.UnmarshalJSON([]byte(request), &x); err != nil { t.Fatalf("failed to unmarshal request: %v", err) } @@ -1718,7 +1718,7 @@ func TestHTTPSendInterQueryForceCachingRefresh(t *testing.T) { } // pull the result out of the cache - var x interface{} + var x any if err := util.UnmarshalJSON([]byte(request), &x); err != nil { t.Fatalf("failed to unmarshal request on query %d: %v", i, err) } @@ -2471,15 +2471,15 @@ func TestHTTPSClient(t *testing.T) { t.Run("Server reflects Certificate CommonName", func(t *testing.T) { // expected result bodyMap := map[string]string{"CommonName": "my-ca"} - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "raw_body": "{\"CommonName\":\"my-ca\"}", } expectedResult["body"] = bodyMap - expectedResult["headers"] = map[string]interface{}{ - "content-length": []interface{}{"22"}, - "content-type": []interface{}{"application/json"}, + expectedResult["headers"] = map[string]any{ + "content-length": []any{"22"}, + "content-type": []any{"application/json"}, } resultObj, err := ast.InterfaceToValue(expectedResult) @@ -2498,13 +2498,13 @@ func TestHTTPSClient(t *testing.T) { t.Run("HTTPS Get with Inline Cert", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2542,13 +2542,13 @@ func TestHTTPSClient(t *testing.T) { t.Run("HTTPS Get with File Cert", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2569,13 +2569,13 @@ func TestHTTPSClient(t *testing.T) { t.Run("HTTPS Get with Env Cert", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2596,13 +2596,13 @@ func TestHTTPSClient(t *testing.T) { t.Run("HTTPS Get with Env and File Cert", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2623,13 +2623,13 @@ func TestHTTPSClient(t *testing.T) { t.Run("HTTPS Get with System Certs, Env and File Cert", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2770,13 +2770,13 @@ func TestHTTPSNoClientCerts(t *testing.T) { }) t.Run("HTTPS Get with Inline CA Cert", func(t *testing.T) { - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2801,13 +2801,13 @@ func TestHTTPSNoClientCerts(t *testing.T) { t.Run("HTTPS Get with CA Cert File", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2828,13 +2828,13 @@ func TestHTTPSNoClientCerts(t *testing.T) { t.Run("HTTPS Get with CA Cert ENV", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2855,13 +2855,13 @@ func TestHTTPSNoClientCerts(t *testing.T) { t.Run("HTTPS Get with System CA Cert Pool", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -2882,13 +2882,13 @@ func TestHTTPSNoClientCerts(t *testing.T) { t.Run("HTTPS Get with System Certs, Env and File Cert", func(t *testing.T) { // expected result - expectedResult := map[string]interface{}{ + expectedResult := map[string]any{ "status": "200 OK", "status_code": http.StatusOK, "body": nil, "raw_body": "", - "headers": map[string]interface{}{ - "content-length": []interface{}{"0"}, + "headers": map[string]any{ + "content-length": []any{"0"}, }, } @@ -3581,20 +3581,20 @@ func TestSocketHTTPGetRequest(t *testing.T) { rawURL := fmt.Sprintf("unix://localhost/end/point?%s¶m1=value1¶m2=value2", path) // Send a request to the server over the socket // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK - var body []interface{} + var body []any bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body expectedResult["raw_body"] = "[{\"id\":\"1\",\"firstname\":\"John\"}]\n" - expectedResult["headers"] = map[string]interface{}{ - "content-length": []interface{}{"32"}, - "content-type": []interface{}{"text/plain; charset=utf-8"}, - "test-header": []interface{}{"test-value"}, - "echo-query-string": []interface{}{"param1=value1¶m2=value2"}, + expectedResult["headers"] = map[string]any{ + "content-length": []any{"32"}, + "content-type": []any{"text/plain; charset=utf-8"}, + "test-header": []any{"test-value"}, + "echo-query-string": []any{"param1=value1¶m2=value2"}, } resultObj := ast.MustInterfaceToValue(expectedResult) @@ -3603,7 +3603,7 @@ func TestSocketHTTPGetRequest(t *testing.T) { tests := []struct { note string rules []string - expected interface{} + expected any }{ {"http.send", []string{fmt.Sprintf( `p = x { http.send({"method": "get", "url": %q, "force_json_decode": true}, resp); x := clean_headers(resp) }`, rawURL)}, resultObj.String()}, @@ -3700,7 +3700,7 @@ func TestHTTPGetRequestAllowNet(t *testing.T) { serverHost := strings.Split(serverURL.Host, ":")[0] // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK @@ -3719,7 +3719,7 @@ func TestHTTPGetRequestAllowNet(t *testing.T) { note string rules []string options func(*Query) *Query - expected interface{} + expected any }{ { "http.send allow_net nil", @@ -3806,7 +3806,7 @@ func TestHTTPWithCustomTransport(t *testing.T) { serverHost := strings.Split(serverURL.Host, ":")[0] // expected result - expectedResult := make(map[string]interface{}) + expectedResult := make(map[string]any) expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK @@ -3831,7 +3831,7 @@ func TestHTTPWithCustomTransport(t *testing.T) { note string rules []string options func(*Query) *Query - expected interface{} + expected any calls int }{ { diff --git a/v1/topdown/input_test.go b/v1/topdown/input_test.go index cd78b45d45..b1645a4771 100644 --- a/v1/topdown/input_test.go +++ b/v1/topdown/input_test.go @@ -17,7 +17,7 @@ func TestMergeTermWithValues(t *testing.T) { note string exist string input [][2]string - expected interface{} + expected any }{ { note: "var", diff --git a/v1/topdown/json_bench_test.go b/v1/topdown/json_bench_test.go index 3207e6a9d6..e2c0424b73 100644 --- a/v1/topdown/json_bench_test.go +++ b/v1/topdown/json_bench_test.go @@ -347,7 +347,7 @@ func BenchmarkJSONPatchReplace(b *testing.B) { for _, p := range sizes { testName := fmt.Sprintf("%dx%dx10-%dp", n, m, p) b.Run(testName, func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{ + store := inmem.NewFromObject(map[string]any{ "obj": testdata[testName][0], "patches": testdata[testName][1], }) @@ -496,7 +496,7 @@ func BenchmarkJSONPatchPathologicalNestedAddChainSet(b *testing.B) { } func runJSONPatchBenchmarkTest(ctx context.Context, b *testing.B, source ast.Value, patches ast.Value) { - store := inmem.NewFromObject(map[string]interface{}{ + store := inmem.NewFromObject(map[string]any{ "source": source, "patches": patches, }) diff --git a/v1/topdown/jsonschema.go b/v1/topdown/jsonschema.go index b1609fb044..88057c7746 100644 --- a/v1/topdown/jsonschema.go +++ b/v1/topdown/jsonschema.go @@ -29,7 +29,7 @@ func astValueToJSONSchemaLoader(value ast.Value) (gojsonschema.JSONLoader, error loader = gojsonschema.NewStringLoader(string(x)) case ast.Object: // In case of object serialize it to JSON representation. - var data interface{} + var data any data, err = ast.JSON(value) if err != nil { return nil, err diff --git a/v1/topdown/net_test.go b/v1/topdown/net_test.go index c5b55a1e36..57ac7d72f4 100644 --- a/v1/topdown/net_test.go +++ b/v1/topdown/net_test.go @@ -219,4 +219,4 @@ func TestNetLookupIPAddr(t *testing.T) { type sink struct{} -func (sink) Printf(string, ...interface{}) {} +func (sink) Printf(string, ...any) {} diff --git a/v1/topdown/object_bench_test.go b/v1/topdown/object_bench_test.go index 24ec7a56c5..8533352f29 100644 --- a/v1/topdown/object_bench_test.go +++ b/v1/topdown/object_bench_test.go @@ -34,7 +34,7 @@ func BenchmarkObjectUnionN(b *testing.B) { for _, n := range sizes { for _, m := range sizes { b.Run(fmt.Sprintf("%dx%d", n, m), func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{"objs": genNxMObjectBenchmarkData(n, m)}) + store := inmem.NewFromObject(map[string]any{"objs": genNxMObjectBenchmarkData(n, m)}) module := `package test combined := object.union_n(data.objs)` @@ -83,7 +83,7 @@ func BenchmarkObjectUnionNSlow(b *testing.B) { for _, n := range sizes { for _, m := range sizes { b.Run(fmt.Sprintf("%dx%d", n, m), func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{"objs": genNxMObjectBenchmarkData(n, m)}) + store := inmem.NewFromObject(map[string]any{"objs": genNxMObjectBenchmarkData(n, m)}) module := `package test combined := {k: true | s := data.objs[_]; s[k]}` diff --git a/v1/topdown/runtime.go b/v1/topdown/runtime.go index dc72fc5818..dea0b31746 100644 --- a/v1/topdown/runtime.go +++ b/v1/topdown/runtime.go @@ -26,9 +26,9 @@ func builtinOPARuntime(bctx BuiltinContext, _ []*ast.Term, iter func(*ast.Term) if err != nil { return err } - if object, ok := iface.(map[string]interface{}); ok { + if object, ok := iface.(map[string]any); ok { if cfgRaw, ok := object["config"]; ok { - if config, ok := cfgRaw.(map[string]interface{}); ok { + if config, ok := cfgRaw.(map[string]any); ok { configPurged, err := activeConfig(config) if err != nil { return err @@ -51,7 +51,7 @@ func init() { RegisterBuiltinFunc(ast.OPARuntime.Name, builtinOPARuntime) } -func activeConfig(config map[string]interface{}) (interface{}, error) { +func activeConfig(config map[string]any) (any, error) { if config["services"] != nil { err := removeServiceCredentials(config["services"]) @@ -70,10 +70,10 @@ func activeConfig(config map[string]interface{}) (interface{}, error) { return config, nil } -func removeServiceCredentials(x interface{}) error { +func removeServiceCredentials(x any) error { switch x := x.(type) { - case []interface{}: + case []any: for _, v := range x { err := removeKey(v, "credentials") if err != nil { @@ -81,7 +81,7 @@ func removeServiceCredentials(x interface{}) error { } } - case map[string]interface{}: + case map[string]any: for _, v := range x { err := removeKey(v, "credentials") if err != nil { @@ -95,10 +95,10 @@ func removeServiceCredentials(x interface{}) error { return nil } -func removeCryptoKeys(x interface{}) error { +func removeCryptoKeys(x any) error { switch x := x.(type) { - case map[string]interface{}: + case map[string]any: for _, v := range x { err := removeKey(v, "key", "private_key") if err != nil { @@ -112,8 +112,8 @@ func removeCryptoKeys(x interface{}) error { return nil } -func removeKey(x interface{}, keys ...string) error { - val, ok := x.(map[string]interface{}) +func removeKey(x any, keys ...string) error { + val, ok := x.(map[string]any) if !ok { return errors.New("type assertion error") } @@ -127,6 +127,6 @@ func removeKey(x interface{}, keys ...string) error { type illegalResolver struct{} -func (illegalResolver) Resolve(ref ast.Ref) (interface{}, error) { +func (illegalResolver) Resolve(ref ast.Ref) (any, error) { return nil, fmt.Errorf("illegal value: %v", ref) } diff --git a/v1/topdown/save.go b/v1/topdown/save.go index 439f554a34..15b61a7f77 100644 --- a/v1/topdown/save.go +++ b/v1/topdown/save.go @@ -355,11 +355,11 @@ func splitPackageAndRule(path ast.Ref) (ast.Ref, ast.Ref) { // being saved. This check allows the evaluator to evaluate statements // completely during partial evaluation as long as they do not depend on any // kind of unknown value or statements that would generate saves. -func saveRequired(c *ast.Compiler, ic *inliningControl, icIgnoreInternal bool, ss *saveSet, b *bindings, x interface{}, rec bool) bool { +func saveRequired(c *ast.Compiler, ic *inliningControl, icIgnoreInternal bool, ss *saveSet, b *bindings, x any, rec bool) bool { var found bool - vis := ast.NewGenericVisitor(func(node interface{}) bool { + vis := ast.NewGenericVisitor(func(node any) bool { if found { return found } diff --git a/v1/topdown/sets_bench_test.go b/v1/topdown/sets_bench_test.go index 510d8a1c80..2a0695599b 100644 --- a/v1/topdown/sets_bench_test.go +++ b/v1/topdown/sets_bench_test.go @@ -34,7 +34,7 @@ func BenchmarkSetIntersection(b *testing.B) { for _, n := range sizes { for _, m := range sizes { b.Run(fmt.Sprintf("%dx%d", n, m), func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{"sets": genNxMSetBenchmarkData(n, m)}) + store := inmem.NewFromObject(map[string]any{"sets": genNxMSetBenchmarkData(n, m)}) module := `package test @@ -81,7 +81,7 @@ func BenchmarkSetIntersectionSlow(b *testing.B) { for _, n := range sizes { for _, m := range sizes { b.Run(fmt.Sprintf("%dx%d", n, m), func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{"sets": genNxMSetBenchmarkData(n, m)}) + store := inmem.NewFromObject(map[string]any{"sets": genNxMSetBenchmarkData(n, m)}) module := `package test @@ -133,7 +133,7 @@ func BenchmarkSetUnion(b *testing.B) { for _, n := range sizes { for _, m := range sizes { b.Run(fmt.Sprintf("%dx%d", n, m), func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{"sets": genNxMSetBenchmarkData(n, m)}) + store := inmem.NewFromObject(map[string]any{"sets": genNxMSetBenchmarkData(n, m)}) // Code is lifted from here: // https://github.com/open-policy-agent/opa/issues/4979#issue-1332019382 @@ -186,7 +186,7 @@ func BenchmarkSetUnionSlow(b *testing.B) { for _, n := range sizes { for _, m := range sizes { b.Run(fmt.Sprintf("%dx%d", n, m), func(b *testing.B) { - store := inmem.NewFromObject(map[string]interface{}{"sets": genNxMSetBenchmarkData(n, m)}) + store := inmem.NewFromObject(map[string]any{"sets": genNxMSetBenchmarkData(n, m)}) // Code is lifted from here: // https://github.com/open-policy-agent/opa/issues/4979#issue-1332019382 diff --git a/v1/topdown/strings_bench_test.go b/v1/topdown/strings_bench_test.go index cd69c6825c..c4cbcdcf0c 100644 --- a/v1/topdown/strings_bench_test.go +++ b/v1/topdown/strings_bench_test.go @@ -100,7 +100,7 @@ result if { } } -func generateBulkStartsWithInput() map[string]interface{} { +func generateBulkStartsWithInput() map[string]any { strs := make([]string, 0, 1000) for i := range strs { strs = append(strs, fmt.Sprintf("aabbccddeeffgghhiijjkkllmmnnoopp_%d", i)) @@ -109,7 +109,7 @@ func generateBulkStartsWithInput() map[string]interface{} { for i := range prefixes { prefixes = append(prefixes, fmt.Sprintf("aabbccddeeffgghhiijjkkllmmnnoorr_%d", i)) } - return map[string]interface{}{ + return map[string]any{ "strings": strs, "prefixes": prefixes, } diff --git a/v1/topdown/template.go b/v1/topdown/template.go index cf4635559d..29038a6579 100644 --- a/v1/topdown/template.go +++ b/v1/topdown/template.go @@ -19,7 +19,7 @@ func renderTemplate(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) return err } - var templateVariables map[string]interface{} + var templateVariables map[string]any if err := ast.As(templateVariablesTerm, &templateVariables); err != nil { return err diff --git a/v1/topdown/tokens.go b/v1/topdown/tokens.go index 2050e82d63..4054476d0f 100644 --- a/v1/topdown/tokens.go +++ b/v1/topdown/tokens.go @@ -224,7 +224,7 @@ func builtinJWTVerifyPS512(bctx BuiltinContext, operands []*ast.Term, iter func( // Implements RSA JWT signature verification. func builtinJWTVerifyRSA(bctx BuiltinContext, jwt ast.Value, keyStr ast.Value, hasher func() hash.Hash, verify func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error) (ast.Value, error) { - return builtinJWTVerify(bctx, jwt, keyStr, hasher, func(publicKey interface{}, digest []byte, signature []byte) error { + return builtinJWTVerify(bctx, jwt, keyStr, hasher, func(publicKey any, digest []byte, signature []byte) error { publicKeyRsa, ok := publicKey.(*rsa.PublicKey) if !ok { return errors.New("incorrect public key type") @@ -260,7 +260,7 @@ func builtinJWTVerifyES512(bctx BuiltinContext, operands []*ast.Term, iter func( return err } -func verifyES(publicKey interface{}, digest []byte, signature []byte) (err error) { +func verifyES(publicKey any, digest []byte, signature []byte) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("ECDSA signature verification error: %v", r) @@ -283,7 +283,7 @@ func verifyES(publicKey interface{}, digest []byte, signature []byte) (err error type verificationKey struct { alg string kid string - key interface{} + key any } // getKeysFromCertOrJWK returns the public key found in a X.509 certificate or JWK key(s). @@ -346,7 +346,7 @@ func getKeyByKid(kid string, keys []verificationKey) *verificationKey { } // Implements JWT signature verification. -func builtinJWTVerify(bctx BuiltinContext, jwt ast.Value, keyStr ast.Value, hasher func() hash.Hash, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) { +func builtinJWTVerify(bctx BuiltinContext, jwt ast.Value, keyStr ast.Value, hasher func() hash.Hash, verify func(publicKey any, digest []byte, signature []byte) error) (ast.Value, error) { if found, _, _, valid := getTokenFromCache(bctx, jwt, keyStr); found { return ast.Boolean(valid), nil } @@ -701,8 +701,8 @@ func (constraints *tokenConstraints) validAudience(aud ast.Value) bool { // JWT algorithms type ( - tokenVerifyFunction func(key interface{}, hash crypto.Hash, payload []byte, signature []byte) error - tokenVerifyAsymmetricFunction func(key interface{}, hash crypto.Hash, digest []byte, signature []byte) error + tokenVerifyFunction func(key any, hash crypto.Hash, payload []byte, signature []byte) error + tokenVerifyAsymmetricFunction func(key any, hash crypto.Hash, digest []byte, signature []byte) error ) // jwtAlgorithm describes a JWS 'alg' value @@ -730,7 +730,7 @@ var tokenAlgorithms = map[string]tokenAlgorithm{ // errSignatureNotVerified is returned when a signature cannot be verified. var errSignatureNotVerified = errors.New("signature not verified") -func verifyHMAC(key interface{}, hash crypto.Hash, payload []byte, signature []byte) error { +func verifyHMAC(key any, hash crypto.Hash, payload []byte, signature []byte) error { macKey, ok := key.([]byte) if !ok { return errors.New("incorrect symmetric key type") @@ -746,14 +746,14 @@ func verifyHMAC(key interface{}, hash crypto.Hash, payload []byte, signature []b } func verifyAsymmetric(verify tokenVerifyAsymmetricFunction) tokenVerifyFunction { - return func(key interface{}, hash crypto.Hash, payload []byte, signature []byte) error { + return func(key any, hash crypto.Hash, payload []byte, signature []byte) error { h := hash.New() h.Write(payload) return verify(key, hash, h.Sum([]byte{}), signature) } } -func verifyRSAPKCS(key interface{}, hash crypto.Hash, digest []byte, signature []byte) error { +func verifyRSAPKCS(key any, hash crypto.Hash, digest []byte, signature []byte) error { publicKeyRsa, ok := key.(*rsa.PublicKey) if !ok { return errors.New("incorrect public key type") @@ -764,7 +764,7 @@ func verifyRSAPKCS(key interface{}, hash crypto.Hash, digest []byte, signature [ return nil } -func verifyRSAPSS(key interface{}, hash crypto.Hash, digest []byte, signature []byte) error { +func verifyRSAPSS(key any, hash crypto.Hash, digest []byte, signature []byte) error { publicKeyRsa, ok := key.(*rsa.PublicKey) if !ok { return errors.New("incorrect public key type") @@ -775,7 +775,7 @@ func verifyRSAPSS(key interface{}, hash crypto.Hash, digest []byte, signature [] return nil } -func verifyECDSA(key interface{}, _ crypto.Hash, digest []byte, signature []byte) (err error) { +func verifyECDSA(key any, _ crypto.Hash, digest []byte, signature []byte) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("ECDSA signature verification error: %v", r) diff --git a/v1/topdown/tokens_test.go b/v1/topdown/tokens_test.go index a7fdf3eb43..31e8ebb1aa 100644 --- a/v1/topdown/tokens_test.go +++ b/v1/topdown/tokens_test.go @@ -653,7 +653,7 @@ func TestTopdownJWTVerifyOnlyVerifiesUsingApplicableKeys(t *testing.T) { token := ast.MustInterfaceToValue(fmt.Sprintf("%s.%s.%s", header, payload, signature)) verifyCalls := 0 - verifier := func(_ interface{}, _ []byte, _ []byte) error { + verifier := func(_ any, _ []byte, _ []byte) error { verifyCalls++ return errors.New("fail") } diff --git a/v1/topdown/topdown_bench_test.go b/v1/topdown/topdown_bench_test.go index fe9c36a33b..a66b50d3b6 100644 --- a/v1/topdown/topdown_bench_test.go +++ b/v1/topdown/topdown_bench_test.go @@ -38,11 +38,11 @@ func BenchmarkArrayPlugging(b *testing.B) { for _, n := range sizes { b.Run(strconv.Itoa(n), func(b *testing.B) { - data := make([]interface{}, n) + data := make([]any, n) for i := range n { data[i] = fmt.Sprintf("whatever%d", i) } - store := inmem.NewFromObject(map[string]interface{}{"fixture": data}) + store := inmem.NewFromObject(map[string]any{"fixture": data}) module := `package test fixture := data.fixture main if { x := fixture }` @@ -503,17 +503,17 @@ const partialEvalBenchmarkPolicy = `package authz } ` -func generatePartialEvalBenchmarkData(numRoles int) map[string]interface{} { - roles := make([]interface{}, numRoles) - bindings := make([]interface{}, numRoles) +func generatePartialEvalBenchmarkData(numRoles int) map[string]any { + roles := make([]any, numRoles) + bindings := make([]any, numRoles) for i := range numRoles { - role := map[string]interface{}{ + role := map[string]any{ "name": fmt.Sprintf("role-%d", i), "operation": fmt.Sprintf("operation-%d", i), "resource": fmt.Sprintf("resource-%d", i), } roles[i] = role - binding := map[string]interface{}{ + binding := map[string]any{ "name": fmt.Sprintf("binding-%d", i), "iss": fmt.Sprintf("iss-%d", i), "group": fmt.Sprintf("group-%d", i), @@ -521,7 +521,7 @@ func generatePartialEvalBenchmarkData(numRoles int) map[string]interface{} { } bindings[i] = binding } - return map[string]interface{}{ + return map[string]any{ "roles": roles, "bindings": bindings, } @@ -586,12 +586,12 @@ func BenchmarkWalk(b *testing.B) { } -func genWalkBenchmarkData(n int) map[string]interface{} { - sl := make([]interface{}, n) +func genWalkBenchmarkData(n int) map[string]any { + sl := make([]any, n) for i := range n { sl[i] = i } - return map[string]interface{}{ + return map[string]any{ "arr": sl, } } @@ -724,12 +724,12 @@ func moduleWithDefs(n int) string { return b.String() } -func genComprehensionIndexingData(n int) map[string]interface{} { - items := map[string]interface{}{} +func genComprehensionIndexingData(n int) map[string]any { + items := map[string]any{} for i := range n { items[strconv.Itoa(i)] = strconv.Itoa(i) } - return map[string]interface{}{"items": items} + return map[string]any{"items": items} } func BenchmarkObjectSubset(b *testing.B) { @@ -749,7 +749,7 @@ func BenchmarkObjectSubset(b *testing.B) { } } - store := inmem.NewFromObject(map[string]interface{}{"all": all, "evens": evens}) + store := inmem.NewFromObject(map[string]any{"all": all, "evens": evens}) module := `package test main if {object.subset(data.all, data.evens)}` @@ -806,7 +806,7 @@ func BenchmarkObjectSubsetSlow(b *testing.B) { } } - store := inmem.NewFromObject(map[string]interface{}{"all": all, "evens": evens}) + store := inmem.NewFromObject(map[string]any{"all": all, "evens": evens}) // Code is lifted from here: // https://github.com/open-policy-agent/opa/issues/4358#issue-1141145857 @@ -899,7 +899,7 @@ func BenchmarkGlob(b *testing.B) { needle := haystack[needleIndex] needleGlob := needle[0:length/2] + "*" - store := inmem.NewFromObject(map[string]interface{}{ + store := inmem.NewFromObject(map[string]any{ "haystack": haystack, "needleGlob": needleGlob, }) diff --git a/v1/topdown/topdown_partial_bench_test.go b/v1/topdown/topdown_partial_bench_test.go index 61bf50f061..f4da598238 100644 --- a/v1/topdown/topdown_partial_bench_test.go +++ b/v1/topdown/topdown_partial_bench_test.go @@ -67,14 +67,14 @@ func BenchmarkInliningFullScan(b *testing.B) { } -func generateInlineFullScanBenchmarkData(n int) map[string]interface{} { +func generateInlineFullScanBenchmarkData(n int) map[string]any { - sl := make([]interface{}, n) + sl := make([]any, n) for i := range sl { sl[i] = strconv.Itoa(i) } - return map[string]interface{}{ + return map[string]any{ "a": sl, } } diff --git a/v1/topdown/topdown_partial_test.go b/v1/topdown/topdown_partial_test.go index d6d940dc46..68690bc545 100644 --- a/v1/topdown/topdown_partial_test.go +++ b/v1/topdown/topdown_partial_test.go @@ -4322,7 +4322,7 @@ func prepareTest(ctx context.Context, t *testing.T, params fixtureParams, f func if len(params.data) > 0 { j := util.MustUnmarshalJSON([]byte(params.data)) - store = inmem.NewFromObject(j.(map[string]interface{})) + store = inmem.NewFromObject(j.(map[string]any)) } else { store = inmem.New() } diff --git a/v1/topdown/topdown_test.go b/v1/topdown/topdown_test.go index 3386b5e869..816c8a488f 100644 --- a/v1/topdown/topdown_test.go +++ b/v1/topdown/topdown_test.go @@ -136,7 +136,7 @@ func TestTopDownWithKeyword(t *testing.T) { rules []string modules []string input string - exp interface{} + exp any }{ { // NOTE(tsandall): This case assumes that partial sets are not memoized. @@ -200,11 +200,11 @@ func TestTopDownQueryCancellation(t *testing.T) { `, }) - arr := make([]interface{}, 1000) + arr := make([]any, 1000) for i := range 1000 { arr[i] = i } - data := map[string]interface{}{ + data := map[string]any{ "arr": arr, } @@ -241,7 +241,7 @@ func TestTopDownQueryCancellationEvery(t *testing.T) { ctx := context.Background() - module := func(ev ast.Every, _ ...interface{}) *ast.Module { + module := func(ev ast.Every, _ ...any) *ast.Module { t.Helper() m := ast.MustParseModuleWithOpts(`package test p if { true }`, @@ -282,11 +282,11 @@ func TestTopDownQueryCancellationEvery(t *testing.T) { t.Fatalf("compiler: %v", compiler.Errors) } - arr := make([]interface{}, 1000) + arr := make([]any, 1000) for i := range 1000 { arr[i] = i } - data := map[string]interface{}{ + data := map[string]any{ "arr": arr, } @@ -1514,13 +1514,13 @@ arr := [1, 2, 3, 4, 5] ctx := context.Background() compiler := compileModules([]string{tc.module}) size := 1000 - arr := make([]interface{}, size) - obj := make(map[string]interface{}, size) + arr := make([]any, size) + obj := make(map[string]any, size) for i := range size { arr[i] = i obj[strconv.Itoa(i)] = i } - data := map[string]interface{}{ + data := map[string]any{ "arr": arr, "arr_small": []int{1, 2, 3, 4, 5}, "obj": obj, @@ -1737,7 +1737,7 @@ type contextPropagationStore struct { storage.WritesNotSupported storage.TriggersNotSupported storage.PolicyNotSupported - calls []interface{} + calls []any } func (*contextPropagationStore) NewTransaction(context.Context, ...storage.TransactionParams) (storage.Transaction, error) { @@ -1755,7 +1755,7 @@ func (*contextPropagationStore) Truncate(context.Context, storage.Transaction, s return nil } -func (m *contextPropagationStore) Read(ctx context.Context, _ storage.Transaction, _ storage.Path) (interface{}, error) { +func (m *contextPropagationStore) Read(ctx context.Context, _ storage.Transaction, _ storage.Path) (any, error) { val := ctx.Value(contextPropagationMock{}) m.calls = append(m.calls, val) return nil, nil @@ -1786,7 +1786,7 @@ p contains x if { data.a[i] = x }`, t.Fatalf("Unexpected query error: %v", err) } - expectedCalls := []interface{}{"bar"} + expectedCalls := []any{"bar"} if !reflect.DeepEqual(expectedCalls, mockStore.calls) { t.Fatalf("Expected %v but got: %v", expectedCalls, mockStore.calls) @@ -1816,7 +1816,7 @@ func (*astStore) Truncate(context.Context, storage.Transaction, storage.Transact return nil } -func (a *astStore) Read(_ context.Context, _ storage.Transaction, path storage.Path) (interface{}, error) { +func (a *astStore) Read(_ context.Context, _ storage.Transaction, path storage.Path) (any, error) { if path.String() == a.path { return a.value, nil } @@ -1859,10 +1859,10 @@ func TestTopdownLazyObj(t *testing.T) { body := ast.MustParseBody(`data.stored = x`) ctx := context.Background() compiler := ast.NewCompiler() - foo := map[string]interface{}{ + foo := map[string]any{ "foo": "bar", } - store := inmem.NewFromObject(map[string]interface{}{ + store := inmem.NewFromObject(map[string]any{ "stored": foo, }) txn := storage.NewTransactionOrDie(ctx, store) @@ -1891,10 +1891,10 @@ func TestTopdownLazyObjOptOut(t *testing.T) { body := ast.MustParseBody(`data.stored = x`) ctx := context.Background() compiler := ast.NewCompiler() - foo := map[string]interface{}{ + foo := map[string]any{ "foo": "bar", } - store := inmem.NewFromObject(map[string]interface{}{ + store := inmem.NewFromObject(map[string]any{ "stored": foo, }) txn := storage.NewTransactionOrDie(ctx, store) @@ -1984,8 +1984,8 @@ func compileRules(imports []string, input []string, modules []string) (*ast.Comp // // Avoid the following top-level keys: i, j, k, p, q, r, v, x, y, z. // These are used for rule names, local variables, etc. -func loadSmallTestData() map[string]interface{} { - var data map[string]interface{} +func loadSmallTestData() map[string]any { + var data map[string]any err := util.UnmarshalJSON([]byte(`{ "a": [1,2,3,4], "b": { @@ -2072,19 +2072,19 @@ func setRoundTripper(t CustomizeRoundTripper) func(*Query) *Query { } } -func runTopDownTestCase(t *testing.T, data map[string]interface{}, note string, rules []string, expected interface{}, options ...func(*Query) *Query) { +func runTopDownTestCase(t *testing.T, data map[string]any, note string, rules []string, expected any, options ...func(*Query) *Query) { t.Helper() runTopDownTestCaseWithContext(context.Background(), t, data, note, rules, nil, "", expected, options...) } -func runTopDownTestCaseWithModules(t *testing.T, data map[string]interface{}, note string, rules []string, modules []string, input string, expected interface{}) { +func runTopDownTestCaseWithModules(t *testing.T, data map[string]any, note string, rules []string, modules []string, input string, expected any) { t.Helper() runTopDownTestCaseWithContext(context.Background(), t, data, note, rules, modules, input, expected) } -func runTopDownTestCaseWithContext(ctx context.Context, t *testing.T, data map[string]interface{}, note string, rules []string, modules []string, input string, expected interface{}, +func runTopDownTestCaseWithContext(ctx context.Context, t *testing.T, data map[string]any, note string, rules []string, modules []string, input string, expected any, options ...func(*Query) *Query) { t.Helper() @@ -2108,7 +2108,7 @@ func runTopDownTestCaseWithContext(ctx context.Context, t *testing.T, data map[s assertTopDownWithPathAndContext(ctx, t, compiler, store, note, []string{"generated", "p"}, input, expected, options...) } -func assertTopDownWithPathAndContext(ctx context.Context, t *testing.T, compiler *ast.Compiler, store storage.Store, note string, path []string, input string, expected interface{}, +func assertTopDownWithPathAndContext(ctx context.Context, t *testing.T, compiler *ast.Compiler, store storage.Store, note string, path []string, input string, expected any, options ...func(*Query) *Query) { t.Helper() @@ -2216,8 +2216,8 @@ func assertTopDownWithPathAndContext(ctx context.Context, t *testing.T, compiler expected := util.MustUnmarshalJSON([]byte(e)) if requiresSort { - sort.Sort(resultSet(result.([]interface{}))) - if sl, ok := expected.([]interface{}); ok { + sort.Sort(resultSet(result.([]any))) + if sl, ok := expected.([]any); ok { sort.Sort(resultSet(sl)) } } @@ -2240,7 +2240,7 @@ func assertTopDownWithPathAndContext(ctx context.Context, t *testing.T, compiler }) } -func runTopDownPartialTestCase(ctx context.Context, t *testing.T, compiler *ast.Compiler, store storage.Store, txn storage.Transaction, input *ast.Term, output *ast.Term, body ast.Body, requiresSort bool, expected interface{}, +func runTopDownPartialTestCase(ctx context.Context, t *testing.T, compiler *ast.Compiler, store storage.Store, txn storage.Transaction, input *ast.Term, output *ast.Term, body ast.Body, requiresSort bool, expected any, options ...func(*Query) *Query) { t.Helper() @@ -2310,8 +2310,8 @@ func runTopDownPartialTestCase(ctx context.Context, t *testing.T, compiler *ast. } if requiresSort { - sort.Sort(resultSet(result.([]interface{}))) - if sl, ok := expected.([]interface{}); ok { + sort.Sort(resultSet(result.([]any))) + if sl, ok := expected.([]any); ok { sort.Sort(resultSet(sl)) } } @@ -2321,7 +2321,7 @@ func runTopDownPartialTestCase(ctx context.Context, t *testing.T, compiler *ast. } } -type resultSet []interface{} +type resultSet []any func (rs resultSet) Less(i, j int) bool { return util.Compare(rs[i], rs[j]) < 0 @@ -2372,7 +2372,7 @@ func getTestNamespace() string { return "" } -func dump(note string, modules map[string]*ast.Module, data interface{}, docpath []string, input *ast.Term, exp interface{}, requiresSort bool) { +func dump(note string, modules map[string]*ast.Module, data any, docpath []string, input *ast.Term, exp any, requiresSort bool) { moduleSet := []string{} for _, module := range modules { @@ -2381,7 +2381,7 @@ func dump(note string, modules map[string]*ast.Module, data interface{}, docpath namespace := getTestNamespace() - test := map[string]interface{}{ + test := map[string]any{ "note": namespace + "/" + note, "data": data, "modules": moduleSet, @@ -2394,14 +2394,14 @@ func dump(note string, modules map[string]*ast.Module, data interface{}, docpath switch e := exp.(type) { case string: - rs := []map[string]interface{}{} + rs := []map[string]any{} if len(e) > 0 { exp := util.MustUnmarshalJSON([]byte(e)) if requiresSort { - sl := exp.([]interface{}) + sl := exp.([]any) sort.Sort(resultSet(sl)) } - rs = append(rs, map[string]interface{}{"x": exp}) + rs = append(rs, map[string]any{"x": exp}) } test["want_result"] = rs if requiresSort { @@ -2414,7 +2414,7 @@ func dump(note string, modules map[string]*ast.Module, data interface{}, docpath panic("Unexpected test expectation. Cowardly refusing to generate test cases.") } - bs, err := yaml.Marshal(map[string]interface{}{"cases": []interface{}{test}}) + bs, err := yaml.Marshal(map[string]any{"cases": []any{test}}) if err != nil { panic(err) } @@ -2438,7 +2438,7 @@ func dump(note string, modules map[string]*ast.Module, data interface{}, docpath } -func assertError(t *testing.T, expected interface{}, actual error) { +func assertError(t *testing.T, expected any, actual error) { t.Helper() if actual == nil { t.Errorf("Expected error but got: %v", actual) diff --git a/v1/topdown/trace.go b/v1/topdown/trace.go index 070e254d28..0c8dc0fb63 100644 --- a/v1/topdown/trace.go +++ b/v1/topdown/trace.go @@ -407,7 +407,7 @@ func formatEvent(event *Event, depth int) string { return fmt.Sprintf("%v%v %q", padding, event.Op, event.Message) } - var details interface{} + var details any if node, ok := event.Node.(*ast.Rule); ok { details = node.Path() } else if event.Ref != nil { @@ -417,7 +417,7 @@ func formatEvent(event *Event, depth int) string { } template := "%v%v %v" - opts := []interface{}{padding, event.Op, details} + opts := []any{padding, event.Op, details} if event.Message != "" { template += " %v" @@ -640,9 +640,9 @@ type PrettyEventOpts struct { PrettyVars bool } -func walkTestTerms(x interface{}, f func(*ast.Term) bool) { +func walkTestTerms(x any, f func(*ast.Term) bool) { var vis *ast.GenericVisitor - vis = ast.NewGenericVisitor(func(x interface{}) bool { + vis = ast.NewGenericVisitor(func(x any) bool { switch x := x.(type) { case ast.Call: for _, t := range x[1:] { @@ -785,7 +785,7 @@ func PrettyEvent(w io.Writer, e *Event, opts PrettyEventOpts) error { func printPrettyVars(w *bytes.Buffer, exprVars map[string]varInfo) { containsTabs := false - varRows := make(map[int]interface{}) + varRows := make(map[int]any) for _, info := range exprVars { if len(info.exprLoc.Tabs) > 0 { containsTabs = true diff --git a/v1/topdown/trace_test.go b/v1/topdown/trace_test.go index 327d0a60b5..3f1bf0b97c 100644 --- a/v1/topdown/trace_test.go +++ b/v1/topdown/trace_test.go @@ -292,7 +292,7 @@ func TestPrettyTracePartialWithLocationTruncatedPaths(t *testing.T) { }, }) - var data map[string]interface{} + var data map[string]any err := util.UnmarshalJSON([]byte(`{ "roles": [ { diff --git a/v1/tracing/tracing.go b/v1/tracing/tracing.go index 2708b78e29..df2fb434a6 100644 --- a/v1/tracing/tracing.go +++ b/v1/tracing/tracing.go @@ -11,10 +11,10 @@ package tracing import "net/http" // Options are options for the HTTPTracingService, passed along as-is. -type Options []interface{} +type Options []any // NewOptions is a helper method for constructing `tracing.Options` -func NewOptions(opts ...interface{}) Options { +func NewOptions(opts ...any) Options { return opts } diff --git a/v1/types/decode.go b/v1/types/decode.go index e3e1e98370..367b64bffb 100644 --- a/v1/types/decode.go +++ b/v1/types/decode.go @@ -131,7 +131,7 @@ type rawobject struct { } type rawstaticproperty struct { - Key interface{} `json:"key"` + Key any `json:"key"` Value json.RawMessage `json:"value"` } diff --git a/v1/types/types.go b/v1/types/types.go index c661e96666..3d5b7b6864 100644 --- a/v1/types/types.go +++ b/v1/types/types.go @@ -62,12 +62,12 @@ type NamedType struct { func (n *NamedType) typeMarker() string { return n.Type.typeMarker() } func (n *NamedType) String() string { return n.Name + ": " + n.Type.String() } func (n *NamedType) MarshalJSON() ([]byte, error) { - var obj map[string]interface{} + var obj map[string]any switch x := n.Type.(type) { - case interface{ toMap() map[string]interface{} }: + case interface{ toMap() map[string]any }: obj = x.toMap() default: - obj = map[string]interface{}{ + obj = map[string]any{ "type": n.Type.typeMarker(), } } @@ -95,7 +95,7 @@ func Named(name string, t Type) *NamedType { // MarshalJSON returns the JSON encoding of t. func (t Null) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "type": t.typeMarker(), }) } @@ -126,7 +126,7 @@ func NewBoolean() Boolean { // MarshalJSON returns the JSON encoding of t. func (t Boolean) MarshalJSON() ([]byte, error) { - repr := map[string]interface{}{ + repr := map[string]any{ "type": t.typeMarker(), } return json.Marshal(repr) @@ -149,7 +149,7 @@ func NewString() String { // MarshalJSON returns the JSON encoding of t. func (t String) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "type": t.typeMarker(), }) } @@ -171,7 +171,7 @@ func NewNumber() Number { // MarshalJSON returns the JSON encoding of t. func (t Number) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "type": t.typeMarker(), }) } @@ -199,8 +199,8 @@ func (t *Array) MarshalJSON() ([]byte, error) { return json.Marshal(t.toMap()) } -func (t *Array) toMap() map[string]interface{} { - repr := map[string]interface{}{ +func (t *Array) toMap() map[string]any { + repr := map[string]any{ "type": t.typeMarker(), } if len(t.static) != 0 { @@ -279,8 +279,8 @@ func (t *Set) MarshalJSON() ([]byte, error) { return json.Marshal(t.toMap()) } -func (t *Set) toMap() map[string]interface{} { - repr := map[string]interface{}{ +func (t *Set) toMap() map[string]any { + repr := map[string]any{ "type": t.typeMarker(), } if t.of != nil { @@ -296,12 +296,12 @@ func (t *Set) String() string { // StaticProperty represents a static object property. type StaticProperty struct { - Key interface{} + Key any Value Type } // NewStaticProperty returns a new StaticProperty object. -func NewStaticProperty(key interface{}, value Type) *StaticProperty { +func NewStaticProperty(key any, value Type) *StaticProperty { return &StaticProperty{ Key: key, Value: value, @@ -310,7 +310,7 @@ func NewStaticProperty(key interface{}, value Type) *StaticProperty { // MarshalJSON returns the JSON encoding of p. func (p *StaticProperty) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "key": p.Key, "value": p.Value, }) @@ -332,7 +332,7 @@ func NewDynamicProperty(key, value Type) *DynamicProperty { // MarshalJSON returns the JSON encoding of p. func (p *DynamicProperty) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "key": p.Key, "value": p.Value, }) @@ -394,8 +394,8 @@ func (t *Object) StaticProperties() []*StaticProperty { } // Keys returns the keys of the object's static elements. -func (t *Object) Keys() []interface{} { - sl := make([]interface{}, 0, len(t.static)) +func (t *Object) Keys() []any { + sl := make([]any, 0, len(t.static)) for _, p := range t.static { sl = append(sl, p.Key) } @@ -407,8 +407,8 @@ func (t *Object) MarshalJSON() ([]byte, error) { return json.Marshal(t.toMap()) } -func (t *Object) toMap() map[string]interface{} { - repr := map[string]interface{}{ +func (t *Object) toMap() map[string]any { + repr := map[string]any{ "type": t.typeMarker(), } if len(t.static) != 0 { @@ -421,7 +421,7 @@ func (t *Object) toMap() map[string]interface{} { } // Select returns the type of the named property. -func (t *Object) Select(name interface{}) Type { +func (t *Object) Select(name any) Type { pos := sort.Search(len(t.static), func(x int) bool { return util.Compare(t.static[x].Key, name) >= 0 }) @@ -481,7 +481,7 @@ func mergeObjects(a, b *Object) *Object { dynamicProps = b.dynamic } - staticPropsMap := make(map[interface{}]Type) + staticPropsMap := make(map[any]Type) for _, sp := range a.static { staticPropsMap[sp.Key] = sp.Value @@ -546,8 +546,8 @@ func (t Any) MarshalJSON() ([]byte, error) { return json.Marshal(t.toMap()) } -func (t Any) toMap() map[string]interface{} { - repr := map[string]interface{}{ +func (t Any) toMap() map[string]any { + repr := map[string]any{ "type": t.typeMarker(), } if len(t) != 0 { @@ -754,7 +754,7 @@ func (t *Function) String() string { // MarshalJSON returns the JSON encoding of t. func (t *Function) MarshalJSON() ([]byte, error) { - repr := map[string]interface{}{ + repr := map[string]any{ "type": t.typeMarker(), } if len(t.args) > 0 { @@ -994,7 +994,7 @@ func Or(a, b Type) Type { } // Select returns a property or item of a. -func Select(a Type, x interface{}) Type { +func Select(a Type, x any) Type { switch a := unwrap(a).(type) { case *Array: n, ok := x.(json.Number) @@ -1136,7 +1136,7 @@ func Nil(a Type) bool { } // TypeOf returns the type of the Golang native value. -func TypeOf(x interface{}) Type { +func TypeOf(x any) Type { switch x := x.(type) { case nil: return Nl @@ -1146,22 +1146,22 @@ func TypeOf(x interface{}) Type { return S case json.Number: return N - case map[string]interface{}: - // The ast.ValueToInterface() function returns ast.Object values as map[string]interface{} - // so map[string]interface{} must be handled here because the type checker uses the value + case map[string]any: + // The ast.ValueToInterface() function returns ast.Object values as map[string]any + // so map[string]any must be handled here because the type checker uses the value // to interface conversion when inferring object types. static := make([]*StaticProperty, 0, len(x)) for k, v := range x { static = append(static, NewStaticProperty(k, TypeOf(v))) } return NewObject(static, nil) - case map[interface{}]interface{}: + case map[any]any: static := make([]*StaticProperty, 0, len(x)) for k, v := range x { static = append(static, NewStaticProperty(k, TypeOf(v))) } return NewObject(static, nil) - case []interface{}: + case []any: static := make([]Type, len(x)) for i := range x { static[i] = TypeOf(x[i]) diff --git a/v1/types/types_bench_test.go b/v1/types/types_bench_test.go index f6d2cffaca..77608350dd 100644 --- a/v1/types/types_bench_test.go +++ b/v1/types/types_bench_test.go @@ -21,7 +21,7 @@ func BenchmarkSelect(b *testing.B) { } } -func runSelectBenchmark(b *testing.B, tpe Type, key interface{}) { +func runSelectBenchmark(b *testing.B, tpe Type, key any) { b.ResetTimer() for range b.N { if result := Select(tpe, key); result != nil { diff --git a/v1/types/types_test.go b/v1/types/types_test.go index 0744a4edcc..619fa6b166 100644 --- a/v1/types/types_test.go +++ b/v1/types/types_test.go @@ -230,7 +230,7 @@ func TestSelect(t *testing.T) { tests := []struct { note string a Type - k interface{} + k any expected Type }{ {"static", NewArray([]Type{S}, nil), json.Number("0"), S}, @@ -325,8 +325,8 @@ func TestValues(t *testing.T) { } func TestTypeOf(t *testing.T) { - tpe := TypeOf(map[interface{}]interface{}{ - "foo": []interface{}{ + tpe := TypeOf(map[any]any{ + "foo": []any{ json.Number("1"), true, nil, "hello", }, }) @@ -345,7 +345,7 @@ func TestTypeOf(t *testing.T) { } func TestTypeOfMapOfString(t *testing.T) { - tpe := TypeOf(map[string]interface{}{ + tpe := TypeOf(map[string]any{ "foo": "bar", "baz": "qux", }) diff --git a/v1/util/compare.go b/v1/util/compare.go index 2569375b19..cffb683028 100644 --- a/v1/util/compare.go +++ b/v1/util/compare.go @@ -13,10 +13,10 @@ import ( // Compare returns 0 if a equals b, -1 if a is less than b, and 1 if b is than a. // // For comparison between values of different types, the following ordering is used: -// nil < bool < int, float64 < string < []interface{} < map[string]interface{}. Slices and maps +// nil < bool < int, float64 < string < []any < map[string]any. Slices and maps // are compared recursively. If one slice or map is a subset of the other slice or map // it is considered "less than". Nil is always equal to nil. -func Compare(a, b interface{}) int { +func Compare(a, b any) int { aSortOrder := sortOrder(a) bSortOrder := sortOrder(b) if aSortOrder < bSortOrder { @@ -73,9 +73,9 @@ func Compare(a, b interface{}) int { } return 1 } - case []interface{}: + case []any: switch b := b.(type) { - case []interface{}: + case []any: bLen := len(b) aLen := len(a) minLen := aLen @@ -95,9 +95,9 @@ func Compare(a, b interface{}) int { } return 1 } - case map[string]interface{}: + case map[string]any: switch b := b.(type) { - case map[string]interface{}: + case map[string]any: aKeys := KeysSorted(a) bKeys := KeysSorted(b) aLen := len(aKeys) @@ -152,7 +152,7 @@ func compareJSONNumber(a, b json.Number) int { return bigA.Cmp(bigB) } -func sortOrder(v interface{}) int { +func sortOrder(v any) int { switch v.(type) { case nil: return nilSort @@ -166,9 +166,9 @@ func sortOrder(v interface{}) int { return numberSort case string: return stringSort - case []interface{}: + case []any: return arraySort - case map[string]interface{}: + case map[string]any: return objectSort } panic(fmt.Sprintf("illegal argument of type %T", v)) diff --git a/v1/util/compare_test.go b/v1/util/compare_test.go index 894d8aeeed..5d425a1eee 100644 --- a/v1/util/compare_test.go +++ b/v1/util/compare_test.go @@ -12,8 +12,8 @@ import ( func TestCompare(t *testing.T) { tests := []struct { - a interface{} - b interface{} + a any + b any expected int }{ {nil, nil, 0}, @@ -32,18 +32,18 @@ func TestCompare(t *testing.T) { {"", "", 0}, {"hello", "", 1}, {"hello world", "hello worldz", -1}, - {[]interface{}{}, "", 1}, - {[]interface{}{}, []interface{}{}, 0}, - {[]interface{}{true, false}, []interface{}{true, nil}, 1}, - {[]interface{}{true, true}, []interface{}{true, true}, 0}, - {[]interface{}{true, false}, []interface{}{true, true}, -1}, - {map[string]interface{}{}, []interface{}{}, 1}, - {map[string]interface{}{"foo": []interface{}{true, false}, "bar": []interface{}{true, true}}, map[string]interface{}{"foo": []interface{}{true, false}, "bar": []interface{}{true, true}}, 0}, - {map[string]interface{}{"foo": []interface{}{true, false}, "bar": []interface{}{true, nil}}, map[string]interface{}{"foo": []interface{}{true, false}, "bar": []interface{}{true, true}}, -1}, - {map[string]interface{}{"foo": []interface{}{true, true}, "bar": []interface{}{true, true}}, map[string]interface{}{"foo": []interface{}{true, false}, "bar": []interface{}{true, true}}, 1}, - {map[string]interface{}{"foo": true, "barr": false}, map[string]interface{}{"foo": true, "bar": false}, 1}, - {map[string]interface{}{"foo": true, "bar": false, "qux": false}, map[string]interface{}{"foo": true, "bar": false}, 1}, - {map[string]interface{}{"foo": true, "bar": false, "baz": false}, map[string]interface{}{"foo": true, "bar": false}, -1}, + {[]any{}, "", 1}, + {[]any{}, []any{}, 0}, + {[]any{true, false}, []any{true, nil}, 1}, + {[]any{true, true}, []any{true, true}, 0}, + {[]any{true, false}, []any{true, true}, -1}, + {map[string]any{}, []any{}, 1}, + {map[string]any{"foo": []any{true, false}, "bar": []any{true, true}}, map[string]any{"foo": []any{true, false}, "bar": []any{true, true}}, 0}, + {map[string]any{"foo": []any{true, false}, "bar": []any{true, nil}}, map[string]any{"foo": []any{true, false}, "bar": []any{true, true}}, -1}, + {map[string]any{"foo": []any{true, true}, "bar": []any{true, true}}, map[string]any{"foo": []any{true, false}, "bar": []any{true, true}}, 1}, + {map[string]any{"foo": true, "barr": false}, map[string]any{"foo": true, "bar": false}, 1}, + {map[string]any{"foo": true, "bar": false, "qux": false}, map[string]any{"foo": true, "bar": false}, 1}, + {map[string]any{"foo": true, "bar": false, "baz": false}, map[string]any{"foo": true, "bar": false}, -1}, } for i, tc := range tests { result := Compare(tc.a, tc.b) diff --git a/v1/util/hashmap.go b/v1/util/hashmap.go index cf6a385f41..69a90cbb53 100644 --- a/v1/util/hashmap.go +++ b/v1/util/hashmap.go @@ -10,7 +10,7 @@ import ( ) // T is a concise way to refer to T. -type T interface{} +type T any type Hasher interface { Hash() int @@ -64,7 +64,7 @@ func NewHashMap(eq func(T, T) bool, hash func(T) int) *HashMap { // Copy returns a shallow copy of this HashMap. func (h *TypedHashMap[K, V]) Copy() *TypedHashMap[K, V] { - cpy := NewTypedHashMap[K, V](h.keq, h.veq, h.khash, h.vhash, h.def) + cpy := NewTypedHashMap(h.keq, h.veq, h.khash, h.vhash, h.def) h.Iter(func(k K, v V) bool { cpy.Put(k, v) return false diff --git a/v1/util/json.go b/v1/util/json.go index 5a4e460b61..fdb2626c78 100644 --- a/v1/util/json.go +++ b/v1/util/json.go @@ -21,11 +21,11 @@ import ( // // This function is intended to be used in place of the standard json.Marshal // function when json.Number is required. -func UnmarshalJSON(bs []byte, x interface{}) error { +func UnmarshalJSON(bs []byte, x any) error { return unmarshalJSON(bs, x, true) } -func unmarshalJSON(bs []byte, x interface{}, ext bool) error { +func unmarshalJSON(bs []byte, x any, ext bool) error { buf := bytes.NewBuffer(bs) decoder := NewJSONDecoder(buf) if err := decoder.Decode(x); err != nil { @@ -61,8 +61,8 @@ func NewJSONDecoder(r io.Reader) *json.Decoder { // // If the data cannot be decoded, this function will panic. This function is for // test purposes. -func MustUnmarshalJSON(bs []byte) interface{} { - var x interface{} +func MustUnmarshalJSON(bs []byte) any { + var x any if err := UnmarshalJSON(bs, &x); err != nil { panic(err) } @@ -73,7 +73,7 @@ func MustUnmarshalJSON(bs []byte) interface{} { // // If the data cannot be encoded, this function will panic. This function is for // test purposes. -func MustMarshalJSON(x interface{}) []byte { +func MustMarshalJSON(x any) []byte { bs, err := json.Marshal(x) if err != nil { panic(err) @@ -86,7 +86,7 @@ func MustMarshalJSON(x interface{}) []byte { // Thereby, it is converting its argument to the representation expected by // rego.Input and inmem's Write operations. Works with both references and // values. -func RoundTrip(x *interface{}) error { +func RoundTrip(x *any) error { bs, err := json.Marshal(x) if err != nil { return err @@ -99,8 +99,8 @@ func RoundTrip(x *interface{}) error { // // Used for preparing Go types (including pointers to structs) into values to be // put through util.RoundTrip(). -func Reference(x interface{}) *interface{} { - var y interface{} +func Reference(x any) *any { + var y any rv := reflect.ValueOf(x) if rv.Kind() == reflect.Ptr { return Reference(rv.Elem().Interface()) @@ -113,7 +113,7 @@ func Reference(x interface{}) *interface{} { } // Unmarshal decodes a YAML, JSON or JSON extension value into the specified type. -func Unmarshal(bs []byte, v interface{}) error { +func Unmarshal(bs []byte, v any) error { if len(bs) > 2 && bs[0] == 0xef && bs[1] == 0xbb && bs[2] == 0xbf { bs = bs[3:] // Strip UTF-8 BOM, see https://www.rfc-editor.org/rfc/rfc8259#section-8.1 } diff --git a/v1/util/json_test.go b/v1/util/json_test.go index 3c53846482..6f131eaa0e 100644 --- a/v1/util/json_test.go +++ b/v1/util/json_test.go @@ -19,7 +19,7 @@ func TestInvalidJSONInput(t *testing.T) { []byte("{ \"k\": 1 }\n!!!}"), } for _, tc := range cases { - var x interface{} + var x any err := util.UnmarshalJSON(tc, &x) if err == nil { t.Errorf("should be an error") @@ -28,7 +28,7 @@ func TestInvalidJSONInput(t *testing.T) { } func TestRoundTrip(t *testing.T) { - cases := []interface{}{ + cases := []any{ nil, 1, 1.1, @@ -53,8 +53,8 @@ func TestRoundTrip(t *testing.T) { } switch x := tc.(type) { // These are the output types we want, nothing else - case nil, bool, json.Number, int64, float64, int, string, []interface{}, - []string, map[string]interface{}, map[string]string: + case nil, bool, json.Number, int64, float64, int, string, []any, + []string, map[string]any, map[string]string: default: t.Errorf("unexpected type %T", x) } @@ -63,27 +63,27 @@ func TestRoundTrip(t *testing.T) { } func TestReference(t *testing.T) { - cases := []interface{}{ + cases := []any{ nil, - func() interface{} { f := interface{}(nil); return &f }(), + func() any { f := any(nil); return &f }(), 1, - func() interface{} { f := 1; return &f }(), + func() any { f := 1; return &f }(), 1.1, - func() interface{} { f := 1.1; return &f }(), + func() any { f := 1.1; return &f }(), false, - func() interface{} { f := false; return &f }(), + func() any { f := false; return &f }(), []int{1}, &[]int{1}, - func() interface{} { f := &[]int{1}; return &f }(), + func() any { f := &[]int{1}; return &f }(), []bool{true}, &[]bool{true}, - func() interface{} { f := &[]bool{true}; return &f }(), + func() any { f := &[]bool{true}; return &f }(), []string{"foo"}, &[]string{"foo"}, - func() interface{} { f := &[]string{"foo"}; return &f }(), + func() any { f := &[]string{"foo"}; return &f }(), map[string]string{"foo": "bar"}, &map[string]string{"foo": "bar"}, - func() interface{} { f := &map[string]string{"foo": "bar"}; return &f }(), + func() any { f := &map[string]string{"foo": "bar"}; return &f }(), struct { F string `json:"foo"` B int `json:"bar"` diff --git a/v1/util/read_gzip_body.go b/v1/util/read_gzip_body.go index b979d0bd0f..ddffe2a4de 100644 --- a/v1/util/read_gzip_body.go +++ b/v1/util/read_gzip_body.go @@ -14,7 +14,7 @@ import ( ) var gzipReaderPool = sync.Pool{ - New: func() interface{} { + New: func() any { reader := new(gzip.Reader) return reader }, diff --git a/v1/util/test/benchmark.go b/v1/util/test/benchmark.go index 39a32afd1e..0176b7f29d 100644 --- a/v1/util/test/benchmark.go +++ b/v1/util/test/benchmark.go @@ -110,26 +110,26 @@ func ObjectIterationBenchmarkModule(n int) string { // GenerateLargeJSONBenchmarkData returns a map of 100 keys and 100.000 key/value // pairs. -func GenerateLargeJSONBenchmarkData() map[string]interface{} { +func GenerateLargeJSONBenchmarkData() map[string]any { return GenerateJSONBenchmarkData(100, 100*1000) } // GenerateJSONBenchmarkData returns a map of `k` keys and `v` key/value pairs. -func GenerateJSONBenchmarkData(k, v int) map[string]interface{} { +func GenerateJSONBenchmarkData(k, v int) map[string]any { // create array of null values that can be iterated over - keys := make([]interface{}, k) + keys := make([]any, k) for i := range keys { keys[i] = nil } // create large JSON object value (100,000 entries is about 2MB on disk) - values := map[string]interface{}{} + values := map[string]any{} for i := range v { values[fmt.Sprintf("key%d", i)] = fmt.Sprintf("value%d", i) } - return map[string]interface{}{ + return map[string]any{ "keys": keys, "values": values, } @@ -138,7 +138,7 @@ func GenerateJSONBenchmarkData(k, v int) map[string]interface{} { // GenerateConcurrencyBenchmarkData returns a module and data; the module // checks some input parameters against that data in a simple API authz // scheme. -func GenerateConcurrencyBenchmarkData() (string, map[string]interface{}) { +func GenerateConcurrencyBenchmarkData() (string, map[string]any) { obj := []byte(` { "objs": [ @@ -168,7 +168,7 @@ func GenerateConcurrencyBenchmarkData() (string, map[string]interface{}) { } `) - var data map[string]interface{} + var data map[string]any if err := json.Unmarshal(obj, &data); err != nil { panic(err) } @@ -192,7 +192,7 @@ func GenerateConcurrencyBenchmarkData() (string, map[string]interface{}) { // GenerateVirtualDocsBenchmarkData generates a module and input; the // numTotalRules and numHitRules create as many rules in the module to // match/miss the returned input. -func GenerateVirtualDocsBenchmarkData(numTotalRules, numHitRules int) (string, map[string]interface{}) { +func GenerateVirtualDocsBenchmarkData(numTotalRules, numHitRules int) (string, map[string]any) { hitRule := ` allow if { @@ -255,8 +255,8 @@ func GenerateVirtualDocsBenchmarkData(numTotalRules, numHitRules int) (string, m panic(err) } - input := map[string]interface{}{ - "path": []interface{}{"accounts", "alice"}, + input := map[string]any{ + "path": []any{"accounts", "alice"}, "method": "POST", "user_id": "alice", }