Skip to content
Myr

Move documentation sources to site/content (#1428)

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

authored by Unai Martinez-Corral · committed by GitHub · parent cbe4865 · Browse files · 27 files+2069 added−2064 removed
This commit

State

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

Diff stats

27 files+2069 added−2064 removed

  • other:+2069 added−2064 removed

27 files+2069 added−2064 removed

deleted:doc/man_docs.md-31 removed
deleted:doc/md_docs.md-115 removed
1# Generating Markdown Docs For Your Own cobra.Command23Generating Markdown pages from a cobra command is incredibly easy. An example is as follows:45```go6package main78import (9 "log"1011 "github.com/spf13/cobra"12 "github.com/spf13/cobra/doc"13)1415func main() {16 cmd := &cobra.Command{17 Use: "test",18 Short: "my test program",19 }20 err := doc.GenMarkdownTree(cmd, "/tmp")21 if err != nil {22 log.Fatal(err)23 }24}25```2627That will get you a Markdown document `/tmp/test.md`2829## Generate markdown docs for the entire command tree3031This program can actually generate docs for the kubectl command in the kubernetes project3233```go34package main3536import (37 "log"38 "io/ioutil"39 "os"4041 "k8s.io/kubernetes/pkg/kubectl/cmd"42 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"4344 "github.com/spf13/cobra/doc"45)4647func main() {48 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)49 err := doc.GenMarkdownTree(kubectl, "./")50 if err != nil {51 log.Fatal(err)52 }53}54```5556This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")5758## Generate markdown docs for a single command5960You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`6162```go63 out := new(bytes.Buffer)64 err := doc.GenMarkdown(cmd, out)65 if err != nil {66 log.Fatal(err)67 }68```6970This will write the markdown doc for ONLY "cmd" into the out, buffer.7172## Customize the output7374Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:7576```go77func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {78 //...79}80```8182```go83func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {84 //...85}86```8788The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):8990```go91const fmTemplate = `---92date: %s93title: "%s"94slug: %s95url: %s96---97`9899filePrepender := func(filename string) string {100 now := time.Now().Format(time.RFC3339)101 name := filepath.Base(filename)102 base := strings.TrimSuffix(name, path.Ext(name))103 url := "/commands/" + strings.ToLower(base) + "/"104 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)105}106```107108The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:109110```go111linkHandler := func(name string) string {112 base := strings.TrimSuffix(name, path.Ext(name))113 return "/commands/" + strings.ToLower(base) + "/"114}115```
deleted:doc/README.md-17 removed
deleted:doc/rest_docs.md-114 removed
1# Generating ReStructured Text Docs For Your Own cobra.Command23Generating ReST pages from a cobra command is incredibly easy. An example is as follows:45```go6package main78import (9 "log"1011 "github.com/spf13/cobra"12 "github.com/spf13/cobra/doc"13)1415func main() {16 cmd := &cobra.Command{17 Use: "test",18 Short: "my test program",19 }20 err := doc.GenReSTTree(cmd, "/tmp")21 if err != nil {22 log.Fatal(err)23 }24}25```2627That will get you a ReST document `/tmp/test.rst`2829## Generate ReST docs for the entire command tree3031This program can actually generate docs for the kubectl command in the kubernetes project3233```go34package main3536import (37 "log"38 "io/ioutil"39 "os"4041 "k8s.io/kubernetes/pkg/kubectl/cmd"42 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"4344 "github.com/spf13/cobra/doc"45)4647func main() {48 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)49 err := doc.GenReSTTree(kubectl, "./")50 if err != nil {51 log.Fatal(err)52 }53}54```5556This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")5758## Generate ReST docs for a single command5960You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree`6162```go63 out := new(bytes.Buffer)64 err := doc.GenReST(cmd, out)65 if err != nil {66 log.Fatal(err)67 }68```6970This will write the ReST doc for ONLY "cmd" into the out, buffer.7172## Customize the output7374Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output:7576```go77func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {78 //...79}80```8182```go83func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {84 //...85}86```8788The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):8990```go91const fmTemplate = `---92date: %s93title: "%s"94slug: %s95url: %s96---97`98filePrepender := func(filename string) string {99 now := time.Now().Format(time.RFC3339)100 name := filepath.Base(filename)101 base := strings.TrimSuffix(name, path.Ext(name))102 url := "/commands/" + strings.ToLower(base) + "/"103 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)104}105```106107The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used:108109```go110// Sphinx cross-referencing format111linkHandler := func(name, ref string) string {112 return fmt.Sprintf(":ref:`%s <%s>`", name, ref)113}114```
deleted:doc/yaml_docs.md-112 removed
1# Generating Yaml Docs For Your Own cobra.Command23Generating yaml files from a cobra command is incredibly easy. An example is as follows:45```go6package main78import (9 "log"1011 "github.com/spf13/cobra"12 "github.com/spf13/cobra/doc"13)1415func main() {16 cmd := &cobra.Command{17 Use: "test",18 Short: "my test program",19 }20 err := doc.GenYamlTree(cmd, "/tmp")21 if err != nil {22 log.Fatal(err)23 }24}25```2627That will get you a Yaml document `/tmp/test.yaml`2829## Generate yaml docs for the entire command tree3031This program can actually generate docs for the kubectl command in the kubernetes project3233```go34package main3536import (37 "io/ioutil"38 "log"39 "os"4041 "k8s.io/kubernetes/pkg/kubectl/cmd"42 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"4344 "github.com/spf13/cobra/doc"45)4647func main() {48 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)49 err := doc.GenYamlTree(kubectl, "./")50 if err != nil {51 log.Fatal(err)52 }53}54```5556This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")5758## Generate yaml docs for a single command5960You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`6162```go63 out := new(bytes.Buffer)64 doc.GenYaml(cmd, out)65```6667This will write the yaml doc for ONLY "cmd" into the out, buffer.6869## Customize the output7071Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:7273```go74func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {75 //...76}77```7879```go80func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {81 //...82}83```8485The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):8687```go88const fmTemplate = `---89date: %s90title: "%s"91slug: %s92url: %s93---94`9596filePrepender := func(filename string) string {97 now := time.Now().Format(time.RFC3339)98 name := filepath.Base(filename)99 base := strings.TrimSuffix(name, path.Ext(name))100 url := "/commands/" + strings.ToLower(base) + "/"101 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)102}103```104105The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:106107```go108linkHandler := func(name string) string {109 base := strings.TrimSuffix(name, path.Ext(name))110 return "/commands/" + strings.ToLower(base) + "/"111}112```
added:site/content/completions/_index.md+576 added
1# Generating shell completions23Cobra can generate shell completions for multiple shells.4The currently supported shells are:5- Bash6- Zsh7- fish8- PowerShell910Cobra will automatically provide your program with a fully functional `completion` command,11similarly to how it provides the `help` command.1213## Creating your own completion command1415If you do not wish to use the default `completion` command, you can choose to16provide your own, which will take precedence over the default one. (This also provides17backwards-compatibility with programs that already have their own `completion` command.)1819If 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 running2223```bash24cobra-cli add completion25```26and then modifying the generated `cmd/completion.go` file to look something like this27(writing the shell script to stdout allows the most flexible use):2829```go30var completionCmd = &cobra.Command{31 Use: "completion [bash|zsh|fish|powershell]",32 Short: "Generate completion script",33 Long: fmt.Sprintf(`To load completions:3435Bash:3637 $ source <(%[1]s completion bash)3839 # To load completions for each session, execute once:40 # Linux:41 $ %[1]s completion bash > /etc/bash_completion.d/%[1]s42 # macOS:43 $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s4445Zsh:4647 # If shell completion is not already enabled in your environment,48 # you will need to enable it. You can execute the following once:4950 $ echo "autoload -U compinit; compinit" >> ~/.zshrc5152 # To load completions for each session, execute once:53 $ %[1]s completion zsh > "${fpath[1]}/_%[1]s"5455 # You will need to start a new shell for this setup to take effect.5657fish:5859 $ %[1]s completion fish | source6061 # To load completions for each session, execute once:62 $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish6364PowerShell:6566 PS> %[1]s completion powershell | Out-String | Invoke-Expression6768 # To load completions for every new session, run:69 PS> %[1]s completion powershell > %[1]s.ps170 # 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```8990**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.9192## Adapting the default completion command9394Cobra provides a few options for the default `completion` command. To configure such options you must set95the `CompletionOptions` field on the *root* command.9697To tell Cobra *not* to provide the default `completion` command:98```99rootCmd.CompletionOptions.DisableDefaultCmd = true100```101102To tell Cobra to mark the default `completion` command as *hidden*:103```104rootCmd.CompletionOptions.HiddenDefaultCmd = true105```106107To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:108```109rootCmd.CompletionOptions.DisableNoDescFlag = true110```111112To tell Cobra to completely disable descriptions for completions:113```114rootCmd.CompletionOptions.DisableDescriptions = true115```116117# Customizing completions118119The 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.120121## Completion of nouns122123### Static completion of nouns124125Cobra 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:128129```go130validArgs = []string{ "pod", "node", "service", "replicationcontroller" }131132cmd := &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```143144Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:145146```bash147$ kubectl get [tab][tab]148node pod replicationcontroller service149```150151#### Aliases for nouns152153If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:154155```go156argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }157158cmd := &cobra.Command{159 ...160 ValidArgs: validArgs,161 ArgAliases: argAliases162}163```164165The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`.166167### Dynamic completion of nouns168169In 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:171172```go173cmd := &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.ShellCompDirectiveNoFileComp183 }184 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp185 },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:190191```bash192$ helm status [tab][tab]193harbor notary rook thanos194```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```go197// Indicates that the shell will perform its default behavior after completions198// have been provided (this implies none of the other directives).199ShellCompDirectiveDefault200201// Indicates an error occurred and completions should be ignored.202ShellCompDirectiveError203204// Indicates that the shell should not add a space after the completion,205// even if there is a single completion provided.206ShellCompDirectiveNoSpace207208// Indicates that the shell should not provide file completion even when209// no completion is provided.210ShellCompDirectiveNoFileComp211212// Indicates that the returned completions should be used as file extension filters.213// For example, to complete only files of the form *.json or *.yaml:214// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt215// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()216// is a shortcut to using this directive explicitly.217//218ShellCompDirectiveFilterFileExt219220// Indicates that only directory names should be provided in file completion.221// For example:222// return nil, ShellCompDirectiveFilterDirs223// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.224//225// To request directory names within another directory, the returned completions226// should specify a single directory name within which to search. For example,227// to complete directories within "themes/":228// return []string{"themes"}, ShellCompDirectiveFilterDirs229//230ShellCompDirectiveFilterDirs231232// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order233// in which the completions are provided234ShellCompDirectiveKeepOrder235```236237***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.238239#### Debugging240241Cobra 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```bash243$ helm __complete status har<ENTER>244harbor245:4246Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr247```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```bash250$ helm __complete status ""<ENTER>251harbor252notary253rook254thanos255:4256Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr257```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```go260// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE261// is set to a file path) and optionally prints to stderr.262cobra.CompDebug(msg string, printToStdErr bool) {263cobra.CompDebugln(msg string, printToStdErr bool)264265// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE266// 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.271272## Completions for flags273274### Mark flags as required275276Most 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:277278```go279cmd.MarkFlagRequired("pod")280cmd.MarkFlagRequired("container")281```282283and you'll get something like284285```bash286$ kubectl exec [tab][tab]287-c --container= -p --pod=288```289290### Specify dynamic flag completion291292As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.293294```go295flagName := "output"296cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {297 return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault298})299```300Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:301302```bash303$ helm status --output [tab][tab]304json table yaml305```306307#### Debugging308309You can also easily debug your Go completion code for flags:310```bash311$ helm __complete status --output ""312json313table314yaml315:4316Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr317```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.319320### Specify valid filename extensions for flags that take a filename321322To 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```go324flagName := "output"325cmd.MarkFlagFilename(flagName, "yaml", "json")326```327or328```go329flagName := "output"330cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {331 return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})332```333334### Limit flag completions to directory names335336To 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```go338flagName := "output"339cmd.MarkFlagDirname(flagName)340```341or342```go343flagName := "output"344cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {345 return nil, cobra.ShellCompDirectiveFilterDirs346})347```348To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:349```go350flagName := "output"351cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {352 return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs353})354```355### Descriptions for completions356357Cobra provides support for completion descriptions. Such descriptions are supported for each shell358(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 charts364show -- show information of a chart365status -- displays the status of the named release366```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```372373Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:374```go375ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {376 return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp377}}378```379or380```go381ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}382```383384If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:385386```bash387$ 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)391392$ source <(helm completion bash --no-descriptions)393$ helm completion [tab][tab]394bash fish powershell zsh395```396## Bash completions397398### Dependencies399400The 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))401402### Aliases403404You can also configure `bash` aliases for your program and they will also support completions.405406```bash407alias aliasname=origcommand408complete -o default -F __start_origcommand aliasname409410# and now when you run `aliasname` completion will make411# suggestions as it did for `origcommand`.412413$ aliasname <tab><tab>414completion firstcommand secondcommand415```416### Bash legacy dynamic completions417418For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.419Please refer to [Bash Completions](bash.md) for details.420421### Bash completion V2422423Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling424`GenBashCompletion()` or `GenBashCompletionFile()`.425426A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or427`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion428(see [Bash Completions](bash.md)) but instead works only with the Go dynamic completion429solution described in this document.430Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash431completion 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 shells435436`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; Cobra438will provide the description automatically based on usage information. You can choose to make this option configurable by439your users.440441```442# With descriptions443$ 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)446447# Without descriptions448$ helm s[tab][tab]449search show status450```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 completions453454Cobra supports native zsh completion generated from the root `cobra.Command`.455The generated completion script should be put somewhere in your `$fpath` and be named456`_<yourProgram>`. You will need to start a new shell for the completions to become available.457458Zsh supports descriptions for completions. Cobra will provide the description automatically,459based on usage information. Cobra provides a way to completely disable such descriptions by460using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make461this a configurable option to your users.462```463# With descriptions464$ helm s[tab]465search -- search for a keyword in charts466show -- show information of a chart467status -- displays the status of the named release468469# Without descriptions470$ helm s[tab]471search show status472```473*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.474475### Limitations476477* 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()`.481482### Zsh completions standardization483484Cobra 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.486487## fish completions488489Cobra 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 descriptions492$ helm s[tab]493search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)494495# Without descriptions496$ helm s[tab]497search show status498```499*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.500501### Limitations502503* 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)516517## PowerShell completions518519Cobra 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.520521The script is designed to support all three PowerShell completion modes:522523* TabCompleteNext (default windows style - on each key press the next option is displayed)524* Complete (works like bash)525* MenuComplete (works like zsh)526527You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.528529Users 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.530531```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)535536# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.537$ helm s[tab]538search show status539540search for a keyword in charts541542# Without descriptions543$ helm s[tab]544search show status545```546### Aliases547548You can also configure `powershell` aliases for your program and they will also support completions.549550```551$ sal aliasname origcommand552$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock553554# and now when you run `aliasname` completion will make555# suggestions as it did for `origcommand`.556557$ aliasname <tab>558completion firstcommand secondcommand559```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.561562### Limitations563564* 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)
added:site/content/completions/bash.md+93 added
1# Generating Bash Completions For Your cobra.Command23Please refer to [Shell Completions](_index.md) for details.45## Bash legacy dynamic completions67For backward 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.89**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own.1011The 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.1213Some code that works in kubernetes:1415```bash16const (17 bash_completion_func = `__kubectl_parse_get()18{19 local kubectl_output out20 if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then21 out=($(echo "${kubectl_output}" | awk '{print $1}'))22 COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )23 fi24}2526__kubectl_get_resource()27{28 if [[ ${#nouns[@]} -eq 0 ]]; then29 return 130 fi31 __kubectl_parse_get ${nouns[${#nouns[@]} -1]}32 if [[ $? -eq 0 ]]; then33 return 034 fi35}3637__kubectl_custom_func() {38 case ${last_command} in39 kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)40 __kubectl_get_resource41 return42 ;;43 *)44 ;;45 esac46}47`)48```4950And then I set that in my command definition:5152```go53cmds := &cobra.Command{54 Use: "kubectl",55 Short: "kubectl controls the Kubernetes cluster manager",56 Long: `kubectl controls the Kubernetes cluster manager.5758Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,59 Run: runHelp,60 BashCompletionFunction: bash_completion_func,61}62```6364The `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!6566Similarly, for flags:6768```go69 annotation := make(map[string][]string)70 annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}7172 flag := &pflag.Flag{73 Name: "namespace",74 Usage: usage,75 Annotations: annotation,76 }77 cmd.Flags().AddFlag(flag)78```7980In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`81value, e.g.:8283```bash84__kubectl_get_namespaces()85{86 local template87 template="{{ range .items }}{{ .metadata.name }} {{ end }}"88 local kubectl_out89 if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then90 COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )91 fi92}93```
added:site/content/completions/fish.md+4 added
added:site/content/completions/powershell.md+3 added
added:site/content/completions/zsh.md+48 added
added:site/content/docgen/_index.md+17 added
added:site/content/docgen/man.md+31 added
added:site/content/docgen/md.md+115 added
1# Generating Markdown Docs For Your Own cobra.Command23Generating Markdown pages from a cobra command is incredibly easy. An example is as follows:45```go6package main78import (9 "log"1011 "github.com/spf13/cobra"12 "github.com/spf13/cobra/doc"13)1415func main() {16 cmd := &cobra.Command{17 Use: "test",18 Short: "my test program",19 }20 err := doc.GenMarkdownTree(cmd, "/tmp")21 if err != nil {22 log.Fatal(err)23 }24}25```2627That will get you a Markdown document `/tmp/test.md`2829## Generate markdown docs for the entire command tree3031This program can actually generate docs for the kubectl command in the kubernetes project3233```go34package main3536import (37 "log"38 "io/ioutil"39 "os"4041 "k8s.io/kubernetes/pkg/kubectl/cmd"42 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"4344 "github.com/spf13/cobra/doc"45)4647func main() {48 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)49 err := doc.GenMarkdownTree(kubectl, "./")50 if err != nil {51 log.Fatal(err)52 }53}54```5556This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")5758## Generate markdown docs for a single command5960You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`6162```go63 out := new(bytes.Buffer)64 err := doc.GenMarkdown(cmd, out)65 if err != nil {66 log.Fatal(err)67 }68```6970This will write the markdown doc for ONLY "cmd" into the out, buffer.7172## Customize the output7374Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:7576```go77func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {78 //...79}80```8182```go83func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {84 //...85}86```8788The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):8990```go91const fmTemplate = `---92date: %s93title: "%s"94slug: %s95url: %s96---97`9899filePrepender := func(filename string) string {100 now := time.Now().Format(time.RFC3339)101 name := filepath.Base(filename)102 base := strings.TrimSuffix(name, path.Ext(name))103 url := "/commands/" + strings.ToLower(base) + "/"104 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)105}106```107108The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:109110```go111linkHandler := func(name string) string {112 base := strings.TrimSuffix(name, path.Ext(name))113 return "/commands/" + strings.ToLower(base) + "/"114}115```
added:site/content/docgen/rest.md+114 added
1# Generating ReStructured Text Docs For Your Own cobra.Command23Generating ReST pages from a cobra command is incredibly easy. An example is as follows:45```go6package main78import (9 "log"1011 "github.com/spf13/cobra"12 "github.com/spf13/cobra/doc"13)1415func main() {16 cmd := &cobra.Command{17 Use: "test",18 Short: "my test program",19 }20 err := doc.GenReSTTree(cmd, "/tmp")21 if err != nil {22 log.Fatal(err)23 }24}25```2627That will get you a ReST document `/tmp/test.rst`2829## Generate ReST docs for the entire command tree3031This program can actually generate docs for the kubectl command in the kubernetes project3233```go34package main3536import (37 "log"38 "io/ioutil"39 "os"4041 "k8s.io/kubernetes/pkg/kubectl/cmd"42 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"4344 "github.com/spf13/cobra/doc"45)4647func main() {48 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)49 err := doc.GenReSTTree(kubectl, "./")50 if err != nil {51 log.Fatal(err)52 }53}54```5556This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")5758## Generate ReST docs for a single command5960You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree`6162```go63 out := new(bytes.Buffer)64 err := doc.GenReST(cmd, out)65 if err != nil {66 log.Fatal(err)67 }68```6970This will write the ReST doc for ONLY "cmd" into the out, buffer.7172## Customize the output7374Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output:7576```go77func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {78 //...79}80```8182```go83func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {84 //...85}86```8788The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):8990```go91const fmTemplate = `---92date: %s93title: "%s"94slug: %s95url: %s96---97`98filePrepender := func(filename string) string {99 now := time.Now().Format(time.RFC3339)100 name := filepath.Base(filename)101 base := strings.TrimSuffix(name, path.Ext(name))102 url := "/commands/" + strings.ToLower(base) + "/"103 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)104}105```106107The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used:108109```go110// Sphinx cross-referencing format111linkHandler := func(name, ref string) string {112 return fmt.Sprintf(":ref:`%s <%s>`", name, ref)113}114```
added:site/content/docgen/yaml.md+112 added
1# Generating Yaml Docs For Your Own cobra.Command23Generating yaml files from a cobra command is incredibly easy. An example is as follows:45```go6package main78import (9 "log"1011 "github.com/spf13/cobra"12 "github.com/spf13/cobra/doc"13)1415func main() {16 cmd := &cobra.Command{17 Use: "test",18 Short: "my test program",19 }20 err := doc.GenYamlTree(cmd, "/tmp")21 if err != nil {22 log.Fatal(err)23 }24}25```2627That will get you a Yaml document `/tmp/test.yaml`2829## Generate yaml docs for the entire command tree3031This program can actually generate docs for the kubectl command in the kubernetes project3233```go34package main3536import (37 "io/ioutil"38 "log"39 "os"4041 "k8s.io/kubernetes/pkg/kubectl/cmd"42 cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"4344 "github.com/spf13/cobra/doc"45)4647func main() {48 kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)49 err := doc.GenYamlTree(kubectl, "./")50 if err != nil {51 log.Fatal(err)52 }53}54```5556This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")5758## Generate yaml docs for a single command5960You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`6162```go63 out := new(bytes.Buffer)64 doc.GenYaml(cmd, out)65```6667This will write the yaml doc for ONLY "cmd" into the out, buffer.6869## Customize the output7071Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:7273```go74func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {75 //...76}77```7879```go80func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {81 //...82}83```8485The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):8687```go88const fmTemplate = `---89date: %s90title: "%s"91slug: %s92url: %s93---94`9596filePrepender := func(filename string) string {97 now := time.Now().Format(time.RFC3339)98 name := filepath.Base(filename)99 base := strings.TrimSuffix(name, path.Ext(name))100 url := "/commands/" + strings.ToLower(base) + "/"101 return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)102}103```104105The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:106107```go108linkHandler := func(name string) string {109 base := strings.TrimSuffix(name, path.Ext(name))110 return "/commands/" + strings.ToLower(base) + "/"111}112```
added:site/content/active_help.md+157 added
1# Active Help23Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion.45For example, 6```7bash-5.1$ helm repo add [tab]8You must choose a name for the repo you are adding.910bash-5.1$ bin/helm package [tab]11Please specify the path to the chart to package1213bash-5.1$ bin/helm package [tab][tab]14bin/ internal/ scripts/ pkg/ testdata/15```1617**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program.18## Supported shells1920Active Help is currently only supported for the following shells:21- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.22- Zsh2324## Adding Active Help messages2526As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md).2728Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details.2930### Active Help for nouns3132Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example:3334```go35cmd := &cobra.Command{36 Use: "add [NAME] [URL]",37 Short: "add a chart repository",38 Args: require.ExactArgs(2),39 RunE: func(cmd *cobra.Command, args []string) error {40 return addRepo(args)41 },42 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {43 var comps []string44 if len(args) == 0 {45 comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")46 } else if len(args) == 1 {47 comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")48 } else {49 comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")50 }51 return comps, cobra.ShellCompDirectiveNoFileComp52 },53}54```55The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior:56```57bash-5.1$ helm repo add [tab]58You must choose a name for the repo you are adding5960bash-5.1$ helm repo add grafana [tab]61You must specify the URL for the repo you are adding6263bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]64This command does not take any more arguments65```66**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions.6768### Active Help for flags6970Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:71```go72_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {73 if len(args) != 2 {74 return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp75 }76 return compVersionFlag(args[1], toComplete)77 })78```79The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.80```81bash-5.1$ bin/helm install myrelease --version 2.0.[tab]82You must first specify the chart to install before the --version flag can be completed8384bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]852.0.1 2.0.2 2.0.386```8788## User control of Active Help8990You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any.91Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.9293The way to configure Active Help is to use the program's Active Help environment94variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your 95program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever96Active Help configuration values are supported by the program.9798For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user99would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.100101For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the102Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages103should or should not be added (instead of reading the environment variable directly).104105For example:106```go107ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {108 activeHelpLevel := cobra.GetActiveHelpConfig(cmd)109110 var comps []string111 if len(args) == 0 {112 if activeHelpLevel != "off" {113 comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")114 }115 } else if len(args) == 1 {116 if activeHelpLevel != "off" {117 comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")118 }119 } else {120 if activeHelpLevel == "local" {121 comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")122 }123 }124 return comps, cobra.ShellCompDirectiveNoFileComp125},126```127**Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly.128129**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to.130131**Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. 132## Active Help with Cobra's default completion command133134Cobra provides a default `completion` command for programs that wish to use it.135When using the default `completion` command, Active Help is configurable in the same136fashion as described above using environment variables. You may wish to document this in more137details for your users.138139## Debugging Active Help140141Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details.142143When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:144```145$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>146bitnami/haproxy147bitnami/harbor148_activeHelp_ WARNING: cannot re-use a name that is still in use149:0150Completion ended with directive: ShellCompDirectiveDefault151152$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>153bitnami/haproxy154bitnami/harbor155:0156Completion ended with directive: ShellCompDirectiveDefault157```
added:site/content/projects_using_cobra.md+64 added
added:site/content/user_guide.md+731 added
1# User Guide23While you are welcome to provide your own organization, typically a Cobra-based4application will follow the following organizational structure:56```7 ▾ appName/8 ▾ cmd/9 add.go10 your.go11 commands.go12 here.go13 main.go14```1516In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.1718```go19package main2021import (22 "{pathToYourApp}/cmd"23)2425func main() {26 cmd.Execute()27}28```2930## Using the Cobra Generator3132Cobra-CLI is its own program that will create your application and add any commands you want.33It's the easiest way to incorporate Cobra into your application.3435For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)3637## Using the Cobra Library3839To manually implement Cobra you need to create a bare main.go file and a rootCmd file.40You will optionally provide additional commands as you see fit.4142### Create rootCmd4344Cobra doesn't require any special constructors. Simply create your commands.4546Ideally you place this in app/cmd/root.go:4748```go49var rootCmd = &cobra.Command{50 Use: "hugo",51 Short: "Hugo is a very fast static site generator",52 Long: `A Fast and Flexible Static Site Generator built with53 love by spf13 and friends in Go.54 Complete documentation is available at https://gohugo.io/documentation/`,55 Run: func(cmd *cobra.Command, args []string) {56 // Do Stuff Here57 },58}5960func Execute() {61 if err := rootCmd.Execute(); err != nil {62 fmt.Fprintln(os.Stderr, err)63 os.Exit(1)64 }65}66```6768You will additionally define flags and handle configuration in your init() function.6970For example cmd/root.go:7172```go73package cmd7475import (76 "fmt"77 "os"7879 "github.com/spf13/cobra"80 "github.com/spf13/viper"81)8283var (84 // Used for flags.85 cfgFile string86 userLicense string8788 rootCmd = &cobra.Command{89 Use: "cobra-cli",90 Short: "A generator for Cobra based Applications",91 Long: `Cobra is a CLI library for Go that empowers applications.92This application is a tool to generate the needed files93to quickly create a Cobra application.`,94 }95)9697// Execute executes the root command.98func Execute() error {99 return rootCmd.Execute()100}101102func init() {103 cobra.OnInitialize(initConfig)104105 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")106 rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")107 rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")108 rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")109 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))110 viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))111 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")112 viper.SetDefault("license", "apache")113114 rootCmd.AddCommand(addCmd)115 rootCmd.AddCommand(initCmd)116}117118func initConfig() {119 if cfgFile != "" {120 // Use config file from the flag.121 viper.SetConfigFile(cfgFile)122 } else {123 // Find home directory.124 home, err := os.UserHomeDir()125 cobra.CheckErr(err)126127 // Search config in home directory with name ".cobra" (without extension).128 viper.AddConfigPath(home)129 viper.SetConfigType("yaml")130 viper.SetConfigName(".cobra")131 }132133 viper.AutomaticEnv()134135 if err := viper.ReadInConfig(); err == nil {136 fmt.Println("Using config file:", viper.ConfigFileUsed())137 }138}139```140141### Create your main.go142143With the root command you need to have your main function execute it.144Execute should be run on the root for clarity, though it can be called on any command.145146In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.147148```go149package main150151import (152 "{pathToYourApp}/cmd"153)154155func main() {156 cmd.Execute()157}158```159160### Create additional commands161162Additional commands can be defined and typically are each given their own file163inside of the cmd/ directory.164165If you wanted to create a version command you would create cmd/version.go and166populate it with the following:167168```go169package cmd170171import (172 "fmt"173174 "github.com/spf13/cobra"175)176177func init() {178 rootCmd.AddCommand(versionCmd)179}180181var versionCmd = &cobra.Command{182 Use: "version",183 Short: "Print the version number of Hugo",184 Long: `All software has versions. This is Hugo's`,185 Run: func(cmd *cobra.Command, args []string) {186 fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")187 },188}189```190191### Organizing subcommands192193A command may have subcommands which in turn may have other subcommands. This is achieved by using194`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in195its own go package.196197The suggested approach is for the parent command to use `AddCommand` to add its most immediate198subcommands. For example, consider the following directory structure:199200```text201├── cmd202│   ├── root.go203│   └── sub1204│   ├── sub1.go205│   └── sub2206│   ├── leafA.go207│   ├── leafB.go208│   └── sub2.go209└── main.go210```211212In this case:213214* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.215* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.216* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the217 sub2 command.218219This approach ensures the subcommands are always included at compile time while avoiding cyclic220references.221222### Returning and handling errors223224If you wish to return an error to the caller of a command, `RunE` can be used.225226```go227package cmd228229import (230 "fmt"231232 "github.com/spf13/cobra"233)234235func init() {236 rootCmd.AddCommand(tryCmd)237}238239var tryCmd = &cobra.Command{240 Use: "try",241 Short: "Try and possibly fail at something",242 RunE: func(cmd *cobra.Command, args []string) error {243 if err := someFunc(); err != nil {244 return err245 }246 return nil247 },248}249```250251The error can then be caught at the execute function call.252253## Working with Flags254255Flags provide modifiers to control how the action command operates.256257### Assign flags to a command258259Since the flags are defined and used in different locations, we need to260define a variable outside with the correct scope to assign the flag to261work with.262263```go264var Verbose bool265var Source string266```267268There are two different approaches to assign a flag.269270### Persistent Flags271272A flag can be 'persistent', meaning that this flag will be available to the273command it's assigned to as well as every command under that command. For274global flags, assign a flag as a persistent flag on the root.275276```go277rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")278```279280### Local Flags281282A flag can also be assigned locally, which will only apply to that specific command.283284```go285localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")286```287288### Local Flag on Parent Commands289290By default, Cobra only parses local flags on the target command, and any local flags on291parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will292parse local flags on each command before executing the target command.293294```go295command := cobra.Command{296 Use: "print [OPTIONS] [COMMANDS]",297 TraverseChildren: true,298}299```300301### Bind Flags with Config302303You can also bind your flags with [viper](https://github.com/spf13/viper):304```go305var author string306307func init() {308 rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")309 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))310}311```312313In this example, the persistent flag `author` is bound with `viper`.314**Note**: the variable `author` will not be set to the value from config,315when the `--author` flag is provided by user.316317More in [viper documentation](https://github.com/spf13/viper#working-with-flags).318319### Required flags320321Flags are optional by default. If instead you wish your command to report an error322when a flag has not been set, mark it as required:323```go324rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")325rootCmd.MarkFlagRequired("region")326```327328Or, for persistent flags:329```go330rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")331rootCmd.MarkPersistentFlagRequired("region")332```333334### Flag Groups335336If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then337Cobra can enforce that requirement:338```go339rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")340rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")341rootCmd.MarkFlagsRequiredTogether("username", "password")342```343344You can also prevent different flags from being provided together if they represent mutually345exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:346```go347rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")348rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")349rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")350```351352In both of these cases:353 - both local and persistent flags can be used354 - **NOTE:** the group is only enforced on commands where every flag is defined355 - a flag may appear in multiple groups356 - a group may contain any number of flags357358## Positional and Custom Arguments359360Validation of positional arguments can be specified using the `Args` field of `Command`.361The following validators are built in:362363- Number of arguments:364 - `NoArgs` - report an error if there are any positional args.365 - `ArbitraryArgs` - accept any number of args.366 - `MinimumNArgs(int)` - report an error if less than N positional args are provided.367 - `MaximumNArgs(int)` - report an error if more than N positional args are provided.368 - `ExactArgs(int)` - report an error if there are not exactly N positional args.369 - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.370- Content of the arguments:371 - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args.372373If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.374375Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.376For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional377args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as378shown below:379380```go381var cmd = &cobra.Command{382 Short: "hello",383 Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),384 Run: func(cmd *cobra.Command, args []string) {385 fmt.Println("Hello, World!")386 },387}388```389390It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.391For example:392393```go394var cmd = &cobra.Command{395 Short: "hello",396 Args: func(cmd *cobra.Command, args []string) error {397 // Optionally run one of the validators provided by cobra398 if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {399 return err400 }401 // Run the custom validation logic402 if myapp.IsValidColor(args[0]) {403 return nil404 }405 return fmt.Errorf("invalid color specified: %s", args[0])406 },407 Run: func(cmd *cobra.Command, args []string) {408 fmt.Println("Hello, World!")409 },410}411```412413## Example414415In the example below, we have defined three commands. Two are at the top level416and one (cmdTimes) is a child of one of the top commands. In this case the root417is not executable, meaning that a subcommand is required. This is accomplished418by not providing a 'Run' for the 'rootCmd'.419420We have only defined one flag for a single command.421422More documentation about flags is available at https://github.com/spf13/pflag423424```go425package main426427import (428 "fmt"429 "strings"430431 "github.com/spf13/cobra"432)433434func main() {435 var echoTimes int436437 var cmdPrint = &cobra.Command{438 Use: "print [string to print]",439 Short: "Print anything to the screen",440 Long: `print is for printing anything back to the screen.441For many years people have printed back to the screen.`,442 Args: cobra.MinimumNArgs(1),443 Run: func(cmd *cobra.Command, args []string) {444 fmt.Println("Print: " + strings.Join(args, " "))445 },446 }447448 var cmdEcho = &cobra.Command{449 Use: "echo [string to echo]",450 Short: "Echo anything to the screen",451 Long: `echo is for echoing anything back.452Echo works a lot like print, except it has a child command.`,453 Args: cobra.MinimumNArgs(1),454 Run: func(cmd *cobra.Command, args []string) {455 fmt.Println("Echo: " + strings.Join(args, " "))456 },457 }458459 var cmdTimes = &cobra.Command{460 Use: "times [string to echo]",461 Short: "Echo anything to the screen more times",462 Long: `echo things multiple times back to the user by providing463a count and a string.`,464 Args: cobra.MinimumNArgs(1),465 Run: func(cmd *cobra.Command, args []string) {466 for i := 0; i < echoTimes; i++ {467 fmt.Println("Echo: " + strings.Join(args, " "))468 }469 },470 }471472 cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")473474 var rootCmd = &cobra.Command{Use: "app"}475 rootCmd.AddCommand(cmdPrint, cmdEcho)476 cmdEcho.AddCommand(cmdTimes)477 rootCmd.Execute()478}479```480481For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).482483## Help Command484485Cobra automatically adds a help command to your application when you have subcommands.486This will be called when a user runs 'app help'. Additionally, help will also487support all other commands as input. Say, for instance, you have a command called488'create' without any additional configuration; Cobra will work when 'app help489create' is called. Every command will automatically have the '--help' flag added.490491### Example492493The following output is automatically generated by Cobra. Nothing beyond the494command and flag definitions are needed.495496 $ cobra-cli help497498 Cobra is a CLI library for Go that empowers applications.499 This application is a tool to generate the needed files500 to quickly create a Cobra application.501502 Usage:503 cobra-cli [command]504505 Available Commands:506 add Add a command to a Cobra Application507 completion Generate the autocompletion script for the specified shell508 help Help about any command509 init Initialize a Cobra Application510511 Flags:512 -a, --author string author name for copyright attribution (default "YOUR NAME")513 --config string config file (default is $HOME/.cobra.yaml)514 -h, --help help for cobra-cli515 -l, --license string name of license for the project516 --viper use Viper for configuration517518 Use "cobra-cli [command] --help" for more information about a command.519520521Help is just a command like any other. There is no special logic or behavior522around it. In fact, you can provide your own if you want.523524### Grouping commands in help525526Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly527defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element528of that subcommand. The groups will appear in the help output in the same order as they are defined using different529calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using530`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.531532### Defining your own help533534You can provide your own Help command or your own template for the default command to use535with the following functions:536537```go538cmd.SetHelpCommand(cmd *Command)539cmd.SetHelpFunc(f func(*Command, []string))540cmd.SetHelpTemplate(s string)541```542543The latter two will also apply to any children commands.544545## Usage Message546547When the user provides an invalid flag or invalid command, Cobra responds by548showing the user the 'usage'.549550### Example551You may recognize this from the help above. That's because the default help552embeds the usage as part of its output.553554 $ cobra-cli --invalid555 Error: unknown flag: --invalid556 Usage:557 cobra-cli [command]558559 Available Commands:560 add Add a command to a Cobra Application561 completion Generate the autocompletion script for the specified shell562 help Help about any command563 init Initialize a Cobra Application564565 Flags:566 -a, --author string author name for copyright attribution (default "YOUR NAME")567 --config string config file (default is $HOME/.cobra.yaml)568 -h, --help help for cobra-cli569 -l, --license string name of license for the project570 --viper use Viper for configuration571572 Use "cobra [command] --help" for more information about a command.573574### Defining your own usage575You can provide your own usage function or template for Cobra to use.576Like help, the function and template are overridable through public methods:577578```go579cmd.SetUsageFunc(f func(*Command) error)580cmd.SetUsageTemplate(s string)581```582583## Version Flag584585Cobra adds a top-level '--version' flag if the Version field is set on the root command.586Running an application with the '--version' flag will print the version to stdout using587the version template. The template can be customized using the588`cmd.SetVersionTemplate(s string)` function.589590## PreRun and PostRun Hooks591592It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:593594- `PersistentPreRun`595- `PreRun`596- `Run`597- `PostRun`598- `PersistentPostRun`599600An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:601602```go603package main604605import (606 "fmt"607608 "github.com/spf13/cobra"609)610611func main() {612613 var rootCmd = &cobra.Command{614 Use: "root [sub]",615 Short: "My root command",616 PersistentPreRun: func(cmd *cobra.Command, args []string) {617 fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)618 },619 PreRun: func(cmd *cobra.Command, args []string) {620 fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)621 },622 Run: func(cmd *cobra.Command, args []string) {623 fmt.Printf("Inside rootCmd Run with args: %v\n", args)624 },625 PostRun: func(cmd *cobra.Command, args []string) {626 fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)627 },628 PersistentPostRun: func(cmd *cobra.Command, args []string) {629 fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)630 },631 }632633 var subCmd = &cobra.Command{634 Use: "sub [no options!]",635 Short: "My subcommand",636 PreRun: func(cmd *cobra.Command, args []string) {637 fmt.Printf("Inside subCmd PreRun with args: %v\n", args)638 },639 Run: func(cmd *cobra.Command, args []string) {640 fmt.Printf("Inside subCmd Run with args: %v\n", args)641 },642 PostRun: func(cmd *cobra.Command, args []string) {643 fmt.Printf("Inside subCmd PostRun with args: %v\n", args)644 },645 PersistentPostRun: func(cmd *cobra.Command, args []string) {646 fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)647 },648 }649650 rootCmd.AddCommand(subCmd)651652 rootCmd.SetArgs([]string{""})653 rootCmd.Execute()654 fmt.Println()655 rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})656 rootCmd.Execute()657}658```659660Output:661```662Inside rootCmd PersistentPreRun with args: []663Inside rootCmd PreRun with args: []664Inside rootCmd Run with args: []665Inside rootCmd PostRun with args: []666Inside rootCmd PersistentPostRun with args: []667668Inside rootCmd PersistentPreRun with args: [arg1 arg2]669Inside subCmd PreRun with args: [arg1 arg2]670Inside subCmd Run with args: [arg1 arg2]671Inside subCmd PostRun with args: [arg1 arg2]672Inside subCmd PersistentPostRun with args: [arg1 arg2]673```674675## Suggestions when "unknown command" happens676677Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:678679```680$ hugo srever681Error: unknown command "srever" for "hugo"682683Did you mean this?684 server685686Run 'hugo --help' for usage.687```688689Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.690691If you need to disable suggestions or tweak the string distance in your command, use:692693```go694command.DisableSuggestions = true695```696697or698699```go700command.SuggestionsMinimumDistance = 1701```702703You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which704you don't want aliases. Example:705706```707$ kubectl remove708Error: unknown command "remove" for "kubectl"709710Did you mean this?711 delete712713Run 'kubectl help' for usage.714```715716## Generating documentation for your command717718Cobra can generate documentation based on subcommands, flags, etc.719Read more about it in the [docs generation documentation](docgen/_index.md).720721## Generating shell completions722723Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell.724If you add more information to your commands, these completions can be amazingly powerful and flexible.725Read more about it in [Shell Completions](completions/_index.md).726727## Providing Active Help728729Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users.730Active Help are messages (hints, warnings, etc) printed as the program is being used.731Read more about it in [Active Help](active_help.md).
deleted:active_help.md-157 removed
1# Active Help23Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion.45For example, 6```7bash-5.1$ helm repo add [tab]8You must choose a name for the repo you are adding.910bash-5.1$ bin/helm package [tab]11Please specify the path to the chart to package1213bash-5.1$ bin/helm package [tab][tab]14bin/ internal/ scripts/ pkg/ testdata/15```1617**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program.18## Supported shells1920Active Help is currently only supported for the following shells:21- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.22- Zsh2324## Adding Active Help messages2526As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md).2728Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details.2930### Active Help for nouns3132Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example:3334```go35cmd := &cobra.Command{36 Use: "add [NAME] [URL]",37 Short: "add a chart repository",38 Args: require.ExactArgs(2),39 RunE: func(cmd *cobra.Command, args []string) error {40 return addRepo(args)41 },42 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {43 var comps []string44 if len(args) == 0 {45 comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")46 } else if len(args) == 1 {47 comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")48 } else {49 comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")50 }51 return comps, cobra.ShellCompDirectiveNoFileComp52 },53}54```55The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior:56```57bash-5.1$ helm repo add [tab]58You must choose a name for the repo you are adding5960bash-5.1$ helm repo add grafana [tab]61You must specify the URL for the repo you are adding6263bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]64This command does not take any more arguments65```66**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions.6768### Active Help for flags6970Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:71```go72_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {73 if len(args) != 2 {74 return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp75 }76 return compVersionFlag(args[1], toComplete)77 })78```79The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.80```81bash-5.1$ bin/helm install myrelease --version 2.0.[tab]82You must first specify the chart to install before the --version flag can be completed8384bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]852.0.1 2.0.2 2.0.386```8788## User control of Active Help8990You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any.91Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.9293The way to configure Active Help is to use the program's Active Help environment94variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your 95program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever96Active Help configuration values are supported by the program.9798For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user99would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.100101For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the102Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages103should or should not be added (instead of reading the environment variable directly).104105For example:106```go107ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {108 activeHelpLevel := cobra.GetActiveHelpConfig(cmd)109110 var comps []string111 if len(args) == 0 {112 if activeHelpLevel != "off" {113 comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")114 }115 } else if len(args) == 1 {116 if activeHelpLevel != "off" {117 comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")118 }119 } else {120 if activeHelpLevel == "local" {121 comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")122 }123 }124 return comps, cobra.ShellCompDirectiveNoFileComp125},126```127**Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly.128129**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to.130131**Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. 132## Active Help with Cobra's default completion command133134Cobra provides a default `completion` command for programs that wish to use it.135When using the default `completion` command, Active Help is configurable in the same136fashion as described above using environment variables. You may wish to document this in more137details for your users.138139## Debugging Active Help140141Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details.142143When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:144```145$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>146bitnami/haproxy147bitnami/harbor148_activeHelp_ WARNING: cannot re-use a name that is still in use149:0150Completion ended with directive: ShellCompDirectiveDefault151152$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>153bitnami/haproxy154bitnami/harbor155:0156Completion ended with directive: ShellCompDirectiveDefault157```
deleted:bash_completions.md-93 removed
1# Generating Bash Completions For Your cobra.Command23Please refer to [Shell Completions](shell_completions.md) for details.45## Bash legacy dynamic completions67For backward 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.89**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own.1011The 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.1213Some code that works in kubernetes:1415```bash16const (17 bash_completion_func = `__kubectl_parse_get()18{19 local kubectl_output out20 if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then21 out=($(echo "${kubectl_output}" | awk '{print $1}'))22 COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )23 fi24}2526__kubectl_get_resource()27{28 if [[ ${#nouns[@]} -eq 0 ]]; then29 return 130 fi31 __kubectl_parse_get ${nouns[${#nouns[@]} -1]}32 if [[ $? -eq 0 ]]; then33 return 034 fi35}3637__kubectl_custom_func() {38 case ${last_command} in39 kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)40 __kubectl_get_resource41 return42 ;;43 *)44 ;;45 esac46}47`)48```4950And then I set that in my command definition:5152```go53cmds := &cobra.Command{54 Use: "kubectl",55 Short: "kubectl controls the Kubernetes cluster manager",56 Long: `kubectl controls the Kubernetes cluster manager.5758Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,59 Run: runHelp,60 BashCompletionFunction: bash_completion_func,61}62```6364The `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!6566Similarly, for flags:6768```go69 annotation := make(map[string][]string)70 annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}7172 flag := &pflag.Flag{73 Name: "namespace",74 Usage: usage,75 Annotations: annotation,76 }77 cmd.Flags().AddFlag(flag)78```7980In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`81value, e.g.:8283```bash84__kubectl_get_namespaces()85{86 local template87 template="{{ range .items }}{{ .metadata.name }} {{ end }}"88 local kubectl_out89 if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then90 COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )91 fi92}93```
deleted:fish_completions.md-4 removed
1## Generating Fish Completions For Your cobra.Command23Please refer to [Shell Completions](shell_completions.md) for details.4
deleted:powershell_completions.md-3 removed
1# Generating PowerShell Completions For Your Own cobra.Command23Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details.
deleted:projects_using_cobra.md-64 removed
1## Projects using Cobra23- [Allero](https://github.com/allero-io/allero)4- [Arewefastyet](https://benchmark.vitess.io)5- [Arduino CLI](https://github.com/arduino/arduino-cli)6- [Bleve](https://blevesearch.com/)7- [Cilium](https://cilium.io/)8- [CloudQuery](https://github.com/cloudquery/cloudquery)9- [CockroachDB](https://www.cockroachlabs.com/)10- [Constellation](https://github.com/edgelesssys/constellation)11- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)12- [Datree](https://github.com/datreeio/datree)13- [Delve](https://github.com/derekparker/delve)14- [Docker (distribution)](https://github.com/docker/distribution)15- [Etcd](https://etcd.io/)16- [Gardener](https://github.com/gardener/gardenctl)17- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)18- [Git Bump](https://github.com/erdaltsksn/git-bump)19- [GitHub CLI](https://github.com/cli/cli)20- [GitHub Labeler](https://github.com/erdaltsksn/gh-label)21- [Golangci-lint](https://golangci-lint.run)22- [GopherJS](https://github.com/gopherjs/gopherjs)23- [GoReleaser](https://goreleaser.com)24- [Helm](https://helm.sh)25- [Hugo](https://gohugo.io)26- [Infracost](https://github.com/infracost/infracost)27- [Istio](https://istio.io)28- [Kool](https://github.com/kool-dev/kool)29- [Kubernetes](https://kubernetes.io/)30- [Kubescape](https://github.com/kubescape/kubescape)31- [KubeVirt](https://github.com/kubevirt/kubevirt)32- [Linkerd](https://linkerd.io/)33- [Mattermost-server](https://github.com/mattermost/mattermost-server)34- [Mercure](https://mercure.rocks/)35- [Meroxa CLI](https://github.com/meroxa/cli)36- [Metal Stack CLI](https://github.com/metal-stack/metalctl)37- [Moby (former Docker)](https://github.com/moby/moby)38- [Moldy](https://github.com/Moldy-Community/moldy)39- [Multi-gitter](https://github.com/lindell/multi-gitter)40- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)41- [nFPM](https://nfpm.goreleaser.com)42- [Okteto](https://github.com/okteto/okteto)43- [OpenShift](https://www.openshift.com/)44- [Ory Hydra](https://github.com/ory/hydra)45- [Ory Kratos](https://github.com/ory/kratos)46- [Pixie](https://github.com/pixie-io/pixie)47- [Polygon Edge](https://github.com/0xPolygon/polygon-edge)48- [Pouch](https://github.com/alibaba/pouch)49- [ProjectAtomic (enterprise)](https://www.projectatomic.io/)50- [Prototool](https://github.com/uber/prototool)51- [Pulumi](https://www.pulumi.com)52- [QRcp](https://github.com/claudiodangelis/qrcp)53- [Random](https://github.com/erdaltsksn/random)54- [Rclone](https://rclone.org/)55- [Scaleway CLI](https://github.com/scaleway/scaleway-cli)56- [Sia](https://github.com/SiaFoundation/siad)57- [Skaffold](https://skaffold.dev/)58- [Tendermint](https://github.com/tendermint/tendermint)59- [Twitch CLI](https://github.com/twitchdev/twitch-cli)60- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)61- [Vitess](https://vitess.io)62- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)63- [Werf](https://werf.io/)64- [ZITADEL](https://github.com/zitadel/zitadel)
modified:README.md+4 added-4 removed
2 unmodified lines
3Cobra is a library for creating powerful modern CLI applications.45Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),6[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to7name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.7name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra.89[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)10[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra)11[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
67 unmodified lines
79which maintains the same interface while adding POSIX compliance.8081# Installing82Using Cobra is easy. First, use `go get` to install the latest version83of the library. 83of the library.8485```86go get -u github.com/spf13/cobra@latest87```
16 unmodified lines
104```105106For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)107108For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).108For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md).109110# License111112Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)112Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt)
deleted:shell_completions.md-576 removed
1# Generating shell completions23Cobra can generate shell completions for multiple shells.4The currently supported shells are:5- Bash6- Zsh7- fish8- PowerShell910Cobra will automatically provide your program with a fully functional `completion` command,11similarly to how it provides the `help` command.1213## Creating your own completion command1415If you do not wish to use the default `completion` command, you can choose to16provide your own, which will take precedence over the default one. (This also provides17backwards-compatibility with programs that already have their own `completion` command.)1819If 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 running2223```bash24cobra-cli add completion25```26and then modifying the generated `cmd/completion.go` file to look something like this27(writing the shell script to stdout allows the most flexible use):2829```go30var completionCmd = &cobra.Command{31 Use: "completion [bash|zsh|fish|powershell]",32 Short: "Generate completion script",33 Long: fmt.Sprintf(`To load completions:3435Bash:3637 $ source <(%[1]s completion bash)3839 # To load completions for each session, execute once:40 # Linux:41 $ %[1]s completion bash > /etc/bash_completion.d/%[1]s42 # macOS:43 $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s4445Zsh:4647 # If shell completion is not already enabled in your environment,48 # you will need to enable it. You can execute the following once:4950 $ echo "autoload -U compinit; compinit" >> ~/.zshrc5152 # To load completions for each session, execute once:53 $ %[1]s completion zsh > "${fpath[1]}/_%[1]s"5455 # You will need to start a new shell for this setup to take effect.5657fish:5859 $ %[1]s completion fish | source6061 # To load completions for each session, execute once:62 $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish6364PowerShell:6566 PS> %[1]s completion powershell | Out-String | Invoke-Expression6768 # To load completions for every new session, run:69 PS> %[1]s completion powershell > %[1]s.ps170 # 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```8990**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.9192## Adapting the default completion command9394Cobra provides a few options for the default `completion` command. To configure such options you must set95the `CompletionOptions` field on the *root* command.9697To tell Cobra *not* to provide the default `completion` command:98```99rootCmd.CompletionOptions.DisableDefaultCmd = true100```101102To tell Cobra to mark the default `completion` command as *hidden*:103```104rootCmd.CompletionOptions.HiddenDefaultCmd = true105```106107To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:108```109rootCmd.CompletionOptions.DisableNoDescFlag = true110```111112To tell Cobra to completely disable descriptions for completions:113```114rootCmd.CompletionOptions.DisableDescriptions = true115```116117# Customizing completions118119The 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.120121## Completion of nouns122123### Static completion of nouns124125Cobra 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:128129```go130validArgs = []string{ "pod", "node", "service", "replicationcontroller" }131132cmd := &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```143144Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:145146```bash147$ kubectl get [tab][tab]148node pod replicationcontroller service149```150151#### Aliases for nouns152153If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:154155```go156argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }157158cmd := &cobra.Command{159 ...160 ValidArgs: validArgs,161 ArgAliases: argAliases162}163```164165The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`.166167### Dynamic completion of nouns168169In 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:171172```go173cmd := &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.ShellCompDirectiveNoFileComp183 }184 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp185 },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:190191```bash192$ helm status [tab][tab]193harbor notary rook thanos194```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```go197// Indicates that the shell will perform its default behavior after completions198// have been provided (this implies none of the other directives).199ShellCompDirectiveDefault200201// Indicates an error occurred and completions should be ignored.202ShellCompDirectiveError203204// Indicates that the shell should not add a space after the completion,205// even if there is a single completion provided.206ShellCompDirectiveNoSpace207208// Indicates that the shell should not provide file completion even when209// no completion is provided.210ShellCompDirectiveNoFileComp211212// Indicates that the returned completions should be used as file extension filters.213// For example, to complete only files of the form *.json or *.yaml:214// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt215// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()216// is a shortcut to using this directive explicitly.217//218ShellCompDirectiveFilterFileExt219220// Indicates that only directory names should be provided in file completion.221// For example:222// return nil, ShellCompDirectiveFilterDirs223// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.224//225// To request directory names within another directory, the returned completions226// should specify a single directory name within which to search. For example,227// to complete directories within "themes/":228// return []string{"themes"}, ShellCompDirectiveFilterDirs229//230ShellCompDirectiveFilterDirs231232// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order233// in which the completions are provided234ShellCompDirectiveKeepOrder235```236237***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.238239#### Debugging240241Cobra 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```bash243$ helm __complete status har<ENTER>244harbor245:4246Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr247```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```bash250$ helm __complete status ""<ENTER>251harbor252notary253rook254thanos255:4256Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr257```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```go260// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE261// is set to a file path) and optionally prints to stderr.262cobra.CompDebug(msg string, printToStdErr bool) {263cobra.CompDebugln(msg string, printToStdErr bool)264265// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE266// 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.271272## Completions for flags273274### Mark flags as required275276Most 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:277278```go279cmd.MarkFlagRequired("pod")280cmd.MarkFlagRequired("container")281```282283and you'll get something like284285```bash286$ kubectl exec [tab][tab]287-c --container= -p --pod=288```289290### Specify dynamic flag completion291292As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.293294```go295flagName := "output"296cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {297 return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault298})299```300Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:301302```bash303$ helm status --output [tab][tab]304json table yaml305```306307#### Debugging308309You can also easily debug your Go completion code for flags:310```bash311$ helm __complete status --output ""312json313table314yaml315:4316Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr317```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.319320### Specify valid filename extensions for flags that take a filename321322To 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```go324flagName := "output"325cmd.MarkFlagFilename(flagName, "yaml", "json")326```327or328```go329flagName := "output"330cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {331 return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})332```333334### Limit flag completions to directory names335336To 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```go338flagName := "output"339cmd.MarkFlagDirname(flagName)340```341or342```go343flagName := "output"344cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {345 return nil, cobra.ShellCompDirectiveFilterDirs346})347```348To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:349```go350flagName := "output"351cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {352 return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs353})354```355### Descriptions for completions356357Cobra provides support for completion descriptions. Such descriptions are supported for each shell358(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 charts364show -- show information of a chart365status -- displays the status of the named release366```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```372373Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:374```go375ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {376 return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp377}}378```379or380```go381ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}382```383384If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:385386```bash387$ 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)391392$ source <(helm completion bash --no-descriptions)393$ helm completion [tab][tab]394bash fish powershell zsh395```396## Bash completions397398### Dependencies399400The 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))401402### Aliases403404You can also configure `bash` aliases for your program and they will also support completions.405406```bash407alias aliasname=origcommand408complete -o default -F __start_origcommand aliasname409410# and now when you run `aliasname` completion will make411# suggestions as it did for `origcommand`.412413$ aliasname <tab><tab>414completion firstcommand secondcommand415```416### Bash legacy dynamic completions417418For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.419Please refer to [Bash Completions](bash_completions.md) for details.420421### Bash completion V2422423Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling424`GenBashCompletion()` or `GenBashCompletionFile()`.425426A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or427`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion428(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion429solution described in this document.430Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash431completion 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 435436`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; Cobra438will provide the description automatically based on usage information. You can choose to make this option configurable by439your users.440441```442# With descriptions443$ 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)446447# Without descriptions448$ helm s[tab][tab]449search show status450```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 completions453454Cobra supports native zsh completion generated from the root `cobra.Command`.455The generated completion script should be put somewhere in your `$fpath` and be named456`_<yourProgram>`. You will need to start a new shell for the completions to become available.457458Zsh supports descriptions for completions. Cobra will provide the description automatically,459based on usage information. Cobra provides a way to completely disable such descriptions by460using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make461this a configurable option to your users.462```463# With descriptions464$ helm s[tab]465search -- search for a keyword in charts466show -- show information of a chart467status -- displays the status of the named release468469# Without descriptions470$ helm s[tab]471search show status472```473*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.474475### Limitations476477* 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()`.481482### Zsh completions standardization483484Cobra 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_completions.md) for details.486487## fish completions488489Cobra 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 descriptions492$ helm s[tab]493search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)494495# Without descriptions496$ helm s[tab]497search show status498```499*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.500501### Limitations502503* 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)516517## PowerShell completions518519Cobra 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.520521The script is designed to support all three PowerShell completion modes:522523* TabCompleteNext (default windows style - on each key press the next option is displayed)524* Complete (works like bash)525* MenuComplete (works like zsh)526527You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.528529Users 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.530531```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)535536# 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 539540search for a keyword in charts541542# Without descriptions543$ helm s[tab]544search show status545```546### Aliases547548You can also configure `powershell` aliases for your program and they will also support completions.549550```551$ sal aliasname origcommand552$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock553554# and now when you run `aliasname` completion will make555# suggestions as it did for `origcommand`.556557$ aliasname <tab>558completion firstcommand secondcommand559```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.561562### Limitations563564* 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)
deleted:user_guide.md-726 removed
1# User Guide23While you are welcome to provide your own organization, typically a Cobra-based4application will follow the following organizational structure:56```7 ▾ appName/8 ▾ cmd/9 add.go10 your.go11 commands.go12 here.go13 main.go14```1516In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.1718```go19package main2021import (22 "{pathToYourApp}/cmd"23)2425func main() {26 cmd.Execute()27}28```2930## Using the Cobra Generator3132Cobra-CLI is its own program that will create your application and add any33commands you want. It's the easiest way to incorporate Cobra into your application.3435For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)3637## Using the Cobra Library3839To manually implement Cobra you need to create a bare main.go file and a rootCmd file.40You will optionally provide additional commands as you see fit.4142### Create rootCmd4344Cobra doesn't require any special constructors. Simply create your commands.4546Ideally you place this in app/cmd/root.go:4748```go49var rootCmd = &cobra.Command{50 Use: "hugo",51 Short: "Hugo is a very fast static site generator",52 Long: `A Fast and Flexible Static Site Generator built with53 love by spf13 and friends in Go.54 Complete documentation is available at https://gohugo.io/documentation/`,55 Run: func(cmd *cobra.Command, args []string) {56 // Do Stuff Here57 },58}5960func Execute() {61 if err := rootCmd.Execute(); err != nil {62 fmt.Fprintln(os.Stderr, err)63 os.Exit(1)64 }65}66```6768You will additionally define flags and handle configuration in your init() function.6970For example cmd/root.go:7172```go73package cmd7475import (76 "fmt"77 "os"7879 "github.com/spf13/cobra"80 "github.com/spf13/viper"81)8283var (84 // Used for flags.85 cfgFile string86 userLicense string8788 rootCmd = &cobra.Command{89 Use: "cobra-cli",90 Short: "A generator for Cobra based Applications",91 Long: `Cobra is a CLI library for Go that empowers applications.92This application is a tool to generate the needed files93to quickly create a Cobra application.`,94 }95)9697// Execute executes the root command.98func Execute() error {99 return rootCmd.Execute()100}101102func init() {103 cobra.OnInitialize(initConfig)104105 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")106 rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")107 rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")108 rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")109 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))110 viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))111 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")112 viper.SetDefault("license", "apache")113114 rootCmd.AddCommand(addCmd)115 rootCmd.AddCommand(initCmd)116}117118func initConfig() {119 if cfgFile != "" {120 // Use config file from the flag.121 viper.SetConfigFile(cfgFile)122 } else {123 // Find home directory.124 home, err := os.UserHomeDir()125 cobra.CheckErr(err)126127 // Search config in home directory with name ".cobra" (without extension).128 viper.AddConfigPath(home)129 viper.SetConfigType("yaml")130 viper.SetConfigName(".cobra")131 }132133 viper.AutomaticEnv()134135 if err := viper.ReadInConfig(); err == nil {136 fmt.Println("Using config file:", viper.ConfigFileUsed())137 }138}139```140141### Create your main.go142143With the root command you need to have your main function execute it.144Execute should be run on the root for clarity, though it can be called on any command.145146In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.147148```go149package main150151import (152 "{pathToYourApp}/cmd"153)154155func main() {156 cmd.Execute()157}158```159160### Create additional commands161162Additional commands can be defined and typically are each given their own file163inside of the cmd/ directory.164165If you wanted to create a version command you would create cmd/version.go and166populate it with the following:167168```go169package cmd170171import (172 "fmt"173174 "github.com/spf13/cobra"175)176177func init() {178 rootCmd.AddCommand(versionCmd)179}180181var versionCmd = &cobra.Command{182 Use: "version",183 Short: "Print the version number of Hugo",184 Long: `All software has versions. This is Hugo's`,185 Run: func(cmd *cobra.Command, args []string) {186 fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")187 },188}189```190191### Organizing subcommands192193A command may have subcommands which in turn may have other subcommands. This is achieved by using194`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in195its own go package.196197The suggested approach is for the parent command to use `AddCommand` to add its most immediate198subcommands. For example, consider the following directory structure:199200```text201├── cmd202│   ├── root.go203│   └── sub1204│   ├── sub1.go205│   └── sub2206│   ├── leafA.go207│   ├── leafB.go208│   └── sub2.go209└── main.go210```211212In this case:213214* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.215* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.216* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the217 sub2 command.218219This approach ensures the subcommands are always included at compile time while avoiding cyclic220references.221222### Returning and handling errors223224If you wish to return an error to the caller of a command, `RunE` can be used.225226```go227package cmd228229import (230 "fmt"231232 "github.com/spf13/cobra"233)234235func init() {236 rootCmd.AddCommand(tryCmd)237}238239var tryCmd = &cobra.Command{240 Use: "try",241 Short: "Try and possibly fail at something",242 RunE: func(cmd *cobra.Command, args []string) error {243 if err := someFunc(); err != nil {244 return err245 }246 return nil247 },248}249```250251The error can then be caught at the execute function call.252253## Working with Flags254255Flags provide modifiers to control how the action command operates.256257### Assign flags to a command258259Since the flags are defined and used in different locations, we need to260define a variable outside with the correct scope to assign the flag to261work with.262263```go264var Verbose bool265var Source string266```267268There are two different approaches to assign a flag.269270### Persistent Flags271272A flag can be 'persistent', meaning that this flag will be available to the273command it's assigned to as well as every command under that command. For274global flags, assign a flag as a persistent flag on the root.275276```go277rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")278```279280### Local Flags281282A flag can also be assigned locally, which will only apply to that specific command.283284```go285localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")286```287288### Local Flag on Parent Commands289290By default, Cobra only parses local flags on the target command, and any local flags on291parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will292parse local flags on each command before executing the target command.293294```go295command := cobra.Command{296 Use: "print [OPTIONS] [COMMANDS]",297 TraverseChildren: true,298}299```300301### Bind Flags with Config302303You can also bind your flags with [viper](https://github.com/spf13/viper):304```go305var author string306307func init() {308 rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")309 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))310}311```312313In this example, the persistent flag `author` is bound with `viper`.314**Note**: the variable `author` will not be set to the value from config,315when the `--author` flag is provided by user.316317More in [viper documentation](https://github.com/spf13/viper#working-with-flags).318319### Required flags320321Flags are optional by default. If instead you wish your command to report an error322when a flag has not been set, mark it as required:323```go324rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")325rootCmd.MarkFlagRequired("region")326```327328Or, for persistent flags:329```go330rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")331rootCmd.MarkPersistentFlagRequired("region")332```333334### Flag Groups335336If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then337Cobra can enforce that requirement:338```go339rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")340rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")341rootCmd.MarkFlagsRequiredTogether("username", "password")342```343344You can also prevent different flags from being provided together if they represent mutually345exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:346```go347rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")348rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")349rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")350```351352In both of these cases:353 - both local and persistent flags can be used354 - **NOTE:** the group is only enforced on commands where every flag is defined355 - a flag may appear in multiple groups356 - a group may contain any number of flags357358## Positional and Custom Arguments359360Validation of positional arguments can be specified using the `Args` field of `Command`.361The following validators are built in:362363- Number of arguments:364 - `NoArgs` - report an error if there are any positional args.365 - `ArbitraryArgs` - accept any number of args.366 - `MinimumNArgs(int)` - report an error if less than N positional args are provided.367 - `MaximumNArgs(int)` - report an error if more than N positional args are provided.368 - `ExactArgs(int)` - report an error if there are not exactly N positional args.369 - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.370- Content of the arguments:371 - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args.372373If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.374375Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.376For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional377args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as378shown below:379380```go381var cmd = &cobra.Command{382 Short: "hello",383 Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),384 Run: func(cmd *cobra.Command, args []string) {385 fmt.Println("Hello, World!")386 },387}388```389390It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.391For example:392393```go394var cmd = &cobra.Command{395 Short: "hello",396 Args: func(cmd *cobra.Command, args []string) error {397 // Optionally run one of the validators provided by cobra398 if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {399 return err400 }401 // Run the custom validation logic402 if myapp.IsValidColor(args[0]) {403 return nil404 }405 return fmt.Errorf("invalid color specified: %s", args[0])406 },407 Run: func(cmd *cobra.Command, args []string) {408 fmt.Println("Hello, World!")409 },410}411```412413## Example414415In the example below, we have defined three commands. Two are at the top level416and one (cmdTimes) is a child of one of the top commands. In this case the root417is not executable, meaning that a subcommand is required. This is accomplished418by not providing a 'Run' for the 'rootCmd'.419420We have only defined one flag for a single command.421422More documentation about flags is available at https://github.com/spf13/pflag423424```go425package main426427import (428 "fmt"429 "strings"430431 "github.com/spf13/cobra"432)433434func main() {435 var echoTimes int436437 var cmdPrint = &cobra.Command{438 Use: "print [string to print]",439 Short: "Print anything to the screen",440 Long: `print is for printing anything back to the screen.441For many years people have printed back to the screen.`,442 Args: cobra.MinimumNArgs(1),443 Run: func(cmd *cobra.Command, args []string) {444 fmt.Println("Print: " + strings.Join(args, " "))445 },446 }447448 var cmdEcho = &cobra.Command{449 Use: "echo [string to echo]",450 Short: "Echo anything to the screen",451 Long: `echo is for echoing anything back.452Echo works a lot like print, except it has a child command.`,453 Args: cobra.MinimumNArgs(1),454 Run: func(cmd *cobra.Command, args []string) {455 fmt.Println("Echo: " + strings.Join(args, " "))456 },457 }458459 var cmdTimes = &cobra.Command{460 Use: "times [string to echo]",461 Short: "Echo anything to the screen more times",462 Long: `echo things multiple times back to the user by providing463a count and a string.`,464 Args: cobra.MinimumNArgs(1),465 Run: func(cmd *cobra.Command, args []string) {466 for i := 0; i < echoTimes; i++ {467 fmt.Println("Echo: " + strings.Join(args, " "))468 }469 },470 }471472 cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")473474 var rootCmd = &cobra.Command{Use: "app"}475 rootCmd.AddCommand(cmdPrint, cmdEcho)476 cmdEcho.AddCommand(cmdTimes)477 rootCmd.Execute()478}479```480481For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).482483## Help Command484485Cobra automatically adds a help command to your application when you have subcommands.486This will be called when a user runs 'app help'. Additionally, help will also487support all other commands as input. Say, for instance, you have a command called488'create' without any additional configuration; Cobra will work when 'app help489create' is called. Every command will automatically have the '--help' flag added.490491### Example492493The following output is automatically generated by Cobra. Nothing beyond the494command and flag definitions are needed.495496 $ cobra-cli help497498 Cobra is a CLI library for Go that empowers applications.499 This application is a tool to generate the needed files500 to quickly create a Cobra application.501502 Usage:503 cobra-cli [command]504505 Available Commands:506 add Add a command to a Cobra Application507 completion Generate the autocompletion script for the specified shell508 help Help about any command509 init Initialize a Cobra Application510511 Flags:512 -a, --author string author name for copyright attribution (default "YOUR NAME")513 --config string config file (default is $HOME/.cobra.yaml)514 -h, --help help for cobra-cli515 -l, --license string name of license for the project516 --viper use Viper for configuration517518 Use "cobra-cli [command] --help" for more information about a command.519520521Help is just a command like any other. There is no special logic or behavior522around it. In fact, you can provide your own if you want.523524### Grouping commands in help525526Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly527defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element528of that subcommand. The groups will appear in the help output in the same order as they are defined using different529calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using530`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.531532### Defining your own help533534You can provide your own Help command or your own template for the default command to use535with the following functions:536537```go538cmd.SetHelpCommand(cmd *Command)539cmd.SetHelpFunc(f func(*Command, []string))540cmd.SetHelpTemplate(s string)541```542543The latter two will also apply to any children commands.544545## Usage Message546547When the user provides an invalid flag or invalid command, Cobra responds by548showing the user the 'usage'.549550### Example551You may recognize this from the help above. That's because the default help552embeds the usage as part of its output.553554 $ cobra-cli --invalid555 Error: unknown flag: --invalid556 Usage:557 cobra-cli [command]558559 Available Commands:560 add Add a command to a Cobra Application561 completion Generate the autocompletion script for the specified shell562 help Help about any command563 init Initialize a Cobra Application564565 Flags:566 -a, --author string author name for copyright attribution (default "YOUR NAME")567 --config string config file (default is $HOME/.cobra.yaml)568 -h, --help help for cobra-cli569 -l, --license string name of license for the project570 --viper use Viper for configuration571572 Use "cobra [command] --help" for more information about a command.573574### Defining your own usage575You can provide your own usage function or template for Cobra to use.576Like help, the function and template are overridable through public methods:577578```go579cmd.SetUsageFunc(f func(*Command) error)580cmd.SetUsageTemplate(s string)581```582583## Version Flag584585Cobra adds a top-level '--version' flag if the Version field is set on the root command.586Running an application with the '--version' flag will print the version to stdout using587the version template. The template can be customized using the588`cmd.SetVersionTemplate(s string)` function.589590## PreRun and PostRun Hooks591592It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:593594- `PersistentPreRun`595- `PreRun`596- `Run`597- `PostRun`598- `PersistentPostRun`599600An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:601602```go603package main604605import (606 "fmt"607608 "github.com/spf13/cobra"609)610611func main() {612613 var rootCmd = &cobra.Command{614 Use: "root [sub]",615 Short: "My root command",616 PersistentPreRun: func(cmd *cobra.Command, args []string) {617 fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)618 },619 PreRun: func(cmd *cobra.Command, args []string) {620 fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)621 },622 Run: func(cmd *cobra.Command, args []string) {623 fmt.Printf("Inside rootCmd Run with args: %v\n", args)624 },625 PostRun: func(cmd *cobra.Command, args []string) {626 fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)627 },628 PersistentPostRun: func(cmd *cobra.Command, args []string) {629 fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)630 },631 }632633 var subCmd = &cobra.Command{634 Use: "sub [no options!]",635 Short: "My subcommand",636 PreRun: func(cmd *cobra.Command, args []string) {637 fmt.Printf("Inside subCmd PreRun with args: %v\n", args)638 },639 Run: func(cmd *cobra.Command, args []string) {640 fmt.Printf("Inside subCmd Run with args: %v\n", args)641 },642 PostRun: func(cmd *cobra.Command, args []string) {643 fmt.Printf("Inside subCmd PostRun with args: %v\n", args)644 },645 PersistentPostRun: func(cmd *cobra.Command, args []string) {646 fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)647 },648 }649650 rootCmd.AddCommand(subCmd)651652 rootCmd.SetArgs([]string{""})653 rootCmd.Execute()654 fmt.Println()655 rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})656 rootCmd.Execute()657}658```659660Output:661```662Inside rootCmd PersistentPreRun with args: []663Inside rootCmd PreRun with args: []664Inside rootCmd Run with args: []665Inside rootCmd PostRun with args: []666Inside rootCmd PersistentPostRun with args: []667668Inside rootCmd PersistentPreRun with args: [arg1 arg2]669Inside subCmd PreRun with args: [arg1 arg2]670Inside subCmd Run with args: [arg1 arg2]671Inside subCmd PostRun with args: [arg1 arg2]672Inside subCmd PersistentPostRun with args: [arg1 arg2]673```674675## Suggestions when "unknown command" happens676677Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:678679```680$ hugo srever681Error: unknown command "srever" for "hugo"682683Did you mean this?684 server685686Run 'hugo --help' for usage.687```688689Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.690691If you need to disable suggestions or tweak the string distance in your command, use:692693```go694command.DisableSuggestions = true695```696697or698699```go700command.SuggestionsMinimumDistance = 1701```702703You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which704you don't want aliases. Example:705706```707$ kubectl remove708Error: unknown command "remove" for "kubectl"709710Did you mean this?711 delete712713Run 'kubectl help' for usage.714```715716## Generating documentation for your command717718Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).719720## Generating shell completions721722Cobra 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).723724## Providing Active Help725726Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md).
deleted:zsh_completions.md-48 removed
1## Generating Zsh Completion For Your cobra.Command23Please refer to [Shell Completions](shell_completions.md) for details.45## Zsh completions standardization67Cobra 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.89### Deprecation summary1011See 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|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`|26`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|27|`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)|28|`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|2930**Flag-value completion**3132|Old behavior|New behavior|33|---|---|34|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion|35|`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|36|`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"}`)|37|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells|38|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`|39|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`|4041**Improvements**4243* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`)44* File completion by default if no other completions found45* Handling of required flags46* File extension filtering no longer mutually exclusive with bash usage47* Completion of directory names *within* another directory48* Support for `=` form of flags