Skip to content
Myr

Introduce FixedCompletions (#1574)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Example usage: choices := []string{"choice1", "choice2", "choice3"} cmd.RegisterFlagCompletionFunc(cobra.FixedCompletions(choices, ShellCompDirectiveNoFileComp))

authored by Simon Ser · committed by GitHub · parent 94e552d · Browse files · 2 files+35 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+35 added−0 removed

  • other:+35 added−0 removed

2 files+35 added−0 removed

modified:completions_test.go+27 added
2662 unmodified lines
2663 if output != expected {2664 t.Errorf("expected: %q, got: %q", expected, output)2665 }2666}26672668func 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)26772678 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "a")2679 if err != nil {2680 t.Errorf("Unexpected error: %v", err)2681 }26822683 expected := strings.Join([]string{2684 "apple",2685 "banana",2686 "orange",2687 ":4",2688 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")26892690 if output != expected {2691 t.Errorf("expected: %q, got: %q", expected, output)2692 }2693}
modified:completions.go+8 added
101 unmodified lines
102func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {103 return nil, ShellCompDirectiveNoFileComp104}105106// FixedCompletions can be used to create a completion function which always107// returns the same results.108func 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, directive111 }112}113114// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.115func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {116 flag := c.Flag(flagName)117 if flag == nil {
706 unmodified lines