1# Generating shell completions
2
3Cobra can generate shell completions for multiple shells.
4The currently supported shells are:
5- Bash
6- Zsh
7- fish
8- PowerShell
9
10Cobra will automatically provide your program with a fully functional `completion` command,
11similarly to how it provides the `help` command.
12
13## Creating your own completion command
14
15If you do not wish to use the default `completion` command, you can choose to
16provide your own, which will take precedence over the default one. (This also provides
17backwards-compatibility with programs that already have their own `completion` command.)
18
19If you are using the `cobra-cli` generator,
20which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli),
21you can create a completion command by running
22
23```bash
24cobra-cli add completion
25```
26and then modifying the generated `cmd/completion.go` file to look something like this
27(writing the shell script to stdout allows the most flexible use):
28
29```go
30var completionCmd = &cobra.Command{
31 Use: "completion [bash|zsh|fish|powershell]",
32 Short: "Generate completion script",
33 Long: fmt.Sprintf(`To load completions:
34
35Bash:
36
37 $ source <(%[1]s completion bash)
38
39 # To load completions for each session, execute once:
40 # Linux:
41 $ %[1]s completion bash > /etc/bash_completion.d/%[1]s
42 # macOS:
43 $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
44
45Zsh:
46
47 # If shell completion is not already enabled in your environment,
48 # you will need to enable it. You can execute the following once:
49
50 $ echo "autoload -U compinit; compinit" >> ~/.zshrc
51
52 # To load completions for each session, execute once:
53 $ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
54
55 # You will need to start a new shell for this setup to take effect.
56
57fish:
58
59 $ %[1]s completion fish | source
60
61 # To load completions for each session, execute once:
62 $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
63
64PowerShell:
65
66 PS> %[1]s completion powershell | Out-String | Invoke-Expression
67
68 # To load completions for every new session, run:
69 PS> %[1]s completion powershell > %[1]s.ps1
70 # and source this file from your PowerShell profile.
71`,cmd.Root().Name()),
72 DisableFlagsInUseLine: true,
73 ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
74 Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
75 Run: func(cmd *cobra.Command, args []string) {
76 switch args[0] {
77 case "bash":
78 cmd.Root().GenBashCompletion(os.Stdout)
79 case "zsh":
80 cmd.Root().GenZshCompletion(os.Stdout)
81 case "fish":
82 cmd.Root().GenFishCompletion(os.Stdout, true)
83 case "powershell":
84 cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
85 }
86 },
87}
88```
89
90**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.
91
92## Adapting the default completion command
93
94Cobra provides a few options for the default `completion` command. To configure such options you must set
95the `CompletionOptions` field on the *root* command.
96
97To tell Cobra *not* to provide the default `completion` command:
98```
99rootCmd.CompletionOptions.DisableDefaultCmd = true
100```
101
102To tell Cobra to mark the default `completion` command as *hidden*:
103```
104rootCmd.CompletionOptions.HiddenDefaultCmd = true
105```
106
107To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:
108```
109rootCmd.CompletionOptions.DisableNoDescFlag = true
110```
111
112To tell Cobra to completely disable descriptions for completions:
113```
114rootCmd.CompletionOptions.DisableDescriptions = true
115```
116
117# Customizing completions
118
119The 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.
120
121## Completion of nouns
122
123### Static completion of nouns
124
125Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field.
126For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them.
127Some simplified code from `kubectl get` looks like:
128
129```go
130validArgs = []string{ "pod", "node", "service", "replicationcontroller" }
131
132cmd := &cobra.Command{
133 Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
134 Short: "Display one or many resources",
135 Long: get_long,
136 Example: get_example,
137 Run: func(cmd *cobra.Command, args []string) {
138 cobra.CheckErr(RunGet(f, out, cmd, args))
139 },
140 ValidArgs: validArgs,
141}
142```
143
144Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:
145
146```bash
147$ kubectl get [tab][tab]
148node pod replicationcontroller service
149```
150
151#### Aliases for nouns
152
153If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
154
155```go
156argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
157
158cmd := &cobra.Command{
159 ...
160 ValidArgs: validArgs,
161 ArgAliases: argAliases
162}
163```
164
165The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`.
166
167### Dynamic completion of nouns
168
169In 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.
170Simplified code from `helm status` looks like:
171
172```go
173cmd := &cobra.Command{
174 Use: "status RELEASE_NAME",
175 Short: "Display the status of the named release",
176 Long: status_long,
177 RunE: func(cmd *cobra.Command, args []string) {
178 RunGet(args[0])
179 },
180 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
181 if len(args) != 0 {
182 return nil, cobra.ShellCompDirectiveNoFileComp
183 }
184 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
185 },
186}
187```
188Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
189Notice 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:
190
191```bash
192$ helm status [tab][tab]
193harbor notary rook thanos
194```
195You 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`
196```go
197// Indicates that the shell will perform its default behavior after completions
198// have been provided (this implies none of the other directives).
199ShellCompDirectiveDefault
200
201// Indicates an error occurred and completions should be ignored.
202ShellCompDirectiveError
203
204// Indicates that the shell should not add a space after the completion,
205// even if there is a single completion provided.
206ShellCompDirectiveNoSpace
207
208// Indicates that the shell should not provide file completion even when
209// no completion is provided.
210ShellCompDirectiveNoFileComp
211
212// Indicates that the returned completions should be used as file extension filters.
213// For example, to complete only files of the form *.json or *.yaml:
214// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt
215// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
216// is a shortcut to using this directive explicitly.
217//
218ShellCompDirectiveFilterFileExt
219
220// Indicates that only directory names should be provided in file completion.
221// For example:
222// return nil, ShellCompDirectiveFilterDirs
223// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.
224//
225// To request directory names within another directory, the returned completions
226// should specify a single directory name within which to search. For example,
227// to complete directories within "themes/":
228// return []string{"themes"}, ShellCompDirectiveFilterDirs
229//
230ShellCompDirectiveFilterDirs
231
232// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
233// in which the completions are provided
234ShellCompDirectiveKeepOrder
235```
236
237***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.
238
239#### Debugging
240
241Cobra 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:
242```bash
243$ helm __complete status har<ENTER>
244harbor
245:4
246Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
247```
248***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:
249```bash
250$ helm __complete status ""<ENTER>
251harbor
252notary
253rook
254thanos
255:4
256Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
257```
258Calling 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:
259```go
260// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
261// is set to a file path) and optionally prints to stderr.
262cobra.CompDebug(msg string, printToStdErr bool) {
263cobra.CompDebugln(msg string, printToStdErr bool)
264
265// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
266// is set to a file path) and to stderr.
267cobra.CompError(msg string)
268cobra.CompErrorln(msg string)
269```
270***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.
271
272## Completions for flags
273
274### Mark flags as required
275
276Most 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:
277
278```go
279cmd.MarkFlagRequired("pod")
280cmd.MarkFlagRequired("container")
281```
282
283and you'll get something like
284
285```bash
286$ kubectl exec [tab][tab]
287-c --container= -p --pod=
288```
289
290### Specify dynamic flag completion
291
292As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.
293
294```go
295flagName := "output"
296cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
297 return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
298})
299```
300Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
301
302```bash
303$ helm status --output [tab][tab]
304json table yaml
305```
306
307#### Debugging
308
309You can also easily debug your Go completion code for flags:
310```bash
311$ helm __complete status --output ""
312json
313table
314yaml
315:4
316Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
317```
318***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.
319
320### Specify valid filename extensions for flags that take a filename
321
322To 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:
323```go
324flagName := "output"
325cmd.MarkFlagFilename(flagName, "yaml", "json")
326```
327or
328```go
329flagName := "output"
330cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
331 return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})
332```
333
334### Limit flag completions to directory names
335
336To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so:
337```go
338flagName := "output"
339cmd.MarkFlagDirname(flagName)
340```
341or
342```go
343flagName := "output"
344cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
345 return nil, cobra.ShellCompDirectiveFilterDirs
346})
347```
348To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:
349```go
350flagName := "output"
351cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
352 return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs
353})
354```
355### Descriptions for completions
356
357Cobra provides support for completion descriptions. Such descriptions are supported for each shell
358(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)).
359For commands and flags, Cobra will provide the descriptions automatically, based on usage information.
360For example, using zsh:
361```
362$ helm s[tab]
363search -- search for a keyword in charts
364show -- show information of a chart
365status -- displays the status of the named release
366```
367while using fish:
368```
369$ helm s[tab]
370search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
371```
372
373Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
374```go
375ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
376 return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp
377}}
378```
379or
380```go
381ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
382```
383
384If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:
385
386```bash
387$ source <(helm completion bash)
388$ helm completion [tab][tab]
389bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell)
390fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh)
391
392$ source <(helm completion bash --no-descriptions)
393$ helm completion [tab][tab]
394bash fish powershell zsh
395```
396## Bash completions
397
398### Dependencies
399
400The 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))
401
402### Aliases
403
404You can also configure `bash` aliases for your program and they will also support completions.
405
406```bash
407alias aliasname=origcommand
408complete -o default -F __start_origcommand aliasname
409
410# and now when you run `aliasname` completion will make
411# suggestions as it did for `origcommand`.
412
413$ aliasname <tab><tab>
414completion firstcommand secondcommand
415```
416### Bash legacy dynamic completions
417
418For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
419Please refer to [Bash Completions](bash.md) for details.
420
421### Bash completion V2
422
423Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling
424`GenBashCompletion()` or `GenBashCompletionFile()`.
425
426A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or
427`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion
428(see [Bash Completions](bash.md)) but instead works only with the Go dynamic completion
429solution described in this document.
430Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash
431completion V2 solution which provides the following extra features:
432- Supports completion descriptions (like the other shells)
433- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines)
434- Streamlined user experience thanks to a completion behavior aligned with the other shells
435
436`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()`
437you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra
438will provide the description automatically based on usage information. You can choose to make this option configurable by
439your users.
440
441```
442# With descriptions
443$ helm s[tab][tab]
444search (search for a keyword in charts) status (display the status of the named release)
445show (show information of a chart)
446
447# Without descriptions
448$ helm s[tab][tab]
449search show status
450```
451**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.
452## Zsh completions
453
454Cobra supports native zsh completion generated from the root `cobra.Command`.
455The generated completion script should be put somewhere in your `$fpath` and be named
456`_<yourProgram>`. You will need to start a new shell for the completions to become available.
457
458Zsh supports descriptions for completions. Cobra will provide the description automatically,
459based on usage information. Cobra provides a way to completely disable such descriptions by
460using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make
461this a configurable option to your users.
462```
463# With descriptions
464$ helm s[tab]
465search -- search for a keyword in charts
466show -- show information of a chart
467status -- displays the status of the named release
468
469# Without descriptions
470$ helm s[tab]
471search show status
472```
473*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
474
475### Limitations
476
477* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).
478 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
479* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.
480 * You should instead use `RegisterFlagCompletionFunc()`.
481
482### Zsh completions standardization
483
484Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced.
485Please refer to [Zsh Completions](zsh.md) for details.
486
487## fish completions
488
489Cobra 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.
490```
491# With descriptions
492$ helm s[tab]
493search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
494
495# Without descriptions
496$ helm s[tab]
497search show status
498```
499*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
500
501### Limitations
502
503* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).
504 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
505* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.
506 * You should instead use `RegisterFlagCompletionFunc()`.
507* The following flag completion annotations are not supported and will be ignored for `fish`:
508 * `BashCompFilenameExt` (filtering by file extension)
509 * `BashCompSubdirsInDir` (filtering by directory)
510* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`:
511 * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
512 * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
513* Similarly, the following completion directives are not supported and will be ignored for `fish`:
514 * `ShellCompDirectiveFilterFileExt` (filtering by file extension)
515 * `ShellCompDirectiveFilterDirs` (filtering by directory)
516
517## PowerShell completions
518
519Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
520
521The script is designed to support all three PowerShell completion modes:
522
523* TabCompleteNext (default windows style - on each key press the next option is displayed)
524* Complete (works like bash)
525* MenuComplete (works like zsh)
526
527You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.
528
529Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
530
531```
532# With descriptions and Mode 'Complete'
533$ helm s[tab]
534search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
535
536# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
537$ helm s[tab]
538search show status
539
540search for a keyword in charts
541
542# Without descriptions
543$ helm s[tab]
544search show status
545```
546### Aliases
547
548You can also configure `powershell` aliases for your program and they will also support completions.
549
550```
551$ sal aliasname origcommand
552$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock
553
554# and now when you run `aliasname` completion will make
555# suggestions as it did for `origcommand`.
556
557$ aliasname <tab>
558completion firstcommand secondcommand
559```
560The name of the completer block variable is of the form `$__<programName>CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax.
561
562### Limitations
563
564* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).
565 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
566* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.
567 * You should instead use `RegisterFlagCompletionFunc()`.
568* The following flag completion annotations are not supported and will be ignored for `powershell`:
569 * `BashCompFilenameExt` (filtering by file extension)
570 * `BashCompSubdirsInDir` (filtering by directory)
571* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:
572 * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
573 * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
574* Similarly, the following completion directives are not supported and will be ignored for `powershell`:
575 * `ShellCompDirectiveFilterFileExt` (filtering by file extension)
576 * `ShellCompDirectiveFilterDirs` (filtering by directory)
View as plain text