feat: add CompletionWithDesc helper (#2231)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The code has also been refactored to use a type alias for completion and a completion helper Using a type alias is a non-breaking change and it makes the code more readable and easier to understand.
authored by ccoVeille · committed by GitHub · parent 17b6dca · Browse files · 6 files·+118 added−46 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: ccoVeille <3875889+ccoVeille@users.noreply.github.com>
- Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
Diff stats
6 files+118 added−46 removed
- other:+118 added−46 removed
Provenance
- Commit
8cb30f9- Tree
500fd26- Author
ccoVeille <3875889+ccoVeille@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
17b6dca
6 files changed+118 added−46 removed
modified:site/content/completions/_index.md+21 added-15 removed
175 unmodified lines176 Long: status_long,177 RunE: func(cmd *cobra.Command, args []string) {178 RunGet(args[0])179 },180- ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {180+ ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {181 if len(args) != 0 {182 return nil, cobra.ShellCompDirectiveNoFileComp183 }184 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp25 unmodified lines210 ShellCompDirectiveNoFileComp211 212 // Indicates that the returned completions should be used as file extension filters.213 // For example, to complete only files of the form *.json or *.yaml:214-// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt214+// return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt215 // For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()216 // is a shortcut to using this directive explicitly.217 //218 ShellCompDirectiveFilterFileExt219 220 // Indicates that only directory names should be provided in file completion.221 // For example:222-// return nil, ShellCompDirectiveFilterDirs222+// return nil, cobra.ShellCompDirectiveFilterDirs223 // For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.224 //225 // To request directory names within another directory, the returned completions226 // should specify a single directory name within which to search. For example,227 // to complete directories within "themes/":228-// return []string{"themes"}, ShellCompDirectiveFilterDirs228+// return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs229 //230 ShellCompDirectiveFilterDirs231 232 // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order59 unmodified lines292 As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.293 294 ```go295 flagName := "output"296-cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {297- return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault296+cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {297+ return []cobra.Completion{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault298 })299 ```300 Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:301 24 unmodified lines326 ```327 or328 ```go329 flagName := "output"330-cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {331- return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})330+cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {331+ return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt})332 ```333 334 ### Limit flag completions to directory names335 4 unmodified lines340 ```341 or342 ```go343 flagName := "output"344-cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {344+cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {345 return nil, cobra.ShellCompDirectiveFilterDirs346 })347 ```348 To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:349 ```go350 flagName := "output"351-cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {352- return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs351+cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {352+ return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs353 })354 ```355 ### Descriptions for completions356 12 unmodified lines369 $ helm s[tab]370 search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)371 ```372 373-Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:373+Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. Cobra provides the helper function `CompletionWithDesc(string, string)` to create a completion with a description. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:374 ```go375-ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {376- return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp375+ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {376+ return []cobra.Completion{377+ cobra.CompletionWithDesc("harbor", "An image registry"),378+ cobra.CompletionWithDesc("thanos", "Long-term metrics")379+ }, cobra.ShellCompDirectiveNoFileComp380 }}381 ```382 or383 ```go381-ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}384+ValidArgs: []cobra.Completion{385+ cobra.CompletionWithDesc("bash", "Completions for bash"),386+ cobra.CompletionWithDesc("zsh", "Completions for zsh")387+ }388 ```389 390 If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:391 194 unmodified linesmodified:site/content/active_help.md+5 added-5 removed
39 unmodified lines40414243444544454647484924 unmodified lines7475767778787980818228 unmodified lines11111211311411511511611711811811912012112246 unmodified lines39 unmodified lines Args: require.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { return addRepo(args) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { var comps []string ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { var comps []cobra.Completion if len(args) == 0 { comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") } else if len(args) == 1 { comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")24 unmodified lines
Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:
```go_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { if len(args) != 2 { return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp } return compVersionFlag(args[1], toComplete)28 unmodified lines
For example:
```goValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
var comps []string var comps []cobra.Completion if len(args) == 0 { if activeHelpLevel != "off" { comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") }46 unmodified linesmodified:active_help.go+1 added-1 removed
33 unmodified lines34 // The array parameter should be the array that will contain the completions.35 // This function can be called multiple times before and/or after completions are added to36 // the array. Each time this function is called with the same array, the new37 // ActiveHelp line will be shown below the previous ones when completion is triggered.38-func AppendActiveHelp(compArray []string, activeHelpStr string) []string {38+func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion {39 return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))40 }41 42 // GetActiveHelpConfig returns the value of the ActiveHelp environment variable18 unmodified linesmodified:command.go+4 added-4 removed
80 unmodified lines81 // Example is examples of how to use the command.82 Example string83 84 // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions85- ValidArgs []string85+ ValidArgs []Completion86 // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.87 // It is a dynamic version of using ValidArgs.88 // Only one of ValidArgs and ValidArgsFunction can be used for a command.89 ValidArgsFunction CompletionFunc1181 unmodified lines1271 Use: "help [command]",1272 Short: "Help about any command",1273 Long: `Help provides help for any command in the application.1274 Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,1275- ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1276- var completions []string1275+ ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {1276+ var completions []Completion1277 cmd, _, e := c.Root().Find(args)1278 if e != nil {1279 return nil, ShellCompDirectiveNoFileComp1280 }3 unmodified lines1284 }1285 for _, subCmd := range cmd.Commands() {1286 if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1287 if strings.HasPrefix(subCmd.Name(), toComplete) {1288- completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))1288+ completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))1289 }1290 }1291 }1292 return completions, ShellCompDirectiveNoFileComp776 unmodified linesmodified:completions_test.go+50 added
2870 unmodified lines2871 t.Errorf("expected: %q, got: %q", expected, output)2872 }2873 }2874 2875+func TestFixedCompletionsWithCompletionHelpers(t *testing.T) {2876+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}2877+ // here we are mixing string, [Completion] and [CompletionWithDesc]2878+ choices := []string{"apple", Completion("banana"), CompletionWithDesc("orange", "orange are orange")}2879+ childCmd := &Command{2880+ Use: "child",2881+ ValidArgsFunction: FixedCompletions(choices, ShellCompDirectiveNoFileComp),2882+ Run: emptyRun,2883+ }2884+ rootCmd.AddCommand(childCmd)2885+2886+ t.Run("completion with description", func(t *testing.T) {2887+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child", "a")2888+ if err != nil {2889+ t.Errorf("Unexpected error: %v", err)2890+ }2891+2892+ expected := strings.Join([]string{2893+ "apple",2894+ "banana",2895+ "orange\torange are orange", // this one has the description as expected with [ShellCompRequestCmd] flag2896+ ":4",2897+ "Completion ended with directive: ShellCompDirectiveNoFileComp", "",2898+ }, "\n")2899+2900+ if output != expected {2901+ t.Errorf("expected: %q, got: %q", expected, output)2902+ }2903+ })2904+2905+ t.Run("completion with no description", func(t *testing.T) {2906+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "a")2907+ if err != nil {2908+ t.Errorf("Unexpected error: %v", err)2909+ }2910+2911+ expected := strings.Join([]string{2912+ "apple",2913+ "banana",2914+ "orange", // the description is absent as expected with [ShellCompNoDescRequestCmd] flag2915+ ":4",2916+ "Completion ended with directive: ShellCompDirectiveNoFileComp", "",2917+ }, "\n")2918+2919+ if output != expected {2920+ t.Errorf("expected: %q, got: %q", expected, output)2921+ }2922+ })2923+}2924+2925 func TestCompletionForGroupedFlags(t *testing.T) {2926 getCmd := func() *Command {2927 rootCmd := &Command{2928 Use: "root",866 unmodified linesmodified:completions.go+37 added-21 removed
115 unmodified lines116 // HiddenDefaultCmd makes the default 'completion' command hidden117 HiddenDefaultCmd bool118 }119 120+// Completion is a string that can be used for completions121+//122+// two formats are supported:123+// - the completion choice124+// - the completion choice with a textual description (separated by a TAB).125+//126+// [CompletionWithDesc] can be used to create a completion string with a textual description.127+//128+// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used.129+type Completion = string130+131 // CompletionFunc is a function that provides completion results.121-type CompletionFunc func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)132+type CompletionFunc func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)133 134+// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format.135+func CompletionWithDesc(choice string, description string) Completion {136+ return choice + "\t" + description137+}138+139 // NoFileCompletions can be used to disable file completion for commands that should140 // not trigger file completions.141 //142 // This method satisfies [CompletionFunc].143 // It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].128-func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {144+func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {145 return nil, ShellCompDirectiveNoFileComp146 }147 148 // FixedCompletions can be used to create a completion function which always149 // returns the same results.150 //151 // This method returns a function that satisfies [CompletionFunc]152 // It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].137-func FixedCompletions(choices []string, directive ShellCompDirective) CompletionFunc {138- return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {153+func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc {154+ return func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {155 return choices, directive156 }157 }158 146 unmodified lines305 // GetSlice returns the flag value list as an array of strings.306 GetSlice() []string307 }308 293-func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {309+func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) {310 // The last argument, which is not completely typed by the user,311 // should not be part of the list of arguments312 toComplete := args[len(args)-1]313 trimmedArgs := args[:len(args)-1]19 unmodified lines333 finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs)334 }335 if err != nil {336 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>321- return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs)337+ return c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs)338 }339 finalCmd.ctx = c.ctx340 341 // These flags are normally added when `execute()` is called on `finalCmd`,21 unmodified lines363 newArgCount := finalCmd.Flags().NArg()364 365 // Parse the flags early so we can check if required flags are set366 if err = finalCmd.ParseFlags(finalArgs); err != nil {351- return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())367+ return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())368 }369 370 realArgCount := finalCmd.Flags().NArg()371 if newArgCount > realArgCount {3 unmodified lines375 // Error while attempting to parse flags376 if flagErr != nil {377 // If error type is flagCompError and we don't want flagCompletion we should ignore the error378 if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {363- return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr379+ return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr380 }381 }382 383 // Look for the --help or --version flags. If they are present,384 // there should be no further completions.385 if helpOrVersionFlagPresent(finalCmd) {370- return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil386+ return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil387 }388 389 // We only remove the flags from the arguments if DisableFlagParsing is not set.390 // This is important for commands which have requested to do their own flag completion.20 unmodified lines411 // Directory completion from within a directory412 return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil413 }414 // Directory completion399- return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil415+ return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil416 }417 }418 403- var completions []string419+ var completions []Completion420 var directive ShellCompDirective421 422 // Enforce flag groups before doing flag completions423 finalCmd.enforceFlagGroupsForCompletion()77 unmodified lines501 // - there are no local, non-persistent flags on the command-line or TraverseChildren is true502 for _, subCmd := range finalCmd.Commands() {503 if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {504 if strings.HasPrefix(subCmd.Name(), toComplete) {489- completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))505+ completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))506 }507 directive = ShellCompDirectiveNoFileComp508 }509 }47 unmodified lines557 }558 if completionFn != nil {559 // Go custom completion defined for this flag or command.560 // Call the registered completion function to get the completions.545- var comps []string561+ var comps []Completion562 comps, directive = completionFn(finalCmd, finalArgs, toComplete)563 completions = append(completions, comps...)564 }565 11 unmodified lines577 }578 return false579 }580 565-func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {581+func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion {582 if nonCompletableFlag(flag) {567- return []string{}583+ return []Completion{}584 }585 570- var completions []string586+ var completions []Completion587 flagName := "--" + flag.Name588 if strings.HasPrefix(flagName, toComplete) {589 // Flag without the =574- completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))590+ completions = append(completions, CompletionWithDesc(flagName, flag.Usage))591 592 // Why suggest both long forms: --flag and --flag= ?593 // This forces the user to *always* have to type either an = or a space after the flag name.594 // Let's be nice and avoid making users have to do that.3 unmodified lines598 //599 // if len(flag.NoOptDefVal) == 0 {600 // // Flag requires a value, so it can be suffixed with =601 // flagName += "="586- // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))602+ // completions = append(completions, CompletionWithDesc(flagName, flag.Usage))603 // }604 }605 606 flagName = "-" + flag.Shorthand607 if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {592- completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))608+ completions = append(completions, CompletionWithDesc(flagName, flag.Usage))609 }610 611 return completions612 }613 598-func completeRequireFlags(finalCmd *Command, toComplete string) []string {599- var completions []string614+func completeRequireFlags(finalCmd *Command, toComplete string) []Completion {615+ var completions []Completion616 617 doCompleteRequiredFlags := func(flag *pflag.Flag) {618 if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {619 if !flag.Changed {360 unmodified lines