image/tree: Sort image tree by name instead of creation date

Sort images alphabetically by their repository tags rather than by
creation date.

When an image has multiple tags, they are sorted internally and the
first tag is used as the representative for sorting the image in the
list. Untagged images are placed at the end.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
This commit is contained in:
Paweł Gronowski
2025-10-31 11:30:59 +01:00
parent 513ee76bac
commit 8e2943c6c5

View File

@ -7,6 +7,7 @@ import (
"context"
"fmt"
"os"
"slices"
"sort"
"strings"
@ -90,16 +91,36 @@ func runTree(ctx context.Context, dockerCLI command.Cli, opts treeOptions) error
details.ContentSize = units.HumanSizeWithPrecision(float64(totalContent), 3)
// Sort tags for this image
sortedTags := make([]string, len(img.RepoTags))
copy(sortedTags, img.RepoTags)
slices.Sort(sortedTags)
view.images = append(view.images, topImage{
Names: img.RepoTags,
Names: sortedTags,
Details: details,
Children: children,
created: img.Created,
})
}
sort.Slice(view.images, func(i, j int) bool {
return view.images[i].created > view.images[j].created
slices.SortFunc(view.images, func(a, b topImage) int {
nameA := ""
if len(a.Names) > 0 {
nameA = a.Names[0]
}
nameB := ""
if len(b.Names) > 0 {
nameB = b.Names[0]
}
// Empty names sort last
if (nameA == "") != (nameB == "") {
if nameB == "" {
return -1
}
return 1
}
return strings.Compare(nameA, nameB)
})
return printImageTree(dockerCLI, view)