Apply modernize linter fixes (#7599)

Following up on #7566, and now applying the more exciting
modernizations. fmt.Appendf was new to me! But especially
the contains checks are so much better IMHO. I have reviewed
all changes myself and did a few manual changes where it
became obvious that things could be improved a little further.

(the modernize analyzer still has some issues running against
OPA, and I have manually worked around those for the time being)

Signed-off-by: Anders Eknert <anders@styra.com>
This commit is contained in:
Anders Eknert
2025-05-20 23:12:13 +02:00
committed by GitHub
parent 1ccbd9083f
commit 8ba08ac80c
77 changed files with 265 additions and 624 deletions
+2 -3
View File
@@ -10,6 +10,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"strings"
@@ -1187,9 +1188,7 @@ a contains 4 if {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.modules {
files[k] = v
}
maps.Copy(files, tc.modules)
manifest := bundle.Manifest{
RegoVersion: &tc.bundleRegoVersion,
+2 -7
View File
@@ -11,6 +11,7 @@ import (
"path"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"testing"
@@ -1404,13 +1405,7 @@ func capsWithoutFeat(regoVersion ast.RegoVersion, feat ...string) *ast.Capabilit
feats := make([]string, 0, len(caps.Features))
for _, f := range caps.Features {
skip := false
for _, skipF := range feat {
if f == skipF {
skip = true
break
}
}
skip := slices.Contains(feat, f)
if !skip {
feats = append(feats, f)
}
+2 -3
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"io/fs"
"maps"
"os"
"github.com/spf13/cobra"
@@ -94,9 +95,7 @@ func checkModules(params checkParams, args []string) error {
if err != nil {
return err
}
for name, mod := range b.ParsedModules(path) {
modules[name] = mod
}
maps.Copy(modules, b.ParsedModules(path))
}
} else {
f := loaderFilter{
+2 -3
View File
@@ -7,6 +7,7 @@ package cmd
import (
"encoding/json"
"fmt"
"maps"
"os"
"path"
"path/filepath"
@@ -1262,9 +1263,7 @@ q contains x if {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTempFS(files, func(root string) {
+2 -3
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"os"
"github.com/open-policy-agent/opa/internal/presentation"
@@ -147,9 +148,7 @@ func deps(args []string, params depsCommandParams, w io.Writer) error {
return err
}
for name, mod := range b.ParsedModules(path) {
modules[name] = mod
}
maps.Copy(modules, b.ParsedModules(path))
}
}
+2 -3
View File
@@ -7,6 +7,7 @@ package cmd
import (
"fmt"
"io"
"maps"
"os"
"path/filepath"
"strings"
@@ -519,9 +520,7 @@ p contains 4 if {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTempFS(files, func(root string) {
+1 -3
View File
@@ -3476,9 +3476,7 @@ p contains 2 if {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTempFS(files, func(root string) {
+2 -3
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"regexp"
@@ -854,9 +855,7 @@ main contains "hello" if {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTempFS(files, func(root string) {
+2 -3
View File
@@ -7,6 +7,7 @@ package cmd
import (
"bytes"
"fmt"
"maps"
"os"
"path/filepath"
"reflect"
@@ -956,9 +957,7 @@ p contains 2 if {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTempFS(files, func(root string) {
+3 -4
View File
@@ -12,6 +12,7 @@ import (
"fmt"
"os"
"path"
"slices"
"time"
"github.com/spf13/cobra"
@@ -417,10 +418,8 @@ func verifyCipherSuites(cipherSuites []string) (*[]uint16, error) {
}
// verify no TLS 1.3 cipher suites as they are not configurable
for _, ver := range val.SupportedVersions {
if ver == tls.VersionTLS13 {
return nil, fmt.Errorf("TLS 1.3 cipher suite \"%v\" is not configurable", c)
}
if slices.Contains(val.SupportedVersions, tls.VersionTLS13) {
return nil, fmt.Errorf("TLS 1.3 cipher suite \"%v\" is not configurable", c)
}
cipherSuitesIDs = append(cipherSuitesIDs, val.ID)
+2 -3
View File
@@ -5,6 +5,7 @@ import (
"context"
"fmt"
"io"
"maps"
"os"
"path"
"path/filepath"
@@ -3482,9 +3483,7 @@ test_l if {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTempFS(files, func(root string) {
+1 -3
View File
@@ -342,9 +342,7 @@ p contains "B" if {
if bundleType.tar {
files["bundle.tar"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTestFS(tc.files, false, func(root string, fsys fs.FS) {
+1 -1
View File
@@ -51,7 +51,7 @@ func shiftLower(bit byte, b []byte) byte {
// position of the first byte in the slice.
// This returns the bit that was shifted off the last byte.
func shiftHigher(bit byte, b []byte) byte {
for i := 0; i < len(b); i++ {
for i := range b {
newByte := b[i] << 1
newByte |= bit
bit = (b[i] & 0x80) >> 7
+2 -7
View File
@@ -28,6 +28,7 @@ package gojsonschema
import (
"errors"
"fmt"
"slices"
"strings"
)
@@ -58,13 +59,7 @@ func (t *jsonSchemaType) Add(etype string) error {
func (t *jsonSchemaType) Contains(etype string) bool {
for _, v := range t.types {
if v == etype {
return true
}
}
return false
return slices.Contains(t.types, etype)
}
func (t *jsonSchemaType) String() string {
+2 -6
View File
@@ -29,15 +29,11 @@ package gojsonschema
import (
"encoding/json"
"math/big"
"slices"
)
func isStringInSlice(s []string, what string) bool {
for i := range s {
if s[i] == what {
return true
}
}
return false
return slices.Contains(s, what)
}
func marshalToJSONString(value any) (*string, error) {
+1 -4
View File
@@ -53,10 +53,7 @@ func (o DepAnalysisOutput) Pretty(w io.Writer) error {
// Fill two columns if results have base and virtual docs. Else fill one column.
if len(o.Base) > 0 && len(o.Virtual) > 0 {
maxLen := len(o.Base)
if len(o.Virtual) > maxLen {
maxLen = len(o.Virtual)
}
maxLen := max(len(o.Virtual), len(o.Base))
headers = []string{"Base Documents", "Virtual Documents"}
rows = make([][]string, maxLen)
for i := range rows {
+1 -1
View File
@@ -16,7 +16,7 @@ func ConstantTimeByteCompare(x, y []byte) (int, error) {
xLarger, yLarger := 0, 0
for i := 0; i < len(x); i++ {
for i := range x {
xByte, yByte := int(x[i]), int(y[i])
x := ((yByte - xByte) >> 8) & 1
+2 -2
View File
@@ -81,9 +81,9 @@ func New(id string, opts Options) (*Reporter, error) {
url = ExternalServiceURL
}
restConfig := []byte(fmt.Sprintf(`{
restConfig := fmt.Appendf(nil, `{
"url": %q,
}`, url))
}`, url)
client, err := rest.New(restConfig, map[string]*keys.Config{}, rest.Logger(opts.Logger))
if err != nil {
+3 -12
View File
@@ -353,10 +353,7 @@ func (i *VM) Eval(ctx context.Context,
metrics.Timer("wasm_vm_eval_call").Stop()
data := i.memory.UnsafeData(i.store)[resultAddr:]
n := bytes.IndexByte(data, 0)
if n < 0 {
n = 0
}
n := max(bytes.IndexByte(data, 0), 0)
// Skip free'ing input and result JSON as the heap will be reset next round anyway.
return data[:n], nil
@@ -439,10 +436,7 @@ func (i *VM) evalCompat(ctx context.Context,
}
data := i.memory.UnsafeData(i.store)[serialized:]
n := bytes.IndexByte(data, 0)
if n < 0 {
n = 0
}
n := max(bytes.IndexByte(data, 0), 0)
metrics.Timer("wasm_vm_eval_prepare_result").Stop()
@@ -656,10 +650,7 @@ func (i *VM) fromRegoJSON(ctx context.Context, addr int32, free bool) (any, erro
}
data := i.memory.UnsafeData(i.store)[serialized:]
n := bytes.IndexByte(data, 0)
if n < 0 {
n = 0
}
n := max(bytes.IndexByte(data, 0), 0)
// Parse the result into go types.
+2 -5
View File
@@ -369,10 +369,7 @@ func compareRelatedResources(a, b []*RelatedResourceAnnotation) int {
}
func compareSchemas(a, b []*SchemaAnnotation) int {
maxLen := len(a)
if len(b) < maxLen {
maxLen = len(b)
}
maxLen := min(len(b), len(a))
for i := range maxLen {
if cmp := a[i].Compare(b[i]); cmp != 0 {
@@ -562,7 +559,7 @@ func attachRuleAnnotations(mod *Module) {
}
if found && j < len(cpy) {
cpy = append(cpy[:j], cpy[j+1:]...)
cpy = slices.Delete(cpy, j, j+1)
}
}
}
+2 -6
View File
@@ -6,6 +6,7 @@ package ast
import (
"fmt"
"slices"
"sort"
"strings"
@@ -1006,12 +1007,7 @@ func (d *ArgErrDetail) Lines() []string {
}
func (d *ArgErrDetail) nilType() bool {
for i := range d.Have {
if types.Nil(d.Have[i]) {
return true
}
}
return false
return slices.ContainsFunc(d.Have, types.Nil)
}
// UnificationErrDetail describes a type mismatch error when two values are
+5 -20
View File
@@ -296,10 +296,7 @@ func sortOrder(x any) int {
}
func importsCompare(a, b []*Import) int {
minLen := len(a)
if len(b) < minLen {
minLen = len(b)
}
minLen := min(len(b), len(a))
for i := range minLen {
if cmp := a[i].Compare(b[i]); cmp != 0 {
return cmp
@@ -315,10 +312,7 @@ func importsCompare(a, b []*Import) int {
}
func annotationsCompare(a, b []*Annotations) int {
minLen := len(a)
if len(b) < minLen {
minLen = len(b)
}
minLen := min(len(b), len(a))
for i := range minLen {
if cmp := a[i].Compare(b[i]); cmp != 0 {
return cmp
@@ -334,10 +328,7 @@ func annotationsCompare(a, b []*Annotations) int {
}
func rulesCompare(a, b []*Rule) int {
minLen := len(a)
if len(b) < minLen {
minLen = len(b)
}
minLen := min(len(b), len(a))
for i := range minLen {
if cmp := a[i].Compare(b[i]); cmp != 0 {
return cmp
@@ -353,10 +344,7 @@ func rulesCompare(a, b []*Rule) int {
}
func termSliceCompare(a, b []*Term) int {
minLen := len(a)
if len(b) < minLen {
minLen = len(b)
}
minLen := min(len(b), len(a))
for i := range minLen {
if cmp := Compare(a[i], b[i]); cmp != 0 {
return cmp
@@ -371,10 +359,7 @@ func termSliceCompare(a, b []*Term) int {
}
func withSliceCompare(a, b []*With) int {
minLen := len(a)
if len(b) < minLen {
minLen = len(b)
}
minLen := min(len(b), len(a))
for i := range minLen {
if cmp := Compare(a[i], b[i]); cmp != 0 {
return cmp
+3 -7
View File
@@ -874,9 +874,7 @@ func (c *Compiler) PassesTypeCheckRules(rules []*Rule) Errors {
c.builtins[bi.Name] = bi
}
for name, bi := range c.customBuiltins {
c.builtins[name] = bi
}
maps.Copy(c.builtins, c.customBuiltins)
c.TypeEnv = checker.Env(c.builtins)
}
@@ -1701,9 +1699,7 @@ func (c *Compiler) init() {
}
}
for name, bi := range c.customBuiltins {
c.builtins[name] = bi
}
maps.Copy(c.builtins, c.customBuiltins)
// Load the global input schema if one was provided.
if c.schemaSet != nil {
@@ -5044,7 +5040,7 @@ func expandExprTermArray(gen *localVarGenerator, arr *Array) (support []*Expr) {
}
func expandExprTermSlice(gen *localVarGenerator, v []*Term) (support []*Expr) {
for i := 0; i < len(v); i++ {
for i := range v {
var extras []*Expr
extras, v[i] = expandExprTerm(gen, v[i])
support = append(support, extras...)
+5 -35
View File
@@ -8737,13 +8737,7 @@ p contains 2 if { true }`,
t.Fatalf("Expected exactly %v rules but got: %v", len(tc.expected), rules)
}
for i := range rules {
found := false
for j := range tc.expected {
if rules[i].Equal(tc.expected[j]) {
found = true
break
}
}
found := slices.ContainsFunc(tc.expected, rules[i].Equal)
if !found {
t.Fatalf("Expected exactly %v but got: %v", tc.expected, rules)
}
@@ -8800,13 +8794,7 @@ p contains 2 if { true }`,
t.Fatalf("Expected exactly %v rules but got: %v", len(tc.expected), rules)
}
for i := range rules {
found := false
for j := range tc.expected {
if rules[i].Equal(tc.expected[j]) {
found = true
break
}
}
found := slices.ContainsFunc(tc.expected, rules[i].Equal)
if !found {
t.Fatalf("Expected exactly %v but got: %v", tc.expected, rules)
}
@@ -8868,13 +8856,7 @@ q contains 3 if { true }`,
t.Fatalf("Expected exactly %v rules but got: %v", len(tc.expected), rules)
}
for i := range rules {
found := false
for j := range tc.expected {
if rules[i].Equal(tc.expected[j]) {
found = true
break
}
}
found := slices.ContainsFunc(tc.expected, rules[i].Equal)
if !found {
t.Fatalf("Expected %v but got: %v", tc.expected, rules)
}
@@ -8918,13 +8900,7 @@ q["b"] = 2 if { true }`,
}
for i := range result {
found := false
for j := range tc.expected {
if result[i].Equal(tc.expected[j]) {
found = true
break
}
}
found := slices.ContainsFunc(tc.expected, result[i].Equal)
if !found {
t.Fatalf("Expected %v but got: %v", tc.expected, result)
}
@@ -8997,13 +8973,7 @@ r5.baz = 7 if { input.y }
}
for i := range result {
found := false
for j := range tc.expected {
if result[i].Equal(tc.expected[j]) {
found = true
break
}
}
found := slices.ContainsFunc(tc.expected, result[i].Equal)
if !found {
t.Fatalf("Expected %v but got: %v", tc.expected, result)
}
+2 -8
View File
@@ -394,14 +394,8 @@ q[x.y] = 10 if {
}
}
buffer := tc.modules["buffer.rego"]
before := tc.pos - 4
if before < 0 {
before = 0
}
after := tc.pos + 5
if after > len(buffer) {
after = len(buffer)
}
before := max(tc.pos-4, 0)
after := min(tc.pos+5, len(buffer))
t.Logf("pos is %d: \"%s<%s>%s\"", tc.pos, buffer[before:tc.pos], string(buffer[tc.pos]), buffer[tc.pos+1:after])
o := New()
result, err := o.FindDefinition(DefinitionQuery{
+20 -32
View File
@@ -10,9 +10,11 @@ import (
"errors"
"fmt"
"io"
"maps"
"math/big"
"net/url"
"regexp"
"slices"
"sort"
"strconv"
"strings"
@@ -330,9 +332,7 @@ func (p *Parser) Parse() ([]Statement, []*Comment, Errors) {
}
// rego-v1 includes all v0 future keywords in the default language definition
for k, v := range futureKeywordsV0 {
allowedFutureKeywords[k] = v
}
maps.Copy(allowedFutureKeywords, futureKeywordsV0)
for _, kw := range p.po.Capabilities.FutureKeywords {
if tok, ok := futureKeywords[kw]; ok {
@@ -380,9 +380,7 @@ func (p *Parser) Parse() ([]Statement, []*Comment, Errors) {
if p.po.Capabilities.ContainsFeature(FeatureRegoV1) {
// rego-v1 includes all v0 future keywords in the default language definition
for k, v := range futureKeywordsV0 {
allowedFutureKeywords[k] = v
}
maps.Copy(allowedFutureKeywords, futureKeywordsV0)
}
}
@@ -400,9 +398,7 @@ func (p *Parser) Parse() ([]Statement, []*Comment, Errors) {
selected := map[string]tokens.Token{}
if p.po.AllFutureKeywords || p.po.EffectiveRegoVersion() == RegoV1 {
for kw, tok := range allowedFutureKeywords {
selected[kw] = tok
}
maps.Copy(selected, allowedFutureKeywords)
} else {
for _, kw := range p.po.FutureKeywords {
tok, ok := allowedFutureKeywords[kw]
@@ -979,7 +975,7 @@ func (p *Parser) parseHead(defaultRule bool) (*Head, bool) {
ref = y
}
head = RefHead(ref)
head.Args = append([]*Term{}, args...)
head.Args = slices.Clone[[]*Term](args)
default:
return nil, false
@@ -2065,28 +2061,24 @@ func (p *Parser) parseTermPairList(end tokens.Token, r [][2]*Term) [][2]*Term {
}
func (p *Parser) parseTermOp(values ...tokens.Token) *Term {
for i := range values {
if p.s.tok == values[i] {
r := RefTerm(VarTerm(p.s.tok.String()).SetLocation(p.s.Loc())).SetLocation(p.s.Loc())
p.scan()
return r
}
if slices.Contains(values, p.s.tok) {
r := RefTerm(VarTerm(p.s.tok.String()).SetLocation(p.s.Loc())).SetLocation(p.s.Loc())
p.scan()
return r
}
return nil
}
func (p *Parser) parseTermOpName(ref Ref, values ...tokens.Token) *Term {
for i := range values {
if p.s.tok == values[i] {
cp := ref.Copy()
for _, r := range cp {
r.SetLocation(p.s.Loc())
}
t := RefTerm(cp...)
t.SetLocation(p.s.Loc())
p.scan()
return t
if slices.Contains(values, p.s.tok) {
cp := ref.Copy()
for _, r := range cp {
r.SetLocation(p.s.Loc())
}
t := RefTerm(cp...)
t.SetLocation(p.s.Loc())
p.scan()
return t
}
return nil
}
@@ -2764,10 +2756,6 @@ func (p *Parser) regoV1Import(imp *Import) {
func init() {
allFutureKeywords = map[string]tokens.Token{}
for k, v := range futureKeywords {
allFutureKeywords[k] = v
}
for k, v := range futureKeywordsV0 {
allFutureKeywords[k] = v
}
maps.Copy(allFutureKeywords, futureKeywords)
maps.Copy(allFutureKeywords, futureKeywordsV0)
}
+3 -10
View File
@@ -14,6 +14,7 @@ import (
"bytes"
"errors"
"fmt"
"slices"
"strings"
"unicode"
@@ -731,12 +732,7 @@ func parseModule(filename string, stmts []Statement, comments []*Comment, regoCo
}
func ruleDeclarationHasKeyword(rule *Rule, keyword tokens.Token) bool {
for _, kw := range rule.Head.keywords {
if kw == keyword {
return true
}
}
return false
return slices.Contains(rule.Head.keywords, keyword)
}
func newScopeAttachmentErr(a *Annotations, want string) *Error {
@@ -809,10 +805,7 @@ func newParserErrorDetail(bs []byte, offset int) *ParserErrorDetail {
func (d ParserErrorDetail) Lines() []string {
line := strings.TrimLeft(d.Line, "\t") // remove leading tabs
tabCount := len(d.Line) - len(line)
indent := d.Idx - tabCount
if indent < 0 {
indent = 0
}
indent := max(d.Idx-tabCount, 0)
return []string{line, strings.Repeat(" ", indent) + "^"}
}
+2 -10
View File
@@ -143,12 +143,7 @@ func IsKeyword(s string) bool {
}
func IsInKeywords(s string, keywords []string) bool {
for _, x := range keywords {
if x == s {
return true
}
}
return false
return slices.Contains(keywords, s)
}
// IsKeywordInRegoVersion returns true if s is a language keyword.
@@ -1168,10 +1163,7 @@ func (body Body) Set(expr *Expr, pos int) {
//
// If body is a subset of other, it is considered less than (and vice versa).
func (body Body) Compare(other Body) int {
minLen := len(body)
if len(other) < minLen {
minLen = len(other)
}
minLen := min(len(other), len(body))
for i := range minLen {
if cmp := body[i].Compare(other[i]); cmp != 0 {
return cmp
+1 -4
View File
@@ -88,10 +88,7 @@ func TestPretty(t *testing.T) {
resultLines := strings.Split(result, "\n")
expectedLines := strings.Split(expected, "\n")
minLines := len(resultLines)
if minLines > len(expectedLines) {
minLines = len(expectedLines)
}
minLines := min(len(resultLines), len(expectedLines))
for i := range minLines {
if resultLines[i] != expectedLines[i] {
+3 -13
View File
@@ -928,7 +928,7 @@ func PtrRef(head *Term, s string) (Ref, error) {
}
ref := make(Ref, uint(len(parts))+1)
ref[0] = head
for i := 0; i < len(parts); i++ {
for i := range parts {
var err error
parts[i], err = url.PathUnescape(parts[i])
if err != nil {
@@ -1484,12 +1484,7 @@ func (arr *Array) Iter(f func(*Term) error) error {
// Until calls f on each element in arr. If f returns true, iteration stops.
func (arr *Array) Until(f func(*Term) bool) bool {
for _, term := range arr.elems {
if f(term) {
return true
}
}
return false
return slices.ContainsFunc(arr.elems, f)
}
// Foreach calls f on each element in arr.
@@ -1707,12 +1702,7 @@ func (s *set) Iter(f func(*Term) error) error {
// Until calls f on each element in s. If f returns true, iteration stops.
func (s *set) Until(f func(*Term) bool) bool {
for _, term := range s.sortedKeys() {
if f(term) {
return true
}
}
return false
return slices.ContainsFunc(s.sortedKeys(), f)
}
// Foreach calls f on each element in s.
+3 -6
View File
@@ -14,6 +14,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"net/url"
"os"
"path"
@@ -234,9 +235,7 @@ func (m Manifest) Copy() Manifest {
if metadata != nil {
m.Metadata = make(map[string]any)
for k, v := range metadata {
m.Metadata[k] = v
}
maps.Copy(m.Metadata, metadata)
}
return m
@@ -1478,9 +1477,7 @@ func MergeWithRegoVersion(bundles []*Bundle, regoVersion ast.RegoVersion, usePat
if err != nil {
return nil, err
}
for k, v := range fileRegoVersions {
result.Manifest.FileRegoVersions[k] = v
}
maps.Copy(result.Manifest.FileRegoVersions, fileRegoVersions)
}
}
+3 -6
View File
@@ -1,6 +1,7 @@
package bundle
import (
"maps"
"os"
"path/filepath"
"strconv"
@@ -33,9 +34,7 @@ func BenchmarkTarballLoader(b *testing.B) {
for _, n := range sizes {
expectedFiles := make(map[string]string, len(benchTestArchiveFiles)+1)
for k, v := range benchTestArchiveFiles {
expectedFiles[k] = v
}
maps.Copy(expectedFiles, benchTestArchiveFiles)
expectedFiles["/x/data.json"] = benchTestGetFlatDataJSON(n)
// We generate the tarball once in the tempfs, and then reuse it many
@@ -69,9 +68,7 @@ func BenchmarkDirectoryLoader(b *testing.B) {
for _, n := range sizes {
expectedFiles := make(map[string]string, len(benchTestArchiveFiles)+1)
for k, v := range benchTestArchiveFiles {
expectedFiles[k] = v
}
maps.Copy(expectedFiles, benchTestArchiveFiles)
expectedFiles["/x/data.json"] = benchTestGetFlatDataJSON(n)
test.WithTempFS(expectedFiles, func(rootDir string) {
+2 -3
View File
@@ -9,6 +9,7 @@ import (
"crypto/rand"
"encoding/json"
"fmt"
"maps"
"github.com/open-policy-agent/opa/internal/jwx/jwa"
"github.com/open-policy-agent/opa/internal/jwx/jws"
@@ -98,9 +99,7 @@ func generatePayload(files []FileInfo, sc *SigningConfig, keyID string) ([]byte,
return nil, err
}
for claim, value := range claims {
payload[claim] = value
}
maps.Copy(payload, claims)
} else if keyID != "" {
// keyid claim is deprecated but include it for backwards compatibility.
payload["keyid"] = keyID
+9 -24
View File
@@ -10,6 +10,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"path/filepath"
"strings"
@@ -484,12 +485,8 @@ func activateBundles(opts *ActivateOpts) error {
// Compile the modules all at once to avoid having to re-do work.
remainingAndExtra := make(map[string]*ast.Module)
for name, mod := range remaining {
remainingAndExtra[name] = mod
}
for name, mod := range opts.ExtraModules {
remainingAndExtra[name] = mod
}
maps.Copy(remainingAndExtra, remaining)
maps.Copy(remainingAndExtra, opts.ExtraModules)
err = compileModules(opts.Compiler, opts.Metrics, snapshotBundles, remainingAndExtra, opts.legacy, opts.AuthorizationDecisionRef)
if err != nil {
@@ -930,14 +927,10 @@ func compileModules(compiler *ast.Compiler, m metrics.Metrics, bundles map[strin
modules := map[string]*ast.Module{}
// preserve any modules already on the compiler
for name, module := range compiler.Modules {
modules[name] = module
}
maps.Copy(modules, compiler.Modules)
// preserve any modules passed in from the store
for name, module := range extraModules {
modules[name] = module
}
maps.Copy(modules, extraModules)
// include all the new bundle modules
for bundleName, b := range bundles {
@@ -946,9 +939,7 @@ func compileModules(compiler *ast.Compiler, m metrics.Metrics, bundles map[strin
modules[mf.Path] = mf.Parsed
}
} else {
for name, module := range b.ParsedModules(bundleName) {
modules[name] = module
}
maps.Copy(modules, b.ParsedModules(bundleName))
}
}
@@ -971,14 +962,10 @@ func writeModules(ctx context.Context, store storage.Store, txn storage.Transact
modules := map[string]*ast.Module{}
// preserve any modules already on the compiler
for name, module := range compiler.Modules {
modules[name] = module
}
maps.Copy(modules, compiler.Modules)
// preserve any modules passed in from the store
for name, module := range extraModules {
modules[name] = module
}
maps.Copy(modules, extraModules)
// include all the new bundle modules
for bundleName, b := range bundles {
@@ -987,9 +974,7 @@ func writeModules(ctx context.Context, store storage.Store, txn storage.Transact
modules[mf.Path] = mf.Parsed
}
} else {
for name, module := range b.ParsedModules(bundleName) {
modules[name] = module
}
maps.Copy(modules, b.ParsedModules(bundleName))
}
}
+3 -14
View File
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
@@ -187,13 +188,7 @@ func verifyReadBundleNames(ctx context.Context, t *testing.T, store storage.Stor
}
for _, actualName := range actualNames {
found := false
for _, expectedName := range expected {
if actualName == expectedName {
found = true
break
}
}
found := slices.Contains(expected, actualName)
if !found {
t.Errorf("Found unexpecxted bundle name %s, expected names: %+v", actualName, expected)
}
@@ -6099,13 +6094,7 @@ func TestErasePolicies(t *testing.T) {
t.Fatalf("expected %d modules remaining in the store, got %d", len(tc.expectedRemaining), len(actualRemaining))
}
for _, expectedName := range tc.expectedRemaining {
found := false
for _, actualName := range actualRemaining {
if expectedName == actualName {
found = true
break
}
}
found := slices.Contains(actualRemaining, expectedName)
if !found {
t.Fatalf("expected remaining module %s not found", expectedName)
}
+5 -17
View File
@@ -15,6 +15,7 @@ import (
"io/fs"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
@@ -410,11 +411,8 @@ func (c *Compiler) init() error {
}
var found bool
for _, t := range Targets {
if c.target == t {
found = true
break
}
if slices.Contains(Targets, c.target) {
found = true
}
if !found {
@@ -1306,12 +1304,7 @@ func (ss orderedStringSet) Append(s ...string) orderedStringSet {
}
func (ss orderedStringSet) Contains(s string) bool {
for _, other := range ss {
if s == other {
return true
}
}
return false
return slices.Contains(ss, s)
}
func stringsToRefs(x []string) []ast.Ref {
@@ -1336,12 +1329,7 @@ func newRefSet(x ...ast.Ref) *refSet {
// ContainsPrefix returns true if r is prefixed by any of the existing refs in the set.
func (rs *refSet) ContainsPrefix(r ast.Ref) bool {
for i := range rs.s {
if r.HasPrefix(rs.s[i]) {
return true
}
}
return false
return slices.ContainsFunc(rs.s, r.HasPrefix)
}
// AddPrefix inserts r into the set if r is not prefixed by any existing
+1 -3
View File
@@ -437,9 +437,7 @@ p contains "B" if {
if bundleType.tar {
files["bundle.tar"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTestFS(tc.files, false, func(root string, fsys fs.FS) {
+4 -4
View File
@@ -344,14 +344,14 @@ func TestActiveConfig(t *testing.T) {
err error
}{
"valid_config_with_svc_object": {
[]byte(fmt.Sprintf(`{ %v %v }`, serviceObj, common)),
[]byte(fmt.Sprintf(`{ %v %v }`, expectedServiceObj, expectedCommon)),
fmt.Appendf(nil, `{ %v %v }`, serviceObj, common),
fmt.Appendf(nil, `{ %v %v }`, expectedServiceObj, expectedCommon),
false,
nil,
},
"valid_config_with_svc_list": {
[]byte(fmt.Sprintf(`{ %v %v }`, servicesList, common)),
[]byte(fmt.Sprintf(`{ %v %v }`, expectedServicesList, expectedCommon)),
fmt.Appendf(nil, `{ %v %v }`, servicesList, common),
fmt.Appendf(nil, `{ %v %v }`, expectedServicesList, expectedCommon),
false,
nil,
},
+1 -6
View File
@@ -700,12 +700,7 @@ func (s *session) handleEvent(t *thread, stackIndex int, e *topdown.Event, ts th
}
func (s *session) skipOp(op topdown.Op) bool {
for _, skip := range s.properties.SkipOps {
if skip == op {
return true
}
}
return false
return slices.Contains(s.properties.SkipOps, op)
}
func (s *session) result(t *thread, rs rego.ResultSet) {
+3 -11
View File
@@ -13,6 +13,7 @@ import (
"math/rand"
"net/http"
"path"
"slices"
"strconv"
"strings"
"sync"
@@ -361,9 +362,9 @@ func (d *Downloader) download(ctx context.Context, m metrics.Metrics) (*download
"application/octet-stream",
"application/vnd.openpolicyagent.bundles",
}
contentType := resp.Header.Get("content-type")
if !contains(contentType, expectedBundleContentType) {
if !slices.Contains(expectedBundleContentType, contentType) {
d.logger.Debug("Content-Type response header set to %v. Expected one of %v. "+
"Possibly not a bundle being downloaded.",
contentType,
@@ -441,12 +442,3 @@ type HTTPError struct {
func (e HTTPError) Error() string {
return "server replied with " + http.StatusText(e.StatusCode)
}
func contains(s string, strings []string) bool {
for _, str := range strings {
if s == str {
return true
}
}
return false
}
+1 -10
View File
@@ -249,7 +249,7 @@ func AstWithOpts(x any, opts Opts) ([]byte, error) {
x.Imports = ensureRegoV1Import(x.Imports)
}
regoV1Imported := moduleIsRegoV1Compatible(x)
regoV1Imported := slices.ContainsFunc(x.Imports, isRegoV1Compatible)
if regoVersion == ast.RegoV0CompatV1 || regoVersion == ast.RegoV1 || regoV1Imported {
if !opts.DropV0Imports && !regoV1Imported {
for _, kw := range o.futureKeywords {
@@ -2206,15 +2206,6 @@ func (d *ArityFormatErrDetail) Lines() []string {
}
}
func moduleIsRegoV1Compatible(m *ast.Module) bool {
for _, imp := range m.Imports {
if isRegoV1Compatible(imp) {
return true
}
}
return false
}
var v1StringTerm = ast.StringTerm("v1")
// isRegoV1Compatible returns true if the passed *ast.Import is `rego.v1`
+1 -4
View File
@@ -740,10 +740,7 @@ func differsAt(a, b []byte) (int, int) {
if bytes.Equal(a, b) {
return 0, 0
}
minLen := len(a)
if minLen > len(b) {
minLen = len(b)
}
minLen := min(len(a), len(b))
ln := 1
for i := range minLen {
if a[i] == '\n' {
+3 -6
View File
@@ -3,6 +3,7 @@ package logging
import (
"context"
"io"
"maps"
"net/http"
"github.com/sirupsen/logrus"
@@ -71,12 +72,8 @@ func (l *StandardLogger) SetFormatter(formatter logrus.Formatter) {
func (l *StandardLogger) WithFields(fields map[string]any) Logger {
cp := *l
cp.fields = make(map[string]any)
for k, v := range l.fields {
cp.fields[k] = v
}
for k, v := range fields {
cp.fields[k] = v
}
maps.Copy(cp.fields, l.fields)
maps.Copy(cp.fields, fields)
return &cp
}
+3 -6
View File
@@ -2,6 +2,7 @@ package test
import (
"fmt"
"maps"
"sync"
"github.com/open-policy-agent/opa/v1/logging"
@@ -43,12 +44,8 @@ func (l *Logger) WithFields(fields map[string]any) logging.Logger {
mtx: l.mtx,
}
flds := make(map[string]any)
for k, v := range cp.fields {
flds[k] = v
}
for k, v := range fields {
flds[k] = v
}
maps.Copy(flds, cp.fields)
maps.Copy(flds, fields)
cp.fields = flds
return &cp
}
+3 -4
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"net/url"
"path"
"slices"
"strings"
"github.com/open-policy-agent/opa/v1/plugins"
@@ -237,10 +238,8 @@ func (*Config) getServiceFromList(service string, services []string) (string, er
if service == "" && len(services) != 0 {
return services[0], nil
}
for _, svc := range services {
if svc == service {
return service, nil
}
if slices.Contains(services, service) {
return service, nil
}
return service, fmt.Errorf("service name %q not found", service)
}
+3 -6
View File
@@ -10,6 +10,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"net/url"
"os"
"path/filepath"
@@ -133,9 +134,7 @@ func (p *Plugin) Start(ctx context.Context) error {
func (p *Plugin) Stop(ctx context.Context) {
p.mtx.Lock()
stopDownloaders := map[string]Loader{}
for name, dl := range p.downloaders {
stopDownloaders[name] = dl
}
maps.Copy(stopDownloaders, p.downloaders)
p.downloaders = nil
p.stopped = true
p.mtx.Unlock()
@@ -262,9 +261,7 @@ func (p *Plugin) Trigger(ctx context.Context) error {
p.mtx.Lock()
downloaders := map[string]Loader{}
for name, dl := range p.downloaders {
downloaders[name] = dl
}
maps.Copy(downloaders, p.downloaders)
p.mtx.Unlock()
for name, d := range downloaders {
+26 -26
View File
@@ -859,7 +859,7 @@ func TestPluginStartLazyLoadInMem(t *testing.T) {
}
}))
config := []byte(fmt.Sprintf(`{
config := fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
@@ -868,7 +868,7 @@ func TestPluginStartLazyLoadInMem(t *testing.T) {
"url": %q
}
}
}`, s1.URL, s2.URL))
}`, s1.URL, s2.URL)
manager := getTestManagerWithOpts(config, inmem.NewWithOpts(inmem.OptReturnASTValuesOnRead(rm.readAst)))
defer manager.Stop(ctx)
@@ -1344,7 +1344,7 @@ func TestStop(t *testing.T) {
serviceName := "test-svc"
err := manager.Reconfigure(&config.Config{
Services: []byte(fmt.Sprintf("{%q:{ \"url\": %q}}", serviceName, ts.URL+tsURLBase)),
Services: fmt.Appendf(nil, "{%q:{ \"url\": %q}}", serviceName, ts.URL+tsURLBase),
})
if err != nil {
t.Fatalf("Error configuring plugin manager: %s", err)
@@ -1973,13 +1973,13 @@ corge contains 1 if {
}
}
expData := util.MustUnmarshalJSON([]byte(fmt.Sprintf(`{
expData := util.MustUnmarshalJSON(fmt.Appendf(nil, `{
"foo": {"bar": 1, "baz": "qux"},
"system": {
"bundles": {"test-bundle": {"etag": "foo", "manifest": {"revision": "quickbrownfaux"%s, "roots": [""]}}}%s
}
}`,
manifestRegoVersion, moduleRegoVersion)))
manifestRegoVersion, moduleRegoVersion))
if err != nil {
t.Fatal(err)
@@ -2730,22 +2730,22 @@ corge contains 1 if {
var expData any
if moduleRegoVersion != runtimeRegoVersion {
expData = util.MustUnmarshalJSON([]byte(fmt.Sprintf(`{
expData = util.MustUnmarshalJSON(fmt.Appendf(nil, `{
"foo": {"bar": 1, "baz": "qux"},
"system": {
"bundles": {"test-bundle": {"etag": "", "manifest": {"revision": "quickbrownfaux"%s, "roots": [""]}}},
"modules": {"test-bundle/foo/bar.rego": {"rego_version": %d}}
}
}`,
manifestRegoVersionStr, moduleRegoVersion)))
manifestRegoVersionStr, moduleRegoVersion))
} else {
expData = util.MustUnmarshalJSON([]byte(fmt.Sprintf(`{
expData = util.MustUnmarshalJSON(fmt.Appendf(nil, `{
"foo": {"bar": 1, "baz": "qux"},
"system": {
"bundles": {"test-bundle": {"etag": "", "manifest": {"revision": "quickbrownfaux"%s, "roots": [""]}}}
}
}`,
manifestRegoVersionStr)))
manifestRegoVersionStr))
}
if err != nil {
@@ -3978,7 +3978,7 @@ func TestPluginReconfigure(t *testing.T) {
serviceName := "test-svc"
err := manager.Reconfigure(&config.Config{
Services: []byte(fmt.Sprintf("{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase)),
Services: fmt.Appendf(nil, "{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase),
})
if err != nil {
t.Fatalf("Error configuring plugin manager: %s", err)
@@ -4657,7 +4657,7 @@ func TestUpgradeLegacyBundleToMultiBundleNewBundles(t *testing.T) {
serviceName := "test-svc"
err := manager.Reconfigure(&config.Config{
Services: []byte(fmt.Sprintf("{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase)),
Services: fmt.Appendf(nil, "{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase),
})
if err != nil {
t.Fatalf("Error configuring plugin manager: %s", err)
@@ -4814,7 +4814,7 @@ func TestLegacyBundleDataRead(t *testing.T) {
serviceName := "test-svc"
err := manager.Reconfigure(&config.Config{
Services: []byte(fmt.Sprintf("{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase)),
Services: fmt.Appendf(nil, "{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase),
})
if err != nil {
t.Fatalf("Error configuring plugin manager: %s", err)
@@ -6276,13 +6276,13 @@ func TestPluginReadBundleEtagFromDiskStore(t *testing.T) {
}
// setup plugin pointing at fake server
manager := getTestManagerWithOpts([]byte(fmt.Sprintf(`{
manager := getTestManagerWithOpts(fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
}
}
}`, s.URL)), store)
}`, s.URL), store)
var mode plugins.TriggerMode = "manual"
@@ -6460,13 +6460,13 @@ func TestPluginStateReconciliationOnReconfigure(t *testing.T) {
}))
// setup plugin pointing at fake server
manager := getTestManagerWithOpts([]byte(fmt.Sprintf(`{
manager := getTestManagerWithOpts(fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
}
}
}`, s.URL)))
}`, s.URL))
// setup manual trigger mode to simulate the downloader
var mode plugins.TriggerMode = "manual"
@@ -6630,13 +6630,13 @@ func TestPluginManualTrigger(t *testing.T) {
}))
// setup plugin pointing at fake server
manager := getTestManagerWithOpts([]byte(fmt.Sprintf(`{
manager := getTestManagerWithOpts(fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
}
}
}`, s.URL)))
}`, s.URL))
var mode plugins.TriggerMode = "manual"
@@ -6752,7 +6752,7 @@ func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) {
if err != nil {
t.Fatal(err)
}
config := []byte(fmt.Sprintf(`{
config := fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
@@ -6761,7 +6761,7 @@ func TestPluginManualTriggerMultipleDiskStorage(t *testing.T) {
"url": %q
}
}
}`, s1.URL, s2.URL))
}`, s1.URL, s2.URL)
manager := getTestManagerWithOpts(config, store)
defer manager.Stop(ctx)
@@ -6892,7 +6892,7 @@ func TestPluginManualTriggerMultiple(t *testing.T) {
}))
// setup plugin pointing at fake server
manager := getTestManagerWithOpts([]byte(fmt.Sprintf(`{
manager := getTestManagerWithOpts(fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
@@ -6901,7 +6901,7 @@ func TestPluginManualTriggerMultiple(t *testing.T) {
"url": %q
}
}
}`, s1.URL, s2.URL)))
}`, s1.URL, s2.URL))
var mode plugins.TriggerMode = "manual"
@@ -6971,13 +6971,13 @@ func TestPluginManualTriggerWithTimeout(t *testing.T) {
}))
// setup plugin pointing at fake server
manager := getTestManagerWithOpts([]byte(fmt.Sprintf(`{
manager := getTestManagerWithOpts(fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
}
}
}`, s.URL)))
}`, s.URL))
var mode plugins.TriggerMode = "manual"
@@ -7032,13 +7032,13 @@ func TestPluginManualTriggerWithServerError(t *testing.T) {
}))
// setup plugin pointing at fake server
manager := getTestManagerWithOpts([]byte(fmt.Sprintf(`{
manager := getTestManagerWithOpts(fmt.Appendf(nil, `{
"services": {
"default": {
"url": %q
}
}
}`, s.URL)))
}`, s.URL))
var manual plugins.TriggerMode = "manual"
+5 -7
View File
@@ -7,6 +7,8 @@ package discovery
import (
"errors"
"fmt"
"maps"
"slices"
"strings"
"github.com/open-policy-agent/opa/v1/keys"
@@ -92,9 +94,7 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin
// make a copy of the keys map
cpy := map[string]*keys.Config{}
for key, kc := range confKeys {
cpy[key] = kc
}
maps.Copy(cpy, confKeys)
if c.Signing != nil {
err := c.Signing.ValidateAndInjectDefaults(cpy)
@@ -141,10 +141,8 @@ func (*Config) getServiceFromList(service string, services []string) (string, er
}
return services[0], nil
}
for _, svc := range services {
if svc == service {
return service, nil
}
if slices.Contains(services, service) {
return service, nil
}
return service, fmt.Errorf("service name %q not found", service)
}
+8 -8
View File
@@ -2717,7 +2717,7 @@ func TestStatusUpdates(t *testing.T) {
ts.Start()
defer ts.Stop()
manager, err := plugins.New([]byte(fmt.Sprintf(`{
manager, err := plugins.New(fmt.Appendf(nil, `{
"labels": {"x": "y"},
"services": {
"localhost": {
@@ -2725,7 +2725,7 @@ func TestStatusUpdates(t *testing.T) {
}
},
"discovery": {"name": "config"},
}`, ts.server.URL)), "test-id", inmem.New())
}`, ts.server.URL), "test-id", inmem.New())
if err != nil {
t.Fatal(err)
}
@@ -2892,7 +2892,7 @@ func TestStatusUpdatesFromPersistedBundlesDontDelayBoot(t *testing.T) {
}
defer listener.Close()
manager, err := plugins.New([]byte(fmt.Sprintf(`{
manager, err := plugins.New(fmt.Appendf(nil, `{
"persistence_directory": %q,
"services": {
"localhost": {
@@ -2900,7 +2900,7 @@ func TestStatusUpdatesFromPersistedBundlesDontDelayBoot(t *testing.T) {
}
},
"discovery": {"name": "config", "persist": true, "decision": "discovery"},
}`, dir, listener.Addr().String())), "test-id", inmem.New())
}`, dir, listener.Addr().String()), "test-id", inmem.New())
if err != nil {
t.Fatal(err)
}
@@ -2943,7 +2943,7 @@ func TestStatusUpdatesTimestamp(t *testing.T) {
ts.Start()
defer ts.Stop()
manager, err := plugins.New([]byte(fmt.Sprintf(`{
manager, err := plugins.New(fmt.Appendf(nil, `{
"labels": {"x": "y"},
"services": {
"localhost": {
@@ -2951,7 +2951,7 @@ func TestStatusUpdatesTimestamp(t *testing.T) {
}
},
"discovery": {"name": "config"},
}`, ts.server.URL)), "test-id", inmem.New())
}`, ts.server.URL), "test-id", inmem.New())
if err != nil {
t.Fatal(err)
}
@@ -3875,7 +3875,7 @@ func newTestFixture(t *testing.T) *testFixture {
ts.start()
managerConfig := []byte(fmt.Sprintf(`{
managerConfig := fmt.Appendf(nil, `{
"labels": {
"app": "example-app"
},
@@ -3885,7 +3885,7 @@ func newTestFixture(t *testing.T) *testFixture {
"name": "example",
"url": %q
}
]}`, ts.server.URL))
]}`, ts.server.URL)
manager, err := plugins.New(managerConfig, "test-id", inmem.New())
if err != nil {
+3 -2
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"net/url"
"slices"
"strconv"
"strings"
@@ -265,10 +266,10 @@ func (maskRule) removeValue(p []string, node any) error {
return errMaskInvalidObject
}
nodeParent[index] = append(v[:targetIndex], v[targetIndex+1:]...)
nodeParent[index] = slices.Delete(v, targetIndex, targetIndex+1)
case map[string]any:
nodeParent[nodeKey] = append(v[:targetIndex], v[targetIndex+1:]...)
nodeParent[nodeKey] = slices.Delete(v, targetIndex, targetIndex+1)
default:
return errMaskInvalidObject
+4 -13
View File
@@ -15,6 +15,7 @@ import (
"math/rand"
"net/url"
"reflect"
"slices"
"strings"
"sync"
"time"
@@ -309,11 +310,8 @@ func (c *Config) validateAndInjectDefaults(services []string, pluginsList []stri
if c.Plugin != nil {
var found bool
for _, other := range pluginsList {
if other == *c.Plugin {
found = true
break
}
if slices.Contains(pluginsList, *c.Plugin) {
found = true
}
if !found {
return fmt.Errorf("invalid plugin name %q in decision_logs", *c.Plugin)
@@ -325,14 +323,7 @@ func (c *Config) validateAndInjectDefaults(services []string, pluginsList []stri
// both console logs and the default service option.
c.Service = services[0]
} else if c.Service != "" {
found := false
for _, svc := range services {
if svc == c.Service {
found = true
break
}
}
found := slices.Contains(services, c.Service)
if !found {
return fmt.Errorf("invalid service name %q in decision_logs", c.Service)
+5 -12
View File
@@ -9,6 +9,7 @@ import (
"context"
"errors"
"fmt"
"maps"
mr "math/rand"
"sync"
"time"
@@ -791,9 +792,7 @@ func (m *Manager) Reconfigure(config *config.Config) error {
if config.Labels == nil {
config.Labels = m.bootstrapConfigLabels
} else {
for label, value := range m.bootstrapConfigLabels {
config.Labels[label] = value
}
maps.Copy(config.Labels, m.bootstrapConfigLabels)
}
// don't erase persistence directory
@@ -803,13 +802,9 @@ func (m *Manager) Reconfigure(config *config.Config) error {
m.Config = config
m.interQueryBuiltinCacheConfig = interQueryBuiltinCacheConfig
for name, client := range services { //nolint:gocritic
m.services[name] = client
}
for name, key := range keys {
m.keys[name] = key
}
maps.Copy(m.services, services)
maps.Copy(m.keys, keys)
for _, trigger := range m.registeredCacheTriggers {
trigger(interQueryBuiltinCacheConfig)
@@ -861,9 +856,7 @@ func (m *Manager) UpdatePluginStatus(pluginName string, status *Status) {
defer m.mtx.Unlock()
m.pluginStatus[pluginName] = status
toNotify = make(map[string]StatusListener, len(m.pluginStatusListeners))
for k, v := range m.pluginStatusListeners {
toNotify[k] = v
}
maps.Copy(toNotify, m.pluginStatusListeners)
statuses = m.copyPluginStatus()
}()
+1 -2
View File
@@ -16,12 +16,11 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"slices"
"github.com/open-policy-agent/opa/internal/providers/aws"
"github.com/open-policy-agent/opa/v1/logging"
"github.com/open-policy-agent/opa/v1/util/test"
+5 -24
View File
@@ -13,6 +13,7 @@ import (
"maps"
"net/http"
"reflect"
"slices"
lstat "github.com/open-policy-agent/opa/v1/plugins/logs/status"
@@ -97,36 +98,16 @@ type trigger struct {
}
func (c *Config) validateAndInjectDefaults(services []string, pluginsList []string, trigger *plugins.TriggerMode) error {
if c.Plugin != nil {
var found bool
for _, other := range pluginsList {
if other == *c.Plugin {
found = true
break
}
}
if !found {
return fmt.Errorf("invalid plugin name %q in status", *c.Plugin)
}
if c.Plugin != nil && !slices.Contains(pluginsList, *c.Plugin) {
return fmt.Errorf("invalid plugin name %q in status", *c.Plugin)
} else if c.Service == "" && len(services) != 0 && !(c.ConsoleLogs || c.Prometheus) {
// For backwards compatibility allow defaulting to the first
// service listed, but only if console logging is disabled. If enabled
// we can't tell if the deployer wanted to use only console logs or
// both console logs and the default service option.
c.Service = services[0]
} else if c.Service != "" {
found := false
for _, svc := range services {
if svc == c.Service {
found = true
break
}
}
if !found {
return fmt.Errorf("invalid service name %q in status", c.Service)
}
} else if c.Service != "" && !slices.Contains(services, c.Service) {
return fmt.Errorf("invalid service name %q in status", c.Service)
}
t, err := plugins.ValidateAndInjectDefaultsForTriggerMode(trigger, c.Trigger)
+4 -4
View File
@@ -576,7 +576,7 @@ func TestPluginStartTriggerManualWithTimeout(t *testing.T) {
time.Sleep(3 * time.Second) // this should cause the context deadline to exceed
}))
managerConfig := []byte(fmt.Sprintf(`{
managerConfig := fmt.Appendf(nil, `{
"labels": {
"app": "example-app"
},
@@ -585,7 +585,7 @@ func TestPluginStartTriggerManualWithTimeout(t *testing.T) {
"name": "example",
"url": %q
}
]}`, s.URL))
]}`, s.URL)
manager, err := plugins.New(managerConfig, "test-instance-id", inmem.New())
if err != nil {
@@ -1138,7 +1138,7 @@ func newTestFixture(t *testing.T, m metrics.Metrics, options ...testPluginCustom
ts.start()
managerConfig := []byte(fmt.Sprintf(`{
managerConfig := fmt.Appendf(nil, `{
"labels": {
"app": "example-app"
},
@@ -1153,7 +1153,7 @@ func newTestFixture(t *testing.T, m metrics.Metrics, options ...testPluginCustom
}
}
}
]}`, ts.server.URL))
]}`, ts.server.URL)
registerMock := &prometheusRegisterMock{
Collectors: map[prometheus.Collector]bool{},
+1 -3
View File
@@ -391,9 +391,7 @@ func EvalNondeterministicBuiltins(yes bool) EvalOption {
func (pq preparedQuery) Modules() map[string]*ast.Module {
mods := make(map[string]*ast.Module)
for name, mod := range pq.r.parsedModules {
mods[name] = mod
}
maps.Copy(mods, pq.r.parsedModules)
for _, b := range pq.r.bundles {
for _, mod := range b.Modules {
+5 -17
View File
@@ -12,10 +12,12 @@ import (
"errors"
"fmt"
"log"
"maps"
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"sync"
@@ -951,13 +953,7 @@ func TestRegoDisableIndexing(t *testing.T) {
}
for _, expected := range expectedEvalNodes {
found := false
for _, actual := range evalNodes {
if actual == expected {
found = true
break
}
}
found := slices.Contains(evalNodes, expected)
if !found {
t.Fatalf("Missing expected eval node in trace: %q\nGot: %q\n", expected, evalNodes)
}
@@ -1011,13 +1007,7 @@ func TestRegoDisableIndexingWithMatch(t *testing.T) {
}
for _, expected := range expectedEvalNodes {
found := false
for _, actual := range evalNodes {
if actual == expected {
found = true
break
}
}
found := slices.Contains(evalNodes, expected)
if !found {
t.Fatalf("Missing expected eval node in trace: %q\nGot: %q\n", expected, evalNodes)
}
@@ -2755,9 +2745,7 @@ func TestEvalWithInterQueryCache(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range newHeaders {
headers[k] = v
}
maps.Copy(headers, newHeaders)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"x": 1}`))
+4 -9
View File
@@ -14,6 +14,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"os"
"strconv"
"strings"
@@ -820,9 +821,7 @@ func (r *REPL) compileRule(ctx context.Context, rule *ast.Rule) error {
return err
}
for id, mod := range r.modules {
policies[id] = mod
}
maps.Copy(policies, r.modules)
compiler := ast.NewCompiler().
SetErrorLimit(r.errLimit).
@@ -949,9 +948,7 @@ func (r *REPL) loadCompiler(ctx context.Context) (*ast.Compiler, error) {
return nil, err
}
for id, mod := range r.modules {
policies[id] = mod
}
maps.Copy(policies, r.modules)
compiler := ast.NewCompiler().
SetErrorLimit(r.errLimit).
@@ -1274,9 +1271,7 @@ func (r *REPL) loadModules(ctx context.Context, txn storage.Transaction) (map[st
if len(r.initBundles) > 0 {
for bundleName, b := range r.initBundles {
for name, module := range b.ParsedModules(bundleName) {
modules[name] = module
}
maps.Copy(modules, b.ParsedModules(bundleName))
}
}
+2 -3
View File
@@ -9,6 +9,7 @@ import (
"context"
"encoding/json"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"os"
@@ -1318,9 +1319,7 @@ func TestServerInitializedWithBundleRegoVersion(t *testing.T) {
if bundleType.tar {
files["bundle.tar.gz"] = ""
} else {
for k, v := range tc.files {
files[k] = v
}
maps.Copy(files, tc.files)
}
test.WithTempFS(files, func(root string) {
+2 -3
View File
@@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
"io"
"maps"
"net/http"
"net/http/httptest"
"os"
@@ -442,9 +443,7 @@ func (s *Server) handleBundles(w http.ResponseWriter, r *http.Request) {
return
}
for k, v := range d {
data[k] = v
}
maps.Copy(data, d)
default:
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "unexpected file in dummy bundle: %s", url)
+2 -10
View File
@@ -19,6 +19,7 @@ import (
"net/http/pprof"
"net/url"
"os"
"slices"
"strconv"
"strings"
"sync"
@@ -387,7 +388,7 @@ func (s *Server) WithRouter(router *mux.Router) *Server {
}
func (s *Server) WithMinTLSVersion(minTLSVersion uint16) *Server {
if isMinTLSVersionSupported(minTLSVersion) {
if slices.Contains(supportedTLSVersions, minTLSVersion) {
s.minTLSVersion = minTLSVersion
} else {
s.minTLSVersion = defaultMinTLSVersion
@@ -581,15 +582,6 @@ func (b *baseHTTPListener) Type() httpListenerType {
return b.t
}
func isMinTLSVersionSupported(tlsVersion uint16) bool {
for _, version := range supportedTLSVersions {
if tlsVersion == version {
return true
}
}
return false
}
func (s *Server) getListener(addr string, h http.Handler, t httpListenerType) ([]Loop, httpListener, error) {
parsedURL, err := parseURL(addr, s.cert != nil)
if err != nil {
+5 -18
View File
@@ -31,6 +31,7 @@ import (
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"sync/atomic"
@@ -5661,14 +5662,7 @@ func TestAddrsWithMixedListenerAddr(t *testing.T) {
}
for _, expectedAddr := range expected {
found := false
for _, actualAddr := range a {
if expectedAddr == actualAddr {
found = true
break
}
}
if !found {
if !slices.Contains(a, expectedAddr) {
t.Errorf("expected %q in address list, got: %+v", expectedAddr, a)
}
}
@@ -5724,14 +5718,7 @@ func TestDiagnosticAddrsWithMixedListenerAddr(t *testing.T) {
}
for _, expectedAddr := range expected {
found := false
for _, actualAddr := range a {
if expectedAddr == actualAddr {
found = true
break
}
}
if !found {
if !slices.Contains(a, expectedAddr) {
t.Errorf("expected %q in address list, got: %+v", expectedAddr, a)
}
}
@@ -5880,7 +5867,7 @@ func TestDistributedTracingResourceAttributes(t *testing.T) {
semconv.ServiceInstanceIDKey: "1",
}
c := []byte(fmt.Sprintf(`{"distributed_tracing": {
c := fmt.Appendf(nil, `{"distributed_tracing": {
"type": "grpc",
"service_name": "%s",
"resource": {
@@ -5893,7 +5880,7 @@ func TestDistributedTracingResourceAttributes(t *testing.T) {
attributes[semconv.ServiceNamespaceKey],
attributes[semconv.ServiceVersionKey],
attributes[semconv.ServiceInstanceIDKey],
attributes[semconv.DeploymentEnvironmentKey]))
attributes[semconv.DeploymentEnvironmentKey])
ctx := context.Background()
_, traceProvider, resource, err := distributedtracing.Init(ctx, c, "foo")
+2 -6
View File
@@ -66,6 +66,7 @@ import (
"os"
"path"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
@@ -1024,10 +1025,5 @@ func lookup(path storage.Path, data []byte) (any, bool, error) {
}
func overwriteRoot(roots []string) bool {
for _, root := range roots {
if root == "" {
return true
}
}
return false
return slices.Contains(roots, "")
}
+1 -6
View File
@@ -139,12 +139,7 @@ func (ps pathSet) Diff(other pathSet) pathSet {
}
func (ps pathSet) Contains(x storage.Path) bool {
for _, other := range ps {
if x.Equal(other) {
return true
}
}
return false
return slices.ContainsFunc(ps, x.Equal)
}
func (ps pathSet) Sorted() []storage.Path {
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"context"
"encoding/json"
"fmt"
"slices"
"strconv"
badger "github.com/dgraph-io/badger/v4"
@@ -558,7 +559,7 @@ func patch(data any, op storage.PatchOp, path storage.Path, idx int, value any)
return nil, err
}
return append(x[:i], x[i+1:]...), nil // i is skipped
return slices.Delete(x, i, i+1), nil // i is skipped
default:
panic("unreachable")
}
+2 -4
View File
@@ -72,11 +72,9 @@ func TestHttpSendInterQueryForceCache(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
counter++
w.Header()["Content-Type"] = []string{"application/json"}
for k, v := range tc.respHeaders {
w.Header()[k] = v
}
maps.Copy(w.Header(), tc.respHeaders)
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(fmt.Sprintf(`{"c": %d}`, counter)))
_, err := w.Write(fmt.Appendf(nil, `{"c": %d}`, counter))
if err != nil {
t.Fatal(err)
}
+4 -4
View File
@@ -11,7 +11,9 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"regexp"
"slices"
"strconv"
"strings"
"testing"
@@ -479,9 +481,7 @@ func (r *Runner) runTests(ctx context.Context, txn storage.Transaction, enablePr
r.modules = map[string]*ast.Module{}
}
for path, b := range r.bundles {
for name, mod := range b.ParsedModules(path) {
r.modules[name] = mod
}
maps.Copy(r.modules, b.ParsedModules(path))
}
}
@@ -790,7 +790,7 @@ func moveExpr(body ast.Body, from int, to int) (ast.Body, bool) {
}
expr := body[from] // Save the expression to move
body = append(body[:from], body[from+1:]...) // Remove the expression from the body
body = slices.Delete(body, from, from+1) // Remove the expression from the body
body = append(body[:to], append(ast.Body{expr}, body[to:]...)...) // Insert the expression at the new position
return body, true
}
+4 -4
View File
@@ -93,7 +93,7 @@ func (u *bindings) plugNamespaced(a *ast.Term, caller *bindings) *ast.Term {
}
cpy := *a
arr := make([]*ast.Term, v.Len())
for i := 0; i < len(arr); i++ {
for i := range arr {
arr[i] = u.plugNamespaced(v.Elem(i), caller)
}
cpy.Value = ast.NewArray(arr...)
@@ -119,7 +119,7 @@ func (u *bindings) plugNamespaced(a *ast.Term, caller *bindings) *ast.Term {
case ast.Ref:
cpy := *a
ref := make(ast.Ref, len(v))
for i := 0; i < len(ref); i++ {
for i := range ref {
ref[i] = u.plugNamespaced(v[i], caller)
}
cpy.Value = ref
@@ -254,7 +254,7 @@ func (vis namespacingVisitor) namespaceTerm(a *ast.Term) *ast.Term {
}
cpy := *a
arr := make([]*ast.Term, v.Len())
for i := 0; i < len(arr); i++ {
for i := range arr {
arr[i] = vis.namespaceTerm(v.Elem(i))
}
cpy.Value = ast.NewArray(arr...)
@@ -280,7 +280,7 @@ func (vis namespacingVisitor) namespaceTerm(a *ast.Term) *ast.Term {
case ast.Ref:
cpy := *a
ref := make(ast.Ref, len(v))
for i := 0; i < len(ref); i++ {
for i := range ref {
ref[i] = vis.namespaceTerm(v[i])
}
cpy.Value = ref
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"math/big"
"net"
"slices"
"sort"
cidrMerge "github.com/open-policy-agent/opa/internal/cidr/merge"
@@ -392,7 +393,7 @@ func mergeCIDRs(ranges cidrBlockRanges) cidrBlockRanges {
ranges[i-1] = &cidrBlockRange{First: &firstIPRange, Last: &lastIPRange, Network: nil}
// Delete ranges[i] since merged with the previous.
ranges = append(ranges[:i], ranges[i+1:]...)
ranges = slices.Delete(ranges, i, i+1)
}
}
return ranges
+3 -4
View File
@@ -19,6 +19,7 @@ import (
"net/url"
"os"
"runtime"
"slices"
"strconv"
"strings"
"time"
@@ -379,10 +380,8 @@ func verifyHost(bctx BuiltinContext, host string) error {
return nil
}
for _, allowed := range bctx.Capabilities.AllowNet {
if allowed == host {
return nil
}
if slices.Contains(bctx.Capabilities.AllowNet, host) {
return nil
}
return fmt.Errorf("unallowed host: %s", host)
+13 -28
View File
@@ -14,6 +14,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"math"
"net"
"net/http"
@@ -21,6 +22,7 @@ import (
"net/url"
"os"
"reflect"
"slices"
"strconv"
"strings"
"testing"
@@ -513,8 +515,7 @@ func TestHTTPDeleteRequest(t *testing.T) {
var people []Person
// test data
people = append(people, Person{ID: "1", Firstname: "John"})
people = append(people, Person{ID: "2", Firstname: "Joe"})
people = append(people, Person{ID: "1", Firstname: "John"}, Person{ID: "2", Firstname: "Joe"})
// test server
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -532,7 +533,7 @@ func TestHTTPDeleteRequest(t *testing.T) {
// delete person
for index, item := range people {
if item.ID == person.ID {
people = append(people[:index], people[index+1:]...)
people = slices.Delete(people, index, index+1)
break
}
}
@@ -1244,9 +1245,7 @@ func TestHTTPSendIntraQueryCaching(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range tc.headers {
headers[k] = v
}
maps.Copy(headers, tc.headers)
headers.Set("Date", t0.Format(time.RFC850))
@@ -1404,9 +1403,7 @@ func TestHTTPSendInterQueryCaching(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range tc.headers {
headers[k] = v
}
maps.Copy(headers, tc.headers)
headers.Set("Date", t0.Format(time.RFC850))
@@ -1575,9 +1572,7 @@ func TestHTTPSendInterQueryForceCaching(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range tc.headers {
headers[k] = v
}
maps.Copy(headers, tc.headers)
headers.Set("Date", t0.Format(http.TimeFormat))
@@ -1659,9 +1654,7 @@ func TestHTTPSendInterQueryForceCachingRefresh(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range tc.headers {
headers[k] = v
}
maps.Copy(headers, tc.headers)
if tc.skipDate {
headers["Date"] = nil
@@ -1809,9 +1802,7 @@ func TestHTTPSendInterQueryCachingModifiedResp(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range tc.headers {
headers[k] = v
}
maps.Copy(headers, tc.headers)
headers.Set("Date", t0.Format(http.TimeFormat))
@@ -1887,9 +1878,7 @@ func TestHTTPSendInterQueryCachingNewResp(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range tc.headers {
headers[k] = v
}
maps.Copy(headers, tc.headers)
headers.Set("Date", t0.Format(http.TimeFormat))
@@ -1984,9 +1973,7 @@ func TestInsertIntoHTTPSendInterQueryCacheError(t *testing.T) {
requests = append(requests, r)
headers := w.Header()
for k, v := range tc.headers {
headers[k] = v
}
maps.Copy(headers, tc.headers)
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(tc.response))
@@ -3768,10 +3755,8 @@ type secretTransport struct {
}
func (st *secretTransport) RoundTrip(req *http.Request) (*http.Response, error) {
for k, v := range st.extraRequestHeaders {
// Set additional headers on the request not visible to the caller
req.Header[k] = v
}
// Set additional headers on the request not visible to the caller
maps.Copy(req.Header, st.extraRequestHeaders)
return st.Transport.RoundTrip(req)
}
+3 -7
View File
@@ -1,8 +1,10 @@
package topdown
import (
"cmp"
"container/list"
"fmt"
"slices"
"strings"
"github.com/open-policy-agent/opa/v1/ast"
@@ -418,13 +420,7 @@ func ignoreDuringPartial(bi *ast.Builtin) bool {
// Note(philipc): We keep this legacy check around to avoid breaking
// existing library users.
//nolint:staticcheck // We specifically ignore our own linter warning here.
for _, ignore := range ast.IgnoreDuringPartialEval {
if bi == ignore {
return true
}
}
// Otherwise, ensure all non-deterministic builtins are thrown out.
return bi.Nondeterministic
return cmp.Or(slices.Contains(ast.IgnoreDuringPartialEval, bi), bi.Nondeterministic)
}
type inliningControl struct {
+2 -8
View File
@@ -328,10 +328,7 @@ func builtinSubstring(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter
return iter(operands[0])
}
upto := startIndex + length
if len(sbase) < upto {
upto = len(sbase)
}
upto := min(len(sbase), startIndex+length)
return iter(ast.StringTerm(sbase[startIndex:upto]))
}
@@ -349,10 +346,7 @@ func builtinSubstring(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter
if length < 0 {
s = string(runes[startIndex:])
} else {
upto := startIndex + length
if len(runes) < upto {
upto = len(runes)
}
upto := min(len(runes), startIndex+length)
s = string(runes[startIndex:upto])
}
+2 -2
View File
@@ -2364,8 +2364,8 @@ func getTestNamespace() string {
for more := true; more; {
var f runtime.Frame
f, more = frames.Next()
if strings.HasPrefix(f.Function, "github.com/open-policy-agent/opa/topdown.Test") {
return strings.TrimPrefix(strings.ToLower(strings.TrimPrefix(strings.TrimPrefix(f.Function, "github.com/open-policy-agent/opa/topdown.Test"), "TopDown")), "builtin")
if after, ok := strings.CutPrefix(f.Function, "github.com/open-policy-agent/opa/topdown.Test"); ok {
return strings.TrimPrefix(strings.ToLower(strings.TrimPrefix(after, "TopDown")), "builtin")
}
}
}
+3 -6
View File
@@ -865,12 +865,9 @@ func printArrows(w *bytes.Buffer, l []varInfo, printValueAt int) {
for j := range spaces {
tab := false
for _, t := range info.exprLoc.Tabs {
if t == j+prevCol+1 {
w.WriteString("\t")
tab = true
break
}
if slices.Contains(info.exprLoc.Tabs, j+prevCol+1) {
w.WriteString("\t")
tab = true
}
if !tab {
w.WriteString(" ")
+7 -20
View File
@@ -588,10 +588,7 @@ func (t Any) Union(other Any) Any {
return other
}
// Prealloc the output list.
maxLen := lenT
if lenT < lenOther {
maxLen = lenOther
}
maxLen := max(lenT, lenOther)
merged := make(Any, 0, maxLen)
// Note(philipc): Create a merged slice, doing the minimum number of
// comparisons along the way. We treat this as a problem of merging two
@@ -897,10 +894,7 @@ func Compare(a, b Type) int {
lenStaticA := len(objA.static)
lenStaticB := len(objB.static)
minLen := lenStaticA
if lenStaticB < minLen {
minLen = lenStaticB
}
minLen := min(lenStaticB, lenStaticA)
for i := range minLen {
if cmp := util.Compare(objA.static[i].Key, objB.static[i].Key); cmp != 0 {
@@ -1105,17 +1099,13 @@ func Nil(a Type) bool {
case nil:
return true
case *Function:
for i := range a.args {
if Nil(a.args[i]) {
return true
}
if slices.ContainsFunc(a.args, Nil) {
return true
}
return Nil(a.result)
case *Array:
for i := range a.static {
if Nil(a.static[i]) {
return true
}
if slices.ContainsFunc(a.static, Nil) {
return true
}
if a.dynamic != nil {
return Nil(a.dynamic)
@@ -1178,10 +1168,7 @@ func (s typeSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s typeSlice) Len() int { return len(s) }
func typeSliceCompare(a, b []Type) int {
minLen := len(a)
if len(b) < minLen {
minLen = len(b)
}
minLen := min(len(b), len(a))
for i := range minLen {
if cmp := Compare(a[i], b[i]); cmp != 0 {
return cmp
+2 -8
View File
@@ -78,10 +78,7 @@ func Compare(a, b any) int {
case []any:
bLen := len(b)
aLen := len(a)
minLen := aLen
if bLen < minLen {
minLen = bLen
}
minLen := min(bLen, aLen)
for i := range minLen {
cmp := Compare(a[i], b[i])
if cmp != 0 {
@@ -102,10 +99,7 @@ func Compare(a, b any) int {
bKeys := KeysSorted(b)
aLen := len(aKeys)
bLen := len(bKeys)
minLen := aLen
if bLen < minLen {
minLen = bLen
}
minLen := min(bLen, aLen)
for i := range minLen {
if aKeys[i] < bKeys[i] {
return -1