1
0
mirror of https://github.com/moby/buildkit.git synced 2025-04-18 18:04:03 +03:00

Merge pull request #5863 from tonistiigi/sort-update

lint: update some sorting code to newer generics based libs
This commit is contained in:
Tõnis Tiigi 2025-04-09 09:38:30 -07:00 committed by GitHub
commit 37daea90eb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 129 additions and 148 deletions

View File

@ -3,7 +3,7 @@ package contenthash
import (
"archive/tar"
"io"
"sort"
"slices"
"strconv"
"strings"
)
@ -56,7 +56,7 @@ func v1TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) {
}
}
}
sort.Strings(xAttrKeys)
slices.Sort(xAttrKeys)
// Make the slice with enough capacity to hold the 11 basic headers
// we want from the v0 selector plus however many xattrs we have.

4
cache/filelist.go vendored
View File

@ -7,7 +7,7 @@ import (
"fmt"
"io"
"path"
"sort"
"slices"
cdcompression "github.com/containerd/containerd/v2/pkg/archive/compression"
"github.com/moby/buildkit/session"
@ -69,7 +69,7 @@ func (sr *immutableRef) FileList(ctx context.Context, s session.Group) ([]string
name := path.Clean(hdr.Name)
files = append(files, name)
}
sort.Strings(files)
slices.Sort(files)
dt, err = json.Marshal(files)
if err != nil {

37
cache/manager.go vendored
View File

@ -1,10 +1,11 @@
package cache
import (
"cmp"
"context"
"fmt"
"maps"
"sort"
"slices"
"strings"
"sync"
"time"
@ -1667,23 +1668,23 @@ type deleteRecord struct {
*cacheRecord
lastUsedAt *time.Time
usageCount int
lastUsedAtIndex int
usageCountIndex int
lastUsedAtIndex float64
usageCountIndex float64
released bool
}
func sortDeleteRecords(toDelete []*deleteRecord) {
sort.Slice(toDelete, func(i, j int) bool {
if toDelete[i].lastUsedAt == nil {
return true
slices.SortFunc(toDelete, func(a, b *deleteRecord) int {
if a.lastUsedAt == nil {
return -1
}
if toDelete[j].lastUsedAt == nil {
return false
if b.lastUsedAt == nil {
return 1
}
return toDelete[i].lastUsedAt.Before(*toDelete[j].lastUsedAt)
return a.lastUsedAt.Compare(*b.lastUsedAt)
})
maxLastUsedIndex := 0
maxLastUsedIndex := 1.0
var val time.Time
for _, v := range toDelete {
if v.lastUsedAt != nil && v.lastUsedAt.After(val) {
@ -1693,11 +1694,11 @@ func sortDeleteRecords(toDelete []*deleteRecord) {
v.lastUsedAtIndex = maxLastUsedIndex
}
sort.Slice(toDelete, func(i, j int) bool {
return toDelete[i].usageCount < toDelete[j].usageCount
slices.SortFunc(toDelete, func(a, b *deleteRecord) int {
return a.usageCount - b.usageCount
})
maxUsageCountIndex := 0
maxUsageCountIndex := 1.0
var count int
for _, v := range toDelete {
if v.usageCount != count {
@ -1707,11 +1708,11 @@ func sortDeleteRecords(toDelete []*deleteRecord) {
v.usageCountIndex = maxUsageCountIndex
}
sort.Slice(toDelete, func(i, j int) bool {
return float64(toDelete[i].lastUsedAtIndex)/float64(maxLastUsedIndex)+
float64(toDelete[i].usageCountIndex)/float64(maxUsageCountIndex) <
float64(toDelete[j].lastUsedAtIndex)/float64(maxLastUsedIndex)+
float64(toDelete[j].usageCountIndex)/float64(maxUsageCountIndex)
slices.SortFunc(toDelete, func(a, b *deleteRecord) int {
return cmp.Compare(
a.lastUsedAtIndex/maxLastUsedIndex+a.usageCountIndex/maxUsageCountIndex,
b.lastUsedAtIndex/maxLastUsedIndex+b.usageCountIndex/maxUsageCountIndex,
)
})
}

View File

@ -1,8 +1,10 @@
package cacheimport
import (
"cmp"
"context"
"fmt"
"slices"
"sort"
cerrdefs "github.com/containerd/errdefs"
@ -28,13 +30,8 @@ func sortConfig(cc *CacheConfig) {
unsortedLayers[i] = il
sortedLayers[i] = il
}
sort.Slice(sortedLayers, func(i, j int) bool {
li := sortedLayers[i].l
lj := sortedLayers[j].l
if li.Blob == lj.Blob {
return li.ParentIndex < lj.ParentIndex
}
return li.Blob < lj.Blob
slices.SortFunc(sortedLayers, func(a, b *indexedLayer) int {
return cmp.Or(cmp.Compare(a.l.Blob, b.l.Blob), cmp.Compare(a.l.ParentIndex, b.l.ParentIndex))
})
for i, l := range sortedLayers {
l.newIndex = i
@ -101,8 +98,8 @@ func sortConfig(cc *CacheConfig) {
for k := range inputs {
r.r.Inputs[j][k].LinkIndex = unsortedRecords[r.r.Inputs[j][k].LinkIndex].newIndex
}
sort.Slice(inputs, func(i, j int) bool {
return inputs[i].LinkIndex < inputs[j].LinkIndex
slices.SortFunc(inputs, func(a, b CacheInput) int {
return cmp.Compare(a.LinkIndex, b.LinkIndex)
})
}
records[i] = r.r

View File

@ -1,8 +1,9 @@
package client
import (
"cmp"
"context"
"sort"
"slices"
"time"
controlapi "github.com/moby/buildkit/api/services/control"
@ -60,13 +61,9 @@ func (c *Client) DiskUsage(ctx context.Context, opts ...DiskUsageOption) ([]*Usa
})
}
sort.Slice(du, func(i, j int) bool {
if du[i].Size == du[j].Size {
return du[i].ID > du[j].ID
}
return du[i].Size > du[j].Size
slices.SortFunc(du, func(a, b *UsageInfo) int {
return cmp.Or(cmp.Compare(a.Size, b.Size), cmp.Compare(a.ID, b.ID))
})
return du, nil
}

View File

@ -5,7 +5,7 @@ import (
_ "crypto/sha256" // for opencontainers/go-digest
"fmt"
"net"
"sort"
"slices"
"strings"
"github.com/moby/buildkit/solver/pb"
@ -143,8 +143,8 @@ func (e *ExecOp) Marshal(ctx context.Context, c *Constraints) (digest.Digest, []
return "", nil, nil, nil, err
}
// make sure mounts are sorted
sort.Slice(e.mounts, func(i, j int) bool {
return e.mounts[i].target < e.mounts[j].target
slices.SortFunc(e.mounts, func(a, b *mount) int {
return strings.Compare(a.target, b.target)
})
env, err := getEnv(e.base)(ctx, c)
@ -477,10 +477,9 @@ func (e *ExecOp) Inputs() (inputs []Output) {
// make sure mounts are sorted
// the same sort occurs in (*ExecOp).Marshal, and this
// sort must be the same
sort.Slice(e.mounts, func(i int, j int) bool {
return e.mounts[i].target < e.mounts[j].target
slices.SortFunc(e.mounts, func(a, b *mount) int {
return strings.Compare(a.target, b.target)
})
seen := map[Output]struct{}{}
for _, m := range e.mounts {
if m.source != nil {
@ -497,8 +496,8 @@ func (e *ExecOp) Inputs() (inputs []Output) {
func (e *ExecOp) getMountIndexFn(m *mount) func() (pb.OutputIndex, error) {
return func() (pb.OutputIndex, error) {
// make sure mounts are sorted
sort.Slice(e.mounts, func(i, j int) bool {
return e.mounts[i].target < e.mounts[j].target
slices.SortFunc(e.mounts, func(a, b *mount) int {
return strings.Compare(a.target, b.target)
})
i := 0

View File

@ -3,8 +3,9 @@ package debug
import (
"context"
"fmt"
"maps"
"os"
"sort"
"slices"
"strings"
"text/tabwriter"
@ -135,15 +136,8 @@ func printWorkersTable(tw *tabwriter.Writer, winfo []*client.WorkerInfo) {
tw.Flush()
}
func sortedKeys(m map[string]string) []string {
s := make([]string, len(m))
i := 0
for k := range m {
s[i] = k
i++
}
sort.Strings(s)
return s
func sortedKeys[T any](m map[string]T) []string {
return slices.Sorted(maps.Keys(m))
}
func commandContext(c *cli.Context) context.Context {

View File

@ -10,7 +10,7 @@ import (
"os/user"
"path/filepath"
"runtime"
"sort"
"slices"
"strconv"
"strings"
@ -107,10 +107,9 @@ var (
func registerWorkerInitializer(wi workerInitializer, flags ...cli.Flag) {
workerInitializers = append(workerInitializers, wi)
sort.Slice(workerInitializers,
func(i, j int) bool {
return workerInitializers[i].priority < workerInitializers[j].priority
})
slices.SortFunc(workerInitializers, func(a, b workerInitializer) int {
return a.priority - b.priority
})
appFlags = append(appFlags, flags...)
}

View File

@ -3,7 +3,7 @@ package verifier
import (
"context"
"fmt"
"sort"
"slices"
"strings"
"github.com/containerd/platforms"
@ -115,10 +115,10 @@ func CheckInvalidPlatforms[T comparable](ctx context.Context, res *result.Result
}
func platformsString(ps []exptypes.Platform) string {
var ss []string
for _, p := range ps {
ss = append(ss, platforms.FormatAll(platforms.Normalize(p.Platform)))
ss := make([]string, len(ps))
for i, p := range ps {
ss[i] = platforms.FormatAll(platforms.Normalize(p.Platform))
}
sort.Strings(ss)
slices.Sort(ss)
return strings.Join(ss, ",")
}

View File

@ -14,7 +14,6 @@ import (
"regexp"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"sync"
@ -2383,8 +2382,8 @@ func mergeLocations(locations ...[]parser.Range) []parser.Range {
return allRanges
}
sort.Slice(allRanges, func(i, j int) bool {
return allRanges[i].Start.Line < allRanges[j].Start.Line
slices.SortFunc(allRanges, func(a, b parser.Range) int {
return a.Start.Line - b.Start.Line
})
location := []parser.Range{}

View File

@ -1,12 +1,14 @@
package dockerfile
import (
"cmp"
"context"
"encoding/json"
"fmt"
"maps"
"os"
"regexp"
"slices"
"sort"
"testing"
"time"
@ -1483,14 +1485,10 @@ func checkUnmarshal(t *testing.T, sb integration.Sandbox, lintTest *lintTestPara
require.Equal(t, len(warnings), len(lintResults.Warnings))
sort.Slice(lintResults.Warnings, func(i, j int) bool {
// sort by line number in ascending order
firstRange := lintResults.Warnings[i].Location.Ranges[0]
secondRange := lintResults.Warnings[j].Location.Ranges[0]
if firstRange.Start.Line == secondRange.Start.Line {
return lintResults.Warnings[i].Detail < lintResults.Warnings[j].Detail
}
return firstRange.Start.Line < secondRange.Start.Line
slices.SortFunc(lintResults.Warnings, func(a, b lint.Warning) int {
firstRange := a.Location.Ranges[0]
secondRange := b.Location.Ranges[0]
return cmp.Or(cmp.Compare(firstRange.Start.Line, secondRange.Start.Line), cmp.Compare(a.Detail, b.Detail))
})
// Compare expectedLintWarning with actual lint results
for i, w := range lintResults.Warnings {

View File

@ -17,7 +17,7 @@ import (
"path/filepath"
"regexp"
"runtime"
"sort"
"slices"
"strings"
"testing"
"time"
@ -3524,8 +3524,7 @@ EXPOSE 5000
for p := range ociimg.Config.ExposedPorts {
ports = append(ports, p)
}
sort.Strings(ports)
slices.Sort(ports)
require.Equal(t, "3000/tcp", ports[0])
require.Equal(t, "4000/udp", ports[1])

View File

@ -1,7 +1,7 @@
package instructions
import (
"sort"
"slices"
"strings"
"testing"
)
@ -206,7 +206,7 @@ func TestBuilderFlags(t *testing.T) {
t.Fatalf("Test %q was supposed to work: %s", bf.Args, err)
}
used := bf.Used()
sort.Strings(used)
slices.Sort(used)
expected = "bool2, bool3, bool4, bool5, str2, str3, str4"
actual := strings.Join(used, ", ")
if actual != expected {

View File

@ -8,7 +8,6 @@ import (
"fmt"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"time"
@ -688,7 +687,7 @@ func parseExpose(req parseRequest) (*ExposeCommand, error) {
return nil, err
}
sort.Strings(portsTab)
slices.Sort(portsTab)
return &ExposeCommand{
Ports: portsTab,
withNameAndCode: newWithNameAndCode(req),

View File

@ -1,11 +1,12 @@
package container
import (
"cmp"
"context"
"fmt"
"path/filepath"
"runtime"
"sort"
"slices"
"strings"
"sync"
"syscall"
@ -276,8 +277,8 @@ func PrepareMounts(ctx context.Context, mm *mounts.MountManager, cm cache.Manage
}
// sort mounts so parents are mounted first
sort.Slice(p.Mounts, func(i, j int) bool {
return p.Mounts[i].Dest < p.Mounts[j].Dest
slices.SortFunc(p.Mounts, func(a, b executor.Mount) int {
return cmp.Compare(a.Dest, b.Dest)
})
return p, nil

View File

@ -8,7 +8,6 @@ import (
"io"
"os"
"slices"
"sort"
"strconv"
"strings"
"sync"
@ -336,8 +335,8 @@ func (h *HistoryQueue) gc() error {
}
// sort array by newest records first
sort.Slice(records, func(i, j int) bool {
return records[i].CompletedAt.AsTime().After(records[j].CompletedAt.AsTime())
slices.SortFunc(records, func(a, b *controlapi.BuildHistoryRecord) int {
return -a.CompletedAt.AsTime().Compare(b.CompletedAt.AsTime())
})
h.mu.Lock()

View File

@ -2,13 +2,13 @@ package ops
import (
"bytes"
"cmp"
"context"
"encoding/json"
"fmt"
"path"
"runtime"
"slices"
"sort"
"sync"
"github.com/moby/buildkit/cache"
@ -151,9 +151,8 @@ func (f *fileOp) CacheMap(ctx context.Context, g session.Group, index int) (*sol
for _, k := range m {
dgsts = append(dgsts, []byte(k.Path))
}
sort.Slice(dgsts, func(i, j int) bool {
return bytes.Compare(dgsts[i], dgsts[j]) > 0
})
slices.SortFunc(dgsts, bytes.Compare)
slices.Reverse(dgsts) // historical reasons
cm.Deps[idx].Selector = digest.FromBytes(bytes.Join(dgsts, []byte{0}))
cm.Deps[idx].ComputeDigestFunc = opsutils.NewContentHashFunc(dedupeSelectors(m))
@ -261,10 +260,9 @@ func dedupeSelectors(m []opsutils.Selector) []opsutils.Selector {
}
}
sort.Slice(selectors, func(i, j int) bool {
return selectors[i].Path < selectors[j].Path
slices.SortFunc(selectors, func(i, j opsutils.Selector) int {
return cmp.Compare(i.Path, j.Path)
})
return selectors
}

View File

@ -1,7 +1,8 @@
package provenance
import (
"sort"
"cmp"
"slices"
distreference "github.com/distribution/reference"
resourcestypes "github.com/moby/buildkit/executor/resources/types"
@ -56,23 +57,23 @@ func (c *Capture) Merge(c2 *Capture) error {
}
func (c *Capture) Sort() {
sort.Slice(c.Sources.Images, func(i, j int) bool {
return c.Sources.Images[i].Ref < c.Sources.Images[j].Ref
slices.SortFunc(c.Sources.Images, func(a, b provenancetypes.ImageSource) int {
return cmp.Compare(a.Ref, b.Ref)
})
sort.Slice(c.Sources.Local, func(i, j int) bool {
return c.Sources.Local[i].Name < c.Sources.Local[j].Name
slices.SortFunc(c.Sources.Local, func(a, b provenancetypes.LocalSource) int {
return cmp.Compare(a.Name, b.Name)
})
sort.Slice(c.Sources.Git, func(i, j int) bool {
return c.Sources.Git[i].URL < c.Sources.Git[j].URL
slices.SortFunc(c.Sources.Git, func(a, b provenancetypes.GitSource) int {
return cmp.Compare(a.URL, b.URL)
})
sort.Slice(c.Sources.HTTP, func(i, j int) bool {
return c.Sources.HTTP[i].URL < c.Sources.HTTP[j].URL
slices.SortFunc(c.Sources.HTTP, func(a, b provenancetypes.HTTPSource) int {
return cmp.Compare(a.URL, b.URL)
})
sort.Slice(c.Secrets, func(i, j int) bool {
return c.Secrets[i].ID < c.Secrets[j].ID
slices.SortFunc(c.Secrets, func(a, b provenancetypes.Secret) int {
return cmp.Compare(a.ID, b.ID)
})
sort.Slice(c.SSH, func(i, j int) bool {
return c.SSH[i].ID < c.SSH[j].ID
slices.SortFunc(c.SSH, func(a, b provenancetypes.SSH) int {
return cmp.Compare(a.ID, b.ID)
})
}

View File

@ -3,7 +3,7 @@ package solver
import (
"context"
"io"
"sort"
"slices"
"time"
"github.com/moby/buildkit/util/bklog"
@ -77,20 +77,20 @@ func (j *Job) Status(ctx context.Context, ch chan *client.SolveStatus) error {
ss.Warnings = append(ss.Warnings, &v)
}
}
sort.Slice(ss.Vertexes, func(i, j int) bool {
if ss.Vertexes[i].Started == nil {
return true
slices.SortFunc(ss.Vertexes, func(a, b *client.Vertex) int {
if a.Started == nil {
return -1
}
if ss.Vertexes[j].Started == nil {
return false
if b.Started == nil {
return 1
}
return ss.Vertexes[i].Started.Before(*ss.Vertexes[j].Started)
return a.Started.Compare(*b.Started)
})
sort.Slice(ss.Statuses, func(i, j int) bool {
return ss.Statuses[i].Timestamp.Before(ss.Statuses[j].Timestamp)
slices.SortFunc(ss.Statuses, func(a, b *client.VertexStatus) int {
return a.Timestamp.Compare(b.Timestamp)
})
sort.Slice(ss.Logs, func(i, j int) bool {
return ss.Logs[i].Timestamp.Before(ss.Logs[j].Timestamp)
slices.SortFunc(ss.Logs, func(a, b *client.VertexLog) int {
return a.Timestamp.Compare(b.Timestamp)
})
select {

View File

@ -1,8 +1,9 @@
package apicaps
import (
"cmp"
"fmt"
"sort"
"slices"
"strings"
pb "github.com/moby/buildkit/util/apicaps/pb"
@ -76,8 +77,8 @@ func (l *CapList) All() []*pb.APICap {
DisabledAlternative: c.DisabledAlternative,
})
}
sort.Slice(out, func(i, j int) bool {
return out[i].ID < out[j].ID
slices.SortFunc(out, func(a, b *pb.APICap) int {
return cmp.Compare(a.ID, b.ID)
})
return out
}

View File

@ -1,7 +1,7 @@
package archutil
import (
"sort"
"slices"
"strings"
"sync"
"time"
@ -192,7 +192,7 @@ func amd64vector(v string) (out []string) {
case "v2":
out = append(out, "v2")
}
sort.Strings(out)
slices.Sort(out)
return
}

View File

@ -5,7 +5,6 @@ import (
"io"
"math/rand"
"slices"
"sort"
"sync"
"time"
@ -331,8 +330,8 @@ func (ps *progressState) add(pw progress.Writer) {
for _, p := range ps.items {
plist = append(plist, p)
}
sort.Slice(plist, func(i, j int) bool {
return plist[i].Timestamp.Before(plist[j].Timestamp)
slices.SortFunc(plist, func(a, b *progress.Progress) int {
return a.Timestamp.Compare(b.Timestamp)
})
for _, p := range plist {
rw.WriteRawProgress(p)

View File

@ -2,7 +2,7 @@ package progress
import (
"maps"
"sort"
"slices"
"sync"
"time"
)
@ -49,8 +49,8 @@ func (ps *MultiWriter) Add(pw Writer) {
ps.mu.Lock()
plist := make([]*Progress, 0, len(ps.items))
plist = append(plist, ps.items...)
sort.Slice(plist, func(i, j int) bool {
return plist[i].Timestamp.Before(plist[j].Timestamp)
slices.SortFunc(plist, func(a, b *Progress) int {
return a.Timestamp.Compare(b.Timestamp)
})
for _, p := range plist {
rw.WriteRawProgress(p)

View File

@ -4,7 +4,7 @@ import (
"context"
"io"
"maps"
"sort"
"slices"
"sync"
"time"
@ -165,9 +165,8 @@ func (pr *progressReader) Read(ctx context.Context) ([]*Progress, error) {
for _, p := range dmap {
out = append(out, p)
}
sort.Slice(out, func(i, j int) bool {
return out[i].Timestamp.Before(out[j].Timestamp)
slices.SortFunc(out, func(a, b *Progress) int {
return a.Timestamp.Compare(b.Timestamp)
})
return out, nil

View File

@ -8,6 +8,7 @@ import (
"fmt"
"io"
"os"
"slices"
"sort"
"strconv"
"strings"
@ -518,8 +519,8 @@ func mergeIntervals(intervals []interval) []interval {
}
// sort intervals by start time
sort.Slice(intervals, func(i, j int) bool {
return intervals[i].start.Before(*intervals[j].start)
slices.SortFunc(intervals, func(a, b interval) int {
return a.start.Compare(*b.start)
})
var merged []interval

View File

@ -6,7 +6,7 @@ import (
"fmt"
"maps"
"net/http"
"sort"
"slices"
"strings"
"sync"
"time"
@ -481,7 +481,7 @@ func (s scopes) normalize() []string {
for n := range s {
names = append(names, n)
}
sort.Strings(names)
slices.Sort(names)
out := make([]string, 0, len(s))
@ -490,7 +490,7 @@ func (s scopes) normalize() []string {
for a := range s[n] {
actions = append(actions, a)
}
sort.Strings(actions)
slices.Sort(actions)
out = append(out, n+":"+strings.Join(actions, ","))
}

View File

@ -6,7 +6,7 @@ import (
"io"
"io/fs"
"os"
"sort"
"slices"
"strings"
"github.com/tonistiigi/fsutil"
@ -52,7 +52,7 @@ func (fs *FS) Walk(ctx context.Context, target string, fn fs.WalkDirFunc) error
}
keys = append(keys, convertPathToKey(k))
}
sort.Strings(keys)
slices.Sort(keys)
for _, k := range keys {
p := convertKeyToPath(k)
st := fs.files[p].Stat

View File

@ -12,7 +12,7 @@ import (
"path/filepath"
"reflect"
"runtime"
"sort"
"slices"
"strconv"
"strings"
"sync"
@ -462,7 +462,7 @@ func (mv matrixValue) functionSuffix() string {
if len(mv.fn) == 0 {
return ""
}
sort.Strings(mv.fn)
slices.Sort(mv.fn)
sb := &strings.Builder{}
for _, f := range mv.fn {
sb.Write([]byte("/" + f + "=" + mv.values[f].name))

View File

@ -3,7 +3,7 @@ package detect
import (
"context"
"os"
"sort"
"slices"
"strconv"
"github.com/pkg/errors"
@ -66,8 +66,8 @@ func detectExporter[T any](envVar string, fn func(d ExporterDetector) (T, bool,
for _, d := range detectors {
arr = append(arr, d)
}
sort.Slice(arr, func(i, j int) bool {
return arr[i].priority < arr[j].priority
slices.SortFunc(arr, func(a, b detector) int {
return a.priority - b.priority
})
var ok bool