diff --git a/cmd/bench_test.go b/cmd/bench_test.go index 8e48e07e73..e0d8a76ad9 100644 --- a/cmd/bench_test.go +++ b/cmd/bench_test.go @@ -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, diff --git a/cmd/build_test.go b/cmd/build_test.go index 27b4b9a740..9ad2120a0b 100644 --- a/cmd/build_test.go +++ b/cmd/build_test.go @@ -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) } diff --git a/cmd/check.go b/cmd/check.go index e4492d89d8..e02eac9c80 100644 --- a/cmd/check.go +++ b/cmd/check.go @@ -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{ diff --git a/cmd/check_test.go b/cmd/check_test.go index 333496fa43..86bb9dd31f 100644 --- a/cmd/check_test.go +++ b/cmd/check_test.go @@ -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) { diff --git a/cmd/deps.go b/cmd/deps.go index e82db8dc85..0dbac853ef 100644 --- a/cmd/deps.go +++ b/cmd/deps.go @@ -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)) } } diff --git a/cmd/deps_test.go b/cmd/deps_test.go index 6e25d620ee..30ef7d4562 100644 --- a/cmd/deps_test.go +++ b/cmd/deps_test.go @@ -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) { diff --git a/cmd/eval_test.go b/cmd/eval_test.go index 74f2bc34c3..73ec166bc2 100755 --- a/cmd/eval_test.go +++ b/cmd/eval_test.go @@ -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) { diff --git a/cmd/exec_test.go b/cmd/exec_test.go index 79f64863f0..ee30f96889 100644 --- a/cmd/exec_test.go +++ b/cmd/exec_test.go @@ -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) { diff --git a/cmd/inspect_test.go b/cmd/inspect_test.go index baa9f049eb..dbc0595a3c 100644 --- a/cmd/inspect_test.go +++ b/cmd/inspect_test.go @@ -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) { diff --git a/cmd/run.go b/cmd/run.go index a1d764c5c4..e5b743294e 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -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) diff --git a/cmd/test_test.go b/cmd/test_test.go index f105a3f033..6e155ab230 100644 --- a/cmd/test_test.go +++ b/cmd/test_test.go @@ -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) { diff --git a/compile/compile_test.go b/compile/compile_test.go index 4d3dad4947..e197ed75d0 100644 --- a/compile/compile_test.go +++ b/compile/compile_test.go @@ -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) { diff --git a/internal/edittree/bitvector/bitvector.go b/internal/edittree/bitvector/bitvector.go index 8e4d65ed3f..bfacf3bcea 100644 --- a/internal/edittree/bitvector/bitvector.go +++ b/internal/edittree/bitvector/bitvector.go @@ -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 diff --git a/internal/gojsonschema/schemaType.go b/internal/gojsonschema/schemaType.go index 271832d334..4abcc6814e 100644 --- a/internal/gojsonschema/schemaType.go +++ b/internal/gojsonschema/schemaType.go @@ -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 { diff --git a/internal/gojsonschema/utils.go b/internal/gojsonschema/utils.go index 05808ecfd2..ca071930f2 100644 --- a/internal/gojsonschema/utils.go +++ b/internal/gojsonschema/utils.go @@ -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) { diff --git a/internal/presentation/presentation.go b/internal/presentation/presentation.go index 7f89f24312..4329a3dcdd 100644 --- a/internal/presentation/presentation.go +++ b/internal/presentation/presentation.go @@ -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 { diff --git a/internal/providers/aws/crypto/compare.go b/internal/providers/aws/crypto/compare.go index 103dc77667..e2514423b7 100644 --- a/internal/providers/aws/crypto/compare.go +++ b/internal/providers/aws/crypto/compare.go @@ -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 diff --git a/internal/report/report.go b/internal/report/report.go index 55f4cfe210..b517864ed3 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -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 { diff --git a/internal/wasm/sdk/internal/wasm/vm.go b/internal/wasm/sdk/internal/wasm/vm.go index 73a46cc0db..396b542693 100644 --- a/internal/wasm/sdk/internal/wasm/vm.go +++ b/internal/wasm/sdk/internal/wasm/vm.go @@ -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. diff --git a/v1/ast/annotations.go b/v1/ast/annotations.go index 1f92c5a6c9..5d906e35cd 100644 --- a/v1/ast/annotations.go +++ b/v1/ast/annotations.go @@ -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) } } } diff --git a/v1/ast/check.go b/v1/ast/check.go index ca48ea58b2..ffc3d8b264 100644 --- a/v1/ast/check.go +++ b/v1/ast/check.go @@ -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 diff --git a/v1/ast/compare.go b/v1/ast/compare.go index b5d8ca7670..c4754341de 100644 --- a/v1/ast/compare.go +++ b/v1/ast/compare.go @@ -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 diff --git a/v1/ast/compile.go b/v1/ast/compile.go index 81464e5cad..1f48a0d0b6 100644 --- a/v1/ast/compile.go +++ b/v1/ast/compile.go @@ -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...) diff --git a/v1/ast/compile_test.go b/v1/ast/compile_test.go index 48d6606731..5c7e01b348 100644 --- a/v1/ast/compile_test.go +++ b/v1/ast/compile_test.go @@ -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) } diff --git a/v1/ast/oracle/oracle_test.go b/v1/ast/oracle/oracle_test.go index e6094b717b..7098195f0d 100644 --- a/v1/ast/oracle/oracle_test.go +++ b/v1/ast/oracle/oracle_test.go @@ -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{ diff --git a/v1/ast/parser.go b/v1/ast/parser.go index 678466d58a..f835ef323b 100644 --- a/v1/ast/parser.go +++ b/v1/ast/parser.go @@ -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) } diff --git a/v1/ast/parser_ext.go b/v1/ast/parser_ext.go index dec06f1969..42b0503690 100644 --- a/v1/ast/parser_ext.go +++ b/v1/ast/parser_ext.go @@ -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) + "^"} } diff --git a/v1/ast/policy.go b/v1/ast/policy.go index cf8e1970c3..fd669f1e78 100644 --- a/v1/ast/policy.go +++ b/v1/ast/policy.go @@ -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 diff --git a/v1/ast/pretty_test.go b/v1/ast/pretty_test.go index 82ff5cdb6b..96603d5ed1 100644 --- a/v1/ast/pretty_test.go +++ b/v1/ast/pretty_test.go @@ -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] { diff --git a/v1/ast/term.go b/v1/ast/term.go index e366b0f335..a111fe8e0f 100644 --- a/v1/ast/term.go +++ b/v1/ast/term.go @@ -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. diff --git a/v1/bundle/bundle.go b/v1/bundle/bundle.go index 8efb06a67c..865e4b64b9 100644 --- a/v1/bundle/bundle.go +++ b/v1/bundle/bundle.go @@ -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) } } diff --git a/v1/bundle/file_bench_test.go b/v1/bundle/file_bench_test.go index d6c7c288f8..e71e41a2c8 100644 --- a/v1/bundle/file_bench_test.go +++ b/v1/bundle/file_bench_test.go @@ -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) { diff --git a/v1/bundle/sign.go b/v1/bundle/sign.go index 0d6a2fae4a..edc41a1e50 100644 --- a/v1/bundle/sign.go +++ b/v1/bundle/sign.go @@ -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 diff --git a/v1/bundle/store.go b/v1/bundle/store.go index b1031938c2..33e6887d84 100644 --- a/v1/bundle/store.go +++ b/v1/bundle/store.go @@ -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)) } } diff --git a/v1/bundle/store_test.go b/v1/bundle/store_test.go index bd37388bf4..5b57b9784d 100644 --- a/v1/bundle/store_test.go +++ b/v1/bundle/store_test.go @@ -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) } diff --git a/v1/compile/compile.go b/v1/compile/compile.go index 57f980ed84..9f22e340db 100644 --- a/v1/compile/compile.go +++ b/v1/compile/compile.go @@ -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 diff --git a/v1/compile/compile_test.go b/v1/compile/compile_test.go index 53d7002510..65404abea6 100644 --- a/v1/compile/compile_test.go +++ b/v1/compile/compile_test.go @@ -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) { diff --git a/v1/config/config_test.go b/v1/config/config_test.go index 7d1ff51a79..eb25bd8bd4 100644 --- a/v1/config/config_test.go +++ b/v1/config/config_test.go @@ -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, }, diff --git a/v1/debug/debugger.go b/v1/debug/debugger.go index b9feaf12d0..9e74410a25 100644 --- a/v1/debug/debugger.go +++ b/v1/debug/debugger.go @@ -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) { diff --git a/v1/download/download.go b/v1/download/download.go index c17e4a19a5..4a8a42a946 100644 --- a/v1/download/download.go +++ b/v1/download/download.go @@ -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 -} diff --git a/v1/format/format.go b/v1/format/format.go index 815b7ca9d9..5160a44bef 100644 --- a/v1/format/format.go +++ b/v1/format/format.go @@ -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` diff --git a/v1/format/format_test.go b/v1/format/format_test.go index 29a94ff5c5..3e4d709c1c 100644 --- a/v1/format/format_test.go +++ b/v1/format/format_test.go @@ -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' { diff --git a/v1/logging/logging.go b/v1/logging/logging.go index 707854c5bc..9e36a20bf8 100644 --- a/v1/logging/logging.go +++ b/v1/logging/logging.go @@ -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 } diff --git a/v1/logging/test/test.go b/v1/logging/test/test.go index d216cdde87..dacefe5596 100644 --- a/v1/logging/test/test.go +++ b/v1/logging/test/test.go @@ -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 } diff --git a/v1/plugins/bundle/config.go b/v1/plugins/bundle/config.go index 8a75caa888..cad437b6bd 100644 --- a/v1/plugins/bundle/config.go +++ b/v1/plugins/bundle/config.go @@ -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) } diff --git a/v1/plugins/bundle/plugin.go b/v1/plugins/bundle/plugin.go index fe65fda63f..2e982c580f 100644 --- a/v1/plugins/bundle/plugin.go +++ b/v1/plugins/bundle/plugin.go @@ -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 { diff --git a/v1/plugins/bundle/plugin_test.go b/v1/plugins/bundle/plugin_test.go index e58617aca0..78a3afa15b 100644 --- a/v1/plugins/bundle/plugin_test.go +++ b/v1/plugins/bundle/plugin_test.go @@ -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" diff --git a/v1/plugins/discovery/config.go b/v1/plugins/discovery/config.go index 117b28c56a..aeb3ded8ba 100644 --- a/v1/plugins/discovery/config.go +++ b/v1/plugins/discovery/config.go @@ -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) } diff --git a/v1/plugins/discovery/discovery_test.go b/v1/plugins/discovery/discovery_test.go index fddc7f509f..86bc4397a6 100644 --- a/v1/plugins/discovery/discovery_test.go +++ b/v1/plugins/discovery/discovery_test.go @@ -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 { diff --git a/v1/plugins/logs/mask.go b/v1/plugins/logs/mask.go index ec28c0eb66..98a55329e4 100644 --- a/v1/plugins/logs/mask.go +++ b/v1/plugins/logs/mask.go @@ -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 diff --git a/v1/plugins/logs/plugin.go b/v1/plugins/logs/plugin.go index 5e7a73125e..1e64ce4f7d 100644 --- a/v1/plugins/logs/plugin.go +++ b/v1/plugins/logs/plugin.go @@ -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) diff --git a/v1/plugins/plugins.go b/v1/plugins/plugins.go index 8040eb3e8c..430b15efdb 100644 --- a/v1/plugins/plugins.go +++ b/v1/plugins/plugins.go @@ -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() }() diff --git a/v1/plugins/rest/aws_test.go b/v1/plugins/rest/aws_test.go index 64194ec667..79ff9bdf41 100644 --- a/v1/plugins/rest/aws_test.go +++ b/v1/plugins/rest/aws_test.go @@ -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" diff --git a/v1/plugins/status/plugin.go b/v1/plugins/status/plugin.go index ecfc3abff8..3fc9f46f93 100644 --- a/v1/plugins/status/plugin.go +++ b/v1/plugins/status/plugin.go @@ -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) diff --git a/v1/plugins/status/plugin_test.go b/v1/plugins/status/plugin_test.go index 3c9582b349..5570d2cb54 100644 --- a/v1/plugins/status/plugin_test.go +++ b/v1/plugins/status/plugin_test.go @@ -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{}, diff --git a/v1/rego/rego.go b/v1/rego/rego.go index 46d2022769..ed51ed4e3e 100644 --- a/v1/rego/rego.go +++ b/v1/rego/rego.go @@ -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 { diff --git a/v1/rego/rego_test.go b/v1/rego/rego_test.go index 01c5096b69..aaad2299a3 100644 --- a/v1/rego/rego_test.go +++ b/v1/rego/rego_test.go @@ -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}`)) diff --git a/v1/repl/repl.go b/v1/repl/repl.go index c6d6fb0cb9..d2c9f8dbf7 100644 --- a/v1/repl/repl.go +++ b/v1/repl/repl.go @@ -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)) } } diff --git a/v1/runtime/runtime_test.go b/v1/runtime/runtime_test.go index 684ddb6099..78c82a7ddb 100644 --- a/v1/runtime/runtime_test.go +++ b/v1/runtime/runtime_test.go @@ -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) { diff --git a/v1/sdk/test/test.go b/v1/sdk/test/test.go index 0925513621..1db9dfac8c 100644 --- a/v1/sdk/test/test.go +++ b/v1/sdk/test/test.go @@ -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) diff --git a/v1/server/server.go b/v1/server/server.go index 021b2ad716..cc141454f4 100644 --- a/v1/server/server.go +++ b/v1/server/server.go @@ -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 { diff --git a/v1/server/server_test.go b/v1/server/server_test.go index 8751a9804d..657f79a382 100644 --- a/v1/server/server_test.go +++ b/v1/server/server_test.go @@ -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") diff --git a/v1/storage/disk/disk.go b/v1/storage/disk/disk.go index 99e0fd155c..46152ca27d 100644 --- a/v1/storage/disk/disk.go +++ b/v1/storage/disk/disk.go @@ -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, "") } diff --git a/v1/storage/disk/paths.go b/v1/storage/disk/paths.go index 909bdf17cc..799a676c93 100644 --- a/v1/storage/disk/paths.go +++ b/v1/storage/disk/paths.go @@ -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 { diff --git a/v1/storage/disk/txn.go b/v1/storage/disk/txn.go index 2df10dc891..d3e76bad86 100644 --- a/v1/storage/disk/txn.go +++ b/v1/storage/disk/txn.go @@ -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") } diff --git a/v1/test/e2e/http/http_test.go b/v1/test/e2e/http/http_test.go index 8014940364..952cf2f0dc 100644 --- a/v1/test/e2e/http/http_test.go +++ b/v1/test/e2e/http/http_test.go @@ -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) } diff --git a/v1/tester/runner.go b/v1/tester/runner.go index 696c7eba21..d13f45b1e6 100644 --- a/v1/tester/runner.go +++ b/v1/tester/runner.go @@ -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 } diff --git a/v1/topdown/bindings.go b/v1/topdown/bindings.go index 06d5b09748..0012e14d0c 100644 --- a/v1/topdown/bindings.go +++ b/v1/topdown/bindings.go @@ -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 diff --git a/v1/topdown/cidr.go b/v1/topdown/cidr.go index 00c034656b..c404d51006 100644 --- a/v1/topdown/cidr.go +++ b/v1/topdown/cidr.go @@ -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 diff --git a/v1/topdown/http.go b/v1/topdown/http.go index 98720163d1..b388c25e05 100644 --- a/v1/topdown/http.go +++ b/v1/topdown/http.go @@ -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) diff --git a/v1/topdown/http_test.go b/v1/topdown/http_test.go index 26882ea6b4..de96dff211 100644 --- a/v1/topdown/http_test.go +++ b/v1/topdown/http_test.go @@ -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) } diff --git a/v1/topdown/save.go b/v1/topdown/save.go index 4574469231..47bf7521b4 100644 --- a/v1/topdown/save.go +++ b/v1/topdown/save.go @@ -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 { diff --git a/v1/topdown/strings.go b/v1/topdown/strings.go index 3b1a412c39..4908ff88f9 100644 --- a/v1/topdown/strings.go +++ b/v1/topdown/strings.go @@ -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]) } diff --git a/v1/topdown/topdown_test.go b/v1/topdown/topdown_test.go index 816c8a488f..240cfbb8df 100644 --- a/v1/topdown/topdown_test.go +++ b/v1/topdown/topdown_test.go @@ -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") } } } diff --git a/v1/topdown/trace.go b/v1/topdown/trace.go index 0c8dc0fb63..4133935fb9 100644 --- a/v1/topdown/trace.go +++ b/v1/topdown/trace.go @@ -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(" ") diff --git a/v1/types/types.go b/v1/types/types.go index 3d5b7b6864..f8d7db1ef0 100644 --- a/v1/types/types.go +++ b/v1/types/types.go @@ -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 diff --git a/v1/util/compare.go b/v1/util/compare.go index cffb683028..df78f64755 100644 --- a/v1/util/compare.go +++ b/v1/util/compare.go @@ -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