From 7a4062a4a94943292b7f43186c2672d5b855a640 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 5 Jul 2024 14:15:29 +0200 Subject: [PATCH] cli/command/completion: add FromList utility It's an alias for cobra.FixedCompletions but takes a variadic list of strings, so that it's not needed to construct an array for this. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 5e7bcbeac6e368a9f90167215168f699a0ee197b) Signed-off-by: Sebastiaan van Stijn --- cli/command/completion/functions.go | 5 +++++ cli/command/container/run.go | 1 + cmd/docker/completions.go | 9 ++------- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/cli/command/completion/functions.go b/cli/command/completion/functions.go index 1e9e062c06..c25330a4b6 100644 --- a/cli/command/completion/functions.go +++ b/cli/command/completion/functions.go @@ -130,6 +130,11 @@ func EnvVarNames(_ *cobra.Command, _ []string, _ string) (names []string, _ cobr return names, cobra.ShellCompDirectiveNoFileComp } +// FromList offers completion for the given list of options. +func FromList(options ...string) ValidArgsFn { + return cobra.FixedCompletions(options, cobra.ShellCompDirectiveNoFileComp) +} + // FileNames is a convenience function to use [cobra.ShellCompDirectiveDefault], // which indicates to let the shell perform its default behavior after // completions have been provided. diff --git a/cli/command/container/run.go b/cli/command/container/run.go index 5fb44baef3..b06156f05d 100644 --- a/cli/command/container/run.go +++ b/cli/command/container/run.go @@ -72,6 +72,7 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command { _ = cmd.RegisterFlagCompletionFunc("env", completion.EnvVarNames) _ = cmd.RegisterFlagCompletionFunc("env-file", completion.FileNames) _ = cmd.RegisterFlagCompletionFunc("network", completion.NetworkNames(dockerCli)) + _ = cmd.RegisterFlagCompletionFunc("pull", completion.FromList(PullImageAlways, PullImageMissing, PullImageNever)) return cmd } diff --git a/cmd/docker/completions.go b/cmd/docker/completions.go index 582a2051e3..afa87d7008 100644 --- a/cmd/docker/completions.go +++ b/cmd/docker/completions.go @@ -1,6 +1,7 @@ package main import ( + "github.com/docker/cli/cli/command/completion" "github.com/docker/cli/cli/context/store" "github.com/spf13/cobra" ) @@ -19,13 +20,7 @@ func registerCompletionFuncForGlobalFlags(contextStore store.Store, cmd *cobra.C if err != nil { return err } - err = cmd.RegisterFlagCompletionFunc( - "log-level", - func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - values := []string{"debug", "info", "warn", "error", "fatal"} - return values, cobra.ShellCompDirectiveNoFileComp - }, - ) + err = cmd.RegisterFlagCompletionFunc("log-level", completion.FromList("debug", "info", "warn", "error", "fatal")) if err != nil { return err }