Skip to content
Myr

completion: improve detection for flags that accept multiple values (#2210)

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

The completion code attempts to detect whether a flag can be specified more than once, and therefore should provide completion even if already set. Currently, this code depends on conventions used in the pflag package, which uses an "Array" or "Slice" suffix or for some types a "stringTo" prefix. Cobra allows custom value types to be used, which may not use the same convention for naming, and therefore currently aren't detected to allow multiple values. The pflag module defines a [SliceValue] interface, which is implemented by the Slice and Array value types it provides (unfortunately, it's not currently implemented by the "stringTo" values). This patch adds a reduced interface based on the [SliceValue] interface mentioned above to allow detecting Value-types that accept multiple values. Custom types can implement this interface to make completion work for those values. I deliberately used a reduced interface to keep the requirements for this detection as low as possible, without enforcing the other methods defined in the interface (Append, Replace) which may not apply to all custom types. Future improvements can likely still be made, considering either implementing the SliceValue interface for the "stringTo" values or defining a separate "MapValue" interface for those types. Possibly providing the reduced interface as part of the pflag module and to export it. [SliceValue]: https://github.com/spf13/pflag/blob/d5e0c0615acee7028e1e2740a11102313be88de1/flag.go#L193-L203

authored by Sebastiaan van Stijn · committed by GitHub · parent d1e9d85 · Browse files · 2 files+47 added−3 removed
This commit

State

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

Trailers

  • Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
  • Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
  • Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>

Diff stats

2 files+47 added−3 removed

  • other:+47 added−3 removed

2 files+47 added−3 removed

modified:completions_test.go+34 added-1 removed
669 unmodified lines
670 t.Errorf("expected: %q, got: %q", expected, output)671 }672}673674// customMultiString is a custom Value type that accepts multiple values,675// but does not include "Slice" or "Array" in its "Type" string.676type customMultiString []string677678var _ SliceValue = (*customMultiString)(nil)679680func (s *customMultiString) String() string {681 return fmt.Sprintf("%v", *s)682}683684func (s *customMultiString) Set(v string) error {685 *s = append(*s, v)686 return nil687}688689func (s *customMultiString) Type() string {690 return "multi string"691}692693func (s *customMultiString) GetSlice() []string {694 return *s695}696697func TestFlagNameCompletionRepeat(t *testing.T) {698 rootCmd := &Command{699 Use: "root",700 Run: emptyRun,
14 unmodified lines
715 rootCmd.Flags().IntSliceP("slice", "l", nil, "slice flag")716 sliceFlag := rootCmd.Flags().Lookup("slice")717 rootCmd.Flags().BoolSliceP("bslice", "b", nil, "bool slice flag")718 bsliceFlag := rootCmd.Flags().Lookup("bslice")719 rootCmd.Flags().VarP(&customMultiString{}, "multi", "m", "multi string flag")720 multiFlag := rootCmd.Flags().Lookup("multi")721722 // Test that flag names are not repeated unless they are an array or slice723 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--")724 if err != nil {
5 unmodified lines
730 expected := strings.Join([]string{731 "--array",732 "--bslice",733 "--help",734 "--multi",735 "--second",736 "--slice",737 ":4",738 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
14 unmodified lines
753 expected = strings.Join([]string{754 "--array",755 "--bslice",756 "--help",757 "--multi",758 "--slice",759 ":4",760 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")761
1 unmodified line
763 t.Errorf("expected: %q, got: %q", expected, output)764 }765766 // Test that flag names are not repeated unless they are an array or slice740 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--")767 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--multi", "val", "--")768 if err != nil {769 t.Errorf("Unexpected error: %v", err)770 }771 // Reset the flag for the next command772 sliceFlag.Changed = false773 arrayFlag.Changed = false774 bsliceFlag.Changed = false775 multiFlag.Changed = false776777 expected = strings.Join([]string{778 "--array",779 "--bslice",780 "--first",781 "--help",782 "--multi",783 "--second",784 "--slice",785 ":4",786 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
9 unmodified lines
796 }797 // Reset the flag for the next command798 sliceFlag.Changed = false799 arrayFlag.Changed = false800 multiFlag.Changed = false801802 expected = strings.Join([]string{803 "--array",804 "-a",
2 unmodified lines
807 "--first",808 "-f",809 "--help",810 "-h",811 "--multi",812 "-m",813 "--second",814 "-s",815 "--slice",816 "-l",
11 unmodified lines
828 }829 // Reset the flag for the next command830 sliceFlag.Changed = false831 arrayFlag.Changed = false832 multiFlag.Changed = false833834 expected = strings.Join([]string{835 "-a",836 ":4",
2908 unmodified lines
modified:completions.go+13 added-2 removed
268 unmodified lines
269 c.RemoveCommand(completeCmd)270 }271}272273// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect274// flags that accept multiple values and therefore can provide completion275// multiple times.276type SliceValue interface {277 // GetSlice returns the flag value list as an array of strings.278 GetSlice() []string279}280281func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {282 // The last argument, which is not completely typed by the user,283 // should not be part of the list of arguments284 toComplete := args[len(args)-1]
121 unmodified lines
406407 // If we have not found any required flags, only then can we show regular flags408 if len(completions) == 0 {409 doCompleteFlags := func(flag *pflag.Flag) {402 if !flag.Changed ||410 _, acceptsMultiple := flag.Value.(SliceValue)411 acceptsMultiple = acceptsMultiple ||412 strings.Contains(flag.Value.Type(), "Slice") ||413 strings.Contains(flag.Value.Type(), "Array") ||405 strings.HasPrefix(flag.Value.Type(), "stringTo") {414 strings.HasPrefix(flag.Value.Type(), "stringTo")415416 if !flag.Changed || acceptsMultiple {417 // If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo)418 // we suggest it as a completion419 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)420 }
531 unmodified lines