Bump golangci-lint, more gocritic linters (#8052)

- Bump golangci-lint -> 2.6.2
- Fix all `deprecatedComment` "notices should be in a dedicated paragraph, separated from the rest" reports
- Enable `appendCombine` and fix all "appendCombine: can combine chain of X appends into one" notices
- Enable `preferFprint` and fix the few reported issues
- Fix various issues reported only once or twice, like `zeroByteRepeat`

Signed-off-by: Anders Eknert <anders.eknert@apple.com>
This commit is contained in:
Anders Eknert
2025-11-17 11:08:39 +01:00
committed by GitHub
parent e0f2ac2ad7
commit e03ac2f200
56 changed files with 425 additions and 309 deletions
+4 -6
View File
@@ -36,13 +36,8 @@ linters:
# Reasonable rule, but not sure what to replace with in # Reasonable rule, but not sure what to replace with in
# many locations, so disabling for now # many locations, so disabling for now
- exitAfterDefer - exitAfterDefer
# The following 3 rules are disabled from the perfomance tag # This is disabled from the perfomance tag enabled further down.
# enabled further down. The first two are reasonable, but not
# super important. appendCombine is really nice though! And
# should be enabled. Just many places to fix..
- hugeParam - hugeParam
- preferFprint
- appendCombine
enabled-tags: enabled-tags:
- performance - performance
settings: settings:
@@ -53,6 +48,9 @@ linters:
# switch)... just too many violations right now # switch)... just too many violations right now
minThreshold: 10 minThreshold: 10
govet: govet:
disable:
# enable later and fix
- buildtag
enable: enable:
- deepequalerrors - deepequalerrors
- nilness - nilness
+1 -1
View File
@@ -24,7 +24,7 @@ ifeq ($(WASM_ENABLED),1)
GO_TAGS = -tags=opa_wasm GO_TAGS = -tags=opa_wasm
endif endif
GOLANGCI_LINT_VERSION := v2.4.0 GOLANGCI_LINT_VERSION := v2.6.2
YAML_LINT_VERSION := 0.29.0 YAML_LINT_VERSION := 0.29.0
YAML_LINT_FORMAT ?= auto YAML_LINT_FORMAT ?= auto
+4
View File
@@ -10,16 +10,19 @@ import v1 "github.com/open-policy-agent/opa/v1/ast"
// can return a Visitor w which will be used to visit the children of the AST // can return a Visitor w which will be used to visit the children of the AST
// element v. If the Visit function returns nil, the children will not be // element v. If the Visit function returns nil, the children will not be
// visited. // visited.
//
// Deprecated: use GenericVisitor or another visitor implementation // Deprecated: use GenericVisitor or another visitor implementation
type Visitor = v1.Visitor type Visitor = v1.Visitor
// BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before // BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before
// and after the AST has been visited. // and after the AST has been visited.
//
// Deprecated: use GenericVisitor or another visitor implementation // Deprecated: use GenericVisitor or another visitor implementation
type BeforeAndAfterVisitor = v1.BeforeAndAfterVisitor type BeforeAndAfterVisitor = v1.BeforeAndAfterVisitor
// Walk iterates the AST by calling the Visit function on the Visitor // Walk iterates the AST by calling the Visit function on the Visitor
// v for x before recursing. // v for x before recursing.
//
// Deprecated: use GenericVisitor.Walk // Deprecated: use GenericVisitor.Walk
func Walk(v Visitor, x any) { func Walk(v Visitor, x any) {
v1.Walk(v, x) v1.Walk(v, x)
@@ -27,6 +30,7 @@ func Walk(v Visitor, x any) {
// WalkBeforeAndAfter iterates the AST by calling the Visit function on the // WalkBeforeAndAfter iterates the AST by calling the Visit function on the
// Visitor v for x before recursing. // Visitor v for x before recursing.
//
// Deprecated: use GenericVisitor.Walk // Deprecated: use GenericVisitor.Walk
func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any) { func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any) {
v1.WalkBeforeAndAfter(v, x) v1.WalkBeforeAndAfter(v, x)
+4
View File
@@ -100,24 +100,28 @@ func Deactivate(opts *DeactivateOpts) error {
} }
// LegacyWriteManifestToStore will write the bundle manifest to the older single (unnamed) bundle manifest location. // LegacyWriteManifestToStore will write the bundle manifest to the older single (unnamed) bundle manifest location.
//
// Deprecated: Use WriteManifestToStore and named bundles instead. // Deprecated: Use WriteManifestToStore and named bundles instead.
func LegacyWriteManifestToStore(ctx context.Context, store storage.Store, txn storage.Transaction, manifest Manifest) error { func LegacyWriteManifestToStore(ctx context.Context, store storage.Store, txn storage.Transaction, manifest Manifest) error {
return v1.LegacyWriteManifestToStore(ctx, store, txn, manifest) return v1.LegacyWriteManifestToStore(ctx, store, txn, manifest)
} }
// LegacyEraseManifestFromStore will erase the bundle manifest from the older single (unnamed) bundle manifest location. // LegacyEraseManifestFromStore will erase the bundle manifest from the older single (unnamed) bundle manifest location.
//
// Deprecated: Use WriteManifestToStore and named bundles instead. // Deprecated: Use WriteManifestToStore and named bundles instead.
func LegacyEraseManifestFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) error { func LegacyEraseManifestFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) error {
return v1.LegacyEraseManifestFromStore(ctx, store, txn) return v1.LegacyEraseManifestFromStore(ctx, store, txn)
} }
// LegacyReadRevisionFromStore will read the bundle manifest revision from the older single (unnamed) bundle manifest location. // LegacyReadRevisionFromStore will read the bundle manifest revision from the older single (unnamed) bundle manifest location.
//
// Deprecated: Use ReadBundleRevisionFromStore and named bundles instead. // Deprecated: Use ReadBundleRevisionFromStore and named bundles instead.
func LegacyReadRevisionFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) (string, error) { func LegacyReadRevisionFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) (string, error) {
return v1.LegacyReadRevisionFromStore(ctx, store, txn) return v1.LegacyReadRevisionFromStore(ctx, store, txn)
} }
// ActivateLegacy calls Activate for the bundles but will also write their manifest to the older unnamed store location. // ActivateLegacy calls Activate for the bundles but will also write their manifest to the older unnamed store location.
//
// Deprecated: Use Activate with named bundles instead. // Deprecated: Use Activate with named bundles instead.
func ActivateLegacy(opts *ActivateOpts) error { func ActivateLegacy(opts *ActivateOpts) error {
return v1.ActivateLegacy(opts) return v1.ActivateLegacy(opts)
+232 -190
View File
@@ -32,7 +32,7 @@ const (
opaWasmABIMinorVersionVar = "opa_wasm_abi_minor_version" opaWasmABIMinorVersionVar = "opa_wasm_abi_minor_version"
) )
// nolint: deadcode,varcheck // nolint: varcheck
const ( const (
opaTypeNull int32 = iota + 1 opaTypeNull int32 = iota + 1
opaTypeBoolean opaTypeBoolean
@@ -414,7 +414,7 @@ func (c *Compiler) initModule() error {
}, },
}, },
}, },
Init: bytes.Repeat([]byte{0}, int(heapBase-offset)), Init: make([]byte, int(heapBase-offset)),
}) })
return nil return nil
@@ -1058,9 +1058,11 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
}, },
}) })
case *ir.AssignIntStmt: case *ir.AssignIntStmt:
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Target)}) instrs = append(instrs,
instrs = append(instrs, instruction.I64Const{Value: stmt.Value}) instruction.GetLocal{Index: c.local(stmt.Target)},
instrs = append(instrs, instruction.Call{Index: c.function(opaValueNumberSetInt)}) instruction.I64Const{Value: stmt.Value},
instruction.Call{Index: c.function(opaValueNumberSetInt)},
)
case *ir.ScanStmt: case *ir.ScanStmt:
if err := c.compileScan(stmt, &instrs); err != nil { if err := c.compileScan(stmt, &instrs); err != nil {
return nil, err return nil, err
@@ -1073,12 +1075,14 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
} }
case *ir.DotStmt: case *ir.DotStmt:
if loc, ok := stmt.Source.Value.(ir.Local); ok { if loc, ok := stmt.Source.Value.(ir.Local); ok {
instrs = append(instrs, instruction.GetLocal{Index: c.local(loc)}) instrs = append(instrs,
instrs = append(instrs, c.instrRead(stmt.Key)) instruction.GetLocal{Index: c.local(loc)},
instrs = append(instrs, instruction.Call{Index: c.function(opaValueGet)}) c.instrRead(stmt.Key),
instrs = append(instrs, instruction.TeeLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaValueGet)},
instrs = append(instrs, instruction.I32Eqz{}) instruction.TeeLocal{Index: c.local(stmt.Target)},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.I32Eqz{},
instruction.BrIf{Index: 0},
)
} else { } else {
// Booleans and string sources would lead to the BrIf (since opa_value_get // Booleans and string sources would lead to the BrIf (since opa_value_get
// on them returns 0), so let's skip trying that. // on them returns 0), so let's skip trying that.
@@ -1086,97 +1090,131 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
break break
} }
case *ir.LenStmt: case *ir.LenStmt:
instrs = append(instrs, c.instrRead(stmt.Source)) instrs = append(instrs,
instrs = append(instrs, instruction.Call{Index: c.function(opaValueLength)}) c.instrRead(stmt.Source),
instrs = append(instrs, instruction.Call{Index: c.function(opaNumberSize)}) instruction.Call{Index: c.function(opaValueLength)},
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaNumberSize)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.EqualStmt: case *ir.EqualStmt:
instrs = append(instrs, c.instrRead(stmt.A)) instrs = append(instrs,
instrs = append(instrs, c.instrRead(stmt.B)) c.instrRead(stmt.A),
instrs = append(instrs, instruction.Call{Index: c.function(opaValueCompare)}) c.instrRead(stmt.B),
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.Call{Index: c.function(opaValueCompare)},
instruction.BrIf{Index: 0},
)
case *ir.NotEqualStmt: case *ir.NotEqualStmt:
instrs = append(instrs, c.instrRead(stmt.A)) instrs = append(instrs,
instrs = append(instrs, c.instrRead(stmt.B)) c.instrRead(stmt.A),
instrs = append(instrs, instruction.Call{Index: c.function(opaValueCompare)}) c.instrRead(stmt.B),
instrs = append(instrs, instruction.I32Eqz{}) instruction.Call{Index: c.function(opaValueCompare)},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.I32Eqz{},
instruction.BrIf{Index: 0},
)
case *ir.MakeNullStmt: case *ir.MakeNullStmt:
instrs = append(instrs, instruction.Call{Index: c.function(opaNull)}) instrs = append(instrs,
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaNull)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.MakeNumberIntStmt: case *ir.MakeNumberIntStmt:
instrs = append(instrs, instruction.I64Const{Value: stmt.Value}) instrs = append(instrs,
instrs = append(instrs, instruction.Call{Index: c.function(opaNumberInt)}) instruction.I64Const{Value: stmt.Value},
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaNumberInt)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.MakeNumberRefStmt: case *ir.MakeNumberRefStmt:
instrs = append(instrs, instruction.I32Const{Value: c.stringAddr(stmt.Index)}) instrs = append(instrs,
instrs = append(instrs, instruction.I32Const{Value: int32(len(c.policy.Static.Strings[stmt.Index].Value))}) instruction.I32Const{Value: c.stringAddr(stmt.Index)},
instrs = append(instrs, instruction.Call{Index: c.function(opaNumberRef)}) instruction.I32Const{Value: int32(len(c.policy.Static.Strings[stmt.Index].Value))},
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaNumberRef)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.MakeArrayStmt: case *ir.MakeArrayStmt:
instrs = append(instrs, instruction.I32Const{Value: stmt.Capacity}) instrs = append(instrs,
instrs = append(instrs, instruction.Call{Index: c.function(opaArrayWithCap)}) instruction.I32Const{Value: stmt.Capacity},
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaArrayWithCap)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.MakeObjectStmt: case *ir.MakeObjectStmt:
instrs = append(instrs, instruction.Call{Index: c.function(opaObject)}) instrs = append(instrs,
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaObject)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.MakeSetStmt: case *ir.MakeSetStmt:
instrs = append(instrs, instruction.Call{Index: c.function(opaSet)}) instrs = append(instrs,
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaSet)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.IsArrayStmt: case *ir.IsArrayStmt:
if loc, ok := stmt.Source.Value.(ir.Local); ok { if loc, ok := stmt.Source.Value.(ir.Local); ok {
instrs = append(instrs, instruction.GetLocal{Index: c.local(loc)}) instrs = append(instrs,
instrs = append(instrs, instruction.Call{Index: c.function(opaValueType)}) instruction.GetLocal{Index: c.local(loc)},
instrs = append(instrs, instruction.I32Const{Value: opaTypeArray}) instruction.Call{Index: c.function(opaValueType)},
instrs = append(instrs, instruction.I32Ne{}) instruction.I32Const{Value: opaTypeArray},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.I32Ne{},
instruction.BrIf{Index: 0},
)
} else { } else {
instrs = append(instrs, instruction.Br{Index: 0}) instrs = append(instrs, instruction.Br{Index: 0})
break break
} }
case *ir.IsObjectStmt: case *ir.IsObjectStmt:
if loc, ok := stmt.Source.Value.(ir.Local); ok { if loc, ok := stmt.Source.Value.(ir.Local); ok {
instrs = append(instrs, instruction.GetLocal{Index: c.local(loc)}) instrs = append(instrs,
instrs = append(instrs, instruction.Call{Index: c.function(opaValueType)}) instruction.GetLocal{Index: c.local(loc)},
instrs = append(instrs, instruction.I32Const{Value: opaTypeObject}) instruction.Call{Index: c.function(opaValueType)},
instrs = append(instrs, instruction.I32Ne{}) instruction.I32Const{Value: opaTypeObject},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.I32Ne{},
instruction.BrIf{Index: 0},
)
} else { } else {
instrs = append(instrs, instruction.Br{Index: 0}) instrs = append(instrs, instruction.Br{Index: 0})
break break
} }
case *ir.IsSetStmt: case *ir.IsSetStmt:
if loc, ok := stmt.Source.Value.(ir.Local); ok { if loc, ok := stmt.Source.Value.(ir.Local); ok {
instrs = append(instrs, instruction.GetLocal{Index: c.local(loc)}) instrs = append(instrs,
instrs = append(instrs, instruction.Call{Index: c.function(opaValueType)}) instruction.GetLocal{Index: c.local(loc)},
instrs = append(instrs, instruction.I32Const{Value: opaTypeSet}) instruction.Call{Index: c.function(opaValueType)},
instrs = append(instrs, instruction.I32Ne{}) instruction.I32Const{Value: opaTypeSet},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.I32Ne{},
instruction.BrIf{Index: 0},
)
} else { } else {
instrs = append(instrs, instruction.Br{Index: 0}) instrs = append(instrs, instruction.Br{Index: 0})
break break
} }
case *ir.IsUndefinedStmt: case *ir.IsUndefinedStmt:
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Source)}) instrs = append(instrs,
instrs = append(instrs, instruction.I32Const{Value: 0}) instruction.GetLocal{Index: c.local(stmt.Source)},
instrs = append(instrs, instruction.I32Ne{}) instruction.I32Const{Value: 0},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.I32Ne{},
instruction.BrIf{Index: 0},
)
case *ir.ResetLocalStmt: case *ir.ResetLocalStmt:
instrs = append(instrs, instruction.I32Const{Value: 0}) instrs = append(instrs,
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.I32Const{Value: 0},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.IsDefinedStmt: case *ir.IsDefinedStmt:
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Source)}) instrs = append(instrs,
instrs = append(instrs, instruction.I32Eqz{}) instruction.GetLocal{Index: c.local(stmt.Source)},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.I32Eqz{},
instruction.BrIf{Index: 0},
)
case *ir.ArrayAppendStmt: case *ir.ArrayAppendStmt:
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Array)}) instrs = append(instrs,
instrs = append(instrs, c.instrRead(stmt.Value)) instruction.GetLocal{Index: c.local(stmt.Array)},
instrs = append(instrs, instruction.Call{Index: c.function(opaArrayAppend)}) c.instrRead(stmt.Value),
instruction.Call{Index: c.function(opaArrayAppend)},
)
case *ir.ObjectInsertStmt: case *ir.ObjectInsertStmt:
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Object)}) instrs = append(instrs,
instrs = append(instrs, c.instrRead(stmt.Key)) instruction.GetLocal{Index: c.local(stmt.Object)},
instrs = append(instrs, c.instrRead(stmt.Value)) c.instrRead(stmt.Key),
instrs = append(instrs, instruction.Call{Index: c.function(opaObjectInsert)}) c.instrRead(stmt.Value),
instruction.Call{Index: c.function(opaObjectInsert)},
)
case *ir.ObjectInsertOnceStmt: case *ir.ObjectInsertOnceStmt:
tmp := c.genLocal() tmp := c.genLocal()
instrs = append(instrs, instruction.Block{ instrs = append(instrs, instruction.Block{
@@ -1203,14 +1241,18 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
}, },
}) })
case *ir.ObjectMergeStmt: case *ir.ObjectMergeStmt:
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.A)}) instrs = append(instrs,
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.B)}) instruction.GetLocal{Index: c.local(stmt.A)},
instrs = append(instrs, instruction.Call{Index: c.function(opaValueMerge)}) instruction.GetLocal{Index: c.local(stmt.B)},
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) instruction.Call{Index: c.function(opaValueMerge)},
instruction.SetLocal{Index: c.local(stmt.Target)},
)
case *ir.SetAddStmt: case *ir.SetAddStmt:
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Set)}) instrs = append(instrs,
instrs = append(instrs, c.instrRead(stmt.Value)) instruction.GetLocal{Index: c.local(stmt.Set)},
instrs = append(instrs, instruction.Call{Index: c.function(opaSetAdd)}) c.instrRead(stmt.Value),
instruction.Call{Index: c.function(opaSetAdd)},
)
default: default:
var buf bytes.Buffer var buf bytes.Buffer
err := ir.Pretty(&buf, stmt) err := ir.Pretty(&buf, stmt)
@@ -1226,8 +1268,7 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
func (c *Compiler) compileScan(scan *ir.ScanStmt, result *[]instruction.Instruction) error { func (c *Compiler) compileScan(scan *ir.ScanStmt, result *[]instruction.Instruction) error {
var instrs = *result var instrs = *result
instrs = append(instrs, instruction.I32Const{Value: 0}) instrs = append(instrs, instruction.I32Const{Value: 0}, instruction.SetLocal{Index: c.local(scan.Key)})
instrs = append(instrs, instruction.SetLocal{Index: c.local(scan.Key)})
body, err := c.compileScanBlock(scan) body, err := c.compileScanBlock(scan)
if err != nil { if err != nil {
return err return err
@@ -1242,23 +1283,21 @@ func (c *Compiler) compileScan(scan *ir.ScanStmt, result *[]instruction.Instruct
} }
func (c *Compiler) compileScanBlock(scan *ir.ScanStmt) ([]instruction.Instruction, error) { func (c *Compiler) compileScanBlock(scan *ir.ScanStmt) ([]instruction.Instruction, error) {
var instrs []instruction.Instruction instrs := []instruction.Instruction{
// Execute iterator.
// Execute iterator. instruction.GetLocal{Index: c.local(scan.Source)},
instrs = append(instrs, instruction.GetLocal{Index: c.local(scan.Source)}) instruction.GetLocal{Index: c.local(scan.Key)},
instrs = append(instrs, instruction.GetLocal{Index: c.local(scan.Key)}) instruction.Call{Index: c.function(opaValueIter)},
instrs = append(instrs, instruction.Call{Index: c.function(opaValueIter)}) // Check for emptiness.
instruction.TeeLocal{Index: c.local(scan.Key)},
// Check for emptiness. instruction.I32Eqz{},
instrs = append(instrs, instruction.TeeLocal{Index: c.local(scan.Key)}) instruction.BrIf{Index: 1},
instrs = append(instrs, instruction.I32Eqz{}) // Load value.
instrs = append(instrs, instruction.BrIf{Index: 1}) instruction.GetLocal{Index: c.local(scan.Source)},
instruction.GetLocal{Index: c.local(scan.Key)},
// Load value. instruction.Call{Index: c.function(opaValueGet)},
instrs = append(instrs, instruction.GetLocal{Index: c.local(scan.Source)}) instruction.SetLocal{Index: c.local(scan.Value)},
instrs = append(instrs, instruction.GetLocal{Index: c.local(scan.Key)}) }
instrs = append(instrs, instruction.Call{Index: c.function(opaValueGet)})
instrs = append(instrs, instruction.SetLocal{Index: c.local(scan.Value)})
// Loop body. // Loop body.
nested, err := c.compileBlock(scan.Block) nested, err := c.compileBlock(scan.Block)
@@ -1278,8 +1317,7 @@ func (c *Compiler) compileNot(not *ir.NotStmt, result *[]instruction.Instruction
// generate and initialize condition variable // generate and initialize condition variable
cond := c.genLocal() cond := c.genLocal()
instrs = append(instrs, instruction.I32Const{Value: 1}) instrs = append(instrs, instruction.I32Const{Value: 1}, instruction.SetLocal{Index: cond})
instrs = append(instrs, instruction.SetLocal{Index: cond})
nested, err := c.compileBlock(not.Block) nested, err := c.compileBlock(not.Block)
if err != nil { if err != nil {
@@ -1287,14 +1325,15 @@ func (c *Compiler) compileNot(not *ir.NotStmt, result *[]instruction.Instruction
} }
// unset condition variable if end of block is reached // unset condition variable if end of block is reached
nested = append(nested, instruction.I32Const{Value: 0}) instrs = append(instrs, instruction.Block{Instrs: append(nested,
nested = append(nested, instruction.SetLocal{Index: cond}) instruction.I32Const{Value: 0},
instrs = append(instrs, instruction.Block{Instrs: nested}) instruction.SetLocal{Index: cond},
)},
// break out of block if condition variable was unset // break out of block if condition variable was unset
instrs = append(instrs, instruction.GetLocal{Index: cond}) instruction.GetLocal{Index: cond},
instrs = append(instrs, instruction.I32Eqz{}) instruction.I32Eqz{},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.BrIf{Index: 0},
)
*result = instrs *result = instrs
return nil return nil
@@ -1304,34 +1343,36 @@ func (c *Compiler) compileWithStmt(with *ir.WithStmt, result *[]instruction.Inst
var instrs = *result var instrs = *result
save := c.genLocal() save := c.genLocal()
instrs = append(instrs, instruction.Call{Index: c.function(opaMemoizePush)}) instrs = append(instrs,
instrs = append(instrs, instruction.GetLocal{Index: c.local(with.Local)}) instruction.Call{Index: c.function(opaMemoizePush)},
instrs = append(instrs, instruction.SetLocal{Index: save}) instruction.GetLocal{Index: c.local(with.Local)},
instruction.SetLocal{Index: save},
)
if len(with.Path) == 0 { if len(with.Path) == 0 {
instrs = append(instrs, c.instrRead(with.Value)) instrs = append(instrs, c.instrRead(with.Value), instruction.SetLocal{Index: c.local(with.Local)})
instrs = append(instrs, instruction.SetLocal{Index: c.local(with.Local)})
} else { } else {
instrs = c.compileUpsert(with.Local, with.Path, with.Value, with.Location, instrs) instrs = c.compileUpsert(with.Local, with.Path, with.Value, with.Location, instrs)
} }
undefined := c.genLocal() undefined := c.genLocal()
instrs = append(instrs, instruction.I32Const{Value: 1}) instrs = append(instrs, instruction.I32Const{Value: 1}, instruction.SetLocal{Index: undefined})
instrs = append(instrs, instruction.SetLocal{Index: undefined})
nested, err := c.compileBlock(with.Block) nested, err := c.compileBlock(with.Block)
if err != nil { if err != nil {
return err return err
} }
nested = append(nested, instruction.I32Const{Value: 0}) nested = append(nested, instruction.I32Const{Value: 0}, instruction.SetLocal{Index: undefined})
nested = append(nested, instruction.SetLocal{Index: undefined})
instrs = append(instrs, instruction.Block{Instrs: nested}) instrs = append(instrs,
instrs = append(instrs, instruction.GetLocal{Index: save}) instruction.Block{Instrs: nested},
instrs = append(instrs, instruction.SetLocal{Index: c.local(with.Local)}) instruction.GetLocal{Index: save},
instrs = append(instrs, instruction.Call{Index: c.function(opaMemoizePop)}) instruction.SetLocal{Index: c.local(with.Local)},
instrs = append(instrs, instruction.GetLocal{Index: undefined}) instruction.Call{Index: c.function(opaMemoizePop)},
instrs = append(instrs, instruction.BrIf{Index: 0}) instruction.GetLocal{Index: undefined},
instruction.BrIf{Index: 0},
)
*result = instrs *result = instrs
@@ -1339,37 +1380,38 @@ func (c *Compiler) compileWithStmt(with *ir.WithStmt, result *[]instruction.Inst
} }
func (c *Compiler) compileUpsert(local ir.Local, path []int, value ir.Operand, _ ir.Location, instrs []instruction.Instruction) []instruction.Instruction { func (c *Compiler) compileUpsert(local ir.Local, path []int, value ir.Operand, _ ir.Location, instrs []instruction.Instruction) []instruction.Instruction {
lcopy := c.genLocal() // holds copy of local lcopy := c.genLocal() // holds copy of local
instrs = append(instrs, instruction.GetLocal{Index: c.local(local)}) instrs = append(instrs,
instrs = append(instrs, instruction.SetLocal{Index: lcopy}) instruction.GetLocal{Index: c.local(local)},
instruction.SetLocal{Index: lcopy},
// Shallow copy the local if defined otherwise initialize to an empty object. // Shallow copy the local if defined otherwise initialize to an empty object.
instrs = append(instrs, instruction.Block{ instruction.Block{
Instrs: []instruction.Instruction{ Instrs: []instruction.Instruction{
instruction.Block{Instrs: []instruction.Instruction{ instruction.Block{Instrs: []instruction.Instruction{
instruction.GetLocal{Index: lcopy}, instruction.GetLocal{Index: lcopy},
instruction.I32Eqz{}, instruction.I32Eqz{},
instruction.BrIf{Index: 0}, instruction.BrIf{Index: 0},
instruction.GetLocal{Index: lcopy}, instruction.GetLocal{Index: lcopy},
instruction.Call{Index: c.function(opaValueShallowCopy)}, instruction.Call{Index: c.function(opaValueShallowCopy)},
instruction.TeeLocal{Index: lcopy},
instruction.SetLocal{Index: c.local(local)},
instruction.Br{Index: 1},
}},
instruction.Call{Index: c.function(opaObject)},
instruction.TeeLocal{Index: lcopy}, instruction.TeeLocal{Index: lcopy},
instruction.SetLocal{Index: c.local(local)}, instruction.SetLocal{Index: c.local(local)},
instruction.Br{Index: 1}, },
}}, })
instruction.Call{Index: c.function(opaObject)},
instruction.TeeLocal{Index: lcopy},
instruction.SetLocal{Index: c.local(local)},
},
})
// Initialize the locals that specify the path of the upsert operation. // Initialize the locals that specify the path of the upsert operation.
lpath := make(map[int]uint32, len(path)) lpath := make(map[int]uint32, len(path))
for i := range path { for i := range path {
lpath[i] = c.genLocal() lpath[i] = c.genLocal()
instrs = append(instrs, instruction.I32Const{Value: c.opaStringAddr(path[i])}) instrs = append(instrs,
instrs = append(instrs, instruction.SetLocal{Index: lpath[i]}) instruction.I32Const{Value: c.opaStringAddr(path[i])},
instruction.SetLocal{Index: lpath[i]},
)
} }
// Generate a block that traverses the path of the upsert operation, // Generate a block that traverses the path of the upsert operation,
@@ -1379,36 +1421,34 @@ func (c *Compiler) compileUpsert(local ir.Local, path []int, value ir.Operand, _
ltemp := c.genLocal() ltemp := c.genLocal()
for i := range len(path) - 1 { for i := range len(path) - 1 {
inner = append(inner,
// Lookup the next part of the path. // Lookup the next part of the path.
inner = append(inner, instruction.GetLocal{Index: lcopy}) instruction.GetLocal{Index: lcopy},
inner = append(inner, instruction.GetLocal{Index: lpath[i]}) instruction.GetLocal{Index: lpath[i]},
inner = append(inner, instruction.Call{Index: c.function(opaValueGet)}) instruction.Call{Index: c.function(opaValueGet)},
inner = append(inner, instruction.SetLocal{Index: ltemp}) instruction.SetLocal{Index: ltemp},
// If the next node is missing, break.
// If the next node is missing, break. instruction.GetLocal{Index: ltemp},
inner = append(inner, instruction.GetLocal{Index: ltemp}) instruction.I32Eqz{},
inner = append(inner, instruction.I32Eqz{}) instruction.BrIf{Index: uint32(i)},
inner = append(inner, instruction.BrIf{Index: uint32(i)}) // If the next node is not an object, break.
instruction.GetLocal{Index: ltemp},
// If the next node is not an object, break. instruction.Call{Index: c.function(opaValueType)},
inner = append(inner, instruction.GetLocal{Index: ltemp}) instruction.I32Const{Value: opaTypeObject},
inner = append(inner, instruction.Call{Index: c.function(opaValueType)}) instruction.I32Ne{},
inner = append(inner, instruction.I32Const{Value: opaTypeObject}) instruction.BrIf{Index: uint32(i)},
inner = append(inner, instruction.I32Ne{}) // Otherwise, shallow copy the next node node and insert into the copy
inner = append(inner, instruction.BrIf{Index: uint32(i)}) // before continuing.
instruction.GetLocal{Index: ltemp},
// Otherwise, shallow copy the next node node and insert into the copy instruction.Call{Index: c.function(opaValueShallowCopy)},
// before continuing. instruction.SetLocal{Index: ltemp},
inner = append(inner, instruction.GetLocal{Index: ltemp}) instruction.GetLocal{Index: lcopy},
inner = append(inner, instruction.Call{Index: c.function(opaValueShallowCopy)}) instruction.GetLocal{Index: lpath[i]},
inner = append(inner, instruction.SetLocal{Index: ltemp}) instruction.GetLocal{Index: ltemp},
inner = append(inner, instruction.GetLocal{Index: lcopy}) instruction.Call{Index: c.function(opaObjectInsert)},
inner = append(inner, instruction.GetLocal{Index: lpath[i]}) instruction.GetLocal{Index: ltemp},
inner = append(inner, instruction.GetLocal{Index: ltemp}) instruction.SetLocal{Index: lcopy},
inner = append(inner, instruction.Call{Index: c.function(opaObjectInsert)}) )
inner = append(inner, instruction.GetLocal{Index: ltemp})
inner = append(inner, instruction.SetLocal{Index: lcopy})
} }
inner = append(inner, instruction.Br{Index: uint32(len(path) - 1)}) inner = append(inner, instruction.Br{Index: uint32(len(path) - 1)})
@@ -1418,27 +1458,29 @@ func (c *Compiler) compileUpsert(local ir.Local, path []int, value ir.Operand, _
lval := c.genLocal() lval := c.genLocal()
for i := range len(path) - 1 { for i := range len(path) - 1 {
block = append(block, instruction.Block{Instrs: inner}) block = append(block,
block = append(block, instruction.Call{Index: c.function(opaObject)}) instruction.Block{Instrs: inner},
block = append(block, instruction.SetLocal{Index: lval}) instruction.Call{Index: c.function(opaObject)},
block = append(block, instruction.GetLocal{Index: lcopy}) instruction.SetLocal{Index: lval},
block = append(block, instruction.GetLocal{Index: lpath[i]}) instruction.GetLocal{Index: lcopy},
block = append(block, instruction.GetLocal{Index: lval}) instruction.GetLocal{Index: lpath[i]},
block = append(block, instruction.Call{Index: c.function(opaObjectInsert)}) instruction.GetLocal{Index: lval},
block = append(block, instruction.GetLocal{Index: lval}) instruction.Call{Index: c.function(opaObjectInsert)},
block = append(block, instruction.SetLocal{Index: lcopy}) instruction.GetLocal{Index: lval},
instruction.SetLocal{Index: lcopy},
)
inner = block inner = block
block = nil block = nil
} }
// Finish by inserting the statement's value into the shallow copied node. // Finish by inserting the statement's value into the shallow copied node.
instrs = append(instrs, instruction.Block{Instrs: inner}) return append(instrs,
instrs = append(instrs, instruction.GetLocal{Index: lcopy}) instruction.Block{Instrs: inner},
instrs = append(instrs, instruction.GetLocal{Index: lpath[len(path)-1]}) instruction.GetLocal{Index: lcopy},
instrs = append(instrs, c.instrRead(value)) instruction.GetLocal{Index: lpath[len(path)-1]},
instrs = append(instrs, instruction.Call{Index: c.function(opaObjectInsert)}) c.instrRead(value),
instruction.Call{Index: c.function(opaObjectInsert)},
return instrs )
} }
func (c *Compiler) compileCallDynamicStmt(stmt *ir.CallDynamicStmt, result *[]instruction.Instruction) error { func (c *Compiler) compileCallDynamicStmt(stmt *ir.CallDynamicStmt, result *[]instruction.Instruction) error {
-1
View File
@@ -23,7 +23,6 @@
// //
// created 16-06-2013 // created 16-06-2013
// nolint: deadcode // Package in development (2021).
package gojsonschema package gojsonschema
import ( import (
+1 -1
View File
@@ -23,7 +23,7 @@
// //
// created 26-02-2013 // created 26-02-2013
// nolint: deadcode,unused,varcheck // Package in development (2021). // nolint:unused,varcheck // Package in development (2021).
package gojsonschema package gojsonschema
import ( import (
+1 -1
View File
@@ -54,7 +54,7 @@ func (*prettyFormatter) Format(e *logrus.Entry) ([]byte, error) {
b := new(bytes.Buffer) b := new(bytes.Buffer)
level := strings.ToUpper(e.Level.String()) level := strings.ToUpper(e.Level.String())
b.WriteString(fmt.Sprintf("[%s] %s\n", level, e.Message)) fmt.Fprintf(b, "[%s] %s\n", level, e.Message)
// Format each key for optimal ease of human reading // Format each key for optimal ease of human reading
fieldIndent := 2 fieldIndent := 2
+2
View File
@@ -158,6 +158,8 @@ func SignV4(headers map[string][]string, method string, theURL *url.URL, body []
// include the values for the signed headers // include the values for the signed headers
orderedKeys := util.KeysSorted(headersToSign) orderedKeys := util.KeysSorted(headersToSign)
for _, k := range orderedKeys { for _, k := range orderedKeys {
// TODO: fix later
//nolint:perfsprint
canonicalReq += k + ":" + strings.Join(headersToSign[k], ",") + "\n" canonicalReq += k + ":" + strings.Join(headersToSign[k], ",") + "\n"
} }
canonicalReq += "\n" // linefeed to terminate headers canonicalReq += "\n" // linefeed to terminate headers
+3
View File
@@ -77,6 +77,7 @@ func Schemas(schemaPath string) (*ast.SchemaSet, error) {
} }
// All returns a Result object loaded (recursively) from the specified paths. // All returns a Result object loaded (recursively) from the specified paths.
//
// Deprecated: Use FileLoader.Filtered() instead. // Deprecated: Use FileLoader.Filtered() instead.
func All(paths []string) (*Result, error) { func All(paths []string) (*Result, error) {
return NewFileLoader().Filtered(paths, nil) return NewFileLoader().Filtered(paths, nil)
@@ -85,6 +86,7 @@ func All(paths []string) (*Result, error) {
// Filtered returns a Result object loaded (recursively) from the specified // Filtered returns a Result object loaded (recursively) from the specified
// paths while applying the given filters. If any filter returns true, the // paths while applying the given filters. If any filter returns true, the
// file/directory is excluded. // file/directory is excluded.
//
// Deprecated: Use FileLoader.Filtered() instead. // Deprecated: Use FileLoader.Filtered() instead.
func Filtered(paths []string, filter Filter) (*Result, error) { func Filtered(paths []string, filter Filter) (*Result, error) {
return NewFileLoader().Filtered(paths, filter) return NewFileLoader().Filtered(paths, filter)
@@ -93,6 +95,7 @@ func Filtered(paths []string, filter Filter) (*Result, error) {
// AsBundle loads a path as a bundle. If it is a single file // AsBundle loads a path as a bundle. If it is a single file
// it will be treated as a normal tarball bundle. If a directory // it will be treated as a normal tarball bundle. If a directory
// is supplied it will be loaded as an unzipped bundle tree. // is supplied it will be loaded as an unzipped bundle tree.
//
// Deprecated: Use FileLoader.AsBundle() instead. // Deprecated: Use FileLoader.AsBundle() instead.
func AsBundle(path string) (*bundle.Bundle, error) { func AsBundle(path string) (*bundle.Bundle, error) {
return NewFileLoader().AsBundle(path) return NewFileLoader().AsBundle(path)
+1
View File
@@ -11,6 +11,7 @@ import (
// ParseConfig validates the config and injects default values. This is // ParseConfig validates the config and injects default values. This is
// for the legacy single bundle configuration. This will add the bundle // for the legacy single bundle configuration. This will add the bundle
// to the `Bundles` map to provide compatibility with newer clients. // to the `Bundles` map to provide compatibility with newer clients.
//
// Deprecated: Use `ParseBundlesConfig` with `bundles` OPA config option instead // Deprecated: Use `ParseBundlesConfig` with `bundles` OPA config option instead
func ParseConfig(config []byte, services []string) (*Config, error) { func ParseConfig(config []byte, services []string) (*Config, error) {
return v1.ParseConfig(config, services) return v1.ParseConfig(config, services)
+2
View File
@@ -68,6 +68,7 @@ func EvalInstrument(instrument bool) EvalOption {
} }
// EvalTracer configures a tracer for a Prepared Query's evaluation // EvalTracer configures a tracer for a Prepared Query's evaluation
//
// Deprecated: Use EvalQueryTracer instead. // Deprecated: Use EvalQueryTracer instead.
func EvalTracer(tracer topdown.Tracer) EvalOption { func EvalTracer(tracer topdown.Tracer) EvalOption {
return v1.EvalTracer(tracer) return v1.EvalTracer(tracer)
@@ -441,6 +442,7 @@ func Trace(yes bool) func(r *Rego) {
} }
// Tracer returns an argument that adds a query tracer to r. // Tracer returns an argument that adds a query tracer to r.
//
// Deprecated: Use QueryTracer instead. // Deprecated: Use QueryTracer instead.
func Tracer(t topdown.Tracer) func(r *Rego) { func Tracer(t topdown.Tracer) func(r *Rego) {
return v1.Tracer(t) return v1.Tracer(t)
+1
View File
@@ -201,6 +201,7 @@ const (
// ParamBundleActivationV1 defines the name of the HTTP URL parameter that // ParamBundleActivationV1 defines the name of the HTTP URL parameter that
// indicates the client wants to include bundle activation in the results // indicates the client wants to include bundle activation in the results
// of the health API. // of the health API.
//
// Deprecated: Use ParamBundlesActivationV1 instead. // Deprecated: Use ParamBundlesActivationV1 instead.
ParamBundleActivationV1 = v1.ParamBundleActivationV1 ParamBundleActivationV1 = v1.ParamBundleActivationV1
+2
View File
@@ -37,6 +37,7 @@ func Error(w http.ResponseWriter, status int, err *types.ErrorV1) {
// JSON writes a response with the specified status code and object. The object // JSON writes a response with the specified status code and object. The object
// will be JSON serialized. // will be JSON serialized.
//
// Deprecated: This method is problematic when using a non-200 status `code`: if // Deprecated: This method is problematic when using a non-200 status `code`: if
// encoding the payload fails, it'll print "superfluous call to WriteHeader()" // encoding the payload fails, it'll print "superfluous call to WriteHeader()"
// logs. // logs.
@@ -50,6 +51,7 @@ func JSONOK(w http.ResponseWriter, v any, pretty bool) {
} }
// Bytes writes a response with the specified status code and bytes. // Bytes writes a response with the specified status code and bytes.
//
// Deprecated: Unused in OPA, will be removed in the future. // Deprecated: Unused in OPA, will be removed in the future.
func Bytes(w http.ResponseWriter, code int, bs []byte) { func Bytes(w http.ResponseWriter, code int, bs []byte) {
v1.Bytes(w, code, bs) v1.Bytes(w, code, bs)
+1
View File
@@ -63,6 +63,7 @@ type VarMetadata = v1.VarMetadata
type Event = v1.Event type Event = v1.Event
// Tracer defines the interface for tracing in the top-down evaluation engine. // Tracer defines the interface for tracing in the top-down evaluation engine.
//
// Deprecated: Use QueryTracer instead. // Deprecated: Use QueryTracer instead.
type Tracer = v1.Tracer type Tracer = v1.Tracer
+2
View File
@@ -440,6 +440,7 @@ func (c *Compiler) WithDebug(sink io.Writer) *Compiler {
} }
// WithBuiltins is deprecated. // WithBuiltins is deprecated.
//
// Deprecated: Use WithCapabilities instead. // Deprecated: Use WithCapabilities instead.
func (c *Compiler) WithBuiltins(builtins map[string]*Builtin) *Compiler { func (c *Compiler) WithBuiltins(builtins map[string]*Builtin) *Compiler {
c.customBuiltins = maps.Clone(builtins) c.customBuiltins = maps.Clone(builtins)
@@ -447,6 +448,7 @@ func (c *Compiler) WithBuiltins(builtins map[string]*Builtin) *Compiler {
} }
// WithUnsafeBuiltins is deprecated. // WithUnsafeBuiltins is deprecated.
//
// Deprecated: Use WithCapabilities instead. // Deprecated: Use WithCapabilities instead.
func (c *Compiler) WithUnsafeBuiltins(unsafeBuiltins map[string]struct{}) *Compiler { func (c *Compiler) WithUnsafeBuiltins(unsafeBuiltins map[string]struct{}) *Compiler {
maps.Copy(c.unsafeBuiltinsMap, unsafeBuiltins) maps.Copy(c.unsafeBuiltinsMap, unsafeBuiltins)
+1
View File
@@ -29,6 +29,7 @@ func newTypeEnv(f func() *typeChecker) *TypeEnv {
} }
// Get returns the type of x. // Get returns the type of x.
//
// Deprecated: Use GetByValue or GetByRef instead, as they are more efficient. // Deprecated: Use GetByValue or GetByRef instead, as they are more efficient.
func (env *TypeEnv) Get(x any) types.Type { func (env *TypeEnv) Get(x any) types.Type {
if term, ok := x.(*Term); ok { if term, ok := x.(*Term); ok {
+10 -5
View File
@@ -99,19 +99,24 @@ func (e *Error) Error() string {
} }
} }
msg := fmt.Sprintf("%v: %v", e.Code, e.Message) sb := strings.Builder{}
if len(prefix) > 0 { if len(prefix) > 0 {
msg = prefix + ": " + msg sb.WriteString(prefix)
sb.WriteString(": ")
} }
sb.WriteString(e.Code)
sb.WriteString(": ")
sb.WriteString(e.Message)
if e.Details != nil { if e.Details != nil {
for _, line := range e.Details.Lines() { for _, line := range e.Details.Lines() {
msg += "\n\t" + line sb.WriteString("\n\t")
sb.WriteString(line)
} }
} }
return msg return sb.String()
} }
// NewError returns a new Error object. // NewError returns a new Error object.
+3 -2
View File
@@ -884,7 +884,6 @@ func indexValue(b Value) (Value, bool) {
} }
func globDelimiterToString(delim *Term) (string, bool) { func globDelimiterToString(delim *Term) (string, bool) {
arr, ok := delim.Value.(*Array) arr, ok := delim.Value.(*Array)
if !ok { if !ok {
return "", false return "", false
@@ -895,14 +894,16 @@ func globDelimiterToString(delim *Term) (string, bool) {
if arr.Len() == 0 { if arr.Len() == 0 {
result = "." result = "."
} else { } else {
sb := strings.Builder{}
for i := range arr.Len() { for i := range arr.Len() {
term := arr.Elem(i) term := arr.Elem(i)
s, ok := term.Value.(String) s, ok := term.Value.(String)
if !ok { if !ok {
return "", false return "", false
} }
result += string(s) sb.WriteString(string(s))
} }
result = sb.String()
} }
return result, true return result, true
+1
View File
@@ -220,6 +220,7 @@ func runParseStatementBenchmarkWithError(b *testing.B, stmt string) {
func generateModule(numRules int) string { func generateModule(numRules int) string {
mod := "package bench\n" mod := "package bench\n"
for i := range numRules { for i := range numRules {
//nolint:perfsprint
mod += fmt.Sprintf("p%d if { input.x%d = %d }\n", i, i, i) mod += fmt.Sprintf("p%d if { input.x%d = %d }\n", i, i, i)
} }
return mod return mod
+1
View File
@@ -5560,6 +5560,7 @@ func TestRuleFromBody(t *testing.T) {
// Verify the rule and rule and rule head col/loc values // Verify the rule and rule and rule head col/loc values
testModule := "package a.b.c\n\n" testModule := "package a.b.c\n\n"
for _, tc := range tests { for _, tc := range tests {
//nolint:perfsprint
testModule += tc.input + "\n" testModule += tc.input + "\n"
} }
module, err := ParseModuleWithOpts("test.rego", testModule, popts) module, err := ParseModuleWithOpts("test.rego", testModule, popts)
+5 -2
View File
@@ -379,8 +379,10 @@ func (mod *Module) String() string {
appendAnnotationStrings := func(buf []string, node Node) []string { appendAnnotationStrings := func(buf []string, node Node) []string {
if as, ok := byNode[node]; ok { if as, ok := byNode[node]; ok {
for i := range as { for i := range as {
buf = append(buf, "# METADATA") buf = append(buf,
buf = append(buf, "# "+as[i].String()) "# METADATA",
"# "+as[i].String(),
)
} }
} }
return buf return buf
@@ -730,6 +732,7 @@ func (rule *Rule) SetLoc(loc *Location) {
// Path returns a ref referring to the document produced by this rule. If rule // Path returns a ref referring to the document produced by this rule. If rule
// is not contained in a module, this function panics. // is not contained in a module, this function panics.
//
// Deprecated: Poor handling of ref rules. Use `(*Rule).Ref()` instead. // Deprecated: Poor handling of ref rules. Use `(*Rule).Ref()` instead.
func (rule *Rule) Path() Ref { func (rule *Rule) Path() Ref {
if rule.Module == nil { if rule.Module == nil {
+54 -47
View File
@@ -41,17 +41,17 @@ func testParseSchema(t *testing.T, schema string, expectedType types.Type, expec
} }
func TestParseSchemaObject(t *testing.T) { func TestParseSchemaObject(t *testing.T) {
innerObjectStaticProps := []*types.StaticProperty{} innerObjectStaticProps := append([]*types.StaticProperty{},
innerObjectStaticProps = append(innerObjectStaticProps, &types.StaticProperty{Key: "a", Value: types.N}) &types.StaticProperty{Key: "a", Value: types.N},
innerObjectStaticProps = append(innerObjectStaticProps, &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.N)}) &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.N)},
innerObjectStaticProps = append(innerObjectStaticProps, &types.StaticProperty{Key: "c", Value: types.A}) &types.StaticProperty{Key: "c", Value: types.A},
innerObjectType := types.NewObject(innerObjectStaticProps, nil) )
staticProps := append([]*types.StaticProperty{},
staticProps := []*types.StaticProperty{} &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.NewObject(innerObjectStaticProps, nil))},
staticProps = append(staticProps, &types.StaticProperty{Key: "b", Value: types.NewArray(nil, innerObjectType)}) &types.StaticProperty{Key: "foo", Value: types.S},
staticProps = append(staticProps, &types.StaticProperty{Key: "foo", Value: types.S}) )
expectedType := types.NewObject(staticProps, nil) expectedType := types.NewObject(staticProps, nil)
testParseSchema(t, objectSchema, expectedType, nil) testParseSchema(t, objectSchema, expectedType, nil)
} }
@@ -141,25 +141,27 @@ func TestSetTypesWithPodSchema(t *testing.T) {
func TestAllOfSchemas(t *testing.T) { func TestAllOfSchemas(t *testing.T) {
// Test 1: object schema // Test 1: object schema
objectSchemaStaticProps := []*types.StaticProperty{} objectSchemaStaticProps := []*types.StaticProperty{
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine1", Value: types.S}) {Key: "AddressLine1", Value: types.S},
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine2", Value: types.S}) {Key: "AddressLine2", Value: types.S},
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "City", Value: types.S}) {Key: "City", Value: types.S},
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "State", Value: types.S}) {Key: "State", Value: types.S},
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S}) {Key: "ZipCode", Value: types.S},
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "County", Value: types.S}) {Key: "County", Value: types.S},
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S}) {Key: "PostCode", Value: types.S},
}
objectSchemaExpectedType := types.NewObject(objectSchemaStaticProps, nil) objectSchemaExpectedType := types.NewObject(objectSchemaStaticProps, nil)
// Test 2: array schema // Test 2: array schema
arrayExpectedType := types.NewArray(nil, types.N) arrayExpectedType := types.NewArray(nil, types.N)
// Test 3: parent variation // Test 3: parent variation
parentVariationStaticProps := []*types.StaticProperty{} parentVariationStaticProps := []*types.StaticProperty{
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "State", Value: types.S}) {Key: "State", Value: types.S},
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S}) {Key: "ZipCode", Value: types.S},
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "County", Value: types.S}) {Key: "County", Value: types.S},
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S}) {Key: "PostCode", Value: types.S},
}
parentVariationExpectedType := types.NewObject(parentVariationStaticProps, nil) parentVariationExpectedType := types.NewObject(parentVariationStaticProps, nil)
// Test 4: empty schema with allOf // Test 4: empty schema with allOf
@@ -169,23 +171,25 @@ func TestAllOfSchemas(t *testing.T) {
expectedError := errors.New("unable to merge these schemas") expectedError := errors.New("unable to merge these schemas")
// Test 7: array of objects // Test 7: array of objects
arrayOfObjectsStaticProps := []*types.StaticProperty{} arrayOfObjectsStaticProps := []*types.StaticProperty{
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "State", Value: types.S}) {Key: "State", Value: types.S},
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S}) {Key: "ZipCode", Value: types.S},
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "County", Value: types.S}) {Key: "County", Value: types.S},
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S}) {Key: "PostCode", Value: types.S},
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "Street", Value: types.S}) {Key: "Street", Value: types.S},
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "House", Value: types.S}) {Key: "House", Value: types.S},
}
innerType := types.NewObject(arrayOfObjectsStaticProps, nil) innerType := types.NewObject(arrayOfObjectsStaticProps, nil)
arrayOfObjectsExpectedType := types.NewArray(nil, innerType) arrayOfObjectsExpectedType := types.NewArray(nil, innerType)
// Tests 8 & 9: allOf schema with type not specified // Tests 8 & 9: allOf schema with type not specified
objectMissingStaticProps := []*types.StaticProperty{} objectMissingStaticProps := []*types.StaticProperty{
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "AddressLine", Value: types.S}) {Key: "AddressLine", Value: types.S},
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "State", Value: types.S}) {Key: "State", Value: types.S},
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S}) {Key: "ZipCode", Value: types.S},
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "County", Value: types.S}) {Key: "County", Value: types.S},
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.N}) {Key: "PostCode", Value: types.N},
}
objectMissingExpectedType := types.NewObject(objectMissingStaticProps, nil) objectMissingExpectedType := types.NewObject(objectMissingStaticProps, nil)
arrayMissingExpectedType := types.NewArray([]types.Type{types.N, types.N}, nil) arrayMissingExpectedType := types.NewArray([]types.Type{types.N, types.N}, nil)
@@ -193,24 +197,27 @@ func TestAllOfSchemas(t *testing.T) {
arrayDifTypesExpectedType := types.NewArray([]types.Type{types.S, types.N}, nil) arrayDifTypesExpectedType := types.NewArray([]types.Type{types.S, types.N}, nil)
// Test 12: array inside of object // Test 12: array inside of object
arrayInObjectstaticProps := []*types.StaticProperty{} arrayInObjectstaticProps := []*types.StaticProperty{
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "age", Value: types.N}) {Key: "age", Value: types.N},
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "name", Value: types.S}) {Key: "name", Value: types.S},
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "personality", Value: types.S}) {Key: "personality", Value: types.S},
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "nickname", Value: types.S}) {Key: "nickname", Value: types.S},
}
innerObjectsType := types.NewObject(arrayInObjectstaticProps, nil) innerObjectsType := types.NewObject(arrayInObjectstaticProps, nil)
arrayInObjectInnerType := types.NewArray(nil, innerObjectsType) arrayInObjectInnerType := types.NewArray(nil, innerObjectsType)
arrayInObjectExpectedType := types.NewObject([]*types.StaticProperty{ arrayInObjectExpectedType := types.NewObject([]*types.StaticProperty{
types.NewStaticProperty("familyMembers", arrayInObjectInnerType)}, nil) types.NewStaticProperty("familyMembers", arrayInObjectInnerType)}, nil)
// Test 13: allOf inside core schema // Test 13: allOf inside core schema
coreStaticProps := []*types.StaticProperty{} coreStaticProps := []*types.StaticProperty{
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessMe", Value: types.S}) {Key: "accessMe", Value: types.S},
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessYou", Value: types.S}) {Key: "accessYou", Value: types.S},
}
insideType := types.NewObject(coreStaticProps, nil) insideType := types.NewObject(coreStaticProps, nil)
outerType := []*types.StaticProperty{} outerType := []*types.StaticProperty{
outerType = append(outerType, &types.StaticProperty{Key: "RandomInfo", Value: insideType}) {Key: "RandomInfo", Value: insideType},
outerType = append(outerType, &types.StaticProperty{Key: "AddressLine", Value: types.S}) {Key: "AddressLine", Value: types.S},
}
coreSchemaExpectedType := types.NewObject(outerType, nil) coreSchemaExpectedType := types.NewObject(outerType, nil)
// Test 14-17: other types besides array and object // Test 14-17: other types besides array and object
-1
View File
@@ -2,7 +2,6 @@
// Use of this source code is governed by an Apache2 // Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// nolint: deadcode // Public API.
package ast package ast
import ( import (
+4
View File
@@ -8,6 +8,7 @@ package ast
// can return a Visitor w which will be used to visit the children of the AST // can return a Visitor w which will be used to visit the children of the AST
// element v. If the Visit function returns nil, the children will not be // element v. If the Visit function returns nil, the children will not be
// visited. // visited.
//
// Deprecated: use GenericVisitor or another visitor implementation // Deprecated: use GenericVisitor or another visitor implementation
type Visitor interface { type Visitor interface {
Visit(v any) (w Visitor) Visit(v any) (w Visitor)
@@ -15,6 +16,7 @@ type Visitor interface {
// BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before // BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before
// and after the AST has been visited. // and after the AST has been visited.
//
// Deprecated: use GenericVisitor or another visitor implementation // Deprecated: use GenericVisitor or another visitor implementation
type BeforeAndAfterVisitor interface { type BeforeAndAfterVisitor interface {
Visitor Visitor
@@ -24,6 +26,7 @@ type BeforeAndAfterVisitor interface {
// Walk iterates the AST by calling the Visit function on the Visitor // Walk iterates the AST by calling the Visit function on the Visitor
// v for x before recursing. // v for x before recursing.
//
// Deprecated: use GenericVisitor.Walk // Deprecated: use GenericVisitor.Walk
func Walk(v Visitor, x any) { func Walk(v Visitor, x any) {
if bav, ok := v.(BeforeAndAfterVisitor); !ok { if bav, ok := v.(BeforeAndAfterVisitor); !ok {
@@ -37,6 +40,7 @@ func Walk(v Visitor, x any) {
// WalkBeforeAndAfter iterates the AST by calling the Visit function on the // WalkBeforeAndAfter iterates the AST by calling the Visit function on the
// Visitor v for x before recursing. // Visitor v for x before recursing.
//
// Deprecated: use GenericVisitor.Walk // Deprecated: use GenericVisitor.Walk
func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any) { func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any) {
Walk(v, x) Walk(v, x)
+5
View File
@@ -1191,17 +1191,20 @@ func applyPatches(ctx context.Context, store storage.Store, txn storage.Transact
// Helpers for the older single (unnamed) bundle style manifest storage. // Helpers for the older single (unnamed) bundle style manifest storage.
// LegacyManifestStoragePath is the older unnamed bundle path for manifests to be stored. // LegacyManifestStoragePath is the older unnamed bundle path for manifests to be stored.
//
// Deprecated: Use ManifestStoragePath and named bundles instead. // Deprecated: Use ManifestStoragePath and named bundles instead.
var legacyManifestStoragePath = storage.MustParsePath("/system/bundle/manifest") var legacyManifestStoragePath = storage.MustParsePath("/system/bundle/manifest")
var legacyRevisionStoragePath = append(legacyManifestStoragePath, "revision") var legacyRevisionStoragePath = append(legacyManifestStoragePath, "revision")
// LegacyWriteManifestToStore will write the bundle manifest to the older single (unnamed) bundle manifest location. // LegacyWriteManifestToStore will write the bundle manifest to the older single (unnamed) bundle manifest location.
//
// Deprecated: Use WriteManifestToStore and named bundles instead. // Deprecated: Use WriteManifestToStore and named bundles instead.
func LegacyWriteManifestToStore(ctx context.Context, store storage.Store, txn storage.Transaction, manifest Manifest) error { func LegacyWriteManifestToStore(ctx context.Context, store storage.Store, txn storage.Transaction, manifest Manifest) error {
return write(ctx, store, txn, legacyManifestStoragePath, manifest) return write(ctx, store, txn, legacyManifestStoragePath, manifest)
} }
// LegacyEraseManifestFromStore will erase the bundle manifest from the older single (unnamed) bundle manifest location. // LegacyEraseManifestFromStore will erase the bundle manifest from the older single (unnamed) bundle manifest location.
//
// Deprecated: Use WriteManifestToStore and named bundles instead. // Deprecated: Use WriteManifestToStore and named bundles instead.
func LegacyEraseManifestFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) error { func LegacyEraseManifestFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) error {
err := store.Write(ctx, txn, storage.RemoveOp, legacyManifestStoragePath, nil) err := store.Write(ctx, txn, storage.RemoveOp, legacyManifestStoragePath, nil)
@@ -1212,12 +1215,14 @@ func LegacyEraseManifestFromStore(ctx context.Context, store storage.Store, txn
} }
// LegacyReadRevisionFromStore will read the bundle manifest revision from the older single (unnamed) bundle manifest location. // LegacyReadRevisionFromStore will read the bundle manifest revision from the older single (unnamed) bundle manifest location.
//
// Deprecated: Use ReadBundleRevisionFromStore and named bundles instead. // Deprecated: Use ReadBundleRevisionFromStore and named bundles instead.
func LegacyReadRevisionFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) (string, error) { func LegacyReadRevisionFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) (string, error) {
return readRevisionFromStore(ctx, store, txn, legacyRevisionStoragePath) return readRevisionFromStore(ctx, store, txn, legacyRevisionStoragePath)
} }
// ActivateLegacy calls Activate for the bundles but will also write their manifest to the older unnamed store location. // ActivateLegacy calls Activate for the bundles but will also write their manifest to the older unnamed store location.
//
// Deprecated: Use Activate with named bundles instead. // Deprecated: Use Activate with named bundles instead.
func ActivateLegacy(opts *ActivateOpts) error { func ActivateLegacy(opts *ActivateOpts) error {
opts.legacy = true opts.legacy = true
+7 -6
View File
@@ -3697,15 +3697,16 @@ type prettyBundle struct {
} }
func (p prettyBundle) String() string { func (p prettyBundle) String() string {
buf := []string{fmt.Sprintf("%d module(s) (hiding data):", len(p.Modules)), ""} buf := []string{fmt.Sprintf("%d module(s) (hiding data):", len(p.Modules)), ""}
for _, mf := range p.Modules { for _, mf := range p.Modules {
buf = append(buf, "#") buf = append(buf,
buf = append(buf, fmt.Sprintf("# Module: %q", mf.Path)) "#",
buf = append(buf, "#") fmt.Sprintf("# Module: %q", mf.Path),
buf = append(buf, mf.Parsed.String()) "#",
buf = append(buf, "") mf.Parsed.String(),
"",
)
} }
return strings.Join(buf, "\n") return strings.Join(buf, "\n")
+1
View File
@@ -107,6 +107,7 @@ func (c *Cover) Report(modules map[string]*ast.Module) (report Report) {
} }
// Trace updates the coverage state. // Trace updates the coverage state.
//
// Deprecated: Use TraceEvent instead. // Deprecated: Use TraceEvent instead.
func (c *Cover) Trace(event *topdown.Event) { func (c *Cover) Trace(event *topdown.Event) {
c.TraceEvent(*event) c.TraceEvent(*event)
+6 -4
View File
@@ -264,10 +264,12 @@ func (d *debugger) LaunchEval(ctx context.Context, props LaunchEvalProperties, o
// We apply all user options first, so the debugger can make overrides if necessary. // We apply all user options first, so the debugger can make overrides if necessary.
regoArgs = append(regoArgs, options.regoOptions...) regoArgs = append(regoArgs, options.regoOptions...)
regoArgs = append(regoArgs, rego.Query(props.Query)) regoArgs = append(regoArgs,
regoArgs = append(regoArgs, rego.Store(store)) rego.Query(props.Query),
regoArgs = append(regoArgs, rego.Transaction(txn)) rego.Store(store),
regoArgs = append(regoArgs, rego.StrictBuiltinErrors(props.StrictBuiltinErrors)) rego.Transaction(txn),
rego.StrictBuiltinErrors(props.StrictBuiltinErrors),
)
if props.SkipOps == nil { if props.SkipOps == nil {
props.SkipOps = []topdown.Op{topdown.IndexOp, topdown.RedoOp, topdown.SaveOp, topdown.UnifyOp} props.SkipOps = []topdown.Op{topdown.IndexOp, topdown.RedoOp, topdown.SaveOp, topdown.UnifyOp}
+3 -4
View File
@@ -32,15 +32,14 @@ type Event struct {
func (d Event) String() string { func (d Event) String() string {
buf := new(strings.Builder) buf := new(strings.Builder)
buf.WriteString(fmt.Sprintf("%s{", d.Type)) fmt.Fprintf(buf, "%s{thread=%d", d.Type, d.Thread)
buf.WriteString(fmt.Sprintf("thread=%d", d.Thread))
if d.Message != "" { if d.Message != "" {
buf.WriteString(fmt.Sprintf(", message=%q", d.Message)) fmt.Fprintf(buf, ", message=%q", d.Message)
} }
if d.stackEvent != nil { if d.stackEvent != nil {
buf.WriteString(fmt.Sprintf(", stackIndex=%d", d.stackIndex)) fmt.Fprintf(buf, ", stackIndex=%d", d.stackIndex)
} }
buf.WriteString("}") buf.WriteString("}")
+4 -2
View File
@@ -495,6 +495,7 @@ func loadOneSchema(path string) (any, error) {
} }
// All returns a Result object loaded (recursively) from the specified paths. // All returns a Result object loaded (recursively) from the specified paths.
//
// Deprecated: Use FileLoader.Filtered() instead. // Deprecated: Use FileLoader.Filtered() instead.
func All(paths []string) (*Result, error) { func All(paths []string) (*Result, error) {
return NewFileLoader().Filtered(paths, nil) return NewFileLoader().Filtered(paths, nil)
@@ -503,6 +504,7 @@ func All(paths []string) (*Result, error) {
// Filtered returns a Result object loaded (recursively) from the specified // Filtered returns a Result object loaded (recursively) from the specified
// paths while applying the given filters. If any filter returns true, the // paths while applying the given filters. If any filter returns true, the
// file/directory is excluded. // file/directory is excluded.
//
// Deprecated: Use FileLoader.Filtered() instead. // Deprecated: Use FileLoader.Filtered() instead.
func Filtered(paths []string, filter Filter) (*Result, error) { func Filtered(paths []string, filter Filter) (*Result, error) {
return NewFileLoader().Filtered(paths, filter) return NewFileLoader().Filtered(paths, filter)
@@ -511,6 +513,7 @@ func Filtered(paths []string, filter Filter) (*Result, error) {
// AsBundle loads a path as a bundle. If it is a single file // AsBundle loads a path as a bundle. If it is a single file
// it will be treated as a normal tarball bundle. If a directory // it will be treated as a normal tarball bundle. If a directory
// is supplied it will be loaded as an unzipped bundle tree. // is supplied it will be loaded as an unzipped bundle tree.
//
// Deprecated: Use FileLoader.AsBundle() instead. // Deprecated: Use FileLoader.AsBundle() instead.
func AsBundle(path string) (*bundle.Bundle, error) { func AsBundle(path string) (*bundle.Bundle, error) {
return NewFileLoader().AsBundle(path) return NewFileLoader().AsBundle(path)
@@ -631,11 +634,10 @@ func (l *Result) mergeDocument(path string, doc any) error {
} }
func (l *Result) withParent(p string) *Result { func (l *Result) withParent(p string) *Result {
path := append(l.path, p)
return &Result{ return &Result{
Documents: l.Documents, Documents: l.Documents,
Modules: l.Modules, Modules: l.Modules,
path: path, path: append(l.path, p),
} }
} }
+1
View File
@@ -22,6 +22,7 @@ import (
// ParseConfig validates the config and injects default values. This is // ParseConfig validates the config and injects default values. This is
// for the legacy single bundle configuration. This will add the bundle // for the legacy single bundle configuration. This will add the bundle
// to the `Bundles` map to provide compatibility with newer clients. // to the `Bundles` map to provide compatibility with newer clients.
//
// Deprecated: Use `ParseBundlesConfig` with `bundles` OPA config option instead // Deprecated: Use `ParseBundlesConfig` with `bundles` OPA config option instead
func ParseConfig(config []byte, services []string) (*Config, error) { func ParseConfig(config []byte, services []string) (*Config, error) {
if config == nil { if config == nil {
+1 -1
View File
@@ -784,7 +784,7 @@ func getNormalizedBundleName(name string) string {
sb := new(strings.Builder) sb := new(strings.Builder)
for i := range len(name) { for i := range len(name) {
if isReservedCharacter(rune(name[i])) { if isReservedCharacter(rune(name[i])) {
sb.WriteString(fmt.Sprintf("\\%c", name[i])) fmt.Fprintf(sb, "\\%c", name[i])
} else { } else {
sb.WriteByte(name[i]) sb.WriteByte(name[i])
} }
+3 -3
View File
@@ -1366,7 +1366,7 @@ func TestPluginStart(t *testing.T) {
if err != nil { if err != nil {
t.Fatal("unexpected error:", err) t.Fatal("unexpected error:", err)
} }
defer plugin.Stop(ctx) plugin.Stop(ctx)
} }
func TestStop(t *testing.T) { func TestStop(t *testing.T) {
@@ -2559,7 +2559,7 @@ corge contains 2 if {
if err != nil { if err != nil {
fatal(err) fatal(err)
} else if !bytes.Equal(bs, exp) { } else if !bytes.Equal(bs, exp) {
fatal("Bad policy content. Exp:\n%v\n\nGot:\n\n%v", string(exp), string(bs)) fatal(fmt.Sprintf("Bad policy content. Exp:\n%v\n\nGot:\n\n%v", string(exp), string(bs)))
} }
} }
@@ -2574,7 +2574,7 @@ corge contains 2 if {
if err != nil { if err != nil {
fatal(err) fatal(err)
} else if !reflect.DeepEqual(data, expData) { } else if !reflect.DeepEqual(data, expData) {
fatal("Bad data content. Exp:\n%v\n\nGot:\n\n%v", expData, data) fatal(fmt.Sprintf("Bad data content. Exp:\n%v\n\nGot:\n\n%v", expData, data))
} }
manager.Store.Abort(ctx, txn) manager.Store.Abort(ctx, txn)
+1 -2
View File
@@ -250,9 +250,8 @@ func convertPointsToBase64(alg string, r, s []byte) (string, error) {
copy(rBytesPadded[keyBytes-len(r):], r) copy(rBytesPadded[keyBytes-len(r):], r)
sBytesPadded := make([]byte, keyBytes) sBytesPadded := make([]byte, keyBytes)
copy(sBytesPadded[keyBytes-len(s):], s) copy(sBytesPadded[keyBytes-len(s):], s)
signatureEnc := append(rBytesPadded, sBytesPadded...)
return base64.RawURLEncoding.EncodeToString(signatureEnc), nil return base64.RawURLEncoding.EncodeToString(append(rBytesPadded, sBytesPadded...)), nil
} }
func retrieveCurveBits(alg string) (int, error) { func retrieveCurveBits(alg string) (int, error) {
+1
View File
@@ -293,6 +293,7 @@ func (p *Plugin) flush(ctx context.Context) {
} }
// UpdateBundleStatus notifies the plugin that the policy bundle was updated. // UpdateBundleStatus notifies the plugin that the policy bundle was updated.
//
// Deprecated: Use BulkUpdateBundleStatus instead. // Deprecated: Use BulkUpdateBundleStatus instead.
func (p *Plugin) UpdateBundleStatus(status bundle.Status) { func (p *Plugin) UpdateBundleStatus(status bundle.Status) {
util.PushFIFO(p.bundleCh, status, p.metrics, statusBufferDropCounterName) util.PushFIFO(p.bundleCh, status, p.metrics, statusBufferDropCounterName)
+1
View File
@@ -140,6 +140,7 @@ func (p *Profiler) ReportTopNResults(numResults int, criteria []string) []ExprSt
} }
// Trace updates the profiler state. // Trace updates the profiler state.
//
// Deprecated: Use TraceEvent instead. // Deprecated: Use TraceEvent instead.
func (p *Profiler) Trace(event *topdown.Event) { func (p *Profiler) Trace(event *topdown.Event) {
p.TraceEvent(*event) p.TraceEvent(*event)
+3 -1
View File
@@ -44,7 +44,7 @@ const (
wasmVarPrefix = "^" wasmVarPrefix = "^"
) )
// nolint: deadcode,varcheck // nolint:varcheck
const ( const (
targetWasm = "wasm" targetWasm = "wasm"
targetRego = "rego" targetRego = "rego"
@@ -235,6 +235,7 @@ func EvalInstrument(instrument bool) EvalOption {
} }
// EvalTracer configures a tracer for a Prepared Query's evaluation // EvalTracer configures a tracer for a Prepared Query's evaluation
//
// Deprecated: Use EvalQueryTracer instead. // Deprecated: Use EvalQueryTracer instead.
func EvalTracer(tracer topdown.Tracer) EvalOption { func EvalTracer(tracer topdown.Tracer) EvalOption {
return func(e *EvalContext) { return func(e *EvalContext) {
@@ -1115,6 +1116,7 @@ func Trace(yes bool) func(r *Rego) {
} }
// Tracer returns an argument that adds a query tracer to r. // Tracer returns an argument that adds a query tracer to r.
//
// Deprecated: Use QueryTracer instead. // Deprecated: Use QueryTracer instead.
func Tracer(t topdown.Tracer) func(r *Rego) { func Tracer(t topdown.Tracer) func(r *Rego) {
return func(r *Rego) { return func(r *Rego) {
+1
View File
@@ -361,6 +361,7 @@ func (r *REPL) WithRegoVersion(v ast.RegoVersion) *REPL {
} }
// WithV1Compatible sets the Rego version to v1. // WithV1Compatible sets the Rego version to v1.
//
// Deprecated: Use WithRegoVersion instead. // Deprecated: Use WithRegoVersion instead.
func (r *REPL) WithV1Compatible(v1Compatible bool) *REPL { func (r *REPL) WithV1Compatible(v1Compatible bool) *REPL {
if v1Compatible { if v1Compatible {
+1 -1
View File
@@ -2068,7 +2068,7 @@ func TestExtraMiddleware(t *testing.T) {
} }
rt.Manager.ExtraMiddleware(func(next http.Handler) http.Handler { rt.Manager.ExtraMiddleware(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "foo", "bar") //nolint:staticcheck,SA1029 // this is a simple example ctx := context.WithValue(r.Context(), "foo", "bar") //nolint:staticcheck // this is a simple example
next.ServeHTTP(w, r.WithContext(ctx)) next.ServeHTTP(w, r.WithContext(ctx))
}) })
}) })
+1
View File
@@ -272,6 +272,7 @@ func (s *Server) Shutdown(ctx context.Context) error {
if len(errorList) > 0 { if len(errorList) > 0 {
errMsg := "error while shutting down: " errMsg := "error while shutting down: "
for i, err := range errorList { for i, err := range errorList {
//nolint:perfsprint
errMsg += fmt.Sprintf("(%d) %s. ", i, err.Error()) errMsg += fmt.Sprintf("(%d) %s. ", i, err.Error())
} }
return errors.New(errMsg) return errors.New(errMsg)
+1
View File
@@ -448,6 +448,7 @@ const (
// ParamBundleActivationV1 defines the name of the HTTP URL parameter that // ParamBundleActivationV1 defines the name of the HTTP URL parameter that
// indicates the client wants to include bundle activation in the results // indicates the client wants to include bundle activation in the results
// of the health API. // of the health API.
//
// Deprecated: Use ParamBundlesActivationV1 instead. // Deprecated: Use ParamBundlesActivationV1 instead.
ParamBundleActivationV1 = "bundle" ParamBundleActivationV1 = "bundle"
+2
View File
@@ -56,6 +56,7 @@ func Error(w http.ResponseWriter, status int, err *types.ErrorV1) {
// JSON writes a response with the specified status code and object. The object // JSON writes a response with the specified status code and object. The object
// will be JSON serialized. // will be JSON serialized.
//
// Deprecated: This method is problematic when using a non-200 status `code`: if // Deprecated: This method is problematic when using a non-200 status `code`: if
// encoding the payload fails, it'll print "superfluous call to WriteHeader()" // encoding the payload fails, it'll print "superfluous call to WriteHeader()"
// logs. // logs.
@@ -91,6 +92,7 @@ func JSONOK(w http.ResponseWriter, v any, pretty bool) {
} }
// Bytes writes a response with the specified status code and bytes. // Bytes writes a response with the specified status code and bytes.
//
// Deprecated: Unused in OPA, will be removed in the future. // Deprecated: Unused in OPA, will be removed in the future.
func Bytes(w http.ResponseWriter, code int, bs []byte) { func Bytes(w http.ResponseWriter, code int, bs []byte) {
w.WriteHeader(code) w.WriteHeader(code)
+1 -1
View File
@@ -5,7 +5,7 @@
//go:build bench_disk //go:build bench_disk
// +build bench_disk // +build bench_disk
// nolint: deadcode,unused // build tags confuse these linters // nolint: unused // build tags confuse these linters
package authz package authz
import ( import (
+1 -1
View File
@@ -5,7 +5,7 @@
//go:build !bench_disk //go:build !bench_disk
// +build !bench_disk // +build !bench_disk
// nolint: deadcode,unused // build tags confuse these linters // nolint: unused // build tags confuse these linters
package authz package authz
import "github.com/open-policy-agent/opa/v1/storage/disk" import "github.com/open-policy-agent/opa/v1/storage/disk"
+2
View File
@@ -124,6 +124,7 @@ func WrapRuntime(ctx context.Context, cancel context.CancelFunc, rt *runtime.Run
// handles starting and stopping the local API server. The return // handles starting and stopping the local API server. The return
// value is what should be used as the code in `os.Exit` in the // value is what should be used as the code in `os.Exit` in the
// `TestMain` function. // `TestMain` function.
//
// Deprecated: Use RunTests instead // Deprecated: Use RunTests instead
func (t *TestRuntime) RunAPIServerTests(m *testing.M) int { func (t *TestRuntime) RunAPIServerTests(m *testing.M) int {
return t.runTests(m, true) return t.runTests(m, true)
@@ -134,6 +135,7 @@ func (t *TestRuntime) RunAPIServerTests(m *testing.M) int {
// will suppress logging output on stdout to prevent the tests // will suppress logging output on stdout to prevent the tests
// from being overly verbose. If log output is desired set // from being overly verbose. If log output is desired set
// the `test.v` flag. // the `test.v` flag.
//
// Deprecated: Use RunTests instead // Deprecated: Use RunTests instead
func (t *TestRuntime) RunAPIServerBenchmarks(m *testing.M) int { func (t *TestRuntime) RunAPIServerBenchmarks(m *testing.M) int {
return t.runTests(m, !testing.Verbose()) return t.runTests(m, !testing.Verbose())
+1 -1
View File
@@ -5,7 +5,7 @@
//go:build bench_disk //go:build bench_disk
// +build bench_disk // +build bench_disk
// nolint: deadcode,unused // build tags confuse these linters // nolint: unused // build tags confuse these linters
package authz package authz
import ( import (
+1 -1
View File
@@ -5,7 +5,7 @@
//go:build !bench_disk //go:build !bench_disk
// +build !bench_disk // +build !bench_disk
// nolint: deadcode,unused // build tags confuse these linters // nolint: unused // build tags confuse these linters
package authz package authz
import "github.com/open-policy-agent/opa/v1/storage/disk" import "github.com/open-policy-agent/opa/v1/storage/disk"
+1 -1
View File
@@ -245,7 +245,7 @@ func (r PrettyReporter) fmtBenchmark(tr *Result) string {
// like BenchmarkDataFooBarTestAuth. // like BenchmarkDataFooBarTestAuth.
camelCaseName := "" camelCaseName := ""
for part := range strings.SplitSeq(strings.ReplaceAll(name, "_", "."), ".") { for part := range strings.SplitSeq(strings.ReplaceAll(name, "_", "."), ".") {
camelCaseName += strings.Title(part) //nolint:staticcheck // SA1019, no unicode here camelCaseName += strings.Title(part) //nolint:perfsprint,staticcheck
} }
name = "Benchmark" + camelCaseName name = "Benchmark" + camelCaseName
} }
+2
View File
@@ -325,6 +325,7 @@ func (r *Runner) SetStore(store storage.Store) *Runner {
} }
// SetCoverageTracer sets the tracer to use to compute coverage. // SetCoverageTracer sets the tracer to use to compute coverage.
//
// Deprecated: Use SetCoverageQueryTracer instead. // Deprecated: Use SetCoverageQueryTracer instead.
func (r *Runner) SetCoverageTracer(tracer topdown.Tracer) *Runner { func (r *Runner) SetCoverageTracer(tracer topdown.Tracer) *Runner {
if tracer == nil { if tracer == nil {
@@ -406,6 +407,7 @@ func (r *Runner) Target(target string) *Runner {
} }
// Run executes all tests contained in supplied modules. // Run executes all tests contained in supplied modules.
//
// Deprecated: Use RunTests and the Runner#SetModules or Runner#SetBundles // Deprecated: Use RunTests and the Runner#SetModules or Runner#SetBundles
// helpers instead. This will NOT use the modules or bundles set on the Runner. // helpers instead. This will NOT use the modules or bundles set on the Runner.
func (r *Runner) Run(ctx context.Context, modules map[string]*ast.Module) (chan *Result, error) { func (r *Runner) Run(ctx context.Context, modules map[string]*ast.Module) (chan *Result, error) {
+24 -16
View File
@@ -107,10 +107,7 @@ func TestHTTPGetRequest(t *testing.T) {
func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) { func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) {
t.Parallel() t.Parallel()
var people []Person people := []Person{{ID: "1", Firstname: "John"}}
// test data
people = append(people, Person{ID: "1", Firstname: "John"})
// test server // test server
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
@@ -120,9 +117,10 @@ func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) {
defer ts.Close() defer ts.Close()
// expected result // expected result
expectedResult := make(map[string]any) expectedResult := map[string]any{
expectedResult["status"] = "200 OK" "status": "200 OK",
expectedResult["status_code"] = http.StatusOK "status_code": http.StatusOK,
}
var body []any var body []any
bodyMap := map[string]string{"id": "1", "firstname": "John"} bodyMap := map[string]string{"id": "1", "firstname": "John"}
@@ -143,15 +141,25 @@ func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) {
} }
// run the test // run the test
tests := []httpsStruct{} tests := []httpsStruct{
tests = append(tests, httpsStruct{note: "http.send", rules: []string{fmt.Sprintf( {
`p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true, "tls_insecure_skip_verify": true}, resp); x := clean_headers(resp) }`, ts.URL)}, expected: resultObj.String()}) note: "http.send",
rules: []string{fmt.Sprintf(
// This case verifies that `tls_insecure_skip_verify` `p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true, "tls_insecure_skip_verify": true}, resp); x := clean_headers(resp) }`, ts.URL),
// is still applied, even if other TLS settings are },
// present. expected: resultObj.String(),
tests = append(tests, httpsStruct{note: "http.send", rules: []string{fmt.Sprintf( },
`p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true, "tls_insecure_skip_verify": true, "tls_use_system_certs": true,}, resp); x := clean_headers(resp) }`, ts.URL)}, expected: resultObj.String()}) {
// This case verifies that `tls_insecure_skip_verify`
// is still applied, even if other TLS settings are
// present.
note: "http.send",
rules: []string{fmt.Sprintf(
`p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true, "tls_insecure_skip_verify": true}, resp); x := clean_headers(resp) }`, ts.URL),
},
expected: resultObj.String(),
},
}
data := loadSmallTestData() data := loadSmallTestData()
+1
View File
@@ -121,6 +121,7 @@ func (q *Query) WithInput(input *ast.Term) *Query {
} }
// WithTracer adds a query tracer to use during evaluation. This is optional. // WithTracer adds a query tracer to use during evaluation. This is optional.
//
// Deprecated: Use WithQueryTracer instead. // Deprecated: Use WithQueryTracer instead.
func (q *Query) WithTracer(tracer Tracer) *Query { func (q *Query) WithTracer(tracer Tracer) *Query {
qt, ok := tracer.(QueryTracer) qt, ok := tracer.(QueryTracer)
+4 -2
View File
@@ -170,6 +170,7 @@ func (evt *Event) equalNodes(other *Event) bool {
} }
// Tracer defines the interface for tracing in the top-down evaluation engine. // Tracer defines the interface for tracing in the top-down evaluation engine.
//
// Deprecated: Use QueryTracer instead. // Deprecated: Use QueryTracer instead.
type Tracer interface { type Tracer interface {
Enabled() bool Enabled() bool
@@ -230,6 +231,7 @@ func (b *BufferTracer) Enabled() bool {
} }
// Trace adds the event to the buffer. // Trace adds the event to the buffer.
//
// Deprecated: Use TraceEvent instead. // Deprecated: Use TraceEvent instead.
func (b *BufferTracer) Trace(evt *Event) { func (b *BufferTracer) Trace(evt *Event) {
*b = append(*b, evt) *b = append(*b, evt)
@@ -806,7 +808,7 @@ func printPrettyVars(w *bytes.Buffer, exprVars map[string]varInfo) {
w.WriteString("\n\nWhere:\n") w.WriteString("\n\nWhere:\n")
for _, info := range byName { for _, info := range byName {
w.WriteString(fmt.Sprintf("\n%s: %s", info.Title(), iStrs.Truncate(info.Value(), maxPrettyExprVarWidth))) fmt.Fprintf(w, "\n%s: %s", info.Title(), iStrs.Truncate(info.Value(), maxPrettyExprVarWidth))
} }
return return
@@ -878,7 +880,7 @@ func printArrows(w *bytes.Buffer, l []varInfo, printValueAt int) {
valueStr := iStrs.Truncate(info.Value(), maxPrettyExprVarWidth) valueStr := iStrs.Truncate(info.Value(), maxPrettyExprVarWidth)
if (i > 0 && col == l[i-1].col) || (i < len(l)-1 && col == l[i+1].col) { if (i > 0 && col == l[i-1].col) || (i < len(l)-1 && col == l[i+1].col) {
// There is another var on this column, so we need to include the name to differentiate them. // There is another var on this column, so we need to include the name to differentiate them.
w.WriteString(fmt.Sprintf("%s: %s", info.Title(), valueStr)) fmt.Fprintf(w, "%s: %s", info.Title(), valueStr)
} else { } else {
w.WriteString(valueStr) w.WriteString(valueStr)
} }
+1
View File
@@ -716,6 +716,7 @@ func (t *Function) NamedFuncArgs() FuncArgs {
} }
// Args returns the function's arguments as a slice, ignoring variadic arguments. // Args returns the function's arguments as a slice, ignoring variadic arguments.
//
// Deprecated: Use FuncArgs instead. // Deprecated: Use FuncArgs instead.
func (t *Function) Args() []Type { func (t *Function) Args() []Type {
cpy := make([]Type, len(t.args)) cpy := make([]Type, len(t.args))
+2 -5
View File
@@ -77,13 +77,10 @@ func dfsRecursive(t Traversal, eq Equals, u, z T, path []T) []T {
} }
for _, v := range t.Edges(u) { for _, v := range t.Edges(u) {
if eq(v, z) { if eq(v, z) {
path = append(path, z) return append(path, z, u)
path = append(path, u)
return path
} }
if p := dfsRecursive(t, eq, v, z, path); len(p) > 0 { if p := dfsRecursive(t, eq, v, z, path); len(p) > 0 {
path = append(p, u) return append(p, u)
return path
} }
} }
return path return path
+1
View File
@@ -44,6 +44,7 @@ func PartialObjectBenchmarkCrossModule(n int) []string {
ruleBuilder := "" ruleBuilder := ""
for idx := 1; idx <= n; idx++ { for idx := 1; idx <= n; idx++ {
//nolint:perfsprint
barMod += fmt.Sprintf(` barMod += fmt.Sprintf(`
bench_test_%[1]d := result if { bench_test_%[1]d := result if {
input.bench_test_collector_mambo_number_%[3]d input.bench_test_collector_mambo_number_%[3]d