From d9f3010dda6b821e20a10a772f543e1224340635 Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Wed, 29 Dec 2021 21:14:04 +0100 Subject: [PATCH] Introduce FixedCompletions Example usage: choices := []string{"choice1", "choice2", "choice3"} cmd.RegisterFlagCompletionFunc(cobra.FixedCompletions(choices, ShellCompDirectiveNoFileComp)) --- completions.go | 8 ++++++++ completions_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/completions.go b/completions.go index 9ecd56a47..60c614d32 100644 --- a/completions.go +++ b/completions.go @@ -103,6 +103,14 @@ func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string return nil, ShellCompDirectiveNoFileComp } +// FixedCompletions can be used to create a completion function which always +// returns the same results. +func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return choices, directive + } +} + // RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { flag := c.Flag(flagName) diff --git a/completions_test.go b/completions_test.go index 6a62f0cc8..28a3228e3 100644 --- a/completions_test.go +++ b/completions_test.go @@ -2664,3 +2664,30 @@ func TestCompleteWithRootAndLegacyArgs(t *testing.T) { t.Errorf("expected: %q, got: %q", expected, output) } } + +func TestFixedCompletions(t *testing.T) { + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + choices := []string{"apple", "banana", "orange"} + childCmd := &Command{ + Use: "child", + ValidArgsFunction: FixedCompletions(choices, ShellCompDirectiveNoFileComp), + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "a") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected := strings.Join([]string{ + "apple", + "banana", + "orange", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } +}