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.
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
Provenance
- Commit
b80aeb1- Tree
8835cef- Author
Marc Khouzam <marc.khouzam@montreal.ca>- Committer
GitHub <noreply@github.com>- Parent
138b98f
5 files changed+955 added−57 removed
modified:bash_completions.go+85 added-1 removed
56 unmodified lines57 done58 return 159 }60 61+__%[1]s_handle_go_custom_completion()62+{63+ __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"64+65+ local out requestComp lastParam lastChar comp directive args66+67+ # 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[*]}"71+72+ lastParam=${words[$((${#words[@]}-1))]}73+ lastChar=${lastParam:$((${#lastParam}-1)):1}74+ __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"75+76+ 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+ fi82+83+ __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"84+ # Use eval to handle any environment variables and such85+ out=$(eval "${requestComp}" 2>/dev/null)86+87+ # 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[*]}"97+98+ 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+ fi115+116+ while IFS='' read -r comp; do117+ COMPREPLY+=("$comp")118+ done < <(compgen -W "${out[*]}" -- "$cur")119+ fi120+}121+122 __%[1]s_handle_reply()123 {124 __%[1]s_debug "${FUNCNAME[0]}"125 local comp55 unmodified lines181 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 fi150 unmodified lines343 fi344 __%[1]s_handle_word345 }346 282-`, name))347+`, name, CompRequestCmd, BashCompDirectiveError, BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp))348 }349 350 func writePostscript(buf *bytes.Buffer, name string) {351 name = strings.Replace(name, ":", "__", -1)16 unmodified lines368 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=()375 376 __%[1]s_handle_word92 unmodified lines469 format += "\")\n"470 buf.WriteString(fmt.Sprintf(format, name))471 }472 473+// Setup annotations for go completions for registered flags474+func 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+}486+487 func 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 lines549 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 }557 558 func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {559 if len(cmd.Aliases) == 0 {79 unmodified linesmodified:bash_completions.md+179 added-56 removed
54 unmodified lines55 ```56 57 `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.58 59-## Creating your own custom functions59+## Have the completions code complete your 'nouns'60 61+### Static completion of nouns62+63+This method allows you to provide a pre-defined list of completion choices for your nouns using the `validArgs` field.64+For 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:65+66+```go67+validArgs []string = { "pod", "node", "service", "replicationcontroller" }68+69+cmd := &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+```81+82+Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like83+84+```bash85+# kubectl get [tab][tab]86+node pod replicationcontroller service87+```88+89+### Plural form and shortcuts for nouns90+91+If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:92+93+```go94+argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }95+96+cmd := &cobra.Command{97+ ...98+ ValidArgs: validArgs,99+ ArgAliases: argAliases100+}101+```102+103+The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by104+the completion algorithm if entered manually, e.g. in:105+106+```bash107+# kubectl get rc [tab][tab]108+backend frontend database 109+```110+111+Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns112+in this example again instead of the replication controllers.113+114+### Dynamic completion of nouns115+116+In 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.117+118+#### 1. Custom completions of nouns written in Go119+120+In 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.121+Simplified code from `helm status` looks like:122+123+```go124+cmd := &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+```139+Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.140+Notice 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 like141+142+```bash143+# helm status [tab][tab]144+harbor notary rook thanos145+```146+You 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.149+BashCompDirectiveError150+// Indicates that the shell should not add a space after the completion,151+// even if there is a single completion provided.152+BashCompDirectiveNoSpace153+// 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 < 4156+BashCompDirectiveNoFileComp157+// Indicates that the shell will perform its default behavior after completions158+// have been provided (this implies !BashCompDirectiveNoSpace && !BashCompDirectiveNoFileComp).159+BashCompDirectiveDefault160+```161+162+When 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.163+164+##### Debugging165+166+Cobra 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>169+harbor170+:4171+Completion 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>176+harbor177+notary178+rook179+thanos180+:4181+Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr182+```183+Calling 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.187+cobra.CompDebug(msg string, printToStdErr bool) {188+cobra.CompDebugln(msg string, printToStdErr bool)189+190+// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE191+// is set to a file path) and to stderr.192+cobra.CompError(msg string)193+cobra.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.196+197+#### 2. Custom completions of nouns written in Bash198+199+This 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.200+201 Some more actual code that works in kubernetes:202 203 ```bash204 const (45 unmodified lines250 ```251 252 The `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!253 114-## Have the completions code complete your 'nouns'115-116-In 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:117-118-```go119-validArgs []string = { "pod", "node", "service", "replicationcontroller" }120-121-cmd := &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-```133-134-Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like135-136-```bash137-# kubectl get [tab][tab]138-node pod replicationcontroller service139-```140-141-## Plural form and shortcuts for nouns142-143-If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:144-145-```go146-argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }147-148-cmd := &cobra.Command{149- ...150- ValidArgs: validArgs,151- ArgAliases: argAliases152-}153-```154-155-The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by156-the completion algorithm if entered manually, e.g. in:157-158-```bash159-# kubectl get rc [tab][tab]160-backend frontend database 161-```162-163-Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns164-in this example again instead of the replication controllers.165-254 ## Mark flags as required255 256 Most 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 lines298 So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.299 300 # Specify custom flag completion301 214-Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specify215-a custom flag completion function with cobra.BashCompCustom:302+As 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.303 304+## 1. Custom completions of flags written in Go305+306+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 in the following manner:307+308 ```go309+flagName := "output"310+cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) {311+ return []string{"json", "table", "yaml"}, cobra.BashCompDirectiveDefault312+})313+```314+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:315+316+```bash317+# helm status --output [tab][tab]318+json table yaml319+```320+321+### Debugging322+323+You can also easily debug your Go completion code for flags:324+```bash325+# helm __complete status --output ""326+json327+table328+yaml329+:4330+Completion 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.333+334+## 2. Custom completions of flags written in Bash335+336+Alternatively, you can use bash code for flag custom completion. Similar to the filename337+completion and filtering using `cobra.BashCompFilenameExt`, you can specify338+a custom flag completion bash function with `cobra.BashCompCustom`:339+340+```go341 annotation := make(map[string][]string)342 annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}343 344 flag := &pflag.Flag{3 unmodified lines348 }349 cmd.Flags().AddFlag(flag)350 ```351 229-In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction`352+In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`353 value, e.g.:354 355 ```bash356 __kubectl_get_namespaces()23 unmodified linesmodified:command.go+7 added
55 unmodified lines56 Example string57 58 // 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)64 65 // Expected arguments66 Args PositionalArgs67 846 unmodified lines914 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {915 args = os.Args[1:]916 }917 918+ // initialize the hidden command to be used for bash completion919+ c.initCompleteCmd(args)920+921 var flags []string922 if c.TraverseChildren {923 cmd, flags, err = c.Traverse(args)924 } else {710 unmodified linesadded:custom_completions_test.go+385 added
1+package cobra2+3+import (4+ "bytes"5+ "strings"6+ "testing"7+)8+9+func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {10+ if len(args) != 0 {11+ return nil, BashCompDirectiveNoFileComp12+ }13+14+ 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+}22+23+func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {24+ if len(args) != 0 {25+ return nil, BashCompDirectiveNoFileComp26+ }27+28+ 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+}36+37+func TestValidArgsFuncSingleCmd(t *testing.T) {38+ rootCmd := &Command{39+ Use: "root",40+ ValidArgsFunction: validArgsFunc,41+ Run: emptyRun,42+ }43+44+ // Test completing an empty string45+ output, err := executeCommand(rootCmd, CompRequestCmd, "")46+ if err != nil {47+ t.Errorf("Unexpected error: %v", err)48+ }49+50+ expected := strings.Join([]string{51+ "one",52+ "two",53+ ":0",54+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")55+56+ if output != expected {57+ t.Errorf("expected: %q, got: %q", expected, output)58+ }59+60+ // Check completing with a prefix61+ output, err = executeCommand(rootCmd, CompRequestCmd, "t")62+ if err != nil {63+ t.Errorf("Unexpected error: %v", err)64+ }65+66+ expected = strings.Join([]string{67+ "two",68+ ":0",69+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")70+71+ if output != expected {72+ t.Errorf("expected: %q, got: %q", expected, output)73+ }74+}75+76+func 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+ }87+88+ // 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+ }93+94+ expected := strings.Join([]string{95+ ":4",96+ "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")97+98+ if output != expected {99+ t.Errorf("expected: %q, got: %q", expected, output)100+ }101+}102+103+func 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)116+117+ // 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+ }122+123+ expected := strings.Join([]string{124+ "one",125+ "two",126+ ":0",127+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")128+129+ if output != expected {130+ t.Errorf("expected: %q, got: %q", expected, output)131+ }132+133+ // 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+ }138+139+ expected = strings.Join([]string{140+ "two",141+ ":0",142+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")143+144+ if output != expected {145+ t.Errorf("expected: %q, got: %q", expected, output)146+ }147+148+ // 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+ }153+154+ expected = strings.Join([]string{155+ ":4",156+ "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")157+158+ if output != expected {159+ t.Errorf("expected: %q, got: %q", expected, output)160+ }161+162+ // 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+ }167+168+ expected = strings.Join([]string{169+ "three",170+ "four",171+ ":0",172+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")173+174+ if output != expected {175+ t.Errorf("expected: %q, got: %q", expected, output)176+ }177+178+ output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "t")179+ if err != nil {180+ t.Errorf("Unexpected error: %v", err)181+ }182+183+ expected = strings.Join([]string{184+ "three",185+ ":0",186+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")187+188+ if output != expected {189+ t.Errorf("expected: %q, got: %q", expected, output)190+ }191+192+ // 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+ }197+198+ expected = strings.Join([]string{199+ ":4",200+ "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")201+202+ if output != expected {203+ t.Errorf("expected: %q, got: %q", expected, output)204+ }205+}206+207+func 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)216+217+ // 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+ }222+223+ expected := strings.Join([]string{224+ "one",225+ "two",226+ ":0",227+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")228+229+ if output != expected {230+ t.Errorf("expected: %q, got: %q", expected, output)231+ }232+233+ // 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+ }238+239+ expected = strings.Join([]string{240+ "two",241+ ":0",242+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")243+244+ if output != expected {245+ t.Errorf("expected: %q, got: %q", expected, output)246+ }247+248+ // 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+ }253+254+ expected = strings.Join([]string{255+ ":4",256+ "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")257+258+ if output != expected {259+ t.Errorf("expected: %q, got: %q", expected, output)260+ }261+}262+263+func 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)271+272+ buf := new(bytes.Buffer)273+ rootCmd.GenBashCompletion(buf)274+ output := buf.String()275+276+ check(t, output, "has_completion_function=1")277+}278+279+func 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)286+287+ buf := new(bytes.Buffer)288+ rootCmd.GenBashCompletion(buf)289+ output := buf.String()290+291+ checkOmit(t, output, "has_completion_function=1")292+}293+294+func 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+ })319+320+ // Test completing an empty string321+ output, err := executeCommand(rootCmd, CompRequestCmd, "--introot", "")322+ if err != nil {323+ t.Errorf("Unexpected error: %v", err)324+ }325+326+ expected := strings.Join([]string{327+ "1",328+ "2",329+ "10",330+ ":0",331+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")332+333+ if output != expected {334+ t.Errorf("expected: %q, got: %q", expected, output)335+ }336+337+ // Check completing with a prefix338+ output, err = executeCommand(rootCmd, CompRequestCmd, "--introot", "1")339+ if err != nil {340+ t.Errorf("Unexpected error: %v", err)341+ }342+343+ expected = strings.Join([]string{344+ "1",345+ "10",346+ ":0",347+ "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")348+349+ if output != expected {350+ t.Errorf("expected: %q, got: %q", expected, output)351+ }352+353+ // Test completing an empty string354+ output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "")355+ if err != nil {356+ t.Errorf("Unexpected error: %v", err)357+ }358+359+ expected = strings.Join([]string{360+ "file.yaml",361+ "myfile.json",362+ "file.xml",363+ ":6",364+ "Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n")365+366+ if output != expected {367+ t.Errorf("expected: %q, got: %q", expected, output)368+ }369+370+ // Check completing with a prefix371+ output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "f")372+ if err != nil {373+ t.Errorf("Unexpected error: %v", err)374+ }375+376+ expected = strings.Join([]string{377+ "file.yaml",378+ "file.xml",379+ ":6",380+ "Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n")381+382+ if output != expected {383+ t.Errorf("expected: %q, got: %q", expected, output)384+ }385+}added:custom_completions.go+299 added
1+package cobra2+3+import (4+ "errors"5+ "fmt"6+ "os"7+ "strings"8+9+ "github.com/spf13/pflag"10+)11+12+// 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.14+const CompRequestCmd = "__complete"15+16+// Global map of flag completion functions.17+var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective){}18+19+// BashCompDirective is a bit map representing the different behaviors the shell20+// can be instructed to have once completions have been provided.21+type BashCompDirective int22+23+const (24+ // BashCompDirectiveError indicates an error occurred and completions should be ignored.25+ BashCompDirectiveError BashCompDirective = 1 << iota26+27+ // BashCompDirectiveNoSpace indicates that the shell should not add a space28+ // after the completion even if there is a single completion provided.29+ BashCompDirectiveNoSpace30+31+ // 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+ BashCompDirectiveNoFileComp35+36+ // BashCompDirectiveDefault indicates to let the shell perform its default37+ // behavior after completions have been provided.38+ BashCompDirectiveDefault BashCompDirective = 039+)40+41+// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.42+func (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+}53+54+// Returns a string listing the different directive enabled in the specified parameter55+func (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+ }69+70+ if d > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp {71+ return fmt.Sprintf("ERROR: unexpected BashCompDirective value: %d", d)72+ }73+ return strings.Join(directives, ", ")74+}75+76+// Adds a special hidden command that can be used to request custom completions.77+func (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+ }95+96+ for _, comp := range completions {97+ // Print each possible completion to stdout for the completion script to consume.98+ fmt.Fprintln(finalCmd.OutOrStdout(), comp)99+ }100+101+ if directive > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp {102+ directive = BashCompDirectiveDefault103+ }104+105+ // 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)109+110+ // 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+}126+127+func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDirective, error) {128+ var completions []string129+130+ // 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]134+135+ // 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+ }141+142+ 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+ }152+153+ // 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+ }157+158+ // 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+ }163+164+ // 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+ }175+176+ // 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+}181+182+func 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+ }195+196+ 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, "-")205+206+ // 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+ }213+214+ if len(flagName) == 0 {215+ // Not doing flag completion216+ return nil, trimmedArgs, lastArg, nil217+ }218+219+ 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+ }225+226+ 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+ }235+236+ return flag, trimmedArgs, lastArg, nil237+}238+239+func 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+}257+258+// 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.262+func CompDebug(msg string, printToStdErr bool) {263+ msg = fmt.Sprintf("[Debug] %s", msg)264+265+ // 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+ }275+276+ 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+}281+282+// 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.286+func CompDebugln(msg string, printToStdErr bool) {287+ CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)288+}289+290+// CompError prints the specified completion message to stderr.291+func CompError(msg string) {292+ msg = fmt.Sprintf("[Error] %s", msg)293+ CompDebug(msg, true)294+}295+296+// CompErrorln prints the specified completion message to stderr with a newline at the end.297+func CompErrorln(msg string) {298+ CompError(fmt.Sprintf("%s\n", msg))299+}