From 437f1260fd16820787911659c91765b42c25c36b Mon Sep 17 00:00:00 2001 From: Dorin Geman Date: Fri, 11 Apr 2025 14:28:14 +0300 Subject: [PATCH] Enable completion for `docker images` Signed-off-by: Dorin Geman --- cli/command/completion/functions.go | 34 +++++++++++++++++++++++++++++ cli/command/image/list.go | 2 ++ 2 files changed, 36 insertions(+) diff --git a/cli/command/completion/functions.go b/cli/command/completion/functions.go index bc60668a08b1..811134167a16 100644 --- a/cli/command/completion/functions.go +++ b/cli/command/completion/functions.go @@ -4,6 +4,7 @@ import ( "os" "strings" + "github.com/distribution/reference" "github.com/docker/cli/cli/command/formatter" "github.com/moby/moby/api/types/container" "github.com/moby/moby/client" @@ -38,6 +39,39 @@ func ImageNames(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc { } } +// ImageNamesWithBase offers completion for images present within the local store, +// including both full image names with tags and base image names (repository names only) +// when multiple tags exist for the same base name +func ImageNamesWithBase(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if limit > 0 && len(args) >= limit { + return nil, cobra.ShellCompDirectiveNoFileComp + } + list, err := dockerCLI.Client().ImageList(cmd.Context(), client.ImageListOptions{}) + if err != nil { + return nil, cobra.ShellCompDirectiveError + } + var names []string + baseNameCounts := make(map[string]int) + for _, img := range list { + names = append(names, img.RepoTags...) + for _, tag := range img.RepoTags { + ref, err := reference.ParseNormalizedNamed(tag) + if err != nil { + continue + } + baseNameCounts[reference.FamiliarName(ref)]++ + } + } + for baseName, count := range baseNameCounts { + if count > 1 { + names = append(names, baseName) + } + } + return names, cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp + } +} + // ContainerNames offers completion for container names and IDs // By default, only names are returned. // Set DOCKER_COMPLETION_SHOW_CONTAINER_IDS=yes to also complete IDs. diff --git a/cli/command/image/list.go b/cli/command/image/list.go index 3cf1988405e1..971cc4e7c571 100644 --- a/cli/command/image/list.go +++ b/cli/command/image/list.go @@ -8,6 +8,7 @@ import ( "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" + "github.com/docker/cli/cli/command/completion" "github.com/docker/cli/cli/command/formatter" flagsHelper "github.com/docker/cli/cli/flags" "github.com/docker/cli/opts" @@ -52,6 +53,7 @@ func newImagesCommand(dockerCLI command.Cli) *cobra.Command { "aliases": "docker image ls, docker image list, docker images", }, DisableFlagsInUseLine: true, + ValidArgsFunction: completion.ImageNamesWithBase(dockerCLI, 1), } flags := cmd.Flags()