From 6f439ea4a4b2a9b60a212080e0e4d4a7f2b26fd3 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Thu, 24 Oct 2024 11:31:25 +0000 Subject: [PATCH] Add completion for `--link` Signed-off-by: Harald Albers (cherry picked from commit e513454244f129d04b3a89ea1ad499362dc68040) Signed-off-by: Sebastiaan van Stijn --- cli/command/container/completion.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/cli/command/container/completion.go b/cli/command/container/completion.go index 30cb058281..cffa714003 100644 --- a/cli/command/container/completion.go +++ b/cli/command/container/completion.go @@ -62,6 +62,7 @@ func addCompletions(cmd *cobra.Command, dockerCLI completion.APIClientProvider) _ = cmd.RegisterFlagCompletionFunc("env", completion.EnvVarNames) _ = cmd.RegisterFlagCompletionFunc("env-file", completion.FileNames) _ = cmd.RegisterFlagCompletionFunc("ipc", completeIpc(dockerCLI)) + _ = cmd.RegisterFlagCompletionFunc("link", completeLink(dockerCLI)) _ = cmd.RegisterFlagCompletionFunc("network", completion.NetworkNames(dockerCLI)) _ = cmd.RegisterFlagCompletionFunc("platform", completion.Platforms) _ = cmd.RegisterFlagCompletionFunc("pull", completion.FromList(PullImageAlways, PullImageMissing, PullImageNever)) @@ -91,6 +92,23 @@ func completeIpc(dockerCLI completion.APIClientProvider) func(cmd *cobra.Command } } +// completeLink implements shell completion for the `--link` option of `run` and `create`. +func completeLink(dockerCLI completion.APIClientProvider) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return postfixWith(":", containerNames(dockerCLI, cmd, args, toComplete)), cobra.ShellCompDirectiveNoSpace + } +} + +// containerNames contacts the API to get names and optionally IDs of containers. +// In case of an error, an empty list is returned. +func containerNames(dockerCLI completion.APIClientProvider, cmd *cobra.Command, args []string, toComplete string) []string { + names, _ := completion.ContainerNames(dockerCLI, true)(cmd, args, toComplete) + if names == nil { + return []string{} + } + return names +} + // prefixWith prefixes every element in the slice with the given prefix. func prefixWith(prefix string, values []string) []string { result := make([]string, len(values)) @@ -100,6 +118,15 @@ func prefixWith(prefix string, values []string) []string { return result } +// postfixWith appends postfix to every element in the slice. +func postfixWith(postfix string, values []string) []string { + result := make([]string, len(values)) + for i, v := range values { + result[i] = v + postfix + } + return result +} + func completeLinuxCapabilityNames(cmd *cobra.Command, args []string, toComplete string) (names []string, _ cobra.ShellCompDirective) { return completion.FromList(allLinuxCapabilities()...)(cmd, args, toComplete) }