Skip to content

Commit 2333226

Browse files
authored
Merge pull request #6452 from doringeman/image-list-completions
Enable completion for `docker images`
2 parents 5d8fb33 + 437f126 commit 2333226

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

cli/command/completion/functions.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"os"
55
"strings"
66

7+
"github.com/distribution/reference"
78
"github.com/docker/cli/cli/command/formatter"
89
"github.com/moby/moby/api/types/container"
910
"github.com/moby/moby/client"
@@ -38,6 +39,39 @@ func ImageNames(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc {
3839
}
3940
}
4041

42+
// ImageNamesWithBase offers completion for images present within the local store,
43+
// including both full image names with tags and base image names (repository names only)
44+
// when multiple tags exist for the same base name
45+
func ImageNamesWithBase(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc {
46+
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
47+
if limit > 0 && len(args) >= limit {
48+
return nil, cobra.ShellCompDirectiveNoFileComp
49+
}
50+
list, err := dockerCLI.Client().ImageList(cmd.Context(), client.ImageListOptions{})
51+
if err != nil {
52+
return nil, cobra.ShellCompDirectiveError
53+
}
54+
var names []string
55+
baseNameCounts := make(map[string]int)
56+
for _, img := range list {
57+
names = append(names, img.RepoTags...)
58+
for _, tag := range img.RepoTags {
59+
ref, err := reference.ParseNormalizedNamed(tag)
60+
if err != nil {
61+
continue
62+
}
63+
baseNameCounts[reference.FamiliarName(ref)]++
64+
}
65+
}
66+
for baseName, count := range baseNameCounts {
67+
if count > 1 {
68+
names = append(names, baseName)
69+
}
70+
}
71+
return names, cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp
72+
}
73+
}
74+
4175
// ContainerNames offers completion for container names and IDs
4276
// By default, only names are returned.
4377
// 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)