Use any in place of interface{} (#7566)

Earlier this evening I tried to run the Go
[modernize](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize)
analyzer on OPA. That didn't go as planned:

- https://github.com/golang/go/issues/73661
- https://github.com/golang/go/issues/73663

While we wait for that to be fixed, I figured an old-fashioned
search-and-replace across the repo may work for at least the
`interface{}` to `any` conversion. That should help make it easier
to see the other fixes as applied by the modernize tool once it has
had those issues resolved.

Signed-off-by: Anders Eknert <anders@styra.com>
This commit is contained in:
Anders Eknert
2025-05-12 13:57:48 +02:00
committed by GitHub
parent f3cb38dc05
commit e43ef0a979
336 changed files with 2872 additions and 2872 deletions
+1 -1
View File
@@ -34,6 +34,6 @@ import (
// Sets are considered equal if and only if the symmetric difference of a and b // Sets are considered equal if and only if the symmetric difference of a and b
// is empty. // is empty.
// Other comparisons are consistent but not defined. // Other comparisons are consistent but not defined.
func Compare(a, b interface{}) int { func Compare(a, b any) int {
return v1.Compare(a, b) return v1.Compare(a, b)
} }
+1 -1
View File
@@ -41,6 +41,6 @@ type ErrorDetails = v1.ErrorDetails
type Error = v1.Error type Error = v1.Error
// NewError returns a new Error object. // 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...) return v1.NewError(code, loc, f, a...)
} }
+2 -2
View File
@@ -211,7 +211,7 @@ func NewBody(exprs ...*Expr) Body {
} }
// NewExpr returns a new Expr object. // NewExpr returns a new Expr object.
func NewExpr(terms interface{}) *Expr { func NewExpr(terms any) *Expr {
return v1.NewExpr(terms) 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. // 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) return v1.Copy(x)
} }
+1 -1
View File
@@ -13,6 +13,6 @@ import (
// Pretty writes a pretty representation of the AST rooted at x to w. // Pretty writes a pretty representation of the AST rooted at x to w.
// //
// This is function is intended for debug purposes when inspecting ASTs. // 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) v1.Pretty(w, x)
} }
+1 -1
View File
@@ -9,6 +9,6 @@ import (
) )
// TypeName returns a human readable name for the AST element type. // 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) return v1.TypeName(x)
} }
+11 -11
View File
@@ -30,7 +30,7 @@ func NewLocation(text []byte, file string, row int, col int) *Location {
type Value = v1.Value type Value = v1.Value
// InterfaceToValue converts a native Go value x to a 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) 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. // 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) 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 // ValueToInterface returns the Go representation of an AST value. The AST
// value should not contain any values that require evaluation (e.g., vars, // value should not contain any values that require evaluation (e.g., vars,
// comprehensions, etc.) // comprehensions, etc.)
func ValueToInterface(v Value, resolver Resolver) (interface{}, error) { func ValueToInterface(v Value, resolver Resolver) (any, error) {
return v1.ValueToInterface(v, resolver) return v1.ValueToInterface(v, resolver)
} }
// JSON returns the JSON representation of v. The value must not contain any // JSON returns the JSON representation of v. The value must not contain any
// refs or terms that require evaluation (e.g., vars, comprehensions, etc.) // 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) 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 // JSONWithOpt returns the JSON representation of v. The value must not contain any
// refs or terms that require evaluation (e.g., vars, comprehensions, etc.) // 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) 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 // refs or terms that require evaluation (e.g., vars, comprehensions, etc.) If
// the conversion fails, this function will panic. This function is mostly for // the conversion fails, this function will panic. This function is mostly for
// test purposes. // test purposes.
func MustJSON(v Value) interface{} { func MustJSON(v Value) any {
return v1.MustJSON(v) return v1.MustJSON(v)
} }
// MustInterfaceToValue converts a native Go value x to a Value. If the // MustInterfaceToValue converts a native Go value x to a Value. If the
// conversion fails, this function will panic. This function is mostly for test // conversion fails, this function will panic. This function is mostly for test
// purposes. // purposes.
func MustInterfaceToValue(x interface{}) Value { func MustInterfaceToValue(x any) Value {
return v1.MustInterfaceToValue(x) return v1.MustInterfaceToValue(x)
} }
@@ -115,17 +115,17 @@ func IsComprehension(x Value) bool {
} }
// ContainsRefs returns true if the Value v contains refs. // ContainsRefs returns true if the Value v contains refs.
func ContainsRefs(v interface{}) bool { func ContainsRefs(v any) bool {
return v1.ContainsRefs(v) return v1.ContainsRefs(v)
} }
// ContainsComprehensions returns true if the Value v contains comprehensions. // ContainsComprehensions returns true if the Value v contains comprehensions.
func ContainsComprehensions(v interface{}) bool { func ContainsComprehensions(v any) bool {
return v1.ContainsComprehensions(v) return v1.ContainsComprehensions(v)
} }
// ContainsClosures returns true if the Value v contains closures. // ContainsClosures returns true if the Value v contains closures.
func ContainsClosures(v interface{}) bool { func ContainsClosures(v any) bool {
return v1.ContainsClosures(v) return v1.ContainsClosures(v)
} }
@@ -256,7 +256,7 @@ func ObjectTerm(o ...[2]*Term) *Term {
return v1.ObjectTerm(o...) return v1.ObjectTerm(o...)
} }
func LazyObject(blob map[string]interface{}) Object { func LazyObject(blob map[string]any) Object {
return v1.LazyObject(blob) return v1.LazyObject(blob)
} }
+5 -5
View File
@@ -16,22 +16,22 @@ type Transformer = v1.Transformer
// Transform iterates the AST and calls the Transform function on the // Transform iterates the AST and calls the Transform function on the
// Transformer t for x before recursing. // 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) return v1.Transform(t, x)
} }
// TransformRefs calls the function f on all references under 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) return v1.TransformRefs(x, f)
} }
// TransformVars calls the function f on all vars under x. // 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) return v1.TransformVars(x, f)
} }
// TransformComprehensions calls the functio nf on all comprehensions under x. // 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) return v1.TransformComprehensions(x, f)
} }
@@ -41,6 +41,6 @@ type GenericTransformer = v1.GenericTransformer
// NewGenericTransformer returns a new GenericTransformer that will transform // NewGenericTransformer returns a new GenericTransformer that will transform
// AST nodes using the function f. // 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) return v1.NewGenericTransformer(f)
} }
+13 -13
View File
@@ -21,68 +21,68 @@ type BeforeAndAfterVisitor = v1.BeforeAndAfterVisitor
// Walk iterates the AST by calling the Visit function on the Visitor // Walk iterates the AST by calling the Visit function on the Visitor
// v for x before recursing. // v for x before recursing.
// Deprecated: use GenericVisitor.Walk // Deprecated: use GenericVisitor.Walk
func Walk(v Visitor, x interface{}) { func Walk(v Visitor, x any) {
v1.Walk(v, x) v1.Walk(v, x)
} }
// WalkBeforeAndAfter iterates the AST by calling the Visit function on the // WalkBeforeAndAfter iterates the AST by calling the Visit function on the
// Visitor v for x before recursing. // Visitor v for x before recursing.
// Deprecated: use GenericVisitor.Walk // Deprecated: use GenericVisitor.Walk
func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x interface{}) { func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any) {
v1.WalkBeforeAndAfter(v, x) v1.WalkBeforeAndAfter(v, x)
} }
// WalkVars calls the function f on all vars under x. If the function f // 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. // 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) v1.WalkVars(x, f)
} }
// WalkClosures calls the function f on all closures under x. If the function 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. // 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) v1.WalkClosures(x, f)
} }
// WalkRefs calls the function f on all references under x. If the function 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. // 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) v1.WalkRefs(x, f)
} }
// WalkTerms calls the function f on all terms under x. If the function 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. // 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) v1.WalkTerms(x, f)
} }
// WalkWiths calls the function f on all with modifiers under x. If the function 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. // 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) v1.WalkWiths(x, f)
} }
// WalkExprs calls the function f on all expressions under x. If the function 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. // 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) v1.WalkExprs(x, f)
} }
// WalkBodies calls the function f on all bodies under x. If the function 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. // 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) v1.WalkBodies(x, f)
} }
// WalkRules calls the function f on all rules under x. If the function 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. // 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) v1.WalkRules(x, f)
} }
// WalkNodes calls the function f on all nodes under x. If the function 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. // 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) v1.WalkNodes(x, f)
} }
@@ -93,7 +93,7 @@ type GenericVisitor = v1.GenericVisitor
// NewGenericVisitor returns a new GenericVisitor that will invoke the function // NewGenericVisitor returns a new GenericVisitor that will invoke the function
// f on AST nodes. // f on AST nodes.
func NewGenericVisitor(f func(x interface{}) bool) *GenericVisitor { func NewGenericVisitor(f func(x any) bool) *GenericVisitor {
return v1.NewGenericVisitor(f) return v1.NewGenericVisitor(f)
} }
@@ -105,7 +105,7 @@ type BeforeAfterVisitor = v1.BeforeAfterVisitor
// NewBeforeAfterVisitor returns a new BeforeAndAfterVisitor that // NewBeforeAfterVisitor returns a new BeforeAndAfterVisitor that
// will invoke the functions before and after AST nodes. // 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) return v1.NewBeforeAfterVisitor(before, after)
} }
+1 -1
View File
@@ -70,7 +70,7 @@ func ReadBundleRevisionFromStore(ctx context.Context, store storage.Store, txn s
// ReadBundleMetadataFromStore returns the metadata in the specified bundle. // ReadBundleMetadataFromStore returns the metadata in the specified bundle.
// If the bundle is not activated, this function will return // If the bundle is not activated, this function will return
// storage NotFound error. // 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) return v1.ReadBundleMetadataFromStore(ctx, store, txn, name)
} }
+10 -10
View File
@@ -165,7 +165,7 @@ func benchMain(args []string, params benchmarkCommandParams, w io.Writer, r benc
return 1, errRender 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 — // Do nothing with the result, as we are only interested in benchmarking evaluation —
// not the potentially slow process of rendering the result. // not the potentially slow process of rendering the result.
// Undefined / empty results will still be handled normally (fail the benchmark unless --fail // 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 // Wrap input in "input" attribute
inp := make(map[string]interface{}) inp := make(map[string]any)
if input != nil { if input != nil {
if err = util.Unmarshal(input, &inp); err != 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 var path string
if params.partial { if params.partial {
@@ -426,7 +426,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams,
return nil 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() hist := metrics.New()
var benchErr error var benchErr error
@@ -482,7 +482,7 @@ func runE2E(params benchmarkCommandParams, url string, input map[string]interfac
return br, benchErr 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) reqBody, err := json.Marshal(input)
if err != nil { if err != nil {
@@ -507,7 +507,7 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
var e map[string]interface{} var e map[string]any
if err = util.Unmarshal(body, &e); err != nil { if err = util.Unmarshal(body, &e); err != nil {
return nil, err return nil, err
} }
@@ -555,7 +555,7 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf
i := *result.Result i := *result.Result
peResult, ok := i.(map[string]interface{}) peResult, ok := i.(map[string]any)
if !ok { if !ok {
return nil, errors.New("invalid result for compile response") 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 { if val, ok := peResult["queries"]; ok {
queries, ok := val.([]interface{}) queries, ok := val.([]any)
if !ok { if !ok {
return nil, errors.New("invalid result for output of partial evaluation") 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) 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. // For each histogram add their values to the benchmark results.
// Note: If there are many metrics this gets super verbose. // Note: If there are many metrics this gets super verbose.
for histName, metric := range m { for histName, metric := range m {
histValues, ok := metric.(map[string]interface{}) histValues, ok := metric.(map[string]any)
if !ok { if !ok {
continue continue
} }
+4 -4
View File
@@ -1211,7 +1211,7 @@ a contains 4 if {
RegoVersion: &tc.bundleRegoVersion, RegoVersion: &tc.bundleRegoVersion,
FileRegoVersions: tc.bundleFileRegoVersions, FileRegoVersions: tc.bundleFileRegoVersions,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
} }
for k, v := range tc.modules { for k, v := range tc.modules {
b.Modules = append(b.Modules, bundle.ModuleFile{ b.Modules = append(b.Modules, bundle.ModuleFile{
@@ -1550,9 +1550,9 @@ func testBundle() bundle.Bundle {
return bundle.Bundle{ return bundle.Bundle{
Manifest: bundle.Manifest{}, Manifest: bundle.Manifest{},
Data: map[string]interface{}{ Data: map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": map[string]interface{}{ "b": map[string]any{
"c": 42, "c": 42,
}, },
}, },
+4 -4
View File
@@ -392,7 +392,7 @@ func eval(args []string, params evalCommandParams, w io.Writer) (bool, error) {
results := make([]pr.Output, ectx.params.count) results := make([]pr.Output, ectx.params.count)
profiles := make([][]profiler.ExprStats, 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 { for i := range ectx.params.count {
results[i] = evalOnce(ctx, ectx) results[i] = evalOnce(ctx, ectx)
@@ -408,7 +408,7 @@ func eval(args []string, params evalCommandParams, w io.Writer) (bool, error) {
result.Profile = nil result.Profile = nil
result.Metrics = nil result.Metrics = nil
result.AggregatedProfile = profiler.AggregateProfiles(profiles...) result.AggregatedProfile = profiler.AggregateProfiles(profiles...)
timersAggregated := map[string]interface{}{} timersAggregated := map[string]any{}
for name := range timers[0] { for name := range timers[0] {
var vals []int64 var vals []int64
for _, t := range timers { for _, t := range timers {
@@ -632,7 +632,7 @@ func setupEval(args []string, params evalCommandParams) (*evalContext, error) {
return nil, err return nil, err
} }
if inputBytes != nil { if inputBytes != nil {
var input interface{} var input any
err := util.Unmarshal(inputBytes, &input) err := util.Unmarshal(inputBytes, &input)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse input: %s", err.Error()) return nil, fmt.Errorf("unable to parse input: %s", err.Error())
@@ -862,7 +862,7 @@ type astLocationResetVisitor struct {
n int 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, ok := x.(*ast.Expr); ok {
if expr.Location != nil { if expr.Location != nil {
cpy := *expr.Location cpy := *expr.Location
+9 -9
View File
@@ -1154,10 +1154,10 @@ func TestEvalWithStrictBuiltinErrors(t *testing.T) {
func assertResultSet(t *testing.T, rs rego.ResultSet, expected string) { func assertResultSet(t *testing.T, rs rego.ResultSet, expected string) {
t.Helper() t.Helper()
result := []interface{}{} result := []any{}
for i := range rs { for i := range rs {
values := []interface{}{} values := []any{}
for j := range rs[i].Expressions { for j := range rs[i].Expressions {
values = append(values, rs[i].Expressions[j].Value) 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 // Only check that it *can* be loaded as valid JSON, and that the errors
// are populated. // are populated.
var output map[string]interface{} var output map[string]any
if err := util.NewJSONDecoder(&buf).Decode(&output); err != nil { if err := util.NewJSONDecoder(&buf).Decode(&output); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -1250,10 +1250,10 @@ func TestEvalDebugTraceJSONOutput(t *testing.T) {
var output struct { var output struct {
Explanation []struct { Explanation []struct {
Op string `json:"Op"` Op string `json:"Op"`
Node interface{} `json:"Node"` Node any `json:"Node"`
Location *ast.Location `json:"Location"` Location *ast.Location `json:"Location"`
Locals []map[string]interface{} `json:"Locals"` Locals []map[string]any `json:"Locals"`
LocalMetadata map[string]struct { LocalMetadata map[string]struct {
Name string `json:"name"` Name string `json:"name"`
} `json:"LocalMetadata"` } `json:"LocalMetadata"`
@@ -1802,7 +1802,7 @@ func TestResetExprLocations(t *testing.T) {
var exp int 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, ok := x.(*ast.Expr); ok {
if expr.Location.Row != exp { if expr.Location.Row != exp {
t.Fatalf("Expected %v to have row %v but got %v", expr, exp, expr.Location.Row) 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) 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 { if err := util.NewJSONDecoder(&buf).Decode(&output); err != nil {
t.Fatal(err) t.Fatal(err)
} }
+12 -12
View File
@@ -65,7 +65,7 @@ e.g., opa exec --decision /foo/bar/baz ...
params.Paths = args params.Paths = args
params.BundlePaths = bundlePaths.v params.BundlePaths = bundlePaths.v
if err := runExec(params); err != nil { 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) os.Exit(1)
} }
}, },
@@ -204,7 +204,7 @@ func setupConfig(file string, overrides []string, overrideFiles []string, bundle
return nil, err return nil, err
} }
var root map[string]interface{} var root map[string]any
if err := util.Unmarshal(bs, &root); err != nil { if err := util.Unmarshal(bs, &root); err != nil {
return nil, err 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 // 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 // trigger mode is explicitly set to something other than 'manual' this will
// result in a configuration error. // 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" 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 { for _, x := range cfg {
if bcfg, ok := x.(map[string]interface{}); ok { if bcfg, ok := x.(map[string]any); ok {
bcfg["trigger"] = "manual" bcfg["trigger"] = "manual"
} }
} }
} }
if cfg, ok := root["decision_logs"].(map[string]interface{}); ok { if cfg, ok := root["decision_logs"].(map[string]any); ok {
if rcfg, ok := cfg["reporting"].(map[string]interface{}); ok { if rcfg, ok := cfg["reporting"].(map[string]any); ok {
rcfg["trigger"] = "manual" rcfg["trigger"] = "manual"
} }
} }
if cfg, ok := root["status"].(map[string]interface{}); ok { if cfg, ok := root["status"].(map[string]any); ok {
cfg["trigger"] = "manual" cfg["trigger"] = "manual"
} }
return json.Marshal(root) 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 { if len(paths) == 0 {
return nil return nil
} }
bundles, ok := root["bundles"].(map[string]interface{}) bundles, ok := root["bundles"].(map[string]any)
if !ok { if !ok {
bundles = map[string]interface{}{} bundles = map[string]any{}
root["bundles"] = bundles root["bundles"] = bundles
} }
@@ -263,7 +263,7 @@ func injectExplicitBundles(root map[string]interface{}, paths []string) error {
return err return err
} }
abspath = filepath.ToSlash(abspath) 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), "resource": fmt.Sprintf("file://%v", abspath),
} }
} }
+1 -1
View File
@@ -50,7 +50,7 @@ func toStringSlice(a *any) []string {
switch a := (*a).(type) { switch a := (*a).(type) {
case []string: case []string:
return a return a
case []interface{}: case []any:
strSlice := make([]string, len(a)) strSlice := make([]string, len(a))
for i := range a { for i := range a {
strSlice[i] = a[i].(string) strSlice[i] = a[i].(string)
+1 -1
View File
@@ -273,7 +273,7 @@ func (e fmtError) Error() string {
return fmt.Sprintf("%s (%d)", e.msg, e.code) 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{ return fmtError{
msg: fmt.Sprintf(msg, a...), msg: fmt.Sprintf(msg, a...),
code: 2, code: 2,
+1 -1
View File
@@ -118,7 +118,7 @@ func listAllPaths(roots []string) chan fileListItem {
return ch return ch
} }
func parse(p string) (*interface{}, error) { func parse(p string) (*any, error) {
selectedParser, ok := parsers[path.Ext(p)] selectedParser, ok := parsers[path.Ext(p)]
if !ok { if !ok {
return nil, nil return nil, nil
+1 -1
View File
@@ -40,7 +40,7 @@ func TestParse(t *testing.T) {
t.Fatalf("unexpected error when passing file wiith valid json: %q", err.Error()) t.Fatalf("unexpected error when passing file wiith valid json: %q", err.Error())
} else { } else {
v := *val v := *val
that, ok := v.(map[string]interface{})["this"] that, ok := v.(map[string]any)["this"]
if !ok { if !ok {
t.Fatalf("expected parsed data to have key %q with value %q, found none", "this", "that") t.Fatalf("expected parsed data to have key %q with value %q, found none", "this", "that")
} }
+1 -1
View File
@@ -64,7 +64,7 @@ func (jr *jsonReporter) StoreDecision(input *any, itemPath string) {
if jr.params.FailNonEmpty && rs.Result != nil { if jr.params.FailNonEmpty && rs.Result != nil {
// Check if rs.Result is an array and has one or more members // 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)) { if (!isArray) || (isArray && (len(resultArray) > 0)) {
jr.failCount++ jr.failCount++
} }
+3 -3
View File
@@ -7,17 +7,17 @@ import (
) )
type parser interface { type parser interface {
Parse(io.Reader) (interface{}, error) Parse(io.Reader) (any, error)
} }
type utilParser struct { type utilParser struct {
} }
func (utilParser) Parse(r io.Reader) (interface{}, error) { func (utilParser) Parse(r io.Reader) (any, error) {
bs, err := io.ReadAll(r) bs, err := io.ReadAll(r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var x interface{} var x any
return x, util.Unmarshal(bs, &x) return x, util.Unmarshal(bs, &x)
} }
+3 -3
View File
@@ -25,7 +25,7 @@ func TestUtilParser_Parse(t *testing.T) {
Name string Name string
Reader io.Reader Reader io.Reader
ShouldError bool ShouldError bool
Expectation func(x interface{}) Expectation func(x any)
}{ }{
{ {
Name: "should return an error if the provided reader raises an error", 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", Name: "should return a valid JSON object",
Reader: bytes.NewBuffer(b), Reader: bytes.NewBuffer(b),
ShouldError: false, ShouldError: false,
Expectation: func(x interface{}) { Expectation: func(x any) {
if val, ok := x.(map[string]interface{})["this"]; !ok { if val, ok := x.(map[string]any)["this"]; !ok {
t.Fatalf("expected returned value to have key %q, but none was found", "this") t.Fatalf("expected returned value to have key %q, but none was found", "this")
} else if val != "that" { } else if val != "that" {
t.Fatalf("expected returned value to have value %q for key %q, instead got %q", "that", "this", val) t.Fatalf("expected returned value to have value %q for key %q, instead got %q", "that", "this", val)
+1 -1
View File
@@ -172,7 +172,7 @@ func dofindDefinition(params findDefinitionParams, stdin io.Reader, stdout io.Wr
}) })
if err != nil { if err != nil {
return presentation.JSON(stdout, map[string]interface{}{ return presentation.JSON(stdout, map[string]any{
"error": err, "error": err,
}) })
} }
+2 -2
View File
@@ -106,11 +106,11 @@ func expectJSON(t *testing.T, err error, buffer *bytes.Buffer, exp string) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
var x interface{} var x any
if err := util.UnmarshalJSON(buffer.Bytes(), &x); err != nil { if err := util.UnmarshalJSON(buffer.Bytes(), &x); err != nil {
t.Fatal(err) t.Fatal(err)
} }
var y interface{} var y any
if err := util.UnmarshalJSON([]byte(exp), &y); err != nil { if err := util.UnmarshalJSON([]byte(exp), &y); err != nil {
t.Fatal(err) t.Fatal(err)
} }
+2 -2
View File
@@ -237,7 +237,7 @@ func readBundleFiles(loaders []initload.BundleLoader, h bundle.SignatureHasher)
func hashFileContent(h bundle.SignatureHasher, data []byte, path string) (bundle.FileInfo, error) { func hashFileContent(h bundle.SignatureHasher, data []byte, path string) (bundle.FileInfo, error) {
var fileInfo bundle.FileInfo var fileInfo bundle.FileInfo
var value interface{} var value any
if bundle.IsStructuredDoc(path) { if bundle.IsStructuredDoc(path) {
err := util.Unmarshal(data, &value) 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 { func writeTokenToFile(token, fileLoc string) error {
content := make(map[string]interface{}) content := make(map[string]any)
content["signatures"] = []string{token} content["signatures"] = []string{token}
bs, err := json.MarshalIndent(content, "", " ") bs, err := json.MarshalIndent(content, "", " ")
+1 -1
View File
@@ -20,7 +20,7 @@ import (
func TestWriteTokenToFile(t *testing.T) { func TestWriteTokenToFile(t *testing.T) {
token := `eyJhbGciOiJSUzI1NiJ9.eyJmaWxlcyI6W3sibmFtZSI6ImJ1bmRsZS8ubWFuaWZlc3QiLCJoYXNoIjoiZWUwZWRiZGZkMjgzNTBjNDk2ZjA4ODI3Y2E1Y2VhYjgwMzA2NzI0YjYyZGY1ZjY0MDRlNzBjYjc2NjYxNWQ5ZCIsImFsZ29yaXRobSI6IlNIQTI1NiJ9LHsibmFtZSI6ImJ1bmRsZS9odHRwL2V4YW1wbGUvYXV0aHovYXV0aHoucmVnbyIsImhhc2giOiI2MDJiZTcwMWIyYmE4ZTc3YTljNTNmOWIzM2QwZTkwM2MzNGMwMGMzMDkzM2Y2NDZiYmU3NGI3YzE2NGY2OGM2IiwiYWxnb3JpdGhtIjoiU0hBMjU2In0seyJuYW1lIjoiYnVuZGxlL3JvbGVzL2JpbmRpbmcvZGF0YS5qc29uIiwiaGFzaCI6ImIxODg1NTViZjczMGVlNDdkZjBiY2Y4MzVlYTNmNTQ1MjlmMzc4N2Y0ODQxZjFhZGE2MDM5M2RhYWZhZmJkYzciLCJhbGdvcml0aG0iOiJTSEEyNTYifV0sImtleWlkIjoiZm9vIiwic2NvcGUiOiJyZWFkIn0.YojuPnGWutdlDL7lwFGBXqPfDtxOG2BuZmShN5zm-G9zfMprI1AMqKDoPoNv4tuCGIBNXwoNsYHYiK538CHfJEfY1v4iDX3JFEWQlwx_CfJWDonwqT9SY9tHUW7PUUrI_WgJXZ5zei8RAMYMymKSb9hpSAtfGg_PU0kZr52WzjbPUj4SRiB19Swi61r0CFXYjbfx3GDJdjrGTNBSWrUCMrdhHYLEWqJPfSQ-fYfRrgQVhq3BJLwJJe66dgBEGnHEgA7XMuxkNIOv7mj3Y_EChbv2tjrD9NJPekDcYH1zCEc4BycHjNCcsGiQXDE6sFtoNZiCXLB2D0sLqUnBx4TCw27wTPfcOuL2KauLPahZitnH5mYvQD8NI76Pm4NSyJfevwdWjSsrT7vf0DCLS-dU6r9dJ79xM_hJU7136CT8ARcmSrk-EvCqfkrH2c4WwZyAzdyyyFumMZh4CYc2vcC7ap0NANHJT193fTud1i23mx1PBslwXdsIqXvBGlTbR7nb9o661m-B_mxbHMkG4nIeoGpZoaBJw8RVaA6-4D55gtk8aaMyLJIlIIlV2_AKOLk3nPG3ACHiLSndasLDOIRIYkCluIEaM2FLEEPEtJfKNR6e1K-EK2TvNKMDAEUtJW71ggOuGQ3b5otYOoVVENJLwm-PsO7qb2Tq6PyAquI3ExU` 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} expected["signatures"] = []string{token}
files := map[string]string{} files := map[string]string{}
+3 -3
View File
@@ -2517,7 +2517,7 @@ test_l if {
} }
testBundle := bundle.Bundle{ testBundle := bundle.Bundle{
Data: map[string]interface{}{}, Data: map[string]any{},
} }
for k, v := range tc.files { for k, v := range tc.files {
testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{ testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{
@@ -2864,7 +2864,7 @@ test_l if {
} }
testBundle := bundle.Bundle{ testBundle := bundle.Bundle{
Data: map[string]interface{}{}, Data: map[string]any{},
} }
for k, v := range tc.files { for k, v := range tc.files {
testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{ testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{
@@ -3118,7 +3118,7 @@ test_l if {
} }
testBundle := bundle.Bundle{ testBundle := bundle.Bundle{
Data: map[string]interface{}{}, Data: map[string]any{},
} }
for k, v := range tc.files { for k, v := range tc.files {
testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{ testBundle.Modules = append(testBundle.Modules, bundle.ModuleFile{
+1 -1
View File
@@ -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() mux := http.NewServeMux()
ts := httptest.NewServer(mux) ts := httptest.NewServer(mux)
+15 -15
View File
@@ -414,7 +414,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Manifest: bundle.Manifest{ Manifest: bundle.Manifest{
Roots: &[]string{"a"}, Roots: &[]string{"a"},
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{}, Modules: []bundle.ModuleFile{},
}, },
}, },
@@ -429,7 +429,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"a"}, Roots: &[]string{"a"},
RegoVersion: &regoV1, RegoVersion: &regoV1,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{}, Modules: []bundle.ModuleFile{},
}, },
}, },
@@ -443,14 +443,14 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Manifest: bundle.Manifest{ Manifest: bundle.Manifest{
Roots: &[]string{"a"}, Roots: &[]string{"a"},
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{}, Modules: []bundle.ModuleFile{},
}, },
{ {
Manifest: bundle.Manifest{ Manifest: bundle.Manifest{
Roots: &[]string{"b"}, Roots: &[]string{"b"},
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{}, Modules: []bundle.ModuleFile{},
}, },
}, },
@@ -465,7 +465,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"a"}, Roots: &[]string{"a"},
RegoVersion: &regoV1, RegoVersion: &regoV1,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "a/test1.rego", Path: "a/test1.rego",
@@ -480,7 +480,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"b"}, Roots: &[]string{"b"},
RegoVersion: &regoV1, RegoVersion: &regoV1,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "b/test1.rego", Path: "b/test1.rego",
@@ -507,7 +507,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"a"}, Roots: &[]string{"a"},
RegoVersion: &regoV0, RegoVersion: &regoV0,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "a/test1.rego", Path: "a/test1.rego",
@@ -522,7 +522,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"b"}, Roots: &[]string{"b"},
RegoVersion: &regoV0, RegoVersion: &regoV0,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "b/test1.rego", Path: "b/test1.rego",
@@ -549,7 +549,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"a"}, Roots: &[]string{"a"},
RegoVersion: &regoV0, RegoVersion: &regoV0,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "a/test1.rego", Path: "a/test1.rego",
@@ -564,7 +564,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"b"}, Roots: &[]string{"b"},
RegoVersion: &regoV1, RegoVersion: &regoV1,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "b/test1.rego", Path: "b/test1.rego",
@@ -590,7 +590,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
Roots: &[]string{"a"}, Roots: &[]string{"a"},
RegoVersion: &regoV1, RegoVersion: &regoV1,
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "a/test1.rego", Path: "a/test1.rego",
@@ -614,7 +614,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
"/test1.rego": 0, "/test1.rego": 0,
}, },
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
// we don't expect this file to get an individual rego-version in the result, as // 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: &regoV0, RegoVersion: &regoV0,
Roots: &[]string{"c"}, Roots: &[]string{"c"},
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
// we don't expect these files to get individual rego-versions in the result, // 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 // as they have the same rego-version as the global rego-version
@@ -677,7 +677,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
"a/*": 1, "a/*": 1,
}, },
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "a/foo/test.rego", Path: "a/foo/test.rego",
@@ -705,7 +705,7 @@ func TestCompilerBundleMergeWithBundleRegoVersion(t *testing.T) {
"*/bar/*": 0, "*/bar/*": 0,
}, },
}, },
Data: map[string]interface{}{}, Data: map[string]any{},
Modules: []bundle.ModuleFile{ Modules: []bundle.ModuleFile{
{ {
Path: "b/foo/test.rego", Path: "b/foo/test.rego",
+4 -4
View File
@@ -10,7 +10,7 @@ import (
) )
// All returns the list of data ast.Refs that the given AST element depends on. // 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) 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 // As an example, if an element depends on data.x and data.x.y, only data.x will
// be in the returned list. // 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) 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 // 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. // 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) 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 // 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. // 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) return v1.Virtual(compiler, x)
} }
+2 -2
View File
@@ -1103,7 +1103,7 @@ if err != nil {
// handle error // handle error
} }
var input interface{} var input any
if err := json.Unmarshal(bs, &input); err != nil { if err := json.Unmarshal(bs, &input); err != nil {
// handle error // handle error
@@ -1157,7 +1157,7 @@ func main() {
} }
// Load the input document from stdin. // Load the input document from stdin.
var input interface{} var input any
dec := json.NewDecoder(os.Stdin) dec := json.NewDecoder(os.Stdin)
dec.UseNumber() dec.UseNumber()
if err := dec.Decode(&input); err != nil { if err := dec.Decode(&input); err != nil {
+5 -5
View File
@@ -695,10 +695,10 @@ type Plugin struct {
manager *plugins.Manager manager *plugins.Manager
config Config config Config
stop chan chan struct{} 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 var parsedConfig Config
if err := util.Unmarshal(config, &parsedConfig); err != nil { if err := util.Unmarshal(config, &parsedConfig); err != nil {
return nil, err return nil, err
@@ -706,12 +706,12 @@ func (p *PluginFactory) Validate(manager *plugins.Manager, config []byte) (inter
return &parsedConfig, nil 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{ return &Plugin{
config: *config.(*Config), config: *config.(*Config),
manager: manager, manager: manager,
stop: make(chan chan struct{}), 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 return
} }
func (p *Plugin) Reconfigure(ctx context.Context, config interface{}) { func (p *Plugin) Reconfigure(ctx context.Context, config any) {
p.reconfig <- config p.reconfig <- config
return return
} }
+3 -3
View File
@@ -250,7 +250,7 @@ func (p *PrintlnLogger) Stop(ctx context.Context) {
p.manager.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateNotReady}) 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() p.mtx.Lock()
defer p.mtx.Unlock() defer p.mtx.Unlock()
p.config = config.(Config) p.config = config.(Config)
@@ -289,7 +289,7 @@ import (
type Factory struct{} 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}) 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{} parsedConfig := Config{}
return parsedConfig, util.Unmarshal(config, &parsedConfig) return parsedConfig, util.Unmarshal(config, &parsedConfig)
} }
+7 -7
View File
@@ -29,13 +29,13 @@ OPA supports different ways to evaluate policies.
* The [REST API](../rest-api) returns decisions as JSON over HTTP. * 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. * 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 * 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.) etc.)
* [WebAssembly](../wasm) compiles Rego policies into Wasm instructions so they can be embedded and evaluated by any WebAssembly runtime * [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 * 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 [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 * 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 ### Integrating with the REST API
@@ -264,7 +264,7 @@ func main() {
defer opa.Stop(ctx) defer opa.Stop(ctx)
// get the named policy decision for the specified input // 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. // handle error.
} else if decision, ok := result.Result.(bool); !ok || !decision { } else if decision, ok := result.Result.(bool); !ok || !decision {
// handle error. // handle error.
@@ -380,12 +380,12 @@ Using the `query` returned by `rego.Rego#PrepareForEval` call the `Eval`
function to evaluate the policy: function to evaluate the policy:
```go ```go
input := map[string]interface{}{ input := map[string]any{
"method": "GET", "method": "GET",
"path": []interface{}{"salary", "bob"}, "path": []any{"salary", "bob"},
"subject": map[string]interface{}{ "subject": map[string]any{
"user": "bob", "user": "bob",
"groups": []interface{}{"sales", "marketing"}, "groups": []any{"sales", "marketing"},
}, },
} }
+1 -1
View File
@@ -18,7 +18,7 @@ func (d *OCIDownloader) WithCallback(f func(context.Context, Update)) *OCIDownlo
panic("built without OCI support") 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") panic("built without OCI support")
} }
+4 -4
View File
@@ -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 // 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 // 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) bs, err := Ast(x)
if err != nil { if err != nil {
panic(err) 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 // 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 // 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) bs, err := AstWithOpts(x, opts)
if err != nil { if err != nil {
panic(err) 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 // 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 // element, Ast returns nil and an error. If AST nodes are missing locations
// an arbitrary location will be used. // an arbitrary location will be used.
func Ast(x interface{}) ([]byte, error) { func Ast(x any) ([]byte, error) {
return AstWithOpts(x, Opts{ return AstWithOpts(x, Opts{
RegoVersion: ast.DefaultRegoVersion, RegoVersion: ast.DefaultRegoVersion,
}) })
} }
func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { func AstWithOpts(x any, opts Opts) ([]byte, error) {
if opts.RegoVersion == ast.RegoUndefined { if opts.RegoVersion == ast.RegoUndefined {
opts.RegoVersion = ast.DefaultRegoVersion opts.RegoVersion = ast.DefaultRegoVersion
} }
+8 -8
View File
@@ -23,12 +23,12 @@ import (
// Info represents information about a bundle. // Info represents information about a bundle.
type Info struct { type Info struct {
Manifest *bundle.Manifest `json:"manifest,omitempty"` Manifest *bundle.Manifest `json:"manifest,omitempty"`
Signatures bundle.SignaturesConfig `json:"signatures_config,omitempty"` Signatures bundle.SignaturesConfig `json:"signatures_config,omitempty"`
WasmModules []map[string]interface{} `json:"wasm_modules,omitempty"` WasmModules []map[string]any `json:"wasm_modules,omitempty"`
Namespaces map[string][]string `json:"namespaces,omitempty"` Namespaces map[string][]string `json:"namespaces,omitempty"`
Annotations []*ast.AnnotationsRef `json:"annotations,omitempty"` Annotations []*ast.AnnotationsRef `json:"annotations,omitempty"`
Required *ast.Capabilities `json:"capabilities,omitempty"` Required *ast.Capabilities `json:"capabilities,omitempty"`
} }
func File(path string, includeAnnotations bool) (*Info, error) { func File(path string, includeAnnotations bool) (*Info, error) {
@@ -103,9 +103,9 @@ func bundleOrDirInfoForRegoVersion(regoVersion ast.RegoVersion, path string, inc
return nil, err 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 { for _, w := range b.WasmModules {
wasmModule := map[string]interface{}{ wasmModule := map[string]any{
"url": w.URL, "url": w.URL,
"path": w.Path, "path": w.Path,
} }
+6 -6
View File
@@ -137,8 +137,8 @@ func TestGenerateBundleInfoWithFile(t *testing.T) {
Roots: &[]string{"a", "b/c"}, Roots: &[]string{"a", "b/c"},
Revision: "123", Revision: "123",
}, },
Data: map[string]interface{}{ Data: map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": []int{4, 5, 6}, "b": []int{4, 5, 6},
}, },
}, },
@@ -217,7 +217,7 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) {
t.Fatalf("Unexpected error: %v", err) t.Fatalf("Unexpected error: %v", err)
} }
metadata := map[string]interface{}{"foo": "bar"} metadata := map[string]any{"foo": "bar"}
wasmResolvers := []bundle.WasmResolver{{ wasmResolvers := []bundle.WasmResolver{{
Entrypoint: "http/example/authz/allow", Entrypoint: "http/example/authz/allow",
Module: "/policy.wasm", Module: "/policy.wasm",
@@ -250,14 +250,14 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) {
t.Fatalf("expected namespaces %v, but got %v", expectedNamespaces, info.Namespaces) t.Fatalf("expected namespaces %v, but got %v", expectedNamespaces, info.Namespaces)
} }
expectedWasmModules := []map[string]interface{}{} expectedWasmModules := []map[string]any{}
expectedWasmModule1 := map[string]interface{}{ expectedWasmModule1 := map[string]any{
"path": "/example/policy.wasm", "path": "/example/policy.wasm",
"url": filepath.Join(bundleFile, "example", "policy.wasm"), "url": filepath.Join(bundleFile, "example", "policy.wasm"),
"entrypoints": []string{"data.http.example.foo.allow"}, "entrypoints": []string{"data.http.example.foo.allow"},
} }
expectedWasmModule2 := map[string]interface{}{ expectedWasmModule2 := map[string]any{
"path": "/policy.wasm", "path": "/policy.wasm",
"url": filepath.Join(bundleFile, "policy.wasm"), "url": filepath.Join(bundleFile, "policy.wasm"),
"entrypoints": []string{"data.http.example.authz.allow"}, "entrypoints": []string{"data.http.example.authz.allow"},
+6 -6
View File
@@ -20,7 +20,7 @@ func main() {
sorted := sortedCaps() sorted := sortedCaps()
sorted = append(sorted, versionedCaps{version: "edge", caps: f}) sorted = append(sorted, versionedCaps{version: "edge", caps: f})
mdata := make(map[string]interface{}) mdata := make(map[string]any)
categories := make(map[string][]string) categories := make(map[string][]string)
for _, bi := range f.Builtins { for _, bi := range f.Builtins {
@@ -29,11 +29,11 @@ func main() {
categories[cat] = append(categories[cat], bi.Name) 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 { for i, typ := range latest.Decl.NamedFuncArgs().Args {
if n, ok := typ.(*types.NamedType); ok { if n, ok := typ.(*types.NamedType); ok {
argTypes[i] = map[string]interface{}{ argTypes[i] = map[string]any{
"name": n.Name, "name": n.Name,
"type": n.Type.String(), "type": n.Type.String(),
} }
@@ -41,12 +41,12 @@ func main() {
argTypes[i]["description"] = n.Descr argTypes[i]["description"] = n.Descr
} }
} else { } else {
argTypes[i] = map[string]interface{}{ argTypes[i] = map[string]any{
"type": typ.String(), "type": typ.String(),
} }
} }
} }
res := map[string]interface{}{} res := map[string]any{}
resType := latest.Decl.NamedResult() resType := latest.Decl.NamedResult()
if n, ok := resType.(*types.NamedType); ok { if n, ok := resType.(*types.NamedType); ok {
res["name"] = n.Name res["name"] = n.Name
@@ -58,7 +58,7 @@ func main() {
res["type"] = resType.String() res["type"] = resType.String()
} }
versions := getVersions(bi.Name, sorted) versions := getVersions(bi.Name, sorted)
md := map[string]interface{}{ md := map[string]any{
"introduced": versions[0], "introduced": versions[0],
"available": versions, "available": versions,
"wasm": getWasm(bi.Name), "wasm": getWasm(bi.Name),
+6 -6
View File
@@ -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 // 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. // specified, the overrides can still be applied to an empty config.
func Load(configFile string, overrides []string, overrideFiles []string) ([]byte, error) { func Load(configFile string, overrides []string, overrideFiles []string) ([]byte, error) {
baseConf := map[string]interface{}{} baseConf := map[string]any{}
// User specified config file // User specified config file
if configFile != "" { 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 // User specified a config override via --set
for _, override := range overrides { 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 // User specified a config override value via --set-file
for _, override := range overrideFiles { for _, override := range overrideFiles {
reader := func(rs []rune) (interface{}, error) { reader := func(rs []rune) (any, error) {
bytes, err := os.ReadFile(string(rs)) bytes, err := os.ReadFile(string(rs))
value := strings.TrimSpace(string(bytes)) value := strings.TrimSpace(string(bytes))
return value, err 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 // 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 { for k, v := range src {
// If the key doesn't exist already, then just set the key to that value // If the key doesn't exist already, then just set the key to that value
if _, exists := dest[k]; !exists { if _, exists := dest[k]; !exists {
dest[k] = v dest[k] = v
continue continue
} }
nextMap, ok := v.(map[string]interface{}) nextMap, ok := v.(map[string]any)
// If it isn't another map, overwrite the value // If it isn't another map, overwrite the value
if !ok { if !ok {
dest[k] = v dest[k] = v
continue continue
} }
// Edge case: If the key exists in the destination, but isn't a map // 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 the source map has a map for this key, prefer it
if !isMap { if !isMap {
dest[k] = v dest[k] = v
+72 -72
View File
@@ -119,17 +119,17 @@ func TestSubEnvVarsVarsSubEmptyVarName(t *testing.T) {
} }
func TestMergeValuesNoOverride(t *testing.T) { func TestMergeValuesNoOverride(t *testing.T) {
dest := map[string]interface{}{} dest := map[string]any{}
src := map[string]interface{}{ src := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": "foo", "b": "foo",
}, },
} }
actual := mergeValues(dest, src) actual := mergeValues(dest, src)
expected := map[string]interface{}{ expected := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": "foo", "b": "foo",
}, },
} }
@@ -140,16 +140,16 @@ func TestMergeValuesNoOverride(t *testing.T) {
} }
func TestMergeValuesOverrideSingle(t *testing.T) { func TestMergeValuesOverrideSingle(t *testing.T) {
dest := map[string]interface{}{ dest := map[string]any{
"a": "bar", "a": "bar",
} }
src := map[string]interface{}{ src := map[string]any{
"a": "override-value", "a": "override-value",
} }
actual := mergeValues(dest, src) actual := mergeValues(dest, src)
expected := map[string]interface{}{ expected := map[string]any{
"a": "override-value", "a": "override-value",
} }
@@ -159,21 +159,21 @@ func TestMergeValuesOverrideSingle(t *testing.T) {
} }
func TestMergeValuesOverrideSingleNested(t *testing.T) { func TestMergeValuesOverrideSingleNested(t *testing.T) {
dest := map[string]interface{}{ dest := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": "foo", "b": "foo",
}, },
} }
src := map[string]interface{}{ src := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": "override-value", "b": "override-value",
}, },
} }
actual := mergeValues(dest, src) actual := mergeValues(dest, src)
expected := map[string]interface{}{ expected := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": "override-value", "b": "override-value",
}, },
} }
@@ -184,9 +184,9 @@ func TestMergeValuesOverrideSingleNested(t *testing.T) {
} }
func TestMergeValuesOverrideMultipleNested(t *testing.T) { func TestMergeValuesOverrideMultipleNested(t *testing.T) {
dest := map[string]interface{}{ dest := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": map[string]interface{}{ "b": map[string]any{
"k1": "v1", "k1": "v1",
"k2": "v2", "k2": "v2",
"k3": "v3", "k3": "v3",
@@ -194,9 +194,9 @@ func TestMergeValuesOverrideMultipleNested(t *testing.T) {
}, },
}, },
} }
src := map[string]interface{}{ src := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": map[string]interface{}{ "b": map[string]any{
"k1": "v1-override", "k1": "v1-override",
"k4": "v4-override", "k4": "v4-override",
}, },
@@ -205,9 +205,9 @@ func TestMergeValuesOverrideMultipleNested(t *testing.T) {
actual := mergeValues(dest, src) actual := mergeValues(dest, src)
expected := map[string]interface{}{ expected := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": map[string]interface{}{ "b": map[string]any{
"k1": "v1-override", "k1": "v1-override",
"k2": "v2", "k2": "v2",
"k3": "v3", "k3": "v3",
@@ -222,9 +222,9 @@ func TestMergeValuesOverrideMultipleNested(t *testing.T) {
} }
func TestMergeValuesOverrideSingleList(t *testing.T) { func TestMergeValuesOverrideSingleList(t *testing.T) {
dest := map[string]interface{}{ dest := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": []map[string]interface{}{ "b": []map[string]any{
{ {
"k1": "v1", "k1": "v1",
"k2": "v2", "k2": "v2",
@@ -232,9 +232,9 @@ func TestMergeValuesOverrideSingleList(t *testing.T) {
}, },
}, },
} }
src := map[string]interface{}{ src := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": []map[string]interface{}{ "b": []map[string]any{
{ {
"k3": "v3", "k3": "v3",
}, },
@@ -245,9 +245,9 @@ func TestMergeValuesOverrideSingleList(t *testing.T) {
actual := mergeValues(dest, src) actual := mergeValues(dest, src)
// The list index 0 should have been replaced instead of merging the sub objects // The list index 0 should have been replaced instead of merging the sub objects
expected := map[string]interface{}{ expected := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": []map[string]interface{}{ "b": []map[string]any{
{ {
"k3": "v3", "k3": "v3",
}, },
@@ -261,17 +261,17 @@ func TestMergeValuesOverrideSingleList(t *testing.T) {
} }
func TestMergeValuesNoSrc(t *testing.T) { func TestMergeValuesNoSrc(t *testing.T) {
dest := map[string]interface{}{ dest := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": "foo", "b": "foo",
}, },
} }
src := map[string]interface{}{} src := map[string]any{}
actual := mergeValues(dest, src) actual := mergeValues(dest, src)
expected := map[string]interface{}{ expected := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": "foo", "b": "foo",
}, },
} }
@@ -282,12 +282,12 @@ func TestMergeValuesNoSrc(t *testing.T) {
} }
func TestMergeValuesNoSrcOrDest(t *testing.T) { func TestMergeValuesNoSrcOrDest(t *testing.T) {
dest := map[string]interface{}{} dest := map[string]any{}
src := map[string]interface{}{} src := map[string]any{}
actual := mergeValues(dest, src) actual := mergeValues(dest, src)
expected := map[string]interface{}{} expected := map[string]any{}
if !reflect.DeepEqual(actual, expected) { if !reflect.DeepEqual(actual, expected) {
t.Errorf("merged map does not match expected:\n\nExpected: %+v\nActual: %+v", expected, actual) 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()) t.Errorf("unexpected error loading config: %s", err.Error())
} }
config := map[string]interface{}{} config := map[string]any{}
err = yaml.Unmarshal(configBytes, &config) err = yaml.Unmarshal(configBytes, &config)
if err != nil { if err != nil {
t.Errorf("unexpected error unmarshalling config") t.Errorf("unexpected error unmarshalling config")
} }
expected := map[string]interface{}{ expected := map[string]any{
"services": map[string]interface{}{ "services": map[string]any{
"acmecorp": map[string]interface{}{ "acmecorp": map[string]any{
"url": "https://example.com/control-plane-api/v1", "url": "https://example.com/control-plane-api/v1",
"credentials": map[string]interface{}{ "credentials": map[string]any{
"bearer": map[string]interface{}{ "bearer": map[string]any{
"token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm", "token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm",
}, },
}, },
}, },
}, },
"discovery": map[string]interface{}{ "discovery": map[string]any{
"name": "/example/discovery", "name": "/example/discovery",
"prefix": "configuration", "prefix": "configuration",
}, },
@@ -370,24 +370,24 @@ discovery:
t.Errorf("unexpected error loading config: %s", err.Error()) t.Errorf("unexpected error loading config: %s", err.Error())
} }
config := map[string]interface{}{} config := map[string]any{}
err = yaml.Unmarshal(configBytes, &config) err = yaml.Unmarshal(configBytes, &config)
if err != nil { if err != nil {
t.Errorf("unexpected error unmarshalling config") t.Errorf("unexpected error unmarshalling config")
} }
expected := map[string]interface{}{ expected := map[string]any{
"services": map[string]interface{}{ "services": map[string]any{
"acmecorp": map[string]interface{}{ "acmecorp": map[string]any{
"url": "https://example.com/control-plane-api/v1", "url": "https://example.com/control-plane-api/v1",
"credentials": map[string]interface{}{ "credentials": map[string]any{
"bearer": map[string]interface{}{ "bearer": map[string]any{
"token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm", "token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm",
}, },
}, },
}, },
}, },
"discovery": map[string]interface{}{ "discovery": map[string]any{
"name": "/example/discovery", "name": "/example/discovery",
"prefix": "configuration", "prefix": "configuration",
}, },
@@ -412,24 +412,24 @@ func TestLoadConfigWithParamOverrideNoConfigFile(t *testing.T) {
t.Errorf("unexpected error loading config: %s", err.Error()) t.Errorf("unexpected error loading config: %s", err.Error())
} }
config := map[string]interface{}{} config := map[string]any{}
err = yaml.Unmarshal(configBytes, &config) err = yaml.Unmarshal(configBytes, &config)
if err != nil { if err != nil {
t.Errorf("unexpected error unmarshalling config") t.Errorf("unexpected error unmarshalling config")
} }
expected := map[string]interface{}{ expected := map[string]any{
"services": map[string]interface{}{ "services": map[string]any{
"acmecorp": map[string]interface{}{ "acmecorp": map[string]any{
"url": "https://example.com/control-plane-api/v1", "url": "https://example.com/control-plane-api/v1",
"credentials": map[string]interface{}{ "credentials": map[string]any{
"bearer": map[string]interface{}{ "bearer": map[string]any{
"token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm", "token": "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm",
}, },
}, },
}, },
}, },
"discovery": map[string]interface{}{ "discovery": map[string]any{
"name": "/example/discovery", "name": "/example/discovery",
"prefix": "configuration", "prefix": "configuration",
}, },
@@ -454,29 +454,29 @@ func TestLoadConfigWithParamOverrideNoConfigFileWithEmptyObject(t *testing.T) {
t.Errorf("unexpected error loading config: %s", err.Error()) t.Errorf("unexpected error loading config: %s", err.Error())
} }
config := map[string]interface{}{} config := map[string]any{}
err = yaml.Unmarshal(configBytes, &config) err = yaml.Unmarshal(configBytes, &config)
if err != nil { if err != nil {
t.Errorf("unexpected error unmarshalling config") t.Errorf("unexpected error unmarshalling config")
} }
expected := map[string]interface{}{ expected := map[string]any{
"services": map[string]interface{}{ "services": map[string]any{
"acmecorp": map[string]interface{}{ "acmecorp": map[string]any{
"url": "https://example.com/control-plane-api/v1", "url": "https://example.com/control-plane-api/v1",
"headers": map[string]interface{}{}, "headers": map[string]any{},
"credentials": map[string]interface{}{ "credentials": map[string]any{
"s3_signing": map[string]interface{}{ "s3_signing": map[string]any{
"environment_credentials": map[string]interface{}{}, "environment_credentials": map[string]any{},
}, },
}, },
}, },
}, },
"decision_logs": map[string]interface{}{ "decision_logs": map[string]any{
"plugin": "my_plugin", "plugin": "my_plugin",
}, },
"plugins": map[string]interface{}{ "plugins": map[string]any{
"my_plugin": map[string]interface{}{}, "my_plugin": map[string]any{},
}, },
} }
+1 -1
View File
@@ -8,7 +8,7 @@ import (
// Debug allows printing debug messages. // Debug allows printing debug messages.
type Debug interface { type Debug interface {
// Printf prints, with a short file:line-number prefix // 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 // Writer returns the writer being written to, which may be
// `io.Discard` if no debug output is requested. // `io.Discard` if no debug output is requested.
Writer() io.Writer Writer() io.Writer
+8 -8
View File
@@ -5,25 +5,25 @@
package deepcopy package deepcopy
// DeepCopy performs a recursive deep copy for nested slices/maps and // DeepCopy performs a recursive deep copy for nested slices/maps and
// returns the copied object. Supports []interface{} // returns the copied object. Supports []any
// and map[string]interface{} only // and map[string]any only
func DeepCopy(val interface{}) interface{} { func DeepCopy(val any) any {
switch val := val.(type) { switch val := val.(type) {
case []interface{}: case []any:
cpy := make([]interface{}, len(val)) cpy := make([]any, len(val))
for i := range cpy { for i := range cpy {
cpy[i] = DeepCopy(val[i]) cpy[i] = DeepCopy(val[i])
} }
return cpy return cpy
case map[string]interface{}: case map[string]any:
return Map(val) return Map(val)
default: default:
return val return val
} }
} }
func Map(val map[string]interface{}) map[string]interface{} { func Map(val map[string]any) map[string]any {
cpy := make(map[string]interface{}, len(val)) cpy := make(map[string]any, len(val))
for k := range val { for k := range val {
cpy[k] = DeepCopy(val[k]) cpy[k] = DeepCopy(val[k])
} }
+4 -4
View File
@@ -10,9 +10,9 @@ import (
) )
func TestDeepCopyMapRoot(t *testing.T) { func TestDeepCopyMapRoot(t *testing.T) {
target := map[string]interface{}{ target := map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"b": []interface{}{ "b": []any{
"c", "c",
"d", "d",
}, },
@@ -20,7 +20,7 @@ func TestDeepCopyMapRoot(t *testing.T) {
}, },
"x": "y", "x": "y",
} }
result := DeepCopy(target).(map[string]interface{}) result := DeepCopy(target).(map[string]any)
if !reflect.DeepEqual(target, result) { if !reflect.DeepEqual(target, result) {
t.Fatal("Expected result of DeepCopy to be DeepEqual with original.") t.Fatal("Expected result of DeepCopy to be DeepEqual with original.")
} }
@@ -394,18 +394,18 @@ func (s *sink) Enabled(level int) bool {
func (*sink) Init(logr.RuntimeInfo) {} // ignored 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) s.logger.Info(msg)
} }
func (s *sink) Error(err error, msg string, _ ...interface{}) { func (s *sink) Error(err error, msg string, _ ...any) {
s.logger.WithFields(map[string]interface{}{"err": err}).Error(msg) s.logger.WithFields(map[string]any{"err": err}).Error(msg)
} }
func (s *sink) WithName(name string) logr.LogSink { 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 return s
} }
+2 -2
View File
@@ -86,12 +86,12 @@ func (dc draftConfigs) GetSchemaURL(draft Draft) string {
return "" return ""
} }
func parseSchemaURL(documentNode interface{}) (string, *Draft, error) { func parseSchemaURL(documentNode any) (string, *Draft, error) {
if _, ok := documentNode.(bool); ok { if _, ok := documentNode.(bool); ok {
return "", nil, nil return "", nil, nil
} }
m, ok := documentNode.(map[string]interface{}) m, ok := documentNode.(map[string]any)
if !ok { if !ok {
return "", nil, errors.New("schema is invalid") return "", nil, errors.New("schema is invalid")
} }
+1 -1
View File
@@ -212,7 +212,7 @@ type (
) )
// newError takes a ResultError type and sets the type, context, description, details, value, and field // 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 t string
var d string var d string
switch err.(type) { switch err.(type) {
+16 -16
View File
@@ -14,7 +14,7 @@ type (
// FormatChecker is the interface all formatters added to FormatCheckerChain must implement // FormatChecker is the interface all formatters added to FormatCheckerChain must implement
FormatChecker interface { FormatChecker interface {
// IsFormat checks if input has the correct format // IsFormat checks if input has the correct format
IsFormat(input interface{}) bool IsFormat(input any) bool
} }
// FormatCheckerChain holds the formatters // 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 // IsFormat will check an input against a FormatChecker with the given name
// to see if it is the correct format // 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() lock.RLock()
f, ok := c.formatters[name] f, ok := c.formatters[name]
lock.RUnlock() 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 // 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) asString, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -199,7 +199,7 @@ func (f EmailFormatChecker) IsFormat(input interface{}) bool {
} }
// IsFormat checks if input is a correctly formatted IPv4-address // 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) asString, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -211,7 +211,7 @@ func (f IPV4FormatChecker) IsFormat(input interface{}) bool {
} }
// IsFormat checks if input is a correctly formatted IPv6=address // 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) asString, ok := input.(string)
if !ok { if !ok {
return true 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 // 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) asString, ok := input.(string)
if !ok { if !ok {
return true 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) // 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) asString, ok := input.(string)
if !ok { if !ok {
return true 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) // 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) asString, ok := input.(string)
if !ok { if !ok {
return true 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 // 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) asString, ok := input.(string)
if !ok { if !ok {
return true 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 // 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) asString, ok := input.(string)
if !ok { if !ok {
return true 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 // 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) asString, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -314,7 +314,7 @@ func (f URITemplateFormatChecker) IsFormat(input interface{}) bool {
} }
// IsFormat checks if input is a correctly formatted hostname // 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) asString, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -324,7 +324,7 @@ func (f HostnameFormatChecker) IsFormat(input interface{}) bool {
} }
// IsFormat checks if input is a correctly formatted UUID // 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) asString, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -334,7 +334,7 @@ func (f UUIDFormatChecker) IsFormat(input interface{}) bool {
} }
// IsFormat checks if input is a correctly formatted regular expression // 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) asString, ok := input.(string)
if !ok { if !ok {
return true 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 // 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) asString, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -358,7 +358,7 @@ func (f JSONPointerFormatChecker) IsFormat(input interface{}) bool {
} }
// IsFormat checks if input is a correctly formatted relative JSON Pointer // 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) asString, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -58,8 +58,8 @@ const formatSchema = `{
type arrayChecker struct{} type arrayChecker struct{}
func (c arrayChecker) IsFormat(input interface{}) bool { func (c arrayChecker) IsFormat(input any) bool {
arr, ok := input.([]interface{}) arr, ok := input.([]any)
if !ok { if !ok {
return true return true
} }
@@ -73,7 +73,7 @@ func (c arrayChecker) IsFormat(input interface{}) bool {
type boolChecker struct{} type boolChecker struct{}
func (c boolChecker) IsFormat(input interface{}) bool { func (c boolChecker) IsFormat(input any) bool {
b, ok := input.(bool) b, ok := input.(bool)
if !ok { if !ok {
return true return true
@@ -83,7 +83,7 @@ func (c boolChecker) IsFormat(input interface{}) bool {
type integerChecker struct{} type integerChecker struct{}
func (c integerChecker) IsFormat(input interface{}) bool { func (c integerChecker) IsFormat(input any) bool {
number, ok := input.(json.Number) number, ok := input.(json.Number)
if !ok { if !ok {
return true return true
@@ -94,8 +94,8 @@ func (c integerChecker) IsFormat(input interface{}) bool {
type objectChecker struct{} type objectChecker struct{}
func (c objectChecker) IsFormat(input interface{}) bool { func (c objectChecker) IsFormat(input any) bool {
obj, ok := input.(map[string]interface{}) obj, ok := input.(map[string]any)
if !ok { if !ok {
return true return true
} }
@@ -104,7 +104,7 @@ func (c objectChecker) IsFormat(input interface{}) bool {
type stringChecker struct{} type stringChecker struct{}
func (c stringChecker) IsFormat(input interface{}) bool { func (c stringChecker) IsFormat(input any) bool {
str, ok := input.(string) str, ok := input.(string)
if !ok { if !ok {
return true return true
@@ -121,7 +121,7 @@ func TestCustomFormat(t *testing.T) {
Add("StringChecker", stringChecker{}) Add("StringChecker", stringChecker{})
sl := NewStringLoader(formatSchema) sl := NewStringLoader(formatSchema)
validResult, err := Validate(sl, NewGoLoader(map[string]interface{}{ validResult, err := Validate(sl, NewGoLoader(map[string]any{
"arr": []string{"x", "y", "z"}, "arr": []string{"x", "y", "z"},
"bool": true, "bool": true,
"int": "2", // format not defined for string "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"}, "arr": []string{"a", "b", "c"},
"bool": false, "bool": false,
"int": 1, "int": 1,
+1 -1
View File
@@ -32,6 +32,6 @@ import (
const internalLogEnabled = false const internalLogEnabled = false
func internalLog(format string, v ...interface{}) { func internalLog(format string, v ...any) {
log.Printf(format, v...) log.Printf(format, v...)
} }
+24 -24
View File
@@ -77,8 +77,8 @@ var osFS = osFileSystem(os.Open)
// JSONLoader defines the JSON loader interface // JSONLoader defines the JSON loader interface
type JSONLoader interface { type JSONLoader interface {
JSONSource() interface{} JSONSource() any
LoadJSON() (interface{}, error) LoadJSON() (any, error)
JSONReference() (gojsonreference.JsonReference, error) JSONReference() (gojsonreference.JsonReference, error)
LoaderFactory() JSONLoaderFactory LoaderFactory() JSONLoaderFactory
} }
@@ -130,7 +130,7 @@ type jsonReferenceLoader struct {
source string source string
} }
func (l *jsonReferenceLoader) JSONSource() interface{} { func (l *jsonReferenceLoader) JSONSource() any {
return l.source 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 var err error
@@ -207,7 +207,7 @@ func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) {
return nil, fmt.Errorf("remote reference loading disabled: %s", reference.String()) 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) resp, err := http.Get(address)
if err != nil { if err != nil {
@@ -227,7 +227,7 @@ func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error)
return decodeJSONUsingNumber(bytes.NewReader(bodyBuff)) 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) f, err := l.fs.Open(path)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -249,7 +249,7 @@ type jsonStringLoader struct {
source string source string
} }
func (l *jsonStringLoader) JSONSource() interface{} { func (l *jsonStringLoader) JSONSource() any {
return l.source return l.source
} }
@@ -266,7 +266,7 @@ func NewStringLoader(source string) JSONLoader {
return &jsonStringLoader{source: source} return &jsonStringLoader{source: source}
} }
func (l *jsonStringLoader) LoadJSON() (interface{}, error) { func (l *jsonStringLoader) LoadJSON() (any, error) {
return decodeJSONUsingNumber(strings.NewReader(l.JSONSource().(string))) return decodeJSONUsingNumber(strings.NewReader(l.JSONSource().(string)))
@@ -278,7 +278,7 @@ type jsonBytesLoader struct {
source []byte source []byte
} }
func (l *jsonBytesLoader) JSONSource() interface{} { func (l *jsonBytesLoader) JSONSource() any {
return l.source return l.source
} }
@@ -295,18 +295,18 @@ func NewBytesLoader(source []byte) JSONLoader {
return &jsonBytesLoader{source: source} return &jsonBytesLoader{source: source}
} }
func (l *jsonBytesLoader) LoadJSON() (interface{}, error) { func (l *jsonBytesLoader) LoadJSON() (any, error) {
return decodeJSONUsingNumber(bytes.NewReader(l.JSONSource().([]byte))) return decodeJSONUsingNumber(bytes.NewReader(l.JSONSource().([]byte)))
} }
// JSON Go (types) loader // 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 { type jsonGoLoader struct {
source interface{} source any
} }
func (l *jsonGoLoader) JSONSource() interface{} { func (l *jsonGoLoader) JSONSource() any {
return l.source return l.source
} }
@@ -319,11 +319,11 @@ func (l *jsonGoLoader) LoaderFactory() JSONLoaderFactory {
} }
// NewGoLoader creates a new JSONLoader from a given Go struct // NewGoLoader creates a new JSONLoader from a given Go struct
func NewGoLoader(source interface{}) JSONLoader { func NewGoLoader(source any) JSONLoader {
return &jsonGoLoader{source: source} 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" // 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) return &jsonIOLoader{buf: buf}, io.MultiWriter(source, buf)
} }
func (l *jsonIOLoader) JSONSource() interface{} { func (l *jsonIOLoader) JSONSource() any {
return l.buf.String() return l.buf.String()
} }
func (l *jsonIOLoader) LoadJSON() (interface{}, error) { func (l *jsonIOLoader) LoadJSON() (any, error) {
return decodeJSONUsingNumber(l.buf) return decodeJSONUsingNumber(l.buf)
} }
@@ -369,21 +369,21 @@ func (l *jsonIOLoader) LoaderFactory() JSONLoaderFactory {
} }
// JSON raw loader // 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 // 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 // "properly" by using https://golang.org/pkg/encoding/json/#Decoder.UseNumber
type jsonRawLoader struct { type jsonRawLoader struct {
source interface{} source any
} }
// NewRawLoader creates a new JSON raw loader for the given source // 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} return &jsonRawLoader{source: source}
} }
func (l *jsonRawLoader) JSONSource() interface{} { func (l *jsonRawLoader) JSONSource() any {
return l.source return l.source
} }
func (l *jsonRawLoader) LoadJSON() (interface{}, error) { func (l *jsonRawLoader) LoadJSON() (any, error) {
return l.source, nil return l.source, nil
} }
func (l *jsonRawLoader) JSONReference() (gojsonreference.JsonReference, error) { func (l *jsonRawLoader) JSONReference() (gojsonreference.JsonReference, error) {
@@ -393,9 +393,9 @@ func (l *jsonRawLoader) LoaderFactory() JSONLoaderFactory {
return &DefaultJSONLoaderFactory{} 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 := json.NewDecoder(r)
decoder.UseNumber() decoder.UseNumber()
+4 -4
View File
@@ -30,13 +30,13 @@ type jsonSchemaTest struct {
// Some tests may not always pass, so some tests are manually edited to include // 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 // an extra attribute whether that specific test should be disabled and skipped
Disabled bool `json:"disabled"` Disabled bool `json:"disabled"`
Schema interface{} `json:"schema"` Schema any `json:"schema"`
Tests []jsonSchemaTestCase `json:"tests"` Tests []jsonSchemaTestCase `json:"tests"`
} }
type jsonSchemaTestCase struct { type jsonSchemaTestCase struct {
Description string `json:"description"` Description string `json:"description"`
Data interface{} `json:"data"` Data any `json:"data"`
Valid bool `json:"valid"` Valid bool `json:"valid"`
} }
// Skip any directories not named appropiately // Skip any directories not named appropiately
+7 -7
View File
@@ -33,7 +33,7 @@ import (
type ( type (
// ErrorDetails is a map of details specific to each error. // ErrorDetails is a map of details specific to each error.
// While the values will vary, every error will contain a "field" value // 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 is the interface that library errors must implement
ResultError interface { ResultError interface {
@@ -57,9 +57,9 @@ type (
// DescriptionFormat returns the format for the description in the default text/template format // DescriptionFormat returns the format for the description in the default text/template format
DescriptionFormat() string DescriptionFormat() string
// SetValue sets the value related to the error // SetValue sets the value related to the error
SetValue(interface{}) SetValue(any)
// Value returns the value related to the error // Value returns the value related to the error
Value() interface{} Value() any
// SetDetails sets the details specific to the error // SetDetails sets the details specific to the error
SetDetails(ErrorDetails) SetDetails(ErrorDetails)
// Details returns details about the error // 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 ... context *JSONContext // Tree like notation of the part that failed the validation. ex (root).a.b ...
description string // A human readable error message description string // A human readable error message
descriptionFormat string // A format for 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 details ErrorDetails
} }
@@ -136,12 +136,12 @@ func (v *ResultErrorFields) DescriptionFormat() string {
} }
// SetValue sets the value related to the error // SetValue sets the value related to the error
func (v *ResultErrorFields) SetValue(value interface{}) { func (v *ResultErrorFields) SetValue(value any) {
v.value = value v.value = value
} }
// Value returns the value related to the error // Value returns the value related to the error
func (v *ResultErrorFields) Value() interface{} { func (v *ResultErrorFields) Value() any {
return v.value return v.value
} }
@@ -203,7 +203,7 @@ func (v *Result) AddError(err ResultError, details ErrorDetails) {
v.errors = append(v.errors, err) 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) newError(err, context, value, Locale, details)
v.errors = append(v.errors, err) 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 v.score -= 2 // results in a net -1 when added to the +1 we get at the end of the validation function
+31 -31
View File
@@ -58,7 +58,7 @@ type Schema struct {
ReferencePool *schemaReferencePool 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} d.RootSchema = &SubSchema{Property: StringRootSchemaProperty, Draft: &draft}
return d.parseSchema(document, d.RootSchema) 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 // 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, // 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 // 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.Draft == nil {
if currentSchema.Parent == 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 { if !isMap {
return errors.New(formatErrorDescription( return errors.New(formatErrorDescription(
Locale.ParseError(), Locale.ParseError(),
@@ -146,10 +146,10 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
// definitions // definitions
if v, ok := m[KeyDefinitions]; ok { if v, ok := m[KeyDefinitions]; ok {
switch mt := v.(type) { switch mt := v.(type) {
case map[string]interface{}: case map[string]any:
for _, dv := range mt { for _, dv := range mt {
switch dv.(type) { switch dv.(type) {
case bool, map[string]interface{}: case bool, map[string]any:
newSchema := &SubSchema{Property: KeyDefinitions, Parent: currentSchema} newSchema := &SubSchema{Property: KeyDefinitions, Parent: currentSchema}
err := d.parseSchema(dv, newSchema) err := d.parseSchema(dv, newSchema)
if err != nil { if err != nil {
@@ -203,7 +203,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
if err != nil { if err != nil {
return err return err
} }
case []interface{}: case []any:
for _, typeInArray := range t { for _, typeInArray := range t {
s, isString := typeInArray.(string) s, isString := typeInArray.(string)
if !isString { if !isString {
@@ -231,7 +231,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
switch v := additionalProperties.(type) { switch v := additionalProperties.(type) {
case bool: case bool:
currentSchema.additionalProperties = v currentSchema.additionalProperties = v
case map[string]interface{}: case map[string]any:
newSchema := &SubSchema{Property: KeyAdditionalProperties, Parent: currentSchema, Ref: currentSchema.Ref} newSchema := &SubSchema{Property: KeyAdditionalProperties, Parent: currentSchema, Ref: currentSchema.Ref}
currentSchema.additionalProperties = newSchema currentSchema.additionalProperties = newSchema
err := d.parseSchema(v, newSchema) err := d.parseSchema(v, newSchema)
@@ -270,7 +270,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
// propertyNames // propertyNames
if propertyNames, found := m[KeyPropertyNames]; found && *currentSchema.Draft >= Draft6 { if propertyNames, found := m[KeyPropertyNames]; found && *currentSchema.Draft >= Draft6 {
switch propertyNames.(type) { switch propertyNames.(type) {
case bool, map[string]interface{}: case bool, map[string]any:
newSchema := &SubSchema{Property: KeyPropertyNames, Parent: currentSchema, Ref: currentSchema.Ref} newSchema := &SubSchema{Property: KeyPropertyNames, Parent: currentSchema, Ref: currentSchema.Ref}
currentSchema.propertyNames = newSchema currentSchema.propertyNames = newSchema
err := d.parseSchema(propertyNames, newSchema) err := d.parseSchema(propertyNames, newSchema)
@@ -299,10 +299,10 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
// items // items
if items, found := m[KeyItems]; found { if items, found := m[KeyItems]; found {
switch i := items.(type) { switch i := items.(type) {
case []interface{}: case []any:
for _, itemElement := range i { for _, itemElement := range i {
switch itemElement.(type) { switch itemElement.(type) {
case map[string]interface{}, bool: case map[string]any, bool:
newSchema := &SubSchema{Parent: currentSchema, Property: KeyItems} newSchema := &SubSchema{Parent: currentSchema, Property: KeyItems}
newSchema.Ref = currentSchema.Ref newSchema.Ref = currentSchema.Ref
currentSchema.ItemsChildren = append(currentSchema.ItemsChildren, newSchema) currentSchema.ItemsChildren = append(currentSchema.ItemsChildren, newSchema)
@@ -315,7 +315,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
} }
currentSchema.ItemsChildrenIsSingleSchema = false currentSchema.ItemsChildrenIsSingleSchema = false
} }
case map[string]interface{}, bool: case map[string]any, bool:
newSchema := &SubSchema{Parent: currentSchema, Property: KeyItems} newSchema := &SubSchema{Parent: currentSchema, Property: KeyItems}
newSchema.Ref = currentSchema.Ref newSchema.Ref = currentSchema.Ref
currentSchema.ItemsChildren = append(currentSchema.ItemsChildren, newSchema) currentSchema.ItemsChildren = append(currentSchema.ItemsChildren, newSchema)
@@ -334,7 +334,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
switch i := additionalItems.(type) { switch i := additionalItems.(type) {
case bool: case bool:
currentSchema.additionalItems = i currentSchema.additionalItems = i
case map[string]interface{}: case map[string]any:
newSchema := &SubSchema{Property: KeyAdditionalItems, Parent: currentSchema, Ref: currentSchema.Ref} newSchema := &SubSchema{Property: KeyAdditionalItems, Parent: currentSchema, Ref: currentSchema.Ref}
currentSchema.additionalItems = newSchema currentSchema.additionalItems = newSchema
err := d.parseSchema(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 { if vNot, found := m[KeyNot]; found {
switch vNot.(type) { switch vNot.(type) {
case bool, map[string]interface{}: case bool, map[string]any:
newSchema := &SubSchema{Property: KeyNot, Parent: currentSchema, Ref: currentSchema.Ref} newSchema := &SubSchema{Property: KeyNot, Parent: currentSchema, Ref: currentSchema.Ref}
currentSchema.not = newSchema currentSchema.not = newSchema
err := d.parseSchema(vNot, newSchema) err := d.parseSchema(vNot, newSchema)
@@ -735,7 +735,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
if *currentSchema.Draft >= Draft7 { if *currentSchema.Draft >= Draft7 {
if vIf, found := m[KeyIf]; found { if vIf, found := m[KeyIf]; found {
switch vIf.(type) { switch vIf.(type) {
case bool, map[string]interface{}: case bool, map[string]any:
newSchema := &SubSchema{Property: KeyIf, Parent: currentSchema, Ref: currentSchema.Ref} newSchema := &SubSchema{Property: KeyIf, Parent: currentSchema, Ref: currentSchema.Ref}
currentSchema._if = newSchema currentSchema._if = newSchema
err := d.parseSchema(vIf, newSchema) err := d.parseSchema(vIf, newSchema)
@@ -752,7 +752,7 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
if then, found := m[KeyThen]; found { if then, found := m[KeyThen]; found {
switch then.(type) { switch then.(type) {
case bool, map[string]interface{}: case bool, map[string]any:
newSchema := &SubSchema{Property: KeyThen, Parent: currentSchema, Ref: currentSchema.Ref} newSchema := &SubSchema{Property: KeyThen, Parent: currentSchema, Ref: currentSchema.Ref}
currentSchema._then = newSchema currentSchema._then = newSchema
err := d.parseSchema(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 { if vElse, found := m[KeyElse]; found {
switch vElse.(type) { switch vElse.(type) {
case bool, map[string]interface{}: case bool, map[string]any:
newSchema := &SubSchema{Property: KeyElse, Parent: currentSchema, Ref: currentSchema.Ref} newSchema := &SubSchema{Property: KeyElse, Parent: currentSchema, Ref: currentSchema.Ref}
currentSchema._else = newSchema currentSchema._else = newSchema
err := d.parseSchema(vElse, newSchema) err := d.parseSchema(vElse, newSchema)
@@ -788,9 +788,9 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *SubSchema)
return nil return nil
} }
func (d *Schema) parseReference(_ interface{}, currentSchema *SubSchema) error { func (d *Schema) parseReference(_ any, currentSchema *SubSchema) error {
var ( var (
refdDocumentNode interface{} refdDocumentNode any
dsp *schemaPoolDocument dsp *schemaPoolDocument
err error err error
) )
@@ -809,7 +809,7 @@ func (d *Schema) parseReference(_ interface{}, currentSchema *SubSchema) error {
newSchema.Draft = dsp.Draft newSchema.Draft = dsp.Draft
switch refdDocumentNode.(type) { switch refdDocumentNode.(type) {
case bool, map[string]interface{}: case bool, map[string]any:
// expected // expected
default: default:
return errors.New(formatErrorDescription( 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 { func (d *Schema) parseProperties(documentNode any, currentSchema *SubSchema) error {
m, isMap := documentNode.(map[string]interface{}) m, isMap := documentNode.(map[string]any)
if !isMap { if !isMap {
return errors.New(formatErrorDescription( return errors.New(formatErrorDescription(
Locale.MustBeOfType(), Locale.MustBeOfType(),
@@ -851,19 +851,19 @@ func (d *Schema) parseProperties(documentNode interface{}, currentSchema *SubSch
return nil return nil
} }
func (d *Schema) parseDependencies(documentNode interface{}, currentSchema *SubSchema) error { func (d *Schema) parseDependencies(documentNode any, currentSchema *SubSchema) error {
m, isMap := documentNode.(map[string]interface{}) m, isMap := documentNode.(map[string]any)
if !isMap { if !isMap {
return errors.New(formatErrorDescription( return errors.New(formatErrorDescription(
Locale.MustBeOfType(), Locale.MustBeOfType(),
ErrorDetails{"key": KeyDependencies, "type": TypeObject}, ErrorDetails{"key": KeyDependencies, "type": TypeObject},
)) ))
} }
currentSchema.dependencies = make(map[string]interface{}) currentSchema.dependencies = make(map[string]any)
for k := range m { for k := range m {
switch values := m[k].(type) { switch values := m[k].(type) {
case []interface{}: case []any:
var valuesToRegister []string var valuesToRegister []string
for _, value := range values { for _, value := range values {
str, isString := value.(string) str, isString := value.(string)
@@ -880,7 +880,7 @@ func (d *Schema) parseDependencies(documentNode interface{}, currentSchema *SubS
currentSchema.dependencies[k] = valuesToRegister currentSchema.dependencies[k] = valuesToRegister
} }
case bool, map[string]interface{}: case bool, map[string]any:
depSchema := &SubSchema{Property: k, Parent: currentSchema, Ref: currentSchema.Ref} depSchema := &SubSchema{Property: k, Parent: currentSchema, Ref: currentSchema.Ref}
err := d.parseSchema(m[k], depSchema) err := d.parseSchema(m[k], depSchema)
if err != nil { 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] v, found := m[key]
if !found { if !found {
// not found // not found
@@ -927,13 +927,13 @@ func getString(m map[string]interface{}, key string) (*string, error) {
return &s, nil 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] v, found := m[key]
if !found { if !found {
// not found // not found
return nil, nil return nil, nil
} }
s, isMap := v.(map[string]interface{}) s, isMap := v.(map[string]any)
if !isMap { if !isMap {
// wrong type // wrong type
return nil, invalidType(StringSchema, key) return nil, invalidType(StringSchema, key)
@@ -941,12 +941,12 @@ func getMap(m map[string]interface{}, key string) (map[string]interface{}, error
return s, nil 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] v, found := m[key]
if !found { if !found {
return nil, nil return nil, nil
} }
s, isArray := v.([]interface{}) s, isArray := v.([]any)
if !isArray { if !isArray {
return nil, errors.New(formatErrorDescription( return nil, errors.New(formatErrorDescription(
Locale.MustBeOfAn(), Locale.MustBeOfAn(),
+2 -2
View File
@@ -45,7 +45,7 @@ func NewSchemaLoader() *SchemaLoader {
return ps return ps
} }
func (sl *SchemaLoader) validateMetaschema(documentNode interface{}) error { func (sl *SchemaLoader) validateMetaschema(documentNode any) error {
var ( var (
schema string schema string
@@ -158,7 +158,7 @@ func (sl *SchemaLoader) Compile(rootSchema JSONLoader) (*Schema, error) {
d.DocumentReference = ref d.DocumentReference = ref
d.ReferencePool = newSchemaReferencePool() d.ReferencePool = newSchemaReferencePool()
var doc interface{} var doc any
if ref.String() != "" { if ref.String() != "" {
// Get document from schema pool // Get document from schema pool
spd, err := d.Pool.GetDocument(d.DocumentReference) spd, err := d.Pool.GetDocument(d.DocumentReference)
+6 -6
View File
@@ -34,7 +34,7 @@ import (
) )
type schemaPoolDocument struct { type schemaPoolDocument struct {
Document interface{} Document any
Draft *Draft Draft *Draft
} }
@@ -44,7 +44,7 @@ type schemaPool struct {
autoDetect *bool 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 ( var (
draft *Draft draft *Draft
@@ -72,7 +72,7 @@ func (p *schemaPool) parseReferences(document interface{}, ref gojsonreference.J
return err 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. // 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 // For $ref references it takes into account the $id scope it is in and replaces
// the reference by the absolute resolved reference // 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 // 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. // is syntactically parsed and any error encountered here should also come up there.
switch m := document.(type) { switch m := document.(type) {
case []interface{}: case []any:
for _, v := range m { for _, v := range m {
err := p.parseReferencesRecursive(v, ref, draft) err := p.parseReferencesRecursive(v, ref, draft)
if err != nil { if err != nil {
return err return err
} }
} }
case map[string]interface{}: case map[string]any:
localRef := &ref localRef := &ref
keyID := KeyIDNew 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 // 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. // Therefore don't treat it like a schema.
if k == KeyProperties || k == KeyDependencies || k == KeyPatternProperties { 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 { for _, v := range child {
err := p.parseReferencesRecursive(v, *localRef, draft) err := p.parseReferencesRecursive(v, *localRef, draft)
if err != nil { if err != nil {
+3 -3
View File
@@ -123,8 +123,8 @@ type SubSchema struct {
maxProperties *int maxProperties *int
required []string required []string
dependencies map[string]interface{} dependencies map[string]any
additionalProperties interface{} additionalProperties any
patternProperties map[string]*SubSchema patternProperties map[string]*SubSchema
propertyNames *SubSchema propertyNames *SubSchema
@@ -134,7 +134,7 @@ type SubSchema struct {
uniqueItems bool uniqueItems bool
contains *SubSchema contains *SubSchema
additionalItems interface{} additionalItems any
// validation : all // validation : all
_const *string //const is a golang keyword _const *string //const is a golang keyword
+12 -12
View File
@@ -40,7 +40,7 @@ func isStringInSlice(s []string, what string) bool {
return false return false
} }
func marshalToJSONString(value interface{}) (*string, error) { func marshalToJSONString(value any) (*string, error) {
mBytes, err := json.Marshal(value) mBytes, err := json.Marshal(value)
if err != nil { if err != nil {
@@ -51,7 +51,7 @@ func marshalToJSONString(value interface{}) (*string, error) {
return &sBytes, nil 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 // 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 // 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 return nil, err
} }
var document interface{} var document any
err = json.Unmarshal([]byte(*jsonString), &document) err = json.Unmarshal([]byte(*jsonString), &document)
if err != nil { if err != nil {
@@ -73,7 +73,7 @@ func marshalWithoutNumber(value interface{}) (*string, error) {
return marshalToJSONString(document) return marshalToJSONString(document)
} }
func isJSONNumber(what interface{}) bool { func isJSONNumber(what any) bool {
switch what.(type) { switch what.(type) {
@@ -84,7 +84,7 @@ func isJSONNumber(what interface{}) bool {
return false return false
} }
func checkJSONInteger(what interface{}) (isInt bool) { func checkJSONInteger(what any) (isInt bool) {
jsonNumber := what.(json.Number) jsonNumber := what.(json.Number)
@@ -100,7 +100,7 @@ const (
minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 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) number, ok := what.(json.Number)
if !ok { if !ok {
return nil return nil
@@ -123,7 +123,7 @@ func mustBeInteger(what interface{}) *int {
return &int32Value return &int32Value
} }
func mustBeNumber(what interface{}) *big.Rat { func mustBeNumber(what any) *big.Rat {
number, ok := what.(json.Number) number, ok := what.(json.Number)
if !ok { if !ok {
return nil return nil
@@ -136,11 +136,11 @@ func mustBeNumber(what interface{}) *big.Rat {
return nil 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 { for _, v := range lval {
res = append(res, convertDocumentNode(v)) 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 { for k, v := range mval {
res[k.(string)] = convertDocumentNode(v) res[k.(string)] = convertDocumentNode(v)
+15 -15
View File
@@ -54,21 +54,21 @@ func (v *Schema) Validate(l JSONLoader) (*Result, error) {
return v.validateDocument(root), nil return v.validateDocument(root), nil
} }
func (v *Schema) validateDocument(root interface{}) *Result { func (v *Schema) validateDocument(root any) *Result {
result := &Result{} result := &Result{}
context := NewJSONContext(StringContextRoot, nil) context := NewJSONContext(StringContextRoot, nil)
v.RootSchema.validateRecursive(v.RootSchema, root, result, context) v.RootSchema.validateRecursive(v.RootSchema, root, result, context)
return result return result
} }
func (v *SubSchema) subValidateWithContext(document interface{}, context *JSONContext) *Result { func (v *SubSchema) subValidateWithContext(document any, context *JSONContext) *Result {
result := &Result{} result := &Result{}
v.validateRecursive(v, document, result, context) v.validateRecursive(v, document, result, context)
return result return result
} }
// Walker function to validate the json recursively against the SubSchema // 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 { if internalLogEnabled {
internalLog("validateRecursive %s", context.String()) internalLog("validateRecursive %s", context.String())
@@ -167,7 +167,7 @@ func (v *SubSchema) validateRecursive(currentSubSchema *SubSchema, currentNode i
return return
} }
castCurrentNode := currentNode.([]interface{}) castCurrentNode := currentNode.([]any)
currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)
@@ -190,9 +190,9 @@ func (v *SubSchema) validateRecursive(currentSubSchema *SubSchema, currentNode i
return return
} }
castCurrentNode, ok := currentNode.(map[string]interface{}) castCurrentNode, ok := currentNode.(map[string]any)
if !ok { if !ok {
castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{}) castCurrentNode = convertDocumentNode(currentNode).(map[string]any)
} }
currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) 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... // 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 { if internalLogEnabled {
internalLog("validateSchema %s", context.String()) internalLog("validateSchema %s", context.String())
@@ -349,14 +349,14 @@ func (v *SubSchema) validateSchema(currentSubSchema *SubSchema, currentNode inte
} }
if len(currentSubSchema.dependencies) > 0 { 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 { for elementKey := range currentNodeMap {
if dependency, ok := currentSubSchema.dependencies[elementKey]; ok { if dependency, ok := currentSubSchema.dependencies[elementKey]; ok {
switch dependency := dependency.(type) { switch dependency := dependency.(type) {
case []string: case []string:
for _, dependOnKey := range dependency { for _, dependOnKey := range dependency {
if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved { if _, dependencyResolved := currentNode.(map[string]any)[dependOnKey]; !dependencyResolved {
result.addInternalError( result.addInternalError(
new(MissingDependencyError), new(MissingDependencyError),
context, context,
@@ -395,7 +395,7 @@ func (v *SubSchema) validateSchema(currentSubSchema *SubSchema, currentNode inte
result.incrementScore() 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 { if internalLogEnabled {
internalLog("validateCommon %s", context.String()) internalLog("validateCommon %s", context.String())
@@ -452,7 +452,7 @@ func (v *SubSchema) validateCommon(currentSubSchema *SubSchema, value interface{
result.incrementScore() 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 { if internalLogEnabled {
internalLog("validateArray %s", context.String()) internalLog("validateArray %s", context.String())
@@ -578,7 +578,7 @@ func (v *SubSchema) validateArray(currentSubSchema *SubSchema, value []interface
result.incrementScore() 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 { if internalLogEnabled {
internalLog("validateObject %s", context.String()) internalLog("validateObject %s", context.String())
@@ -675,7 +675,7 @@ func (v *SubSchema) validateObject(currentSubSchema *SubSchema, value map[string
result.incrementScore() 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 { if internalLogEnabled {
internalLog("validatePatternProperty %s", context.String()) internalLog("validatePatternProperty %s", context.String())
@@ -701,7 +701,7 @@ func (v *SubSchema) validatePatternProperty(currentSubSchema *SubSchema, key str
return true 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 // Ignore JSON numbers
stringValue, isString := value.(string) stringValue, isString := value.(string)
@@ -752,7 +752,7 @@ func (v *SubSchema) validateString(currentSubSchema *SubSchema, value interface{
result.incrementScore() 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 // Ignore non numbers
number, isNumber := value.(json.Number) number, isNumber := value.(json.Number)
+1 -1
View File
@@ -21,7 +21,7 @@ const (
// Accept is used when conversion from values given by // Accept is used when conversion from values given by
// outside sources (such as JSON payloads) is required // 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 var tmp KeyType
switch x := value.(type) { switch x := value.(type) {
case string: case string:
+1 -1
View File
@@ -32,7 +32,7 @@ const (
// Accept is used when conversion from values given by // Accept is used when conversion from values given by
// outside sources (such as JSON payloads) is required // 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 var tmp SignatureAlgorithm
switch x := value.(type) { switch x := value.(type) {
case string: case string:
+2 -2
View File
@@ -39,12 +39,12 @@ func newECDSAPrivateKey(key *ecdsa.PrivateKey) (*ECDSAPrivateKey, error) {
} }
// Materialize returns the EC-DSA public key represented by this JWK // 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 return k.key, nil
} }
// Materialize returns the EC-DSA private key represented by this JWK // 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 return k.key, nil
} }
+10 -10
View File
@@ -18,15 +18,15 @@ const (
// Headers provides a common interface to all future possible headers // Headers provides a common interface to all future possible headers
type Headers interface { type Headers interface {
Get(string) (interface{}, bool) Get(string) (any, bool)
Set(string, interface{}) error Set(string, any) error
Walk(func(string, interface{}) error) error Walk(func(string, any) error) error
GetAlgorithm() jwa.SignatureAlgorithm GetAlgorithm() jwa.SignatureAlgorithm
GetKeyID() string GetKeyID() string
GetKeyOps() KeyOperationList GetKeyOps() KeyOperationList
GetKeyType() jwa.KeyType GetKeyType() jwa.KeyType
GetKeyUsage() string GetKeyUsage() string
GetPrivateParams() map[string]interface{} GetPrivateParams() map[string]any
} }
// StandardHeaders stores the common JWK parameters // 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 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 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 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 // 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 // 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 return h.PrivateParams
} }
// Get is a general getter function for JWK StandardHeaders structure // 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 { switch name {
case AlgorithmKey: case AlgorithmKey:
alg := h.GetAlgorithm() 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 // 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 { switch name {
case AlgorithmKey: case AlgorithmKey:
var acceptor jwa.SignatureAlgorithm 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) return fmt.Errorf("invalid value for %s key: %T", KeyUsageKey, value)
case PrivateParamsKey: case PrivateParamsKey:
if v, ok := value.(map[string]interface{}); ok { if v, ok := value.(map[string]any); ok {
h.PrivateParams = v h.PrivateParams = v
return nil 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. // 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} { for _, key := range []string{AlgorithmKey, KeyIDKey, KeyOpsKey, KeyTypeKey, KeyUsageKey, PrivateParamsKey} {
if v, ok := h.Get(key); ok { if v, ok := h.Get(key); ok {
if err := f(key, v); err != nil { if err := f(key, v); err != nil {
+6 -6
View File
@@ -10,9 +10,9 @@ import (
func TestHeader(t *testing.T) { 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) { t.Run("RoundTrip", func(t *testing.T) {
values := map[string]interface{}{ values := map[string]any{
jwk.KeyIDKey: "helloworld01", jwk.KeyIDKey: "helloworld01",
jwk.KeyTypeKey: jwa.RSA, jwk.KeyTypeKey: jwa.RSA,
jwk.KeyOpsKey: jwk.KeyOperationList{jwk.KeyOpSign}, jwk.KeyOpsKey: jwk.KeyOperationList{jwk.KeyOpSign},
@@ -49,7 +49,7 @@ func TestHeader(t *testing.T) {
dummy2 float64 dummy2 float64
} }
dummy := &dummyStruct{1, 3.4} dummy := &dummyStruct{1, 3.4}
values := map[string]interface{}{ values := map[string]any{
jwk.AlgorithmKey: dummy, jwk.AlgorithmKey: dummy,
jwk.KeyIDKey: dummy, jwk.KeyIDKey: dummy,
jwk.KeyTypeKey: dummy, jwk.KeyTypeKey: dummy,
@@ -92,7 +92,7 @@ func TestHeader(t *testing.T) {
dummy2 float64 dummy2 float64
} }
dummy := &dummyStruct{1, 3.4} dummy := &dummyStruct{1, 3.4}
values := map[string]interface{}{ values := map[string]any{
jwk.AlgorithmKey: jwa.SignatureAlgorithm("dummy"), jwk.AlgorithmKey: jwa.SignatureAlgorithm("dummy"),
jwk.KeyIDKey: 1, jwk.KeyIDKey: 1,
jwk.KeyTypeKey: jwa.KeyType("dummy"), jwk.KeyTypeKey: jwa.KeyType("dummy"),
@@ -131,7 +131,7 @@ func TestHeader(t *testing.T) {
t.Run("Algorithm", func(t *testing.T) { t.Run("Algorithm", func(t *testing.T) {
var h jwk.StandardHeaders 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) err := h.Set("alg", value)
if err != nil { if err != nil {
t.Fatalf("Failed to set algorithm value: %s", err.Error()) 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) { t.Run("KeyType", func(t *testing.T) {
var h jwk.StandardHeaders var h jwk.StandardHeaders
for _, value := range []interface{}{jwa.RSA, "RSA"} { for _, value := range []any{jwa.RSA, "RSA"} {
err := h.Set(jwk.KeyTypeKey, value) err := h.Set(jwk.KeyTypeKey, value)
if err != nil { if err != nil {
t.Fatalf("failed to set key type: %s", err.Error()) t.Fatalf("failed to set key type: %s", err.Error())
+1 -1
View File
@@ -24,7 +24,7 @@ type Key interface {
// RSA types would create *rsa.PublicKey or *rsa.PrivateKey, // RSA types would create *rsa.PublicKey or *rsa.PrivateKey,
// EC types would create *ecdsa.PublicKey or *ecdsa.PrivateKey, // EC types would create *ecdsa.PublicKey or *ecdsa.PrivateKey,
// and OctetSeq types create a []byte key. // and OctetSeq types create a []byte key.
Materialize() (interface{}, error) Materialize() (any, error)
GenerateKey(*RawKeyJSON) error GenerateKey(*RawKeyJSON) error
} }
+4 -4
View File
@@ -15,7 +15,7 @@ import (
// For rsa key types *rsa.PublicKey is returned; for ecdsa key types *ecdsa.PublicKey; // 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 // for byte slice (raw) keys, the key itself is returned. If the corresponding
// public key cannot be deduced, an error is returned // public key cannot be deduced, an error is returned
func GetPublicKey(key interface{}) (interface{}, error) { func GetPublicKey(key any) (any, error) {
if key == nil { if key == nil {
return nil, errors.New("jwk.New requires a non-nil key") 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) { switch v := key.(type) {
// Mental note: although Public() is defined in both types, // Mental note: although Public() is defined in both types,
// you can not coalesce the clauses for rsa.PrivateKey and // 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. // b/c the compiler cannot deduce the exact type.
case *rsa.PrivateKey: case *rsa.PrivateKey:
return v.Public(), nil return v.Public(), nil
@@ -37,7 +37,7 @@ func GetPublicKey(key interface{}) (interface{}, error) {
} }
// GetKeyTypeFromKey creates a jwk.Key from the given key. // GetKeyTypeFromKey creates a jwk.Key from the given key.
func GetKeyTypeFromKey(key interface{}) jwa.KeyType { func GetKeyTypeFromKey(key any) jwa.KeyType {
switch key.(type) { switch key.(type) {
case *rsa.PrivateKey, *rsa.PublicKey: case *rsa.PrivateKey, *rsa.PublicKey:
@@ -52,7 +52,7 @@ func GetKeyTypeFromKey(key interface{}) jwa.KeyType {
} }
// New creates a jwk.Key from the given key. // New creates a jwk.Key from the given key.
func New(key interface{}) (Key, error) { func New(key any) (Key, error) {
if key == nil { if key == nil {
return nil, errors.New("jwk.New requires a non-nil key") return nil, errors.New("jwk.New requires a non-nil key")
} }
+1 -1
View File
@@ -39,7 +39,7 @@ const (
) )
// Accept determines if Key Operation is valid // 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) { switch x := v.(type) {
case KeyOperationList: case KeyOperationList:
*keyOperationList = x *keyOperationList = x
+2 -2
View File
@@ -65,7 +65,7 @@ func newRSAPrivateKey(key *rsa.PrivateKey) (*RSAPrivateKey, error) {
} }
// Materialize returns the standard RSA Public Key representation stored in the internal representation // 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 { if k.key == nil {
return nil, errors.New("key has no rsa.PublicKey associated with it") 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 // 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 { if k.key == nil {
return nil, errors.New("key has no rsa.PrivateKey associated with it") return nil, errors.New("key has no rsa.PrivateKey associated with it")
} }
+1 -1
View File
@@ -24,7 +24,7 @@ func TestRSA(t *testing.T) {
t.Fatalf("jwk.New failed: %s", err.Error()) 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) return newKey.Set(k, v)
}) })
if err != nil { if err != nil {
+1 -1
View File
@@ -21,7 +21,7 @@ func newSymmetricKey(key []byte) (*SymmetricKey, error) {
// Materialize returns the octets for this symmetric key. // Materialize returns the octets for this symmetric key.
// Since this is a symmetric key, this just calls Octets // 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 return s.Octets(), nil
} }
+6 -6
View File
@@ -20,8 +20,8 @@ const (
// Headers provides a common interface for common header parameters // Headers provides a common interface for common header parameters
type Headers interface { type Headers interface {
Get(string) (interface{}, bool) Get(string) (any, bool)
Set(string, interface{}) error Set(string, any) error
GetAlgorithm() jwa.SignatureAlgorithm 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 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 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 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 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 // 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 { switch name {
case AlgorithmKey: case AlgorithmKey:
v := h.Algorithm v := h.Algorithm
@@ -99,7 +99,7 @@ func (h *StandardHeaders) Get(name string) (interface{}, bool) {
} }
// Set is a general setter function for StandardHeaders structure // 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 { switch name {
case AlgorithmKey: case AlgorithmKey:
if err := h.Algorithm.Accept(value); err != nil { 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) return fmt.Errorf("invalid value for %s key: %T", KeyIDKey, value)
case PrivateParamsKey: case PrivateParamsKey:
if v, ok := value.(map[string]interface{}); ok { if v, ok := value.(map[string]any); ok {
h.PrivateParams = v h.PrivateParams = v
return nil return nil
} }
+3 -3
View File
@@ -18,9 +18,9 @@ func TestHeader(t *testing.T) {
"kid": "2011-04-29" "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.AlgorithmKey: jwa.ES256,
jws.ContentTypeKey: "example", jws.ContentTypeKey: "example",
jws.CriticalKey: []string{"exp"}, jws.CriticalKey: []string{"exp"},
@@ -81,7 +81,7 @@ func TestHeader(t *testing.T) {
} }
dummy := &dummyStruct{1, 3.4} dummy := &dummyStruct{1, 3.4}
values := map[string]interface{}{ values := map[string]any{
jws.AlgorithmKey: dummy, jws.AlgorithmKey: dummy,
jws.ContentTypeKey: dummy, jws.ContentTypeKey: dummy,
jws.CriticalKey: dummy, jws.CriticalKey: dummy,
+3 -3
View File
@@ -38,7 +38,7 @@ import (
// SignLiteral generates a Signature for the given Payload and Headers, and serializes // SignLiteral generates a Signature for the given Payload and Headers, and serializes
// it in compact serialization format. In this format you may NOT use // it in compact serialization format. In this format you may NOT use
// multiple signers. // 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) encodedHdr := base64.RawURLEncoding.EncodeToString(hdrBuf)
encodedPayload := base64.RawURLEncoding.EncodeToString(payload) encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
signingInput := strings.Join( signingInput := strings.Join(
@@ -77,7 +77,7 @@ func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, hd
// multiple signers. // multiple signers.
// //
// If you would like to pass custom Headers, use the WithHeaders option. // 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{} var headers Headers = &StandardHeaders{}
err := headers.Set(AlgorithmKey, alg) 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 // Payload that was signed is returned. If you need more fine-grained
// control of the verification process, manually call `Parse`, generate a // control of the verification process, manually call `Parse`, generate a
// verifier, and call `Verify` on the parsed JWS message object. // 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) verifier, err := verify.New(alg)
if err != nil { if err != nil {
+2 -2
View File
@@ -72,7 +72,7 @@ func (s ECDSASigner) Algorithm() jwa.SignatureAlgorithm {
// SignWithRand signs payload with a ECDSA private key and a provided randomness // SignWithRand signs payload with a ECDSA private key and a provided randomness
// source (such as `rand.Reader`). // 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 { if key == nil {
return nil, errors.New("missing private key while signing payload") 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 // 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) return s.SignWithRand(payload, key, rand.Reader)
} }
+1 -1
View File
@@ -52,7 +52,7 @@ func (s HMACSigner) Algorithm() jwa.SignatureAlgorithm {
} }
// Sign signs payload with a Symmetric key // 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) hmackey, ok := key.([]byte)
if !ok { if !ok {
return nil, fmt.Errorf(`invalid key type %T. []byte is required`, key) return nil, fmt.Errorf(`invalid key type %T. []byte is required`, key)
+1 -1
View File
@@ -16,7 +16,7 @@ type Signer interface {
// for `jwa.RSXXX` and `jwa.PSXXX` types, you need to pass the // for `jwa.RSXXX` and `jwa.PSXXX` types, you need to pass the
// `*"crypto/rsa".PrivateKey` type. // `*"crypto/rsa".PrivateKey` type.
// Check the documentation for each signer for details // 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 Algorithm() jwa.SignatureAlgorithm
} }
+1 -1
View File
@@ -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 // Sign creates a signature using crypto/rsa. key must be a non-nil instance of
// `*"crypto/rsa".PrivateKey`. // `*"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 { if key == nil {
return nil, errors.New(`missing private key while signing payload`) return nil, errors.New(`missing private key while signing payload`)
} }
+1 -1
View File
@@ -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" // 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. // or "EC PRIVATE KEY" for RSA and ECDSA family of algorithms.
// For HMAC family, it return a []byte value // 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 { switch alg {
case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512: case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512:
block, _ := pem.Decode([]byte(key)) block, _ := pem.Decode([]byte(key))
+1 -1
View File
@@ -54,7 +54,7 @@ func newECDSA(alg jwa.SignatureAlgorithm) (*ECDSAVerifier, error) {
} }
// Verify checks whether the signature for a given input and key is correct // 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 { if key == nil {
return errors.New(`missing public key while verifying payload`) return errors.New(`missing public key while verifying payload`)
} }
+1 -1
View File
@@ -19,7 +19,7 @@ func newHMAC(alg jwa.SignatureAlgorithm) (*HMACVerifier, error) {
} }
// Verify checks whether the signature for a given input and key is correct // 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) expected, err := v.signer.Sign(signingInput, key)
if err != nil { if err != nil {
+1 -1
View File
@@ -16,7 +16,7 @@ type Verifier interface {
// for `jwa.RSXXX` and `jwa.PSXXX` types, you need to pass the // for `jwa.RSXXX` and `jwa.PSXXX` types, you need to pass the
// `*"crypto/rsa".PublicKey` type. // `*"crypto/rsa".PublicKey` type.
// Check the documentation for each verifier for details // 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 type rsaVerifyFunc func([]byte, []byte, *rsa.PublicKey) error
+1 -1
View File
@@ -75,7 +75,7 @@ func newRSA(alg jwa.SignatureAlgorithm) (*RSAVerifier, error) {
} }
// Verify checks if a JWS is valid. // 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 { if key == nil {
return errors.New(`missing public key while verifying payload`) return errors.New(`missing public key while verifying payload`)
} }
+1 -1
View File
@@ -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", // 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 RSA and ECDSA family of algorithms.
// For HMAC family, it return a []byte value // 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 { switch alg {
case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512, jwa.ES256, jwa.ES384, jwa.ES512: case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512, jwa.ES256, jwa.ES384, jwa.ES512:
block, _ := pem.Decode([]byte(key)) block, _ := pem.Decode([]byte(key))
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"testing" "testing"
) )
func assertEqual(t *testing.T, expected, actual interface{}) { func assertEqual(t *testing.T, expected, actual any) {
t.Helper() t.Helper()
if !reflect.DeepEqual(expected, actual) { if !reflect.DeepEqual(expected, actual) {
+2 -2
View File
@@ -143,11 +143,11 @@ public_servers[server] {
func TestPrettyFormatterMultilineJSONFields(t *testing.T) { func TestPrettyFormatterMultilineJSONFields(t *testing.T) {
fmtr := prettyFormatter{} fmtr := prettyFormatter{}
obj := map[string]interface{}{ obj := map[string]any{
"a": 123, "a": 123,
"b": nil, "b": nil,
"d": "abc", "d": "abc",
"e": map[string]interface{}{ "e": map[string]any{
"test": []string{ "test": []string{
"aa", "aa",
"bb", "bb",
+7 -7
View File
@@ -8,7 +8,7 @@ package merge
// InterfaceMaps returns the result of merging a and b. If a and b cannot be // 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. // 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 { if a == nil {
return b, true return b, true
@@ -21,7 +21,7 @@ func InterfaceMaps(a map[string]interface{}, b map[string]interface{}) (map[stri
return merge(a, b), true 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 { for k := range b {
@@ -32,8 +32,8 @@ func merge(a, b map[string]interface{}) map[string]interface{} {
continue continue
} }
existObj := exist.(map[string]interface{}) existObj := exist.(map[string]any)
addObj := add.(map[string]interface{}) addObj := add.(map[string]any)
a[k] = merge(existObj, addObj) a[k] = merge(existObj, addObj)
} }
@@ -41,7 +41,7 @@ func merge(a, b map[string]interface{}) map[string]interface{} {
return a return a
} }
func hasConflicts(a, b map[string]interface{}) bool { func hasConflicts(a, b map[string]any) bool {
for k := range b { for k := range b {
add := b[k] add := b[k]
@@ -50,8 +50,8 @@ func hasConflicts(a, b map[string]interface{}) bool {
continue continue
} }
existObj, existOk := exist.(map[string]interface{}) existObj, existOk := exist.(map[string]any)
addObj, addOk := add.(map[string]interface{}) addObj, addOk := add.(map[string]any)
if !existOk || !addOk { if !existOk || !addOk {
return true return true
} }
+4 -4
View File
@@ -26,16 +26,16 @@ func TestMergeDocs(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
a := map[string]interface{}{} a := map[string]any{}
if err := util.UnmarshalJSON([]byte(tc.a), &a); err != nil { if err := util.UnmarshalJSON([]byte(tc.a), &a); err != nil {
panic(err) panic(err)
} }
aInitial := map[string]interface{}{} aInitial := map[string]any{}
if err := util.UnmarshalJSON([]byte(tc.a), &aInitial); err != nil { if err := util.UnmarshalJSON([]byte(tc.a), &aInitial); err != nil {
panic(err) panic(err)
} }
b := map[string]interface{}{} b := map[string]any{}
if err := util.UnmarshalJSON([]byte(tc.b), &b); err != nil { if err := util.UnmarshalJSON([]byte(tc.b), &b); err != nil {
panic(err) panic(err)
} }
@@ -53,7 +53,7 @@ func TestMergeDocs(t *testing.T) {
} else { } else {
expected := map[string]interface{}{} expected := map[string]any{}
if err := util.UnmarshalJSON([]byte(tc.c), &expected); err != nil { if err := util.UnmarshalJSON([]byte(tc.c), &expected); err != nil {
panic(err) panic(err)
} }
+2 -2
View File
@@ -51,10 +51,10 @@ type Planner struct {
// debugf prepends the planner location. We're passing callstack depth 2 because // debugf prepends the planner location. We're passing callstack depth 2 because
// it should still log the file location of p.debugf. // 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 var msg string
if p.loc != nil { 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 { } else {
msg = fmt.Sprintf(format, args...) msg = fmt.Sprintf(format, args...)
} }
+34 -34
View File
@@ -428,13 +428,13 @@ q = 2`,
} }
type cmpWalker struct { type cmpWalker struct {
needle interface{} needle any
loc string loc string
found bool // stop comparing after first found needle found bool // stop comparing after first found needle
} }
func (*cmpWalker) Before(interface{}) {} func (*cmpWalker) Before(any) {}
func (*cmpWalker) After(interface{}) {} func (*cmpWalker) After(any) {}
// Visit takes, for example, // 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 // 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, // returned. This trap can be avoided by starting with a failing test,
// and proceeding with caution. ;) // 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) { if !f.found && reflect.TypeOf(f.needle) == reflect.TypeOf(x) {
f.found = true f.found = true
expLoc := f.loc expLoc := f.loc
@@ -459,7 +459,7 @@ func (f *cmpWalker) Visit(x interface{}) (ir.Visitor, error) {
return f, nil return f, nil
} }
func getLocation(x interface{}) string { func getLocation(x any) string {
v := reflect.ValueOf(x).Elem().FieldByName("Location") v := reflect.ValueOf(x).Elem().FieldByName("Location")
li := v.Interface() li := v.Interface()
file := v.FieldByName("file").String() file := v.FieldByName("file").String()
@@ -470,7 +470,7 @@ func getLocation(x interface{}) string {
return "unknown" 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) 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. // counted differently in the editor vs. in code.
func TestPlannerLocations(t *testing.T) { func TestPlannerLocations(t *testing.T) {
funcs := func(p *ir.Policy) interface{} { funcs := func(p *ir.Policy) any {
return p.Funcs return p.Funcs
} }
@@ -487,8 +487,8 @@ func TestPlannerLocations(t *testing.T) {
note string note string
queries []string queries []string
modules []string modules []string
exps map[ir.Stmt]string // stmt -> expected location "file:row:col: text" exps map[ir.Stmt]string // stmt -> expected location "file:row:col: text"
where func(*ir.Policy) interface{} // where to start walking search for `exps` where func(*ir.Policy) any // where to start walking search for `exps`
}{ }{
{ {
note: "complete rule reference", note: "complete rule reference",
@@ -567,7 +567,7 @@ p = x if {
&ir.MakeObjectStmt{}: `module-0.rego:3:9: p = {"foo": "bar"}`, &ir.MakeObjectStmt{}: `module-0.rego:3:9: p = {"foo": "bar"}`,
&ir.AssignVarOnceStmt{}: `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 return p.Funcs.Funcs[0].Blocks[2] // default rule block
}, },
}, },
@@ -634,7 +634,7 @@ q = 2 if {
&ir.CallStmt{}: "<query>:1:1: data", &ir.CallStmt{}: "<query>:1:1: data",
&ir.ObjectInsertStmt{}: "<query>:1:1: data", &ir.ObjectInsertStmt{}: "<query>:1:1: data",
}, },
where: func(p *ir.Policy) interface{} { where: func(p *ir.Policy) any {
return p.Plans.Plans[0].Blocks[0].Stmts[4] return p.Plans.Plans[0].Blocks[0].Stmts[4]
}, },
}, },
@@ -650,7 +650,7 @@ a = true`},
&ir.ResultSetAddStmt{}: "<query>:1:1: data[y].a = x", &ir.ResultSetAddStmt{}: "<query>:1:1: data[y].a = x",
&ir.DotStmt{}: "<query>:1:1: data[y].a = x", &ir.DotStmt{}: "<query>:1:1: data[y].a = x",
}, },
where: func(p *ir.Policy) interface{} { where: func(p *ir.Policy) any {
return p.Plans.Plans[0] return p.Plans.Plans[0]
}, },
}, },
@@ -713,7 +713,7 @@ a if {
t.Fatal(err) t.Fatal(err)
} }
} }
start := interface{}(policy) start := any(policy)
if tc.where != nil { if tc.where != nil {
start = tc.where(policy) start = tc.where(policy)
} }
@@ -1130,17 +1130,17 @@ func TestPlannerCallDynamic(t *testing.T) {
note string note string
queries []string queries []string
modules []string modules []string
path []interface{} // path expected on irCallDynamicStmt, string => string const, int => local path []any // path expected on irCallDynamicStmt, string => string const, int => local
where func(*ir.Policy) interface{} // where to start walking search for `exps` where func(*ir.Policy) any // where to start walking search for `exps`
extras []func(interface{}) error extras []func(any) error
}{ }{
{ {
note: "CallDynamicStmt optimization", note: "CallDynamicStmt optimization",
queries: []string{`x := "a"; data.test[x] = y`}, queries: []string{`x := "a"; data.test[x] = y`},
modules: []string{`package test modules: []string{`package test
a if { true }`}, a if { true }`},
path: []interface{}{"g0", "test", 2}, path: []any{"g0", "test", 2},
extras: []func(interface{}) error{ extras: []func(any) error{
findFunc("g0.data.test.a", "g0.test.a"), 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`}, queries: []string{`x := "a"; data.test.a[x].c = y`},
modules: []string{`package test modules: []string{`package test
a.b.c = 1 if { true }`}, a.b.c = 1 if { true }`},
path: []interface{}{"g0", "test", "a", 2, "c"}, path: []any{"g0", "test", "a", 2, "c"},
extras: []func(interface{}) error{ extras: []func(any) error{
findFunc("g0.data.test.a.b.c", "g0.test.a.b.c"), 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 modules: []string{`package test
a.b.c = 1 if { true } a.b.c = 1 if { true }
a.b[t] = 2 if { t := input }`}, a.b[t] = 2 if { t := input }`},
path: []interface{}{"g0", "test", "a", 2}, path: []any{"g0", "test", "a", 2},
extras: []func(interface{}) error{ extras: []func(any) error{
findFunc("g0.data.test.a.b", "g0.test.a.b"), 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 modules: []string{`package test
a.b[1] = 1 if { true } a.b[1] = 1 if { true }
a.b[t] = 2 if { t := input }`}, a.b[t] = 2 if { t := input }`},
path: []interface{}{"g0", "test", "a", 2}, path: []any{"g0", "test", "a", 2},
extras: []func(interface{}) error{ extras: []func(any) error{
findFunc("g0.data.test.a.b", "g0.test.a.b"), 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`}, queries: []string{`x := "a"; data.test.a[x] = y`},
modules: []string{`package test modules: []string{`package test
a.b[1] = 1 if { true }`}, a.b[1] = 1 if { true }`},
path: []interface{}{"g0", "test", "a", 2}, path: []any{"g0", "test", "a", 2},
extras: []func(interface{}) error{ extras: []func(any) error{
findFunc("g0.data.test.a.b", "g0.test.a.b"), findFunc("g0.data.test.a.b", "g0.test.a.b"),
}, },
}, },
@@ -1222,7 +1222,7 @@ a.b[1] = 1 if { true }`},
t.Fatal(err) t.Fatal(err)
} }
} }
start := interface{}(policy) start := any(policy)
if tc.where != nil { if tc.where != nil {
start = tc.where(policy) start = tc.where(policy)
} }
@@ -1255,13 +1255,13 @@ a.b[1] = 1 if { true }`},
} }
type stmtCmpWalker struct { type stmtCmpWalker struct {
stmt interface{} stmt any
found bool // stop comparing after first found needle found bool // stop comparing after first found needle
} }
func (*stmtCmpWalker) Before(interface{}) {} func (*stmtCmpWalker) Before(any) {}
func (*stmtCmpWalker) After(interface{}) {} func (*stmtCmpWalker) After(any) {}
func (w *stmtCmpWalker) Visit(x interface{}) (ir.Visitor, error) { func (w *stmtCmpWalker) Visit(x any) (ir.Visitor, error) {
if !w.found { if !w.found {
switch s := w.stmt.(type) { switch s := w.stmt.(type) {
case *ir.CallDynamicStmt: case *ir.CallDynamicStmt:
@@ -1285,7 +1285,7 @@ func (w *stmtCmpWalker) Visit(x interface{}) (ir.Visitor, error) {
return w, nil 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}} w := &stmtCmpWalker{stmt: &ir.CallDynamicStmt{Path: path}}
if err := ir.Walk(w, p); err != nil { if err := ir.Walk(w, p); err != nil {
return err return err
@@ -1296,8 +1296,8 @@ func findCallDynamic(path []ir.Operand, p interface{}) error {
return nil return nil
} }
func findFunc(name, path string) func(interface{}) error { func findFunc(name, path string) func(any) error {
return func(p interface{}) error { return func(p any) error {
w := &stmtCmpWalker{stmt: &ir.Func{Name: name, Path: strings.Split(path, ".")}} w := &stmtCmpWalker{stmt: &ir.Func{Name: name, Path: strings.Split(path, ".")}}
if err := ir.Walk(w, p); err != nil { if err := ir.Walk(w, p); err != nil {
return err return err
+13 -13
View File
@@ -114,7 +114,7 @@ type Output struct {
Result rego.ResultSet `json:"result,omitempty"` Result rego.ResultSet `json:"result,omitempty"`
Partial *rego.PartialQueries `json:"partial,omitempty"` Partial *rego.PartialQueries `json:"partial,omitempty"`
Metrics metrics.Metrics `json:"metrics,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"` Explanation []*topdown.Event `json:"explanation,omitempty"`
Profile []profiler.ExprStats `json:"profile,omitempty"` Profile []profiler.ExprStats `json:"profile,omitempty"`
AggregatedProfile []profiler.ExprStatsAggregated `json:"aggregated_profile,omitempty"` AggregatedProfile []profiler.ExprStatsAggregated `json:"aggregated_profile,omitempty"`
@@ -236,7 +236,7 @@ type OutputError struct {
Message string `json:"message"` Message string `json:"message"`
Code string `json:"code,omitempty"` Code string `json:"code,omitempty"`
Location *ast.Location `json:"location,omitempty"` Location *ast.Location `json:"location,omitempty"`
Details interface{} `json:"details,omitempty"` Details any `json:"details,omitempty"`
err error err error
} }
@@ -245,7 +245,7 @@ func (j OutputError) Error() string {
} }
// JSON writes x to w with indentation. // 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 := json.NewEncoder(w)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
return encoder.Encode(x) return encoder.Encode(x)
@@ -270,7 +270,7 @@ func Values(w io.Writer, r Output) error {
return prettyError(w, r.Errors) return prettyError(w, r.Errors)
} }
for _, rs := range r.Result { for _, rs := range r.Result {
line := make([]interface{}, len(rs.Expressions)) line := make([]any, len(rs.Expressions))
for i := range line { for i := range line {
line[i] = rs.Expressions[i].Value line[i] = rs.Expressions[i].Value
} }
@@ -406,7 +406,7 @@ func Raw(w io.Writer, r Output) error {
return nil return nil
} }
func Discard(w io.Writer, x interface{}) error { func Discard(w io.Writer, x any) error {
encoder := json.NewEncoder(w) encoder := json.NewEncoder(w)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
field, ok := x.(Output) field, ok := x.(Output)
@@ -417,7 +417,7 @@ func Discard(w io.Writer, x interface{}) error {
if err != nil { if err != nil {
return err return err
} }
var rawData map[string]interface{} var rawData map[string]any
err = json.Unmarshal(bs, &rawData) err = json.Unmarshal(bs, &rawData)
if err != nil { if err != nil {
return err 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 // 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}) bs, err := format.AstWithOpts(x, format.Opts{IgnoreLocations: true, RegoVersion: regoVersion})
if err != nil { if err != nil {
return "", 0, fmt.Errorf("format error: %w", err) 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%"} 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"} keys := []string{"metric"}
tableMetrics := generateTableWithKeys(w, append(keys, statKeys...)...) tableMetrics := generateTableWithKeys(w, append(keys, statKeys...)...)
populateTableAggregatedMetrics(ms, tableMetrics, limit) populateTableAggregatedMetrics(ms, tableMetrics, limit)
@@ -548,7 +548,7 @@ func prettyAggregatedProfile(w io.Writer, profile []profiler.ExprStatsAggregated
for _, rs := range profile { for _, rs := range profile {
line := []string{} line := []string{}
for _, k := range statKeys { for _, k := range statKeys {
v := rs.ExprTimeNsStats.(map[string]interface{})[k] v := rs.ExprTimeNsStats.(map[string]any)[k]
if f, ok := v.(float64); ok { if f, ok := v.(float64); ok {
line = append(line, time.Duration(f).String()) line = append(line, time.Duration(f).String())
} else if i, ok := v.(int64); ok { } 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) { func populateTableMetrics(m metrics.Metrics, table *tablewriter.Table, prettyLimit int) {
lines := [][]string{} lines := [][]string{}
for varName, varValueInterface := range m.All() { for varName, varValueInterface := range m.All() {
val, ok := varValueInterface.(map[string]interface{}) val, ok := varValueInterface.(map[string]any)
if !ok { if !ok {
line := []string{} line := []string{}
varValue := checkStrLimit(fmt.Sprintf("%v", varValueInterface), prettyLimit) varValue := checkStrLimit(fmt.Sprintf("%v", varValueInterface), prettyLimit)
@@ -669,11 +669,11 @@ func populateTableMetrics(m metrics.Metrics, table *tablewriter.Table, prettyLim
table.AppendBulk(lines) 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{} lines := [][]string{}
for name, vals := range ms { for name, vals := range ms {
line := []string{name} line := []string{name}
vs := vals.(map[string]interface{}) vs := vals.(map[string]any)
for _, k := range statKeys { for _, k := range statKeys {
line = append(line, checkStrLimit(fmt.Sprintf("%v", vs[k]), prettyLimit)) line = append(line, checkStrLimit(fmt.Sprintf("%v", vs[k]), prettyLimit))
} }
@@ -712,7 +712,7 @@ func (rk resultKey) string() string {
return rk.exprText return rk.exprText
} }
func (rk resultKey) selectVarValue(result rego.Result) interface{} { func (rk resultKey) selectVarValue(result rego.Result) any {
if rk.varName != "" { if rk.varName != "" {
return result.Bindings[rk.varName] return result.Bindings[rk.varName]
} }
+4 -4
View File
@@ -127,7 +127,7 @@ func TestOutputJSONErrorStructuredASTErr(t *testing.T) {
func TestOutputJSONErrorStructuredStorageErr(t *testing.T) { func TestOutputJSONErrorStructuredStorageErr(t *testing.T) {
store := inmem.New() store := inmem.New()
txn := storage.NewTransactionOrDie(context.Background(), store) 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 := `{ expected := `{
"errors": [ "errors": [
{ {
@@ -470,9 +470,9 @@ func TestRaw(t *testing.T) {
Result: []rego.Result{ Result: []rego.Result{
{ {
Expressions: []*rego.ExpressionValue{ Expressions: []*rego.ExpressionValue{
{Value: []interface{}{"one"}}, {Value: []any{"one"}},
{Value: map[string]interface{}{ {Value: map[string]any{
"key": []interface{}{}, "key": []any{},
}}, }},
}, },
}, },
+3 -3
View File
@@ -34,7 +34,7 @@ type Provider struct {
logger loggerFunc 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. // New returns a new Provider object.
func New(inner metrics.Metrics, logger loggerFunc, httpRequestBuckets []float64) *Provider { 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 // All returns the union of the inner metric provider and the underlying
// prometheus registry. // prometheus registry.
func (p *Provider) All() map[string]interface{} { func (p *Provider) All() map[string]any {
all := p.inner.All() all := p.inner.All()
families, err := p.registry.Gather() families, err := p.registry.Gather()
if err != nil && p.logger != nil { if err != nil && p.logger != nil {
p.logger(map[string]interface{}{ p.logger(map[string]any{
"err": err, "err": err,
}, "Failed to gather metrics from Prometheus registry.") }, "Failed to gather metrics from Prometheus registry.")
} }
+2 -2
View File
@@ -19,7 +19,7 @@ import (
func TestJSONSerialization(t *testing.T) { func TestJSONSerialization(t *testing.T) {
inner := metrics.New() inner := metrics.New()
logger := func(logger logging.Logger) loggerFunc { 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...) logger.WithFields(attrs).Error(f, a...)
} }
}(logging.NewNoOpLogger()) }(logging.NewNoOpLogger())
@@ -32,7 +32,7 @@ func TestJSONSerialization(t *testing.T) {
t.Fatal(err) 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) err = json.Unmarshal(bs, &act)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
+1 -1
View File
@@ -18,7 +18,7 @@ func DoRequestWithClient(req *http.Request, client *http.Client, desc string, lo
} }
defer resp.Body.Close() defer resp.Body.Close()
logger.WithFields(map[string]interface{}{ logger.WithFields(map[string]any{
"url": req.URL.String(), "url": req.URL.String(),
"status": resp.Status, "status": resp.Status,
"headers": resp.Header, "headers": resp.Header,
+3 -3
View File
@@ -36,10 +36,10 @@ type EvalEngine interface {
Init() (EvalEngine, error) Init() (EvalEngine, error)
Entrypoints(context.Context) (map[string]int32, error) Entrypoints(context.Context) (map[string]int32, error)
WithPolicyBytes([]byte) EvalEngine WithPolicyBytes([]byte) EvalEngine
WithDataJSON(interface{}) EvalEngine WithDataJSON(any) EvalEngine
Eval(context.Context, EvalOpts) (*Result, error) Eval(context.Context, EvalOpts) (*Result, error)
SetData(context.Context, interface{}) error SetData(context.Context, any) error
SetDataPath(context.Context, []string, interface{}) error SetDataPath(context.Context, []string, any) error
RemoveDataPath(context.Context, []string) error RemoveDataPath(context.Context, []string) error
Close() Close()
} }
+1 -1
View File
@@ -18,7 +18,7 @@ type Result struct {
// EvalOpts define options for performing an evaluation. // EvalOpts define options for performing an evaluation.
type EvalOpts struct { type EvalOpts struct {
Input *interface{} Input *any
Metrics metrics.Metrics Metrics metrics.Metrics
Entrypoint int32 Entrypoint int32
Time time.Time Time time.Time
+1 -1
View File
@@ -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() mux := http.NewServeMux()
ts := httptest.NewServer(mux) ts := httptest.NewServer(mux)
+15 -15
View File
@@ -206,12 +206,12 @@ func TestLoadTarGzsInBundleAndNonBundleMode(t *testing.T) {
Manifest: bundle.Manifest{ Manifest: bundle.Manifest{
Roots: &[]string{"a"}, Roots: &[]string{"a"},
}, },
Data: map[string]interface{}{ Data: map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"foo": "bar1", "foo": "bar1",
"x": map[string]interface{}{ "x": map[string]any{
"y": map[string]interface{}{ "y": map[string]any{
"z": []interface{}{json.Number("1")}, "z": []any{json.Number("1")},
}, },
}, },
}, },
@@ -229,12 +229,12 @@ func TestLoadTarGzsInBundleAndNonBundleMode(t *testing.T) {
Manifest: bundle.Manifest{ Manifest: bundle.Manifest{
Roots: &[]string{"b"}, Roots: &[]string{"b"},
}, },
Data: map[string]interface{}{ Data: map[string]any{
"b": map[string]interface{}{ "b": map[string]any{
"foo": "bar2", "foo": "bar2",
"x": map[string]interface{}{ "x": map[string]any{
"y": map[string]interface{}{ "y": map[string]any{
"z": []interface{}{json.Number("1")}, "z": []any{json.Number("1")},
}, },
}, },
}, },
@@ -257,12 +257,12 @@ func TestLoadTarGzsInBundleAndNonBundleMode(t *testing.T) {
Manifest: bundle.Manifest{ Manifest: bundle.Manifest{
Roots: &[]string{"a"}, Roots: &[]string{"a"},
}, },
Data: map[string]interface{}{ Data: map[string]any{
"a": map[string]interface{}{ "a": map[string]any{
"foo1": "bar2", "foo1": "bar2",
"x": map[string]interface{}{ "x": map[string]any{
"y": map[string]interface{}{ "y": map[string]any{
"z": []interface{}{json.Number("2")}, "z": []any{json.Number("2")},
}, },
}, },
}, },
+1 -1
View File
@@ -37,7 +37,7 @@ func Term(params Params) (*ast.Term, error) {
if params.Config != nil { if params.Config != nil {
var x interface{} var x any
if err := util.Unmarshal(params.Config, &x); err != nil { if err := util.Unmarshal(params.Config, &x); err != nil {
return nil, err return nil, err
} }
+4 -4
View File
@@ -46,7 +46,7 @@ func (t *Transaction) safeToUse() bool {
type Store struct { type Store struct {
inmem storage.Store inmem storage.Store
storeOpts []inmem.Opt storeOpts []inmem.Opt
baseData map[string]interface{} baseData map[string]any
Transactions []*Transaction Transactions []*Transaction
Reads []*ReadCall Reads []*ReadCall
Writes []*WriteCall Writes []*WriteCall
@@ -79,7 +79,7 @@ func New(opt ...inmem.Opt) *Store {
} }
// NewWithData creates a store with some initial data // 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{ s := &Store{
baseData: data, baseData: data,
storeOpts: opt, 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 // 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 // is an error are the read is unsafe it will be noted in
// the ReadCall. // 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) mockTxn := txn.(*Transaction)
data, err := s.inmem.Read(ctx, mockTxn.txn, path) 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 // 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 // is an error are the write is unsafe it will be noted in
// the WriteCall. // 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) mockTxn := txn.(*Transaction)
err := s.inmem.Write(ctx, mockTxn.txn, op, path, value) err := s.inmem.Write(ctx, mockTxn.txn, op, path, value)
+32 -32
View File
@@ -46,8 +46,8 @@ func ToYAML(s string) (string, error) {
// Parse parses a set line. // Parse parses a set line.
// //
// A set line is of the form name1=value1,name2=value2 // A set line is of the form name1=value1,name2=value2
func Parse(s string) (map[string]interface{}, error) { func Parse(s string) (map[string]any, error) {
vals := map[string]interface{}{} vals := map[string]any{}
scanner := bytes.NewBufferString(s) scanner := bytes.NewBufferString(s)
t := newParser(scanner, vals, false) t := newParser(scanner, vals, false)
err := t.parse() 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. // ParseString parses a set line and forces a string value.
// //
// A set line is of the form name1=value1,name2=value2 // A set line is of the form name1=value1,name2=value2
func ParseString(s string) (map[string]interface{}, error) { func ParseString(s string) (map[string]any, error) {
vals := map[string]interface{}{} vals := map[string]any{}
scanner := bytes.NewBufferString(s) scanner := bytes.NewBufferString(s)
t := newParser(scanner, vals, true) t := newParser(scanner, vals, true)
err := t.parse() 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 // If the strval string has a key that exists in dest, it overwrites the
// dest version. // dest version.
func ParseInto(s string, dest map[string]interface{}) error { func ParseInto(s string, dest map[string]any) error {
scanner := bytes.NewBufferString(s) scanner := bytes.NewBufferString(s)
t := newParser(scanner, dest, false) t := newParser(scanner, dest, false)
return t.parse() 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. // ParseIntoFile parses a filevals line and merges the result into dest.
// //
// This method always returns a string as the value. // 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) scanner := bytes.NewBufferString(s)
t := newFileParser(scanner, dest, runesToVal) t := newFileParser(scanner, dest, runesToVal)
return t.parse() 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. // ParseIntoString parses a strvals line and merges the result into dest.
// //
// This method always returns a string as the value. // 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) scanner := bytes.NewBufferString(s)
t := newParser(scanner, dest, true) t := newParser(scanner, dest, true)
return t.parse() 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 // where st is a boolean to figure out if we're forcing it to parse values as string
type parser struct { type parser struct {
sc *bytes.Buffer sc *bytes.Buffer
data map[string]interface{} data map[string]any
runesToVal runesToVal 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 { func newParser(sc *bytes.Buffer, data map[string]any, stringBool bool) *parser {
rs2v := func(rs []rune) (interface{}, error) { rs2v := func(rs []rune) (any, error) {
return typedVal(rs, stringBool), nil return typedVal(rs, stringBool), nil
} }
return &parser{sc: sc, data: data, runesToVal: rs2v} 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} return &parser{sc: sc, data: data, runesToVal: runesToVal}
} }
@@ -139,7 +139,7 @@ func runeSet(r []rune) map[rune]bool {
return s return s
} }
func (t *parser) key(data map[string]interface{}) error { func (t *parser) key(data map[string]any) error {
stop := runeSet([]rune{'=', '[', ',', '.'}) stop := runeSet([]rune{'=', '[', ',', '.'})
for { for {
switch k, last, err := runesUntil(t.sc, stop); { switch k, last, err := runesUntil(t.sc, stop); {
@@ -156,9 +156,9 @@ func (t *parser) key(data map[string]interface{}) error {
} }
kk := string(k) kk := string(k)
// Find or create target list // Find or create target list
list := []interface{}{} list := []any{}
if _, ok := data[kk]; ok { if _, ok := data[kk]; ok {
list = data[kk].([]interface{}) list = data[kk].([]any)
} }
// Now we need to get the value after the ]. // 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)) return fmt.Errorf("key %q has no value (cannot end with ,)", string(k))
case last == '.': case last == '.':
// First, create or find the target map. // First, create or find the target map.
inner := map[string]interface{}{} inner := map[string]any{}
if _, ok := data[string(k)]; ok { if _, ok := data[string(k)]; ok {
inner = data[string(k)].(map[string]interface{}) inner = data[string(k)].(map[string]any)
} }
// Recurse // 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 key is empty, don't set it.
if len(key) == 0 { if len(key) == 0 {
return return
@@ -218,7 +218,7 @@ func set(data map[string]interface{}, key string, val interface{}) {
data[key] = val 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 // 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. // 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. // 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) return list, fmt.Errorf("index of %d is greater than maximum supported index of %d", index, MaxIndex)
} }
if len(list) <= index { if len(list) <= index {
newlist := make([]interface{}, index+1) newlist := make([]any, index+1)
copy(newlist, list) copy(newlist, list)
list = newlist list = newlist
} }
@@ -254,7 +254,7 @@ func (t *parser) keyIndex() (int, error) {
return strconv.Atoi(string(v)) 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 { if i < 0 {
return list, fmt.Errorf("negative %d index not allowed", i) 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) return setIndex(list, i, list2)
case last == '.': case last == '.':
// We have a nested object. Send to t.key // We have a nested object. Send to t.key
inner := map[string]interface{}{} inner := map[string]any{}
if len(list) > i { if len(list) > i {
var ok bool var ok bool
inner, ok = list[i].(map[string]interface{}) inner, ok = list[i].(map[string]any)
if !ok { if !ok {
// We have indices out of order. Initialize empty value. // We have indices out of order. Initialize empty value.
list[i] = map[string]interface{}{} list[i] = map[string]any{}
inner = list[i].(map[string]interface{}) inner = list[i].(map[string]any)
} }
} }
@@ -326,21 +326,21 @@ func (t *parser) val() ([]rune, error) {
return v, err return v, err
} }
func (t *parser) valList() ([]interface{}, error) { func (t *parser) valList() ([]any, error) {
r, _, e := t.sc.ReadRune() r, _, e := t.sc.ReadRune()
if e != nil { if e != nil {
return []interface{}{}, e return []any{}, e
} }
if r != '{' { if r != '{' {
e = t.sc.UnreadRune() e = t.sc.UnreadRune()
if e != nil { if e != nil {
return []interface{}{}, e return []any{}, e
} }
return []interface{}{}, ErrNotList return []any{}, ErrNotList
} }
list := []interface{}{} list := []any{}
stop := runeSet([]rune{',', '}'}) stop := runeSet([]rune{',', '}'})
for { for {
switch rs, last, err := runesUntil(t.sc, stop); { 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 != ',' { if r, _, e := t.sc.ReadRune(); e == nil && r != ',' {
e = t.sc.UnreadRune() e = t.sc.UnreadRune()
if e != nil { if e != nil {
return []interface{}{}, e return []any{}, e
} }
} }
v, e := t.runesToVal(rs) v, e := t.runesToVal(rs)
@@ -395,7 +395,7 @@ func inMap(k rune, m map[rune]bool) bool {
return ok return ok
} }
func typedVal(v []rune, st bool) interface{} { func typedVal(v []rune, st bool) any {
val := string(v) val := string(v)
if st { if st {

Some files were not shown because too many files have changed in this diff Show More