mirror of
https://github.com/open-policy-agent/opa.git
synced 2026-08-12 19:32:48 -06:00
Add perfsprint linter (#7334)
And update code to conform to the rule. - Replace unnecessary fmt.Sprintf with string concatenation - Replace fmt.Sprint with more efficient strconv.Itoa - Replace static fmt.Errorf calls with more efficient errors.New Thanks @srenatus for pushing me down this rabbit hole! Signed-off-by: Anders Eknert <anders@styra.com>
This commit is contained in:
@@ -143,6 +143,15 @@ linters-settings:
|
||||
govet:
|
||||
enable:
|
||||
- deepequalerrors
|
||||
perfsprint:
|
||||
# only rule disabled by default, but it's a good one
|
||||
err-error: true
|
||||
revive:
|
||||
rules:
|
||||
# this mainly complains about us using min/max for variable names,
|
||||
# which seems like an unlikely source of actual issues
|
||||
- name: redefines-builtin-id
|
||||
disabled: true
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
@@ -164,4 +173,5 @@ linters:
|
||||
- prealloc
|
||||
- unconvert
|
||||
- copyloopvar
|
||||
- perfsprint
|
||||
# - gosec # too many false positives
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@
|
||||
package ast
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
v1 "github.com/open-policy-agent/opa/v1/ast"
|
||||
@@ -279,7 +280,7 @@ func ParseStatement(input string) (Statement, error) {
|
||||
return nil, err
|
||||
}
|
||||
if len(stmts) != 1 {
|
||||
return nil, fmt.Errorf("expected exactly one statement")
|
||||
return nil, errors.New("expected exactly one statement")
|
||||
}
|
||||
return stmts[0], nil
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ func main() {
|
||||
removed++
|
||||
continue
|
||||
}
|
||||
document = append(document, fmt.Sprintf("%s\n", str))
|
||||
document = append(document, str+"\n")
|
||||
}
|
||||
|
||||
withHeader := fmt.Sprintf("%s%s", fileHeader, strings.Join(document, ""))
|
||||
|
||||
+16
-15
@@ -8,6 +8,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
@@ -190,7 +191,7 @@ func benchMain(args []string, params benchmarkCommandParams, w io.Writer, r benc
|
||||
if err != nil {
|
||||
return err
|
||||
} else if len(result) == 0 && params.fail {
|
||||
return fmt.Errorf("undefined result")
|
||||
return errors.New("undefined result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -207,7 +208,7 @@ func benchMain(args []string, params benchmarkCommandParams, w io.Writer, r benc
|
||||
if err != nil {
|
||||
return err
|
||||
} else if len(result.Queries) == 0 && params.fail {
|
||||
return fmt.Errorf("undefined result")
|
||||
return errors.New("undefined result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -307,7 +308,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams,
|
||||
// We fix the issue here by binding port 0; this will result in the OS
|
||||
// allocating us an open port.
|
||||
rtParams := runtime.Params{
|
||||
Addrs: &[]string{fmt.Sprintf("%s:0", host)},
|
||||
Addrs: &[]string{host + ":0"},
|
||||
Paths: paths,
|
||||
Logger: logger,
|
||||
BundleMode: params.bundlePaths.isFlagSet(),
|
||||
@@ -365,7 +366,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams,
|
||||
}
|
||||
// Check for port still being unbound after retry loop.
|
||||
if port == 0 {
|
||||
return fmt.Errorf("unable to bind a port for bench testing")
|
||||
return errors.New("unable to bind a port for bench testing")
|
||||
}
|
||||
|
||||
query, err := readQuery(params, args)
|
||||
@@ -399,7 +400,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams,
|
||||
} else {
|
||||
_, err := ast.ParseBody(query)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error occurred while parsing query")
|
||||
return errors.New("error occurred while parsing query")
|
||||
}
|
||||
|
||||
if strings.HasPrefix(query, "data.") {
|
||||
@@ -536,7 +537,7 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf
|
||||
}
|
||||
|
||||
if result.Result == nil && params.fail {
|
||||
return nil, fmt.Errorf("undefined result")
|
||||
return nil, errors.New("undefined result")
|
||||
}
|
||||
|
||||
return result.Metrics, nil
|
||||
@@ -549,31 +550,31 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf
|
||||
|
||||
if params.fail {
|
||||
if result.Result == nil {
|
||||
return nil, fmt.Errorf("undefined result")
|
||||
return nil, errors.New("undefined result")
|
||||
}
|
||||
|
||||
i := *result.Result
|
||||
|
||||
peResult, ok := i.(map[string]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid result for compile response")
|
||||
return nil, errors.New("invalid result for compile response")
|
||||
}
|
||||
|
||||
if len(peResult) == 0 {
|
||||
return nil, fmt.Errorf("undefined result")
|
||||
return nil, errors.New("undefined result")
|
||||
}
|
||||
|
||||
if val, ok := peResult["queries"]; ok {
|
||||
queries, ok := val.([]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid result for output of partial evaluation")
|
||||
return nil, errors.New("invalid result for output of partial evaluation")
|
||||
}
|
||||
|
||||
if len(queries) == 0 {
|
||||
return nil, fmt.Errorf("undefined result")
|
||||
return nil, errors.New("undefined result")
|
||||
}
|
||||
} else {
|
||||
return nil, fmt.Errorf("invalid result for output of partial evaluation")
|
||||
return nil, errors.New("invalid result for output of partial evaluation")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -606,14 +607,14 @@ func renderBenchmarkResult(params benchmarkCommandParams, br testing.BenchmarkRe
|
||||
fmt.Fprintf(w, "\n")
|
||||
default:
|
||||
data := [][]string{
|
||||
{"samples", fmt.Sprintf("%d", br.N)},
|
||||
{"samples", strconv.Itoa(br.N)},
|
||||
{"ns/op", prettyFormatFloat(float64(br.T.Nanoseconds()) / float64(br.N))},
|
||||
}
|
||||
if params.benchMem {
|
||||
data = append(data, []string{
|
||||
"B/op", fmt.Sprintf("%d", br.AllocedBytesPerOp()),
|
||||
"B/op", strconv.FormatInt(br.AllocedBytesPerOp(), 10),
|
||||
}, []string{
|
||||
"allocs/op", fmt.Sprintf("%d", br.AllocsPerOp()),
|
||||
"allocs/op", strconv.FormatInt(br.AllocsPerOp(), 10),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -498,7 +498,7 @@ func validateBenchMainPrep(t *testing.T, args []string, params benchmarkCommandP
|
||||
}
|
||||
|
||||
if len(rs) == 0 {
|
||||
return testing.BenchmarkResult{}, fmt.Errorf("expected result, got none")
|
||||
return testing.BenchmarkResult{}, errors.New("expected result, got none")
|
||||
}
|
||||
|
||||
return testing.BenchmarkResult{}, nil
|
||||
|
||||
+3
-2
@@ -7,6 +7,7 @@ package cmd
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -232,7 +233,7 @@ against OPA v0.22.0:
|
||||
`,
|
||||
PreRunE: func(Cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("expected at least one path")
|
||||
return errors.New("expected at least one path")
|
||||
}
|
||||
return env.CmdFlags.CheckEnvironmentVariables(Cmd)
|
||||
},
|
||||
@@ -293,7 +294,7 @@ func dobuild(params buildParams, args []string) error {
|
||||
}
|
||||
|
||||
if (bvc != nil || bsc != nil) && !params.bundleMode {
|
||||
return fmt.Errorf("enable bundle mode (ie. --bundle) to verify or sign bundle files or directories")
|
||||
return errors.New("enable bundle mode (ie. --bundle) to verify or sign bundle files or directories")
|
||||
}
|
||||
|
||||
var capabilities *ast.Capabilities
|
||||
|
||||
+5
-3
@@ -4,12 +4,14 @@ import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -637,7 +639,7 @@ p contains 1
|
||||
f(x) if { p[x] }
|
||||
`,
|
||||
},
|
||||
err: fmt.Errorf("plan compilation requires at least one entrypoint"),
|
||||
err: errors.New("plan compilation requires at least one entrypoint"),
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
@@ -942,7 +944,7 @@ p2 := 2
|
||||
tr := tar.NewReader(gr)
|
||||
|
||||
expManifest := strings.ReplaceAll(tc.manifest, "%REGO_VERSION%",
|
||||
fmt.Sprintf("%d", ast.DefaultRegoVersion.Int()))
|
||||
strconv.Itoa(ast.DefaultRegoVersion.Int()))
|
||||
|
||||
found := false
|
||||
for {
|
||||
@@ -1868,7 +1870,7 @@ q contains 1 if {
|
||||
}
|
||||
expVal = strings.ReplaceAll(expVal, "%ROOT%", root)
|
||||
expVal = strings.ReplaceAll(expVal, "%DEFAULT_REGO_VERSION%",
|
||||
fmt.Sprintf("%d", ast.DefaultRegoVersion.Int()))
|
||||
strconv.Itoa(ast.DefaultRegoVersion.Int()))
|
||||
if string(b) != expVal {
|
||||
t.Fatalf("expected %v:\n\n%v\n\nbut got:\n\n%v", expName, expVal, string(b))
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
@@ -174,7 +175,7 @@ func init() {
|
||||
|
||||
PreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("specify at least one file")
|
||||
return errors.New("specify at least one file")
|
||||
}
|
||||
return env.CmdFlags.CheckEnvironmentVariables(cmd)
|
||||
},
|
||||
|
||||
+2
-2
@@ -155,7 +155,7 @@ func validateEvalParams(p *evalCommandParams, cmdArgs []string) error {
|
||||
|
||||
if p.optimizationLevel > 0 {
|
||||
if len(p.dataPaths.v) > 0 && p.bundlePaths.isFlagSet() {
|
||||
return fmt.Errorf("specify either --data or --bundle flag with optimization level greater than 0")
|
||||
return errors.New("specify either --data or --bundle flag with optimization level greater than 0")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -699,7 +699,7 @@ func setupEval(args []string, params evalCommandParams) (*evalContext, error) {
|
||||
if params.strictBuiltinErrors {
|
||||
regoArgs = append(regoArgs, rego.StrictBuiltinErrors(true))
|
||||
if params.showBuiltinErrors {
|
||||
return nil, fmt.Errorf("cannot use --show-builtin-errors with --strict-builtin-errors, --strict-builtin-errors will return the first built-in error encountered immediately")
|
||||
return nil, errors.New("cannot use --show-builtin-errors with --strict-builtin-errors, --strict-builtin-errors will return the first built-in error encountered immediately")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -619,17 +619,17 @@ func testReadParamWithSchemaDir(input string, inputSchema string) error {
|
||||
}
|
||||
|
||||
if schemaSet == nil {
|
||||
err = fmt.Errorf("Schema set is empty")
|
||||
err = errors.New("Schema set is empty")
|
||||
return
|
||||
}
|
||||
|
||||
if schemaSet.Get(ast.MustParseRef("schema.input")) == nil {
|
||||
err = fmt.Errorf("Expected schema for input in schemaSet but got none")
|
||||
err = errors.New("Expected schema for input in schemaSet but got none")
|
||||
return
|
||||
}
|
||||
|
||||
if schemaSet.Get(ast.MustParseRef(`schema.kubernetes["data-schema"]`)) == nil {
|
||||
err = fmt.Errorf("Expected schemas for data in schemaSet but got none")
|
||||
err = errors.New("Expected schemas for data in schemaSet but got none")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ func runExecWithContext(ctx context.Context, params *exec.Params) error {
|
||||
case <-ctx.Done():
|
||||
err := ctx.Err()
|
||||
if err == context.DeadlineExceeded {
|
||||
return fmt.Errorf("exec error: timed out before OPA was ready. This can happen when a remote bundle is malformed, or the timeout is set too low for normal OPA initialization")
|
||||
return errors.New("exec error: timed out before OPA was ready. This can happen when a remote bundle is malformed, or the timeout is set too low for normal OPA initialization")
|
||||
}
|
||||
// Note(philipc): Previously, exec would simply eat the context
|
||||
// cancellation error. We now propagate that upwards to the caller.
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ func addBenchmemFlag(fs *pflag.FlagSet, benchMem *bool, value bool) {
|
||||
}
|
||||
|
||||
func addCountFlag(fs *pflag.FlagSet, count *int, cmdType string) {
|
||||
fs.IntVar(count, "count", 1, fmt.Sprintf("number of times to repeat each %s", cmdType))
|
||||
fs.IntVar(count, "count", 1, "number of times to repeat each "+cmdType)
|
||||
}
|
||||
|
||||
func addMaxErrorsFlag(fs *pflag.FlagSet, errLimit *int) {
|
||||
|
||||
+3
-2
@@ -6,6 +6,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -150,14 +151,14 @@ func hasManifest(info *ib.Info) bool {
|
||||
|
||||
func validateInspectParams(p *inspectCommandParams, args []string) error {
|
||||
if len(args) != 1 {
|
||||
return fmt.Errorf("specify exactly one OPA bundle or path")
|
||||
return errors.New("specify exactly one OPA bundle or path")
|
||||
}
|
||||
|
||||
of := p.outputFormat.String()
|
||||
if of == evalJSONOutput || of == evalPrettyOutput {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid output format for inspect command")
|
||||
return errors.New("invalid output format for inspect command")
|
||||
}
|
||||
|
||||
func populateManifest(out io.Writer, m *bundle.Manifest) error {
|
||||
|
||||
+2
-2
@@ -1573,7 +1573,7 @@ p = 1`,
|
||||
}
|
||||
|
||||
test.WithTempFS(files, func(rootDir string) {
|
||||
fileName := fmt.Sprintf("%s/a/xxxxxxxxxxxxxxxxxxxxxx/yyyyyyyyyyyyyyyyyyyy/foo.rego", rootDir)
|
||||
fileName := rootDir + "/a/xxxxxxxxxxxxxxxxxxxxxx/yyyyyyyyyyyyyyyyyyyy/foo.rego"
|
||||
ps := newInspectCommandParams()
|
||||
ps.listAnnotations = true
|
||||
var out bytes.Buffer
|
||||
@@ -1730,7 +1730,7 @@ p = 1`,
|
||||
}
|
||||
|
||||
test.WithTempFS(files, func(rootDir string) {
|
||||
fileName := fmt.Sprintf("%s/a/xxxxxxxxxxxxxxxxxxxxxx/yyyyyyyyyyyyyyyyyyyy/foo.rego", rootDir)
|
||||
fileName := rootDir + "/a/xxxxxxxxxxxxxxxxxxxxxx/yyyyyyyyyyyyyyyyyyyy/foo.rego"
|
||||
ps := newInspectCommandParams()
|
||||
var out bytes.Buffer
|
||||
err := doInspect(ps, fileName, &out)
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/open-policy-agent/opa/v1/sdk"
|
||||
@@ -47,7 +47,7 @@ func TestJsonReporter_StoreDecision(t *testing.T) {
|
||||
Name: "should return nil with increased error count if error is raised from decision",
|
||||
Path: testString,
|
||||
DecisionFunc: func(_ context.Context, _ sdk.DecisionOptions) (*sdk.DecisionResult, error) {
|
||||
return nil, fmt.Errorf("test")
|
||||
return nil, errors.New("test")
|
||||
},
|
||||
Params: Params{FailNonEmpty: true},
|
||||
ExpectedErrorCount: 1,
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -55,7 +56,7 @@ var parseCommand = &cobra.Command{
|
||||
Long: `Parse Rego source file and print AST.`,
|
||||
PreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("no source file specified")
|
||||
return errors.New("no source file specified")
|
||||
}
|
||||
return env.CmdFlags.CheckEnvironmentVariables(cmd)
|
||||
},
|
||||
|
||||
+3
-2
@@ -8,6 +8,7 @@ import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
@@ -359,7 +360,7 @@ func initRuntime(ctx context.Context, params runCmdParams, args []string, addrSe
|
||||
params.rt.BundleVerificationConfig = bvc
|
||||
|
||||
if params.rt.BundleVerificationConfig != nil && !params.rt.BundleMode {
|
||||
return nil, fmt.Errorf("enable bundle mode (ie. --bundle) to verify bundle files or directories")
|
||||
return nil, errors.New("enable bundle mode (ie. --bundle) to verify bundle files or directories")
|
||||
}
|
||||
|
||||
params.rt.SkipKnownSchemaCheck = params.skipKnownSchemaCheck
|
||||
@@ -443,7 +444,7 @@ func loadCertificate(tlsCertFile, tlsPrivateKeyFile string) (*tls.Certificate, e
|
||||
}
|
||||
return &cert, nil
|
||||
} else if tlsCertFile != "" || tlsPrivateKeyFile != "" {
|
||||
return nil, fmt.Errorf("--tls-cert-file and --tls-private-key-file must be specified together")
|
||||
return nil, errors.New("--tls-cert-file and --tls-private-key-file must be specified together")
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
|
||||
+4
-3
@@ -8,6 +8,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -37,7 +38,7 @@ const (
|
||||
signaturesFile = ".signatures.json"
|
||||
)
|
||||
|
||||
var errSigningConfigIncomplete = fmt.Errorf("specify the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)")
|
||||
var errSigningConfigIncomplete = errors.New("specify the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)")
|
||||
|
||||
func newSignCmdParams() signCmdParams {
|
||||
return signCmdParams{}
|
||||
@@ -273,7 +274,7 @@ func writeTokenToFile(token, fileLoc string) error {
|
||||
|
||||
func validateSignParams(args []string, params signCmdParams) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("specify atleast one path containing policy and/or data files")
|
||||
return errors.New("specify atleast one path containing policy and/or data files")
|
||||
}
|
||||
|
||||
if params.key == "" {
|
||||
@@ -281,7 +282,7 @@ func validateSignParams(args []string, params signCmdParams) error {
|
||||
}
|
||||
|
||||
if !params.bundleMode {
|
||||
return fmt.Errorf("enable bundle mode (ie. --bundle) to sign bundle files or directories")
|
||||
return errors.New("enable bundle mode (ie. --bundle) to sign bundle files or directories")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+5
-5
@@ -6,7 +6,7 @@ package cmd
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -139,22 +139,22 @@ func TestValidateSignParams(t *testing.T) {
|
||||
"no_args": {
|
||||
[]string{},
|
||||
newSignCmdParams(),
|
||||
true, fmt.Errorf("specify atleast one path containing policy and/or data files"),
|
||||
true, errors.New("specify atleast one path containing policy and/or data files"),
|
||||
},
|
||||
"no_signing_key": {
|
||||
[]string{"foo"},
|
||||
newSignCmdParams(),
|
||||
true, fmt.Errorf("specify the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)"),
|
||||
true, errors.New("specify the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)"),
|
||||
},
|
||||
"empty_signing_key": {
|
||||
[]string{"foo"},
|
||||
signCmdParams{key: "", bundleMode: true},
|
||||
true, fmt.Errorf("specify the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)"),
|
||||
true, errors.New("specify the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)"),
|
||||
},
|
||||
"non_bundle_mode": {
|
||||
[]string{"foo"},
|
||||
signCmdParams{key: "foo"},
|
||||
true, fmt.Errorf("enable bundle mode (ie. --bundle) to sign bundle files or directories"),
|
||||
true, errors.New("enable bundle mode (ie. --bundle) to sign bundle files or directories"),
|
||||
},
|
||||
"no_error": {
|
||||
[]string{"foo"},
|
||||
|
||||
+1
-1
@@ -521,7 +521,7 @@ recommended as some updates might cause them to be dropped by OPA.
|
||||
`,
|
||||
PreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("specify at least one file")
|
||||
return errors.New("specify at least one file")
|
||||
}
|
||||
|
||||
// If an --explain flag was set, turn on verbose output
|
||||
|
||||
@@ -6,6 +6,7 @@ package inspect
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -144,7 +145,7 @@ func (bi *Info) getBundleDataWasmAndSignatures(name string) error {
|
||||
}
|
||||
|
||||
if len(load.BundlesLoader) == 0 || len(load.BundlesLoader) > 1 {
|
||||
return fmt.Errorf("expected information on one bundle only but got none or multiple")
|
||||
return errors.New("expected information on one bundle only but got none or multiple")
|
||||
}
|
||||
|
||||
bl := load.BundlesLoader[0]
|
||||
|
||||
@@ -6,6 +6,7 @@ package bundle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -132,7 +133,7 @@ func SaveBundleToDisk(path string, raw io.Reader) (string, error) {
|
||||
}
|
||||
|
||||
if raw == nil {
|
||||
return "", fmt.Errorf("no raw bundle bytes to persist to disk")
|
||||
return "", errors.New("no raw bundle bytes to persist to disk")
|
||||
}
|
||||
|
||||
dest, err := os.CreateTemp(path, ".bundle.tar.gz.*.tmp")
|
||||
|
||||
@@ -827,7 +827,7 @@ func (c *Compiler) compileFunc(fn *ir.Func) error {
|
||||
memoize := len(fn.Params) == 2
|
||||
|
||||
if len(fn.Params) == 0 {
|
||||
return fmt.Errorf("illegal function: zero args")
|
||||
return errors.New("illegal function: zero args")
|
||||
}
|
||||
|
||||
c.nextLocal = 0
|
||||
@@ -1678,7 +1678,7 @@ func (c *Compiler) genLocal() uint32 {
|
||||
func (c *Compiler) function(name string) uint32 {
|
||||
fidx, ok := c.funcs[name]
|
||||
if !ok {
|
||||
panic(fmt.Sprintf("function not found: %s", name))
|
||||
panic("function not found: " + name)
|
||||
}
|
||||
return fidx
|
||||
}
|
||||
|
||||
@@ -363,7 +363,7 @@ discovery:
|
||||
test.WithTempFS(fs, func(rootDir string) {
|
||||
configFile := filepath.Join(rootDir, "/some/config.yaml")
|
||||
secretFile := filepath.Join(rootDir, "/some/secret.txt")
|
||||
overrideFiles := []string{fmt.Sprintf("services.acmecorp.credentials.bearer.token=%s", secretFile)}
|
||||
overrideFiles := []string{"services.acmecorp.credentials.bearer.token=" + secretFile}
|
||||
|
||||
configBytes, err := Load(configFile, nil, overrideFiles)
|
||||
if err != nil {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -215,7 +216,7 @@ func loadCertificate(tlsCertFile, tlsPrivateKeyFile string) (*tls.Certificate, e
|
||||
}
|
||||
|
||||
if tlsCertFile != "" || tlsPrivateKeyFile != "" {
|
||||
return nil, fmt.Errorf("distributed_tracing.tls_cert_file and distributed_tracing.tls_private_key_file must be specified together")
|
||||
return nil, errors.New("distributed_tracing.tls_cert_file and distributed_tracing.tls_private_key_file must be specified together")
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
@@ -247,7 +248,7 @@ func tlsOption(encryptionScheme string, encryptionSkipVerify bool, cert *tls.Cer
|
||||
}
|
||||
if encryptionScheme == "mtls" {
|
||||
if cert == nil {
|
||||
return nil, fmt.Errorf("distributed_tracing.tls_cert_file required but not supplied")
|
||||
return nil, errors.New("distributed_tracing.tls_cert_file required but not supplied")
|
||||
}
|
||||
tlsConfig.Certificates = []tls.Certificate{*cert}
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@
|
||||
package edittree
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"sort"
|
||||
@@ -335,13 +336,13 @@ func (e *EditTree) deleteChildValue(hash int) {
|
||||
// Insert creates a new child of e, and returns the new child EditTree node.
|
||||
func (e *EditTree) Insert(key, value *ast.Term) (*EditTree, error) {
|
||||
if e.value == nil {
|
||||
return nil, fmt.Errorf("deleted node encountered during insert operation")
|
||||
return nil, errors.New("deleted node encountered during insert operation")
|
||||
}
|
||||
if key == nil {
|
||||
return nil, fmt.Errorf("nil key provided for insert operation")
|
||||
return nil, errors.New("nil key provided for insert operation")
|
||||
}
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("nil value provided for insert operation")
|
||||
return nil, errors.New("nil value provided for insert operation")
|
||||
}
|
||||
|
||||
switch x := e.value.Value.(type) {
|
||||
@@ -367,7 +368,7 @@ func (e *EditTree) Insert(key, value *ast.Term) (*EditTree, error) {
|
||||
return nil, err
|
||||
}
|
||||
if idx < 0 || idx > e.insertions.Length() {
|
||||
return nil, fmt.Errorf("index for array insertion out of bounds")
|
||||
return nil, errors.New("index for array insertion out of bounds")
|
||||
}
|
||||
return e.unsafeInsertArray(idx, value), nil
|
||||
default:
|
||||
@@ -457,10 +458,10 @@ func (e *EditTree) unsafeInsertArray(idx int, value *ast.Term) *EditTree {
|
||||
// already present in e. It then returns the deleted child EditTree node.
|
||||
func (e *EditTree) Delete(key *ast.Term) (*EditTree, error) {
|
||||
if e.value == nil {
|
||||
return nil, fmt.Errorf("deleted node encountered during delete operation")
|
||||
return nil, errors.New("deleted node encountered during delete operation")
|
||||
}
|
||||
if key == nil {
|
||||
return nil, fmt.Errorf("nil key provided for delete operation")
|
||||
return nil, errors.New("nil key provided for delete operation")
|
||||
}
|
||||
|
||||
switch e.value.Value.(type) {
|
||||
@@ -531,7 +532,7 @@ func (e *EditTree) Delete(key *ast.Term) (*EditTree, error) {
|
||||
return nil, err
|
||||
}
|
||||
if idx < 0 || idx > e.insertions.Length()-1 {
|
||||
return nil, fmt.Errorf("index for array delete out of bounds")
|
||||
return nil, errors.New("index for array delete out of bounds")
|
||||
}
|
||||
|
||||
// Collect insertion indexes above the delete site for rewriting.
|
||||
@@ -637,7 +638,7 @@ func (e *EditTree) Unfold(path ast.Ref) (*EditTree, error) {
|
||||
}
|
||||
// 1+ path segment case.
|
||||
if e.value == nil {
|
||||
return nil, fmt.Errorf("nil value encountered where composite value was expected")
|
||||
return nil, errors.New("nil value encountered where composite value was expected")
|
||||
}
|
||||
|
||||
// Switch behavior based on types.
|
||||
@@ -879,7 +880,7 @@ func (e *EditTree) Render() *ast.Term {
|
||||
// Returns the inserted EditTree node.
|
||||
func (e *EditTree) InsertAtPath(path ast.Ref, value *ast.Term) (*EditTree, error) {
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("cannot insert nil value into EditTree")
|
||||
return nil, errors.New("cannot insert nil value into EditTree")
|
||||
}
|
||||
|
||||
if len(path) == 0 {
|
||||
@@ -910,7 +911,7 @@ func (e *EditTree) DeleteAtPath(path ast.Ref) (*EditTree, error) {
|
||||
// Root document case:
|
||||
if len(path) == 0 {
|
||||
if e.value == nil {
|
||||
return nil, fmt.Errorf("deleted node encountered during delete operation")
|
||||
return nil, errors.New("deleted node encountered during delete operation")
|
||||
}
|
||||
e.value = nil
|
||||
e.childKeys = nil
|
||||
@@ -1046,7 +1047,7 @@ func toIndex(arrayLength int, term *ast.Term) (int, error) {
|
||||
switch v := term.Value.(type) {
|
||||
case ast.Number:
|
||||
if i, ok = v.Int(); !ok {
|
||||
return 0, fmt.Errorf("invalid number type for indexing")
|
||||
return 0, errors.New("invalid number type for indexing")
|
||||
}
|
||||
case ast.String:
|
||||
if v == "-" {
|
||||
@@ -1054,13 +1055,13 @@ func toIndex(arrayLength int, term *ast.Term) (int, error) {
|
||||
}
|
||||
num := ast.Number(v)
|
||||
if i, ok = num.Int(); !ok {
|
||||
return 0, fmt.Errorf("invalid string for indexing")
|
||||
return 0, errors.New("invalid string for indexing")
|
||||
}
|
||||
if v != "0" && strings.HasPrefix(string(v), "0") {
|
||||
return 0, fmt.Errorf("leading zeros are not allowed in JSON paths")
|
||||
return 0, errors.New("leading zeros are not allowed in JSON paths")
|
||||
}
|
||||
default:
|
||||
return 0, fmt.Errorf("invalid type for indexing")
|
||||
return 0, errors.New("invalid type for indexing")
|
||||
}
|
||||
|
||||
return i, nil
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package edittree
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -522,7 +523,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": []}`,
|
||||
},
|
||||
source: `"a"`,
|
||||
expError: fmt.Errorf(`deleted node encountered during delete operation`),
|
||||
expError: errors.New(`deleted node encountered during delete operation`),
|
||||
},
|
||||
// Primitive/Scalar error cases.
|
||||
{
|
||||
@@ -531,7 +532,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": "/a", "value": "example"}`,
|
||||
},
|
||||
source: `"a"`,
|
||||
expError: fmt.Errorf(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
expError: errors.New(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
},
|
||||
{
|
||||
note: "nested add on primitive number",
|
||||
@@ -539,7 +540,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": "/1", "value": "example"}`,
|
||||
},
|
||||
source: `2`,
|
||||
expError: fmt.Errorf(`expected composite type, found value: 2 (type: ast.Number)`),
|
||||
expError: errors.New(`expected composite type, found value: 2 (type: ast.Number)`),
|
||||
},
|
||||
{
|
||||
note: "nested remove on primitive string",
|
||||
@@ -547,7 +548,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/a"}`,
|
||||
},
|
||||
source: `"a"`,
|
||||
expError: fmt.Errorf(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
expError: errors.New(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
},
|
||||
{
|
||||
note: "nested remove on primitive number",
|
||||
@@ -555,7 +556,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/1"}`,
|
||||
},
|
||||
source: `2`,
|
||||
expError: fmt.Errorf(`expected composite type, found value: 2 (type: ast.Number)`),
|
||||
expError: errors.New(`expected composite type, found value: 2 (type: ast.Number)`),
|
||||
},
|
||||
{
|
||||
note: "nested remove on nested primitive number",
|
||||
@@ -563,7 +564,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "test", "path": "/a/2/b", "value": 3}`,
|
||||
},
|
||||
source: `{"a": 2}`,
|
||||
expError: fmt.Errorf(`expected composite type for path "2", found value: 2 (type: ast.Number)`),
|
||||
expError: errors.New(`expected composite type for path "2", found value: 2 (type: ast.Number)`),
|
||||
},
|
||||
// Object error cases.
|
||||
{
|
||||
@@ -572,7 +573,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/b"}`,
|
||||
},
|
||||
source: `{"a": {}}`,
|
||||
expError: fmt.Errorf(`cannot delete child key "b" that does not exist`),
|
||||
expError: errors.New(`cannot delete child key "b" that does not exist`),
|
||||
},
|
||||
{
|
||||
note: "add on non-existent nested Object path",
|
||||
@@ -580,7 +581,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": "/b/c", "value": "example"}`,
|
||||
},
|
||||
source: `{"a": {}}`,
|
||||
expError: fmt.Errorf(`path "b" does not exist in object term {"a": {}}`),
|
||||
expError: errors.New(`path "b" does not exist in object term {"a": {}}`),
|
||||
},
|
||||
{
|
||||
note: "remove on non-existent nested Object path",
|
||||
@@ -588,7 +589,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/b/c"}`,
|
||||
},
|
||||
source: `{"a": {}}`,
|
||||
expError: fmt.Errorf(`path "b" does not exist in object term {"a": {}}`),
|
||||
expError: errors.New(`path "b" does not exist in object term {"a": {}}`),
|
||||
},
|
||||
{
|
||||
note: "delete fails on deleted Object path - scalar",
|
||||
@@ -597,7 +598,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/a"}`,
|
||||
},
|
||||
source: `{"a": 2}`,
|
||||
expError: fmt.Errorf(`cannot delete the already deleted scalar node for key "a"`),
|
||||
expError: errors.New(`cannot delete the already deleted scalar node for key "a"`),
|
||||
},
|
||||
{
|
||||
note: "delete fails on deleted Object path - composite",
|
||||
@@ -607,7 +608,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/a"}`,
|
||||
},
|
||||
source: `{}`,
|
||||
expError: fmt.Errorf(`cannot delete the already deleted composite node for key "a"`),
|
||||
expError: errors.New(`cannot delete the already deleted composite node for key "a"`),
|
||||
},
|
||||
{
|
||||
note: "unfold fails on deleted Object path - scalar",
|
||||
@@ -617,7 +618,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "test", "path": "/a", "value": 2}`,
|
||||
},
|
||||
source: `{}`,
|
||||
expError: fmt.Errorf(`cannot unfold the already deleted scalar node for key "a"`),
|
||||
expError: errors.New(`cannot unfold the already deleted scalar node for key "a"`),
|
||||
},
|
||||
{
|
||||
note: "unfold fails on deleted Object path - composite",
|
||||
@@ -627,7 +628,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "test", "path": "/a", "value": 2}`,
|
||||
},
|
||||
source: `{}`,
|
||||
expError: fmt.Errorf(`cannot unfold the already deleted composite node for key "a"`),
|
||||
expError: errors.New(`cannot unfold the already deleted composite node for key "a"`),
|
||||
},
|
||||
// Array error cases.
|
||||
{
|
||||
@@ -636,7 +637,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": "/2", "value": "example"}`,
|
||||
},
|
||||
source: `["a"]`,
|
||||
expError: fmt.Errorf(`index for array insertion out of bounds`),
|
||||
expError: errors.New(`index for array insertion out of bounds`),
|
||||
},
|
||||
{
|
||||
note: "remove on non-existent Array path",
|
||||
@@ -644,7 +645,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/2"}`,
|
||||
},
|
||||
source: `["a"]`,
|
||||
expError: fmt.Errorf(`index for array delete out of bounds`),
|
||||
expError: errors.New(`index for array delete out of bounds`),
|
||||
},
|
||||
{
|
||||
note: "add on non-existent nested Array path",
|
||||
@@ -652,7 +653,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": "/0/2", "value": "example"}`,
|
||||
},
|
||||
source: `["a", [1, 2]]`,
|
||||
expError: fmt.Errorf(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
expError: errors.New(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
},
|
||||
{
|
||||
note: "remove on non-existent nested Array path",
|
||||
@@ -660,7 +661,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/0/1"}`,
|
||||
},
|
||||
source: `["a", [1, 2]]`,
|
||||
expError: fmt.Errorf(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
expError: errors.New(`expected composite type, found value: "a" (type: ast.String)`),
|
||||
},
|
||||
{
|
||||
note: "remove on non-integer number Array path - term array",
|
||||
@@ -668,7 +669,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": [1, 4.3]}`,
|
||||
},
|
||||
source: `["a", [1, 2]]`,
|
||||
expError: fmt.Errorf(`invalid number type for indexing`),
|
||||
expError: errors.New(`invalid number type for indexing`),
|
||||
},
|
||||
{
|
||||
note: "remove on non-integer number Array path - string",
|
||||
@@ -676,7 +677,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/1/4.3"}`,
|
||||
},
|
||||
source: `["a", [1, 2]]`,
|
||||
expError: fmt.Errorf(`invalid string for indexing`),
|
||||
expError: errors.New(`invalid string for indexing`),
|
||||
},
|
||||
{
|
||||
note: "remove using number with 0 prefix in Array path",
|
||||
@@ -684,7 +685,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/1/01"}`,
|
||||
},
|
||||
source: `["a", [1, 2]]`,
|
||||
expError: fmt.Errorf(`leading zeros are not allowed in JSON paths`),
|
||||
expError: errors.New(`leading zeros are not allowed in JSON paths`),
|
||||
},
|
||||
{
|
||||
note: "add with wrong indexing type in Array path",
|
||||
@@ -692,7 +693,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": [1, [0]], "value": 4}`,
|
||||
},
|
||||
source: `["a", [1, 2]]`,
|
||||
expError: fmt.Errorf(`invalid type for indexing`),
|
||||
expError: errors.New(`invalid type for indexing`),
|
||||
},
|
||||
{
|
||||
note: "test on non-existent nested Array path",
|
||||
@@ -702,7 +703,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "test", "path": "/1/2", "value": "example"}`,
|
||||
},
|
||||
source: `[0]`,
|
||||
expError: fmt.Errorf(`expected composite type for path "2", found value: 1 (type: ast.Number)`),
|
||||
expError: errors.New(`expected composite type for path "2", found value: 1 (type: ast.Number)`),
|
||||
},
|
||||
// The "-" index is always one beyond the end of the array, thus the delete case is an error.
|
||||
{
|
||||
@@ -711,7 +712,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "-"}`,
|
||||
},
|
||||
source: `[0, 1, 2]`,
|
||||
expError: fmt.Errorf("index for array delete out of bounds"), // Ref: https://www.rfc-editor.org/rfc/rfc6901, section 4
|
||||
expError: errors.New("index for array delete out of bounds"), // Ref: https://www.rfc-editor.org/rfc/rfc6901, section 4
|
||||
},
|
||||
// Set error cases.
|
||||
{
|
||||
@@ -720,7 +721,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/b"}`,
|
||||
},
|
||||
source: `{"a"}`,
|
||||
expError: fmt.Errorf(`cannot delete child key "b" that does not exist`),
|
||||
expError: errors.New(`cannot delete child key "b" that does not exist`),
|
||||
},
|
||||
{
|
||||
note: "add on non-existent nested Set path",
|
||||
@@ -728,7 +729,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": [{"a", [2, 1]}, [2, 1], 1], "value": {"a"}}`,
|
||||
},
|
||||
source: `{"a"}`,
|
||||
expError: fmt.Errorf(`path {"a", [2, 1]} does not exist in set term {"a"}`),
|
||||
expError: errors.New(`path {"a", [2, 1]} does not exist in set term {"a"}`),
|
||||
},
|
||||
{
|
||||
note: "remove on non-existent nested Set path",
|
||||
@@ -736,7 +737,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": [{"a", [2, 1]}, [2, 1], 0]}`,
|
||||
},
|
||||
source: `{"a"}`,
|
||||
expError: fmt.Errorf(`path {"a", [2, 1]} does not exist in set term {"a"}`),
|
||||
expError: errors.New(`path {"a", [2, 1]} does not exist in set term {"a"}`),
|
||||
},
|
||||
{
|
||||
note: "insert non-matching key value pair into Set",
|
||||
@@ -744,7 +745,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "add", "path": ["b"], "value": "c"}`,
|
||||
},
|
||||
source: `{"a"}`,
|
||||
expError: fmt.Errorf(`set key "b" does not equal value to be inserted "c"`),
|
||||
expError: errors.New(`set key "b" does not equal value to be inserted "c"`),
|
||||
},
|
||||
{
|
||||
note: "delete fails on deleted Set path - scalar",
|
||||
@@ -753,7 +754,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
`{"op": "remove", "path": "/a"}`,
|
||||
},
|
||||
source: `{"a"}`,
|
||||
expError: fmt.Errorf(`cannot delete the already deleted scalar node for key "a"`),
|
||||
expError: errors.New(`cannot delete the already deleted scalar node for key "a"`),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -768,7 +769,7 @@ func TestEditTreeApplyPatches(t *testing.T) {
|
||||
err := patches.Iter(func(term *ast.Term) error {
|
||||
object, ok := term.Value.(ast.Object)
|
||||
if !ok {
|
||||
return fmt.Errorf("must be an array of JSON-Patch objects, but at least one element is not an object")
|
||||
return errors.New("must be an array of JSON-Patch objects, but at least one element is not an object")
|
||||
}
|
||||
patch, err := getPatch(object)
|
||||
if err != nil {
|
||||
@@ -915,7 +916,7 @@ func getPatch(o ast.Object) (jsonPatch, error) {
|
||||
}
|
||||
op, ok := opTerm.Value.(ast.String)
|
||||
if !ok {
|
||||
return out, fmt.Errorf("attribute 'op' must be a string")
|
||||
return out, errors.New("attribute 'op' must be a string")
|
||||
}
|
||||
out.op = string(op)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package future
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/open-policy-agent/opa/v1/ast"
|
||||
@@ -33,7 +34,7 @@ func ParserOptionsFromFutureImports(imports []*ast.Import) (ast.ParserOptions, e
|
||||
}
|
||||
if len(path) == 3 {
|
||||
if imp.Alias != "" {
|
||||
return popts, fmt.Errorf("alias not supported")
|
||||
return popts, errors.New("alias not supported")
|
||||
}
|
||||
popts.FutureKeywords = append(popts.FutureKeywords, string(path[2].Value.(ast.String)))
|
||||
}
|
||||
|
||||
@@ -40,10 +40,10 @@ func (d *dumper) dump(v reflect.Value) {
|
||||
d.WriteString("false")
|
||||
}
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
d.WriteString(fmt.Sprintf("%d", v.Int()))
|
||||
d.WriteString(strconv.FormatInt(v.Int(), 10))
|
||||
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
d.WriteString(fmt.Sprintf("%d", v.Uint()))
|
||||
d.WriteString(strconv.FormatUint(v.Uint(), 10))
|
||||
|
||||
case reflect.Float32, reflect.Float64:
|
||||
d.WriteString(fmt.Sprintf("%.2f", v.Float()))
|
||||
|
||||
@@ -51,7 +51,7 @@ func init() {
|
||||
}
|
||||
var via string
|
||||
if len(fragmentNames) != 0 {
|
||||
via = fmt.Sprintf(" via %s", strings.Join(fragmentNames, ", "))
|
||||
via = " via " + strings.Join(fragmentNames, ", ")
|
||||
}
|
||||
addError(
|
||||
Message(`Cannot spread fragment "%s" within itself%s.`, spreadName, via),
|
||||
|
||||
@@ -2,6 +2,7 @@ package validator
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
@@ -11,7 +12,7 @@ import (
|
||||
"github.com/open-policy-agent/opa/internal/gqlparser/gqlerror"
|
||||
)
|
||||
|
||||
var ErrUnexpectedType = fmt.Errorf("Unexpected Type")
|
||||
var ErrUnexpectedType = errors.New("Unexpected Type")
|
||||
|
||||
// VariableValues coerces and validates variable values
|
||||
func VariableValues(schema *ast.Schema, op *ast.OperationDefinition, variables map[string]interface{}) (map[string]interface{}, error) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package jwk
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
@@ -53,12 +54,12 @@ func (keyOperationList *KeyOperationList) UnmarshalJSON(data []byte) error {
|
||||
var tempKeyOperationList []string
|
||||
err := json.Unmarshal(data, &tempKeyOperationList)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid key operation")
|
||||
return errors.New("invalid key operation")
|
||||
}
|
||||
for _, value := range tempKeyOperationList {
|
||||
_, ok := keyOps[value]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown key operation")
|
||||
return errors.New("unknown key operation")
|
||||
}
|
||||
*keyOperationList = append(*keyOperationList, KeyOperation(value))
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package sign
|
||||
import (
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/open-policy-agent/opa/internal/jwx/jwa"
|
||||
@@ -30,7 +31,7 @@ func GetSigningKey(key string, alg jwa.SignatureAlgorithm) (interface{}, error)
|
||||
case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512:
|
||||
block, _ := pem.Decode([]byte(key))
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("failed to parse PEM block containing the key")
|
||||
return nil, errors.New("failed to parse PEM block containing the key")
|
||||
}
|
||||
|
||||
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
@@ -45,7 +46,7 @@ func GetSigningKey(key string, alg jwa.SignatureAlgorithm) (interface{}, error)
|
||||
case jwa.ES256, jwa.ES384, jwa.ES512:
|
||||
block, _ := pem.Decode([]byte(key))
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("failed to parse PEM block containing the key")
|
||||
return nil, errors.New("failed to parse PEM block containing the key")
|
||||
}
|
||||
|
||||
priv, err := x509.ParseECPrivateKey(block.Bytes)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/open-policy-agent/opa/internal/jwx/jwa"
|
||||
@@ -33,7 +34,7 @@ func GetSigningKey(key string, alg jwa.SignatureAlgorithm) (interface{}, error)
|
||||
case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512, jwa.ES256, jwa.ES384, jwa.ES512:
|
||||
block, _ := pem.Decode([]byte(key))
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("failed to parse PEM block containing the key")
|
||||
return nil, errors.New("failed to parse PEM block containing the key")
|
||||
}
|
||||
|
||||
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
|
||||
@@ -385,7 +385,7 @@ func (p *Planner) planRules(rules []*ast.Rule) (string, error) {
|
||||
return nil
|
||||
})
|
||||
default:
|
||||
return fmt.Errorf("illegal rule kind")
|
||||
return errors.New("illegal rule kind")
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1147,7 +1147,7 @@ func (p *Planner) planExprCallFunc(name string, arity int, void bool, operands [
|
||||
})
|
||||
|
||||
default:
|
||||
return fmt.Errorf("impossible replacement, arity mismatch")
|
||||
return errors.New("impossible replacement, arity mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1173,7 +1173,7 @@ func (p *Planner) planExprCallValue(value *ast.Term, arity int, operands []*ast.
|
||||
})
|
||||
})
|
||||
default:
|
||||
return fmt.Errorf("impossible replacement, arity mismatch")
|
||||
return errors.New("impossible replacement, arity mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1750,7 +1750,7 @@ func (p *Planner) planRef(ref ast.Ref, iter planiter) error {
|
||||
|
||||
head, ok := ref[0].Value.(ast.Var)
|
||||
if !ok {
|
||||
return fmt.Errorf("illegal ref: non-var head")
|
||||
return errors.New("illegal ref: non-var head")
|
||||
}
|
||||
|
||||
if head.Compare(ast.DefaultRootDocument.Value) == 0 {
|
||||
@@ -1767,7 +1767,7 @@ func (p *Planner) planRef(ref ast.Ref, iter planiter) error {
|
||||
|
||||
p.ltarget, ok = p.vars.GetOp(head)
|
||||
if !ok {
|
||||
return fmt.Errorf("illegal ref: unsafe head")
|
||||
return errors.New("illegal ref: unsafe head")
|
||||
}
|
||||
|
||||
return p.planRefRec(ref, 1, iter)
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package planner
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
@@ -1238,7 +1239,7 @@ func findCallDynamic(path []ir.Operand, p interface{}) error {
|
||||
return err
|
||||
}
|
||||
if !w.found {
|
||||
return fmt.Errorf("not found")
|
||||
return errors.New("not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1250,7 +1251,7 @@ func findFunc(name, path string) func(interface{}) error {
|
||||
return err
|
||||
}
|
||||
if !w.found {
|
||||
return fmt.Errorf("not found")
|
||||
return errors.New("not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ package presentation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -410,7 +411,7 @@ func Discard(w io.Writer, x interface{}) error {
|
||||
encoder.SetIndent("", " ")
|
||||
field, ok := x.(Output)
|
||||
if !ok {
|
||||
return fmt.Errorf("error in converting interface to type Output")
|
||||
return errors.New("error in converting interface to type Output")
|
||||
}
|
||||
bs, err := json.Marshal(field)
|
||||
if err != nil {
|
||||
|
||||
@@ -483,7 +483,7 @@ func TestRaw(t *testing.T) {
|
||||
{
|
||||
note: "error",
|
||||
output: Output{
|
||||
Errors: NewOutputErrors(fmt.Errorf("boom")),
|
||||
Errors: NewOutputErrors(errors.New("boom")),
|
||||
},
|
||||
want: "1 error occurred: boom\n",
|
||||
},
|
||||
|
||||
@@ -211,7 +211,7 @@ func allocHandler(rsp http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Query().Get("pretty") == "true" {
|
||||
alloc = prettyByteSize(total)
|
||||
} else {
|
||||
alloc = fmt.Sprintf("%d", total)
|
||||
alloc = strconv.FormatUint(total, 10)
|
||||
}
|
||||
|
||||
rsp.WriteHeader(200)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package crypto
|
||||
|
||||
import "fmt"
|
||||
import "errors"
|
||||
|
||||
// ConstantTimeByteCompare is a constant-time byte comparison of x and y. This function performs an absolute comparison
|
||||
// if the two byte slices assuming they represent a big-endian number.
|
||||
@@ -11,7 +11,7 @@ import "fmt"
|
||||
// +1 if x > y
|
||||
func ConstantTimeByteCompare(x, y []byte) (int, error) {
|
||||
if len(x) != len(y) {
|
||||
return 0, fmt.Errorf("slice lengths do not match")
|
||||
return 0, errors.New("slice lengths do not match")
|
||||
}
|
||||
|
||||
xLarger, yLarger := 0, 0
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"crypto/hmac"
|
||||
"encoding/asn1"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"math"
|
||||
@@ -82,7 +83,7 @@ func HMACKeyDerivation(hash func() hash.Hash, bitLen int, key []byte, label, con
|
||||
|
||||
// verify the requested bit length is not larger then the length encoding size
|
||||
if int64(bitLen) > 0x7FFFFFFF {
|
||||
return nil, fmt.Errorf("bitLen is greater than 32-bits")
|
||||
return nil, errors.New("bitLen is greater than 32-bits")
|
||||
}
|
||||
|
||||
fixedInput := bytes.NewBuffer(nil)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -189,7 +190,7 @@ func SignV4(headers map[string][]string, method string, theURL *url.URL, body []
|
||||
authHeader := "AWS4-HMAC-SHA256 Credential=" + awsCreds.AccessKey + "/" + dateNow
|
||||
authHeader += "/" + awsCreds.RegionName + "/" + service + "/aws4_request,"
|
||||
authHeader += "SignedHeaders=" + headerList + ","
|
||||
authHeader += "Signature=" + fmt.Sprintf("%x", signature)
|
||||
authHeader += "Signature=" + hex.EncodeToString(signature)
|
||||
|
||||
return authHeader, awsHeaders
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"errors"
|
||||
"hash"
|
||||
"io"
|
||||
"math/big"
|
||||
@@ -107,7 +107,7 @@ func deriveKeyFromAccessKeyPair(accessKey, secretKey string) (*ecdsa.PrivateKey,
|
||||
|
||||
counter++
|
||||
if counter > 0xFF {
|
||||
return nil, fmt.Errorf("exhausted single byte external counter")
|
||||
return nil, errors.New("exhausted single byte external counter")
|
||||
}
|
||||
}
|
||||
d = d.Add(d, one)
|
||||
@@ -146,7 +146,7 @@ func retrievePrivateKey(symmetric Credentials) (v4aCredentials, error) {
|
||||
|
||||
privateKey, err := deriveKeyFromAccessKeyPair(symmetric.AccessKey, symmetric.SecretKey)
|
||||
if err != nil {
|
||||
return v4aCredentials{}, fmt.Errorf("failed to derive asymmetric key from credentials")
|
||||
return v4aCredentials{}, errors.New("failed to derive asymmetric key from credentials")
|
||||
}
|
||||
|
||||
creds := v4aCredentials{
|
||||
|
||||
@@ -7,6 +7,7 @@ package encoding
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
@@ -105,7 +106,7 @@ func readMagic(r io.Reader) error {
|
||||
if err := binary.Read(r, binary.LittleEndian, &v); err != nil {
|
||||
return err
|
||||
} else if v != constant.Magic {
|
||||
return fmt.Errorf("illegal magic value")
|
||||
return errors.New("illegal magic value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -115,7 +116,7 @@ func readVersion(r io.Reader) error {
|
||||
if err := binary.Read(r, binary.LittleEndian, &v); err != nil {
|
||||
return err
|
||||
} else if v != constant.Version {
|
||||
return fmt.Errorf("illegal wasm version")
|
||||
return errors.New("illegal wasm version")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -199,7 +200,7 @@ func readSections(r io.Reader, m *module.Module) error {
|
||||
return fmt.Errorf("code section: %w", err)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("illegal section id")
|
||||
return errors.New("illegal section id")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -374,7 +375,7 @@ func readTableSection(r io.Reader, s *module.TableSection) error {
|
||||
if elem, err := readByte(r); err != nil {
|
||||
return err
|
||||
} else if elem != constant.ElementTypeAnyFunc {
|
||||
return fmt.Errorf("illegal element type")
|
||||
return errors.New("illegal element type")
|
||||
}
|
||||
|
||||
table.Type = types.Anyfunc
|
||||
@@ -547,7 +548,7 @@ func readGlobal(r io.Reader, global *module.Global) error {
|
||||
if b == 1 {
|
||||
global.Mutable = true
|
||||
} else if b != 0 {
|
||||
return fmt.Errorf("illegal mutability flag")
|
||||
return errors.New("illegal mutability flag")
|
||||
}
|
||||
|
||||
return readConstantExpr(r, &global.Init)
|
||||
@@ -584,7 +585,7 @@ func readImport(r io.Reader, imp *module.Import) error {
|
||||
if elem, err := readByte(r); err != nil {
|
||||
return err
|
||||
} else if elem != constant.ElementTypeAnyFunc {
|
||||
return fmt.Errorf("illegal element type")
|
||||
return errors.New("illegal element type")
|
||||
}
|
||||
desc := module.TableImport{
|
||||
Type: types.Anyfunc,
|
||||
@@ -617,12 +618,12 @@ func readImport(r io.Reader, imp *module.Import) error {
|
||||
if b == 1 {
|
||||
desc.Mutable = true
|
||||
} else if b != 0 {
|
||||
return fmt.Errorf("illegal mutability flag")
|
||||
return errors.New("illegal mutability flag")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("illegal import descriptor type")
|
||||
return errors.New("illegal import descriptor type")
|
||||
}
|
||||
|
||||
func readExport(r io.Reader, exp *module.Export) error {
|
||||
@@ -646,7 +647,7 @@ func readExport(r io.Reader, exp *module.Export) error {
|
||||
case constant.ExportDescGlobal:
|
||||
exp.Descriptor.Type = module.GlobalExportType
|
||||
default:
|
||||
return fmt.Errorf("illegal export descriptor type")
|
||||
return errors.New("illegal export descriptor type")
|
||||
}
|
||||
|
||||
exp.Descriptor.Index, err = leb128.ReadVarUint32(r)
|
||||
@@ -727,7 +728,7 @@ func readExpr(r io.Reader, expr *module.Expr) (err error) {
|
||||
case error:
|
||||
err = r
|
||||
default:
|
||||
err = fmt.Errorf("unknown panic")
|
||||
err = errors.New("unknown panic")
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -823,7 +824,7 @@ func readLimits(r io.Reader, l *module.Limit) error {
|
||||
}
|
||||
l.Max = &maxLim
|
||||
} else if b != 0 {
|
||||
return fmt.Errorf("illegal limit flag")
|
||||
return errors.New("illegal limit flag")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -7,6 +7,7 @@ package encoding
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
@@ -260,7 +261,7 @@ func writeTableSection(w io.Writer, s module.TableSection) error {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("illegal table element type")
|
||||
return errors.New("illegal table element type")
|
||||
}
|
||||
if err := writeLimits(&buf, table.Lim); err != nil {
|
||||
return err
|
||||
@@ -588,7 +589,7 @@ func writeImport(w io.Writer, imp module.Import) error {
|
||||
}
|
||||
return writeByte(w, constant.Const)
|
||||
default:
|
||||
return fmt.Errorf("illegal import descriptor type")
|
||||
return errors.New("illegal import descriptor type")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -276,7 +276,7 @@ func getABIVersion(i *wasmtime.Instance, store wasmtime.Storelike) (int32, int32
|
||||
return majorVal.I32(), minorVal.I32(), nil
|
||||
}
|
||||
}
|
||||
return 0, 0, fmt.Errorf("failed to read ABI version")
|
||||
return 0, 0, errors.New("failed to read ABI version")
|
||||
}
|
||||
|
||||
// Eval performs an evaluation of the specified entrypoint, with any provided
|
||||
|
||||
@@ -6,6 +6,7 @@ package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
@@ -14,7 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/open-policy-agent/opa/internal/wasm/sdk/opa"
|
||||
"github.com/open-policy-agent/opa/internal/wasm/sdk/opa/errors"
|
||||
werrors "github.com/open-policy-agent/opa/internal/wasm/sdk/opa/errors"
|
||||
"github.com/open-policy-agent/opa/v1/bundle"
|
||||
"github.com/open-policy-agent/opa/v1/util"
|
||||
)
|
||||
@@ -82,7 +83,7 @@ func (l *Loader) Init() (*Loader, error) {
|
||||
}
|
||||
|
||||
if l.url == "" {
|
||||
return nil, errors.New(errors.InvalidConfigErr, "missing url")
|
||||
return nil, werrors.New(werrors.InvalidConfigErr, "missing url")
|
||||
}
|
||||
|
||||
l.initialized = true
|
||||
@@ -93,7 +94,7 @@ func (l *Loader) Init() (*Loader, error) {
|
||||
// successful download. If cancelled, will return context.Cancelled.
|
||||
func (l *Loader) Start(ctx context.Context) error {
|
||||
if !l.initialized {
|
||||
return errors.New(errors.NotReadyErr, "")
|
||||
return werrors.New(werrors.NotReadyErr, "")
|
||||
}
|
||||
|
||||
if err := l.download(ctx); err != nil {
|
||||
@@ -183,7 +184,7 @@ func (l *Loader) download(ctx context.Context) error {
|
||||
// SetPolicyData of OPA returns.
|
||||
func (l *Loader) Load(ctx context.Context) error {
|
||||
if !l.initialized {
|
||||
return errors.New(errors.NotReadyErr, "")
|
||||
return werrors.New(werrors.NotReadyErr, "")
|
||||
}
|
||||
|
||||
l.mutex.Lock()
|
||||
@@ -191,11 +192,11 @@ func (l *Loader) Load(ctx context.Context) error {
|
||||
|
||||
bundle, err := l.get(ctx, "")
|
||||
if err != nil {
|
||||
return errors.New(errors.InvalidBundleErr, err.Error())
|
||||
return werrors.New(werrors.InvalidBundleErr, err.Error())
|
||||
}
|
||||
|
||||
if len(bundle.WasmModules) == 0 {
|
||||
return errors.New(errors.InvalidBundleErr, "missing wasm")
|
||||
return werrors.New(werrors.InvalidBundleErr, "missing wasm")
|
||||
}
|
||||
|
||||
var data *interface{}
|
||||
@@ -245,11 +246,11 @@ func (l *Loader) get(ctx context.Context, tag string) (*bundle.Bundle, error) {
|
||||
case http.StatusNotModified:
|
||||
return nil, nil
|
||||
case http.StatusUnauthorized:
|
||||
return nil, fmt.Errorf("not authorized (401)")
|
||||
return nil, errors.New("not authorized (401)")
|
||||
case http.StatusForbidden:
|
||||
return nil, fmt.Errorf("forbidden (403)")
|
||||
return nil, errors.New("forbidden (403)")
|
||||
case http.StatusNotFound:
|
||||
return nil, fmt.Errorf("not found (404)")
|
||||
return nil, errors.New("not found (404)")
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown HTTP status %v", resp.StatusCode)
|
||||
}
|
||||
|
||||
+1
-1
@@ -1069,7 +1069,7 @@ func (r *RefErrInvalidDetail) Lines() []string {
|
||||
lines := []string{r.Ref.String()}
|
||||
offset := len(r.Ref[:r.Pos].String()) + 1
|
||||
pad := strings.Repeat(" ", offset)
|
||||
lines = append(lines, fmt.Sprintf("%s^", pad))
|
||||
lines = append(lines, pad+"^")
|
||||
if r.Have != nil {
|
||||
lines = append(lines, fmt.Sprintf("%shave (type): %v", pad, r.Have))
|
||||
} else {
|
||||
|
||||
@@ -1233,7 +1233,7 @@ func TestFunctionsTypeInference(t *testing.T) {
|
||||
`corge(x) = y if { qux({"bar": x, "foo": x}, a); baz([a["{5: true}"], "BUZ"], y) }`,
|
||||
}
|
||||
body := strings.Join(functions, "\n")
|
||||
base := fmt.Sprintf("package base\n%s", body)
|
||||
base := "package base\n" + body
|
||||
|
||||
popts := ParserOptions{AllFutureKeywords: true}
|
||||
|
||||
@@ -1306,7 +1306,7 @@ func TestFunctionsTypeInference(t *testing.T) {
|
||||
|
||||
for n, test := range tests {
|
||||
t.Run(fmt.Sprintf("Test Case %d", n), func(t *testing.T) {
|
||||
mod := MustParseModuleWithOpts(fmt.Sprintf("package test\n%s", test.body), popts)
|
||||
mod := MustParseModuleWithOpts("package test\n"+test.body, popts)
|
||||
c := NewCompiler()
|
||||
c.Compile(map[string]*Module{"base": MustParseModuleWithOpts(base, popts), "mod": mod})
|
||||
if test.wantErr && !c.Failed() {
|
||||
|
||||
+5
-5
@@ -1351,7 +1351,7 @@ func compileSchema(goSchema interface{}, allowNet []string) (*gojsonschema.Schem
|
||||
if goSchema != nil {
|
||||
refLoader = gojsonschema.NewGoLoader(goSchema)
|
||||
} else {
|
||||
return nil, fmt.Errorf("no schema as input to compile")
|
||||
return nil, errors.New("no schema as input to compile")
|
||||
}
|
||||
schemasCompiled, err := sl.Compile(refLoader)
|
||||
if err != nil {
|
||||
@@ -1370,13 +1370,13 @@ func mergeSchemas(schemas ...*gojsonschema.SubSchema) (*gojsonschema.SubSchema,
|
||||
if len(schemas[i].PropertiesChildren) > 0 {
|
||||
if !schemas[i].Types.Contains("object") {
|
||||
if err := schemas[i].Types.Add("object"); err != nil {
|
||||
return nil, fmt.Errorf("unable to set the type in schemas")
|
||||
return nil, errors.New("unable to set the type in schemas")
|
||||
}
|
||||
}
|
||||
} else if len(schemas[i].ItemsChildren) > 0 {
|
||||
if !schemas[i].Types.Contains("array") {
|
||||
if err := schemas[i].Types.Add("array"); err != nil {
|
||||
return nil, fmt.Errorf("unable to set the type in schemas")
|
||||
return nil, errors.New("unable to set the type in schemas")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1393,7 +1393,7 @@ func mergeSchemas(schemas ...*gojsonschema.SubSchema) (*gojsonschema.SubSchema,
|
||||
result.ItemsChildren = append(result.ItemsChildren, schemas[i].ItemsChildren[j])
|
||||
}
|
||||
if result.ItemsChildren[j].Types.String() != schemas[i].ItemsChildren[j].Types.String() {
|
||||
return nil, fmt.Errorf("unable to merge these schemas")
|
||||
return nil, errors.New("unable to merge these schemas")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1482,7 +1482,7 @@ func (parser *schemaParser) parseSchemaWithPropertyKey(schema interface{}, prope
|
||||
}
|
||||
return parser.parseSchema(objectOrArrayResult)
|
||||
} else if subSchema.Types.String() != allOfResult.Types.String() {
|
||||
return nil, fmt.Errorf("unable to merge these schemas")
|
||||
return nil, errors.New("unable to merge these schemas")
|
||||
}
|
||||
}
|
||||
return parser.parseSchema(allOfResult)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package ast
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -19,7 +19,7 @@ func BenchmarkRewriteDynamics(b *testing.B) {
|
||||
queries := makeQueriesForRewriteDynamicsBenchmark(sizes, body)
|
||||
|
||||
for i := range sizes {
|
||||
b.Run(fmt.Sprint(sizes[i]), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(sizes[i]), func(b *testing.B) {
|
||||
factory := newEqualityFactory(newLocalVarGenerator("q", nil))
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
|
||||
+40
-39
@@ -13,6 +13,7 @@ import (
|
||||
"reflect"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -445,8 +446,8 @@ func TestCompilerGetExports(t *testing.T) {
|
||||
t.Run(tc.note, func(t *testing.T) {
|
||||
c := NewCompiler()
|
||||
for i, m := range tc.modules {
|
||||
c.Modules[fmt.Sprint(i)] = m
|
||||
c.sorted = append(c.sorted, fmt.Sprint(i))
|
||||
c.Modules[strconv.Itoa(i)] = m
|
||||
c.sorted = append(c.sorted, strconv.Itoa(i))
|
||||
}
|
||||
if exp, act := hashMap(tc.exports), c.getExports(); !exp.Equal(act) {
|
||||
t.Errorf("expected %v, got %v", exp, act)
|
||||
@@ -602,7 +603,7 @@ func TestCompilerCheckRuleHeadRefs(t *testing.T) {
|
||||
t.Run(tc.note, func(t *testing.T) {
|
||||
mods := make(map[string]*Module, len(tc.modules))
|
||||
for i, m := range tc.modules {
|
||||
mods[fmt.Sprint(i)] = m
|
||||
mods[strconv.Itoa(i)] = m
|
||||
}
|
||||
c := NewCompiler()
|
||||
c.Modules = mods
|
||||
@@ -739,8 +740,8 @@ func TestRuleTreeWithDotsInHeads(t *testing.T) {
|
||||
t.Run(tc.note, func(t *testing.T) {
|
||||
c := NewCompiler()
|
||||
for i, m := range tc.modules {
|
||||
c.Modules[fmt.Sprint(i)] = m
|
||||
c.sorted = append(c.sorted, fmt.Sprint(i))
|
||||
c.Modules[strconv.Itoa(i)] = m
|
||||
c.sorted = append(c.sorted, strconv.Itoa(i))
|
||||
}
|
||||
compileStages(c, c.setRuleTree)
|
||||
if len(c.Errors) > 0 {
|
||||
@@ -818,8 +819,8 @@ func TestRuleIndices(t *testing.T) {
|
||||
t.Run(tc.note, func(t *testing.T) {
|
||||
c := NewCompiler()
|
||||
for i, m := range tc.modules {
|
||||
c.Modules[fmt.Sprint(i)] = m
|
||||
c.sorted = append(c.sorted, fmt.Sprint(i))
|
||||
c.Modules[strconv.Itoa(i)] = m
|
||||
c.sorted = append(c.sorted, strconv.Itoa(i))
|
||||
}
|
||||
compileStages(c, c.buildRuleIndices)
|
||||
|
||||
@@ -1962,7 +1963,7 @@ p[r] := 2 if { r := "foo" }`,
|
||||
if slices.Equal(path, []string{"badrules", "dataoverlap", "p"}) {
|
||||
return true, nil
|
||||
} else if slices.Equal(path, []string{"badrules", "existserr", "p"}) {
|
||||
return false, fmt.Errorf("unexpected error")
|
||||
return false, errors.New("unexpected error")
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
@@ -2009,7 +2010,7 @@ p if { true }`,
|
||||
if slices.Contains(path, "dataoverlap") {
|
||||
return true, nil
|
||||
} else if slices.Equal(path, []string{"badrules", "existserr", "p"}) {
|
||||
return false, fmt.Errorf("unexpected error")
|
||||
return false, errors.New("unexpected error")
|
||||
}
|
||||
return false, nil
|
||||
}).WithPathConflictsCheckRoots([]string{"badrules"})
|
||||
@@ -2045,7 +2046,7 @@ func TestCompilerCheckRuleConflictsDefaultFunction(t *testing.T) {
|
||||
t.Run(tc.note, func(t *testing.T) {
|
||||
mods := make(map[string]*Module, len(tc.modules))
|
||||
for i, m := range tc.modules {
|
||||
mods[fmt.Sprint(i)] = m
|
||||
mods[strconv.Itoa(i)] = m
|
||||
}
|
||||
c := NewCompiler()
|
||||
c.Modules = mods
|
||||
@@ -2291,7 +2292,7 @@ func TestCompilerCheckRuleConflictsDotsInRuleHeads(t *testing.T) {
|
||||
t.Run(tc.note, func(t *testing.T) {
|
||||
mods := make(map[string]*Module, len(tc.modules))
|
||||
for i, m := range tc.modules {
|
||||
mods[fmt.Sprint(i)] = m
|
||||
mods[strconv.Itoa(i)] = m
|
||||
}
|
||||
c := NewCompiler()
|
||||
c.Modules = mods
|
||||
@@ -2357,7 +2358,7 @@ func TestCompilerCheckRulePkgConflicts(t *testing.T) {
|
||||
t.Run(tc.note, func(t *testing.T) {
|
||||
mods := make(map[string]*Module, len(tc.modules))
|
||||
for i, m := range tc.modules {
|
||||
mods[fmt.Sprint(i)] = m
|
||||
mods[strconv.Itoa(i)] = m
|
||||
}
|
||||
c := NewCompiler()
|
||||
c.Modules = mods
|
||||
@@ -5523,7 +5524,7 @@ func TestCompilerRewriteLocalAssignments(t *testing.T) {
|
||||
}
|
||||
|
||||
for i, tc := range tests {
|
||||
t.Run(fmt.Sprint(i), func(t *testing.T) {
|
||||
t.Run(strconv.Itoa(i), func(t *testing.T) {
|
||||
setRegoVersion := func(po ParserOptions) ParserOptions {
|
||||
po.RegoVersion = tc.regoVersion
|
||||
return po
|
||||
@@ -7039,7 +7040,7 @@ func TestCompilerRewriteWithValue(t *testing.T) {
|
||||
{
|
||||
note: "invalid target",
|
||||
input: `p if { true with foo.q as 1 }`,
|
||||
wantErr: fmt.Errorf("rego_type_error: with keyword target must reference existing input, data, or a function"),
|
||||
wantErr: errors.New("rego_type_error: with keyword target must reference existing input, data, or a function"),
|
||||
},
|
||||
{
|
||||
note: "built-in function: replaced by (unknown) var",
|
||||
@@ -7130,7 +7131,7 @@ func TestCompilerRewriteWithValue(t *testing.T) {
|
||||
p if { q with is_object as http.send }
|
||||
`,
|
||||
opts: func(c *Compiler) *Compiler { return c.WithUnsafeBuiltins(map[string]struct{}{"http.send": {}}) },
|
||||
wantErr: fmt.Errorf("rego_compile_error: with keyword replacing built-in function: target must not be unsafe: \"http.send\""),
|
||||
wantErr: errors.New("rego_compile_error: with keyword replacing built-in function: target must not be unsafe: \"http.send\""),
|
||||
},
|
||||
{
|
||||
note: "non-built-in function: replaced by another built-in that's marked unsafe",
|
||||
@@ -7141,7 +7142,7 @@ func TestCompilerRewriteWithValue(t *testing.T) {
|
||||
q with r as http.send
|
||||
}`,
|
||||
opts: func(c *Compiler) *Compiler { return c.WithUnsafeBuiltins(map[string]struct{}{"http.send": {}}) },
|
||||
wantErr: fmt.Errorf("rego_compile_error: with keyword replacing built-in function: target must not be unsafe: \"http.send\""),
|
||||
wantErr: errors.New("rego_compile_error: with keyword replacing built-in function: target must not be unsafe: \"http.send\""),
|
||||
},
|
||||
{
|
||||
note: "built-in function: valid, arity 1, non-compound name",
|
||||
@@ -9043,7 +9044,7 @@ func TestCompileCustomBuiltins(t *testing.T) {
|
||||
func TestCompilerLazyLoadingError(t *testing.T) {
|
||||
|
||||
testLoader := func(map[string]*Module) (map[string]*Module, error) {
|
||||
return nil, fmt.Errorf("something went horribly wrong")
|
||||
return nil, errors.New("something went horribly wrong")
|
||||
}
|
||||
|
||||
compiler := NewCompiler().WithModuleLoader(testLoader)
|
||||
@@ -9763,17 +9764,17 @@ func TestQueryCompiler(t *testing.T) {
|
||||
{
|
||||
note: "empty query",
|
||||
q: " \t \n # foo \n",
|
||||
expected: fmt.Errorf("1 error occurred: rego_compile_error: empty query cannot be compiled"),
|
||||
expected: errors.New("1 error occurred: rego_compile_error: empty query cannot be compiled"),
|
||||
},
|
||||
{
|
||||
note: "invalid eq",
|
||||
q: "eq()",
|
||||
expected: fmt.Errorf("1 error occurred: 1:1: rego_type_error: eq: arity mismatch\n\thave: ()\n\twant: (any, any)"),
|
||||
expected: errors.New("1 error occurred: 1:1: rego_type_error: eq: arity mismatch\n\thave: ()\n\twant: (any, any)"),
|
||||
},
|
||||
{
|
||||
note: "invalid eq",
|
||||
q: "eq(1)",
|
||||
expected: fmt.Errorf("1 error occurred: 1:1: rego_type_error: eq: arity mismatch\n\thave: (number)\n\twant: (any, any)"),
|
||||
expected: errors.New("1 error occurred: 1:1: rego_type_error: eq: arity mismatch\n\thave: (number)\n\twant: (any, any)"),
|
||||
},
|
||||
{
|
||||
note: "rewrite assignment",
|
||||
@@ -9808,12 +9809,12 @@ func TestQueryCompiler(t *testing.T) {
|
||||
q: "z",
|
||||
pkg: "",
|
||||
imports: nil,
|
||||
expected: fmt.Errorf("1 error occurred: 1:1: rego_unsafe_var_error: var z is unsafe"),
|
||||
expected: errors.New("1 error occurred: 1:1: rego_unsafe_var_error: var z is unsafe"),
|
||||
},
|
||||
{
|
||||
note: "unsafe var that is a future keyword",
|
||||
q: "1 in 2",
|
||||
expected: fmt.Errorf("1 error occurred: 1:3: rego_unsafe_var_error: var in is unsafe (hint: `import future.keywords.in` to import a future keyword)"),
|
||||
expected: errors.New("1 error occurred: 1:3: rego_unsafe_var_error: var in is unsafe (hint: `import future.keywords.in` to import a future keyword)"),
|
||||
regoVersion: RegoV0,
|
||||
},
|
||||
{
|
||||
@@ -9821,7 +9822,7 @@ func TestQueryCompiler(t *testing.T) {
|
||||
q: "[1 | some x; x == 1]",
|
||||
pkg: "",
|
||||
imports: nil,
|
||||
expected: fmt.Errorf("1 error occurred: 1:14: rego_unsafe_var_error: var x is unsafe"),
|
||||
expected: errors.New("1 error occurred: 1:14: rego_unsafe_var_error: var x is unsafe"),
|
||||
},
|
||||
{
|
||||
note: "safe vars",
|
||||
@@ -9842,7 +9843,7 @@ func TestQueryCompiler(t *testing.T) {
|
||||
q: "x = 1 with foo.p as null",
|
||||
pkg: "",
|
||||
imports: nil,
|
||||
expected: fmt.Errorf("1 error occurred: 1:12: rego_type_error: with keyword target must reference existing input, data, or a function"),
|
||||
expected: errors.New("1 error occurred: 1:12: rego_type_error: with keyword target must reference existing input, data, or a function"),
|
||||
},
|
||||
{
|
||||
note: "rewrite with value",
|
||||
@@ -9856,33 +9857,33 @@ func TestQueryCompiler(t *testing.T) {
|
||||
q: `startswith("x")`,
|
||||
pkg: "",
|
||||
imports: nil,
|
||||
expected: fmt.Errorf("1 error occurred: 1:1: rego_type_error: startswith: arity mismatch\n\thave: (string)\n\twant: (search: string, base: string)"),
|
||||
expected: errors.New("1 error occurred: 1:1: rego_type_error: startswith: arity mismatch\n\thave: (string)\n\twant: (search: string, base: string)"),
|
||||
},
|
||||
{
|
||||
note: "built-in function arity mismatch (arity 0)",
|
||||
q: `x := opa.runtime("foo")`,
|
||||
pkg: "",
|
||||
imports: nil,
|
||||
expected: fmt.Errorf("1 error occurred: 1:6: rego_type_error: opa.runtime: arity mismatch\n\thave: (string, ???)\n\twant: ()"),
|
||||
expected: errors.New("1 error occurred: 1:6: rego_type_error: opa.runtime: arity mismatch\n\thave: (string, ???)\n\twant: ()"),
|
||||
},
|
||||
{
|
||||
note: "built-in function arity mismatch, nested",
|
||||
q: "count(sum())",
|
||||
pkg: "",
|
||||
imports: nil,
|
||||
expected: fmt.Errorf("1 error occurred: 1:7: rego_type_error: sum: arity mismatch\n\thave: (???)\n\twant: (collection: any<array[number], set[number]>)"),
|
||||
expected: errors.New("1 error occurred: 1:7: rego_type_error: sum: arity mismatch\n\thave: (???)\n\twant: (collection: any<array[number], set[number]>)"),
|
||||
},
|
||||
{
|
||||
note: "check types",
|
||||
q: "x = data.a.b.c.z; y = null; x = y",
|
||||
pkg: "",
|
||||
imports: nil,
|
||||
expected: fmt.Errorf("match error\n\tleft : number\n\tright : null"),
|
||||
expected: errors.New("match error\n\tleft : number\n\tright : null"),
|
||||
},
|
||||
{
|
||||
note: "undefined function",
|
||||
q: "data.deadbeef(x)",
|
||||
expected: fmt.Errorf("rego_type_error: undefined function data.deadbeef"),
|
||||
expected: errors.New("rego_type_error: undefined function data.deadbeef"),
|
||||
},
|
||||
{
|
||||
note: "imports resolved without package",
|
||||
@@ -9894,7 +9895,7 @@ func TestQueryCompiler(t *testing.T) {
|
||||
{
|
||||
note: "void call used as value",
|
||||
q: "x = print(1)",
|
||||
expected: fmt.Errorf("rego_type_error: print(1) used as value"),
|
||||
expected: errors.New("rego_type_error: print(1) used as value"),
|
||||
},
|
||||
{
|
||||
note: "print call erasure",
|
||||
@@ -10085,12 +10086,12 @@ func TestQueryCompilerWithDeprecatedBuiltins(t *testing.T) {
|
||||
{
|
||||
note: "all() built-in",
|
||||
query: "all([true, false])",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:1: rego_type_error: deprecated built-in function calls in expression: all"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:1: rego_type_error: deprecated built-in function calls in expression: all"),
|
||||
},
|
||||
{
|
||||
note: "any() built-in",
|
||||
query: "any([true, false])",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:1: rego_type_error: deprecated built-in function calls in expression: any"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:1: rego_type_error: deprecated built-in function calls in expression: any"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -10102,22 +10103,22 @@ func TestQueryCompilerWithUnusedAssignedVar(t *testing.T) {
|
||||
{
|
||||
note: "array comprehension",
|
||||
query: "[1 | x := 2]",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:6: rego_compile_error: assigned var x unused"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:6: rego_compile_error: assigned var x unused"),
|
||||
},
|
||||
{
|
||||
note: "set comprehension",
|
||||
query: "{1 | x := 2}",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:6: rego_compile_error: assigned var x unused"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:6: rego_compile_error: assigned var x unused"),
|
||||
},
|
||||
{
|
||||
note: "object comprehension",
|
||||
query: "{1: 2 | x := 2}",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:9: rego_compile_error: assigned var x unused"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:9: rego_compile_error: assigned var x unused"),
|
||||
},
|
||||
{
|
||||
note: "every: unused var in body",
|
||||
query: "every _ in [] { x := 10 }",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:17: rego_compile_error: assigned var x unused"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:17: rego_compile_error: assigned var x unused"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -10129,17 +10130,17 @@ func TestQueryCompilerCheckKeywordOverrides(t *testing.T) {
|
||||
{
|
||||
note: "input assigned",
|
||||
query: "input := 1",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:1: rego_compile_error: variables must not shadow input (use a different variable name)"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:1: rego_compile_error: variables must not shadow input (use a different variable name)"),
|
||||
},
|
||||
{
|
||||
note: "data assigned",
|
||||
query: "data := 1",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:1: rego_compile_error: variables must not shadow data (use a different variable name)"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:1: rego_compile_error: variables must not shadow data (use a different variable name)"),
|
||||
},
|
||||
{
|
||||
note: "nested input assigned",
|
||||
query: "d := [input | input := 1]",
|
||||
expectedErrors: fmt.Errorf("1 error occurred: 1:15: rego_compile_error: variables must not shadow input (use a different variable name)"),
|
||||
expectedErrors: errors.New("1 error occurred: 1:15: rego_compile_error: variables must not shadow input (use a different variable name)"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -7,6 +7,7 @@ package ast
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -92,9 +93,9 @@ func (e *Error) Error() string {
|
||||
if e.Location != nil {
|
||||
|
||||
if len(e.Location.File) > 0 {
|
||||
prefix += e.Location.File + ":" + fmt.Sprint(e.Location.Row)
|
||||
prefix += e.Location.File + ":" + strconv.Itoa(e.Location.Row)
|
||||
} else {
|
||||
prefix += fmt.Sprint(e.Location.Row) + ":" + fmt.Sprint(e.Location.Col)
|
||||
prefix += strconv.Itoa(e.Location.Row) + ":" + strconv.Itoa(e.Location.Col)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
package ast
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -28,7 +28,7 @@ func (r testResolver) Resolve(ref Ref) (Value, error) {
|
||||
return nil, UnknownValueErr{}
|
||||
}
|
||||
if ref.Equal(r.failRef) {
|
||||
return nil, fmt.Errorf("some error")
|
||||
return nil, errors.New("some error")
|
||||
}
|
||||
if ref.HasPrefix(InputRootRef) {
|
||||
v, err := r.input.Value.Find(ref[1:])
|
||||
|
||||
+11
-10
@@ -7,6 +7,7 @@ package ast
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
@@ -2354,7 +2355,7 @@ func (b *metadataParser) Parse() (*Annotations, error) {
|
||||
var raw rawAnnotation
|
||||
|
||||
if len(bytes.TrimSpace(b.buf.Bytes())) == 0 {
|
||||
return nil, fmt.Errorf("expected METADATA block, found whitespace")
|
||||
return nil, errors.New("expected METADATA block, found whitespace")
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(b.buf.Bytes(), &raw); err != nil {
|
||||
@@ -2403,7 +2404,7 @@ func (b *metadataParser) Parse() (*Annotations, error) {
|
||||
|
||||
a.Path, err = ParseRef(k)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid document reference")
|
||||
return nil, errors.New("invalid document reference")
|
||||
}
|
||||
|
||||
switch v := v.(type) {
|
||||
@@ -2503,7 +2504,7 @@ func unwrapPair(pair map[string]interface{}) (string, interface{}) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
var errInvalidSchemaRef = fmt.Errorf("invalid schema reference")
|
||||
var errInvalidSchemaRef = errors.New("invalid schema reference")
|
||||
|
||||
// NOTE(tsandall): 'schema' is not registered as a root because it's not
|
||||
// supported by the compiler or evaluator today. Once we fix that, we can remove
|
||||
@@ -2542,7 +2543,7 @@ func parseRelatedResource(rr interface{}) (*RelatedResourceAnnotation, error) {
|
||||
}
|
||||
return &RelatedResourceAnnotation{Ref: *u}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("ref URL may not be empty string")
|
||||
return nil, errors.New("ref URL may not be empty string")
|
||||
case map[string]interface{}:
|
||||
description := strings.TrimSpace(getSafeString(rr, "description"))
|
||||
ref := strings.TrimSpace(getSafeString(rr, "ref"))
|
||||
@@ -2553,10 +2554,10 @@ func parseRelatedResource(rr interface{}) (*RelatedResourceAnnotation, error) {
|
||||
}
|
||||
return &RelatedResourceAnnotation{Description: description, Ref: *u}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("'ref' value required in object")
|
||||
return nil, errors.New("'ref' value required in object")
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid value type, must be string or map")
|
||||
return nil, errors.New("invalid value type, must be string or map")
|
||||
}
|
||||
|
||||
func parseAuthor(a interface{}) (*AuthorAnnotation, error) {
|
||||
@@ -2574,10 +2575,10 @@ func parseAuthor(a interface{}) (*AuthorAnnotation, error) {
|
||||
if len(name) > 0 || len(email) > 0 {
|
||||
return &AuthorAnnotation{name, email}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("'name' and/or 'email' values required in object")
|
||||
return nil, errors.New("'name' and/or 'email' values required in object")
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid value type, must be string or map")
|
||||
return nil, errors.New("invalid value type, must be string or map")
|
||||
}
|
||||
|
||||
func getSafeString(m map[string]interface{}, k string) string {
|
||||
@@ -2599,7 +2600,7 @@ func parseAuthorString(s string) (*AuthorAnnotation, error) {
|
||||
parts := strings.Fields(s)
|
||||
|
||||
if len(parts) == 0 {
|
||||
return nil, fmt.Errorf("author is an empty string")
|
||||
return nil, errors.New("author is an empty string")
|
||||
}
|
||||
|
||||
namePartCount := len(parts)
|
||||
@@ -2635,7 +2636,7 @@ func convertYAMLMapKeyTypes(x any, path []string) (any, error) {
|
||||
return result, nil
|
||||
case []any:
|
||||
for i := range x {
|
||||
x[i], err = convertYAMLMapKeyTypes(x[i], append(path, fmt.Sprintf("%d", i)))
|
||||
x[i], err = convertYAMLMapKeyTypes(x[i], append(path, strconv.Itoa(i)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+16
-15
@@ -6,6 +6,7 @@ package ast
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -17,7 +18,7 @@ import (
|
||||
func BenchmarkParseModuleRulesBase(b *testing.B) {
|
||||
sizes := []int{1, 10, 100, 1000}
|
||||
for _, size := range sizes {
|
||||
b.Run(fmt.Sprint(size), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(size), func(b *testing.B) {
|
||||
mod := generateModule(size)
|
||||
runParseModuleBenchmark(b, mod)
|
||||
})
|
||||
@@ -43,7 +44,7 @@ func BenchmarkParseStatementMixedJSON(b *testing.B) {
|
||||
func BenchmarkParseStatementSimpleArray(b *testing.B) {
|
||||
sizes := []int{1, 10, 100, 1000}
|
||||
for _, size := range sizes {
|
||||
b.Run(fmt.Sprint(size), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(size), func(b *testing.B) {
|
||||
stmt := generateArrayStatement(size)
|
||||
runParseStatementBenchmark(b, stmt)
|
||||
})
|
||||
@@ -53,7 +54,7 @@ func BenchmarkParseStatementSimpleArray(b *testing.B) {
|
||||
func TestParseStatementSimpleArray(b *testing.T) {
|
||||
sizes := []int{10} // , 10, 100, 1000}
|
||||
for _, size := range sizes {
|
||||
b.Run(fmt.Sprint(size), func(b *testing.T) {
|
||||
b.Run(strconv.Itoa(size), func(b *testing.T) {
|
||||
stmt := generateArrayStatement(size)
|
||||
_, err := ParseStatement(stmt)
|
||||
if err != nil {
|
||||
@@ -78,7 +79,7 @@ func BenchmarkParseStatementNestedObjects(b *testing.B) {
|
||||
func BenchmarkParseStatementNestedObjectsOrSets(b *testing.B) {
|
||||
sizes := []int{1, 5, 10, 15, 20}
|
||||
for _, size := range sizes {
|
||||
b.Run(fmt.Sprintf("%d", size), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(size), func(b *testing.B) {
|
||||
stmt := generateObjectOrSetStatement(size)
|
||||
runParseStatementBenchmarkWithError(b, stmt)
|
||||
})
|
||||
@@ -90,52 +91,52 @@ func BenchmarkParseBasicABACModule(b *testing.B) {
|
||||
package app.abac
|
||||
|
||||
default allow = false
|
||||
|
||||
|
||||
allow if {
|
||||
user_is_owner
|
||||
}
|
||||
|
||||
|
||||
allow if {
|
||||
user_is_employee
|
||||
action_is_read
|
||||
}
|
||||
|
||||
|
||||
allow if {
|
||||
user_is_employee
|
||||
user_is_senior
|
||||
action_is_update
|
||||
}
|
||||
|
||||
|
||||
allow if {
|
||||
user_is_customer
|
||||
action_is_read
|
||||
not pet_is_adopted
|
||||
}
|
||||
|
||||
|
||||
user_is_owner if {
|
||||
data.user_attributes[input.user].title == "owner"
|
||||
}
|
||||
|
||||
|
||||
user_is_employee if {
|
||||
data.user_attributes[input.user].title == "employee"
|
||||
}
|
||||
|
||||
|
||||
user_is_customer if {
|
||||
data.user_attributes[input.user].title == "customer"
|
||||
}
|
||||
|
||||
|
||||
user_is_senior if {
|
||||
data.user_attributes[input.user].tenure > 8
|
||||
}
|
||||
|
||||
|
||||
action_is_read if {
|
||||
input.action == "read"
|
||||
}
|
||||
|
||||
|
||||
action_is_update if {
|
||||
input.action == "update"
|
||||
}
|
||||
|
||||
|
||||
pet_is_adopted if {
|
||||
data.pet_attributes[input.resource].adopted == true
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ func MustParseTerm(input string) *Term {
|
||||
func ParseRuleFromBody(module *Module, body Body) (*Rule, error) {
|
||||
|
||||
if len(body) != 1 {
|
||||
return nil, fmt.Errorf("multiple expressions cannot be used for rule head")
|
||||
return nil, errors.New("multiple expressions cannot be used for rule head")
|
||||
}
|
||||
|
||||
return ParseRuleFromExpr(module, body[0])
|
||||
@@ -166,11 +166,11 @@ func ParseRuleFromBody(module *Module, body Body) (*Rule, error) {
|
||||
func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error) {
|
||||
|
||||
if len(expr.With) > 0 {
|
||||
return nil, fmt.Errorf("expressions using with keyword cannot be used for rule head")
|
||||
return nil, errors.New("expressions using with keyword cannot be used for rule head")
|
||||
}
|
||||
|
||||
if expr.Negated {
|
||||
return nil, fmt.Errorf("negated expressions cannot be used for rule head")
|
||||
return nil, errors.New("negated expressions cannot be used for rule head")
|
||||
}
|
||||
|
||||
if _, ok := expr.Terms.(*SomeDecl); ok {
|
||||
@@ -207,7 +207,7 @@ func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error) {
|
||||
}
|
||||
|
||||
if _, ok := BuiltinMap[expr.Operator().String()]; ok {
|
||||
return nil, fmt.Errorf("rule name conflicts with built-in function")
|
||||
return nil, errors.New("rule name conflicts with built-in function")
|
||||
}
|
||||
|
||||
return ParseRuleFromCallExpr(module, expr.Terms.([]*Term))
|
||||
@@ -272,7 +272,7 @@ func ParseCompleteDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, erro
|
||||
}
|
||||
head = RefHead(r)
|
||||
if len(r) > 1 && !r[len(r)-1].IsGround() {
|
||||
return nil, fmt.Errorf("ref not ground")
|
||||
return nil, errors.New("ref not ground")
|
||||
}
|
||||
} else {
|
||||
return nil, fmt.Errorf("%v cannot be used for rule name", ValueName(lhs.Value))
|
||||
@@ -387,7 +387,7 @@ func ParseRuleFromCallEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) {
|
||||
|
||||
call, ok := lhs.Value.(Call)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("must be call")
|
||||
return nil, errors.New("must be call")
|
||||
}
|
||||
|
||||
ref, ok := call[0].Value.(Ref)
|
||||
@@ -419,7 +419,7 @@ func ParseRuleFromCallEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) {
|
||||
func ParseRuleFromCallExpr(module *Module, terms []*Term) (*Rule, error) {
|
||||
|
||||
if len(terms) <= 1 {
|
||||
return nil, fmt.Errorf("rule argument list must take at least one argument")
|
||||
return nil, errors.New("rule argument list must take at least one argument")
|
||||
}
|
||||
|
||||
loc := terms[0].Location
|
||||
@@ -600,7 +600,7 @@ func ParseStatement(input string) (Statement, error) {
|
||||
return nil, err
|
||||
}
|
||||
if len(stmts) != 1 {
|
||||
return nil, fmt.Errorf("expected exactly one statement")
|
||||
return nil, errors.New("expected exactly one statement")
|
||||
}
|
||||
return stmts[0], nil
|
||||
}
|
||||
@@ -611,7 +611,7 @@ func ParseStatementWithOpts(input string, popts ParserOptions) (Statement, error
|
||||
return nil, err
|
||||
}
|
||||
if len(stmts) != 1 {
|
||||
return nil, fmt.Errorf("expected exactly one statement")
|
||||
return nil, errors.New("expected exactly one statement")
|
||||
}
|
||||
return stmts[0], nil
|
||||
}
|
||||
|
||||
+14
-14
@@ -1924,7 +1924,7 @@ func TestIsValidImportPath(t *testing.T) {
|
||||
path string
|
||||
expected error
|
||||
}{
|
||||
{"[1,2,3]", fmt.Errorf("invalid path [1, 2, 3]: path must be ref or var")},
|
||||
{"[1,2,3]", errors.New("invalid path [1, 2, 3]: path must be ref or var")},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
@@ -6102,12 +6102,12 @@ func TestAuthorAnnotation(t *testing.T) {
|
||||
{
|
||||
note: "no name",
|
||||
raw: "",
|
||||
expected: fmt.Errorf("author is an empty string"),
|
||||
expected: errors.New("author is an empty string"),
|
||||
},
|
||||
{
|
||||
note: "only whitespaces",
|
||||
raw: " \t",
|
||||
expected: fmt.Errorf("author is an empty string"),
|
||||
expected: errors.New("author is an empty string"),
|
||||
},
|
||||
{
|
||||
note: "one name only",
|
||||
@@ -6178,14 +6178,14 @@ func TestAuthorAnnotation(t *testing.T) {
|
||||
{
|
||||
note: "empty map",
|
||||
raw: map[string]interface{}{},
|
||||
expected: fmt.Errorf("'name' and/or 'email' values required in object"),
|
||||
expected: errors.New("'name' and/or 'email' values required in object"),
|
||||
},
|
||||
{
|
||||
note: "map with empty name",
|
||||
raw: map[string]interface{}{
|
||||
"name": "",
|
||||
},
|
||||
expected: fmt.Errorf("'name' and/or 'email' values required in object"),
|
||||
expected: errors.New("'name' and/or 'email' values required in object"),
|
||||
},
|
||||
{
|
||||
note: "map with email and empty name",
|
||||
@@ -6200,7 +6200,7 @@ func TestAuthorAnnotation(t *testing.T) {
|
||||
raw: map[string]interface{}{
|
||||
"email": "",
|
||||
},
|
||||
expected: fmt.Errorf("'name' and/or 'email' values required in object"),
|
||||
expected: errors.New("'name' and/or 'email' values required in object"),
|
||||
},
|
||||
{
|
||||
note: "map with name and empty email",
|
||||
@@ -6249,17 +6249,17 @@ func TestRelatedResourceAnnotation(t *testing.T) {
|
||||
{
|
||||
note: "empty ref URL",
|
||||
raw: "",
|
||||
expected: fmt.Errorf("ref URL may not be empty string"),
|
||||
expected: errors.New("ref URL may not be empty string"),
|
||||
},
|
||||
{
|
||||
note: "only whitespaces in ref URL",
|
||||
raw: " \t",
|
||||
expected: fmt.Errorf("parse \" \\t\": net/url: invalid control character in URL"),
|
||||
expected: errors.New("parse \" \\t\": net/url: invalid control character in URL"),
|
||||
},
|
||||
{
|
||||
note: "invalid ref URL",
|
||||
raw: "https://foo:bar",
|
||||
expected: fmt.Errorf("parse \"https://foo:bar\": invalid port \":bar\" after host"),
|
||||
expected: errors.New("parse \"https://foo:bar\": invalid port \":bar\" after host"),
|
||||
},
|
||||
{
|
||||
note: "ref URL as string",
|
||||
@@ -6278,7 +6278,7 @@ func TestRelatedResourceAnnotation(t *testing.T) {
|
||||
raw: map[string]interface{}{
|
||||
"description": "foo bar",
|
||||
},
|
||||
expected: fmt.Errorf("'ref' value required in object"),
|
||||
expected: errors.New("'ref' value required in object"),
|
||||
},
|
||||
{
|
||||
note: "map with ref and description",
|
||||
@@ -6306,21 +6306,21 @@ func TestRelatedResourceAnnotation(t *testing.T) {
|
||||
{
|
||||
note: "empty map",
|
||||
raw: map[string]interface{}{},
|
||||
expected: fmt.Errorf("'ref' value required in object"),
|
||||
expected: errors.New("'ref' value required in object"),
|
||||
},
|
||||
{
|
||||
note: "map with empty ref",
|
||||
raw: map[string]interface{}{
|
||||
"ref": "",
|
||||
},
|
||||
expected: fmt.Errorf("'ref' value required in object"),
|
||||
expected: errors.New("'ref' value required in object"),
|
||||
},
|
||||
{
|
||||
note: "map with only whitespace in ref",
|
||||
raw: map[string]interface{}{
|
||||
"ref": " \t",
|
||||
},
|
||||
expected: fmt.Errorf("'ref' value required in object"),
|
||||
expected: errors.New("'ref' value required in object"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -6414,7 +6414,7 @@ func assertParseErrorFunc(t *testing.T, msg string, input string, f func(string)
|
||||
}
|
||||
stmts, _, err := ParseStatementsWithOpts("", input, opt)
|
||||
if err == nil && len(stmts) != 1 {
|
||||
err = fmt.Errorf("expected exactly one statement")
|
||||
err = errors.New("expected exactly one statement")
|
||||
}
|
||||
if err == nil {
|
||||
t.Errorf("Error on test \"%s\": expected parse error on %s: expected no statements, got %d: %v", msg, input, len(stmts), stmts)
|
||||
|
||||
@@ -7,7 +7,7 @@ package ast
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
@@ -347,7 +347,7 @@ func TestExprBadJSON(t *testing.T) {
|
||||
}
|
||||
`
|
||||
|
||||
exp := fmt.Errorf("ast: unable to unmarshal negated field with type: json.Number (expected true or false)")
|
||||
exp := errors.New("ast: unable to unmarshal negated field with type: json.Number (expected true or false)")
|
||||
assert(js, exp)
|
||||
|
||||
js = `
|
||||
@@ -358,7 +358,7 @@ func TestExprBadJSON(t *testing.T) {
|
||||
"index": 0
|
||||
}
|
||||
`
|
||||
exp = fmt.Errorf("ast: unable to unmarshal term")
|
||||
exp = errors.New("ast: unable to unmarshal term")
|
||||
assert(js, exp)
|
||||
|
||||
js = `
|
||||
@@ -367,14 +367,14 @@ func TestExprBadJSON(t *testing.T) {
|
||||
"index": 0
|
||||
}
|
||||
`
|
||||
exp = fmt.Errorf(`ast: unable to unmarshal terms field with type: string (expected {"value": ..., "type": ...} or [{"value": ..., "type": ...}, ...])`)
|
||||
exp = errors.New(`ast: unable to unmarshal terms field with type: string (expected {"value": ..., "type": ...} or [{"value": ..., "type": ...}, ...])`)
|
||||
assert(js, exp)
|
||||
|
||||
js = `
|
||||
{
|
||||
"terms": {"value": "foo", "type": "string"}
|
||||
}`
|
||||
exp = fmt.Errorf("ast: unable to unmarshal index field with type: <nil> (expected integer)")
|
||||
exp = errors.New("ast: unable to unmarshal index field with type: <nil> (expected integer)")
|
||||
assert(js, exp)
|
||||
}
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ func TestAllOfSchemas(t *testing.T) {
|
||||
emptyExpectedType := types.A
|
||||
|
||||
//Tests 5 & 6: schema with array of arrays, object and array as siblings
|
||||
expectedError := fmt.Errorf("unable to merge these schemas")
|
||||
expectedError := errors.New("unable to merge these schemas")
|
||||
|
||||
//Test 7: array of objects
|
||||
arrayOfObjectsStaticProps := []*types.StaticProperty{}
|
||||
@@ -697,27 +697,27 @@ func TestCompilerCheckTypesWithAllOfSchema(t *testing.T) {
|
||||
{
|
||||
note: "allOf schema with unmergeable Array of Arrays",
|
||||
schema: allOfArrayOfArrays,
|
||||
expectedError: fmt.Errorf("unable to merge these schemas"),
|
||||
expectedError: errors.New("unable to merge these schemas"),
|
||||
},
|
||||
{
|
||||
note: "allOf schema with Array and Object types as siblings",
|
||||
schema: allOfObjectAndArray,
|
||||
expectedError: fmt.Errorf("unable to merge these schemas"),
|
||||
expectedError: errors.New("unable to merge these schemas"),
|
||||
},
|
||||
{
|
||||
note: "allOf schema with Array type that contains different unmergeable types",
|
||||
schema: allOfArrayDifTypesWithError,
|
||||
expectedError: fmt.Errorf("unable to merge these schemas"),
|
||||
expectedError: errors.New("unable to merge these schemas"),
|
||||
},
|
||||
{
|
||||
note: "allOf schema with different unmergeable types",
|
||||
schema: allOfTypeErrorSchema,
|
||||
expectedError: fmt.Errorf("unable to merge these schemas"),
|
||||
expectedError: errors.New("unable to merge these schemas"),
|
||||
},
|
||||
{
|
||||
note: "allOf unmergeable schema with different parent and items types",
|
||||
schema: allOfSchemaWithParentError,
|
||||
expectedError: fmt.Errorf("unable to merge these schemas"),
|
||||
expectedError: errors.New("unable to merge these schemas"),
|
||||
},
|
||||
{
|
||||
note: "allOf schema of Array type with uneven numbers of items to merge",
|
||||
@@ -727,7 +727,7 @@ func TestCompilerCheckTypesWithAllOfSchema(t *testing.T) {
|
||||
{
|
||||
note: "allOf schema with unmergeable types String and Boolean",
|
||||
schema: allOfStringSchemaWithError,
|
||||
expectedError: fmt.Errorf("unable to merge these schemas"),
|
||||
expectedError: errors.New("unable to merge these schemas"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+8
-7
@@ -8,6 +8,7 @@ package ast
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
@@ -26,7 +27,7 @@ import (
|
||||
"github.com/open-policy-agent/opa/v1/util"
|
||||
)
|
||||
|
||||
var errFindNotFound = fmt.Errorf("find: not found")
|
||||
var errFindNotFound = errors.New("find: not found")
|
||||
|
||||
// Location records a position in source code.
|
||||
type Location = location.Location
|
||||
@@ -1140,7 +1141,7 @@ func (ref Ref) Ptr() (string, error) {
|
||||
if str, ok := term.Value.(String); ok {
|
||||
parts = append(parts, url.PathEscape(string(str)))
|
||||
} else {
|
||||
return "", fmt.Errorf("invalid path value type")
|
||||
return "", errors.New("invalid path value type")
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "/"), nil
|
||||
@@ -3118,7 +3119,7 @@ func unmarshalBody(b []interface{}) (Body, error) {
|
||||
}
|
||||
return buf, nil
|
||||
unmarshal_error:
|
||||
return nil, fmt.Errorf("ast: unable to unmarshal body")
|
||||
return nil, errors.New("ast: unable to unmarshal body")
|
||||
}
|
||||
|
||||
func unmarshalExpr(expr *Expr, v map[string]interface{}) error {
|
||||
@@ -3255,7 +3256,7 @@ func unmarshalTermSlice(s []interface{}) ([]*Term, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("ast: unable to unmarshal term")
|
||||
return nil, errors.New("ast: unable to unmarshal term")
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
@@ -3264,7 +3265,7 @@ func unmarshalTermSliceValue(d map[string]interface{}) ([]*Term, error) {
|
||||
if s, ok := d["value"].([]interface{}); ok {
|
||||
return unmarshalTermSlice(s)
|
||||
}
|
||||
return nil, fmt.Errorf(`ast: unable to unmarshal term (expected {"value": [...], "type": ...} where type is one of: ref, array, or set)`)
|
||||
return nil, errors.New(`ast: unable to unmarshal term (expected {"value": [...], "type": ...} where type is one of: ref, array, or set)`)
|
||||
}
|
||||
|
||||
func unmarshalWith(i interface{}) (*With, error) {
|
||||
@@ -3284,7 +3285,7 @@ func unmarshalWith(i interface{}) (*With, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf(`ast: unable to unmarshal with modifier (expected {"target": {...}, "value": {...}})`)
|
||||
return nil, errors.New(`ast: unable to unmarshal with modifier (expected {"target": {...}, "value": {...}})`)
|
||||
}
|
||||
|
||||
func unmarshalValue(d map[string]interface{}) (Value, error) {
|
||||
@@ -3402,5 +3403,5 @@ func unmarshalValue(d map[string]interface{}) (Value, error) {
|
||||
}
|
||||
}
|
||||
unmarshal_error:
|
||||
return nil, fmt.Errorf("ast: unable to unmarshal term")
|
||||
return nil, errors.New("ast: unable to unmarshal term")
|
||||
}
|
||||
|
||||
+34
-33
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -15,12 +16,12 @@ import (
|
||||
func BenchmarkObjectLookup(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
obj := NewObject()
|
||||
for i := range n {
|
||||
obj.Insert(StringTerm(fmt.Sprint(i)), IntNumberTerm(i))
|
||||
obj.Insert(StringTerm(strconv.Itoa(i)), InternedIntNumberTerm(i))
|
||||
}
|
||||
key := StringTerm(fmt.Sprint(n - 1))
|
||||
key := StringTerm(strconv.Itoa(n - 1))
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
value := obj.Get(key)
|
||||
@@ -43,9 +44,9 @@ func BenchmarkObjectFind(b *testing.B) {
|
||||
for j := range m {
|
||||
arr = arr.Append(IntNumberTerm(j))
|
||||
}
|
||||
obj.Insert(StringTerm(fmt.Sprint(i)), NewTerm(arr))
|
||||
obj.Insert(StringTerm(strconv.Itoa(i)), NewTerm(arr))
|
||||
}
|
||||
key := Ref{StringTerm(fmt.Sprint(n - 1)), IntNumberTerm(m - 1)}
|
||||
key := Ref{StringTerm(strconv.Itoa(n - 1)), IntNumberTerm(m - 1)}
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
value, err := obj.Find(key)
|
||||
@@ -64,12 +65,12 @@ func BenchmarkObjectFind(b *testing.B) {
|
||||
func BenchmarkObjectCreationAndLookup(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000, 50000, 500000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
obj := NewObject()
|
||||
for i := range n {
|
||||
obj.Insert(StringTerm(fmt.Sprint(i)), IntNumberTerm(i))
|
||||
obj.Insert(StringTerm(strconv.Itoa(i)), IntNumberTerm(i))
|
||||
}
|
||||
key := StringTerm(fmt.Sprint(n - 1))
|
||||
key := StringTerm(strconv.Itoa(n - 1))
|
||||
for range b.N {
|
||||
value := obj.Get(key)
|
||||
if value == nil {
|
||||
@@ -83,13 +84,13 @@ func BenchmarkObjectCreationAndLookup(b *testing.B) {
|
||||
func BenchmarkLazyObjectLookup(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
data := make(map[string]interface{}, n)
|
||||
for i := range n {
|
||||
data[fmt.Sprint(i)] = i
|
||||
data[strconv.Itoa(i)] = i
|
||||
}
|
||||
obj := LazyObject(data)
|
||||
key := StringTerm(fmt.Sprint(n - 1))
|
||||
key := StringTerm(strconv.Itoa(n - 1))
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
value := obj.Get(key)
|
||||
@@ -110,12 +111,12 @@ func BenchmarkLazyObjectFind(b *testing.B) {
|
||||
for i := range n {
|
||||
arr := make([]string, 0, m)
|
||||
for j := range m {
|
||||
arr = append(arr, fmt.Sprint(j))
|
||||
arr = append(arr, strconv.Itoa(j))
|
||||
}
|
||||
data[fmt.Sprint(i)] = arr
|
||||
data[strconv.Itoa(i)] = arr
|
||||
}
|
||||
obj := LazyObject(data)
|
||||
key := Ref{StringTerm(fmt.Sprint(n - 1)), IntNumberTerm(m - 1)}
|
||||
key := Ref{StringTerm(strconv.Itoa(n - 1)), IntNumberTerm(m - 1)}
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
value, err := obj.Find(key)
|
||||
@@ -134,12 +135,12 @@ func BenchmarkLazyObjectFind(b *testing.B) {
|
||||
func BenchmarkSetCreationAndLookup(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000, 50000, 500000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
set := NewSet()
|
||||
for i := range n {
|
||||
set.Add(StringTerm(fmt.Sprint(i)))
|
||||
set.Add(StringTerm(strconv.Itoa(i)))
|
||||
}
|
||||
key := StringTerm(fmt.Sprint(n - 1))
|
||||
key := StringTerm(strconv.Itoa(n - 1))
|
||||
for range b.N {
|
||||
present := set.Contains(key)
|
||||
if !present {
|
||||
@@ -153,7 +154,7 @@ func BenchmarkSetCreationAndLookup(b *testing.B) {
|
||||
func BenchmarkSetIntersection(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
setA := NewSet()
|
||||
setB := NewSet()
|
||||
for i := range n {
|
||||
@@ -174,7 +175,7 @@ func BenchmarkSetIntersection(b *testing.B) {
|
||||
func BenchmarkSetIntersectionDifferentSize(b *testing.B) {
|
||||
sizes := []int{4, 50, 500, 5000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
setA := NewSet()
|
||||
setB := NewSet()
|
||||
for i := range n {
|
||||
@@ -198,7 +199,7 @@ func BenchmarkSetIntersectionDifferentSize(b *testing.B) {
|
||||
func BenchmarkSetMembership(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
setA := NewSet()
|
||||
for i := range n {
|
||||
setA.Add(IntNumberTerm(i))
|
||||
@@ -217,7 +218,7 @@ func BenchmarkSetMembership(b *testing.B) {
|
||||
func BenchmarkTermHashing(b *testing.B) {
|
||||
sizes := []int{10, 100, 1000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
s := String(strings.Repeat("a", n))
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
@@ -250,10 +251,10 @@ func BenchmarkObjectString(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000}
|
||||
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
obj := map[string]int{}
|
||||
for i := range n {
|
||||
obj[fmt.Sprint(i)] = i
|
||||
obj[strconv.Itoa(i)] = i
|
||||
}
|
||||
val := MustInterfaceToValue(obj)
|
||||
|
||||
@@ -285,10 +286,10 @@ func BenchmarkObjectStringInterfaces(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000, 50000}
|
||||
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
obj := map[string]int{}
|
||||
for i := range n {
|
||||
obj[fmt.Sprint(i)] = i
|
||||
obj[strconv.Itoa(i)] = i
|
||||
}
|
||||
valString := MustInterfaceToValue(obj)
|
||||
valJSON := MustInterfaceToValue(obj)
|
||||
@@ -318,7 +319,7 @@ func BenchmarkObjectConstruction(b *testing.B) {
|
||||
|
||||
b.Run("shuffled keys", func(b *testing.B) {
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
es := []struct{ k, v int }{}
|
||||
for i := range n {
|
||||
es = append(es, struct{ k, v int }{i, i})
|
||||
@@ -337,7 +338,7 @@ func BenchmarkObjectConstruction(b *testing.B) {
|
||||
})
|
||||
b.Run("increasing keys", func(b *testing.B) {
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
es := []struct{ k, v int }{}
|
||||
for v := range n {
|
||||
es = append(es, struct{ k, v int }{v, v})
|
||||
@@ -362,10 +363,10 @@ func BenchmarkArrayString(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000}
|
||||
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
obj := make([]string, n)
|
||||
for i := range n {
|
||||
obj[i] = fmt.Sprint(i)
|
||||
obj[i] = strconv.Itoa(i)
|
||||
}
|
||||
val := MustInterfaceToValue(obj)
|
||||
|
||||
@@ -396,7 +397,7 @@ func BenchmarkArrayString(b *testing.B) {
|
||||
func BenchmarkArrayEquality(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000}
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
arrA := NewArray()
|
||||
arrB := NewArray()
|
||||
for i := range n {
|
||||
@@ -420,7 +421,7 @@ func BenchmarkSetString(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000, 50000}
|
||||
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
val := NewSet()
|
||||
for i := range n {
|
||||
val.Add(IntNumberTerm(i))
|
||||
@@ -441,10 +442,10 @@ func BenchmarkSetMarshalJSON(b *testing.B) {
|
||||
sizes := []int{5, 50, 500, 5000, 50000}
|
||||
|
||||
for _, n := range sizes {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
set := NewSet()
|
||||
for i := range n {
|
||||
set.Add(StringTerm(fmt.Sprint(i)))
|
||||
set.Add(StringTerm(strconv.Itoa(i)))
|
||||
}
|
||||
|
||||
b.Run("json.Marshal", func(b *testing.B) {
|
||||
|
||||
+5
-5
@@ -6,7 +6,7 @@ package ast
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"runtime"
|
||||
@@ -120,7 +120,7 @@ func TestInterfaceToValueStructs(t *testing.T) {
|
||||
type brokenMarshaller struct{}
|
||||
|
||||
func (brokenMarshaller) MarshalJSON() ([]byte, error) {
|
||||
return nil, fmt.Errorf("broken")
|
||||
return nil, errors.New("broken")
|
||||
}
|
||||
|
||||
func TestObjectInsertGetLen(t *testing.T) {
|
||||
@@ -276,7 +276,7 @@ func TestTermBadJSON(t *testing.T) {
|
||||
|
||||
term := Term{}
|
||||
err := util.UnmarshalJSON([]byte(input), &term)
|
||||
expected := fmt.Errorf("ast: unable to unmarshal term")
|
||||
expected := errors.New("ast: unable to unmarshal term")
|
||||
if expected.Error() != err.Error() {
|
||||
t.Errorf("Expected %v but got: %v", expected, err)
|
||||
}
|
||||
@@ -325,7 +325,7 @@ func TestFind(t *testing.T) {
|
||||
}{
|
||||
{RefTerm(StringTerm("foo"), IntNumberTerm(1), StringTerm("bar")), MustParseTerm(`{2, 3, 4}`)},
|
||||
{RefTerm(StringTerm("foo"), IntNumberTerm(1), StringTerm("bar"), IntNumberTerm(4)), MustParseTerm(`4`)},
|
||||
{RefTerm(StringTerm("foo"), IntNumberTerm(2)), fmt.Errorf("not found")},
|
||||
{RefTerm(StringTerm("foo"), IntNumberTerm(2)), errors.New("not found")},
|
||||
{RefTerm(StringTerm("baz"), StringTerm("qux"), IntNumberTerm(0)), MustParseTerm(`"hello"`)},
|
||||
}
|
||||
|
||||
@@ -753,7 +753,7 @@ func TestSetMap(t *testing.T) {
|
||||
}
|
||||
|
||||
result, err = set.Map(func(*Term) (*Term, error) {
|
||||
return nil, fmt.Errorf("oops")
|
||||
return nil, errors.New("oops")
|
||||
})
|
||||
|
||||
if err.Error() != "oops" {
|
||||
|
||||
+7
-7
@@ -729,19 +729,19 @@ func (r *Reader) Read() (Bundle, error) {
|
||||
|
||||
if bundle.Type() == DeltaBundleType {
|
||||
if len(bundle.Data) != 0 {
|
||||
return bundle, fmt.Errorf("delta bundle expected to contain only patch file but data files found")
|
||||
return bundle, errors.New("delta bundle expected to contain only patch file but data files found")
|
||||
}
|
||||
|
||||
if len(bundle.Modules) != 0 {
|
||||
return bundle, fmt.Errorf("delta bundle expected to contain only patch file but policy files found")
|
||||
return bundle, errors.New("delta bundle expected to contain only patch file but policy files found")
|
||||
}
|
||||
|
||||
if len(bundle.WasmModules) != 0 {
|
||||
return bundle, fmt.Errorf("delta bundle expected to contain only patch file but wasm files found")
|
||||
return bundle, errors.New("delta bundle expected to contain only patch file but wasm files found")
|
||||
}
|
||||
|
||||
if r.persist {
|
||||
return bundle, fmt.Errorf("'persist' property is true in config. persisting delta bundle to disk is not supported")
|
||||
return bundle, errors.New("'persist' property is true in config. persisting delta bundle to disk is not supported")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -816,12 +816,12 @@ func (r *Reader) checkSignaturesAndDescriptors(signatures SignaturesConfig) erro
|
||||
}
|
||||
|
||||
if signatures.isEmpty() && r.verificationConfig != nil && r.verificationConfig.KeyID != "" {
|
||||
return fmt.Errorf("bundle missing .signatures.json file")
|
||||
return errors.New("bundle missing .signatures.json file")
|
||||
}
|
||||
|
||||
if !signatures.isEmpty() {
|
||||
if r.verificationConfig == nil {
|
||||
return fmt.Errorf("verification key not provided")
|
||||
return errors.New("verification key not provided")
|
||||
}
|
||||
|
||||
// verify the JWT signatures included in the `.signatures.json` file
|
||||
@@ -1390,7 +1390,7 @@ func mktree(path []string, value interface{}) (map[string]interface{}, error) {
|
||||
// For 0 length path the value is the full tree.
|
||||
obj, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("root value must be object")
|
||||
return nil, errors.New("root value must be object")
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
@@ -528,7 +528,7 @@ func TestReadWithSignatures(t *testing.T) {
|
||||
"no_signature_verification_config": {
|
||||
[][2]string{{"/.signatures.json", `{"signatures": []}`}},
|
||||
nil,
|
||||
true, fmt.Errorf("verification key not provided"),
|
||||
true, errors.New("verification key not provided"),
|
||||
},
|
||||
"no_signatures_file_no_keyid": {
|
||||
[][2]string{{"/.manifest", `{"revision": "quickbrownfaux"}`}},
|
||||
@@ -538,12 +538,12 @@ func TestReadWithSignatures(t *testing.T) {
|
||||
"no_signatures_file": {
|
||||
[][2]string{{"/.manifest", `{"revision": "quickbrownfaux"}`}},
|
||||
NewVerificationConfig(map[string]*KeyConfig{}, "somekey", "", nil),
|
||||
true, fmt.Errorf("bundle missing .signatures.json file"),
|
||||
true, errors.New("bundle missing .signatures.json file"),
|
||||
},
|
||||
"no_signatures": {
|
||||
[][2]string{{"/.signatures.json", `{"signatures": []}`}},
|
||||
NewVerificationConfig(map[string]*KeyConfig{}, "", "", nil),
|
||||
true, fmt.Errorf(".signatures.json: missing JWT (expected exactly one)"),
|
||||
true, errors.New(".signatures.json: missing JWT (expected exactly one)"),
|
||||
},
|
||||
"digest_mismatch": {
|
||||
[][2]string{
|
||||
@@ -552,7 +552,7 @@ func TestReadWithSignatures(t *testing.T) {
|
||||
{"/.manifest", `{"revision": "quickbrownfaux"}`},
|
||||
},
|
||||
NewVerificationConfig(map[string]*KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}}, "", "write", nil),
|
||||
true, fmt.Errorf("a/b/c/data.json: digest mismatch (want: 42cfe6768b57bb5f7503c165c28dd07ac5b813554ebc850f2cc35843e7137b1d, got: a615eeaee21de5179de080de8c3052c8da901138406ba71c38c032845f7d54f4)"),
|
||||
true, errors.New("a/b/c/data.json: digest mismatch (want: 42cfe6768b57bb5f7503c165c28dd07ac5b813554ebc850f2cc35843e7137b1d, got: a615eeaee21de5179de080de8c3052c8da901138406ba71c38c032845f7d54f4)"),
|
||||
},
|
||||
"no_hashing_alg": {
|
||||
[][2]string{
|
||||
@@ -560,7 +560,7 @@ func TestReadWithSignatures(t *testing.T) {
|
||||
{"/a/b/c/data.json", "[1,2,3]"},
|
||||
},
|
||||
NewVerificationConfig(map[string]*KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}}, "", "write", nil),
|
||||
true, fmt.Errorf("no hashing algorithm provided for file a/b/c/data.json"),
|
||||
true, errors.New("no hashing algorithm provided for file a/b/c/data.json"),
|
||||
},
|
||||
"exclude_files": {
|
||||
[][2]string{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -53,7 +52,7 @@ func BenchmarkTarballLoader(b *testing.B) {
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
// Reset the file reader.
|
||||
if _, err := f.Seek(0, 0); err != nil {
|
||||
b.Fatalf("Unexpected error: %s", err)
|
||||
@@ -78,7 +77,7 @@ func BenchmarkDirectoryLoader(b *testing.B) {
|
||||
test.WithTempFS(expectedFiles, func(rootDir string) {
|
||||
b.ResetTimer()
|
||||
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
loader := NewDirectoryLoader(rootDir)
|
||||
benchTestLoader(b, loader)
|
||||
})
|
||||
|
||||
@@ -7,7 +7,7 @@ package bundle
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -36,7 +36,7 @@ func TestValidateAndInjectDefaultsVerificationConfig(t *testing.T) {
|
||||
"valid_config_with_key_not_found": {
|
||||
map[string]*KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}},
|
||||
NewVerificationConfig(map[string]*KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}}, "bar", "", nil),
|
||||
true, fmt.Errorf("key id bar not found"),
|
||||
true, errors.New("key id bar not found"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ func TestGetPublicKey(t *testing.T) {
|
||||
"foo",
|
||||
NewVerificationConfig(map[string]*KeyConfig{}, "", "", nil),
|
||||
nil,
|
||||
true, fmt.Errorf("verification key corresponding to ID foo not found"),
|
||||
true, errors.New("verification key corresponding to ID foo not found"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+15
-14
@@ -8,6 +8,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -94,7 +95,7 @@ func ReadBundleNamesFromStore(ctx context.Context, store storage.Store, txn stor
|
||||
|
||||
bundleMap, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("corrupt manifest roots")
|
||||
return nil, errors.New("corrupt manifest roots")
|
||||
}
|
||||
|
||||
bundles := make([]string, len(bundleMap))
|
||||
@@ -196,14 +197,14 @@ func ReadWasmMetadataFromStore(ctx context.Context, store storage.Store, txn sto
|
||||
|
||||
bs, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("corrupt wasm manifest data")
|
||||
return nil, errors.New("corrupt wasm manifest data")
|
||||
}
|
||||
|
||||
var wasmMetadata []WasmResolver
|
||||
|
||||
err = util.UnmarshalJSON(bs, &wasmMetadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("corrupt wasm manifest data")
|
||||
return nil, errors.New("corrupt wasm manifest data")
|
||||
}
|
||||
|
||||
return wasmMetadata, nil
|
||||
@@ -219,14 +220,14 @@ func ReadWasmModulesFromStore(ctx context.Context, store storage.Store, txn stor
|
||||
|
||||
encodedModules, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("corrupt wasm modules")
|
||||
return nil, errors.New("corrupt wasm modules")
|
||||
}
|
||||
|
||||
rawModules := map[string][]byte{}
|
||||
for path, enc := range encodedModules {
|
||||
encStr, ok := enc.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("corrupt wasm modules")
|
||||
return nil, errors.New("corrupt wasm modules")
|
||||
}
|
||||
bs, err := base64.StdEncoding.DecodeString(encStr)
|
||||
if err != nil {
|
||||
@@ -248,7 +249,7 @@ func ReadBundleRootsFromStore(ctx context.Context, store storage.Store, txn stor
|
||||
|
||||
sl, ok := value.([]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("corrupt manifest roots")
|
||||
return nil, errors.New("corrupt manifest roots")
|
||||
}
|
||||
|
||||
roots := make([]string, len(sl))
|
||||
@@ -256,7 +257,7 @@ func ReadBundleRootsFromStore(ctx context.Context, store storage.Store, txn stor
|
||||
for i := range sl {
|
||||
roots[i], ok = sl[i].(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("corrupt manifest root")
|
||||
return nil, errors.New("corrupt manifest root")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -278,7 +279,7 @@ func readRevisionFromStore(ctx context.Context, store storage.Store, txn storage
|
||||
|
||||
str, ok := value.(string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("corrupt manifest revision")
|
||||
return "", errors.New("corrupt manifest revision")
|
||||
}
|
||||
|
||||
return str, nil
|
||||
@@ -299,7 +300,7 @@ func readMetadataFromStore(ctx context.Context, store storage.Store, txn storage
|
||||
|
||||
data, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("corrupt manifest metadata")
|
||||
return nil, errors.New("corrupt manifest metadata")
|
||||
}
|
||||
|
||||
return data, nil
|
||||
@@ -320,7 +321,7 @@ func readEtagFromStore(ctx context.Context, store storage.Store, txn storage.Tra
|
||||
|
||||
str, ok := value.(string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("corrupt bundle etag")
|
||||
return "", errors.New("corrupt bundle etag")
|
||||
}
|
||||
|
||||
return str, nil
|
||||
@@ -446,7 +447,7 @@ func activateBundles(opts *ActivateOpts) error {
|
||||
p := getNormalizedPath(path)
|
||||
|
||||
if len(p) == 0 {
|
||||
return fmt.Errorf("root value must be object")
|
||||
return errors.New("root value must be object")
|
||||
}
|
||||
|
||||
// verify valid YAML or JSON value
|
||||
@@ -716,7 +717,7 @@ func readModuleInfoFromStore(ctx context.Context, store storage.Store, txn stora
|
||||
if vs, ok := ver.(json.Number); ok {
|
||||
i, err := vs.Int64()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("corrupt rego version")
|
||||
return nil, errors.New("corrupt rego version")
|
||||
}
|
||||
versions[k] = moduleInfo{RegoVersion: ast.RegoVersionFromInt(int(i))}
|
||||
}
|
||||
@@ -726,7 +727,7 @@ func readModuleInfoFromStore(ctx context.Context, store storage.Store, txn stora
|
||||
return versions, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("corrupt rego version")
|
||||
return nil, errors.New("corrupt rego version")
|
||||
}
|
||||
|
||||
func erasePolicies(ctx context.Context, store storage.Store, txn storage.Transaction, parserOpts ast.ParserOptions, roots map[string]struct{}) (map[string]*ast.Module, []string, error) {
|
||||
@@ -1093,7 +1094,7 @@ func applyPatches(ctx context.Context, store storage.Store, txn storage.Transact
|
||||
// construct patch path
|
||||
path, ok := patch.ParsePatchPathEscaped("/" + strings.Trim(pat.Path, "/"))
|
||||
if !ok {
|
||||
return fmt.Errorf("error parsing patch path")
|
||||
return errors.New("error parsing patch path")
|
||||
}
|
||||
|
||||
var op storage.PatchOp
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
@@ -1918,8 +1918,8 @@ func TestBundleLazyModeLifecycleRawInvalidData(t *testing.T) {
|
||||
files [][2]string
|
||||
err error
|
||||
}{
|
||||
"non-object root": {[][2]string{{"/data.json", `[1,2,3]`}}, fmt.Errorf("root value must be object")},
|
||||
"invalid yaml": {[][2]string{{"/a/b/data.yaml", `"foo`}}, fmt.Errorf("yaml: found unexpected end of stream")},
|
||||
"non-object root": {[][2]string{{"/data.json", `[1,2,3]`}}, errors.New("root value must be object")},
|
||||
"invalid yaml": {[][2]string{{"/a/b/data.yaml", `"foo`}}, errors.New("yaml: found unexpected end of stream")},
|
||||
}
|
||||
|
||||
for name, tc := range tests {
|
||||
@@ -6411,7 +6411,7 @@ func TestDoDFS(t *testing.T) {
|
||||
path: filepath.Dir(strings.Trim("/data.json", "/")),
|
||||
roots: []string{"a/d"},
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("manifest roots [a/d] do not permit data at path '/d' (hint: check bundle directory structure)"),
|
||||
err: errors.New("manifest roots [a/d] do not permit data at path '/d' (hint: check bundle directory structure)"),
|
||||
},
|
||||
{
|
||||
note: "data outside roots 2",
|
||||
@@ -6419,7 +6419,7 @@ func TestDoDFS(t *testing.T) {
|
||||
path: filepath.Dir(strings.Trim("/x/data.json", "/")),
|
||||
roots: []string{"x/a/b/c/d"},
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("manifest roots [x/a/b/c/d] do not permit data at path '/x/a/b/c/e' (hint: check bundle directory structure)"),
|
||||
err: errors.New("manifest roots [x/a/b/c/d] do not permit data at path '/x/a/b/c/e' (hint: check bundle directory structure)"),
|
||||
},
|
||||
{
|
||||
note: "data outside roots 3",
|
||||
@@ -6427,7 +6427,7 @@ func TestDoDFS(t *testing.T) {
|
||||
path: filepath.Dir(strings.Trim("/data.json", "/")),
|
||||
roots: []string{"a/b/c/d"},
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("manifest roots [a/b/c/d] do not permit data at path '/a/b/c' (hint: check bundle directory structure)"),
|
||||
err: errors.New("manifest roots [a/b/c/d] do not permit data at path '/a/b/c' (hint: check bundle directory structure)"),
|
||||
},
|
||||
{
|
||||
note: "data outside multiple roots",
|
||||
@@ -6435,7 +6435,7 @@ func TestDoDFS(t *testing.T) {
|
||||
path: filepath.Dir(strings.Trim("/data.json", "/")),
|
||||
roots: []string{"a/b", "c"},
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("manifest roots [a/b c] do not permit data at path '/e' (hint: check bundle directory structure)"),
|
||||
err: errors.New("manifest roots [a/b c] do not permit data at path '/e' (hint: check bundle directory structure)"),
|
||||
},
|
||||
{
|
||||
note: "data outside multiple roots 2",
|
||||
@@ -6443,7 +6443,7 @@ func TestDoDFS(t *testing.T) {
|
||||
path: filepath.Dir(strings.Trim("/data.json", "/")),
|
||||
roots: []string{"a/b", "c/d/e"},
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("manifest roots [a/b c/d/e] do not permit data at path '/c/d' (hint: check bundle directory structure)"),
|
||||
err: errors.New("manifest roots [a/b c/d/e] do not permit data at path '/c/d' (hint: check bundle directory structure)"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+5
-4
@@ -10,6 +10,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/open-policy-agent/opa/internal/jwx/jwa"
|
||||
@@ -60,11 +61,11 @@ func (*DefaultVerifier) VerifyBundleSignature(sc SignaturesConfig, bvc *Verifica
|
||||
files := make(map[string]FileInfo)
|
||||
|
||||
if len(sc.Signatures) == 0 {
|
||||
return files, fmt.Errorf(".signatures.json: missing JWT (expected exactly one)")
|
||||
return files, errors.New(".signatures.json: missing JWT (expected exactly one)")
|
||||
}
|
||||
|
||||
if len(sc.Signatures) > 1 {
|
||||
return files, fmt.Errorf(".signatures.json: multiple JWTs not supported (expected exactly one)")
|
||||
return files, errors.New(".signatures.json: multiple JWTs not supported (expected exactly one)")
|
||||
}
|
||||
|
||||
for _, token := range sc.Signatures {
|
||||
@@ -120,7 +121,7 @@ func verifyJWTSignature(token string, bvc *VerificationConfig) (*DecodedSignatur
|
||||
}
|
||||
|
||||
if keyID == "" {
|
||||
return nil, fmt.Errorf("verification key ID is empty")
|
||||
return nil, errors.New("verification key ID is empty")
|
||||
}
|
||||
|
||||
// now that we have the keyID, fetch the actual key
|
||||
@@ -148,7 +149,7 @@ func verifyJWTSignature(token string, bvc *VerificationConfig) (*DecodedSignatur
|
||||
}
|
||||
|
||||
if ds.Scope != scope {
|
||||
return nil, fmt.Errorf("scope mismatch")
|
||||
return nil, errors.New("scope mismatch")
|
||||
}
|
||||
return &ds, nil
|
||||
}
|
||||
|
||||
@@ -296,7 +296,7 @@ func addEntrypointsFromAnnotations(c *Compiler, arefs []*ast.AnnotationsRef) err
|
||||
func (c *Compiler) Build(ctx context.Context) error {
|
||||
|
||||
if c.regoVersion == ast.RegoUndefined {
|
||||
return fmt.Errorf("rego-version not set")
|
||||
return errors.New("rego-version not set")
|
||||
}
|
||||
|
||||
if err := c.init(); err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -25,7 +26,7 @@ func BenchmarkCompileDynamicPolicy(b *testing.B) {
|
||||
testcase := generateDynamicPolicyBenchmarkData(n)
|
||||
test.WithTestFS(testcase, true, func(root string, fileSys fs.FS) {
|
||||
b.ResetTimer()
|
||||
b.Run(fmt.Sprintf("%d", n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
compiler := New().
|
||||
WithFS(fileSys).
|
||||
WithPaths(root)
|
||||
@@ -78,7 +79,7 @@ func BenchmarkLargePartialRulePolicy(b *testing.B) {
|
||||
for _, n := range numPolicies {
|
||||
testcase := generateLargePartialRuleBenchmarkData(n)
|
||||
b.ResetTimer()
|
||||
b.Run(fmt.Sprintf("%d", n), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(n), func(b *testing.B) {
|
||||
test.WithTempFS(testcase, func(root string) {
|
||||
b.ResetTimer()
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ func TestCompilerInitErrors(t *testing.T) {
|
||||
{
|
||||
note: "bad target",
|
||||
c: New().WithTarget("deadbeef"),
|
||||
want: fmt.Errorf("invalid target \"deadbeef\""),
|
||||
want: errors.New("invalid target \"deadbeef\""),
|
||||
},
|
||||
{
|
||||
note: "optimizations require entrypoint",
|
||||
@@ -139,7 +139,7 @@ func TestCompilerLoadError(t *testing.T) {
|
||||
func TestCompilerLoadAsBundleSuccess(t *testing.T) {
|
||||
|
||||
ctx := context.Background()
|
||||
rv := fmt.Sprintf("%d", ast.DefaultRegoVersion.Int())
|
||||
rv := strconv.Itoa(ast.DefaultRegoVersion.Int())
|
||||
|
||||
files := map[string]string{
|
||||
"b1/.manifest": `{"roots": ["b1"], "rego_version": ` + rv + `}`,
|
||||
@@ -2938,7 +2938,7 @@ func TestOptimizerErrors(t *testing.T) {
|
||||
{
|
||||
note: "undefined entrypoint",
|
||||
entrypoints: []string{"data.test.p"},
|
||||
wantErr: fmt.Errorf("undefined entrypoint data.test.p"),
|
||||
wantErr: errors.New("undefined entrypoint data.test.p"),
|
||||
},
|
||||
{
|
||||
note: "compile error",
|
||||
@@ -2949,7 +2949,7 @@ func TestOptimizerErrors(t *testing.T) {
|
||||
p if { data.test.p }
|
||||
`,
|
||||
},
|
||||
wantErr: fmt.Errorf("1 error occurred: test.rego:3: rego_recursion_error: rule data.test.p is recursive: data.test.p -> data.test.p"),
|
||||
wantErr: errors.New("1 error occurred: test.rego:3: rego_recursion_error: rule data.test.p is recursive: data.test.p -> data.test.p"),
|
||||
},
|
||||
{
|
||||
note: "partial eval error",
|
||||
@@ -2960,7 +2960,7 @@ func TestOptimizerErrors(t *testing.T) {
|
||||
p if { {k: v | k = ["a", "a"][_]; v = [0, 1][_] } }
|
||||
`,
|
||||
},
|
||||
wantErr: fmt.Errorf("test.rego:3: eval_conflict_error: object keys must be unique"),
|
||||
wantErr: errors.New("test.rego:3: eval_conflict_error: object keys must be unique"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@ package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -243,7 +244,7 @@ func removeCryptoKeys(x interface{}) error {
|
||||
func removeKey(x interface{}, keys ...string) error {
|
||||
val, ok := x.(map[string]interface{})
|
||||
if !ok {
|
||||
return fmt.Errorf("type assertion error")
|
||||
return errors.New("type assertion error")
|
||||
}
|
||||
|
||||
for _, key := range keys {
|
||||
|
||||
@@ -6,6 +6,7 @@ package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -358,13 +359,13 @@ func TestActiveConfig(t *testing.T) {
|
||||
badKeysConfig,
|
||||
nil,
|
||||
true,
|
||||
fmt.Errorf("illegal keys config type: []interface {}"),
|
||||
errors.New("illegal keys config type: []interface {}"),
|
||||
},
|
||||
"invalid_config_with_bad_creds": {
|
||||
badServicesConfig,
|
||||
nil,
|
||||
true,
|
||||
fmt.Errorf("type assertion error"),
|
||||
errors.New("type assertion error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+17
-17
@@ -287,7 +287,7 @@ func (d *debugger) LaunchEval(ctx context.Context, props LaunchEvalProperties, o
|
||||
}
|
||||
|
||||
if props.InputPath != "" && props.Input != nil {
|
||||
return nil, fmt.Errorf("cannot specify both input and input path")
|
||||
return nil, errors.New("cannot specify both input and input path")
|
||||
}
|
||||
|
||||
if props.Input != nil {
|
||||
@@ -406,7 +406,7 @@ func newSession(ctx context.Context, debugger *debugger, varManager *variableMan
|
||||
|
||||
func (s *session) start() error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -442,7 +442,7 @@ func (s *session) start() error {
|
||||
|
||||
func (s *session) thread(id ThreadID) (*thread, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
index := int(id - 1)
|
||||
@@ -454,7 +454,7 @@ func (s *session) thread(id ThreadID) (*thread, error) {
|
||||
|
||||
func (s *session) Resume(threadID ThreadID) error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -470,7 +470,7 @@ func (s *session) Resume(threadID ThreadID) error {
|
||||
|
||||
func (s *session) ResumeAll() error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -486,7 +486,7 @@ func (s *session) ResumeAll() error {
|
||||
|
||||
func (s *session) StepOver(threadID ThreadID) error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -523,7 +523,7 @@ func (s *session) StepOver(threadID ThreadID) error {
|
||||
|
||||
func (s *session) StepIn(threadID ThreadID) error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -560,7 +560,7 @@ func (s *session) StepIn(threadID ThreadID) error {
|
||||
|
||||
func (s *session) StepOut(threadID ThreadID) error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -597,7 +597,7 @@ func (s *session) StepOut(threadID ThreadID) error {
|
||||
|
||||
func (s *session) Threads() ([]Thread, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -719,7 +719,7 @@ func (s *session) result(t *thread, rs rego.ResultSet) {
|
||||
|
||||
func (s *session) StackTrace(threadID ThreadID) (StackTrace, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -791,7 +791,7 @@ func (s *session) frame(id FrameID) (*stackFrame, error) {
|
||||
|
||||
func (s *session) Scopes(frameID FrameID) ([]Scope, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -812,7 +812,7 @@ func (s *session) Scopes(frameID FrameID) ([]Scope, error) {
|
||||
|
||||
func (s *session) Variables(varRef VarRef) ([]Variable, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -830,7 +830,7 @@ func (s *session) Variables(varRef VarRef) ([]Variable, error) {
|
||||
|
||||
func (s *session) Breakpoints() ([]Breakpoint, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -841,7 +841,7 @@ func (s *session) Breakpoints() ([]Breakpoint, error) {
|
||||
|
||||
func (s *session) AddBreakpoint(loc location.Location) (Breakpoint, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -852,7 +852,7 @@ func (s *session) AddBreakpoint(loc location.Location) (Breakpoint, error) {
|
||||
|
||||
func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no active debug session")
|
||||
return nil, errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -868,7 +868,7 @@ func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) {
|
||||
|
||||
func (s *session) ClearBreakpoints() error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
@@ -881,7 +881,7 @@ func (s *session) ClearBreakpoints() error {
|
||||
|
||||
func (s *session) Terminate() error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("no active debug session")
|
||||
return errors.New("no active debug session")
|
||||
}
|
||||
|
||||
s.mtx.Lock()
|
||||
|
||||
@@ -613,12 +613,12 @@ qux: d
|
||||
LaunchProperties: LaunchProperties{
|
||||
DataPaths: []string{
|
||||
path.Join(rootDir, "mod.rego"),
|
||||
path.Join(rootDir, fmt.Sprintf("data.%s", ext)),
|
||||
path.Join(rootDir, "data."+ext),
|
||||
},
|
||||
EnablePrint: true,
|
||||
},
|
||||
Query: "x = data.test.p",
|
||||
InputPath: path.Join(rootDir, fmt.Sprintf("input.%s", ext)),
|
||||
InputPath: path.Join(rootDir, "input."+ext),
|
||||
}
|
||||
|
||||
s, err := d.LaunchEval(ctx, launchProps)
|
||||
|
||||
+6
-5
@@ -6,7 +6,8 @@ package debug
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"errors"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/open-policy-agent/opa/v1/ast"
|
||||
@@ -139,7 +140,7 @@ func (t *thread) stepIn() (eventAction, error) {
|
||||
defer t.mtx.Unlock()
|
||||
|
||||
if t.stopped {
|
||||
return nopAction, fmt.Errorf("thread stopped")
|
||||
return nopAction, errors.New("thread stopped")
|
||||
}
|
||||
|
||||
var a eventAction
|
||||
@@ -168,7 +169,7 @@ func (t *thread) stepOver() error {
|
||||
defer t.mtx.Unlock()
|
||||
|
||||
if t.stopped {
|
||||
return fmt.Errorf("thread stopped")
|
||||
return errors.New("thread stopped")
|
||||
}
|
||||
|
||||
_, startE, err := t.current()
|
||||
@@ -238,7 +239,7 @@ func (t *thread) stepOut() error {
|
||||
defer t.mtx.Unlock()
|
||||
|
||||
if t.stopped {
|
||||
return fmt.Errorf("thread stopped")
|
||||
return errors.New("thread stopped")
|
||||
}
|
||||
|
||||
_, c, err := t.current()
|
||||
@@ -509,7 +510,7 @@ func (t *thread) resultVars(rs rego.ResultSet) VarRef {
|
||||
)
|
||||
|
||||
vars = append(vars, namedVar{
|
||||
name: fmt.Sprintf("%d", i),
|
||||
name: strconv.Itoa(i),
|
||||
value: res,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ package debug
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/open-policy-agent/opa/v1/ast"
|
||||
@@ -156,7 +157,7 @@ func (vs *variableManager) subVars(v ast.Value) VarRef {
|
||||
vars := make([]namedVar, 0, arr.Len())
|
||||
for i := range arr.Len() {
|
||||
vars = append(vars, namedVar{
|
||||
name: fmt.Sprintf("%d", i),
|
||||
name: strconv.Itoa(i),
|
||||
value: arr.Elem(i).Value,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package dependencies
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -11,7 +12,7 @@ import (
|
||||
func BenchmarkBase(b *testing.B) {
|
||||
ruleCounts := []int{10, 20, 50}
|
||||
for _, ruleCount := range ruleCounts {
|
||||
b.Run(fmt.Sprint(ruleCount), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(ruleCount), func(b *testing.B) {
|
||||
policy := makePolicy(ruleCount)
|
||||
module := ast.MustParseModule(policy)
|
||||
compiler := ast.NewCompiler()
|
||||
@@ -34,7 +35,7 @@ func BenchmarkBase(b *testing.B) {
|
||||
func BenchmarkVirtual(b *testing.B) {
|
||||
ruleCounts := []int{10, 20, 50}
|
||||
for _, ruleCount := range ruleCounts {
|
||||
b.Run(fmt.Sprint(ruleCount), func(b *testing.B) {
|
||||
b.Run(strconv.Itoa(ruleCount), func(b *testing.B) {
|
||||
policy := makePolicy(ruleCount)
|
||||
module := ast.MustParseModule(policy)
|
||||
compiler := ast.NewCompiler()
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
package dependencies
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/open-policy-agent/opa/v1/ast"
|
||||
@@ -341,7 +341,7 @@ func TestDependencies(t *testing.T) {
|
||||
}
|
||||
|
||||
for n, test := range tests {
|
||||
t.Run(fmt.Sprint(n), func(t *testing.T) {
|
||||
t.Run(strconv.Itoa(n), func(t *testing.T) {
|
||||
module := ast.MustParseModuleWithOpts(test.ast, ast.ParserOptions{AllFutureKeywords: true})
|
||||
compiler := ast.NewCompiler()
|
||||
if compiler.Compile(map[string]*ast.Module{"test": module}); compiler.Failed() {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -57,14 +58,14 @@ func (c *Config) ValidateAndInjectDefaults() error {
|
||||
// reject bad min/max values
|
||||
if c.Polling.MaxDelaySeconds != nil && c.Polling.MinDelaySeconds != nil {
|
||||
if *c.Polling.MaxDelaySeconds < *c.Polling.MinDelaySeconds {
|
||||
return fmt.Errorf("max polling delay must be >= min polling delay")
|
||||
return errors.New("max polling delay must be >= min polling delay")
|
||||
}
|
||||
min = *c.Polling.MinDelaySeconds
|
||||
max = *c.Polling.MaxDelaySeconds
|
||||
} else if c.Polling.MaxDelaySeconds == nil && c.Polling.MinDelaySeconds != nil {
|
||||
return fmt.Errorf("polling configuration missing 'max_delay_seconds'")
|
||||
return errors.New("polling configuration missing 'max_delay_seconds'")
|
||||
} else if c.Polling.MinDelaySeconds == nil && c.Polling.MaxDelaySeconds != nil {
|
||||
return fmt.Errorf("polling configuration missing 'min_delay_seconds'")
|
||||
return errors.New("polling configuration missing 'min_delay_seconds'")
|
||||
}
|
||||
|
||||
// scale to seconds
|
||||
@@ -76,7 +77,7 @@ func (c *Config) ValidateAndInjectDefaults() error {
|
||||
|
||||
if c.Polling.LongPollingTimeoutSeconds != nil {
|
||||
if *c.Polling.LongPollingTimeoutSeconds < 1 {
|
||||
return fmt.Errorf("'long_polling_timeout_seconds' must be at least 1")
|
||||
return errors.New("'long_polling_timeout_seconds' must be at least 1")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -291,7 +291,7 @@ func (d *Downloader) download(ctx context.Context, m metrics.Metrics) (*download
|
||||
preferences := []string{fmt.Sprintf("modes=%v,%v", defaultBundleMode, deltaBundleMode)}
|
||||
|
||||
if d.longPollingEnabled && d.config.Polling.LongPollingTimeoutSeconds != nil {
|
||||
wait := fmt.Sprintf("wait=%s", strconv.FormatInt(*d.config.Polling.LongPollingTimeoutSeconds, 10))
|
||||
wait := "wait=" + strconv.FormatInt(*d.config.Polling.LongPollingTimeoutSeconds, 10)
|
||||
preferences = append(preferences, wait)
|
||||
|
||||
// fetch existing response header timeout value on the http client's transport and
|
||||
@@ -304,7 +304,7 @@ func (d *Downloader) download(ctx context.Context, m metrics.Metrics) (*download
|
||||
}
|
||||
}
|
||||
|
||||
preferValue := fmt.Sprintf("%v", strings.Join(preferences, ";"))
|
||||
preferValue := strings.Join(preferences, ";")
|
||||
d.client = d.client.WithHeader("Prefer", preferValue)
|
||||
|
||||
m.Timer(metrics.BundleRequest).Start()
|
||||
@@ -441,7 +441,7 @@ type HTTPError struct {
|
||||
}
|
||||
|
||||
func (e HTTPError) Error() string {
|
||||
return fmt.Sprintf("server replied with %s", http.StatusText(e.StatusCode))
|
||||
return "server replied with " + http.StatusText(e.StatusCode)
|
||||
}
|
||||
|
||||
func contains(s string, strings []string) bool {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
@@ -224,7 +225,7 @@ func (d *OCIDownloader) download(ctx context.Context, m metrics.Metrics) (*downl
|
||||
|
||||
preferences := []string{fmt.Sprintf("modes=%v,%v", defaultBundleMode, deltaBundleMode)}
|
||||
|
||||
preferValue := fmt.Sprintf("%v", strings.Join(preferences, ";"))
|
||||
preferValue := strings.Join(preferences, ";")
|
||||
d.client = d.client.WithHeader("Prefer", preferValue)
|
||||
|
||||
m.Timer(metrics.BundleRequest).Start()
|
||||
@@ -246,7 +247,7 @@ func (d *OCIDownloader) download(ctx context.Context, m metrics.Metrics) (*downl
|
||||
}
|
||||
}
|
||||
if tarballDescriptor.MediaType == "" {
|
||||
return nil, fmt.Errorf("no tarball descriptor found in the layers")
|
||||
return nil, errors.New("no tarball descriptor found in the layers")
|
||||
}
|
||||
etag := tarballDescriptor.Digest.Hex()
|
||||
bundleFilePath := filepath.Join(d.localStorePath, "blobs", "sha256", etag)
|
||||
@@ -423,7 +424,7 @@ func manifestFromDesc(ctx context.Context, target oraslib.Target, desc *ocispec.
|
||||
}
|
||||
|
||||
if len(manifest.Layers) < 1 {
|
||||
return nil, fmt.Errorf("no layers in manifest")
|
||||
return nil, errors.New("no layers in manifest")
|
||||
}
|
||||
|
||||
return &manifest, nil
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -719,7 +720,7 @@ func differsAt(a, b []byte) (int, int) {
|
||||
func prefixWithLineNumbers(bs []byte) []byte {
|
||||
raw := string(bs)
|
||||
lines := strings.Split(raw, "\n")
|
||||
format := fmt.Sprintf("%%%dd %%s", len(fmt.Sprint(len(lines)+1)))
|
||||
format := fmt.Sprintf("%%%dd %%s", len(strconv.Itoa(len(lines)+1)))
|
||||
for i, line := range lines {
|
||||
lines[i] = fmt.Sprintf(format, i+1, line)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package keys
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -40,7 +41,7 @@ func TestParseKeysConfig(t *testing.T) {
|
||||
"invalid_config_no_key": {
|
||||
`{"foo": {"algorithm": "HS256"}}`,
|
||||
nil,
|
||||
true, fmt.Errorf("invalid keys configuration: no keys provided for key ID foo"),
|
||||
true, errors.New("invalid keys configuration: no keys provided for key ID foo"),
|
||||
},
|
||||
"valid_config_default_alg": {
|
||||
`{"foo": {"key": "FdFYFzERwC2uCBB46pZQi4GG85LujR8obt-KWRBICVQ"}}`,
|
||||
@@ -50,12 +51,12 @@ func TestParseKeysConfig(t *testing.T) {
|
||||
"invalid_raw_key_config": {
|
||||
`{"bar": [1,2,3]}`,
|
||||
nil,
|
||||
true, fmt.Errorf("json: cannot unmarshal array into Go value of type keys.Config"),
|
||||
true, errors.New("json: cannot unmarshal array into Go value of type keys.Config"),
|
||||
},
|
||||
"invalid_raw_config": {
|
||||
`[1,2,3]`,
|
||||
nil,
|
||||
true, fmt.Errorf("json: cannot unmarshal array into Go value of type map[string]json.RawMessage"),
|
||||
true, errors.New("json: cannot unmarshal array into Go value of type map[string]json.RawMessage"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ package extension_test
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
)
|
||||
|
||||
func TestLoaderExtensionUnmarshal(t *testing.T) {
|
||||
sentinelErr := fmt.Errorf("test handler called")
|
||||
sentinelErr := errors.New("test handler called")
|
||||
extension.RegisterExtension(".json", func([]byte, any) error {
|
||||
return sentinelErr
|
||||
})
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
@@ -948,17 +948,17 @@ func TestCheckForUNCPath(t *testing.T) {
|
||||
{
|
||||
input: `\\localhost\c$`,
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("UNC path read is not allowed: \\\\localhost\\c$"),
|
||||
err: errors.New("UNC path read is not allowed: \\\\localhost\\c$"),
|
||||
},
|
||||
{
|
||||
input: `\\\\localhost\c$`,
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("UNC path read is not allowed: \\\\\\\\localhost\\c$"),
|
||||
err: errors.New("UNC path read is not allowed: \\\\\\\\localhost\\c$"),
|
||||
},
|
||||
{
|
||||
input: `//localhost/foo`,
|
||||
wantErr: true,
|
||||
err: fmt.Errorf("UNC path read is not allowed: //localhost/foo"),
|
||||
err: errors.New("UNC path read is not allowed: //localhost/foo"),
|
||||
},
|
||||
{
|
||||
input: `file:///a/b/c`,
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/open-policy-agent/opa/v1/plugins"
|
||||
@@ -231,7 +233,7 @@ func TestParseAndValidateBundlesConfig(t *testing.T) {
|
||||
|
||||
keys := map[string]*keys.Config{"foo": {Key: "secret"}}
|
||||
for i := range tests {
|
||||
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
|
||||
t.Run(strconv.Itoa(i), func(t *testing.T) {
|
||||
_, err := NewConfigBuilder().WithBytes([]byte(tests[i].conf)).WithServices(tests[i].services).
|
||||
WithKeyConfigs(keys).Parse()
|
||||
if err != nil && !tests[i].wantError {
|
||||
@@ -409,7 +411,7 @@ func TestConfigIsMultiBundle(t *testing.T) {
|
||||
}
|
||||
|
||||
for i := range tests {
|
||||
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
|
||||
t.Run(strconv.Itoa(i), func(t *testing.T) {
|
||||
actual := tests[i].conf.IsMultiBundle()
|
||||
if actual != tests[i].expected {
|
||||
t.Errorf("expected %t but got %t", tests[i].expected, actual)
|
||||
@@ -462,20 +464,20 @@ func TestParseConfigTriggerMode(t *testing.T) {
|
||||
conf: `{"b1":{"service": "s1", "trigger": "periodic"}}`,
|
||||
services: []string{"s1"},
|
||||
wantError: true,
|
||||
err: fmt.Errorf("invalid configuration for bundle \"b1\": trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
err: errors.New("invalid configuration for bundle \"b1\": trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
triggerMode: &tm,
|
||||
},
|
||||
{
|
||||
conf: `{"b1":{"service": "s1", "trigger": "foo"}}`,
|
||||
services: []string{"s1"},
|
||||
wantError: true,
|
||||
err: fmt.Errorf("invalid configuration for bundle \"b1\": invalid trigger mode \"foo\" (want \"periodic\" or \"manual\")"),
|
||||
err: errors.New("invalid configuration for bundle \"b1\": invalid trigger mode \"foo\" (want \"periodic\" or \"manual\")"),
|
||||
triggerMode: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for i := range tests {
|
||||
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
|
||||
t.Run(strconv.Itoa(i), func(t *testing.T) {
|
||||
config, err := NewConfigBuilder().WithBytes([]byte(tests[i].conf)).WithServices(tests[i].services).WithTriggerMode(tests[i].triggerMode).Parse()
|
||||
if err != nil && !tests[i].wantError {
|
||||
t.Fatalf("Unexpected error: %s", err)
|
||||
|
||||
@@ -2,7 +2,6 @@ package bundle
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/open-policy-agent/opa/v1/ast"
|
||||
@@ -11,8 +10,8 @@ import (
|
||||
|
||||
func TestErrors(t *testing.T) {
|
||||
errs := Errors{
|
||||
NewBundleError("foo", fmt.Errorf("foo error")),
|
||||
NewBundleError("bar", fmt.Errorf("bar error")),
|
||||
NewBundleError("foo", errors.New("foo error")),
|
||||
NewBundleError("bar", errors.New("bar error")),
|
||||
}
|
||||
|
||||
expected := "Bundle name: foo, Code: bundle_error, HTTPCode: -1, Message: foo error\nBundle name: bar, Code: bundle_error, HTTPCode: -1, Message: bar error"
|
||||
@@ -24,8 +23,8 @@ func TestErrors(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUnwrapSlice(t *testing.T) {
|
||||
fooErr := NewBundleError("foo", fmt.Errorf("foo error"))
|
||||
barErr := NewBundleError("bar", fmt.Errorf("bar error"))
|
||||
fooErr := NewBundleError("foo", errors.New("foo error"))
|
||||
barErr := NewBundleError("bar", errors.New("bar error"))
|
||||
|
||||
errs := Errors{fooErr, barErr}
|
||||
|
||||
@@ -124,7 +123,7 @@ func TestASTErrorsWrapping(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGenericErrorWrapping(t *testing.T) {
|
||||
err := fmt.Errorf("foo error")
|
||||
err := errors.New("foo error")
|
||||
bundleErr := NewBundleError("foo", err)
|
||||
|
||||
if bundleErr.BundleName != "foo" {
|
||||
|
||||
@@ -1416,7 +1416,7 @@ func TestPluginOneShotBundlePersistence(t *testing.T) {
|
||||
ensurePluginState(t, plugin, plugins.StateNotReady)
|
||||
|
||||
// simulate a bundle download error with no bundle on disk
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
if plugin.status[bundleName].Message == "" {
|
||||
t.Fatal("expected error but got none")
|
||||
@@ -1462,7 +1462,7 @@ func TestPluginOneShotBundlePersistence(t *testing.T) {
|
||||
}
|
||||
|
||||
// simulate a bundle download error and verify that the bundle on disk is activated
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
ensurePluginState(t, plugin, plugins.StateOK)
|
||||
|
||||
@@ -1583,7 +1583,7 @@ corge contains 1 if {
|
||||
ensurePluginState(t, plugin, plugins.StateNotReady)
|
||||
|
||||
// simulate a bundle download error with no bundle on disk
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
if plugin.status[bundleName].Message == "" {
|
||||
t.Fatal("expected error but got none")
|
||||
@@ -1652,7 +1652,7 @@ corge contains 1 if {
|
||||
}
|
||||
|
||||
// simulate a bundle download error and verify that the bundle on disk is activated
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
ensurePluginState(t, plugin, plugins.StateOK)
|
||||
|
||||
@@ -1868,7 +1868,7 @@ corge contains 1 if {
|
||||
ensurePluginState(t, plugin, plugins.StateNotReady)
|
||||
|
||||
// simulate a bundle download error with no bundle on disk
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
if plugin.status[bundleName].Message == "" {
|
||||
t.Fatal("expected error but got none")
|
||||
@@ -1945,7 +1945,7 @@ corge contains 1 if {
|
||||
}
|
||||
|
||||
// simulate a bundle download error and verify that the bundle on disk is activated
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
ensurePluginState(t, plugin, plugins.StateOK)
|
||||
|
||||
@@ -2024,7 +2024,7 @@ func TestPluginOneShotSignedBundlePersistence(t *testing.T) {
|
||||
ensurePluginState(t, plugin, plugins.StateNotReady)
|
||||
|
||||
// simulate a bundle download error with no bundle on disk
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
if plugin.status[bundleName].Message == "" {
|
||||
t.Fatal("expected error but got none")
|
||||
@@ -2069,7 +2069,7 @@ func TestPluginOneShotSignedBundlePersistence(t *testing.T) {
|
||||
}
|
||||
|
||||
// simulate a bundle download error and verify that the bundle on disk is activated
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
ensurePluginState(t, plugin, plugins.StateOK)
|
||||
|
||||
@@ -3154,7 +3154,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) {
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !slices.Equal([]string{filepath.Join(bundleName, "/example2.rego")}, ids) {
|
||||
return fmt.Errorf("expected updated policy ids")
|
||||
return errors.New("expected updated policy ids")
|
||||
}
|
||||
data, err := manager.Store.Read(ctx, txn, storage.Path{})
|
||||
// remove system key to make comparison simpler
|
||||
@@ -3162,7 +3162,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) {
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !reflect.DeepEqual(data, map[string]interface{}{"baz": "qux"}) {
|
||||
return fmt.Errorf("expected updated data")
|
||||
return errors.New("expected updated data")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
@@ -3448,7 +3448,7 @@ func TestPluginListenerErrorClearedOn304(t *testing.T) {
|
||||
}
|
||||
|
||||
// Test that service error triggers failure notification.
|
||||
go plugin.oneShot(ctx, bundleName, download.Update{Error: fmt.Errorf("some error")})
|
||||
go plugin.oneShot(ctx, bundleName, download.Update{Error: errors.New("some error")})
|
||||
s2 := <-ch
|
||||
|
||||
if s2.ActiveRevision != "quickbrownfaux" || s2.Code == "" {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -86,7 +87,7 @@ func ParseConfig(bs []byte, services []string) (*Config, error) {
|
||||
func (c *Config) validateAndInjectDefaults(services []string, confKeys map[string]*keys.Config) error {
|
||||
|
||||
if c.Resource == nil && c.Name == nil {
|
||||
return fmt.Errorf("missing required discovery.resource field")
|
||||
return errors.New("missing required discovery.resource field")
|
||||
}
|
||||
|
||||
// make a copy of the keys map
|
||||
@@ -138,7 +139,7 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin
|
||||
func (c *Config) getServiceFromList(service string, services []string) (string, error) {
|
||||
if service == "" {
|
||||
if len(services) != 1 {
|
||||
return "", fmt.Errorf("more than one service is defined")
|
||||
return "", errors.New("more than one service is defined")
|
||||
}
|
||||
return services[0], nil
|
||||
}
|
||||
|
||||
@@ -483,7 +483,7 @@ func (c *Discovery) processBundle(ctx context.Context, b *bundleApi.Bundle) (*pl
|
||||
if client, ok := services[c.config.service]; ok {
|
||||
dClient := c.manager.Client(c.config.service)
|
||||
if !client.Config().Equal(dClient.Config()) {
|
||||
return nil, fmt.Errorf("updates to the discovery service are not allowed")
|
||||
return nil, errors.New("updates to the discovery service are not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,7 +497,7 @@ func (c *Discovery) processBundle(ctx context.Context, b *bundleApi.Bundle) (*pl
|
||||
for key, kc := range keys {
|
||||
if curr, ok := c.config.Signing.PublicKeys[key]; ok {
|
||||
if !curr.Equal(kc) {
|
||||
return nil, fmt.Errorf("updates to keys specified in the boot configuration are not allowed")
|
||||
return nil, errors.New("updates to keys specified in the boot configuration are not allowed")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -560,7 +560,7 @@ func evaluateBundle(ctx context.Context, id string, info *ast.Term, b *bundleApi
|
||||
}
|
||||
|
||||
if len(rs) == 0 {
|
||||
return nil, fmt.Errorf("undefined configuration")
|
||||
return nil, errors.New("undefined configuration")
|
||||
}
|
||||
|
||||
bs, err := json.Marshal(rs[0].Expressions[0].Value)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net"
|
||||
@@ -620,7 +621,7 @@ func TestOneShotWithBundlePersistence(t *testing.T) {
|
||||
ensurePluginState(t, disco, plugins.StateNotReady)
|
||||
|
||||
// simulate a bundle download error with no bundle on disk
|
||||
disco.oneShot(ctx, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
disco.oneShot(ctx, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
if disco.status.Message == "" {
|
||||
t.Fatal("expected error but got none")
|
||||
@@ -2737,7 +2738,7 @@ func TestStatusUpdates(t *testing.T) {
|
||||
}`)})
|
||||
|
||||
// Downloader error.
|
||||
disco.oneShot(ctx, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
disco.oneShot(ctx, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
// Clear error.
|
||||
disco.oneShot(ctx, download.Update{ETag: "etag-2", Bundle: makeDataBundle(2, `{
|
||||
@@ -2994,7 +2995,7 @@ func TestStatusUpdatesTimestamp(t *testing.T) {
|
||||
}
|
||||
|
||||
// simulate error response from downloader
|
||||
disco.oneShot(ctx, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
disco.oneShot(ctx, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
if disco.status.LastSuccessfulDownload != disco.status.LastSuccessfulRequest || disco.status.LastSuccessfulDownload == disco.status.LastRequest {
|
||||
t.Fatal("expected last successful request to be same as download but different from request")
|
||||
@@ -3319,7 +3320,7 @@ bundles:
|
||||
confGood, false, nil,
|
||||
},
|
||||
"trigger_mode_mismatch": {
|
||||
confBad, true, fmt.Errorf("invalid configuration for bundle \"bundle-new\": trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
confBad, true, errors.New("invalid configuration for bundle \"bundle-new\": trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3386,7 +3387,7 @@ decision_logs:
|
||||
confGood, false, nil,
|
||||
},
|
||||
"trigger_mode_mismatch": {
|
||||
confBad, true, fmt.Errorf("invalid decision_log config: trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
confBad, true, errors.New("invalid decision_log config: trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3459,7 +3460,7 @@ status:
|
||||
confGood, false, nil,
|
||||
},
|
||||
"trigger_mode_mismatch": {
|
||||
confBad, true, fmt.Errorf("invalid status config: trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
confBad, true, errors.New("invalid status config: trigger mode mismatch: manual and periodic (hint: check discovery configuration)"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3837,7 +3838,7 @@ func TestListeners(t *testing.T) {
|
||||
})
|
||||
|
||||
// simulate a bundle download error
|
||||
disco.oneShot(ctx, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
disco.oneShot(ctx, download.Update{Error: errors.New("unknown error")})
|
||||
|
||||
if status == nil {
|
||||
t.Fatalf("Expected discovery listener to receive status but was nil")
|
||||
@@ -3847,7 +3848,7 @@ func TestListeners(t *testing.T) {
|
||||
disco.Unregister("testlistener")
|
||||
|
||||
// simulate a bundle download error
|
||||
disco.oneShot(ctx, download.Update{Error: fmt.Errorf("unknown error")})
|
||||
disco.oneShot(ctx, download.Update{Error: errors.New("unknown error")})
|
||||
if status != nil {
|
||||
t.Fatalf("Expected discovery listener to be removed but received %v", status)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -98,7 +98,7 @@ func TestChunkEncoderAdaptive(t *testing.T) {
|
||||
for i := range numEvents {
|
||||
|
||||
bundles := map[string]BundleInfoV1{}
|
||||
bundles["authz"] = BundleInfoV1{Revision: fmt.Sprint(i)}
|
||||
bundles["authz"] = BundleInfoV1{Revision: strconv.Itoa(i)}
|
||||
|
||||
event := EventV1{
|
||||
Labels: map[string]string{
|
||||
@@ -106,7 +106,7 @@ func TestChunkEncoderAdaptive(t *testing.T) {
|
||||
"app": "example-app",
|
||||
},
|
||||
Bundles: bundles,
|
||||
DecisionID: fmt.Sprint(i),
|
||||
DecisionID: strconv.Itoa(i),
|
||||
Path: "foo/bar",
|
||||
Input: &expInput,
|
||||
Result: &result,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
@@ -24,7 +25,7 @@ const (
|
||||
partNDBCache = "nd_builtin_cache"
|
||||
)
|
||||
|
||||
var errMaskInvalidObject = fmt.Errorf("mask upsert invalid object")
|
||||
var errMaskInvalidObject = errors.New("mask upsert invalid object")
|
||||
|
||||
type maskRule struct {
|
||||
OP maskOP `json:"op"`
|
||||
@@ -54,9 +55,9 @@ func newMaskRule(path string, opts ...maskRuleOption) (*maskRule, error) {
|
||||
)
|
||||
|
||||
if len(path) == 0 {
|
||||
return nil, fmt.Errorf("mask must be non-empty")
|
||||
return nil, errors.New("mask must be non-empty")
|
||||
} else if !strings.HasPrefix(path, "/") {
|
||||
return nil, fmt.Errorf("mask must be slash-prefixed")
|
||||
return nil, errors.New("mask must be slash-prefixed")
|
||||
}
|
||||
|
||||
parts := strings.Split(path[1:], "/")
|
||||
|
||||
@@ -6,7 +6,7 @@ package logs
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -27,7 +27,7 @@ func TestNewMaskRule(t *testing.T) {
|
||||
OP: maskOPRemove,
|
||||
Path: "",
|
||||
},
|
||||
expErr: fmt.Errorf("mask must be non-empty"),
|
||||
expErr: errors.New("mask must be non-empty"),
|
||||
},
|
||||
{
|
||||
note: "missing slash",
|
||||
@@ -35,7 +35,7 @@ func TestNewMaskRule(t *testing.T) {
|
||||
OP: maskOPRemove,
|
||||
Path: "foo",
|
||||
},
|
||||
expErr: fmt.Errorf("mask must be slash-prefixed"),
|
||||
expErr: errors.New("mask must be slash-prefixed"),
|
||||
},
|
||||
{
|
||||
note: "no prefix",
|
||||
@@ -43,7 +43,7 @@ func TestNewMaskRule(t *testing.T) {
|
||||
OP: maskOPRemove,
|
||||
Path: "/",
|
||||
},
|
||||
expErr: fmt.Errorf("mask prefix not allowed"),
|
||||
expErr: errors.New("mask prefix not allowed"),
|
||||
},
|
||||
{
|
||||
note: "bad prefix key",
|
||||
@@ -51,7 +51,7 @@ func TestNewMaskRule(t *testing.T) {
|
||||
OP: maskOPRemove,
|
||||
Path: "/labels/foo",
|
||||
},
|
||||
expErr: fmt.Errorf("mask prefix not allowed"),
|
||||
expErr: errors.New("mask prefix not allowed"),
|
||||
},
|
||||
{
|
||||
note: "standard",
|
||||
@@ -85,7 +85,7 @@ func TestNewMaskRule(t *testing.T) {
|
||||
OP: maskOP("undefinedOP"),
|
||||
Path: "/input/a/b/c",
|
||||
},
|
||||
expErr: fmt.Errorf("mask op is not supported: undefinedOP"),
|
||||
expErr: errors.New("mask op is not supported: undefinedOP"),
|
||||
},
|
||||
{
|
||||
note: "escaping",
|
||||
@@ -105,7 +105,7 @@ func TestNewMaskRule(t *testing.T) {
|
||||
OP: maskOPRemove,
|
||||
Path: "/input/a/%F/b",
|
||||
},
|
||||
expErr: fmt.Errorf("invalid URL escape"),
|
||||
expErr: errors.New("invalid URL escape"),
|
||||
},
|
||||
{
|
||||
note: "empty component",
|
||||
@@ -150,7 +150,7 @@ func TestNewMaskRule(t *testing.T) {
|
||||
OP: maskOP("unsupported"),
|
||||
Path: "/input",
|
||||
},
|
||||
expErr: fmt.Errorf("mask op is not supported: unsupported"),
|
||||
expErr: errors.New("mask op is not supported: unsupported"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -661,14 +661,14 @@ func TestNewMaskRuleSet(t *testing.T) {
|
||||
{
|
||||
note: "invalid format: not []interface{}",
|
||||
value: map[string]int{"invalid": 1},
|
||||
err: fmt.Errorf("unexpected rule format map[invalid:1] (map[string]int)"),
|
||||
err: errors.New("unexpected rule format map[invalid:1] (map[string]int)"),
|
||||
},
|
||||
{
|
||||
note: "invalid format: nested type not string or map[string]interface{}",
|
||||
value: []interface{}{
|
||||
[]int{1, 2},
|
||||
},
|
||||
err: fmt.Errorf("invalid mask rule format encountered: []int"),
|
||||
err: errors.New("invalid mask rule format encountered: []int"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand"
|
||||
@@ -342,14 +343,14 @@ func (c *Config) validateAndInjectDefaults(services []string, pluginsList []stri
|
||||
// reject bad min/max values
|
||||
if c.Reporting.MaxDelaySeconds != nil && c.Reporting.MinDelaySeconds != nil {
|
||||
if *c.Reporting.MaxDelaySeconds < *c.Reporting.MinDelaySeconds {
|
||||
return fmt.Errorf("max reporting delay must be >= min reporting delay in decision_logs")
|
||||
return errors.New("max reporting delay must be >= min reporting delay in decision_logs")
|
||||
}
|
||||
min = *c.Reporting.MinDelaySeconds
|
||||
max = *c.Reporting.MaxDelaySeconds
|
||||
} else if c.Reporting.MaxDelaySeconds == nil && c.Reporting.MinDelaySeconds != nil {
|
||||
return fmt.Errorf("reporting configuration missing 'max_delay_seconds' in decision_logs")
|
||||
return errors.New("reporting configuration missing 'max_delay_seconds' in decision_logs")
|
||||
} else if c.Reporting.MinDelaySeconds == nil && c.Reporting.MaxDelaySeconds != nil {
|
||||
return fmt.Errorf("reporting configuration missing 'min_delay_seconds' in decision_logs")
|
||||
return errors.New("reporting configuration missing 'min_delay_seconds' in decision_logs")
|
||||
}
|
||||
|
||||
// scale to seconds
|
||||
@@ -368,7 +369,7 @@ func (c *Config) validateAndInjectDefaults(services []string, pluginsList []stri
|
||||
c.Reporting.UploadSizeLimitBytes = &uploadLimit
|
||||
|
||||
if c.Reporting.BufferSizeLimitBytes != nil && c.Reporting.MaxDecisionsPerSecond != nil {
|
||||
return fmt.Errorf("invalid decision_log config, specify either 'buffer_size_limit_bytes' or 'max_decisions_per_second'")
|
||||
return errors.New("invalid decision_log config, specify either 'buffer_size_limit_bytes' or 'max_decisions_per_second'")
|
||||
}
|
||||
|
||||
// default the buffer size limit
|
||||
@@ -722,7 +723,7 @@ func (p *Plugin) Log(ctx context.Context, decision *server.Info) error {
|
||||
if p.config.Plugin != nil {
|
||||
proxy, ok := p.manager.Plugin(*p.config.Plugin).(Logger)
|
||||
if !ok {
|
||||
return fmt.Errorf("plugin does not implement Logger interface")
|
||||
return errors.New("plugin does not implement Logger interface")
|
||||
}
|
||||
return proxy.Log(ctx, event)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ package plugins
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -481,7 +481,7 @@ func (m *mockForInitStartOrdering) Start(_ context.Context) error {
|
||||
if m.Manager.initialized {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("expected manager to be initialized")
|
||||
return errors.New("expected manager to be initialized")
|
||||
}
|
||||
|
||||
func (*mockForInitStartOrdering) Stop(context.Context) {}
|
||||
|
||||
@@ -678,7 +678,7 @@ func (ap *ecrAuthPlugin) Prepare(r *http.Request) error {
|
||||
|
||||
ap.logger.Debug("Signing request with ECR authorization token")
|
||||
|
||||
r.Header.Set("Authorization", fmt.Sprintf("Basic %s", ap.token.AuthorizationToken))
|
||||
r.Header.Set("Authorization", "Basic "+ap.token.AuthorizationToken)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user