Skip to content
Myr

Add support for custom completions in Go (#1035)

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

This commit allows programs using Cobra to code their custom completions in Go instead of Bash. The new ValidArgsFunction field is added for commands, similarly to ValidArgs. For flags, the new function Command.RegisterFlagCompletionFunc() is added. When either of the above functions is used, the bash completion script will call the new hidden command '__complete', passing it all command-line arguments. The '__complete' command will call the function specified by Command.ValidArgsFunction or by Command.RegisterFlagCompletionFunc to obtain completions from the program itself.

authored by Marc Khouzam · committed by GitHub · parent 138b98f · Browse files · 5 files+955 added−57 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: Marc Khouzam <marc.khouzam@montreal.ca>

Diff stats

5 files+955 added−57 removed

  • other:+955 added−57 removed

5 files+955 added−57 removed

modified:bash_completions.go+85 added-1 removed
56 unmodified lines
57 done58 return 159}6061__%[1]s_handle_go_custom_completion()62{63 __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"6465 local out requestComp lastParam lastChar comp directive args6667 # Prepare the command to request completions for the program.68 # Calling ${words[0]} instead of directly %[1]s allows to handle aliases69 args=("${words[@]:1}")70 requestComp="${words[0]} %[2]s ${args[*]}"7172 lastParam=${words[$((${#words[@]}-1))]}73 lastChar=${lastParam:$((${#lastParam}-1)):1}74 __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"7576 if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then77 # If the last parameter is complete (there is a space following it)78 # We add an extra empty parameter so we can indicate this to the go method.79 __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter"80 requestComp="${requestComp} \"\""81 fi8283 __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"84 # Use eval to handle any environment variables and such85 out=$(eval "${requestComp}" 2>/dev/null)8687 # Extract the directive integer at the very end of the output following a colon (:)88 directive=${out##*:}89 # Remove the directive90 out=${out%%:*}91 if [ "${directive}" = "${out}" ]; then92 # There is not directive specified93 directive=094 fi95 __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"96 __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"9798 if [ $((directive & %[3]d)) -ne 0 ]; then99 # Error code. No completion.100 __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"101 return102 else103 if [ $((directive & %[4]d)) -ne 0 ]; then104 if [[ $(type -t compopt) = "builtin" ]]; then105 __%[1]s_debug "${FUNCNAME[0]}: activating no space"106 compopt -o nospace107 fi108 fi109 if [ $((directive & %[5]d)) -ne 0 ]; then110 if [[ $(type -t compopt) = "builtin" ]]; then111 __%[1]s_debug "${FUNCNAME[0]}: activating no file completion"112 compopt +o default113 fi114 fi115116 while IFS='' read -r comp; do117 COMPREPLY+=("$comp")118 done < <(compgen -W "${out[*]}" -- "$cur")119 fi120}121122__%[1]s_handle_reply()123{124 __%[1]s_debug "${FUNCNAME[0]}"125 local comp
55 unmodified lines
181 local completions182 completions=("${commands[@]}")183 if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then184 completions=("${must_have_one_noun[@]}")185 elif [[ -n "${has_completion_function}" ]]; then186 # if a go completion function is provided, defer to that function187 completions=()188 __%[1]s_handle_go_custom_completion189 fi190 if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then191 completions+=("${must_have_one_flag[@]}")192 fi
150 unmodified lines
343 fi344 __%[1]s_handle_word345}346282`, name))347`, name, CompRequestCmd, BashCompDirectiveError, BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp))348}349350func writePostscript(buf *bytes.Buffer, name string) {351 name = strings.Replace(name, ":", "__", -1)
16 unmodified lines
368 local flags_completion=()369 local commands=("%[1]s")370 local must_have_one_flag=()371 local must_have_one_noun=()372 local has_completion_function373 local last_command374 local nouns=()375376 __%[1]s_handle_word
92 unmodified lines
469 format += "\")\n"470 buf.WriteString(fmt.Sprintf(format, name))471}472473// Setup annotations for go completions for registered flags474func prepareCustomAnnotationsForFlags(cmd *Command) {475 for flag := range flagCompletionFunctions {476 // Make sure the completion script calls the __*_go_custom_completion function for477 // every registered flag. We need to do this here (and not when the flag was registered478 // for completion) so that we can know the root command name for the prefix479 // of __<prefix>_go_custom_completion480 if flag.Annotations == nil {481 flag.Annotations = map[string][]string{}482 }483 flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}484 }485}486487func writeFlags(buf *bytes.Buffer, cmd *Command) {488 prepareCustomAnnotationsForFlags(cmd)489 buf.WriteString(` flags=()490 two_word_flags=()491 local_nonpersistent_flags=()492 flags_with_completion=()
56 unmodified lines
549 sort.Sort(sort.StringSlice(cmd.ValidArgs))550 for _, value := range cmd.ValidArgs {551 buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))552 }553 if cmd.ValidArgsFunction != nil {554 buf.WriteString(" has_completion_function=1\n")555 }556}557558func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {559 if len(cmd.Aliases) == 0 {
79 unmodified lines
modified:bash_completions.md+179 added-56 removed
54 unmodified lines
55```5657`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.5859## Creating your own custom functions59## Have the completions code complete your 'nouns'6061### Static completion of nouns6263This method allows you to provide a pre-defined list of completion choices for your nouns using the `validArgs` field.64For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:6566```go67validArgs []string = { "pod", "node", "service", "replicationcontroller" }6869cmd := &cobra.Command{70 Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",71 Short: "Display one or many resources",72 Long: get_long,73 Example: get_example,74 Run: func(cmd *cobra.Command, args []string) {75 err := RunGet(f, out, cmd, args)76 util.CheckErr(err)77 },78 ValidArgs: validArgs,79}80```8182Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like8384```bash85# kubectl get [tab][tab]86node pod replicationcontroller service87```8889### Plural form and shortcuts for nouns9091If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:9293```go94argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }9596cmd := &cobra.Command{97 ...98 ValidArgs: validArgs,99 ArgAliases: argAliases100}101```102103The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by104the completion algorithm if entered manually, e.g. in:105106```bash107# kubectl get rc [tab][tab]108backend frontend database 109```110111Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns112in this example again instead of the replication controllers.113114### Dynamic completion of nouns115116In some cases it is not possible to provide a list of possible completions in advance. Instead, the list of completions must be determined at execution-time. Cobra provides two ways of defining such dynamic completion of nouns. Note that both these methods can be used along-side each other as long as they are not both used for the same command.117118#### 1. Custom completions of nouns written in Go119120In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.121Simplified code from `helm status` looks like:122123```go124cmd := &cobra.Command{125 Use: "status RELEASE_NAME",126 Short: "Display the status of the named release",127 Long: status_long,128 RunE: func(cmd *cobra.Command, args []string) {129 RunGet(args[0])130 },131 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) {132 if len(args) != 0 {133 return nil, cobra.BashCompDirectiveNoFileComp134 }135 return getReleasesFromCluster(toComplete), cobra.BashCompDirectiveNoFileComp136 },137}138```139Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.140Notice we put the `ValidArgsFunction` on the `status` subcommand. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like141142```bash143# helm status [tab][tab]144harbor notary rook thanos145```146You may have noticed the use of `cobra.BashCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.BashCompDirectiveNoSpace | cobra.BashCompDirectiveNoFileComp`147```go148// Indicates an error occurred and completions should be ignored.149BashCompDirectiveError150// Indicates that the shell should not add a space after the completion,151// even if there is a single completion provided.152BashCompDirectiveNoSpace153// Indicates that the shell should not provide file completion even when154// no completion is provided.155// This currently does not work for zsh or bash < 4156BashCompDirectiveNoFileComp157// Indicates that the shell will perform its default behavior after completions158// have been provided (this implies !BashCompDirectiveNoSpace && !BashCompDirectiveNoFileComp).159BashCompDirectiveDefault160```161162When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.163164##### Debugging165166Cobra achieves dynamic completions written in Go through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly:167```bash168# helm __complete status har<ENTER>169harbor170:4171Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr172```173***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command:174```bash175# helm __complete status ""<ENTER>176harbor177notary178rook179thanos180:4181Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr182```183Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:184```go185// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE186// is set to a file path) and optionally prints to stderr.187cobra.CompDebug(msg string, printToStdErr bool) {188cobra.CompDebugln(msg string, printToStdErr bool)189190// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE191// is set to a file path) and to stderr.192cobra.CompError(msg string)193cobra.CompErrorln(msg string)194```195***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above.196197#### 2. Custom completions of nouns written in Bash198199This method allows you to inject bash functions into the completion script. Those bash functions are responsible for providing the completion choices for your own completions.200201Some more actual code that works in kubernetes:202203```bash204const (
45 unmodified lines
250```251252The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`__<command-use>_custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!253114## Have the completions code complete your 'nouns'115116In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:117118```go119validArgs []string = { "pod", "node", "service", "replicationcontroller" }120121cmd := &cobra.Command{122 Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",123 Short: "Display one or many resources",124 Long: get_long,125 Example: get_example,126 Run: func(cmd *cobra.Command, args []string) {127 err := RunGet(f, out, cmd, args)128 util.CheckErr(err)129 },130 ValidArgs: validArgs,131}132```133134Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like135136```bash137# kubectl get [tab][tab]138node pod replicationcontroller service139```140141## Plural form and shortcuts for nouns142143If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:144145```go146argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }147148cmd := &cobra.Command{149 ...150 ValidArgs: validArgs,151 ArgAliases: argAliases152}153```154155The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by156the completion algorithm if entered manually, e.g. in:157158```bash159# kubectl get rc [tab][tab]160backend frontend database 161```162163Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns164in this example again instead of the replication controllers.165254## Mark flags as required255256Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.257
40 unmodified lines
298So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.299300# Specify custom flag completion301214Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specify215a custom flag completion function with cobra.BashCompCustom:302As for nouns, Cobra provides two ways of defining dynamic completion of flags. Note that both these methods can be used along-side each other as long as they are not both used for the same flag.303304## 1. Custom completions of flags written in Go305306To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function in the following manner:307308```go309flagName := "output"310cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) {311 return []string{"json", "table", "yaml"}, cobra.BashCompDirectiveDefault312})313```314Notice 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:315316```bash317# helm status --output [tab][tab]318json table yaml319```320321### Debugging322323You can also easily debug your Go completion code for flags:324```bash325# helm __complete status --output ""326json327table328yaml329:4330Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr331```332***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned in the above section.333334## 2. Custom completions of flags written in Bash335336Alternatively, you can use bash code for flag custom completion. Similar to the filename337completion and filtering using `cobra.BashCompFilenameExt`, you can specify338a custom flag completion bash function with `cobra.BashCompCustom`:339340```go341 annotation := make(map[string][]string)342 annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}343344 flag := &pflag.Flag{
3 unmodified lines
348 }349 cmd.Flags().AddFlag(flag)350```351229In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction`352In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`353value, e.g.:354355```bash356__kubectl_get_namespaces()
23 unmodified lines
modified:command.go+7 added
55 unmodified lines
56 Example string5758 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions59 ValidArgs []string60 // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.61 // It is a dynamic version of using ValidArgs.62 // Only one of ValidArgs and ValidArgsFunction can be used for a command.63 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)6465 // Expected arguments66 Args PositionalArgs67
846 unmodified lines
914 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {915 args = os.Args[1:]916 }917918 // initialize the hidden command to be used for bash completion919 c.initCompleteCmd(args)920921 var flags []string922 if c.TraverseChildren {923 cmd, flags, err = c.Traverse(args)924 } else {
710 unmodified lines
added:custom_completions_test.go+385 added
1package cobra23import (4 "bytes"5 "strings"6 "testing"7)89func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {10 if len(args) != 0 {11 return nil, BashCompDirectiveNoFileComp12 }1314 var completions []string15 for _, comp := range []string{"one", "two"} {16 if strings.HasPrefix(comp, toComplete) {17 completions = append(completions, comp)18 }19 }20 return completions, BashCompDirectiveDefault21}2223func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {24 if len(args) != 0 {25 return nil, BashCompDirectiveNoFileComp26 }2728 var completions []string29 for _, comp := range []string{"three", "four"} {30 if strings.HasPrefix(comp, toComplete) {31 completions = append(completions, comp)32 }33 }34 return completions, BashCompDirectiveDefault35}3637func TestValidArgsFuncSingleCmd(t *testing.T) {38 rootCmd := &Command{39 Use: "root",40 ValidArgsFunction: validArgsFunc,41 Run: emptyRun,42 }4344 // Test completing an empty string45 output, err := executeCommand(rootCmd, CompRequestCmd, "")46 if err != nil {47 t.Errorf("Unexpected error: %v", err)48 }4950 expected := strings.Join([]string{51 "one",52 "two",53 ":0",54 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")5556 if output != expected {57 t.Errorf("expected: %q, got: %q", expected, output)58 }5960 // Check completing with a prefix61 output, err = executeCommand(rootCmd, CompRequestCmd, "t")62 if err != nil {63 t.Errorf("Unexpected error: %v", err)64 }6566 expected = strings.Join([]string{67 "two",68 ":0",69 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")7071 if output != expected {72 t.Errorf("expected: %q, got: %q", expected, output)73 }74}7576func TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {77 rootCmd := &Command{78 Use: "root",79 // If we don't specify a value for Args, this test fails.80 // This is only true for a root command without any subcommands, and is caused81 // by the fact that the __complete command becomes a subcommand when there should not be one.82 // The problem is in the implementation of legacyArgs().83 Args: MinimumNArgs(1),84 ValidArgsFunction: validArgsFunc,85 Run: emptyRun,86 }8788 // Check completing with wrong number of args89 output, err := executeCommand(rootCmd, CompRequestCmd, "unexpectedArg", "t")90 if err != nil {91 t.Errorf("Unexpected error: %v", err)92 }9394 expected := strings.Join([]string{95 ":4",96 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")9798 if output != expected {99 t.Errorf("expected: %q, got: %q", expected, output)100 }101}102103func TestValidArgsFuncChildCmds(t *testing.T) {104 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}105 child1Cmd := &Command{106 Use: "child1",107 ValidArgsFunction: validArgsFunc,108 Run: emptyRun,109 }110 child2Cmd := &Command{111 Use: "child2",112 ValidArgsFunction: validArgsFunc2,113 Run: emptyRun,114 }115 rootCmd.AddCommand(child1Cmd, child2Cmd)116117 // Test completion of first sub-command with empty argument118 output, err := executeCommand(rootCmd, CompRequestCmd, "child1", "")119 if err != nil {120 t.Errorf("Unexpected error: %v", err)121 }122123 expected := strings.Join([]string{124 "one",125 "two",126 ":0",127 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")128129 if output != expected {130 t.Errorf("expected: %q, got: %q", expected, output)131 }132133 // Test completion of first sub-command with a prefix to complete134 output, err = executeCommand(rootCmd, CompRequestCmd, "child1", "t")135 if err != nil {136 t.Errorf("Unexpected error: %v", err)137 }138139 expected = strings.Join([]string{140 "two",141 ":0",142 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")143144 if output != expected {145 t.Errorf("expected: %q, got: %q", expected, output)146 }147148 // Check completing with wrong number of args149 output, err = executeCommand(rootCmd, CompRequestCmd, "child1", "unexpectedArg", "t")150 if err != nil {151 t.Errorf("Unexpected error: %v", err)152 }153154 expected = strings.Join([]string{155 ":4",156 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")157158 if output != expected {159 t.Errorf("expected: %q, got: %q", expected, output)160 }161162 // Test completion of second sub-command with empty argument163 output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "")164 if err != nil {165 t.Errorf("Unexpected error: %v", err)166 }167168 expected = strings.Join([]string{169 "three",170 "four",171 ":0",172 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")173174 if output != expected {175 t.Errorf("expected: %q, got: %q", expected, output)176 }177178 output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "t")179 if err != nil {180 t.Errorf("Unexpected error: %v", err)181 }182183 expected = strings.Join([]string{184 "three",185 ":0",186 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")187188 if output != expected {189 t.Errorf("expected: %q, got: %q", expected, output)190 }191192 // Check completing with wrong number of args193 output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "unexpectedArg", "t")194 if err != nil {195 t.Errorf("Unexpected error: %v", err)196 }197198 expected = strings.Join([]string{199 ":4",200 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")201202 if output != expected {203 t.Errorf("expected: %q, got: %q", expected, output)204 }205}206207func TestValidArgsFuncAliases(t *testing.T) {208 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}209 child := &Command{210 Use: "child",211 Aliases: []string{"son", "daughter"},212 ValidArgsFunction: validArgsFunc,213 Run: emptyRun,214 }215 rootCmd.AddCommand(child)216217 // Test completion of first sub-command with empty argument218 output, err := executeCommand(rootCmd, CompRequestCmd, "son", "")219 if err != nil {220 t.Errorf("Unexpected error: %v", err)221 }222223 expected := strings.Join([]string{224 "one",225 "two",226 ":0",227 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")228229 if output != expected {230 t.Errorf("expected: %q, got: %q", expected, output)231 }232233 // Test completion of first sub-command with a prefix to complete234 output, err = executeCommand(rootCmd, CompRequestCmd, "daughter", "t")235 if err != nil {236 t.Errorf("Unexpected error: %v", err)237 }238239 expected = strings.Join([]string{240 "two",241 ":0",242 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")243244 if output != expected {245 t.Errorf("expected: %q, got: %q", expected, output)246 }247248 // Check completing with wrong number of args249 output, err = executeCommand(rootCmd, CompRequestCmd, "son", "unexpectedArg", "t")250 if err != nil {251 t.Errorf("Unexpected error: %v", err)252 }253254 expected = strings.Join([]string{255 ":4",256 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")257258 if output != expected {259 t.Errorf("expected: %q, got: %q", expected, output)260 }261}262263func TestValidArgsFuncInScript(t *testing.T) {264 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}265 child := &Command{266 Use: "child",267 ValidArgsFunction: validArgsFunc,268 Run: emptyRun,269 }270 rootCmd.AddCommand(child)271272 buf := new(bytes.Buffer)273 rootCmd.GenBashCompletion(buf)274 output := buf.String()275276 check(t, output, "has_completion_function=1")277}278279func TestNoValidArgsFuncInScript(t *testing.T) {280 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}281 child := &Command{282 Use: "child",283 Run: emptyRun,284 }285 rootCmd.AddCommand(child)286287 buf := new(bytes.Buffer)288 rootCmd.GenBashCompletion(buf)289 output := buf.String()290291 checkOmit(t, output, "has_completion_function=1")292}293294func TestFlagCompletionInGo(t *testing.T) {295 rootCmd := &Command{296 Use: "root",297 Run: emptyRun,298 }299 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")300 rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {301 completions := []string{}302 for _, comp := range []string{"1", "2", "10"} {303 if strings.HasPrefix(comp, toComplete) {304 completions = append(completions, comp)305 }306 }307 return completions, BashCompDirectiveDefault308 })309 rootCmd.Flags().String("filename", "", "Enter a filename")310 rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {311 completions := []string{}312 for _, comp := range []string{"file.yaml", "myfile.json", "file.xml"} {313 if strings.HasPrefix(comp, toComplete) {314 completions = append(completions, comp)315 }316 }317 return completions, BashCompDirectiveNoSpace | BashCompDirectiveNoFileComp318 })319320 // Test completing an empty string321 output, err := executeCommand(rootCmd, CompRequestCmd, "--introot", "")322 if err != nil {323 t.Errorf("Unexpected error: %v", err)324 }325326 expected := strings.Join([]string{327 "1",328 "2",329 "10",330 ":0",331 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")332333 if output != expected {334 t.Errorf("expected: %q, got: %q", expected, output)335 }336337 // Check completing with a prefix338 output, err = executeCommand(rootCmd, CompRequestCmd, "--introot", "1")339 if err != nil {340 t.Errorf("Unexpected error: %v", err)341 }342343 expected = strings.Join([]string{344 "1",345 "10",346 ":0",347 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")348349 if output != expected {350 t.Errorf("expected: %q, got: %q", expected, output)351 }352353 // Test completing an empty string354 output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "")355 if err != nil {356 t.Errorf("Unexpected error: %v", err)357 }358359 expected = strings.Join([]string{360 "file.yaml",361 "myfile.json",362 "file.xml",363 ":6",364 "Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n")365366 if output != expected {367 t.Errorf("expected: %q, got: %q", expected, output)368 }369370 // Check completing with a prefix371 output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "f")372 if err != nil {373 t.Errorf("Unexpected error: %v", err)374 }375376 expected = strings.Join([]string{377 "file.yaml",378 "file.xml",379 ":6",380 "Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n")381382 if output != expected {383 t.Errorf("expected: %q, got: %q", expected, output)384 }385}
added:custom_completions.go+299 added
1package cobra23import (4 "errors"5 "fmt"6 "os"7 "strings"89 "github.com/spf13/pflag"10)1112// CompRequestCmd is the name of the hidden command that is used to request13// completion results from the program. It is used by the shell completion script.14const CompRequestCmd = "__complete"1516// Global map of flag completion functions.17var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective){}1819// BashCompDirective is a bit map representing the different behaviors the shell20// can be instructed to have once completions have been provided.21type BashCompDirective int2223const (24 // BashCompDirectiveError indicates an error occurred and completions should be ignored.25 BashCompDirectiveError BashCompDirective = 1 << iota2627 // BashCompDirectiveNoSpace indicates that the shell should not add a space28 // after the completion even if there is a single completion provided.29 BashCompDirectiveNoSpace3031 // BashCompDirectiveNoFileComp indicates that the shell should not provide32 // file completion even when no completion is provided.33 // This currently does not work for zsh or bash < 434 BashCompDirectiveNoFileComp3536 // BashCompDirectiveDefault indicates to let the shell perform its default37 // behavior after completions have been provided.38 BashCompDirectiveDefault BashCompDirective = 039)4041// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.42func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)) error {43 flag := c.Flag(flagName)44 if flag == nil {45 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)46 }47 if _, exists := flagCompletionFunctions[flag]; exists {48 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)49 }50 flagCompletionFunctions[flag] = f51 return nil52}5354// Returns a string listing the different directive enabled in the specified parameter55func (d BashCompDirective) string() string {56 var directives []string57 if d&BashCompDirectiveError != 0 {58 directives = append(directives, "BashCompDirectiveError")59 }60 if d&BashCompDirectiveNoSpace != 0 {61 directives = append(directives, "BashCompDirectiveNoSpace")62 }63 if d&BashCompDirectiveNoFileComp != 0 {64 directives = append(directives, "BashCompDirectiveNoFileComp")65 }66 if len(directives) == 0 {67 directives = append(directives, "BashCompDirectiveDefault")68 }6970 if d > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp {71 return fmt.Sprintf("ERROR: unexpected BashCompDirective value: %d", d)72 }73 return strings.Join(directives, ", ")74}7576// Adds a special hidden command that can be used to request custom completions.77func (c *Command) initCompleteCmd(args []string) {78 completeCmd := &Command{79 Use: fmt.Sprintf("%s [command-line]", CompRequestCmd),80 DisableFlagsInUseLine: true,81 Hidden: true,82 DisableFlagParsing: true,83 Args: MinimumNArgs(1),84 Short: "Request shell completion choices for the specified command-line",85 Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",86 "to request completion choices for the specified command-line.", CompRequestCmd),87 Run: func(cmd *Command, args []string) {88 finalCmd, completions, directive, err := cmd.getCompletions(args)89 if err != nil {90 CompErrorln(err.Error())91 // Keep going for multiple reasons:92 // 1- There could be some valid completions even though there was an error93 // 2- Even without completions, we need to print the directive94 }9596 for _, comp := range completions {97 // Print each possible completion to stdout for the completion script to consume.98 fmt.Fprintln(finalCmd.OutOrStdout(), comp)99 }100101 if directive > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp {102 directive = BashCompDirectiveDefault103 }104105 // As the last printout, print the completion directive for the completion script to parse.106 // The directive integer must be that last character following a single colon (:).107 // The completion script expects :<directive>108 fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)109110 // Print some helpful info to stderr for the user to understand.111 // Output from stderr must be ignored by the completion script.112 fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())113 },114 }115 c.AddCommand(completeCmd)116 subCmd, _, err := c.Find(args)117 if err != nil || subCmd.Name() != CompRequestCmd {118 // Only create this special command if it is actually being called.119 // This reduces possible side-effects of creating such a command;120 // for example, having this command would cause problems to a121 // cobra program that only consists of the root command, since this122 // command would cause the root command to suddenly have a subcommand.123 c.RemoveCommand(completeCmd)124 }125}126127func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDirective, error) {128 var completions []string129130 // The last argument, which is not completely typed by the user,131 // should not be part of the list of arguments132 toComplete := args[len(args)-1]133 trimmedArgs := args[:len(args)-1]134135 // Find the real command for which completion must be performed136 finalCmd, finalArgs, err := c.Root().Find(trimmedArgs)137 if err != nil {138 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>139 return c, completions, BashCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)140 }141142 var flag *pflag.Flag143 if !finalCmd.DisableFlagParsing {144 // We only do flag completion if we are allowed to parse flags145 // This is important for commands which have requested to do their own flag completion.146 flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete)147 if err != nil {148 // Error while attempting to parse flags149 return finalCmd, completions, BashCompDirectiveDefault, err150 }151 }152153 // Parse the flags and extract the arguments to prepare for calling the completion function154 if err = finalCmd.ParseFlags(finalArgs); err != nil {155 return finalCmd, completions, BashCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())156 }157158 // We only remove the flags from the arguments if DisableFlagParsing is not set.159 // This is important for commands which have requested to do their own flag completion.160 if !finalCmd.DisableFlagParsing {161 finalArgs = finalCmd.Flags().Args()162 }163164 // Find the completion function for the flag or command165 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)166 if flag != nil {167 completionFn = flagCompletionFunctions[flag]168 } else {169 completionFn = finalCmd.ValidArgsFunction170 }171 if completionFn == nil {172 // Go custom completion not supported/needed for this flag or command173 return finalCmd, completions, BashCompDirectiveDefault, nil174 }175176 // Call the registered completion function to get the completions177 comps, directive := completionFn(finalCmd, finalArgs, toComplete)178 completions = append(completions, comps...)179 return finalCmd, completions, directive, nil180}181182func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {183 var flagName string184 trimmedArgs := args185 flagWithEqual := false186 if isFlagArg(lastArg) {187 if index := strings.Index(lastArg, "="); index >= 0 {188 flagName = strings.TrimLeft(lastArg[:index], "-")189 lastArg = lastArg[index+1:]190 flagWithEqual = true191 } else {192 return nil, nil, "", errors.New("Unexpected completion request for flag")193 }194 }195196 if len(flagName) == 0 {197 if len(args) > 0 {198 prevArg := args[len(args)-1]199 if isFlagArg(prevArg) {200 // Only consider the case where the flag does not contain an =.201 // If the flag contains an = it means it has already been fully processed,202 // so we don't need to deal with it here.203 if index := strings.Index(prevArg, "="); index < 0 {204 flagName = strings.TrimLeft(prevArg, "-")205206 // Remove the uncompleted flag or else there could be an error created207 // for an invalid value for that flag208 trimmedArgs = args[:len(args)-1]209 }210 }211 }212 }213214 if len(flagName) == 0 {215 // Not doing flag completion216 return nil, trimmedArgs, lastArg, nil217 }218219 flag := findFlag(finalCmd, flagName)220 if flag == nil {221 // Flag not supported by this command, nothing to complete222 err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)223 return nil, nil, "", err224 }225226 if !flagWithEqual {227 if len(flag.NoOptDefVal) != 0 {228 // We had assumed dealing with a two-word flag but the flag is a boolean flag.229 // In that case, there is no value following it, so we are not really doing flag completion.230 // Reset everything to do noun completion.231 trimmedArgs = args232 flag = nil233 }234 }235236 return flag, trimmedArgs, lastArg, nil237}238239func findFlag(cmd *Command, name string) *pflag.Flag {240 flagSet := cmd.Flags()241 if len(name) == 1 {242 // First convert the short flag into a long flag243 // as the cmd.Flag() search only accepts long flags244 if short := flagSet.ShorthandLookup(name); short != nil {245 name = short.Name246 } else {247 set := cmd.InheritedFlags()248 if short = set.ShorthandLookup(name); short != nil {249 name = short.Name250 } else {251 return nil252 }253 }254 }255 return cmd.Flag(name)256}257258// CompDebug prints the specified string to the same file as where the259// completion script prints its logs.260// Note that completion printouts should never be on stdout as they would261// be wrongly interpreted as actual completion choices by the completion script.262func CompDebug(msg string, printToStdErr bool) {263 msg = fmt.Sprintf("[Debug] %s", msg)264265 // Such logs are only printed when the user has set the environment266 // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.267 if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {268 f, err := os.OpenFile(path,269 os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)270 if err == nil {271 defer f.Close()272 f.WriteString(msg)273 }274 }275276 if printToStdErr {277 // Must print to stderr for this not to be read by the completion script.278 fmt.Fprintf(os.Stderr, msg)279 }280}281282// CompDebugln prints the specified string with a newline at the end283// to the same file as where the completion script prints its logs.284// Such logs are only printed when the user has set the environment285// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.286func CompDebugln(msg string, printToStdErr bool) {287 CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)288}289290// CompError prints the specified completion message to stderr.291func CompError(msg string) {292 msg = fmt.Sprintf("[Error] %s", msg)293 CompDebug(msg, true)294}295296// CompErrorln prints the specified completion message to stderr with a newline at the end.297func CompErrorln(msg string) {298 CompError(fmt.Sprintf("%s\n", msg))299}