Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ linters:
enable:
- copyloopvar
- errcheck
- forbidigo
- gocritic
- govet
- ineffassign
Expand All @@ -26,6 +27,10 @@ linters:
exclude-functions:
- github.com/open-policy-agent/opa/v1/util.WriteAppender
- github.com/open-policy-agent/opa/v1/util.WriteInt
forbidigo:
forbid:
- pattern: '^sort\.[A-Z][a-zA-Z]+$'
message: "Prefer the more performant sort/search functions in the slices package"
gocritic:
enabled-checks:
# NOTE that these are rules enabled in addition to the default set
Expand Down
5 changes: 2 additions & 3 deletions cmd/capabilities_jsonv2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"bytes"
"path"
"slices"
"sort"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -189,8 +188,8 @@ func TestCapabilitiesCurrent(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
// These are sorted in the output
sort.Strings(tc.expFutureKeywords)
sort.Strings(tc.expFeatures)
slices.Sort(tc.expFutureKeywords)
slices.Sort(tc.expFeatures)

params := capabilitiesParams{
showCurrent: true,
Expand Down
5 changes: 2 additions & 3 deletions cmd/capabilities_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"bytes"
"path"
"slices"
"sort"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -189,8 +188,8 @@ func TestCapabilitiesCurrent(t *testing.T) {
for _, tc := range tests {
t.Run(tc.note, func(t *testing.T) {
// These are sorted in the output
sort.Strings(tc.expFutureKeywords)
sort.Strings(tc.expFeatures)
slices.Sort(tc.expFutureKeywords)
slices.Sort(tc.expFeatures)

params := capabilitiesParams{
showCurrent: true,
Expand Down
4 changes: 1 addition & 3 deletions cmd/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"

Expand Down Expand Up @@ -198,8 +197,7 @@ func populateManifest(out io.Writer, m *bundle.Manifest) error {
lines = append(lines, []string{"Roots", truncateFileName(roots[0])})
}
} else {
sort.Strings(roots)
for _, root := range roots {
for _, root := range util.Sorted(roots) {
lines = append(lines, []string{"Roots", truncateFileName(root)})
}
}
Expand Down
10 changes: 5 additions & 5 deletions cmd/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"net/http"
"net/http/httptest"
"runtime"
"sort"
"slices"
"strings"
"testing"

Expand Down Expand Up @@ -102,16 +102,16 @@ func expectOutputKeys(t *testing.T, stdout string, expectedKeys []string) {
gotKeys := make([]string, 0, len(lines))

for _, line := range lines {
gotKeys = append(gotKeys, strings.Split(line, ":")[0])
key, _, _ := strings.Cut(line, ":")
gotKeys = append(gotKeys, key)
}

sort.Strings(expectedKeys)
sort.Strings(gotKeys)

slices.Sort(expectedKeys)
if len(expectedKeys) != len(gotKeys) {
t.Fatalf("expected %v but got %v", expectedKeys, gotKeys)
}

slices.Sort(gotKeys)
for i, got := range gotKeys {
if expectedKeys[i] != got {
t.Fatalf("expected %v but got %v", expectedKeys, gotKeys)
Expand Down
5 changes: 2 additions & 3 deletions e2e/proto/protoschemacheck/protoschemacheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import (
"maps"
"reflect"
"slices"
"sort"
"strings"
"testing"
"time"

"github.com/bufbuild/protocompile"
"github.com/open-policy-agent/opa/v1/util"
"google.golang.org/protobuf/reflect/protoreflect"
)

Expand Down Expand Up @@ -476,8 +476,7 @@ func checkOneof(t *testing.T, declared map[string]protoreflect.MessageDescriptor
orphanCases = append(orphanCases, caseName)
}
}
sort.Strings(orphanCases)
for _, caseName := range orphanCases {
for _, caseName := range util.Sorted(orphanCases) {
f := caseFields[caseName]
t.Errorf("%s.%s: proto case %q (number %d) has no corresponding discriminator in DiscriminatorToCase; either remove it (and `reserved %d` the number) or extend the spec", o.MessageName, o.OneofName, caseName, f.Number(), f.Number())
}
Expand Down
17 changes: 3 additions & 14 deletions internal/cmd/genplanschema/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import (
"log"
"os"
"reflect"
"sort"

"github.com/open-policy-agent/opa/internal/genjsonschema"
"github.com/open-policy-agent/opa/v1/ir"
"github.com/open-policy-agent/opa/v1/util"
)

func main() {
Expand Down Expand Up @@ -132,7 +132,7 @@ func addValUnion(b *genjsonschema.Builder) (string, error) {
return b.DefRef(name), nil
}
vals := ir.ValKinds()
kinds := sortedKeys(vals)
kinds := util.KeysSorted(vals)
branches := make([]any, 0, len(kinds))
for _, kind := range kinds {
valueSchema, err := b.ReflectType(reflect.TypeOf(vals[kind]))
Expand Down Expand Up @@ -183,7 +183,7 @@ func addStmtUnion(b *genjsonschema.Builder) (string, error) {
}

stmts := ir.StmtKinds()
kinds := sortedKeys(stmts)
kinds := util.KeysSorted(stmts)
branches := make([]any, 0, len(kinds))
for _, kind := range kinds {
bodyRef, err := b.AddStruct(reflect.TypeOf(stmts[kind]))
Expand Down Expand Up @@ -227,14 +227,3 @@ func makeNumberRefStmtSchema() genjsonschema.OrderedMap {
"additionalProperties", false,
)
}

// sortedKeys returns the keys of m in lexicographic order so the polymorphic
// Stmt/Val unions render their branches in a byte-stable order.
func sortedKeys[V any](m map[string]V) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
7 changes: 3 additions & 4 deletions internal/genjsonschema/genjsonschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
"fmt"
"reflect"
"slices"
"sort"
"strings"
)

Expand Down Expand Up @@ -71,7 +70,7 @@ func (b *Builder) DefsOrdered() OrderedMap {
for n := range b.defs {
names = append(names, n)
}
sort.Strings(names)
slices.Sort(names)
out := make(OrderedMap, 0, len(names))
for _, n := range names {
out = append(out, Entry{n, b.defs[n]})
Expand Down Expand Up @@ -159,7 +158,7 @@ func (b *Builder) reflectStructBody(t reflect.Type) (OrderedMap, error) {
return nil, err
}

sort.Strings(required)
slices.Sort(required)

out := OrderedMap{
{"type", "object"},
Expand Down Expand Up @@ -221,7 +220,7 @@ func (b *Builder) collectFields(t reflect.Type, properties *OrderedMap, required
})
}

sort.Slice(fields, func(i, j int) bool { return fields[i].name < fields[j].name })
slices.SortFunc(fields, func(a, b pendingField) int { return strings.Compare(a.name, b.name) })
for _, f := range fields {
*properties = append(*properties, Entry{f.name, f.schema})
if f.required {
Expand Down
2 changes: 1 addition & 1 deletion internal/lcss/qsufsort.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func qsufsort(data []byte) []int {
}
pk := inv[s] + 1 // pk-1 is last position of unsorted group
sufSortable.sa = sa[pi:pk]
sort.Sort(sufSortable)
sort.Sort(sufSortable) //nolint:forbidigo
sufSortable.updateGroups(pi)
pi = pk // next group
}
Expand Down
19 changes: 10 additions & 9 deletions internal/planner/planner.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
package planner

import (
"cmp"
"errors"
"fmt"
"io"
"sort"
"slices"
"strings"

"github.com/open-policy-agent/opa/internal/debug"
"github.com/open-policy-agent/opa/v1/ast"
Expand Down Expand Up @@ -164,12 +166,12 @@ func (p *Planner) planRules(rules []*ast.Rule) (string, error) {
// We sort rules, first by ref length, and then using the
// Ref.Compare method to break ties. This yields a stable
// sorting order for the slice of rules to be planned.
sort.Slice(rules, func(i, j int) bool {
li, lj := len(rules[i].Ref()), len(rules[j].Ref())
if li != lj {
return li > lj
slices.SortFunc(rules, func(a, b *ast.Rule) int {
aRef, bRef := a.Ref(), b.Ref()
if c := cmp.Compare(len(aRef), len(bRef)); c != 0 {
return -c
}
return rules[i].Ref().Compare(rules[j].Ref()) < 0
return aRef.Compare(bRef)
})

// We know the rules that are closer to the root (shorter static path) are ordered first.
Expand Down Expand Up @@ -2441,15 +2443,14 @@ func (p *Planner) planTermSliceRec(terms []*ast.Term, locals []ir.Operand, index
}

func (p *Planner) planExterns() error {

p.policy.Static.BuiltinFuncs = make([]*ir.BuiltinFunc, 0, len(p.externs))

for name, decl := range p.externs {
p.policy.Static.BuiltinFuncs = append(p.policy.Static.BuiltinFuncs, &ir.BuiltinFunc{Name: name, Decl: decl.Decl})
}

sort.Slice(p.policy.Static.BuiltinFuncs, func(i, j int) bool {
return p.policy.Static.BuiltinFuncs[i].Name < p.policy.Static.BuiltinFuncs[j].Name
slices.SortFunc(p.policy.Static.BuiltinFuncs, func(a, b *ir.BuiltinFunc) int {
return strings.Compare(a.Name, b.Name)
})

return nil
Expand Down
6 changes: 1 addition & 5 deletions internal/planner/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package planner

import (
"fmt"
"sort"

"github.com/open-policy-agent/opa/v1/ast"
"github.com/open-policy-agent/opa/v1/util"
Expand Down Expand Up @@ -242,10 +241,7 @@ func (t *ruletrie) Children() []ast.Value {
sorted = append(sorted, key)
}
}
sort.Slice(sorted, func(i, j int) bool {
return sorted[i].Compare(sorted[j]) < 0
})
return sorted
return util.SortedFunc(sorted, ast.Value.Compare)
}

func (t *ruletrie) Get(k ast.Value) *ruletrie {
Expand Down
35 changes: 10 additions & 25 deletions internal/presentation/presentation.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"fmt"
"io"
"slices"
"sort"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -110,13 +109,8 @@ func (o DepAnalysisOutput) Pretty(w io.Writer) error {
}

func (o DepAnalysisOutput) sort() {
sort.Slice(o.Base, func(i, j int) bool {
return o.Base[i].Compare(o.Base[j]) < 0
})

sort.Slice(o.Virtual, func(i, j int) bool {
return o.Virtual[i].Compare(o.Virtual[j]) < 0
})
slices.SortFunc(o.Base, ast.RefCompare)
slices.SortFunc(o.Virtual, ast.RefCompare)
}

// Output contains the result of evaluation to be presented.
Expand Down Expand Up @@ -752,8 +746,8 @@ func populateTableAggregatedMetrics(ms map[string]any, table *tablewriter.Table,
}

func sortMetricRows(data [][]string) {
sort.Slice(data, func(i, j int) bool {
return data[i][0] < data[j][0]
slices.SortFunc(data, func(a, b []string) int {
return strings.Compare(a[0], b[0])
})
}

Expand All @@ -763,16 +757,6 @@ type resultKey struct {
exprText string
}

func resultKeyLess(a, b resultKey) bool {
if a.varName != "" {
if b.varName == "" {
return true
}
return a.varName < b.varName
}
return a.exprIndex < b.exprIndex
}

func (rk resultKey) string() string {
if rk.varName != "" {
return rk.varName
Expand All @@ -791,9 +775,7 @@ func generateResultKeys(rs rego.ResultSet) []resultKey {
keys := []resultKey{}
if len(rs) != 0 {
for k := range rs[0].Bindings {
keys = append(keys, resultKey{
varName: k,
})
keys = append(keys, resultKey{varName: k})
}

for i, expr := range rs[0].Expressions {
Expand All @@ -805,8 +787,11 @@ func generateResultKeys(rs rego.ResultSet) []resultKey {
}
}

sort.Slice(keys, func(i, j int) bool {
return resultKeyLess(keys[i], keys[j])
slices.SortFunc(keys, func(a, b resultKey) int {
if c := strings.Compare(a.varName, b.varName); c != 0 {
return c
}
return a.exprIndex - b.exprIndex
})
}
return keys
Expand Down
6 changes: 3 additions & 3 deletions internal/providers/aws/signing_v4a.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
"math/big"
"net/http"
"net/url"
"sort"
"slices"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -211,7 +211,7 @@ func (s *httpSigner) Build() (signedRequest, error) {

// Sort Each Query Key's Values
for key := range query {
sort.Strings(query[key])
slices.Sort(query[key])
}

v4Internal.SanitizeHostForHeader(req)
Expand Down Expand Up @@ -319,7 +319,7 @@ func (*httpSigner) buildCanonicalHeaders(host string, rule v4Internal.Rule, head
headers = append(headers, lowerCaseKey)
signed[lowerCaseKey] = v
}
sort.Strings(headers)
slices.Sort(headers)

signedHeaders = strings.Join(headers, ";")

Expand Down
Loading