|
4 | 4 | "os" |
5 | 5 | "strings" |
6 | 6 |
|
| 7 | + "github.com/distribution/reference" |
7 | 8 | "github.com/docker/cli/cli/command/formatter" |
8 | 9 | "github.com/moby/moby/api/types/container" |
9 | 10 | "github.com/moby/moby/client" |
@@ -38,6 +39,39 @@ func ImageNames(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc { |
38 | 39 | } |
39 | 40 | } |
40 | 41 |
|
| 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 | + |
41 | 75 | // ContainerNames offers completion for container names and IDs |
42 | 76 | // By default, only names are returned. |
43 | 77 | // Set DOCKER_COMPLETION_SHOW_CONTAINER_IDS=yes to also complete IDs. |
|
0 commit comments