From 8e2943c6c5437afc63c9a2c183bf66def10e3c48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Gronowski?= Date: Fri, 31 Oct 2025 11:30:59 +0100 Subject: [PATCH] image/tree: Sort image tree by name instead of creation date MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- cli/command/image/tree.go | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/cli/command/image/tree.go b/cli/command/image/tree.go index 383a26522140..c1586af58d47 100644 --- a/cli/command/image/tree.go +++ b/cli/command/image/tree.go @@ -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)