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

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