Skip to content

Commit f3f88ae

Browse files
committed
Enable completion for docker images
Signed-off-by: Dorin Geman <[email protected]>
1 parent 4373ce5 commit f3f88ae

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

cli/command/completion/functions.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,37 @@ func ImageNames(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc {
3838
}
3939
}
4040

41+
// ImageNamesWithBase offers completion for images present within the local store,
42+
// including both full image names with tags and base image names (repository names only)
43+
// when multiple tags exist for the same base name
44+
func ImageNamesWithBase(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc {
45+
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
46+
if limit > 0 && len(args) >= limit {
47+
return nil, cobra.ShellCompDirectiveNoFileComp
48+
}
49+
list, err := dockerCLI.Client().ImageList(cmd.Context(), client.ImageListOptions{})
50+
if err != nil {
51+
return nil, cobra.ShellCompDirectiveError
52+
}
53+
var names []string
54+
baseNameCounts := make(map[string]int)
55+
for _, img := range list {
56+
names = append(names, img.RepoTags...)
57+
for _, tag := range img.RepoTags {
58+
if baseName, _, ok := strings.Cut(tag, ":"); ok {
59+
baseNameCounts[baseName]++
60+
}
61+
}
62+
}
63+
for baseName, count := range baseNameCounts {
64+
if count > 1 {
65+
names = append(names, baseName)
66+
}
67+
}
68+
return names, cobra.ShellCompDirectiveNoSpace
69+
}
70+
}
71+
4172
// ContainerNames offers completion for container names and IDs
4273
// By default, only names are returned.
4374
// Set DOCKER_COMPLETION_SHOW_CONTAINER_IDS=yes to also complete IDs.

cli/command/image/list.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
"github.com/docker/cli/cli"
1010
"github.com/docker/cli/cli/command"
11+
"github.com/docker/cli/cli/command/completion"
1112
"github.com/docker/cli/cli/command/formatter"
1213
flagsHelper "github.com/docker/cli/cli/flags"
1314
"github.com/docker/cli/opts"
@@ -52,6 +53,7 @@ func newImagesCommand(dockerCLI command.Cli) *cobra.Command {
5253
"aliases": "docker image ls, docker image list, docker images",
5354
},
5455
DisableFlagsInUseLine: true,
56+
ValidArgsFunction: completion.ImageNamesWithBase(dockerCLI, 1),
5557
}
5658

5759
flags := cmd.Flags()

0 commit comments

Comments
 (0)