refactor: replace sort.Strings with slices.Sort (#23457)

The slices package provides type-safe generic replacements for the
old typed sort convenience functions. The codebase already uses
slices.Sort in 43 call sites; this finishes the migration for the
remaining 29.

- sort.Strings(x)          -> slices.Sort(x)
- sort.Float64s(x)         -> slices.Sort(x)
- sort.StringsAreSorted(x) -> slices.IsSorted(x)
This commit is contained in:
Mathias Fredriksson
2026-03-23 23:19:23 +02:00
committed by GitHub
parent 9e4c283370
commit 147df5c971
22 changed files with 45 additions and 47 deletions
+1 -2
View File
@@ -16,7 +16,6 @@ import (
"os/user"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"sync"
@@ -1877,7 +1876,7 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
}()
}
wg.Wait()
sort.Float64s(durations)
slices.Sort(durations)
durationsLength := len(durations)
switch {
case durationsLength == 0:
@@ -433,7 +433,7 @@ func convertDockerInspect(raw []byte) ([]codersdk.WorkspaceAgentContainer, []str
}
portKeys := maps.Keys(in.NetworkSettings.Ports)
// Sort the ports for deterministic output.
sort.Strings(portKeys)
slices.Sort(portKeys)
// If we see the same port bound to both ipv4 and ipv6 loopback or unspecified
// interfaces to the same container port, there is no point in adding it multiple times.
loopbackHostPortContainerPorts := make(map[int]uint16, 0)
+2 -2
View File
@@ -1,7 +1,7 @@
package agentgit
import (
"sort"
"slices"
"sync"
"github.com/google/uuid"
@@ -99,7 +99,7 @@ func (ps *PathStore) GetPaths(chatID uuid.UUID) []string {
for p := range m {
out = append(out, p)
}
sort.Strings(out)
slices.Sort(out)
return out
}
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"context"
"os"
"path/filepath"
"sort"
"slices"
"testing"
"github.com/stretchr/testify/require"
@@ -228,6 +228,6 @@ func resultPaths(results []filefinder.Result) []string {
for i, r := range results {
paths[i] = r.Path
}
sort.Strings(paths)
slices.Sort(paths)
return paths
}
+3 -3
View File
@@ -5,7 +5,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"sort"
"slices"
"strings"
"testing"
@@ -376,8 +376,8 @@ func Test_sshConfigOptions_addOption(t *testing.T) {
return
}
require.NoError(t, err)
sort.Strings(tt.Expect)
sort.Strings(o.sshOptions)
slices.Sort(tt.Expect)
slices.Sort(o.sshOptions)
require.Equal(t, tt.Expect, o.sshOptions)
})
}
+2 -2
View File
@@ -24,7 +24,7 @@ import (
"os/user"
"path/filepath"
"regexp"
"sort"
"slices"
"strconv"
"strings"
"sync"
@@ -2825,7 +2825,7 @@ func ReadExternalAuthProvidersFromEnv(environ []string) ([]codersdk.ExternalAuth
// parsing of `GITAUTH` environment variables.
func parseExternalAuthProvidersFromEnv(prefix string, environ []string) ([]codersdk.ExternalAuthConfig, error) {
// The index numbers must be in-order.
sort.Strings(environ)
slices.Sort(environ)
var providers []codersdk.ExternalAuthConfig
for _, v := range serpent.ParseEnviron(environ, prefix) {
+3 -3
View File
@@ -7,7 +7,7 @@ import (
"io"
"os"
"path/filepath"
"sort"
"slices"
"golang.org/x/exp/maps"
"golang.org/x/xerrors"
@@ -31,7 +31,7 @@ func (*RootCmd) templateInit() *serpent.Command {
for _, ex := range exampleList {
templateIDs = append(templateIDs, ex.ID)
}
sort.Strings(templateIDs)
slices.Sort(templateIDs)
cmd := &serpent.Command{
Use: "init [directory]",
Short: "Get started with a templated template.",
@@ -50,7 +50,7 @@ func (*RootCmd) templateInit() *serpent.Command {
optsToID[name] = example.ID
}
opts := maps.Keys(optsToID)
sort.Strings(opts)
slices.Sort(opts)
_, _ = fmt.Fprintln(
inv.Stdout,
pretty.Sprint(
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"sort"
"slices"
"testing"
"github.com/stretchr/testify/require"
@@ -47,7 +47,7 @@ func TestTemplateList(t *testing.T) {
// expect that templates are listed alphabetically
templatesList := []string{firstTemplate.Name, secondTemplate.Name}
sort.Strings(templatesList)
slices.Sort(templatesList)
require.NoError(t, <-errC)
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"fmt"
"os"
"slices"
"sort"
"strings"
"time"
@@ -194,7 +193,7 @@ func joinScopes(scopes []codersdk.APIKeyScope) string {
return ""
}
vals := slice.ToStrings(scopes)
sort.Strings(vals)
slices.Sort(vals)
return strings.Join(vals, ", ")
}
@@ -206,7 +205,7 @@ func joinAllowList(entries []codersdk.APIAllowListTarget) string {
for i, entry := range entries {
vals[i] = entry.String()
}
sort.Strings(vals)
slices.Sort(vals)
return strings.Join(vals, ", ")
}
+2 -2
View File
@@ -6,7 +6,7 @@ import (
"errors"
"fmt"
"reflect"
"sort"
"slices"
"strings"
"testing"
@@ -97,7 +97,7 @@ func (s *MethodTestSuite) TearDownSuite() {
notCalled = append(notCalled, m)
}
}
sort.Strings(notCalled)
slices.Sort(notCalled)
for _, m := range notCalled {
t.Errorf("Method never called: %q", m)
}
+2 -2
View File
@@ -3,7 +3,7 @@ package dynamicparameters
import (
"fmt"
"net/http"
"sort"
"slices"
"github.com/hashicorp/hcl/v2"
@@ -94,7 +94,7 @@ func (e *DiagnosticError) Response() (int, codersdk.Response) {
for name := range e.KeyedDiagnostics {
sortedNames = append(sortedNames, name)
}
sort.Strings(sortedNames)
slices.Sort(sortedNames)
for _, name := range sortedNames {
diag := e.KeyedDiagnostics[name]
+2 -3
View File
@@ -18,7 +18,6 @@ import (
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"sync"
"testing"
@@ -549,8 +548,8 @@ func TestExpiredLeaseIsRequeued(t *testing.T) {
leasedIDs = append(leasedIDs, msg.ID.String())
}
sort.Strings(msgs)
sort.Strings(leasedIDs)
slices.Sort(msgs)
slices.Sort(leasedIDs)
require.EqualValues(t, msgs, leasedIDs)
// Wait out the lease period; all messages should be eligible to be re-acquired.
+2 -1
View File
@@ -1,6 +1,7 @@
package prometheusmetrics_test
import (
"slices"
"sort"
"testing"
@@ -134,7 +135,7 @@ func collectAndSortMetrics(t *testing.T, collector prometheus.Collector, count i
// Ensure always the same order of metrics
sort.Slice(metrics, func(i, j int) bool {
return sort.StringsAreSorted([]string{metrics[i].Label[0].GetValue(), metrics[j].Label[1].GetValue()})
return slices.IsSorted([]string{metrics[i].Label[0].GetValue(), metrics[j].Label[1].GetValue()})
})
return metrics
}
+1 -2
View File
@@ -3,7 +3,6 @@ package rbac
import (
"fmt"
"slices"
"sort"
"strings"
"github.com/google/uuid"
@@ -176,7 +175,7 @@ func CompositeScopeNames() []string {
for k := range compositePerms {
out = append(out, string(k))
}
sort.Strings(out)
slices.Sort(out)
return out
}
+2 -2
View File
@@ -1,7 +1,7 @@
package rbac
import (
"sort"
"slices"
"strings"
"testing"
@@ -16,7 +16,7 @@ func TestExternalScopeNames(t *testing.T) {
// Ensure sorted ascending
sorted := append([]string(nil), names...)
sort.Strings(sorted)
slices.Sort(sorted)
require.Equal(t, sorted, names)
// Ensure each entry expands to site-only
+3 -3
View File
@@ -7,7 +7,7 @@ import (
"fmt"
"net/http"
"net/mail"
"sort"
"slices"
"strconv"
"strings"
"sync"
@@ -1589,7 +1589,7 @@ func claimFields(claims map[string]interface{}) []string {
for field := range claims {
fields = append(fields, field)
}
sort.Strings(fields)
slices.Sort(fields)
return fields
}
@@ -1602,7 +1602,7 @@ func blankFields(claims map[string]interface{}) []string {
fields = append(fields, field)
}
}
sort.Strings(fields)
slices.Sort(fields)
return fields
}
+3 -3
View File
@@ -9,7 +9,7 @@ import (
"io"
"io/fs"
"path"
"sort"
"slices"
"strings"
"sync"
@@ -105,8 +105,8 @@ func parseAndVerifyExamples() (examples []codersdk.TemplateExample, err error) {
}
}
sort.Strings(wantEmbedFiles)
sort.Strings(gotEmbedFiles)
slices.Sort(wantEmbedFiles)
slices.Sort(gotEmbedFiles)
want := strings.Join(wantEmbedFiles, ", ")
got := strings.Join(gotEmbedFiles, ", ")
if want != got {
+2 -2
View File
@@ -5,7 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"sort"
"slices"
"strings"
"time"
@@ -107,7 +107,7 @@ func (h *TestHarness) Results() Results {
func (r *Results) PrintText(w io.Writer) {
var totalDuration time.Duration
keys := maps.Keys(r.Runs)
sort.Strings(keys)
slices.Sort(keys)
for _, key := range keys {
run := r.Runs[key]
totalDuration += time.Duration(run.Duration)
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"os"
"path"
"regexp"
"slices"
"sort"
"strings"
@@ -168,7 +169,7 @@ func writeDocs(sections [][]byte) error {
if mdFiles[j].title == "General" {
return false // ... < "General" - not sorted
}
return sort.StringsAreSorted([]string{mdFiles[i].title, mdFiles[j].title})
return slices.IsSorted([]string{mdFiles[i].title, mdFiles[j].title})
})
// Update manifest.json
+2 -2
View File
@@ -6,7 +6,7 @@ import (
"fmt"
"os"
"regexp"
"sort"
"slices"
"strings"
"golang.org/x/xerrors"
@@ -37,7 +37,7 @@ func main() {
missing = append(missing, k)
}
}
sort.Strings(missing)
slices.Sort(missing)
if len(missing) == 0 {
_, _ = fmt.Println("check-scopes: OK — all RBAC <resource>:<action> values exist in api_key_scope enum")
+2 -2
View File
@@ -3,7 +3,7 @@ package main
import (
"errors"
"os/exec"
"sort"
"slices"
"strconv"
"strings"
"time"
@@ -180,7 +180,7 @@ func ghBuildPRMetadataMap(commits []commitEntry) (*prMetadataMaps, error) {
var labels []string
if parts[3] != "" {
labels = strings.Split(parts[3], ",")
sort.Strings(labels)
slices.Sort(labels)
}
meta := prMetadata{
Labels: labels,
+2 -2
View File
@@ -10,7 +10,7 @@ import (
"os"
"os/exec"
"path/filepath"
"sort"
"slices"
"strings"
"testing"
@@ -34,7 +34,7 @@ func hashTemplateFilesAndTestName(t *testing.T, testName string, templateFiles m
for fileName := range templateFiles {
sortedFileNames = append(sortedFileNames, fileName)
}
sort.Strings(sortedFileNames)
slices.Sort(sortedFileNames)
// Inserting a delimiter between the file name and the file content
// ensures that a file named `ab` with content `cd`