Skip to content
Myr

Extend Go completions and revamp zsh comp (#1070) (#1070)

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

Replace the current Zsh completion with a Zsh completion solution based on Go completions. This allows to support custom completions (based on Go completions), but also to standardize the behavior of completion across all shells. Also, add support to Go completions for the bash completion annotations: BashCompFilenameExt (including Command.MarkFlagFilename() family) - still supported by zsh BashCompSubdirsInDir - now supported by zsh BashCompOneRequiredFlag (including Command.MarkFlagRequired() family) - now supported by zsh and fish Finally, remove the suggestin of the = form of flag completion. The = form is supported, but it will not be suggested to avoid having duplicated suggestions.

authored by Marc Khouzam · committed by GitHub · parent 0431872 · Browse files · 13 files+2222 added−1212 removed
This commit

State

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

Diff stats

13 files+2222 added−1212 removed

  • other:+2222 added−1212 removed

13 files+2222 added−1212 removed

modified:bash_completions.go+38 added-4 removed
60 unmodified lines
61__%[1]s_handle_go_custom_completion()62{63 __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"6465 local shellCompDirectiveError=%[3]d66 local shellCompDirectiveNoSpace=%[4]d67 local shellCompDirectiveNoFileComp=%[5]d68 local shellCompDirectiveFilterFileExt=%[6]d69 local shellCompDirectiveFilterDirs=%[7]d7071 local out requestComp lastParam lastChar comp directive args7273 # Prepare the command to request completions for the program.74 # Calling ${words[0]} instead of directly %[1]s allows to handle aliases
25 unmodified lines
100 fi101 __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"102 __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"10398 if [ $((directive & %[3]d)) -ne 0 ]; then104 if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then105 # Error code. No completion.106 __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"107 return108 else103 if [ $((directive & %[4]d)) -ne 0 ]; then109 if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then110 if [[ $(type -t compopt) = "builtin" ]]; then111 __%[1]s_debug "${FUNCNAME[0]}: activating no space"112 compopt -o nospace113 fi114 fi109 if [ $((directive & %[5]d)) -ne 0 ]; then115 if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then116 if [[ $(type -t compopt) = "builtin" ]]; then117 __%[1]s_debug "${FUNCNAME[0]}: activating no file completion"118 compopt +o default119 fi120 fi121 fi122123 if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then124 # File extension filtering125 local fullFilter filter filteringCmd126 # Do not use quotes around the $out variable or else newline127 # characters will be kept.128 for filter in ${out[*]}; do129 fullFilter+="$filter|"130 done131132 filteringCmd="_filedir $fullFilter"133 __%[1]s_debug "File filtering command: $filteringCmd"134 $filteringCmd135 elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then136 # File completion for directories only137 local subDir138 # Use printf to strip any trailing newline139 subdir=$(printf "%%s" "${out[0]}")140 if [ -n "$subdir" ]; then141 __%[1]s_debug "Listing directories in $subdir"142 __%[1]s_handle_subdirs_in_dir_flag "$subdir"143 else144 __%[1]s_debug "Listing directories in ."145 _filedir -d146 fi147 else148 while IFS='' read -r comp; do149 COMPREPLY+=("$comp")150 done < <(compgen -W "${out[*]}" -- "$cur")151 fi
222 unmodified lines
374 fi375 __%[1]s_handle_word376}377346`, name, ShellCompNoDescRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))378`, name, ShellCompNoDescRequestCmd,379 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,380 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))381}382383func writePostscript(buf *bytes.Buffer, name string) {384 name = strings.Replace(name, ":", "__", -1)
290 unmodified lines
modified:bash_completions.md+7 added-299 removed
1# Generating Bash Completions For Your Own cobra.Command1# Generating Bash Completions For Your cobra.Command23If you are using the generator you can create a completion command by running3Please refer to [Shell Completions](shell_completions.md) for details.45```bash6cobra add completion7```5## Bash legacy dynamic completions69Update the help text show how to install the bash_completion Linux show here [Kubectl docs show mac options](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)7For backwards-compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution.811Writing the shell script to stdout allows the most flexible use.9The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions.1013```go14// completionCmd represents the completion command15var completionCmd = &cobra.Command{16 Use: "completion",17 Short: "Generates bash completion scripts",18 Long: `To load completion run11Some code that works in kubernetes:1220. <(bitbucket completion)2122To configure your bash shell to load completions for each session add to your bashrc2324# ~/.bashrc or ~/.profile25. <(bitbucket completion)26`,27 Run: func(cmd *cobra.Command, args []string) {28 rootCmd.GenBashCompletion(os.Stdout);29 },30}31```3233**Note:** The cobra generator may include messages printed to stdout for example if the config file is loaded, this will break the auto complete script343536## Example from kubectl3738Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:3940```go41package main4243import (44 "io/ioutil"45 "os"4647 "k8s.io/kubernetes/pkg/kubectl/cmd"48 "k8s.io/kubernetes/pkg/kubectl/cmd/util"49)5051func main() {52 kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)53 kubectl.GenBashCompletionFile("out.sh")54}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## 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 like8313```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**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.119120#### 1. Custom completions of nouns written in Go121122In 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.123Simplified code from `helm status` looks like:124125```go126cmd := &cobra.Command{127 Use: "status RELEASE_NAME",128 Short: "Display the status of the named release",129 Long: status_long,130 RunE: func(cmd *cobra.Command, args []string) {131 RunGet(args[0])132 },133 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {134 if len(args) != 0 {135 return nil, cobra.ShellCompDirectiveNoFileComp136 }137 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp138 },139}140```141Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.142Notice 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 like143144```bash145# helm status [tab][tab]146harbor notary rook thanos147```148You may have noticed the use of `cobra.ShellCompDirective`. 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.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`149```go150// Indicates an error occurred and completions should be ignored.151ShellCompDirectiveError152// Indicates that the shell should not add a space after the completion,153// even if there is a single completion provided.154ShellCompDirectiveNoSpace155// Indicates that the shell should not provide file completion even when156// no completion is provided.157// This currently does not work for zsh or bash < 4158ShellCompDirectiveNoFileComp159// Indicates that the shell will perform its default behavior after completions160// have been provided (this implies !ShellCompDirectiveNoSpace && !ShellCompDirectiveNoFileComp).161ShellCompDirectiveDefault162```163164When 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.165166##### Debugging167168Cobra 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:169```bash170# helm __complete status har<ENTER>171harbor172:4173Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr174```175***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command:176```bash177# helm __complete status ""<ENTER>178harbor179notary180rook181thanos182:4183Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr184```185Calling 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:186```go187// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE188// is set to a file path) and optionally prints to stderr.189cobra.CompDebug(msg string, printToStdErr bool) {190cobra.CompDebugln(msg string, printToStdErr bool)191192// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE193// is set to a file path) and to stderr.194cobra.CompError(msg string)195cobra.CompErrorln(msg string)196```197***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.198199#### 2. Custom completions of nouns written in Bash200201This 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.202203Some more actual code that works in kubernetes:204205```bash14const (15 bash_completion_func = `__kubectl_parse_get()16{17 local kubectl_output out
42 unmodified lines
60```6162The `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!63256## Mark flags as required64Similarly, for flags:65258Most 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.25966```go261cmd.MarkFlagRequired("pod")262cmd.MarkFlagRequired("container")263```264265and you'll get something like266267```bash268# kubectl exec [tab][tab][tab]269-c --container= -p --pod= 270```271272# Specify valid filename extensions for flags that take a filename273274In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.275276```go277 annotations := []string{"json", "yaml", "yml"}67 annotation := make(map[string][]string)279 annotation[cobra.BashCompFilenameExt] = annotations280281 flag := &pflag.Flag{282 Name: "filename",283 Shorthand: "f",284 Usage: usage,285 Value: value,286 DefValue: value.String(),287 Annotations: annotation,288 }289 cmd.Flags().AddFlag(flag)290```291292Now when you run a command with this filename flag you'll get something like293294```bash295# kubectl create -f 296test/ example/ rpmbuild/297hello.yml test.json298```299300So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.301302# Specify custom flag completion303304As 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.305306**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.307308## 1. Custom completions of flags written in Go309310To 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:311312```go313flagName := "output"314cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {315 return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault316})317```318Notice 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:319320```bash321# helm status --output [tab][tab]322json table yaml323```324325### Debugging326327You can also easily debug your Go completion code for flags:328```bash329# helm __complete status --output ""330json331table332yaml333:4334Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr335```336***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.337338## 2. Custom completions of flags written in Bash339340Alternatively, you can use bash code for flag custom completion. Similar to the filename341completion and filtering using `cobra.BashCompFilenameExt`, you can specify342a custom flag completion bash function with `cobra.BashCompCustom`:343344```go345 annotation := make(map[string][]string)68 annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}6970 flag := &pflag.Flag{71 Name: "namespace",
16 unmodified lines
88 COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )89 fi90}91```370# Using bash aliases for commands371372You can also configure the `bash aliases` for the commands and they will also support completions.373374```bash375alias aliasname=origcommand376complete -o default -F __start_origcommand aliasname377378# and now when you run `aliasname` completion will make379# suggestions as it did for `origcommand`.380381$) aliasname <tab><tab>382completion firstcommand secondcommand383```
modified:custom_completions_test.go+1236 added-2 removed
32 unmodified lines
33 }34 return completions, ShellCompDirectiveDefault35}3637func TestCmdNameCompletionInGo(t *testing.T) {38 rootCmd := &Command{39 Use: "root",40 Run: emptyRun,41 }42 childCmd1 := &Command{43 Use: "firstChild",44 Short: "First command",45 Run: emptyRun,46 }47 childCmd2 := &Command{48 Use: "secondChild",49 Run: emptyRun,50 }51 hiddenCmd := &Command{52 Use: "testHidden",53 Hidden: true, // Not completed54 Run: emptyRun,55 }56 deprecatedCmd := &Command{57 Use: "testDeprecated",58 Deprecated: "deprecated", // Not completed59 Run: emptyRun,60 }61 aliasedCmd := &Command{62 Use: "aliased",63 Short: "A command with aliases",64 Aliases: []string{"testAlias", "testSynonym"}, // Not completed65 Run: emptyRun,66 }6768 rootCmd.AddCommand(childCmd1, childCmd2, hiddenCmd, deprecatedCmd, aliasedCmd)6970 // Test that sub-command names are completed71 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")72 if err != nil {73 t.Errorf("Unexpected error: %v", err)74 }7576 expected := strings.Join([]string{77 "aliased",78 "firstChild",79 "help",80 "secondChild",81 ":4",82 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")8384 if output != expected {85 t.Errorf("expected: %q, got: %q", expected, output)86 }8788 // Test that sub-command names are completed with prefix89 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "s")90 if err != nil {91 t.Errorf("Unexpected error: %v", err)92 }9394 expected = strings.Join([]string{95 "secondChild",96 ":4",97 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")9899 if output != expected {100 t.Errorf("expected: %q, got: %q", expected, output)101 }102103 // Test that even with no valid sub-command matches, hidden, deprecated and104 // aliases are not completed105 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "test")106 if err != nil {107 t.Errorf("Unexpected error: %v", err)108 }109110 expected = strings.Join([]string{111 ":4",112 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")113114 if output != expected {115 t.Errorf("expected: %q, got: %q", expected, output)116 }117118 // Test that sub-command names are completed with description119 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "")120 if err != nil {121 t.Errorf("Unexpected error: %v", err)122 }123124 expected = strings.Join([]string{125 "aliased\tA command with aliases",126 "firstChild\tFirst command",127 "help\tHelp about any command",128 "secondChild",129 ":4",130 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")131132 if output != expected {133 t.Errorf("expected: %q, got: %q", expected, output)134 }135}136137func TestNoCmdNameCompletionInGo(t *testing.T) {138 rootCmd := &Command{139 Use: "root",140 Run: emptyRun,141 }142 childCmd1 := &Command{143 Use: "childCmd1",144 Short: "First command",145 Args: MinimumNArgs(0),146 Run: emptyRun,147 }148 rootCmd.AddCommand(childCmd1)149 childCmd1.PersistentFlags().StringP("persistent", "p", "", "persistent flag")150 persistentFlag := childCmd1.PersistentFlags().Lookup("persistent")151 childCmd1.Flags().StringP("nonPersistent", "n", "", "non-persistent flag")152 nonPersistentFlag := childCmd1.Flags().Lookup("nonPersistent")153154 childCmd2 := &Command{155 Use: "childCmd2",156 Run: emptyRun,157 }158 childCmd1.AddCommand(childCmd2)159160 // Test that sub-command names are not completed if there is an argument already161 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "arg1", "")162 if err != nil {163 t.Errorf("Unexpected error: %v", err)164 }165166 expected := strings.Join([]string{167 ":0",168 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")169170 if output != expected {171 t.Errorf("expected: %q, got: %q", expected, output)172 }173174 // Test that sub-command names are not completed if a local non-persistent flag is present175 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--nonPersistent", "value", "")176 if err != nil {177 t.Errorf("Unexpected error: %v", err)178 }179 // Reset the flag for the next command180 nonPersistentFlag.Changed = false181182 expected = strings.Join([]string{183 ":0",184 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")185186 if output != expected {187 t.Errorf("expected: %q, got: %q", expected, output)188 }189190 // Test that sub-command names are not completed if a local non-persistent short flag is present191 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-n", "value", "")192 if err != nil {193 t.Errorf("Unexpected error: %v", err)194 }195 // Reset the flag for the next command196 nonPersistentFlag.Changed = false197198 expected = strings.Join([]string{199 ":0",200 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")201202 if output != expected {203 t.Errorf("expected: %q, got: %q", expected, output)204 }205206 // Test that sub-command names are completed with a persistent flag207 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--persistent", "value", "")208 if err != nil {209 t.Errorf("Unexpected error: %v", err)210 }211 // Reset the flag for the next command212 persistentFlag.Changed = false213214 expected = strings.Join([]string{215 "childCmd2",216 ":4",217 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")218219 if output != expected {220 t.Errorf("expected: %q, got: %q", expected, output)221 }222223 // Test that sub-command names are completed with a persistent short flag224 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-p", "value", "")225 if err != nil {226 t.Errorf("Unexpected error: %v", err)227 }228 // Reset the flag for the next command229 persistentFlag.Changed = false230231 expected = strings.Join([]string{232 "childCmd2",233 ":4",234 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")235236 if output != expected {237 t.Errorf("expected: %q, got: %q", expected, output)238 }239}240241func TestValidArgsCompletionInGo(t *testing.T) {242 rootCmd := &Command{243 Use: "root",244 ValidArgs: []string{"one", "two", "three"},245 Args: MinimumNArgs(1),246 }247248 // Test that validArgs are completed249 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")250 if err != nil {251 t.Errorf("Unexpected error: %v", err)252 }253254 expected := strings.Join([]string{255 "one",256 "two",257 "three",258 ":4",259 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")260261 if output != expected {262 t.Errorf("expected: %q, got: %q", expected, output)263 }264265 // Test that validArgs are completed with prefix266 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "o")267 if err != nil {268 t.Errorf("Unexpected error: %v", err)269 }270271 expected = strings.Join([]string{272 "one",273 ":4",274 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")275276 if output != expected {277 t.Errorf("expected: %q, got: %q", expected, output)278 }279280 // Test that validArgs don't repeat281 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "one", "")282 if err != nil {283 t.Errorf("Unexpected error: %v", err)284 }285286 expected = strings.Join([]string{287 ":0",288 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")289290 if output != expected {291 t.Errorf("expected: %q, got: %q", expected, output)292 }293}294295func TestValidArgsAndCmdCompletionInGo(t *testing.T) {296 rootCmd := &Command{297 Use: "root",298 ValidArgs: []string{"one", "two"},299 Run: emptyRun,300 }301302 childCmd := &Command{303 Use: "thechild",304 Run: emptyRun,305 }306307 rootCmd.AddCommand(childCmd)308309 // Test that both sub-commands and validArgs are completed310 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")311 if err != nil {312 t.Errorf("Unexpected error: %v", err)313 }314315 expected := strings.Join([]string{316 "help",317 "thechild",318 "one",319 "two",320 ":4",321 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")322323 if output != expected {324 t.Errorf("expected: %q, got: %q", expected, output)325 }326327 // Test that both sub-commands and validArgs are completed with prefix328 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")329 if err != nil {330 t.Errorf("Unexpected error: %v", err)331 }332333 expected = strings.Join([]string{334 "thechild",335 "two",336 ":4",337 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")338339 if output != expected {340 t.Errorf("expected: %q, got: %q", expected, output)341 }342}343344func TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) {345 rootCmd := &Command{346 Use: "root",347 ValidArgsFunction: validArgsFunc,348 Run: emptyRun,349 }350351 childCmd := &Command{352 Use: "thechild",353 Short: "The child command",354 Run: emptyRun,355 }356357 rootCmd.AddCommand(childCmd)358359 // Test that both sub-commands and validArgsFunction are completed360 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")361 if err != nil {362 t.Errorf("Unexpected error: %v", err)363 }364365 expected := strings.Join([]string{366 "help",367 "thechild",368 "one",369 "two",370 ":0",371 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")372373 if output != expected {374 t.Errorf("expected: %q, got: %q", expected, output)375 }376377 // Test that both sub-commands and validArgs are completed with prefix378 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")379 if err != nil {380 t.Errorf("Unexpected error: %v", err)381 }382383 expected = strings.Join([]string{384 "thechild",385 "two",386 ":0",387 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")388389 if output != expected {390 t.Errorf("expected: %q, got: %q", expected, output)391 }392393 // Test that both sub-commands and validArgs are completed with description394 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")395 if err != nil {396 t.Errorf("Unexpected error: %v", err)397 }398399 expected = strings.Join([]string{400 "thechild\tThe child command",401 "two\tThe second",402 ":0",403 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")404405 if output != expected {406 t.Errorf("expected: %q, got: %q", expected, output)407 }408}409410func TestFlagNameCompletionInGo(t *testing.T) {411 rootCmd := &Command{412 Use: "root",413 Run: emptyRun,414 }415 childCmd := &Command{416 Use: "childCmd",417 Run: emptyRun,418 }419 rootCmd.AddCommand(childCmd)420421 rootCmd.Flags().IntP("first", "f", -1, "first flag")422 rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")423 childCmd.Flags().String("subFlag", "", "sub flag")424425 // Test that flag names are not shown if the user has not given the '-' prefix426 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")427 if err != nil {428 t.Errorf("Unexpected error: %v", err)429 }430431 expected := strings.Join([]string{432 "childCmd",433 "help",434 ":4",435 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")436437 if output != expected {438 t.Errorf("expected: %q, got: %q", expected, output)439 }440441 // Test that flag names are completed442 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")443 if err != nil {444 t.Errorf("Unexpected error: %v", err)445 }446447 expected = strings.Join([]string{448 "--first",449 "-f",450 "--second",451 "-s",452 ":4",453 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")454455 if output != expected {456 t.Errorf("expected: %q, got: %q", expected, output)457 }458459 // Test that flag names are completed when a prefix is given460 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--f")461 if err != nil {462 t.Errorf("Unexpected error: %v", err)463 }464465 expected = strings.Join([]string{466 "--first",467 ":4",468 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")469470 if output != expected {471 t.Errorf("expected: %q, got: %q", expected, output)472 }473474 // Test that flag names are completed in a sub-cmd475 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")476 if err != nil {477 t.Errorf("Unexpected error: %v", err)478 }479480 expected = strings.Join([]string{481 "--second",482 "-s",483 "--subFlag",484 ":4",485 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")486487 if output != expected {488 t.Errorf("expected: %q, got: %q", expected, output)489 }490}491492func TestFlagNameCompletionInGoWithDesc(t *testing.T) {493 rootCmd := &Command{494 Use: "root",495 Run: emptyRun,496 }497 childCmd := &Command{498 Use: "childCmd",499 Short: "first command",500 Run: emptyRun,501 }502 rootCmd.AddCommand(childCmd)503504 rootCmd.Flags().IntP("first", "f", -1, "first flag")505 rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")506 childCmd.Flags().String("subFlag", "", "sub flag")507508 // Test that flag names are not shown if the user has not given the '-' prefix509 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")510 if err != nil {511 t.Errorf("Unexpected error: %v", err)512 }513514 expected := strings.Join([]string{515 "childCmd\tfirst command",516 "help\tHelp about any command",517 ":4",518 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")519520 if output != expected {521 t.Errorf("expected: %q, got: %q", expected, output)522 }523524 // Test that flag names are completed525 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "-")526 if err != nil {527 t.Errorf("Unexpected error: %v", err)528 }529530 expected = strings.Join([]string{531 "--first\tfirst flag",532 "-f\tfirst flag",533 "--second\tsecond flag",534 "-s\tsecond flag",535 ":4",536 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")537538 if output != expected {539 t.Errorf("expected: %q, got: %q", expected, output)540 }541542 // Test that flag names are completed when a prefix is given543 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--f")544 if err != nil {545 t.Errorf("Unexpected error: %v", err)546 }547548 expected = strings.Join([]string{549 "--first\tfirst flag",550 ":4",551 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")552553 if output != expected {554 t.Errorf("expected: %q, got: %q", expected, output)555 }556557 // Test that flag names are completed in a sub-cmd558 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "childCmd", "-")559 if err != nil {560 t.Errorf("Unexpected error: %v", err)561 }562563 expected = strings.Join([]string{564 "--second\tsecond flag",565 "-s\tsecond flag",566 "--subFlag\tsub flag",567 ":4",568 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")569570 if output != expected {571 t.Errorf("expected: %q, got: %q", expected, output)572 }573}574575func TestFlagNameCompletionRepeat(t *testing.T) {576 rootCmd := &Command{577 Use: "root",578 Run: emptyRun,579 }580 childCmd := &Command{581 Use: "childCmd",582 Short: "first command",583 Run: emptyRun,584 }585 rootCmd.AddCommand(childCmd)586587 rootCmd.Flags().IntP("first", "f", -1, "first flag")588 firstFlag := rootCmd.Flags().Lookup("first")589 rootCmd.Flags().BoolP("second", "s", false, "second flag")590 secondFlag := rootCmd.Flags().Lookup("second")591 rootCmd.Flags().StringArrayP("array", "a", nil, "array flag")592 arrayFlag := rootCmd.Flags().Lookup("array")593 rootCmd.Flags().IntSliceP("slice", "l", nil, "slice flag")594 sliceFlag := rootCmd.Flags().Lookup("slice")595 rootCmd.Flags().BoolSliceP("bslice", "b", nil, "bool slice flag")596 bsliceFlag := rootCmd.Flags().Lookup("bslice")597598 // Test that flag names are not repeated unless they are an array or slice599 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--")600 if err != nil {601 t.Errorf("Unexpected error: %v", err)602 }603 // Reset the flag for the next command604 firstFlag.Changed = false605606 expected := strings.Join([]string{607 "--array",608 "--bslice",609 "--second",610 "--slice",611 ":4",612 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")613614 if output != expected {615 t.Errorf("expected: %q, got: %q", expected, output)616 }617618 // Test that flag names are not repeated unless they are an array or slice619 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--second=false", "--")620 if err != nil {621 t.Errorf("Unexpected error: %v", err)622 }623 // Reset the flag for the next command624 firstFlag.Changed = false625 secondFlag.Changed = false626627 expected = strings.Join([]string{628 "--array",629 "--bslice",630 "--slice",631 ":4",632 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")633634 if output != expected {635 t.Errorf("expected: %q, got: %q", expected, output)636 }637638 // Test that flag names are not repeated unless they are an array or slice639 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--")640 if err != nil {641 t.Errorf("Unexpected error: %v", err)642 }643 // Reset the flag for the next command644 sliceFlag.Changed = false645 arrayFlag.Changed = false646 bsliceFlag.Changed = false647648 expected = strings.Join([]string{649 "--array",650 "--bslice",651 "--first",652 "--second",653 "--slice",654 ":4",655 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")656657 if output != expected {658 t.Errorf("expected: %q, got: %q", expected, output)659 }660661 // Test that flag names are not repeated unless they are an array or slice, using shortname662 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-")663 if err != nil {664 t.Errorf("Unexpected error: %v", err)665 }666 // Reset the flag for the next command667 sliceFlag.Changed = false668 arrayFlag.Changed = false669670 expected = strings.Join([]string{671 "--array",672 "-a",673 "--bslice",674 "-b",675 "--first",676 "-f",677 "--second",678 "-s",679 "--slice",680 "-l",681 ":4",682 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")683684 if output != expected {685 t.Errorf("expected: %q, got: %q", expected, output)686 }687688 // Test that flag names are not repeated unless they are an array or slice, using shortname with prefix689 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-a")690 if err != nil {691 t.Errorf("Unexpected error: %v", err)692 }693 // Reset the flag for the next command694 sliceFlag.Changed = false695 arrayFlag.Changed = false696697 expected = strings.Join([]string{698 "-a",699 ":4",700 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")701702 if output != expected {703 t.Errorf("expected: %q, got: %q", expected, output)704 }705}706707func TestRequiredFlagNameCompletionInGo(t *testing.T) {708 rootCmd := &Command{709 Use: "root",710 ValidArgs: []string{"realArg"},711 Run: emptyRun,712 }713 childCmd := &Command{714 Use: "childCmd",715 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {716 return []string{"subArg"}, ShellCompDirectiveNoFileComp717 },718 Run: emptyRun,719 }720 rootCmd.AddCommand(childCmd)721722 rootCmd.Flags().IntP("requiredFlag", "r", -1, "required flag")723 rootCmd.MarkFlagRequired("requiredFlag")724 requiredFlag := rootCmd.Flags().Lookup("requiredFlag")725726 rootCmd.PersistentFlags().IntP("requiredPersistent", "p", -1, "required persistent")727 rootCmd.MarkPersistentFlagRequired("requiredPersistent")728 requiredPersistent := rootCmd.PersistentFlags().Lookup("requiredPersistent")729730 rootCmd.Flags().StringP("release", "R", "", "Release name")731732 childCmd.Flags().BoolP("subRequired", "s", false, "sub required flag")733 childCmd.MarkFlagRequired("subRequired")734 childCmd.Flags().BoolP("subNotRequired", "n", false, "sub not required flag")735736 // Test that a required flag is suggested even without the - prefix737 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")738 if err != nil {739 t.Errorf("Unexpected error: %v", err)740 }741742 expected := strings.Join([]string{743 "childCmd",744 "help",745 "--requiredFlag",746 "-r",747 "--requiredPersistent",748 "-p",749 "realArg",750 ":4",751 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")752753 if output != expected {754 t.Errorf("expected: %q, got: %q", expected, output)755 }756757 // Test that a required flag is suggested without other flags when using the '-' prefix758 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")759 if err != nil {760 t.Errorf("Unexpected error: %v", err)761 }762763 expected = strings.Join([]string{764 "--requiredFlag",765 "-r",766 "--requiredPersistent",767 "-p",768 ":4",769 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")770771 if output != expected {772 t.Errorf("expected: %q, got: %q", expected, output)773 }774775 // Test that if no required flag matches, the normal flags are suggested776 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--relea")777 if err != nil {778 t.Errorf("Unexpected error: %v", err)779 }780781 expected = strings.Join([]string{782 "--release",783 ":4",784 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")785786 if output != expected {787 t.Errorf("expected: %q, got: %q", expected, output)788 }789790 // Test required flags for sub-commands791 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "")792 if err != nil {793 t.Errorf("Unexpected error: %v", err)794 }795796 expected = strings.Join([]string{797 "--requiredPersistent",798 "-p",799 "--subRequired",800 "-s",801 "subArg",802 ":4",803 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")804805 if output != expected {806 t.Errorf("expected: %q, got: %q", expected, output)807 }808809 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")810 if err != nil {811 t.Errorf("Unexpected error: %v", err)812 }813814 expected = strings.Join([]string{815 "--requiredPersistent",816 "-p",817 "--subRequired",818 "-s",819 ":4",820 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")821822 if output != expected {823 t.Errorf("expected: %q, got: %q", expected, output)824 }825826 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "--subNot")827 if err != nil {828 t.Errorf("Unexpected error: %v", err)829 }830831 expected = strings.Join([]string{832 "--subNotRequired",833 ":4",834 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")835836 if output != expected {837 t.Errorf("expected: %q, got: %q", expected, output)838 }839840 // Test that when a required flag is present, it is not suggested anymore841 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "")842 if err != nil {843 t.Errorf("Unexpected error: %v", err)844 }845 // Reset the flag for the next command846 requiredFlag.Changed = false847848 expected = strings.Join([]string{849 "--requiredPersistent",850 "-p",851 "realArg",852 ":4",853 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")854855 if output != expected {856 t.Errorf("expected: %q, got: %q", expected, output)857 }858859 // Test that when a persistent required flag is present, it is not suggested anymore860 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredPersistent", "1", "")861 if err != nil {862 t.Errorf("Unexpected error: %v", err)863 }864 // Reset the flag for the next command865 requiredPersistent.Changed = false866867 expected = strings.Join([]string{868 "childCmd",869 "help",870 "--requiredFlag",871 "-r",872 "realArg",873 ":4",874 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")875876 if output != expected {877 t.Errorf("expected: %q, got: %q", expected, output)878 }879880 // Test that when all required flags are present, normal completion is done881 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "--requiredPersistent", "1", "")882 if err != nil {883 t.Errorf("Unexpected error: %v", err)884 }885 // Reset the flags for the next command886 requiredFlag.Changed = false887 requiredPersistent.Changed = false888889 expected = strings.Join([]string{890 "realArg",891 ":4",892 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")893894 if output != expected {895 t.Errorf("expected: %q, got: %q", expected, output)896 }897}898899func TestFlagFileExtFilterCompletionInGo(t *testing.T) {900 rootCmd := &Command{901 Use: "root",902 Run: emptyRun,903 }904905 // No extensions. Should be ignored.906 rootCmd.Flags().StringP("file", "f", "", "file flag")907 rootCmd.MarkFlagFilename("file")908909 // Single extension910 rootCmd.Flags().StringP("log", "l", "", "log flag")911 rootCmd.MarkFlagFilename("log", "log")912913 // Multiple extensions914 rootCmd.Flags().StringP("yaml", "y", "", "yaml flag")915 rootCmd.MarkFlagFilename("yaml", "yaml", "yml")916917 // Directly using annotation918 rootCmd.Flags().StringP("text", "t", "", "text flag")919 rootCmd.Flags().SetAnnotation("text", BashCompFilenameExt, []string{"txt"})920921 // Test that the completion logic returns the proper info for the completion922 // script to handle the file filtering923 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--file", "")924 if err != nil {925 t.Errorf("Unexpected error: %v", err)926 }927928 expected := strings.Join([]string{929 ":0",930 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")931932 if output != expected {933 t.Errorf("expected: %q, got: %q", expected, output)934 }935936 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--log", "")937 if err != nil {938 t.Errorf("Unexpected error: %v", err)939 }940941 expected = strings.Join([]string{942 "log",943 ":8",944 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")945946 if output != expected {947 t.Errorf("expected: %q, got: %q", expected, output)948 }949950 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml", "")951 if err != nil {952 t.Errorf("Unexpected error: %v", err)953 }954955 expected = strings.Join([]string{956 "yaml", "yml",957 ":8",958 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")959960 if output != expected {961 t.Errorf("expected: %q, got: %q", expected, output)962 }963964 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml=")965 if err != nil {966 t.Errorf("Unexpected error: %v", err)967 }968969 expected = strings.Join([]string{970 "yaml", "yml",971 ":8",972 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")973974 if output != expected {975 t.Errorf("expected: %q, got: %q", expected, output)976 }977978 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y", "")979 if err != nil {980 t.Errorf("Unexpected error: %v", err)981 }982983 expected = strings.Join([]string{984 "yaml", "yml",985 ":8",986 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")987988 if output != expected {989 t.Errorf("expected: %q, got: %q", expected, output)990 }991992 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y=")993 if err != nil {994 t.Errorf("Unexpected error: %v", err)995 }996997 expected = strings.Join([]string{998 "yaml", "yml",999 ":8",1000 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10011002 if output != expected {1003 t.Errorf("expected: %q, got: %q", expected, output)1004 }10051006 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--text", "")1007 if err != nil {1008 t.Errorf("Unexpected error: %v", err)1009 }10101011 expected = strings.Join([]string{1012 "txt",1013 ":8",1014 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10151016 if output != expected {1017 t.Errorf("expected: %q, got: %q", expected, output)1018 }1019}10201021func TestFlagDirFilterCompletionInGo(t *testing.T) {1022 rootCmd := &Command{1023 Use: "root",1024 Run: emptyRun,1025 }10261027 // Filter directories1028 rootCmd.Flags().StringP("dir", "d", "", "dir flag")1029 rootCmd.MarkFlagDirname("dir")10301031 // Filter directories within a directory1032 rootCmd.Flags().StringP("subdir", "s", "", "subdir")1033 rootCmd.Flags().SetAnnotation("subdir", BashCompSubdirsInDir, []string{"themes"})10341035 // Multiple directory specification get ignored1036 rootCmd.Flags().StringP("manydir", "m", "", "manydir")1037 rootCmd.Flags().SetAnnotation("manydir", BashCompSubdirsInDir, []string{"themes", "colors"})10381039 // Test that the completion logic returns the proper info for the completion1040 // script to handle the directory filtering1041 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--dir", "")1042 if err != nil {1043 t.Errorf("Unexpected error: %v", err)1044 }10451046 expected := strings.Join([]string{1047 ":16",1048 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")10491050 if output != expected {1051 t.Errorf("expected: %q, got: %q", expected, output)1052 }10531054 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-d", "")1055 if err != nil {1056 t.Errorf("Unexpected error: %v", err)1057 }10581059 expected = strings.Join([]string{1060 ":16",1061 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")10621063 if output != expected {1064 t.Errorf("expected: %q, got: %q", expected, output)1065 }10661067 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir", "")1068 if err != nil {1069 t.Errorf("Unexpected error: %v", err)1070 }10711072 expected = strings.Join([]string{1073 "themes",1074 ":16",1075 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")10761077 if output != expected {1078 t.Errorf("expected: %q, got: %q", expected, output)1079 }10801081 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir=")1082 if err != nil {1083 t.Errorf("Unexpected error: %v", err)1084 }10851086 expected = strings.Join([]string{1087 "themes",1088 ":16",1089 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")10901091 if output != expected {1092 t.Errorf("expected: %q, got: %q", expected, output)1093 }10941095 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s", "")1096 if err != nil {1097 t.Errorf("Unexpected error: %v", err)1098 }10991100 expected = strings.Join([]string{1101 "themes",1102 ":16",1103 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11041105 if output != expected {1106 t.Errorf("expected: %q, got: %q", expected, output)1107 }11081109 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s=")1110 if err != nil {1111 t.Errorf("Unexpected error: %v", err)1112 }11131114 expected = strings.Join([]string{1115 "themes",1116 ":16",1117 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11181119 if output != expected {1120 t.Errorf("expected: %q, got: %q", expected, output)1121 }11221123 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--manydir", "")1124 if err != nil {1125 t.Errorf("Unexpected error: %v", err)1126 }11271128 expected = strings.Join([]string{1129 ":16",1130 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11311132 if output != expected {1133 t.Errorf("expected: %q, got: %q", expected, output)1134 }1135}11361137func TestValidArgsFuncSingleCmd(t *testing.T) {1138 rootCmd := &Command{1139 Use: "root",1140 ValidArgsFunction: validArgsFunc,
298 unmodified lines
1439 check(t, output, ShellCompRequestCmd)1440 checkOmit(t, output, ShellCompNoDescRequestCmd)1441}14421443func TestCompleteNoDesCmdInZshScript(t *testing.T) {1444 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1445 child := &Command{1446 Use: "child",1447 ValidArgsFunction: validArgsFunc,1448 Run: emptyRun,1449 }1450 rootCmd.AddCommand(child)14511452 buf := new(bytes.Buffer)1453 rootCmd.GenZshCompletionNoDesc(buf)1454 output := buf.String()14551456 check(t, output, ShellCompNoDescRequestCmd)1457}14581459func TestCompleteCmdInZshScript(t *testing.T) {1460 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1461 child := &Command{1462 Use: "child",1463 ValidArgsFunction: validArgsFunc,1464 Run: emptyRun,1465 }1466 rootCmd.AddCommand(child)14671468 buf := new(bytes.Buffer)1469 rootCmd.GenZshCompletion(buf)1470 output := buf.String()14711472 check(t, output, ShellCompRequestCmd)1473 checkOmit(t, output, ShellCompNoDescRequestCmd)1474}14751476func TestFlagCompletionInGo(t *testing.T) {1477 rootCmd := &Command{1478 Use: "root",1479 Run: emptyRun,
282 unmodified lines
1762 t.Errorf("expected: %q, got: %q", expected, output)1763 }1764}17651766func TestValidArgsNotValidArgsFunc(t *testing.T) {1767 rootCmd := &Command{1768 Use: "root",1769 ValidArgs: []string{"one", "two"},1770 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1771 return []string{"three", "four"}, ShellCompDirectiveNoFileComp1772 },1773 Run: emptyRun,1774 }17751776 // Test that if both ValidArgs and ValidArgsFunction are present1777 // only ValidArgs is considered1778 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1779 if err != nil {1780 t.Errorf("Unexpected error: %v", err)1781 }17821783 expected := strings.Join([]string{1784 "one",1785 "two",1786 ":4",1787 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")17881789 if output != expected {1790 t.Errorf("expected: %q, got: %q", expected, output)1791 }17921793 // Check completing with a prefix1794 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1795 if err != nil {1796 t.Errorf("Unexpected error: %v", err)1797 }17981799 expected = strings.Join([]string{1800 "two",1801 ":4",1802 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18031804 if output != expected {1805 t.Errorf("expected: %q, got: %q", expected, output)1806 }1807}18081809func TestArgAliasesCompletionInGo(t *testing.T) {1810 rootCmd := &Command{1811 Use: "root",1812 Args: OnlyValidArgs,1813 ValidArgs: []string{"one", "two", "three"},1814 ArgAliases: []string{"un", "deux", "trois"},1815 Run: emptyRun,1816 }18171818 // Test that argaliases are not completed when there are validargs that match1819 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1820 if err != nil {1821 t.Errorf("Unexpected error: %v", err)1822 }18231824 expected := strings.Join([]string{1825 "one",1826 "two",1827 "three",1828 ":4",1829 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18301831 if output != expected {1832 t.Errorf("expected: %q, got: %q", expected, output)1833 }18341835 // Test that argaliases are not completed when there are validargs that match using a prefix1836 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1837 if err != nil {1838 t.Errorf("Unexpected error: %v", err)1839 }18401841 expected = strings.Join([]string{1842 "two",1843 "three",1844 ":4",1845 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18461847 if output != expected {1848 t.Errorf("expected: %q, got: %q", expected, output)1849 }18501851 // Test that argaliases are completed when there are no validargs that match1852 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "tr")1853 if err != nil {1854 t.Errorf("Unexpected error: %v", err)1855 }18561857 expected = strings.Join([]string{1858 "trois",1859 ":4",1860 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18611862 if output != expected {1863 t.Errorf("expected: %q, got: %q", expected, output)1864 }1865}18661867func TestCompleteHelp(t *testing.T) {1868 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1869 child1Cmd := &Command{1870 Use: "child1",
20 unmodified lines
1891 expected := strings.Join([]string{1892 "child1",1893 "child2",1894 "help",661 ":0",662 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1895 ":4",1896 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18971898 if output != expected {1899 t.Errorf("expected: %q, got: %q", expected, output)1900 }
33 unmodified lines
modified:custom_completions.go+215 added-62 removed
1package cobra23import (4 "errors"4 "fmt"5 "os"6 "strings"7
28 unmodified lines
36 // file completion even when no completion is provided.37 // This currently does not work for zsh or bash < 438 ShellCompDirectiveNoFileComp3940 // ShellCompDirectiveFilterFileExt indicates that the provided completions41 // should be used as file extension filters.42 // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()43 // is a shortcut to using this directive explicitly. The BashCompFilenameExt44 // annotation can also be used to obtain the same behavior for flags.45 ShellCompDirectiveFilterFileExt4647 // ShellCompDirectiveFilterDirs indicates that only directory names should48 // be provided in file completion. To request directory names within another49 // directory, the returned completions should specify the directory within50 // which to search. The BashCompSubdirsInDir annotation can be used to51 // obtain the same behavior but only for flags.52 ShellCompDirectiveFilterDirs5354 // ===========================================================================5556 // All directives using iota should be above this one.57 // For internal use.58 shellCompDirectiveMaxValue5960 // ShellCompDirectiveDefault indicates to let the shell perform its default61 // behavior after completions have been provided.62 // This one must be last to avoid messing up the iota count.63 ShellCompDirectiveDefault ShellCompDirective = 064)6566// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
20 unmodified lines
87 }88 if d&ShellCompDirectiveNoFileComp != 0 {89 directives = append(directives, "ShellCompDirectiveNoFileComp")90 }91 if d&ShellCompDirectiveFilterFileExt != 0 {92 directives = append(directives, "ShellCompDirectiveFilterFileExt")93 }94 if d&ShellCompDirectiveFilterDirs != 0 {95 directives = append(directives, "ShellCompDirectiveFilterDirs")96 }97 if len(directives) == 0 {98 directives = append(directives, "ShellCompDirectiveDefault")99 }10075 if d > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {101 if d >= shellCompDirectiveMaxValue {102 return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)103 }104 return strings.Join(directives, ", ")105}
24 unmodified lines
130 if noDescriptions {131 // Remove any description that may be included following a tab character.132 comp = strings.Split(comp, "\t")[0]133 }134135 // Finally trim the completion. This is especially important to get rid136 // of a trailing tab when there are no description following it.137 // For example, a sub-command without a description should not be completed138 // with a tab at the end (or else zsh will show a -- following it139 // although there is no description).140 comp = strings.TrimSpace(comp)141142 // Print each possible completion to stdout for the completion script to consume.143 fmt.Fprintln(finalCmd.OutOrStdout(), comp)144 }145112 if directive > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {146 if directive >= shellCompDirectiveMaxValue {147 directive = ShellCompDirectiveDefault148 }149150 // As the last printout, print the completion directive for the completion script to parse.
18 unmodified lines
169 }170}171172func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {139 var completions []string140173 // The last argument, which is not completely typed by the user,174 // should not be part of the list of arguments175 toComplete := args[len(args)-1]176 trimmedArgs := args[:len(args)-1]
1 unmodified line
178 // Find the real command for which completion must be performed179 finalCmd, finalArgs, err := c.Root().Find(trimmedArgs)180 if err != nil {181 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>150 return c, completions, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)182 return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)183 }184185 // Check if we are doing flag value completion before parsing the flags.186 // This is important because if we are completing a flag value, we need to also187 // remove the flag name argument from the list of finalArgs or else the parsing188 // could fail due to an invalid value (incomplete) for the flag.189 flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)190 if err != nil {191 // Error while attempting to parse flags192 return finalCmd, []string{}, ShellCompDirectiveDefault, err193 }194195 // Parse the flags early so we can check if required flags are set196 if err = finalCmd.ParseFlags(finalArgs); err != nil {197 return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())198 }199200 if flag != nil {201 // Check if we are completing a flag value subject to annotations202 if validExts, present := flag.Annotations[BashCompFilenameExt]; present {203 if len(validExts) != 0 {204 // File completion filtered by extensions205 return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil206 }207208 // The annotation requests simple file completion. There is no reason to do209 // that since it is the default behavior anyway. Let's ignore this annotation210 // in case the program also registered a completion function for this flag.211 // Even though it is a mistake on the program's side, let's be nice when we can.212 }213214 if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {215 if len(subDir) == 1 {216 // Directory completion from within a directory217 return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil218 }219 // Directory completion220 return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil221 }222 }223224 // When doing completion of a flag name, as soon as an argument starts with225 // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires155 // the flag to be complete156 if len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {157 // We are completing a flag name158 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {159 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)160 })161 finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {162 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)163 })226 // the flag name to be complete227 if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {228 var completions []string229165 directive := ShellCompDirectiveDefault166 if len(completions) > 0 {167 if strings.HasSuffix(completions[0], "=") {168 directive = ShellCompDirectiveNoSpace230 // First check for required flags231 completions = completeRequireFlags(finalCmd, toComplete)232233 // If we have not found any required flags, only then can we show regular flags234 if len(completions) == 0 {235 doCompleteFlags := func(flag *pflag.Flag) {236 if !flag.Changed ||237 strings.Contains(flag.Value.Type(), "Slice") ||238 strings.Contains(flag.Value.Type(), "Array") {239 // If the flag is not already present, or if it can be specified multiple times (Array or Slice)240 // we suggest it as a completion241 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)242 }243 }244245 // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands246 // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and247 // non-inherited flags.248 finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {249 doCompleteFlags(flag)250 })251 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {252 doCompleteFlags(flag)253 })254 }255256 directive := ShellCompDirectiveNoFileComp257 if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {258 // If there is a single completion, the shell usually adds a space259 // after the completion. We don't want that if the flag ends with an =260 directive = ShellCompDirectiveNoSpace261 }262 return finalCmd, completions, directive, nil263 }264174 var flag *pflag.Flag265 // We only remove the flags from the arguments if DisableFlagParsing is not set.266 // This is important for commands which have requested to do their own flag completion.267 if !finalCmd.DisableFlagParsing {176 // We only do flag completion if we are allowed to parse flags177 // This is important for commands which have requested to do their own flag completion.178 flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete)179 if err != nil {180 // Error while attempting to parse flags181 return finalCmd, completions, ShellCompDirectiveDefault, err182 }268 finalArgs = finalCmd.Flags().Args()269 }270271 var completions []string272 directive := ShellCompDirectiveDefault273 if flag == nil {274 // Check if there are any local, non-persistent flags on the command-line275 foundLocalNonPersistentFlag := false276 localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()277 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {278 if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {279 foundLocalNonPersistentFlag = true280 }281 })282283 // Complete subcommand names, including the help command284 if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {285 // We only complete sub-commands if:286 // - there are no arguments on the command-line and287 // - there are no local, non-peristent flag on the command-line187 for _, subCmd := range finalCmd.Commands() {188 if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {189 if strings.HasPrefix(subCmd.Name(), toComplete) {190 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))288 for _, subCmd := range finalCmd.Commands() {289 if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {290 if strings.HasPrefix(subCmd.Name(), toComplete) {291 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))292 }293 directive = ShellCompDirectiveNoFileComp294 }295 }296 }297298 // Complete required flags even without the '-' prefix299 completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)300301 // Always complete ValidArgs, even if we are completing a subcommand name.302 // This is for commands that have both subcommands and ValidArgs.303 if len(finalCmd.ValidArgs) > 0 {196 // Always complete ValidArgs, even if we are completing a subcommand name.197 // This is for commands that have both subcommands and ValidArgs.198 for _, validArg := range finalCmd.ValidArgs {199 if strings.HasPrefix(validArg, toComplete) {200 completions = append(completions, validArg)304 if len(finalArgs) == 0 {305 // ValidArgs are only for the first argument306 for _, validArg := range finalCmd.ValidArgs {307 if strings.HasPrefix(validArg, toComplete) {308 completions = append(completions, validArg)309 }310 }311 directive = ShellCompDirectiveNoFileComp312313 // If no completions were found within commands or ValidArgs,314 // see if there are any ArgAliases that should be completed.315 if len(completions) == 0 {316 for _, argAlias := range finalCmd.ArgAliases {317 if strings.HasPrefix(argAlias, toComplete) {318 completions = append(completions, argAlias)319 }320 }321 }322 }323324 // If there are ValidArgs specified (even if they don't match), we stop completion.325 // Only one of ValidArgs or ValidArgsFunction can be used for a single command.206 return finalCmd, completions, ShellCompDirectiveNoFileComp, nil326 return finalCmd, completions, directive, nil327 }328209 // Always let the logic continue so as to add any ValidArgsFunction completions,329 // Let the logic continue so as to add any ValidArgsFunction completions,330 // even if we already found sub-commands.331 // This is for commands that have subcommands but also specify a ValidArgsFunction.332 }333214 // Parse the flags and extract the arguments to prepare for calling the completion function215 if err = finalCmd.ParseFlags(finalArgs); err != nil {216 return finalCmd, completions, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())217 }218219 // We only remove the flags from the arguments if DisableFlagParsing is not set.220 // This is important for commands which have requested to do their own flag completion.221 if !finalCmd.DisableFlagParsing {222 finalArgs = finalCmd.Flags().Args()223 }224334 // Find the completion function for the flag or command335 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)336 if flag != nil {337 completionFn = flagCompletionFunctions[flag]338 } else {339 completionFn = finalCmd.ValidArgsFunction340 }232 if completionFn == nil {233 // Go custom completion not supported/needed for this flag or command234 return finalCmd, completions, ShellCompDirectiveDefault, nil341 if completionFn != nil {342 // Go custom completion defined for this flag or command.343 // Call the registered completion function to get the completions.344 var comps []string345 comps, directive = completionFn(finalCmd, finalArgs, toComplete)346 completions = append(completions, comps...)347 }348237 // Call the registered completion function to get the completions238 comps, directive := completionFn(finalCmd, finalArgs, toComplete)239 completions = append(completions, comps...)349 return finalCmd, completions, directive, nil350}351352func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
6 unmodified lines
359 if strings.HasPrefix(flagName, toComplete) {360 // Flag without the =361 completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))362363 // Why suggest both long forms: --flag and --flag= ?364 // This forces the user to *always* have to type either an = or a space after the flag name.365 // Let's be nice and avoid making users have to do that.366 // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.367 // The = form will still work, we just won't suggest it.368 // This also makes the list of suggested flags shorter as we avoid all the = forms.369 //254 if len(flag.NoOptDefVal) == 0 {255 // Flag requires a value, so it can be suffixed with =256 flagName += "="257 completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))258 }370 // if len(flag.NoOptDefVal) == 0 {371 // // Flag requires a value, so it can be suffixed with =372 // flagName += "="373 // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))374 // }375 }376377 flagName = "-" + flag.Shorthand378 if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
2 unmodified lines
381382 return completions383}384385func completeRequireFlags(finalCmd *Command, toComplete string) []string {386 var completions []string387388 doCompleteRequiredFlags := func(flag *pflag.Flag) {389 if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {390 if !flag.Changed {391 // If the flag is not already present, we suggest it as a completion392 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)393 }394 }395 }396397 // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands398 // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and399 // non-inherited flags.400 finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {401 doCompleteRequiredFlags(flag)402 })403 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {404 doCompleteRequiredFlags(flag)405 })406407 return completions408}409410func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {411 if finalCmd.DisableFlagParsing {412 // We only do flag completion if we are allowed to parse flags413 // This is important for commands which have requested to do their own flag completion.414 return nil, args, lastArg, nil415 }416417 var flagName string418 trimmedArgs := args419 flagWithEqual := false273 if isFlagArg(lastArg) {420421 // When doing completion of a flag name, as soon as an argument starts with422 // a '-' we know it is a flag. We cannot use isFlagArg() here as that function423 // requires the flag name to be complete424 if len(lastArg) > 0 && lastArg[0] == '-' {425 if index := strings.Index(lastArg, "="); index >= 0 {426 // Flag with an =427 flagName = strings.TrimLeft(lastArg[:index], "-")428 lastArg = lastArg[index+1:]429 flagWithEqual = true430 } else {279 return nil, nil, "", errors.New("Unexpected completion request for flag")431 // Normal flag completion432 return nil, args, lastArg, nil433 }434 }435436 if len(flagName) == 0 {
103 unmodified lines
modified:fish_completions.go+38 added-10 removed
35 unmodified lines
36 set emptyArg \"\"37 end38 __%[1]s_debug "emptyArg: $emptyArg"3940 if not type -q "$args[1]"41 # This can happen when "complete --do-complete %[1]s" is called when running this script.42 __%[1]s_debug "Cannot find $args[1]. No completions."43 return44 end4546 set requestComp "$args[1] %[2]s $args[2..-1] $emptyArg"47 __%[1]s_debug "Calling $requestComp"4849 set results (eval $requestComp 2> /dev/null)
26 unmodified lines
76 set --erase __%[1]s_comp_results7778 # Check if the command-line is already provided. This is useful for testing.79 if not set --query __%[1]s_comp_commandLine80 # Use the -c flag to allow for completion in the middle of the line74 set __%[1]s_comp_commandLine (commandline)81 set __%[1]s_comp_commandLine (commandline -c)82 end83 __%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine"8485 set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine")
3 unmodified lines
89 if test -z "$results"90 __%[1]s_debug "No completion, probably due to a failure"91 # Might as well do file completion, in case it helps92 set --global __%[1]s_comp_do_file_comp 186 return 093 return 194 end9596 set directive (string sub --start 2 $results[-1])97 set --global __%[1]s_comp_results $results[1..-2]9899 __%[1]s_debug "Completions are: $__%[1]s_comp_results"100 __%[1]s_debug "Directive is: $directive"101102 set shellCompDirectiveError %[3]d103 set shellCompDirectiveNoSpace %[4]d104 set shellCompDirectiveNoFileComp %[5]d105 set shellCompDirectiveFilterFileExt %[6]d106 set shellCompDirectiveFilterDirs %[7]d107108 if test -z "$directive"109 set directive 0110 end11199 set compErr (math (math --scale 0 $directive / %[3]d) %% 2)112 set compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)113 if test $compErr -eq 1114 __%[1]s_debug "Received error directive: aborting."115 # Might as well do file completion, in case it helps116 set --global __%[1]s_comp_do_file_comp 1104 return 0117 return 1118 end119107 set nospace (math (math --scale 0 $directive / %[4]d) %% 2)108 set nofiles (math (math --scale 0 $directive / %[5]d) %% 2)120 set filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)121 set dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)122 if test $filefilter -eq 1; or test $dirfilter -eq 1123 __%[1]s_debug "File extension filtering or directory filtering not supported"124 # Do full file completion instead125 set --global __%[1]s_comp_do_file_comp 1126 return 1127 end128129 set nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)130 set nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)131132 __%[1]s_debug "nospace: $nospace, nofiles: $nofiles"133134 # Important not to quote the variable for count to work135 set numComps (count $__%[1]s_comp_results)
17 unmodified lines
153 # completion command was triggered154 return (not set --query __%[1]s_comp_do_file_comp)155end156135# Remove any pre-existing completions for the program since we will be handling all of them136# TODO this cleanup is not sufficient. Fish completions are only loaded once the user triggers137# them, so the below deletion will not work as it is run too early. What else can we do?157# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves158# so we can properly delete any completions provided by another script.159# The space after the the program name is essential to trigger completion for the program160# and not completion of the program name itself.161complete --do-complete "%[1]s " &> /dev/null162163# Remove any pre-existing completions for the program since we will be handling all of them.164complete -c %[1]s -e165166# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions167# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable.
6 unmodified lines
174# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results abd __%[1]s_comp_do_file_comp.175# It provides the program's completion choices.176complete -c %[1]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'177152`, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))178`, name, compCmd,179 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,180 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))181}182183// GenFishCompletion generates fish completion file and writes to the passed writer.184func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
16 unmodified lines
modified:fish_completions.md+2 added-5 removed
modified:powershell_completions.md+2 added
modified:README.md+4 added-10 removed
26 unmodified lines
27 * [Usage Message](#usage-message)28 * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks)29 * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens)30 * [Generating documentation for your command](#generating-documentation-for-your-command)31 * [Generating bash completions](#generating-bash-completions)32 * [Generating zsh completions](#generating-zsh-completions)31 * [Generating shell completions](#generating-shell-completions)32- [Contributing](#contributing)33- [License](#license)3435# Overview
12 unmodified lines
48* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname`49* Intelligent suggestions (`app srver`... did you mean `app server`?)50* Automatic help generation for commands and flags51* Automatic help flag recognition of `-h`, `--help`, etc.53* Automatically generated bash autocomplete for your application52* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)53* Automatically generated man pages for your application54* Command aliases so you can change things without breaking them55* The flexibility to define your own help, usage, etc.56* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
661 unmodified lines
718## Generating documentation for your command719720Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).721723## Generating bash completions722## Generating shell completions723725Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md).724Cobra can generate a shell-completion file for the following shells: Bash, Zsh, Fish, Powershell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md).725727## Generating zsh completions728729Cobra can generate zsh-completion file. Read more about it in730[Zsh Completions](zsh_completions.md).731726# Contributing7277281. Fork it7292. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
9 unmodified lines
modified:shell_completions.go+26 added-27 removed
2 unmodified lines
3import (4 "github.com/spf13/pflag"5)67// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,7// MarkFlagRequired instructs the various shell completion implementations to8// prioritize the named flag when performing completion,9// and causes your command to report an error if invoked without the flag.10func (c *Command) MarkFlagRequired(name string) error {11 return MarkFlagRequired(c.Flags(), name)12}1313// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag if it exists,14// MarkPersistentFlagRequired instructs the various shell completion implementations to15// prioritize the named persistent flag when performing completion,16// and causes your command to report an error if invoked without the flag.17func (c *Command) MarkPersistentFlagRequired(name string) error {18 return MarkFlagRequired(c.PersistentFlags(), name)19}2019// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,21// MarkFlagRequired instructs the various shell completion implementations to22// prioritize the named flag when performing completion,23// and causes your command to report an error if invoked without the flag.24func MarkFlagRequired(flags *pflag.FlagSet, name string) error {25 return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})26}2725// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.26// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.28// MarkFlagFilename instructs the various shell completion implementations to29// limit completions for the named flag to the specified file extensions.30func (c *Command) MarkFlagFilename(name string, extensions ...string) error {31 return MarkFlagFilename(c.Flags(), name, extensions...)32}3334// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.32// Generated bash autocompletion will call the bash function f for the flag.35// The bash completion script will call the bash function f for the flag.36//37// This will only work for bash completion.38// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows39// to register a Go function which will work across all shells.40func (c *Command) MarkFlagCustom(name string, f string) error {41 return MarkFlagCustom(c.Flags(), name, f)42}4344// MarkPersistentFlagFilename instructs the various shell completion38// implementations to limit completions for this persistent flag to the39// specified extensions (patterns).40//41// Shell Completion compatibility matrix: bash, zsh45// implementations to limit completions for the named persistent flag to the46// specified file extensions.47func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {48 return MarkFlagFilename(c.PersistentFlags(), name, extensions...)49}5051// MarkFlagFilename instructs the various shell completion implementations to47// limit completions for this flag to the specified extensions (patterns).48//49// Shell Completion compatibility matrix: bash, zsh52// limit completions for the named flag to the specified file extensions.53func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {54 return flags.SetAnnotation(name, BashCompFilenameExt, extensions)55}5654// MarkFlagCustom instructs the various shell completion implementations to55// limit completions for this flag to the specified extensions (patterns).57// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.58// The bash completion script will call the bash function f for the flag.59//57// Shell Completion compatibility matrix: bash, zsh60// This will only work for bash completion.61// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows62// to register a Go function which will work across all shells.63func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {64 return flags.SetAnnotation(name, BashCompCustom, []string{f})65}6667// MarkFlagDirname instructs the various shell completion implementations to63// complete only directories with this named flag.64//65// Shell Completion compatibility matrix: zsh68// limit completions for the named flag to directory names.69func (c *Command) MarkFlagDirname(name string) error {70 return MarkFlagDirname(c.Flags(), name)71}7273// MarkPersistentFlagDirname instructs the various shell completion71// implementations to complete only directories with this persistent named flag.72//73// Shell Completion compatibility matrix: zsh74// implementations to limit completions for the named persistent flag to75// directory names.76func (c *Command) MarkPersistentFlagDirname(name string) error {77 return MarkFlagDirname(c.PersistentFlags(), name)78}7980// MarkFlagDirname instructs the various shell completion implementations to79// complete only directories with this specified flag.80//81// Shell Completion compatibility matrix: zsh81// limit completions for the named flag to directory names.82func MarkFlagDirname(flags *pflag.FlagSet, name string) error {83 zshPattern := "-(/)"84 return flags.SetAnnotation(name, zshCompDirname, []string{zshPattern})83 return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{})84}
added:shell_completions.md+429 added
1# Generating shell completions23Cobra can generate shell completions for multiple shells.4The currently supported shells are:5- Bash6- Zsh7- Fish8- PowerShell910If you are using the generator you can create a completion command by running1112```bash13cobra add completion14```15and then modifying the generated `cmd/completion.go` file to look something like this16(writing the shell script to stdout allows the most flexible use):1718```go19var completionCmd = &cobra.Command{20 Use: "completion [bash|zsh|fish|powershell]",21 Short: "Generate completion script",22 Long: `To load completions:2324Bash:2526$ source <(yourprogram completion bash)2728# To load completions for each session, execute once:29Linux:30 $ yourprogram completion bash > /etc/bash_completion.d/yourprogram31MacOS:32 $ yourprogram completion bash > /usr/local/etc/bash_completion.d/yourprogram3334Zsh:3536$ source <(yourprogram completion zsh)3738# To load completions for each session, execute once:39$ yourprogram completion zsh > "${fpath[1]}/_yourprogram"4041Fish:4243$ yourprogram completion fish | source4445# To load completions for each session, execute once:46$ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish47`,48 DisableFlagsInUseLine: true,49 ValidArgs: []string{"bash", "zsh", "fish", "powershell"},50 Args: cobra.ExactValidArgs(1),51 Run: func(cmd *cobra.Command, args []string) {52 switch args[0] {53 case "bash":54 cmd.Root().GenBashCompletion(os.Stdout)55 case "zsh":56 cmd.Root().GenZshCompletion(os.Stdout)57 case "fish":58 cmd.Root().GenFishCompletion(os.Stdout, true)59 case "powershell":60 cmd.Root().GenPowerShellCompletion(os.Stdout)61 }62 },63}64```6566**Note:** The cobra generator may include messages printed to stdout for example if the config file is loaded, this will break the auto complete script so must be removed.6768# Customizing completions6970The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.7172## Completion of nouns7374### Static completion of nouns7576Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field.77For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them.78Some simplified code from `kubectl get` looks like:7980```go81validArgs []string = { "pod", "node", "service", "replicationcontroller" }8283cmd := &cobra.Command{84 Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",85 Short: "Display one or many resources",86 Long: get_long,87 Example: get_example,88 Run: func(cmd *cobra.Command, args []string) {89 err := RunGet(f, out, cmd, args)90 util.CheckErr(err)91 },92 ValidArgs: validArgs,93}94```9596Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:9798```bash99$ kubectl get [tab][tab]100node pod replicationcontroller service101```102103#### Aliases for nouns104105If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:106107```go108argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }109110cmd := &cobra.Command{111 ...112 ValidArgs: validArgs,113 ArgAliases: argAliases114}115```116117The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by118the completion algorithm if entered manually, e.g. in:119120```bash121$ kubectl get rc [tab][tab]122backend frontend database 123```124125Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of126replication controllers following `rc`.127128### Dynamic completion of nouns129130In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. 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.131Simplified code from `helm status` looks like:132133```go134cmd := &cobra.Command{135 Use: "status RELEASE_NAME",136 Short: "Display the status of the named release",137 Long: status_long,138 RunE: func(cmd *cobra.Command, args []string) {139 RunGet(args[0])140 },141 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {142 if len(args) != 0 {143 return nil, cobra.ShellCompDirectiveNoFileComp144 }145 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp146 },147}148```149Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.150Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like:151152```bash153$ helm status [tab][tab]154harbor notary rook thanos155```156You may have noticed the use of `cobra.ShellCompDirective`. 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.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`157```go158// Indicates that the shell will perform its default behavior after completions159// have been provided (this implies none of the other directives).160ShellCompDirectiveDefault161162// Indicates an error occurred and completions should be ignored.163ShellCompDirectiveError164165// Indicates that the shell should not add a space after the completion,166// even if there is a single completion provided.167ShellCompDirectiveNoSpace168169// Indicates that the shell should not provide file completion even when170// no completion is provided.171ShellCompDirectiveNoFileComp172173// Indicates that the returned completions should be used as file extension filters.174// For example, to complete only files of the form *.json or *.yaml:175// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt176// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()177// is a shortcut to using this directive explicitly.178//179ShellCompDirectiveFilterFileExt180181// Indicates that only directory names should be provided in file completion.182// For example:183// return nil, ShellCompDirectiveFilterDirs184// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.185//186// To request directory names within another directory, the returned completions187// should specify a single directory name within which to search. For example,188// to complete directories within "themes/":189// return []string{"themes"}, ShellCompDirectiveFilterDirs190//191ShellCompDirectiveFilterDirs192```193194***Note***: 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.195196#### Debugging197198Cobra achieves dynamic completion 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:199```bash200$ helm __complete status har<ENTER>201harbor202:4203Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr204```205***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command:206```bash207$ helm __complete status ""<ENTER>208harbor209notary210rook211thanos212:4213Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr214```215Calling 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:216```go217// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE218// is set to a file path) and optionally prints to stderr.219cobra.CompDebug(msg string, printToStdErr bool) {220cobra.CompDebugln(msg string, printToStdErr bool)221222// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE223// is set to a file path) and to stderr.224cobra.CompError(msg string)225cobra.CompErrorln(msg string)226```227***Important:*** You should **not** leave traces that print directly 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.228229## Completions for flags230231### Mark flags as required232233Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so:234235```go236cmd.MarkFlagRequired("pod")237cmd.MarkFlagRequired("container")238```239240and you'll get something like241242```bash243$ kubectl exec [tab][tab]244-c --container= -p --pod= 245```246247### Specify dynamic flag completion248249As 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.250251```go252flagName := "output"253cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {254 return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault255})256```257Notice 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:258259```bash260$ helm status --output [tab][tab]261json table yaml262```263264#### Debugging265266You can also easily debug your Go completion code for flags:267```bash268$ helm __complete status --output ""269json270table271yaml272:4273Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr274```275***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 further above.276277### Specify valid filename extensions for flags that take a filename278279To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so:280```go281flagName := "output"282cmd.MarkFlagFilename(flagName, "yaml", "json")283```284or285```go286flagName := "output"287cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {288 return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})289```290291### Limit flag completions to directory names292293To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so:294```go295flagName := "output"296cmd.MarkFlagDirname(flagName)297```298or299```go300flagName := "output"301cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {302 return nil, cobra.ShellCompDirectiveFilterDirs303})304```305To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:306```go307flagName := "output"308cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {309 return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs310})311```312### Descriptions for completions313314Both `zsh` and `fish` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh:315```316$ helm s[tab]317search -- search for a keyword in charts318show -- show information of a chart319status -- displays the status of the named release320```321while using fish:322```323$ helm s[tab]324search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)325```326327Cobra allows you to add annotations to your own completions. Simply add the annotation text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:328```go329ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {330 return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp331}}332```333or334```go335ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}336```337## Bash completions338339### Dependencies340341The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion))342343### Aliases344345You can also configure `bash` aliases for your program and they will also support completions.346347```bash348alias aliasname=origcommand349complete -o default -F __start_origcommand aliasname350351# and now when you run `aliasname` completion will make352# suggestions as it did for `origcommand`.353354$ aliasname <tab><tab>355completion firstcommand secondcommand356```357### Bash legacy dynamic completions358359For backwards-compatibility, Cobra still supports its bash legacy dynamic completion solution.360Please refer to [Bash Completions](bash_completions.md) for details.361362## Zsh completions363364Cobra supports native Zsh completion generated from the root `cobra.Command`.365The generated completion script should be put somewhere in your `$fpath` and be named366`_<yourProgram>`.367368Zsh supports descriptions for completions. Cobra will provide the description automatically,369based on usage information. Cobra provides a way to completely disable such descriptions by370using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make371this a configurable option to your users.372```373# With descriptions374$ helm s[tab]375search -- search for a keyword in charts376show -- show information of a chart377status -- displays the status of the named release378379# Without descriptions380$ helm s[tab]381search show status382```383*Note*: Because of backwards-compatibility requirements, we were forced to have a different API to disable completion descriptions between `Zsh` and `Fish`.384385### Limitations386387* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).388 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`).389* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.390 * You should instead use `RegisterFlagCompletionFunc()`.391392### Zsh completions standardization393394Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced.395Please refer to [Zsh Completions](zsh_completions.md) for details.396397## Fish completions398399Cobra supports native Fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.400```401# With descriptions402$ helm s[tab]403search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)404405# Without descriptions406$ helm s[tab]407search show status408```409*Note*: Because of backwards-compatibility requirements, we were forced to have a different API to disable completion descriptions between `Zsh` and `Fish`.410411### Limitations412413* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).414 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`).415* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.416 * You should instead use `RegisterFlagCompletionFunc()`.417* The following flag completion annotations are not supported and will be ignored for `fish`:418 * `BashCompFilenameExt` (filtering by file extension)419 * `BashCompSubdirsInDir` (filtering by directory)420* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`:421 * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)422 * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)423* Similarly, the following completion directives are not supported and will be ignored for `fish`:424 * `ShellCompDirectiveFilterFileExt` (filtering by file extension)425 * `ShellCompDirectiveFilterDirs` (filtering by directory)426427## PowerShell completions428429Please refer to [PowerShell Completions](powershell_completions.md) for details.
deleted:zsh_completions_test.go-475 removed
1package cobra23import (4 "bytes"5 "regexp"6 "strings"7 "testing"8)910func TestGenZshCompletion(t *testing.T) {11 var debug bool12 var option string1314 tcs := []struct {15 name string16 root *Command17 expectedExpressions []string18 invocationArgs []string19 skip string20 }{21 {22 name: "simple command",23 root: func() *Command {24 r := &Command{25 Use: "mycommand",26 Long: "My Command long description",27 Run: emptyRun,28 }29 r.Flags().BoolVar(&debug, "debug", debug, "description")30 return r31 }(),32 expectedExpressions: []string{33 `(?s)function _mycommand {\s+_arguments \\\s+'--debug\[description\]'.*--help.*}`,34 "#compdef _mycommand mycommand",35 },36 },37 {38 name: "flags with both long and short flags",39 root: func() *Command {40 r := &Command{41 Use: "testcmd",42 Long: "long description",43 Run: emptyRun,44 }45 r.Flags().BoolVarP(&debug, "debug", "d", debug, "debug description")46 return r47 }(),48 expectedExpressions: []string{49 `'\(-d --debug\)'{-d,--debug}'\[debug description\]'`,50 },51 },52 {53 name: "command with subcommands and flags with values",54 root: func() *Command {55 r := &Command{56 Use: "rootcmd",57 Long: "Long rootcmd description",58 }59 d := &Command{60 Use: "subcmd1",61 Short: "Subcmd1 short description",62 Run: emptyRun,63 }64 e := &Command{65 Use: "subcmd2",66 Long: "Subcmd2 short description",67 Run: emptyRun,68 }69 r.PersistentFlags().BoolVar(&debug, "debug", debug, "description")70 d.Flags().StringVarP(&option, "option", "o", option, "option description")71 r.AddCommand(d, e)72 return r73 }(),74 expectedExpressions: []string{75 `commands=\(\n\s+"help:.*\n\s+"subcmd1:.*\n\s+"subcmd2:.*\n\s+\)`,76 `_arguments \\\n.*'--debug\[description]'`,77 `_arguments -C \\\n.*'--debug\[description]'`,78 `function _rootcmd_subcmd1 {`,79 `function _rootcmd_subcmd1 {`,80 `_arguments \\\n.*'\(-o --option\)'{-o,--option}'\[option description]:' \\\n`,81 },82 },83 {84 name: "filename completion with and without globs",85 root: func() *Command {86 var file string87 r := &Command{88 Use: "mycmd",89 Short: "my command short description",90 Run: emptyRun,91 }92 r.Flags().StringVarP(&file, "config", "c", file, "config file")93 r.MarkFlagFilename("config")94 r.Flags().String("output", "", "output file")95 r.MarkFlagFilename("output", "*.log", "*.txt")96 return r97 }(),98 expectedExpressions: []string{99 `\n +'\(-c --config\)'{-c,--config}'\[config file]:filename:_files'`,100 `:_files -g "\*.log" -g "\*.txt"`,101 },102 },103 {104 name: "repeated variables both with and without value",105 root: func() *Command {106 r := genTestCommand("mycmd", true)107 _ = r.Flags().BoolSliceP("debug", "d", []bool{}, "debug usage")108 _ = r.Flags().StringArray("option", []string{}, "options")109 return r110 }(),111 expectedExpressions: []string{112 `'\*--option\[options]`,113 `'\(\*-d \*--debug\)'{\\\*-d,\\\*--debug}`,114 },115 },116 {117 name: "generated flags --help and --version should be created even when not executing root cmd",118 root: func() *Command {119 r := &Command{120 Use: "mycmd",121 Short: "mycmd short description",122 Version: "myversion",123 }124 s := genTestCommand("sub1", true)125 r.AddCommand(s)126 return s127 }(),128 expectedExpressions: []string{129 "--version",130 "--help",131 },132 invocationArgs: []string{133 "sub1",134 },135 skip: "--version and --help are currently not generated when not running on root command",136 },137 {138 name: "zsh generation should run on root command",139 root: func() *Command {140 r := genTestCommand("root", false)141 s := genTestCommand("sub1", true)142 r.AddCommand(s)143 return s144 }(),145 expectedExpressions: []string{146 "function _root {",147 },148 },149 {150 name: "flag description with single quote (') shouldn't break quotes in completion file",151 root: func() *Command {152 r := genTestCommand("root", true)153 r.Flags().Bool("private", false, "Don't show public info")154 return r155 }(),156 expectedExpressions: []string{157 `--private\[Don'\\''t show public info]`,158 },159 },160 {161 name: "argument completion for file with and without patterns",162 root: func() *Command {163 r := genTestCommand("root", true)164 r.MarkZshCompPositionalArgumentFile(1, "*.log")165 r.MarkZshCompPositionalArgumentFile(2)166 return r167 }(),168 expectedExpressions: []string{169 `'1: :_files -g "\*.log"' \\\n\s+'2: :_files`,170 },171 },172 {173 name: "argument zsh completion for words",174 root: func() *Command {175 r := genTestCommand("root", true)176 r.MarkZshCompPositionalArgumentWords(1, "word1", "word2")177 return r178 }(),179 expectedExpressions: []string{180 `'1: :\("word1" "word2"\)`,181 },182 },183 {184 name: "argument completion for words with spaces",185 root: func() *Command {186 r := genTestCommand("root", true)187 r.MarkZshCompPositionalArgumentWords(1, "single", "multiple words")188 return r189 }(),190 expectedExpressions: []string{191 `'1: :\("single" "multiple words"\)'`,192 },193 },194 {195 name: "argument completion when command has ValidArgs and no annotation for argument completion",196 root: func() *Command {197 r := genTestCommand("root", true)198 r.ValidArgs = []string{"word1", "word2"}199 return r200 }(),201 expectedExpressions: []string{202 `'1: :\("word1" "word2"\)'`,203 },204 },205 {206 name: "argument completion when command has ValidArgs and no annotation for argument at argPosition 1",207 root: func() *Command {208 r := genTestCommand("root", true)209 r.ValidArgs = []string{"word1", "word2"}210 r.MarkZshCompPositionalArgumentFile(2)211 return r212 }(),213 expectedExpressions: []string{214 `'1: :\("word1" "word2"\)' \\`,215 },216 },217 {218 name: "directory completion for flag",219 root: func() *Command {220 r := genTestCommand("root", true)221 r.Flags().String("test", "", "test")222 r.PersistentFlags().String("ptest", "", "ptest")223 r.MarkFlagDirname("test")224 r.MarkPersistentFlagDirname("ptest")225 return r226 }(),227 expectedExpressions: []string{228 `--test\[test]:filename:_files -g "-\(/\)"`,229 `--ptest\[ptest]:filename:_files -g "-\(/\)"`,230 },231 },232 }233234 for _, tc := range tcs {235 t.Run(tc.name, func(t *testing.T) {236 if tc.skip != "" {237 t.Skip(tc.skip)238 }239 tc.root.Root().SetArgs(tc.invocationArgs)240 tc.root.Execute()241 buf := new(bytes.Buffer)242 if err := tc.root.GenZshCompletion(buf); err != nil {243 t.Error(err)244 }245 output := buf.Bytes()246247 for _, expr := range tc.expectedExpressions {248 rgx, err := regexp.Compile(expr)249 if err != nil {250 t.Errorf("error compiling expression (%s): %v", expr, err)251 }252 if !rgx.Match(output) {253 t.Errorf("expected completion (%s) to match '%s'", buf.String(), expr)254 }255 }256 })257 }258}259260func TestGenZshCompletionHidden(t *testing.T) {261 tcs := []struct {262 name string263 root *Command264 expectedExpressions []string265 }{266 {267 name: "hidden commands",268 root: func() *Command {269 r := &Command{270 Use: "main",271 Short: "main short description",272 }273 s1 := &Command{274 Use: "sub1",275 Hidden: true,276 Run: emptyRun,277 }278 s2 := &Command{279 Use: "sub2",280 Short: "short sub2 description",281 Run: emptyRun,282 }283 r.AddCommand(s1, s2)284285 return r286 }(),287 expectedExpressions: []string{288 "sub1",289 },290 },291 {292 name: "hidden flags",293 root: func() *Command {294 var hidden string295 r := &Command{296 Use: "root",297 Short: "root short description",298 Run: emptyRun,299 }300 r.Flags().StringVarP(&hidden, "hidden", "H", hidden, "hidden usage")301 if err := r.Flags().MarkHidden("hidden"); err != nil {302 t.Errorf("Error setting flag hidden: %v\n", err)303 }304 return r305 }(),306 expectedExpressions: []string{307 "--hidden",308 },309 },310 }311312 for _, tc := range tcs {313 t.Run(tc.name, func(t *testing.T) {314 tc.root.Execute()315 buf := new(bytes.Buffer)316 if err := tc.root.GenZshCompletion(buf); err != nil {317 t.Error(err)318 }319 output := buf.String()320321 for _, expr := range tc.expectedExpressions {322 if strings.Contains(output, expr) {323 t.Errorf("Expected completion (%s) not to contain '%s' but it does", output, expr)324 }325 }326 })327 }328}329330func TestMarkZshCompPositionalArgumentFile(t *testing.T) {331 t.Run("Doesn't allow overwriting existing positional argument", func(t *testing.T) {332 c := &Command{}333 if err := c.MarkZshCompPositionalArgumentFile(1, "*.log"); err != nil {334 t.Errorf("Received error when we shouldn't have: %v\n", err)335 }336 if err := c.MarkZshCompPositionalArgumentFile(1); err == nil {337 t.Error("Didn't receive an error when trying to overwrite argument position")338 }339 })340341 t.Run("Refuses to accept argPosition less then 1", func(t *testing.T) {342 c := &Command{}343 err := c.MarkZshCompPositionalArgumentFile(0, "*")344 if err == nil {345 t.Fatal("Error was not thrown when indicating argument position 0")346 }347 if !strings.Contains(err.Error(), "position") {348 t.Errorf("expected error message '%s' to contain 'position'", err.Error())349 }350 })351}352353func TestMarkZshCompPositionalArgumentWords(t *testing.T) {354 t.Run("Doesn't allow overwriting existing positional argument", func(t *testing.T) {355 c := &Command{}356 if err := c.MarkZshCompPositionalArgumentFile(1, "*.log"); err != nil {357 t.Errorf("Received error when we shouldn't have: %v\n", err)358 }359 if err := c.MarkZshCompPositionalArgumentWords(1, "hello"); err == nil {360 t.Error("Didn't receive an error when trying to overwrite argument position")361 }362 })363364 t.Run("Doesn't allow calling without words", func(t *testing.T) {365 c := &Command{}366 if err := c.MarkZshCompPositionalArgumentWords(0); err == nil {367 t.Error("Should not allow saving empty word list for annotation")368 }369 })370371 t.Run("Refuses to accept argPosition less then 1", func(t *testing.T) {372 c := &Command{}373 err := c.MarkZshCompPositionalArgumentWords(0, "word")374 if err == nil {375 t.Fatal("Should not allow setting argument position less then 1")376 }377 if !strings.Contains(err.Error(), "position") {378 t.Errorf("Expected error '%s' to contain 'position' but didn't", err.Error())379 }380 })381}382383func BenchmarkMediumSizeConstruct(b *testing.B) {384 root := constructLargeCommandHierarchy()385 // if err := root.GenZshCompletionFile("_mycmd"); err != nil {386 // b.Error(err)387 // }388389 for i := 0; i < b.N; i++ {390 buf := new(bytes.Buffer)391 err := root.GenZshCompletion(buf)392 if err != nil {393 b.Error(err)394 }395 }396}397398func TestExtractFlags(t *testing.T) {399 var debug, cmdc, cmdd bool400 c := &Command{401 Use: "cmdC",402 Long: "Command C",403 }404 c.PersistentFlags().BoolVarP(&debug, "debug", "d", debug, "debug mode")405 c.Flags().BoolVar(&cmdc, "cmd-c", cmdc, "Command C")406 d := &Command{407 Use: "CmdD",408 Long: "Command D",409 }410 d.Flags().BoolVar(&cmdd, "cmd-d", cmdd, "Command D")411 c.AddCommand(d)412413 resC := zshCompExtractFlag(c)414 resD := zshCompExtractFlag(d)415416 if len(resC) != 2 {417 t.Errorf("expected Command C to return 2 flags, got %d", len(resC))418 }419 if len(resD) != 2 {420 t.Errorf("expected Command D to return 2 flags, got %d", len(resD))421 }422}423424func constructLargeCommandHierarchy() *Command {425 var config, st1, st2 string426 var long, debug bool427 var in1, in2 int428 var verbose []bool429430 r := genTestCommand("mycmd", false)431 r.PersistentFlags().StringVarP(&config, "config", "c", config, "config usage")432 if err := r.MarkPersistentFlagFilename("config", "*"); err != nil {433 panic(err)434 }435 s1 := genTestCommand("sub1", true)436 s1.Flags().BoolVar(&long, "long", long, "long description")437 s1.Flags().BoolSliceVar(&verbose, "verbose", verbose, "verbose description")438 s1.Flags().StringArray("option", []string{}, "various options")439 s2 := genTestCommand("sub2", true)440 s2.PersistentFlags().BoolVar(&debug, "debug", debug, "debug description")441 s3 := genTestCommand("sub3", true)442 s3.Hidden = true443 s1_1 := genTestCommand("sub1sub1", true)444 s1_1.Flags().StringVar(&st1, "st1", st1, "st1 description")445 s1_1.Flags().StringVar(&st2, "st2", st2, "st2 description")446 s1_2 := genTestCommand("sub1sub2", true)447 s1_3 := genTestCommand("sub1sub3", true)448 s1_3.Flags().IntVar(&in1, "int1", in1, "int1 description")449 s1_3.Flags().IntVar(&in2, "int2", in2, "int2 description")450 s1_3.Flags().StringArrayP("option", "O", []string{}, "more options")451 s2_1 := genTestCommand("sub2sub1", true)452 s2_2 := genTestCommand("sub2sub2", true)453 s2_3 := genTestCommand("sub2sub3", true)454 s2_4 := genTestCommand("sub2sub4", true)455 s2_5 := genTestCommand("sub2sub5", true)456457 s1.AddCommand(s1_1, s1_2, s1_3)458 s2.AddCommand(s2_1, s2_2, s2_3, s2_4, s2_5)459 r.AddCommand(s1, s2, s3)460 r.Execute()461 return r462}463464func genTestCommand(name string, withRun bool) *Command {465 r := &Command{466 Use: name,467 Short: name + " short description",468 Long: "Long description for " + name,469 }470 if withRun {471 r.Run = emptyRun472 }473474 return r475}
modified:zsh_completions.go+183 added-284 removed
1package cobra23import (4 "encoding/json"4 "bytes"5 "fmt"6 "io"7 "os"8 "sort"9 "strings"10 "text/template"1112 "github.com/spf13/pflag"8)915const (16 zshCompArgumentAnnotation = "cobra_annotations_zsh_completion_argument_annotation"17 zshCompArgumentFilenameComp = "cobra_annotations_zsh_completion_argument_file_completion"18 zshCompArgumentWordComp = "cobra_annotations_zsh_completion_argument_word_completion"19 zshCompDirname = "cobra_annotations_zsh_dirname"20)10// GenZshCompletionFile generates zsh completion file including descriptions.11func (c *Command) GenZshCompletionFile(filename string) error {12 return c.genZshCompletionFile(filename, true)13}1422var (23 zshCompFuncMap = template.FuncMap{24 "genZshFuncName": zshCompGenFuncName,25 "extractFlags": zshCompExtractFlag,26 "genFlagEntryForZshArguments": zshCompGenFlagEntryForArguments,27 "extractArgsCompletions": zshCompExtractArgumentCompletionHintsForRendering,28 }29 zshCompletionText = `30{{/* should accept Command (that contains subcommands) as parameter */}}31{{define "argumentsC" -}}32{{ $cmdPath := genZshFuncName .}}33function {{$cmdPath}} {34 local -a commands15// GenZshCompletion generates zsh completion file including descriptions16// and writes it to the passed writer.17func (c *Command) GenZshCompletion(w io.Writer) error {18 return c.genZshCompletion(w, true)19}2036 _arguments -C \{{- range extractFlags .}}37 {{genFlagEntryForZshArguments .}} \{{- end}}38 "1: :->cmnds" \39 "*::arg:->args"21// GenZshCompletionFileNoDesc generates zsh completion file without descriptions.22func (c *Command) GenZshCompletionFileNoDesc(filename string) error {23 return c.genZshCompletionFile(filename, false)24}2541 case $state in42 cmnds)43 commands=({{range .Commands}}{{if not .Hidden}}44 "{{.Name}}:{{.Short}}"{{end}}{{end}}45 )46 _describe "command" commands47 ;;48 esac4950 case "$words[1]" in {{- range .Commands}}{{if not .Hidden}}51 {{.Name}})52 {{$cmdPath}}_{{.Name}}53 ;;{{end}}{{end}}54 esac26// GenZshCompletionNoDesc generates zsh completion file without descriptions27// and writes it to the passed writer.28func (c *Command) GenZshCompletionNoDesc(w io.Writer) error {29 return c.genZshCompletion(w, false)30}56{{range .Commands}}{{if not .Hidden}}57{{template "selectCmdTemplate" .}}58{{- end}}{{end}}59{{- end}}3161{{/* should accept Command without subcommands as parameter */}}62{{define "arguments" -}}63function {{genZshFuncName .}} {64{{" _arguments"}}{{range extractFlags .}} \65 {{genFlagEntryForZshArguments . -}}66{{end}}{{range extractArgsCompletions .}} \67 {{.}}{{end}}32// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was33// not consistent with Bash completion. It has therefore been disabled.34// Instead, when no other completion is specified, file completion is done by35// default for every argument. One can disable file completion on a per-argument36// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp.37// To achieve file extension filtering, one can use ValidArgsFunction and38// ShellCompDirectiveFilterFileExt.39//40// Deprecated41func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {42 return nil43}69{{end}}4471{{/* dispatcher for commands with or without subcommands */}}72{{define "selectCmdTemplate" -}}73{{if .Hidden}}{{/* ignore hidden*/}}{{else -}}74{{if .Commands}}{{template "argumentsC" .}}{{else}}{{template "arguments" .}}{{end}}75{{- end}}76{{- end}}7778{{/* template entry point */}}79{{define "Main" -}}80#compdef _{{.Name}} {{.Name}}8182{{template "selectCmdTemplate" .}}83{{end}}84`85)8687// zshCompArgsAnnotation is used to encode/decode zsh completion for88// arguments to/from Command.Annotations.89type zshCompArgsAnnotation map[int]zshCompArgHint9091type zshCompArgHint struct {92 // Indicates the type of the completion to use. One of:93 // zshCompArgumentFilenameComp or zshCompArgumentWordComp94 Tipe string `json:"type"`9596 // A value for the type above (globs for file completion or words)97 Options []string `json:"options"`45// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore46// been disabled.47// To achieve the same behavior across all shells, one can use48// ValidArgs (for the first argument only) or ValidArgsFunction for49// any argument (can include the first one also).50//51// Deprecated52func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {53 return nil54}55100// GenZshCompletionFile generates zsh completion file.101func (c *Command) GenZshCompletionFile(filename string) error {56func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error {57 outFile, err := os.Create(filename)58 if err != nil {59 return err60 }61 defer outFile.Close()62108 return c.GenZshCompletion(outFile)63 return c.genZshCompletion(outFile, includeDesc)64}65111// GenZshCompletion generates a zsh completion file and writes to the passed112// writer. The completion always run on the root command regardless of the113// command it was called from.114func (c *Command) GenZshCompletion(w io.Writer) error {115 tmpl, err := template.New("Main").Funcs(zshCompFuncMap).Parse(zshCompletionText)116 if err != nil {117 return fmt.Errorf("error creating zsh completion template: %v", err)118 }119 return tmpl.Execute(w, c.Root())66func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {67 buf := new(bytes.Buffer)68 genZshComp(buf, c.Name(), includeDesc)69 _, err := buf.WriteTo(w)70 return err71}72122// MarkZshCompPositionalArgumentFile marks the specified argument (first123// argument is 1) as completed by file selection. patterns (e.g. "*.txt") are124// optional - if not provided the completion will search for all files.125func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {126 if argPosition < 1 {127 return fmt.Errorf("Invalid argument position (%d)", argPosition)73func genZshComp(buf *bytes.Buffer, name string, includeDesc bool) {74 compCmd := ShellCompRequestCmd75 if !includeDesc {76 compCmd = ShellCompNoDescRequestCmd77 }129 annotation, err := c.zshCompGetArgsAnnotations()130 if err != nil {131 return err132 }133 if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {134 return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)135 }136 annotation[argPosition] = zshCompArgHint{137 Tipe: zshCompArgumentFilenameComp,138 Options: patterns,139 }140 return c.zshCompSetArgsAnnotations(annotation)141}78 buf.WriteString(fmt.Sprintf(`#compdef _%[1]s %[1]s79143// MarkZshCompPositionalArgumentWords marks the specified positional argument144// (first argument is 1) as completed by the provided words. At east one word145// must be provided, spaces within words will be offered completion with146// "word\ word".147func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {148 if argPosition < 1 {149 return fmt.Errorf("Invalid argument position (%d)", argPosition)150 }151 if len(words) == 0 {152 return fmt.Errorf("Trying to set empty word list for positional argument %d", argPosition)153 }154 annotation, err := c.zshCompGetArgsAnnotations()155 if err != nil {156 return err157 }158 if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {159 return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)160 }161 annotation[argPosition] = zshCompArgHint{162 Tipe: zshCompArgumentWordComp,163 Options: words,164 }165 return c.zshCompSetArgsAnnotations(annotation)166}80# zsh completion for %-36[1]s -*- shell-script -*-81168func zshCompExtractArgumentCompletionHintsForRendering(c *Command) ([]string, error) {169 var result []string170 annotation, err := c.zshCompGetArgsAnnotations()171 if err != nil {172 return nil, err173 }174 for k, v := range annotation {175 s, err := zshCompRenderZshCompArgHint(k, v)176 if err != nil {177 return nil, err178 }179 result = append(result, s)180 }181 if len(c.ValidArgs) > 0 {182 if _, positionOneExists := annotation[1]; !positionOneExists {183 s, err := zshCompRenderZshCompArgHint(1, zshCompArgHint{184 Tipe: zshCompArgumentWordComp,185 Options: c.ValidArgs,186 })187 if err != nil {188 return nil, err189 }190 result = append(result, s)191 }192 }193 sort.Strings(result)194 return result, nil82__%[1]s_debug()83{84 local file="$BASH_COMP_DEBUG_FILE"85 if [[ -n ${file} ]]; then86 echo "$*" >> "${file}"87 fi88}89197func zshCompRenderZshCompArgHint(i int, z zshCompArgHint) (string, error) {198 switch t := z.Tipe; t {199 case zshCompArgumentFilenameComp:200 var globs []string201 for _, g := range z.Options {202 globs = append(globs, fmt.Sprintf(`-g "%s"`, g))203 }204 return fmt.Sprintf(`'%d: :_files %s'`, i, strings.Join(globs, " ")), nil205 case zshCompArgumentWordComp:206 var words []string207 for _, w := range z.Options {208 words = append(words, fmt.Sprintf("%q", w))209 }210 return fmt.Sprintf(`'%d: :(%s)'`, i, strings.Join(words, " ")), nil211 default:212 return "", fmt.Errorf("Invalid zsh argument completion annotation: %s", t)213 }214}90_%[1]s()91{92 local shellCompDirectiveError=%[3]d93 local shellCompDirectiveNoSpace=%[4]d94 local shellCompDirectiveNoFileComp=%[5]d95 local shellCompDirectiveFilterFileExt=%[6]d96 local shellCompDirectiveFilterDirs=%[7]d97216func (c *Command) zshcompArgsAnnotationnIsDuplicatePosition(annotation zshCompArgsAnnotation, position int) bool {217 _, dup := annotation[position]218 return dup219}98 local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp99 local -a completions100221func (c *Command) zshCompGetArgsAnnotations() (zshCompArgsAnnotation, error) {222 annotation := make(zshCompArgsAnnotation)223 annotationString, ok := c.Annotations[zshCompArgumentAnnotation]224 if !ok {225 return annotation, nil226 }227 err := json.Unmarshal([]byte(annotationString), &annotation)228 if err != nil {229 return annotation, fmt.Errorf("Error unmarshaling zsh argument annotation: %v", err)230 }231 return annotation, nil232}101 __%[1]s_debug "\n========= starting completion logic =========="102 __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"103234func (c *Command) zshCompSetArgsAnnotations(annotation zshCompArgsAnnotation) error {235 jsn, err := json.Marshal(annotation)236 if err != nil {237 return fmt.Errorf("Error marshaling zsh argument annotation: %v", err)238 }239 if c.Annotations == nil {240 c.Annotations = make(map[string]string)241 }242 c.Annotations[zshCompArgumentAnnotation] = string(jsn)243 return nil244}104 # The user could have moved the cursor backwards on the command-line.105 # We need to trigger completion from the $CURRENT location, so we need106 # to truncate the command-line ($words) up to the $CURRENT location.107 # (We cannot use $CURSOR as its value does not work when a command is an alias.)108 words=("${=words[1,CURRENT]}")109 __%[1]s_debug "Truncated words[*]: ${words[*]},"110246func zshCompGenFuncName(c *Command) string {247 if c.HasParent() {248 return zshCompGenFuncName(c.Parent()) + "_" + c.Name()249 }250 return "_" + c.Name()251}111 lastParam=${words[-1]}112 lastChar=${lastParam[-1]}113 __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"114253func zshCompExtractFlag(c *Command) []*pflag.Flag {254 var flags []*pflag.Flag255 c.LocalFlags().VisitAll(func(f *pflag.Flag) {256 if !f.Hidden {257 flags = append(flags, f)258 }259 })260 c.InheritedFlags().VisitAll(func(f *pflag.Flag) {261 if !f.Hidden {262 flags = append(flags, f)263 }264 })265 return flags266}115 # For zsh, when completing a flag with an = (e.g., %[1]s -n=<TAB>)116 # completions must be prefixed with the flag117 setopt local_options BASH_REMATCH118 if [[ "${lastParam}" =~ '-.*=' ]]; then119 # We are dealing with a flag with an =120 flagPrefix="-P ${BASH_REMATCH}"121 fi122268// zshCompGenFlagEntryForArguments returns an entry that matches _arguments269// zsh-completion parameters. It's too complicated to generate in a template.270func zshCompGenFlagEntryForArguments(f *pflag.Flag) string {271 if f.Name == "" || f.Shorthand == "" {272 return zshCompGenFlagEntryForSingleOptionFlag(f)273 }274 return zshCompGenFlagEntryForMultiOptionFlag(f)275}123 # Prepare the command to obtain completions124 requestComp="${words[1]} %[2]s ${words[2,-1]}"125 if [ "${lastChar}" = "" ]; then126 # If the last parameter is complete (there is a space following it)127 # We add an extra empty parameter so we can indicate this to the go completion code.128 __%[1]s_debug "Adding extra empty parameter"129 requestComp="${requestComp} \"\""130 fi131277func zshCompGenFlagEntryForSingleOptionFlag(f *pflag.Flag) string {278 var option, multiMark, extras string132 __%[1]s_debug "About to call: eval ${requestComp}"133280 if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {281 multiMark = "*"282 }134 # Use eval to handle any environment variables and such135 out=$(eval ${requestComp} 2>/dev/null)136 __%[1]s_debug "completion output: ${out}"137284 option = "--" + f.Name285 if option == "--" {286 option = "-" + f.Shorthand287 }288 extras = zshCompGenFlagEntryExtras(f)138 # Extract the directive integer following a : from the last line139 local lastLine140 while IFS='\n' read -r line; do141 lastLine=${line}142 done < <(printf "%%s\n" "${out[@]}")143 __%[1]s_debug "last line: ${lastLine}"144290 return fmt.Sprintf(`'%s%s[%s]%s'`, multiMark, option, zshCompQuoteFlagDescription(f.Usage), extras)291}145 if [ "${lastLine[1]}" = : ]; then146 directive=${lastLine[2,-1]}147 # Remove the directive including the : and the newline148 local suffix149 (( suffix=${#lastLine}+2))150 out=${out[1,-$suffix]}151 else152 # There is no directive specified. Leave $out as is.153 __%[1]s_debug "No directive found. Setting do default"154 directive=0155 fi156293func zshCompGenFlagEntryForMultiOptionFlag(f *pflag.Flag) string {294 var options, parenMultiMark, curlyMultiMark, extras string157 __%[1]s_debug "directive: ${directive}"158 __%[1]s_debug "completions: ${out}"159 __%[1]s_debug "flagPrefix: ${flagPrefix}"160296 if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {297 parenMultiMark = "*"298 curlyMultiMark = "\\*"299 }161 if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then162 __%[1]s_debug "Completion received error. Ignoring completions."163 return164 fi165301 options = fmt.Sprintf(`'(%s-%s %s--%s)'{%s-%s,%s--%s}`,302 parenMultiMark, f.Shorthand, parenMultiMark, f.Name, curlyMultiMark, f.Shorthand, curlyMultiMark, f.Name)303 extras = zshCompGenFlagEntryExtras(f)166 compCount=0167 while IFS='\n' read -r comp; do168 if [ -n "$comp" ]; then169 # If requested, completions are returned with a description.170 # The description is preceded by a TAB character.171 # For zsh's _describe, we need to use a : instead of a TAB.172 # We first need to escape any : as part of the completion itself.173 comp=${comp//:/\\:}174305 return fmt.Sprintf(`%s'[%s]%s'`, options, zshCompQuoteFlagDescription(f.Usage), extras)306}175 local tab=$(printf '\t')176 comp=${comp//$tab/:}177308func zshCompGenFlagEntryExtras(f *pflag.Flag) string {309 if f.NoOptDefVal != "" {310 return ""311 }178 ((compCount++))179 __%[1]s_debug "Adding completion: ${comp}"180 completions+=${comp}181 lastComp=$comp182 fi183 done < <(printf "%%s\n" "${out[@]}")184313 extras := ":" // allow options for flag (even without assistance)314 for key, values := range f.Annotations {315 switch key {316 case zshCompDirname:317 extras = fmt.Sprintf(":filename:_files -g %q", values[0])318 case BashCompFilenameExt:319 extras = ":filename:_files"320 for _, pattern := range values {321 extras = extras + fmt.Sprintf(` -g "%s"`, pattern)322 }323 }324 }185 if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then186 # File extension filtering187 local filteringCmd188 filteringCmd='_files'189 for filter in ${completions[@]}; do190 if [ ${filter[1]} != '*' ]; then191 # zsh requires a glob pattern to do file filtering192 filter="\*.$filter"193 fi194 filteringCmd+=" -g $filter"195 done196 filteringCmd+=" ${flagPrefix}"197326 return extras327}198 __%[1]s_debug "File filtering command: $filteringCmd"199 _arguments '*:filename:'"$filteringCmd"200 elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then201 # File completion for directories only202 local subDir203 subdir="${completions[1]}"204 if [ -n "$subdir" ]; then205 __%[1]s_debug "Listing directories in $subdir"206 pushd "${subdir}" >/dev/null 2>&1207 else208 __%[1]s_debug "Listing directories in ."209 fi210329func zshCompFlagCouldBeSpecifiedMoreThenOnce(f *pflag.Flag) bool {330 return strings.Contains(f.Value.Type(), "Slice") ||331 strings.Contains(f.Value.Type(), "Array")211 _arguments '*:dirname:_files -/'" ${flagPrefix}"212 if [ -n "$subdir" ]; then213 popd >/dev/null 2>&1214 fi215 elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then216 __%[1]s_debug "Activating nospace."217 # We can use compadd here as there is no description when218 # there is only one completion.219 compadd -S '' "${lastComp}"220 elif [ ${compCount} -eq 0 ]; then221 if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then222 __%[1]s_debug "deactivating file completion"223 else224 # Perform file completion225 __%[1]s_debug "activating file completion"226 _arguments '*:filename:_files'" ${flagPrefix}"227 fi228 else229 _describe "completions" completions $(echo $flagPrefix)230 fi231}333334func zshCompQuoteFlagDescription(s string) string {335 return strings.Replace(s, "'", `'\''`, -1)232`, name, compCmd,233 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,234 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))235}
modified:zsh_completions.md+42 added-34 removed
1## Generating Zsh Completion for your cobra.Command1## Generating Zsh Completion For Your cobra.Command23Cobra supports native Zsh completion generated from the root `cobra.Command`.4The generated completion script should be put somewhere in your `$fpath` named5`_<YOUR COMMAND>`.3Please refer to [Shell Completions](shell_completions.md) for details.47### What's Supported5## Zsh completions standardization69* Completion for all non-hidden subcommands using their `.Short` description.10* Completion for all non-hidden flags using the following rules:11 * Filename completion works by marking the flag with `cmd.MarkFlagFilename...`12 family of commands.13 * The requirement for argument to the flag is decided by the `.NoOptDefVal`14 flag value - if it's empty then completion will expect an argument.15 * Flags of one of the various `*Array` and `*Slice` types supports multiple16 specifications (with or without argument depending on the specific type).17* Completion of positional arguments using the following rules:18 * Argument position for all options below starts at `1`. If argument position19 `0` is requested it will raise an error.20 * Use `command.MarkZshCompPositionalArgumentFile` to complete filenames. Glob21 patterns (e.g. `"*.log"`) are optional - if not specified it will offer to22 complete all file types.23 * Use `command.MarkZshCompPositionalArgumentWords` to offer specific words for24 completion. At least one word is required.25 * It's possible to specify completion for some arguments and leave some26 unspecified (e.g. offer words for second argument but nothing for first27 argument). This will cause no completion for first argument but words28 completion for second argument.29 * If no argument completion was specified for 1st argument (but optionally was30 specified for 2nd) and the command has `ValidArgs` it will be used as31 completion options for 1st argument.32 * Argument completions only offered for commands with no subcommands.7Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced.834### What's not yet Supported9### Deprecation summary1036* Custom completion scripts are not supported yet (We should probably create zsh37 specific one, doesn't make sense to re-use the bash one as the functions will38 be different).39* Whatever other feature you're looking for and doesn't exist :)11See further below for more details on these deprecations.1213* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored.14* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored.15 * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`.16* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored.17 * Instead use `ValidArgsFunction`.1819### Behavioral changes2021**Noun completion**22|Old behavior|New behavior|23|---|---|24|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis|25`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored|26|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)|27|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior|2829**Flag-value completion**3031|Old behavior|New behavior|32|---|---|33|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion|34|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored|35|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)|36|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells|37|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`|38|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`|3940**Improvements**4142* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`)43* File completion by default if no other completions found44* Handling of required flags45* File extension filtering no longer mutually exclusive with bash usage46* Completion of directory names *within* another directory47* Support for `=` form of flags