Skip to content
Myr

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

6 files+118 added−46 removed

modified:site/content/completions/_index.md+21 added-15 removed
175 unmodified lines
176 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.ShellCompDirectiveNoFileComp
25 unmodified lines
210ShellCompDirectiveNoFileComp211212// 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//218ShellCompDirectiveFilterFileExt219220// 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//230ShellCompDirectiveFilterDirs231232// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
59 unmodified lines
292As 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.293294```go295flagName := "output"296cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {297 return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault296cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {297 return []cobra.Completion{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault298})299```300Notice 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 lines
326```327or328```go329flagName := "output"330cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {331 return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})330cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {331 return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt})332```333334### Limit flag completions to directory names335
4 unmodified lines
340```341or342```go343flagName := "output"344cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {344cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {345 return nil, cobra.ShellCompDirectiveFilterDirs346})347```348To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:349```go350flagName := "output"351cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {352 return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs351cmd.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 lines
369$ helm s[tab]370search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)371```372373Cobra 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:373Cobra 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```go375ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {376 return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp375ValidArgsFunction: 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```382or383```go381ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}384ValidArgs: []cobra.Completion{385 cobra.CompletionWithDesc("bash", "Completions for bash"),386 cobra.CompletionWithDesc("zsh", "Completions for zsh")387 }388```389390If 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 lines
modified:site/content/active_help.md+5 added-5 removed
modified:active_help.go+1 added-1 removed
33 unmodified lines
34// 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.38func AppendActiveHelp(compArray []string, activeHelpStr string) []string {38func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion {39 return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))40}4142// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
18 unmodified lines
modified:command.go+4 added-4 removed
80 unmodified lines
81 // Example is examples of how to use the command.82 Example string8384 // 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 CompletionFunc
1181 unmodified lines
1271 Use: "help [command]",1272 Short: "Help about any command",1273 Long: `Help provides help for any command in the application.1274Simply 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 lines
1284 }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, ShellCompDirectiveNoFileComp
776 unmodified lines
modified:completions_test.go+50 added
2870 unmodified lines
2871 t.Errorf("expected: %q, got: %q", expected, output)2872 }2873}28742875func 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)28852886 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 }28912892 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")28992900 if output != expected {2901 t.Errorf("expected: %q, got: %q", expected, output)2902 }2903 })29042905 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 }29102911 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")29182919 if output != expected {2920 t.Errorf("expected: %q, got: %q", expected, output)2921 }2922 })2923}29242925func TestCompletionForGroupedFlags(t *testing.T) {2926 getCmd := func() *Command {2927 rootCmd := &Command{2928 Use: "root",
866 unmodified lines
modified:completions.go+37 added-21 removed
115 unmodified lines
116 // HiddenDefaultCmd makes the default 'completion' command hidden117 HiddenDefaultCmd bool118}119120// 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.129type Completion = string130131// CompletionFunc is a function that provides completion results.121type CompletionFunc func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)132type CompletionFunc func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)133134// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format.135func CompletionWithDesc(choice string, description string) Completion {136 return choice + "\t" + description137}138139// 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].128func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {144func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {145 return nil, ShellCompDirectiveNoFileComp146}147148// 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].137func FixedCompletions(choices []string, directive ShellCompDirective) CompletionFunc {138 return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {153func 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 lines
305 // GetSlice returns the flag value list as an array of strings.306 GetSlice() []string307}308293func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {309func (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 lines
333 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.ctx340341 // These flags are normally added when `execute()` is called on `finalCmd`,
21 unmodified lines
363 newArgCount := finalCmd.Flags().NArg()364365 // 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 }369370 realArgCount := finalCmd.Flags().NArg()371 if newArgCount > realArgCount {
3 unmodified lines
375 // 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 }382383 // 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 }388389 // 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 lines
411 // 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 }418403 var completions []string419 var completions []Completion420 var directive ShellCompDirective421422 // Enforce flag groups before doing flag completions423 finalCmd.enforceFlagGroupsForCompletion()
77 unmodified lines
501 // - 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 lines
557 }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 lines
577 }578 return false579}580565func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {581func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion {582 if nonCompletableFlag(flag) {567 return []string{}583 return []Completion{}584 }585570 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))591592 // 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 lines
598 //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 }605606 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 }610611 return completions612}613598func completeRequireFlags(finalCmd *Command, toComplete string) []string {599 var completions []string614func completeRequireFlags(finalCmd *Command, toComplete string) []Completion {615 var completions []Completion616617 doCompleteRequiredFlags := func(flag *pflag.Flag) {618 if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {619 if !flag.Changed {
360 unmodified lines