Skip to content

Commit a10d699

Browse files
emersionhoshsadiq
authored andcommitted
Introduce FixedCompletions
Example usage: choices := []string{"choice1", "choice2", "choice3"} cmd.RegisterFlagCompletionFunc(cobra.FixedCompletions(choices, ShellCompDirectiveNoFileComp)) Merge spf13/cobra#1574
1 parent 5c10ffa commit a10d699

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

completions.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,14 @@ func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string
103103
return nil, ShellCompDirectiveNoFileComp
104104
}
105105

106+
// FixedCompletions can be used to create a completion function which always
107+
// returns the same results.
108+
func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
109+
return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
110+
return choices, directive
111+
}
112+
}
113+
106114
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
107115
func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
108116
flag := c.Flag(flagName)

completions_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2664,3 +2664,30 @@ func TestCompleteWithRootAndLegacyArgs(t *testing.T) {
26642664
t.Errorf("expected: %q, got: %q", expected, output)
26652665
}
26662666
}
2667+
2668+
func TestFixedCompletions(t *testing.T) {
2669+
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
2670+
choices := []string{"apple", "banana", "orange"}
2671+
childCmd := &Command{
2672+
Use: "child",
2673+
ValidArgsFunction: FixedCompletions(choices, ShellCompDirectiveNoFileComp),
2674+
Run: emptyRun,
2675+
}
2676+
rootCmd.AddCommand(childCmd)
2677+
2678+
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "a")
2679+
if err != nil {
2680+
t.Errorf("Unexpected error: %v", err)
2681+
}
2682+
2683+
expected := strings.Join([]string{
2684+
"apple",
2685+
"banana",
2686+
"orange",
2687+
":4",
2688+
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
2689+
2690+
if output != expected {
2691+
t.Errorf("expected: %q, got: %q", expected, output)
2692+
}
2693+
}

0 commit comments

Comments
 (0)