diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 000000000..e69de29bb diff --git a/404.html b/404.html new file mode 100644 index 000000000..7e3596328 --- /dev/null +++ b/404.html @@ -0,0 +1,116 @@ + + + + + + + + 404 Page not found + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NAV + + + +
+ + + + + + + + + + + + +
+
+
+
+ +

Page Not Found!

+ +
+
+ +
+
+ + + diff --git a/categories/index.html b/categories/index.html new file mode 100644 index 000000000..2733fa71b --- /dev/null +++ b/categories/index.html @@ -0,0 +1,1941 @@ + + + + + + + + Categories + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NAV + + + +
+ + + + + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Active Help

+

Active 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.

+

For example,

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding.
+
+bash-5.1$ bin/helm package [tab]
+Please specify the path to the chart to package
+
+bash-5.1$ bin/helm package [tab][tab]
+bin/    internal/    scripts/    pkg/     testdata/
+

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.

+ + + + + + + + +

Supported shells

+

Active Help is currently only supported for the following shells:

+ + + + + + + + + +

Adding Active Help messages

+

As 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.

+

Adding 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.

+ + + + + + + + +

Active Help for nouns

+

Adding 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:

+
cmd := &cobra.Command{
+	Use:   "add [NAME] [URL]",
+	Short: "add a chart repository",
+	Args:  require.ExactArgs(2),
+	RunE: func(cmd *cobra.Command, args []string) error {
+		return addRepo(args)
+	},
+	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		var comps []string
+		if len(args) == 0 {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		} else if len(args) == 1 {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		} else {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+		return comps, cobra.ShellCompDirectiveNoFileComp
+	},
+}
+

The 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:

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding
+
+bash-5.1$ helm repo add grafana [tab]
+You must specify the URL for the repo you are adding
+
+bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
+This command does not take any more arguments
+

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.

+ + + + + + + + +

Active Help for flags

+

Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:

+
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		if len(args) != 2 {
+			return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
+		}
+		return compVersionFlag(args[1], toComplete)
+	})
+

The example above prints an Active Help message when not enough information was given by the user to complete the --version flag.

+
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
+You must first specify the chart to install before the --version flag can be completed
+
+bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
+2.0.1  2.0.2  2.0.3
+
+ + + + + + + +

User control of Active Help

+

You 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. +Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.

+

The way to configure Active Help is to use the program’s Active Help environment +variable. That variable is named <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of your +program in uppercase with any - replaced by an _. The variable should be set by the user to whatever +Active Help configuration values are supported by the program.

+

For example, say helm has chosen to support three levels for Active Help: on, off, local. Then a user +would set the desired behavior to local by doing export HELM_ACTIVE_HELP=local in their shell.

+

For simplicity, when in cmd.ValidArgsFunction(...) or a flag’s completion function, the program should read the +Active Help configuration using the cobra.GetActiveHelpConfig(cmd) function and select what Active Help messages +should or should not be added (instead of reading the environment variable directly).

+

For example:

+
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+	activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
+
+	var comps []string
+	if len(args) == 0 {
+		if activeHelpLevel != "off"  {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		}
+	} else if len(args) == 1 {
+		if activeHelpLevel != "off" {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		}
+	} else {
+		if activeHelpLevel == "local" {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+	}
+	return comps, cobra.ShellCompDirectiveNoFileComp
+},
+

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.

+

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.

+

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.

+ + + + + + + + +

Active Help with Cobra’s default completion command

+

Cobra provides a default completion command for programs that wish to use it. +When using the default completion command, Active Help is configurable in the same +fashion as described above using environment variables. You may wish to document this in more +details for your users.

+ + + + + + + + +

Debugging Active Help

+

Debugging 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 for details.

+

When 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:

+
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+_activeHelp_ WARNING: cannot re-use a name that is still in use
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+ + + + + + + + + +

Generating Bash Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Bash legacy dynamic completions

+

For 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.

+

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.

+

The 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.

+

Some code that works in kubernetes:

+
const (
+        bash_completion_func = `__kubectl_parse_get()
+{
+    local kubectl_output out
+    if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
+        out=($(echo "${kubectl_output}" | awk '{print $1}'))
+        COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
+    fi
+}
+
+__kubectl_get_resource()
+{
+    if [[ ${#nouns[@]} -eq 0 ]]; then
+        return 1
+    fi
+    __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
+    if [[ $? -eq 0 ]]; then
+        return 0
+    fi
+}
+
+__kubectl_custom_func() {
+    case ${last_command} in
+        kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
+            __kubectl_get_resource
+            return
+            ;;
+        *)
+            ;;
+    esac
+}
+`)
+

And then I set that in my command definition:

+
cmds := &cobra.Command{
+	Use:   "kubectl",
+	Short: "kubectl controls the Kubernetes cluster manager",
+	Long: `kubectl controls the Kubernetes cluster manager.
+
+Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
+	Run: runHelp,
+	BashCompletionFunction: bash_completion_func,
+}
+

The BashCompletionFunction option is really only valid/useful on the root command. Doing the above will cause __kubectl_custom_func() (__<command-use>_custom_func()) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like kubectl get pod [mypod]. If you type kubectl get pod [tab][tab] the __kubectl_customc_func() will run because the cobra.Command only understood “kubectl” and “get.” __kubectl_custom_func() will see that the cobra.Command is “kubectl_get” and will thus call another helper __kubectl_get_resource(). __kubectl_get_resource will look at the ’nouns’ collected. In our example the only noun will be pod. So it will call __kubectl_parse_get pod. __kubectl_parse_get will actually call out to kubernetes and get any pods. It will then set COMPREPLY to valid pods!

+

Similarly, for flags:

+
	annotation := make(map[string][]string)
+	annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
+
+	flag := &pflag.Flag{
+		Name:        "namespace",
+		Usage:       usage,
+		Annotations: annotation,
+	}
+	cmd.Flags().AddFlag(flag)
+

In addition add the __kubectl_get_namespaces implementation in the BashCompletionFunction +value, e.g.:

+
__kubectl_get_namespaces()
+{
+    local template
+    template="{{ range .items  }}{{ .metadata.name }} {{ end }}"
+    local kubectl_out
+    if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
+        COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
+    fi
+}
+
+ + + + + + + + + +

Generating Fish Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating PowerShell Completions For Your Own cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating Zsh Completion For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Zsh completions standardization

+

Cobra 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.

+ + + + + + + + +

Deprecation summary

+

See further below for more details on these deprecations.

+ + + + + + + + + +

Behavioral changes

+

Noun completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
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
Completion of flag names without the - prefix having been typedFlag names are only completed if the user has typed the first -
cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) used to turn on file completion on a per-argument position basisFile completion for all arguments by default; cmd.MarkZshCompPositionalArgumentFile() is deprecated and silently ignored
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)
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
+

Flag-value completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
No file completion by default (opposite of bash)File completion by default; use RegisterFlagCompletionFunc() with ShellCompDirectiveNoFileComp to turn off file completion
cmd.MarkFlagFilename(flag, []string{}) and similar used to turn on file completionFile completion by default; cmd.MarkFlagFilename(flag, []string{}) no longer needed in this context and silently ignored
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"})
cmd.MarkFlagDirname(flag) only completes directories (zsh-specific)Has been added for all shells
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
Completion of a flag name does not provide the = form (unlike bash)Retained for zsh and added to fish
+

Improvements

+ + + + + + + + + + + +

Generating Man Pages For Your Own cobra.Command

+

Generating man pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &doc.GenManHeader{
+		Title: "MINE",
+		Section: "3",
+	}
+	err := doc.GenManTree(cmd, header, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a man page /tmp/test.3

+ + + + + + + + + + +

Generating Markdown Docs For Your Own cobra.Command

+

Generating Markdown pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenMarkdownTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Markdown document /tmp/test.md

+ + + + + + + + +

Generate markdown docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenMarkdownTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate markdown docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenMarkdown(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the markdown doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + +

Customize the output

+

Both GenMarkdown and GenMarkdownTree have alternate versions with callbacks to get some control of the output:

+
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Generating ReStructured Text Docs For Your Own cobra.Command

+

Generating ReST pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenReSTTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a ReST document /tmp/test.rst

+ + + + + + + + +

Generate ReST docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenReSTTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate ReST docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenReST(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the ReST doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenReST and GenReSTTree have alternate versions with callbacks to get some control of the output:

+
func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
+	//...
+}
+
func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The 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:

+
// Sphinx cross-referencing format
+linkHandler := func(name, ref string) string {
+    return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
+}
+
+ + + + + + + + + +

Generating Yaml Docs For Your Own cobra.Command

+

Generating yaml files from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenYamlTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Yaml document /tmp/test.yaml

+ + + + + + + + +

Generate yaml docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"io/ioutil"
+	"log"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenYamlTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate yaml docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	doc.GenYaml(cmd, out)
+

This will write the yaml doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenYaml and GenYamlTree have alternate versions with callbacks to get some control of the output:

+
func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Projects using Cobra

+ + + + + + + + + + + +

User Guide

+

While you are welcome to provide your own organization, typically a Cobra-based +application will follow the following organizational structure:

+
  ▾ appName/
+    ▾ cmd/
+        add.go
+        your.go
+        commands.go
+        here.go
+      main.go
+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Using the Cobra Generator

+

Cobra-CLI is its own program that will create your application and add any commands you want. +It’s the easiest way to incorporate Cobra into your application.

+

For complete details on using the Cobra generator, please refer to The Cobra-CLI Generator README

+ + + + + + + + +

Using the Cobra Library

+

To manually implement Cobra you need to create a bare main.go file and a rootCmd file. +You will optionally provide additional commands as you see fit.

+ + + + + + + + +

Create rootCmd

+

Cobra doesn’t require any special constructors. Simply create your commands.

+

Ideally you place this in app/cmd/root.go:

+
var rootCmd = &cobra.Command{
+  Use:   "hugo",
+  Short: "Hugo is a very fast static site generator",
+  Long: `A Fast and Flexible Static Site Generator built with
+                love by spf13 and friends in Go.
+                Complete documentation is available at https://gohugo.io/documentation/`,
+  Run: func(cmd *cobra.Command, args []string) {
+    // Do Stuff Here
+  },
+}
+
+func Execute() {
+  if err := rootCmd.Execute(); err != nil {
+    fmt.Fprintln(os.Stderr, err)
+    os.Exit(1)
+  }
+}
+

You will additionally define flags and handle configuration in your init() function.

+

For example cmd/root.go:

+
package cmd
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+var (
+	// Used for flags.
+	cfgFile     string
+	userLicense string
+
+	rootCmd = &cobra.Command{
+		Use:   "cobra-cli",
+		Short: "A generator for Cobra based Applications",
+		Long: `Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.`,
+	}
+)
+
+// Execute executes the root command.
+func Execute() error {
+	return rootCmd.Execute()
+}
+
+func init() {
+	cobra.OnInitialize(initConfig)
+
+	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+	rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
+	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
+	rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
+	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
+	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+	viper.SetDefault("license", "apache")
+
+	rootCmd.AddCommand(addCmd)
+	rootCmd.AddCommand(initCmd)
+}
+
+func initConfig() {
+	if cfgFile != "" {
+		// Use config file from the flag.
+		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := os.UserHomeDir()
+		cobra.CheckErr(err)
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigType("yaml")
+		viper.SetConfigName(".cobra")
+	}
+
+	viper.AutomaticEnv()
+
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}
+
+ + + + + + + +

Create your main.go

+

With the root command you need to have your main function execute it. +Execute should be run on the root for clarity, though it can be called on any command.

+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Create additional commands

+

Additional commands can be defined and typically are each given their own file +inside of the cmd/ directory.

+

If you wanted to create a version command you would create cmd/version.go and +populate it with the following:

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(versionCmd)
+}
+
+var versionCmd = &cobra.Command{
+  Use:   "version",
+  Short: "Print the version number of Hugo",
+  Long:  `All software has versions. This is Hugo's`,
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
+  },
+}
+
+ + + + + + + +

Organizing subcommands

+

A command may have subcommands which in turn may have other subcommands. This is achieved by using +AddCommand. In some cases, especially in larger applications, each subcommand may be defined in +its own go package.

+

The suggested approach is for the parent command to use AddCommand to add its most immediate +subcommands. For example, consider the following directory structure:

+
├── cmd
+│   ├── root.go
+│   └── sub1
+│       ├── sub1.go
+│       └── sub2
+│           ├── leafA.go
+│           ├── leafB.go
+│           └── sub2.go
+└── main.go
+

In this case:

+ +

This approach ensures the subcommands are always included at compile time while avoiding cyclic +references.

+ + + + + + + + +

Returning and handling errors

+

If you wish to return an error to the caller of a command, RunE can be used.

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(tryCmd)
+}
+
+var tryCmd = &cobra.Command{
+  Use:   "try",
+  Short: "Try and possibly fail at something",
+  RunE: func(cmd *cobra.Command, args []string) error {
+    if err := someFunc(); err != nil {
+	return err
+    }
+    return nil
+  },
+}
+

The error can then be caught at the execute function call.

+ + + + + + + + +

Working with Flags

+

Flags provide modifiers to control how the action command operates.

+ + + + + + + + +

Assign flags to a command

+

Since the flags are defined and used in different locations, we need to +define a variable outside with the correct scope to assign the flag to +work with.

+
var Verbose bool
+var Source string
+

There are two different approaches to assign a flag.

+ + + + + + + + +

Persistent Flags

+

A flag can be ‘persistent’, meaning that this flag will be available to the +command it’s assigned to as well as every command under that command. For +global flags, assign a flag as a persistent flag on the root.

+
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
+
+ + + + + + + +

Local Flags

+

A flag can also be assigned locally, which will only apply to that specific command.

+
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
+
+ + + + + + + +

Local Flag on Parent Commands

+

By default, Cobra only parses local flags on the target command, and any local flags on +parent commands are ignored. By enabling Command.TraverseChildren, Cobra will +parse local flags on each command before executing the target command.

+
command := cobra.Command{
+  Use: "print [OPTIONS] [COMMANDS]",
+  TraverseChildren: true,
+}
+
+ + + + + + + +

Bind Flags with Config

+

You can also bind your flags with viper:

+
var author string
+
+func init() {
+  rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
+  viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+}
+

In this example, the persistent flag author is bound with viper. +Note: the variable author will not be set to the value from config, +when the --author flag is provided by user.

+

More in viper documentation.

+ + + + + + + + +

Required flags

+

Flags are optional by default. If instead you wish your command to report an error +when a flag has not been set, mark it as required:

+
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkFlagRequired("region")
+

Or, for persistent flags:

+
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkPersistentFlagRequired("region")
+
+ + + + + + + +

Flag Groups

+

If 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) then +Cobra can enforce that requirement:

+
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
+rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
+rootCmd.MarkFlagsRequiredTogether("username", "password")
+

You can also prevent different flags from being provided together if they represent mutually +exclusive options such as specifying an output format as either --json or --yaml but never both:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

If you want to require at least one flag from a group to be present, you can use MarkFlagsOneRequired. +This can be combined with MarkFlagsMutuallyExclusive to enforce exactly one flag from a given group:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsOneRequired("json", "yaml")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

In these cases:

+ + + + + + + + + +

Positional and Custom Arguments

+

Validation of positional arguments can be specified using the Args field of Command. +The following validators are built in:

+ +

If Args is undefined or nil, it defaults to ArbitraryArgs.

+

Moreover, MatchAll(pargs ...PositionalArgs) enables combining existing checks with arbitrary other checks. +For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional +args that are not in the ValidArgs field of Command, you can call MatchAll on ExactArgs and OnlyValidArgs, as +shown below:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+

It is possible to set any custom validator that satisfies func(cmd *cobra.Command, args []string) error. +For example:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: func(cmd *cobra.Command, args []string) error {
+    // Optionally run one of the validators provided by cobra
+    if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
+        return err
+    }
+    // Run the custom validation logic
+    if myapp.IsValidColor(args[0]) {
+      return nil
+    }
+    return fmt.Errorf("invalid color specified: %s", args[0])
+  },
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+
+ + + + + + + +

Example

+

In the example below, we have defined three commands. Two are at the top level +and one (cmdTimes) is a child of one of the top commands. In this case the root +is not executable, meaning that a subcommand is required. This is accomplished +by not providing a ‘Run’ for the ‘rootCmd’.

+

We have only defined one flag for a single command.

+

More documentation about flags is available at https://github.com/spf13/pflag

+
package main
+
+import (
+  "fmt"
+  "strings"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+  var echoTimes int
+
+  var cmdPrint = &cobra.Command{
+    Use:   "print [string to print]",
+    Short: "Print anything to the screen",
+    Long: `print is for printing anything back to the screen.
+For many years people have printed back to the screen.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Print: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdEcho = &cobra.Command{
+    Use:   "echo [string to echo]",
+    Short: "Echo anything to the screen",
+    Long: `echo is for echoing anything back.
+Echo works a lot like print, except it has a child command.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Echo: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdTimes = &cobra.Command{
+    Use:   "times [string to echo]",
+    Short: "Echo anything to the screen more times",
+    Long: `echo things multiple times back to the user by providing
+a count and a string.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      for i := 0; i < echoTimes; i++ {
+        fmt.Println("Echo: " + strings.Join(args, " "))
+      }
+    },
+  }
+
+  cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
+
+  var rootCmd = &cobra.Command{Use: "app"}
+  rootCmd.AddCommand(cmdPrint, cmdEcho)
+  cmdEcho.AddCommand(cmdTimes)
+  rootCmd.Execute()
+}
+

For a more complete example of a larger application, please checkout Hugo.

+ + + + + + + + +

Help Command

+

Cobra automatically adds a help command to your application when you have subcommands. +This will be called when a user runs ‘app help’. Additionally, help will also +support all other commands as input. Say, for instance, you have a command called +‘create’ without any additional configuration; Cobra will work when ‘app help +create’ is called. Every command will automatically have the ‘–help’ flag added.

+ + + + + + + + +

Example

+

The following output is automatically generated by Cobra. Nothing beyond the +command and flag definitions are needed.

+
$ cobra-cli help
+
+Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.
+
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra-cli [command] --help" for more information about a command.
+
+

Help is just a command like any other. There is no special logic or behavior +around it. In fact, you can provide your own if you want.

+ + + + + + + + +

Grouping commands in help

+

Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly +defined using AddGroup() on the parent command. Then a subcommand can be added to a group using the GroupID element +of that subcommand. The groups will appear in the help output in the same order as they are defined using different +calls to AddGroup(). If you use the generated help or completion commands, you can set their group ids using +SetHelpCommandGroupId() and SetCompletionCommandGroupId() on the root command, respectively.

+ + + + + + + + +

Defining your own help

+

You can provide your own Help command or your own template for the default command to use +with the following functions:

+
cmd.SetHelpCommand(cmd *Command)
+cmd.SetHelpFunc(f func(*Command, []string))
+cmd.SetHelpTemplate(s string)
+

The latter two will also apply to any children commands.

+ + + + + + + + +

Usage Message

+

When the user provides an invalid flag or invalid command, Cobra responds by +showing the user the ‘usage’.

+ + + + + + + + +

Example

+

You may recognize this from the help above. That’s because the default help +embeds the usage as part of its output.

+
$ cobra-cli --invalid
+Error: unknown flag: --invalid
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra [command] --help" for more information about a command.
+
+ + + + + + + + +

Defining your own usage

+

You can provide your own usage function or template for Cobra to use. +Like help, the function and template are overridable through public methods:

+
cmd.SetUsageFunc(f func(*Command) error)
+cmd.SetUsageTemplate(s string)
+
+ + + + + + + +

Version Flag

+

Cobra adds a top-level ‘–version’ flag if the Version field is set on the root command. +Running an application with the ‘–version’ flag will print the version to stdout using +the version template. The template can be customized using the +cmd.SetVersionTemplate(s string) function.

+ + + + + + + + +

PreRun and PostRun Hooks

+

It 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:

+ +

An 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:

+
package main
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+
+  var rootCmd = &cobra.Command{
+    Use:   "root [sub]",
+    Short: "My root command",
+    PersistentPreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
+    },
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  var subCmd = &cobra.Command{
+    Use:   "sub [no options!]",
+    Short: "My subcommand",
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  rootCmd.AddCommand(subCmd)
+
+  rootCmd.SetArgs([]string{""})
+  rootCmd.Execute()
+  fmt.Println()
+  rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
+  rootCmd.Execute()
+}
+

Output:

+
Inside rootCmd PersistentPreRun with args: []
+Inside rootCmd PreRun with args: []
+Inside rootCmd Run with args: []
+Inside rootCmd PostRun with args: []
+Inside rootCmd PersistentPostRun with args: []
+
+Inside rootCmd PersistentPreRun with args: [arg1 arg2]
+Inside subCmd PreRun with args: [arg1 arg2]
+Inside subCmd Run with args: [arg1 arg2]
+Inside subCmd PostRun with args: [arg1 arg2]
+Inside subCmd PersistentPostRun with args: [arg1 arg2]
+
+ + + + + + + +

Suggestions when “unknown command” happens

+

Cobra 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:

+
$ hugo srever
+Error: unknown command "srever" for "hugo"
+
+Did you mean this?
+        server
+
+Run 'hugo --help' for usage.
+

Suggestions are automatically generated based on existing subcommands and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.

+

If you need to disable suggestions or tweak the string distance in your command, use:

+
command.DisableSuggestions = true
+

or

+
command.SuggestionsMinimumDistance = 1
+

You 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 which +you don’t want aliases. Example:

+
$ kubectl remove
+Error: unknown command "remove" for "kubectl"
+
+Did you mean this?
+        delete
+
+Run 'kubectl help' for usage.
+
+ + + + + + + +

Generating documentation for your command

+

Cobra can generate documentation based on subcommands, flags, etc. +Read more about it in the docs generation documentation.

+ + + + + + + + +

Generating shell completions

+

Cobra 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.

+ + + + + + + + +

Providing Active Help

+

Cobra 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.

+ + + +
+
+ +
+
+ + + diff --git a/categories/index.xml b/categories/index.xml new file mode 100644 index 000000000..e282b7f25 --- /dev/null +++ b/categories/index.xml @@ -0,0 +1,10 @@ + + + + Categories on Cobra documentation + https://spf13.github.io/cobra/categories/ + Recent content in Categories on Cobra documentation + Hugo -- gohugo.io + en + + diff --git a/completions/index.html b/completions/index.html new file mode 100644 index 000000000..506d9ef21 --- /dev/null +++ b/completions/index.html @@ -0,0 +1,1941 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NAV + + + +
+ + + + + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Active Help

+

Active 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.

+

For example,

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding.
+
+bash-5.1$ bin/helm package [tab]
+Please specify the path to the chart to package
+
+bash-5.1$ bin/helm package [tab][tab]
+bin/    internal/    scripts/    pkg/     testdata/
+

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.

+ + + + + + + + +

Supported shells

+

Active Help is currently only supported for the following shells:

+ + + + + + + + + +

Adding Active Help messages

+

As 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.

+

Adding 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.

+ + + + + + + + +

Active Help for nouns

+

Adding 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:

+
cmd := &cobra.Command{
+	Use:   "add [NAME] [URL]",
+	Short: "add a chart repository",
+	Args:  require.ExactArgs(2),
+	RunE: func(cmd *cobra.Command, args []string) error {
+		return addRepo(args)
+	},
+	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		var comps []string
+		if len(args) == 0 {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		} else if len(args) == 1 {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		} else {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+		return comps, cobra.ShellCompDirectiveNoFileComp
+	},
+}
+

The 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:

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding
+
+bash-5.1$ helm repo add grafana [tab]
+You must specify the URL for the repo you are adding
+
+bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
+This command does not take any more arguments
+

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.

+ + + + + + + + +

Active Help for flags

+

Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:

+
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		if len(args) != 2 {
+			return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
+		}
+		return compVersionFlag(args[1], toComplete)
+	})
+

The example above prints an Active Help message when not enough information was given by the user to complete the --version flag.

+
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
+You must first specify the chart to install before the --version flag can be completed
+
+bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
+2.0.1  2.0.2  2.0.3
+
+ + + + + + + +

User control of Active Help

+

You 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. +Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.

+

The way to configure Active Help is to use the program’s Active Help environment +variable. That variable is named <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of your +program in uppercase with any - replaced by an _. The variable should be set by the user to whatever +Active Help configuration values are supported by the program.

+

For example, say helm has chosen to support three levels for Active Help: on, off, local. Then a user +would set the desired behavior to local by doing export HELM_ACTIVE_HELP=local in their shell.

+

For simplicity, when in cmd.ValidArgsFunction(...) or a flag’s completion function, the program should read the +Active Help configuration using the cobra.GetActiveHelpConfig(cmd) function and select what Active Help messages +should or should not be added (instead of reading the environment variable directly).

+

For example:

+
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+	activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
+
+	var comps []string
+	if len(args) == 0 {
+		if activeHelpLevel != "off"  {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		}
+	} else if len(args) == 1 {
+		if activeHelpLevel != "off" {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		}
+	} else {
+		if activeHelpLevel == "local" {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+	}
+	return comps, cobra.ShellCompDirectiveNoFileComp
+},
+

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.

+

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.

+

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.

+ + + + + + + + +

Active Help with Cobra’s default completion command

+

Cobra provides a default completion command for programs that wish to use it. +When using the default completion command, Active Help is configurable in the same +fashion as described above using environment variables. You may wish to document this in more +details for your users.

+ + + + + + + + +

Debugging Active Help

+

Debugging 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 for details.

+

When 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:

+
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+_activeHelp_ WARNING: cannot re-use a name that is still in use
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+ + + + + + + + + +

Generating Bash Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Bash legacy dynamic completions

+

For 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.

+

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.

+

The 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.

+

Some code that works in kubernetes:

+
const (
+        bash_completion_func = `__kubectl_parse_get()
+{
+    local kubectl_output out
+    if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
+        out=($(echo "${kubectl_output}" | awk '{print $1}'))
+        COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
+    fi
+}
+
+__kubectl_get_resource()
+{
+    if [[ ${#nouns[@]} -eq 0 ]]; then
+        return 1
+    fi
+    __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
+    if [[ $? -eq 0 ]]; then
+        return 0
+    fi
+}
+
+__kubectl_custom_func() {
+    case ${last_command} in
+        kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
+            __kubectl_get_resource
+            return
+            ;;
+        *)
+            ;;
+    esac
+}
+`)
+

And then I set that in my command definition:

+
cmds := &cobra.Command{
+	Use:   "kubectl",
+	Short: "kubectl controls the Kubernetes cluster manager",
+	Long: `kubectl controls the Kubernetes cluster manager.
+
+Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
+	Run: runHelp,
+	BashCompletionFunction: bash_completion_func,
+}
+

The BashCompletionFunction option is really only valid/useful on the root command. Doing the above will cause __kubectl_custom_func() (__<command-use>_custom_func()) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like kubectl get pod [mypod]. If you type kubectl get pod [tab][tab] the __kubectl_customc_func() will run because the cobra.Command only understood “kubectl” and “get.” __kubectl_custom_func() will see that the cobra.Command is “kubectl_get” and will thus call another helper __kubectl_get_resource(). __kubectl_get_resource will look at the ’nouns’ collected. In our example the only noun will be pod. So it will call __kubectl_parse_get pod. __kubectl_parse_get will actually call out to kubernetes and get any pods. It will then set COMPREPLY to valid pods!

+

Similarly, for flags:

+
	annotation := make(map[string][]string)
+	annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
+
+	flag := &pflag.Flag{
+		Name:        "namespace",
+		Usage:       usage,
+		Annotations: annotation,
+	}
+	cmd.Flags().AddFlag(flag)
+

In addition add the __kubectl_get_namespaces implementation in the BashCompletionFunction +value, e.g.:

+
__kubectl_get_namespaces()
+{
+    local template
+    template="{{ range .items  }}{{ .metadata.name }} {{ end }}"
+    local kubectl_out
+    if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
+        COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
+    fi
+}
+
+ + + + + + + + + +

Generating Fish Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating PowerShell Completions For Your Own cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating Zsh Completion For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Zsh completions standardization

+

Cobra 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.

+ + + + + + + + +

Deprecation summary

+

See further below for more details on these deprecations.

+ + + + + + + + + +

Behavioral changes

+

Noun completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
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
Completion of flag names without the - prefix having been typedFlag names are only completed if the user has typed the first -
cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) used to turn on file completion on a per-argument position basisFile completion for all arguments by default; cmd.MarkZshCompPositionalArgumentFile() is deprecated and silently ignored
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)
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
+

Flag-value completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
No file completion by default (opposite of bash)File completion by default; use RegisterFlagCompletionFunc() with ShellCompDirectiveNoFileComp to turn off file completion
cmd.MarkFlagFilename(flag, []string{}) and similar used to turn on file completionFile completion by default; cmd.MarkFlagFilename(flag, []string{}) no longer needed in this context and silently ignored
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"})
cmd.MarkFlagDirname(flag) only completes directories (zsh-specific)Has been added for all shells
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
Completion of a flag name does not provide the = form (unlike bash)Retained for zsh and added to fish
+

Improvements

+ + + + + + + + + + + +

Generating Man Pages For Your Own cobra.Command

+

Generating man pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &doc.GenManHeader{
+		Title: "MINE",
+		Section: "3",
+	}
+	err := doc.GenManTree(cmd, header, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a man page /tmp/test.3

+ + + + + + + + + + +

Generating Markdown Docs For Your Own cobra.Command

+

Generating Markdown pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenMarkdownTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Markdown document /tmp/test.md

+ + + + + + + + +

Generate markdown docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenMarkdownTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate markdown docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenMarkdown(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the markdown doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + +

Customize the output

+

Both GenMarkdown and GenMarkdownTree have alternate versions with callbacks to get some control of the output:

+
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Generating ReStructured Text Docs For Your Own cobra.Command

+

Generating ReST pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenReSTTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a ReST document /tmp/test.rst

+ + + + + + + + +

Generate ReST docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenReSTTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate ReST docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenReST(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the ReST doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenReST and GenReSTTree have alternate versions with callbacks to get some control of the output:

+
func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
+	//...
+}
+
func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The 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:

+
// Sphinx cross-referencing format
+linkHandler := func(name, ref string) string {
+    return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
+}
+
+ + + + + + + + + +

Generating Yaml Docs For Your Own cobra.Command

+

Generating yaml files from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenYamlTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Yaml document /tmp/test.yaml

+ + + + + + + + +

Generate yaml docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"io/ioutil"
+	"log"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenYamlTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate yaml docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	doc.GenYaml(cmd, out)
+

This will write the yaml doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenYaml and GenYamlTree have alternate versions with callbacks to get some control of the output:

+
func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Projects using Cobra

+ + + + + + + + + + + +

User Guide

+

While you are welcome to provide your own organization, typically a Cobra-based +application will follow the following organizational structure:

+
  ▾ appName/
+    ▾ cmd/
+        add.go
+        your.go
+        commands.go
+        here.go
+      main.go
+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Using the Cobra Generator

+

Cobra-CLI is its own program that will create your application and add any commands you want. +It’s the easiest way to incorporate Cobra into your application.

+

For complete details on using the Cobra generator, please refer to The Cobra-CLI Generator README

+ + + + + + + + +

Using the Cobra Library

+

To manually implement Cobra you need to create a bare main.go file and a rootCmd file. +You will optionally provide additional commands as you see fit.

+ + + + + + + + +

Create rootCmd

+

Cobra doesn’t require any special constructors. Simply create your commands.

+

Ideally you place this in app/cmd/root.go:

+
var rootCmd = &cobra.Command{
+  Use:   "hugo",
+  Short: "Hugo is a very fast static site generator",
+  Long: `A Fast and Flexible Static Site Generator built with
+                love by spf13 and friends in Go.
+                Complete documentation is available at https://gohugo.io/documentation/`,
+  Run: func(cmd *cobra.Command, args []string) {
+    // Do Stuff Here
+  },
+}
+
+func Execute() {
+  if err := rootCmd.Execute(); err != nil {
+    fmt.Fprintln(os.Stderr, err)
+    os.Exit(1)
+  }
+}
+

You will additionally define flags and handle configuration in your init() function.

+

For example cmd/root.go:

+
package cmd
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+var (
+	// Used for flags.
+	cfgFile     string
+	userLicense string
+
+	rootCmd = &cobra.Command{
+		Use:   "cobra-cli",
+		Short: "A generator for Cobra based Applications",
+		Long: `Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.`,
+	}
+)
+
+// Execute executes the root command.
+func Execute() error {
+	return rootCmd.Execute()
+}
+
+func init() {
+	cobra.OnInitialize(initConfig)
+
+	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+	rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
+	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
+	rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
+	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
+	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+	viper.SetDefault("license", "apache")
+
+	rootCmd.AddCommand(addCmd)
+	rootCmd.AddCommand(initCmd)
+}
+
+func initConfig() {
+	if cfgFile != "" {
+		// Use config file from the flag.
+		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := os.UserHomeDir()
+		cobra.CheckErr(err)
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigType("yaml")
+		viper.SetConfigName(".cobra")
+	}
+
+	viper.AutomaticEnv()
+
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}
+
+ + + + + + + +

Create your main.go

+

With the root command you need to have your main function execute it. +Execute should be run on the root for clarity, though it can be called on any command.

+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Create additional commands

+

Additional commands can be defined and typically are each given their own file +inside of the cmd/ directory.

+

If you wanted to create a version command you would create cmd/version.go and +populate it with the following:

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(versionCmd)
+}
+
+var versionCmd = &cobra.Command{
+  Use:   "version",
+  Short: "Print the version number of Hugo",
+  Long:  `All software has versions. This is Hugo's`,
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
+  },
+}
+
+ + + + + + + +

Organizing subcommands

+

A command may have subcommands which in turn may have other subcommands. This is achieved by using +AddCommand. In some cases, especially in larger applications, each subcommand may be defined in +its own go package.

+

The suggested approach is for the parent command to use AddCommand to add its most immediate +subcommands. For example, consider the following directory structure:

+
├── cmd
+│   ├── root.go
+│   └── sub1
+│       ├── sub1.go
+│       └── sub2
+│           ├── leafA.go
+│           ├── leafB.go
+│           └── sub2.go
+└── main.go
+

In this case:

+ +

This approach ensures the subcommands are always included at compile time while avoiding cyclic +references.

+ + + + + + + + +

Returning and handling errors

+

If you wish to return an error to the caller of a command, RunE can be used.

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(tryCmd)
+}
+
+var tryCmd = &cobra.Command{
+  Use:   "try",
+  Short: "Try and possibly fail at something",
+  RunE: func(cmd *cobra.Command, args []string) error {
+    if err := someFunc(); err != nil {
+	return err
+    }
+    return nil
+  },
+}
+

The error can then be caught at the execute function call.

+ + + + + + + + +

Working with Flags

+

Flags provide modifiers to control how the action command operates.

+ + + + + + + + +

Assign flags to a command

+

Since the flags are defined and used in different locations, we need to +define a variable outside with the correct scope to assign the flag to +work with.

+
var Verbose bool
+var Source string
+

There are two different approaches to assign a flag.

+ + + + + + + + +

Persistent Flags

+

A flag can be ‘persistent’, meaning that this flag will be available to the +command it’s assigned to as well as every command under that command. For +global flags, assign a flag as a persistent flag on the root.

+
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
+
+ + + + + + + +

Local Flags

+

A flag can also be assigned locally, which will only apply to that specific command.

+
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
+
+ + + + + + + +

Local Flag on Parent Commands

+

By default, Cobra only parses local flags on the target command, and any local flags on +parent commands are ignored. By enabling Command.TraverseChildren, Cobra will +parse local flags on each command before executing the target command.

+
command := cobra.Command{
+  Use: "print [OPTIONS] [COMMANDS]",
+  TraverseChildren: true,
+}
+
+ + + + + + + +

Bind Flags with Config

+

You can also bind your flags with viper:

+
var author string
+
+func init() {
+  rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
+  viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+}
+

In this example, the persistent flag author is bound with viper. +Note: the variable author will not be set to the value from config, +when the --author flag is provided by user.

+

More in viper documentation.

+ + + + + + + + +

Required flags

+

Flags are optional by default. If instead you wish your command to report an error +when a flag has not been set, mark it as required:

+
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkFlagRequired("region")
+

Or, for persistent flags:

+
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkPersistentFlagRequired("region")
+
+ + + + + + + +

Flag Groups

+

If 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) then +Cobra can enforce that requirement:

+
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
+rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
+rootCmd.MarkFlagsRequiredTogether("username", "password")
+

You can also prevent different flags from being provided together if they represent mutually +exclusive options such as specifying an output format as either --json or --yaml but never both:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

If you want to require at least one flag from a group to be present, you can use MarkFlagsOneRequired. +This can be combined with MarkFlagsMutuallyExclusive to enforce exactly one flag from a given group:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsOneRequired("json", "yaml")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

In these cases:

+ + + + + + + + + +

Positional and Custom Arguments

+

Validation of positional arguments can be specified using the Args field of Command. +The following validators are built in:

+ +

If Args is undefined or nil, it defaults to ArbitraryArgs.

+

Moreover, MatchAll(pargs ...PositionalArgs) enables combining existing checks with arbitrary other checks. +For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional +args that are not in the ValidArgs field of Command, you can call MatchAll on ExactArgs and OnlyValidArgs, as +shown below:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+

It is possible to set any custom validator that satisfies func(cmd *cobra.Command, args []string) error. +For example:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: func(cmd *cobra.Command, args []string) error {
+    // Optionally run one of the validators provided by cobra
+    if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
+        return err
+    }
+    // Run the custom validation logic
+    if myapp.IsValidColor(args[0]) {
+      return nil
+    }
+    return fmt.Errorf("invalid color specified: %s", args[0])
+  },
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+
+ + + + + + + +

Example

+

In the example below, we have defined three commands. Two are at the top level +and one (cmdTimes) is a child of one of the top commands. In this case the root +is not executable, meaning that a subcommand is required. This is accomplished +by not providing a ‘Run’ for the ‘rootCmd’.

+

We have only defined one flag for a single command.

+

More documentation about flags is available at https://github.com/spf13/pflag

+
package main
+
+import (
+  "fmt"
+  "strings"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+  var echoTimes int
+
+  var cmdPrint = &cobra.Command{
+    Use:   "print [string to print]",
+    Short: "Print anything to the screen",
+    Long: `print is for printing anything back to the screen.
+For many years people have printed back to the screen.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Print: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdEcho = &cobra.Command{
+    Use:   "echo [string to echo]",
+    Short: "Echo anything to the screen",
+    Long: `echo is for echoing anything back.
+Echo works a lot like print, except it has a child command.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Echo: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdTimes = &cobra.Command{
+    Use:   "times [string to echo]",
+    Short: "Echo anything to the screen more times",
+    Long: `echo things multiple times back to the user by providing
+a count and a string.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      for i := 0; i < echoTimes; i++ {
+        fmt.Println("Echo: " + strings.Join(args, " "))
+      }
+    },
+  }
+
+  cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
+
+  var rootCmd = &cobra.Command{Use: "app"}
+  rootCmd.AddCommand(cmdPrint, cmdEcho)
+  cmdEcho.AddCommand(cmdTimes)
+  rootCmd.Execute()
+}
+

For a more complete example of a larger application, please checkout Hugo.

+ + + + + + + + +

Help Command

+

Cobra automatically adds a help command to your application when you have subcommands. +This will be called when a user runs ‘app help’. Additionally, help will also +support all other commands as input. Say, for instance, you have a command called +‘create’ without any additional configuration; Cobra will work when ‘app help +create’ is called. Every command will automatically have the ‘–help’ flag added.

+ + + + + + + + +

Example

+

The following output is automatically generated by Cobra. Nothing beyond the +command and flag definitions are needed.

+
$ cobra-cli help
+
+Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.
+
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra-cli [command] --help" for more information about a command.
+
+

Help is just a command like any other. There is no special logic or behavior +around it. In fact, you can provide your own if you want.

+ + + + + + + + +

Grouping commands in help

+

Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly +defined using AddGroup() on the parent command. Then a subcommand can be added to a group using the GroupID element +of that subcommand. The groups will appear in the help output in the same order as they are defined using different +calls to AddGroup(). If you use the generated help or completion commands, you can set their group ids using +SetHelpCommandGroupId() and SetCompletionCommandGroupId() on the root command, respectively.

+ + + + + + + + +

Defining your own help

+

You can provide your own Help command or your own template for the default command to use +with the following functions:

+
cmd.SetHelpCommand(cmd *Command)
+cmd.SetHelpFunc(f func(*Command, []string))
+cmd.SetHelpTemplate(s string)
+

The latter two will also apply to any children commands.

+ + + + + + + + +

Usage Message

+

When the user provides an invalid flag or invalid command, Cobra responds by +showing the user the ‘usage’.

+ + + + + + + + +

Example

+

You may recognize this from the help above. That’s because the default help +embeds the usage as part of its output.

+
$ cobra-cli --invalid
+Error: unknown flag: --invalid
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra [command] --help" for more information about a command.
+
+ + + + + + + + +

Defining your own usage

+

You can provide your own usage function or template for Cobra to use. +Like help, the function and template are overridable through public methods:

+
cmd.SetUsageFunc(f func(*Command) error)
+cmd.SetUsageTemplate(s string)
+
+ + + + + + + +

Version Flag

+

Cobra adds a top-level ‘–version’ flag if the Version field is set on the root command. +Running an application with the ‘–version’ flag will print the version to stdout using +the version template. The template can be customized using the +cmd.SetVersionTemplate(s string) function.

+ + + + + + + + +

PreRun and PostRun Hooks

+

It 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:

+ +

An 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:

+
package main
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+
+  var rootCmd = &cobra.Command{
+    Use:   "root [sub]",
+    Short: "My root command",
+    PersistentPreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
+    },
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  var subCmd = &cobra.Command{
+    Use:   "sub [no options!]",
+    Short: "My subcommand",
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  rootCmd.AddCommand(subCmd)
+
+  rootCmd.SetArgs([]string{""})
+  rootCmd.Execute()
+  fmt.Println()
+  rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
+  rootCmd.Execute()
+}
+

Output:

+
Inside rootCmd PersistentPreRun with args: []
+Inside rootCmd PreRun with args: []
+Inside rootCmd Run with args: []
+Inside rootCmd PostRun with args: []
+Inside rootCmd PersistentPostRun with args: []
+
+Inside rootCmd PersistentPreRun with args: [arg1 arg2]
+Inside subCmd PreRun with args: [arg1 arg2]
+Inside subCmd Run with args: [arg1 arg2]
+Inside subCmd PostRun with args: [arg1 arg2]
+Inside subCmd PersistentPostRun with args: [arg1 arg2]
+
+ + + + + + + +

Suggestions when “unknown command” happens

+

Cobra 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:

+
$ hugo srever
+Error: unknown command "srever" for "hugo"
+
+Did you mean this?
+        server
+
+Run 'hugo --help' for usage.
+

Suggestions are automatically generated based on existing subcommands and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.

+

If you need to disable suggestions or tweak the string distance in your command, use:

+
command.DisableSuggestions = true
+

or

+
command.SuggestionsMinimumDistance = 1
+

You 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 which +you don’t want aliases. Example:

+
$ kubectl remove
+Error: unknown command "remove" for "kubectl"
+
+Did you mean this?
+        delete
+
+Run 'kubectl help' for usage.
+
+ + + + + + + +

Generating documentation for your command

+

Cobra can generate documentation based on subcommands, flags, etc. +Read more about it in the docs generation documentation.

+ + + + + + + + +

Generating shell completions

+

Cobra 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.

+ + + + + + + + +

Providing Active Help

+

Cobra 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.

+ + + +
+
+ +
+
+ + + diff --git a/completions/index.xml b/completions/index.xml new file mode 100644 index 000000000..af6321252 --- /dev/null +++ b/completions/index.xml @@ -0,0 +1,50 @@ + + + + Cobra documentation + https://spf13.github.io/cobra/completions/ + Recent content on Cobra documentation + Hugo -- gohugo.io + en + + + https://spf13.github.io/cobra/completions/bash/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/bash/ + Generating Bash Completions For Your cobra.Command Please refer to Shell Completions for details. +Bash legacy dynamic completions For 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. + + + + + https://spf13.github.io/cobra/completions/fish/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/fish/ + Generating Fish Completions For Your cobra.Command Please refer to Shell Completions for details. + + + + + https://spf13.github.io/cobra/completions/powershell/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/powershell/ + Generating PowerShell Completions For Your Own cobra.Command Please refer to Shell Completions for details. + + + + + https://spf13.github.io/cobra/completions/zsh/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/zsh/ + Generating Zsh Completion For Your cobra.Command Please refer to Shell Completions for details. +Zsh completions standardization Cobra 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. +Deprecation summary See further below for more details on these deprecations. +cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) is no longer needed. It is therefore deprecated and silently ignored. cmd.MarkZshCompPositionalArgumentFile(pos, glob[]) is deprecated and silently ignored. + + + + diff --git a/docgen/index.html b/docgen/index.html new file mode 100644 index 000000000..506d9ef21 --- /dev/null +++ b/docgen/index.html @@ -0,0 +1,1941 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NAV + + + +
+ + + + + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Active Help

+

Active 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.

+

For example,

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding.
+
+bash-5.1$ bin/helm package [tab]
+Please specify the path to the chart to package
+
+bash-5.1$ bin/helm package [tab][tab]
+bin/    internal/    scripts/    pkg/     testdata/
+

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.

+ + + + + + + + +

Supported shells

+

Active Help is currently only supported for the following shells:

+ + + + + + + + + +

Adding Active Help messages

+

As 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.

+

Adding 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.

+ + + + + + + + +

Active Help for nouns

+

Adding 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:

+
cmd := &cobra.Command{
+	Use:   "add [NAME] [URL]",
+	Short: "add a chart repository",
+	Args:  require.ExactArgs(2),
+	RunE: func(cmd *cobra.Command, args []string) error {
+		return addRepo(args)
+	},
+	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		var comps []string
+		if len(args) == 0 {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		} else if len(args) == 1 {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		} else {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+		return comps, cobra.ShellCompDirectiveNoFileComp
+	},
+}
+

The 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:

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding
+
+bash-5.1$ helm repo add grafana [tab]
+You must specify the URL for the repo you are adding
+
+bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
+This command does not take any more arguments
+

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.

+ + + + + + + + +

Active Help for flags

+

Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:

+
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		if len(args) != 2 {
+			return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
+		}
+		return compVersionFlag(args[1], toComplete)
+	})
+

The example above prints an Active Help message when not enough information was given by the user to complete the --version flag.

+
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
+You must first specify the chart to install before the --version flag can be completed
+
+bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
+2.0.1  2.0.2  2.0.3
+
+ + + + + + + +

User control of Active Help

+

You 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. +Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.

+

The way to configure Active Help is to use the program’s Active Help environment +variable. That variable is named <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of your +program in uppercase with any - replaced by an _. The variable should be set by the user to whatever +Active Help configuration values are supported by the program.

+

For example, say helm has chosen to support three levels for Active Help: on, off, local. Then a user +would set the desired behavior to local by doing export HELM_ACTIVE_HELP=local in their shell.

+

For simplicity, when in cmd.ValidArgsFunction(...) or a flag’s completion function, the program should read the +Active Help configuration using the cobra.GetActiveHelpConfig(cmd) function and select what Active Help messages +should or should not be added (instead of reading the environment variable directly).

+

For example:

+
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+	activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
+
+	var comps []string
+	if len(args) == 0 {
+		if activeHelpLevel != "off"  {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		}
+	} else if len(args) == 1 {
+		if activeHelpLevel != "off" {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		}
+	} else {
+		if activeHelpLevel == "local" {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+	}
+	return comps, cobra.ShellCompDirectiveNoFileComp
+},
+

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.

+

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.

+

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.

+ + + + + + + + +

Active Help with Cobra’s default completion command

+

Cobra provides a default completion command for programs that wish to use it. +When using the default completion command, Active Help is configurable in the same +fashion as described above using environment variables. You may wish to document this in more +details for your users.

+ + + + + + + + +

Debugging Active Help

+

Debugging 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 for details.

+

When 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:

+
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+_activeHelp_ WARNING: cannot re-use a name that is still in use
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+ + + + + + + + + +

Generating Bash Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Bash legacy dynamic completions

+

For 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.

+

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.

+

The 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.

+

Some code that works in kubernetes:

+
const (
+        bash_completion_func = `__kubectl_parse_get()
+{
+    local kubectl_output out
+    if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
+        out=($(echo "${kubectl_output}" | awk '{print $1}'))
+        COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
+    fi
+}
+
+__kubectl_get_resource()
+{
+    if [[ ${#nouns[@]} -eq 0 ]]; then
+        return 1
+    fi
+    __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
+    if [[ $? -eq 0 ]]; then
+        return 0
+    fi
+}
+
+__kubectl_custom_func() {
+    case ${last_command} in
+        kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
+            __kubectl_get_resource
+            return
+            ;;
+        *)
+            ;;
+    esac
+}
+`)
+

And then I set that in my command definition:

+
cmds := &cobra.Command{
+	Use:   "kubectl",
+	Short: "kubectl controls the Kubernetes cluster manager",
+	Long: `kubectl controls the Kubernetes cluster manager.
+
+Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
+	Run: runHelp,
+	BashCompletionFunction: bash_completion_func,
+}
+

The BashCompletionFunction option is really only valid/useful on the root command. Doing the above will cause __kubectl_custom_func() (__<command-use>_custom_func()) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like kubectl get pod [mypod]. If you type kubectl get pod [tab][tab] the __kubectl_customc_func() will run because the cobra.Command only understood “kubectl” and “get.” __kubectl_custom_func() will see that the cobra.Command is “kubectl_get” and will thus call another helper __kubectl_get_resource(). __kubectl_get_resource will look at the ’nouns’ collected. In our example the only noun will be pod. So it will call __kubectl_parse_get pod. __kubectl_parse_get will actually call out to kubernetes and get any pods. It will then set COMPREPLY to valid pods!

+

Similarly, for flags:

+
	annotation := make(map[string][]string)
+	annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
+
+	flag := &pflag.Flag{
+		Name:        "namespace",
+		Usage:       usage,
+		Annotations: annotation,
+	}
+	cmd.Flags().AddFlag(flag)
+

In addition add the __kubectl_get_namespaces implementation in the BashCompletionFunction +value, e.g.:

+
__kubectl_get_namespaces()
+{
+    local template
+    template="{{ range .items  }}{{ .metadata.name }} {{ end }}"
+    local kubectl_out
+    if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
+        COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
+    fi
+}
+
+ + + + + + + + + +

Generating Fish Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating PowerShell Completions For Your Own cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating Zsh Completion For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Zsh completions standardization

+

Cobra 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.

+ + + + + + + + +

Deprecation summary

+

See further below for more details on these deprecations.

+ + + + + + + + + +

Behavioral changes

+

Noun completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
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
Completion of flag names without the - prefix having been typedFlag names are only completed if the user has typed the first -
cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) used to turn on file completion on a per-argument position basisFile completion for all arguments by default; cmd.MarkZshCompPositionalArgumentFile() is deprecated and silently ignored
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)
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
+

Flag-value completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
No file completion by default (opposite of bash)File completion by default; use RegisterFlagCompletionFunc() with ShellCompDirectiveNoFileComp to turn off file completion
cmd.MarkFlagFilename(flag, []string{}) and similar used to turn on file completionFile completion by default; cmd.MarkFlagFilename(flag, []string{}) no longer needed in this context and silently ignored
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"})
cmd.MarkFlagDirname(flag) only completes directories (zsh-specific)Has been added for all shells
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
Completion of a flag name does not provide the = form (unlike bash)Retained for zsh and added to fish
+

Improvements

+ + + + + + + + + + + +

Generating Man Pages For Your Own cobra.Command

+

Generating man pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &doc.GenManHeader{
+		Title: "MINE",
+		Section: "3",
+	}
+	err := doc.GenManTree(cmd, header, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a man page /tmp/test.3

+ + + + + + + + + + +

Generating Markdown Docs For Your Own cobra.Command

+

Generating Markdown pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenMarkdownTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Markdown document /tmp/test.md

+ + + + + + + + +

Generate markdown docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenMarkdownTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate markdown docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenMarkdown(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the markdown doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + +

Customize the output

+

Both GenMarkdown and GenMarkdownTree have alternate versions with callbacks to get some control of the output:

+
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Generating ReStructured Text Docs For Your Own cobra.Command

+

Generating ReST pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenReSTTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a ReST document /tmp/test.rst

+ + + + + + + + +

Generate ReST docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenReSTTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate ReST docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenReST(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the ReST doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenReST and GenReSTTree have alternate versions with callbacks to get some control of the output:

+
func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
+	//...
+}
+
func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The 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:

+
// Sphinx cross-referencing format
+linkHandler := func(name, ref string) string {
+    return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
+}
+
+ + + + + + + + + +

Generating Yaml Docs For Your Own cobra.Command

+

Generating yaml files from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenYamlTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Yaml document /tmp/test.yaml

+ + + + + + + + +

Generate yaml docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"io/ioutil"
+	"log"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenYamlTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate yaml docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	doc.GenYaml(cmd, out)
+

This will write the yaml doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenYaml and GenYamlTree have alternate versions with callbacks to get some control of the output:

+
func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Projects using Cobra

+ + + + + + + + + + + +

User Guide

+

While you are welcome to provide your own organization, typically a Cobra-based +application will follow the following organizational structure:

+
  ▾ appName/
+    ▾ cmd/
+        add.go
+        your.go
+        commands.go
+        here.go
+      main.go
+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Using the Cobra Generator

+

Cobra-CLI is its own program that will create your application and add any commands you want. +It’s the easiest way to incorporate Cobra into your application.

+

For complete details on using the Cobra generator, please refer to The Cobra-CLI Generator README

+ + + + + + + + +

Using the Cobra Library

+

To manually implement Cobra you need to create a bare main.go file and a rootCmd file. +You will optionally provide additional commands as you see fit.

+ + + + + + + + +

Create rootCmd

+

Cobra doesn’t require any special constructors. Simply create your commands.

+

Ideally you place this in app/cmd/root.go:

+
var rootCmd = &cobra.Command{
+  Use:   "hugo",
+  Short: "Hugo is a very fast static site generator",
+  Long: `A Fast and Flexible Static Site Generator built with
+                love by spf13 and friends in Go.
+                Complete documentation is available at https://gohugo.io/documentation/`,
+  Run: func(cmd *cobra.Command, args []string) {
+    // Do Stuff Here
+  },
+}
+
+func Execute() {
+  if err := rootCmd.Execute(); err != nil {
+    fmt.Fprintln(os.Stderr, err)
+    os.Exit(1)
+  }
+}
+

You will additionally define flags and handle configuration in your init() function.

+

For example cmd/root.go:

+
package cmd
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+var (
+	// Used for flags.
+	cfgFile     string
+	userLicense string
+
+	rootCmd = &cobra.Command{
+		Use:   "cobra-cli",
+		Short: "A generator for Cobra based Applications",
+		Long: `Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.`,
+	}
+)
+
+// Execute executes the root command.
+func Execute() error {
+	return rootCmd.Execute()
+}
+
+func init() {
+	cobra.OnInitialize(initConfig)
+
+	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+	rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
+	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
+	rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
+	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
+	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+	viper.SetDefault("license", "apache")
+
+	rootCmd.AddCommand(addCmd)
+	rootCmd.AddCommand(initCmd)
+}
+
+func initConfig() {
+	if cfgFile != "" {
+		// Use config file from the flag.
+		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := os.UserHomeDir()
+		cobra.CheckErr(err)
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigType("yaml")
+		viper.SetConfigName(".cobra")
+	}
+
+	viper.AutomaticEnv()
+
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}
+
+ + + + + + + +

Create your main.go

+

With the root command you need to have your main function execute it. +Execute should be run on the root for clarity, though it can be called on any command.

+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Create additional commands

+

Additional commands can be defined and typically are each given their own file +inside of the cmd/ directory.

+

If you wanted to create a version command you would create cmd/version.go and +populate it with the following:

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(versionCmd)
+}
+
+var versionCmd = &cobra.Command{
+  Use:   "version",
+  Short: "Print the version number of Hugo",
+  Long:  `All software has versions. This is Hugo's`,
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
+  },
+}
+
+ + + + + + + +

Organizing subcommands

+

A command may have subcommands which in turn may have other subcommands. This is achieved by using +AddCommand. In some cases, especially in larger applications, each subcommand may be defined in +its own go package.

+

The suggested approach is for the parent command to use AddCommand to add its most immediate +subcommands. For example, consider the following directory structure:

+
├── cmd
+│   ├── root.go
+│   └── sub1
+│       ├── sub1.go
+│       └── sub2
+│           ├── leafA.go
+│           ├── leafB.go
+│           └── sub2.go
+└── main.go
+

In this case:

+ +

This approach ensures the subcommands are always included at compile time while avoiding cyclic +references.

+ + + + + + + + +

Returning and handling errors

+

If you wish to return an error to the caller of a command, RunE can be used.

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(tryCmd)
+}
+
+var tryCmd = &cobra.Command{
+  Use:   "try",
+  Short: "Try and possibly fail at something",
+  RunE: func(cmd *cobra.Command, args []string) error {
+    if err := someFunc(); err != nil {
+	return err
+    }
+    return nil
+  },
+}
+

The error can then be caught at the execute function call.

+ + + + + + + + +

Working with Flags

+

Flags provide modifiers to control how the action command operates.

+ + + + + + + + +

Assign flags to a command

+

Since the flags are defined and used in different locations, we need to +define a variable outside with the correct scope to assign the flag to +work with.

+
var Verbose bool
+var Source string
+

There are two different approaches to assign a flag.

+ + + + + + + + +

Persistent Flags

+

A flag can be ‘persistent’, meaning that this flag will be available to the +command it’s assigned to as well as every command under that command. For +global flags, assign a flag as a persistent flag on the root.

+
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
+
+ + + + + + + +

Local Flags

+

A flag can also be assigned locally, which will only apply to that specific command.

+
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
+
+ + + + + + + +

Local Flag on Parent Commands

+

By default, Cobra only parses local flags on the target command, and any local flags on +parent commands are ignored. By enabling Command.TraverseChildren, Cobra will +parse local flags on each command before executing the target command.

+
command := cobra.Command{
+  Use: "print [OPTIONS] [COMMANDS]",
+  TraverseChildren: true,
+}
+
+ + + + + + + +

Bind Flags with Config

+

You can also bind your flags with viper:

+
var author string
+
+func init() {
+  rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
+  viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+}
+

In this example, the persistent flag author is bound with viper. +Note: the variable author will not be set to the value from config, +when the --author flag is provided by user.

+

More in viper documentation.

+ + + + + + + + +

Required flags

+

Flags are optional by default. If instead you wish your command to report an error +when a flag has not been set, mark it as required:

+
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkFlagRequired("region")
+

Or, for persistent flags:

+
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkPersistentFlagRequired("region")
+
+ + + + + + + +

Flag Groups

+

If 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) then +Cobra can enforce that requirement:

+
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
+rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
+rootCmd.MarkFlagsRequiredTogether("username", "password")
+

You can also prevent different flags from being provided together if they represent mutually +exclusive options such as specifying an output format as either --json or --yaml but never both:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

If you want to require at least one flag from a group to be present, you can use MarkFlagsOneRequired. +This can be combined with MarkFlagsMutuallyExclusive to enforce exactly one flag from a given group:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsOneRequired("json", "yaml")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

In these cases:

+ + + + + + + + + +

Positional and Custom Arguments

+

Validation of positional arguments can be specified using the Args field of Command. +The following validators are built in:

+ +

If Args is undefined or nil, it defaults to ArbitraryArgs.

+

Moreover, MatchAll(pargs ...PositionalArgs) enables combining existing checks with arbitrary other checks. +For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional +args that are not in the ValidArgs field of Command, you can call MatchAll on ExactArgs and OnlyValidArgs, as +shown below:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+

It is possible to set any custom validator that satisfies func(cmd *cobra.Command, args []string) error. +For example:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: func(cmd *cobra.Command, args []string) error {
+    // Optionally run one of the validators provided by cobra
+    if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
+        return err
+    }
+    // Run the custom validation logic
+    if myapp.IsValidColor(args[0]) {
+      return nil
+    }
+    return fmt.Errorf("invalid color specified: %s", args[0])
+  },
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+
+ + + + + + + +

Example

+

In the example below, we have defined three commands. Two are at the top level +and one (cmdTimes) is a child of one of the top commands. In this case the root +is not executable, meaning that a subcommand is required. This is accomplished +by not providing a ‘Run’ for the ‘rootCmd’.

+

We have only defined one flag for a single command.

+

More documentation about flags is available at https://github.com/spf13/pflag

+
package main
+
+import (
+  "fmt"
+  "strings"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+  var echoTimes int
+
+  var cmdPrint = &cobra.Command{
+    Use:   "print [string to print]",
+    Short: "Print anything to the screen",
+    Long: `print is for printing anything back to the screen.
+For many years people have printed back to the screen.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Print: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdEcho = &cobra.Command{
+    Use:   "echo [string to echo]",
+    Short: "Echo anything to the screen",
+    Long: `echo is for echoing anything back.
+Echo works a lot like print, except it has a child command.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Echo: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdTimes = &cobra.Command{
+    Use:   "times [string to echo]",
+    Short: "Echo anything to the screen more times",
+    Long: `echo things multiple times back to the user by providing
+a count and a string.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      for i := 0; i < echoTimes; i++ {
+        fmt.Println("Echo: " + strings.Join(args, " "))
+      }
+    },
+  }
+
+  cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
+
+  var rootCmd = &cobra.Command{Use: "app"}
+  rootCmd.AddCommand(cmdPrint, cmdEcho)
+  cmdEcho.AddCommand(cmdTimes)
+  rootCmd.Execute()
+}
+

For a more complete example of a larger application, please checkout Hugo.

+ + + + + + + + +

Help Command

+

Cobra automatically adds a help command to your application when you have subcommands. +This will be called when a user runs ‘app help’. Additionally, help will also +support all other commands as input. Say, for instance, you have a command called +‘create’ without any additional configuration; Cobra will work when ‘app help +create’ is called. Every command will automatically have the ‘–help’ flag added.

+ + + + + + + + +

Example

+

The following output is automatically generated by Cobra. Nothing beyond the +command and flag definitions are needed.

+
$ cobra-cli help
+
+Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.
+
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra-cli [command] --help" for more information about a command.
+
+

Help is just a command like any other. There is no special logic or behavior +around it. In fact, you can provide your own if you want.

+ + + + + + + + +

Grouping commands in help

+

Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly +defined using AddGroup() on the parent command. Then a subcommand can be added to a group using the GroupID element +of that subcommand. The groups will appear in the help output in the same order as they are defined using different +calls to AddGroup(). If you use the generated help or completion commands, you can set their group ids using +SetHelpCommandGroupId() and SetCompletionCommandGroupId() on the root command, respectively.

+ + + + + + + + +

Defining your own help

+

You can provide your own Help command or your own template for the default command to use +with the following functions:

+
cmd.SetHelpCommand(cmd *Command)
+cmd.SetHelpFunc(f func(*Command, []string))
+cmd.SetHelpTemplate(s string)
+

The latter two will also apply to any children commands.

+ + + + + + + + +

Usage Message

+

When the user provides an invalid flag or invalid command, Cobra responds by +showing the user the ‘usage’.

+ + + + + + + + +

Example

+

You may recognize this from the help above. That’s because the default help +embeds the usage as part of its output.

+
$ cobra-cli --invalid
+Error: unknown flag: --invalid
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra [command] --help" for more information about a command.
+
+ + + + + + + + +

Defining your own usage

+

You can provide your own usage function or template for Cobra to use. +Like help, the function and template are overridable through public methods:

+
cmd.SetUsageFunc(f func(*Command) error)
+cmd.SetUsageTemplate(s string)
+
+ + + + + + + +

Version Flag

+

Cobra adds a top-level ‘–version’ flag if the Version field is set on the root command. +Running an application with the ‘–version’ flag will print the version to stdout using +the version template. The template can be customized using the +cmd.SetVersionTemplate(s string) function.

+ + + + + + + + +

PreRun and PostRun Hooks

+

It 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:

+ +

An 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:

+
package main
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+
+  var rootCmd = &cobra.Command{
+    Use:   "root [sub]",
+    Short: "My root command",
+    PersistentPreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
+    },
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  var subCmd = &cobra.Command{
+    Use:   "sub [no options!]",
+    Short: "My subcommand",
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  rootCmd.AddCommand(subCmd)
+
+  rootCmd.SetArgs([]string{""})
+  rootCmd.Execute()
+  fmt.Println()
+  rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
+  rootCmd.Execute()
+}
+

Output:

+
Inside rootCmd PersistentPreRun with args: []
+Inside rootCmd PreRun with args: []
+Inside rootCmd Run with args: []
+Inside rootCmd PostRun with args: []
+Inside rootCmd PersistentPostRun with args: []
+
+Inside rootCmd PersistentPreRun with args: [arg1 arg2]
+Inside subCmd PreRun with args: [arg1 arg2]
+Inside subCmd Run with args: [arg1 arg2]
+Inside subCmd PostRun with args: [arg1 arg2]
+Inside subCmd PersistentPostRun with args: [arg1 arg2]
+
+ + + + + + + +

Suggestions when “unknown command” happens

+

Cobra 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:

+
$ hugo srever
+Error: unknown command "srever" for "hugo"
+
+Did you mean this?
+        server
+
+Run 'hugo --help' for usage.
+

Suggestions are automatically generated based on existing subcommands and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.

+

If you need to disable suggestions or tweak the string distance in your command, use:

+
command.DisableSuggestions = true
+

or

+
command.SuggestionsMinimumDistance = 1
+

You 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 which +you don’t want aliases. Example:

+
$ kubectl remove
+Error: unknown command "remove" for "kubectl"
+
+Did you mean this?
+        delete
+
+Run 'kubectl help' for usage.
+
+ + + + + + + +

Generating documentation for your command

+

Cobra can generate documentation based on subcommands, flags, etc. +Read more about it in the docs generation documentation.

+ + + + + + + + +

Generating shell completions

+

Cobra 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.

+ + + + + + + + +

Providing Active Help

+

Cobra 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.

+ + + +
+
+ +
+
+ + + diff --git a/docgen/index.xml b/docgen/index.xml new file mode 100644 index 000000000..c65285ce3 --- /dev/null +++ b/docgen/index.xml @@ -0,0 +1,53 @@ + + + + Cobra documentation + https://spf13.github.io/cobra/docgen/ + Recent content on Cobra documentation + Hugo -- gohugo.io + en + + + https://spf13.github.io/cobra/docgen/man/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/man/ + Generating Man Pages For Your Own cobra.Command Generating man pages from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } header := &amp;doc.GenManHeader{ Title: &#34;MINE&#34;, Section: &#34;3&#34;, } err := doc.GenManTree(cmd, header, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a man page /tmp/test. + + + + + https://spf13.github.io/cobra/docgen/md/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/md/ + Generating Markdown Docs For Your Own cobra.Command Generating Markdown pages from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } err := doc.GenMarkdownTree(cmd, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a Markdown document /tmp/test.md +Generate markdown docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project + + + + + https://spf13.github.io/cobra/docgen/rest/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/rest/ + Generating ReStructured Text Docs For Your Own cobra.Command Generating ReST pages from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } err := doc.GenReSTTree(cmd, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a ReST document /tmp/test.rst +Generate ReST docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project + + + + + https://spf13.github.io/cobra/docgen/yaml/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/yaml/ + Generating Yaml Docs For Your Own cobra.Command Generating yaml files from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } err := doc.GenYamlTree(cmd, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a Yaml document /tmp/test.yaml +Generate yaml docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project + + + + diff --git a/fonts/slate.eot b/fonts/slate.eot new file mode 100644 index 000000000..13c4839a1 Binary files /dev/null and b/fonts/slate.eot differ diff --git a/fonts/slate.svg b/fonts/slate.svg new file mode 100644 index 000000000..5f3498230 --- /dev/null +++ b/fonts/slate.svg @@ -0,0 +1,14 @@ + + + +Generated by IcoMoon + + + + + + + + + + diff --git a/fonts/slate.ttf b/fonts/slate.ttf new file mode 100644 index 000000000..ace9a46a7 Binary files /dev/null and b/fonts/slate.ttf differ diff --git a/fonts/slate.woff b/fonts/slate.woff new file mode 100644 index 000000000..1e72e0ee0 Binary files /dev/null and b/fonts/slate.woff differ diff --git a/fonts/slate.woff2 b/fonts/slate.woff2 new file mode 100644 index 000000000..7c585a727 Binary files /dev/null and b/fonts/slate.woff2 differ diff --git a/images/logo.png b/images/logo.png new file mode 100644 index 000000000..8d4918ce9 Binary files /dev/null and b/images/logo.png differ diff --git a/images/navbar.png b/images/navbar.png new file mode 100644 index 000000000..df38e90d8 Binary files /dev/null and b/images/navbar.png differ diff --git a/index.html b/index.html new file mode 100644 index 000000000..f96c01a31 --- /dev/null +++ b/index.html @@ -0,0 +1,1942 @@ + + + + + + + + + Cobra documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NAV + + + +
+ + + + + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Active Help

+

Active 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.

+

For example,

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding.
+
+bash-5.1$ bin/helm package [tab]
+Please specify the path to the chart to package
+
+bash-5.1$ bin/helm package [tab][tab]
+bin/    internal/    scripts/    pkg/     testdata/
+

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.

+ + + + + + + + +

Supported shells

+

Active Help is currently only supported for the following shells:

+ + + + + + + + + +

Adding Active Help messages

+

As 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.

+

Adding 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.

+ + + + + + + + +

Active Help for nouns

+

Adding 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:

+
cmd := &cobra.Command{
+	Use:   "add [NAME] [URL]",
+	Short: "add a chart repository",
+	Args:  require.ExactArgs(2),
+	RunE: func(cmd *cobra.Command, args []string) error {
+		return addRepo(args)
+	},
+	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		var comps []string
+		if len(args) == 0 {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		} else if len(args) == 1 {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		} else {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+		return comps, cobra.ShellCompDirectiveNoFileComp
+	},
+}
+

The 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:

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding
+
+bash-5.1$ helm repo add grafana [tab]
+You must specify the URL for the repo you are adding
+
+bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
+This command does not take any more arguments
+

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.

+ + + + + + + + +

Active Help for flags

+

Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:

+
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		if len(args) != 2 {
+			return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
+		}
+		return compVersionFlag(args[1], toComplete)
+	})
+

The example above prints an Active Help message when not enough information was given by the user to complete the --version flag.

+
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
+You must first specify the chart to install before the --version flag can be completed
+
+bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
+2.0.1  2.0.2  2.0.3
+
+ + + + + + + +

User control of Active Help

+

You 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. +Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.

+

The way to configure Active Help is to use the program’s Active Help environment +variable. That variable is named <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of your +program in uppercase with any - replaced by an _. The variable should be set by the user to whatever +Active Help configuration values are supported by the program.

+

For example, say helm has chosen to support three levels for Active Help: on, off, local. Then a user +would set the desired behavior to local by doing export HELM_ACTIVE_HELP=local in their shell.

+

For simplicity, when in cmd.ValidArgsFunction(...) or a flag’s completion function, the program should read the +Active Help configuration using the cobra.GetActiveHelpConfig(cmd) function and select what Active Help messages +should or should not be added (instead of reading the environment variable directly).

+

For example:

+
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+	activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
+
+	var comps []string
+	if len(args) == 0 {
+		if activeHelpLevel != "off"  {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		}
+	} else if len(args) == 1 {
+		if activeHelpLevel != "off" {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		}
+	} else {
+		if activeHelpLevel == "local" {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+	}
+	return comps, cobra.ShellCompDirectiveNoFileComp
+},
+

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.

+

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.

+

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.

+ + + + + + + + +

Active Help with Cobra’s default completion command

+

Cobra provides a default completion command for programs that wish to use it. +When using the default completion command, Active Help is configurable in the same +fashion as described above using environment variables. You may wish to document this in more +details for your users.

+ + + + + + + + +

Debugging Active Help

+

Debugging 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 for details.

+

When 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:

+
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+_activeHelp_ WARNING: cannot re-use a name that is still in use
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+ + + + + + + + + +

Generating Bash Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Bash legacy dynamic completions

+

For 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.

+

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.

+

The 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.

+

Some code that works in kubernetes:

+
const (
+        bash_completion_func = `__kubectl_parse_get()
+{
+    local kubectl_output out
+    if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
+        out=($(echo "${kubectl_output}" | awk '{print $1}'))
+        COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
+    fi
+}
+
+__kubectl_get_resource()
+{
+    if [[ ${#nouns[@]} -eq 0 ]]; then
+        return 1
+    fi
+    __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
+    if [[ $? -eq 0 ]]; then
+        return 0
+    fi
+}
+
+__kubectl_custom_func() {
+    case ${last_command} in
+        kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
+            __kubectl_get_resource
+            return
+            ;;
+        *)
+            ;;
+    esac
+}
+`)
+

And then I set that in my command definition:

+
cmds := &cobra.Command{
+	Use:   "kubectl",
+	Short: "kubectl controls the Kubernetes cluster manager",
+	Long: `kubectl controls the Kubernetes cluster manager.
+
+Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
+	Run: runHelp,
+	BashCompletionFunction: bash_completion_func,
+}
+

The BashCompletionFunction option is really only valid/useful on the root command. Doing the above will cause __kubectl_custom_func() (__<command-use>_custom_func()) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like kubectl get pod [mypod]. If you type kubectl get pod [tab][tab] the __kubectl_customc_func() will run because the cobra.Command only understood “kubectl” and “get.” __kubectl_custom_func() will see that the cobra.Command is “kubectl_get” and will thus call another helper __kubectl_get_resource(). __kubectl_get_resource will look at the ’nouns’ collected. In our example the only noun will be pod. So it will call __kubectl_parse_get pod. __kubectl_parse_get will actually call out to kubernetes and get any pods. It will then set COMPREPLY to valid pods!

+

Similarly, for flags:

+
	annotation := make(map[string][]string)
+	annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
+
+	flag := &pflag.Flag{
+		Name:        "namespace",
+		Usage:       usage,
+		Annotations: annotation,
+	}
+	cmd.Flags().AddFlag(flag)
+

In addition add the __kubectl_get_namespaces implementation in the BashCompletionFunction +value, e.g.:

+
__kubectl_get_namespaces()
+{
+    local template
+    template="{{ range .items  }}{{ .metadata.name }} {{ end }}"
+    local kubectl_out
+    if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
+        COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
+    fi
+}
+
+ + + + + + + + + +

Generating Fish Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating PowerShell Completions For Your Own cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating Zsh Completion For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Zsh completions standardization

+

Cobra 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.

+ + + + + + + + +

Deprecation summary

+

See further below for more details on these deprecations.

+ + + + + + + + + +

Behavioral changes

+

Noun completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
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
Completion of flag names without the - prefix having been typedFlag names are only completed if the user has typed the first -
cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) used to turn on file completion on a per-argument position basisFile completion for all arguments by default; cmd.MarkZshCompPositionalArgumentFile() is deprecated and silently ignored
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)
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
+

Flag-value completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
No file completion by default (opposite of bash)File completion by default; use RegisterFlagCompletionFunc() with ShellCompDirectiveNoFileComp to turn off file completion
cmd.MarkFlagFilename(flag, []string{}) and similar used to turn on file completionFile completion by default; cmd.MarkFlagFilename(flag, []string{}) no longer needed in this context and silently ignored
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"})
cmd.MarkFlagDirname(flag) only completes directories (zsh-specific)Has been added for all shells
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
Completion of a flag name does not provide the = form (unlike bash)Retained for zsh and added to fish
+

Improvements

+ + + + + + + + + + + +

Generating Man Pages For Your Own cobra.Command

+

Generating man pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &doc.GenManHeader{
+		Title: "MINE",
+		Section: "3",
+	}
+	err := doc.GenManTree(cmd, header, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a man page /tmp/test.3

+ + + + + + + + + + +

Generating Markdown Docs For Your Own cobra.Command

+

Generating Markdown pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenMarkdownTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Markdown document /tmp/test.md

+ + + + + + + + +

Generate markdown docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenMarkdownTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate markdown docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenMarkdown(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the markdown doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + +

Customize the output

+

Both GenMarkdown and GenMarkdownTree have alternate versions with callbacks to get some control of the output:

+
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Generating ReStructured Text Docs For Your Own cobra.Command

+

Generating ReST pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenReSTTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a ReST document /tmp/test.rst

+ + + + + + + + +

Generate ReST docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenReSTTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate ReST docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenReST(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the ReST doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenReST and GenReSTTree have alternate versions with callbacks to get some control of the output:

+
func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
+	//...
+}
+
func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The 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:

+
// Sphinx cross-referencing format
+linkHandler := func(name, ref string) string {
+    return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
+}
+
+ + + + + + + + + +

Generating Yaml Docs For Your Own cobra.Command

+

Generating yaml files from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenYamlTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Yaml document /tmp/test.yaml

+ + + + + + + + +

Generate yaml docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"io/ioutil"
+	"log"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenYamlTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate yaml docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	doc.GenYaml(cmd, out)
+

This will write the yaml doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenYaml and GenYamlTree have alternate versions with callbacks to get some control of the output:

+
func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Projects using Cobra

+ + + + + + + + + + + +

User Guide

+

While you are welcome to provide your own organization, typically a Cobra-based +application will follow the following organizational structure:

+
  ▾ appName/
+    ▾ cmd/
+        add.go
+        your.go
+        commands.go
+        here.go
+      main.go
+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Using the Cobra Generator

+

Cobra-CLI is its own program that will create your application and add any commands you want. +It’s the easiest way to incorporate Cobra into your application.

+

For complete details on using the Cobra generator, please refer to The Cobra-CLI Generator README

+ + + + + + + + +

Using the Cobra Library

+

To manually implement Cobra you need to create a bare main.go file and a rootCmd file. +You will optionally provide additional commands as you see fit.

+ + + + + + + + +

Create rootCmd

+

Cobra doesn’t require any special constructors. Simply create your commands.

+

Ideally you place this in app/cmd/root.go:

+
var rootCmd = &cobra.Command{
+  Use:   "hugo",
+  Short: "Hugo is a very fast static site generator",
+  Long: `A Fast and Flexible Static Site Generator built with
+                love by spf13 and friends in Go.
+                Complete documentation is available at https://gohugo.io/documentation/`,
+  Run: func(cmd *cobra.Command, args []string) {
+    // Do Stuff Here
+  },
+}
+
+func Execute() {
+  if err := rootCmd.Execute(); err != nil {
+    fmt.Fprintln(os.Stderr, err)
+    os.Exit(1)
+  }
+}
+

You will additionally define flags and handle configuration in your init() function.

+

For example cmd/root.go:

+
package cmd
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+var (
+	// Used for flags.
+	cfgFile     string
+	userLicense string
+
+	rootCmd = &cobra.Command{
+		Use:   "cobra-cli",
+		Short: "A generator for Cobra based Applications",
+		Long: `Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.`,
+	}
+)
+
+// Execute executes the root command.
+func Execute() error {
+	return rootCmd.Execute()
+}
+
+func init() {
+	cobra.OnInitialize(initConfig)
+
+	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+	rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
+	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
+	rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
+	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
+	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+	viper.SetDefault("license", "apache")
+
+	rootCmd.AddCommand(addCmd)
+	rootCmd.AddCommand(initCmd)
+}
+
+func initConfig() {
+	if cfgFile != "" {
+		// Use config file from the flag.
+		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := os.UserHomeDir()
+		cobra.CheckErr(err)
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigType("yaml")
+		viper.SetConfigName(".cobra")
+	}
+
+	viper.AutomaticEnv()
+
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}
+
+ + + + + + + +

Create your main.go

+

With the root command you need to have your main function execute it. +Execute should be run on the root for clarity, though it can be called on any command.

+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Create additional commands

+

Additional commands can be defined and typically are each given their own file +inside of the cmd/ directory.

+

If you wanted to create a version command you would create cmd/version.go and +populate it with the following:

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(versionCmd)
+}
+
+var versionCmd = &cobra.Command{
+  Use:   "version",
+  Short: "Print the version number of Hugo",
+  Long:  `All software has versions. This is Hugo's`,
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
+  },
+}
+
+ + + + + + + +

Organizing subcommands

+

A command may have subcommands which in turn may have other subcommands. This is achieved by using +AddCommand. In some cases, especially in larger applications, each subcommand may be defined in +its own go package.

+

The suggested approach is for the parent command to use AddCommand to add its most immediate +subcommands. For example, consider the following directory structure:

+
├── cmd
+│   ├── root.go
+│   └── sub1
+│       ├── sub1.go
+│       └── sub2
+│           ├── leafA.go
+│           ├── leafB.go
+│           └── sub2.go
+└── main.go
+

In this case:

+ +

This approach ensures the subcommands are always included at compile time while avoiding cyclic +references.

+ + + + + + + + +

Returning and handling errors

+

If you wish to return an error to the caller of a command, RunE can be used.

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(tryCmd)
+}
+
+var tryCmd = &cobra.Command{
+  Use:   "try",
+  Short: "Try and possibly fail at something",
+  RunE: func(cmd *cobra.Command, args []string) error {
+    if err := someFunc(); err != nil {
+	return err
+    }
+    return nil
+  },
+}
+

The error can then be caught at the execute function call.

+ + + + + + + + +

Working with Flags

+

Flags provide modifiers to control how the action command operates.

+ + + + + + + + +

Assign flags to a command

+

Since the flags are defined and used in different locations, we need to +define a variable outside with the correct scope to assign the flag to +work with.

+
var Verbose bool
+var Source string
+

There are two different approaches to assign a flag.

+ + + + + + + + +

Persistent Flags

+

A flag can be ‘persistent’, meaning that this flag will be available to the +command it’s assigned to as well as every command under that command. For +global flags, assign a flag as a persistent flag on the root.

+
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
+
+ + + + + + + +

Local Flags

+

A flag can also be assigned locally, which will only apply to that specific command.

+
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
+
+ + + + + + + +

Local Flag on Parent Commands

+

By default, Cobra only parses local flags on the target command, and any local flags on +parent commands are ignored. By enabling Command.TraverseChildren, Cobra will +parse local flags on each command before executing the target command.

+
command := cobra.Command{
+  Use: "print [OPTIONS] [COMMANDS]",
+  TraverseChildren: true,
+}
+
+ + + + + + + +

Bind Flags with Config

+

You can also bind your flags with viper:

+
var author string
+
+func init() {
+  rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
+  viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+}
+

In this example, the persistent flag author is bound with viper. +Note: the variable author will not be set to the value from config, +when the --author flag is provided by user.

+

More in viper documentation.

+ + + + + + + + +

Required flags

+

Flags are optional by default. If instead you wish your command to report an error +when a flag has not been set, mark it as required:

+
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkFlagRequired("region")
+

Or, for persistent flags:

+
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkPersistentFlagRequired("region")
+
+ + + + + + + +

Flag Groups

+

If 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) then +Cobra can enforce that requirement:

+
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
+rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
+rootCmd.MarkFlagsRequiredTogether("username", "password")
+

You can also prevent different flags from being provided together if they represent mutually +exclusive options such as specifying an output format as either --json or --yaml but never both:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

If you want to require at least one flag from a group to be present, you can use MarkFlagsOneRequired. +This can be combined with MarkFlagsMutuallyExclusive to enforce exactly one flag from a given group:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsOneRequired("json", "yaml")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

In these cases:

+ + + + + + + + + +

Positional and Custom Arguments

+

Validation of positional arguments can be specified using the Args field of Command. +The following validators are built in:

+ +

If Args is undefined or nil, it defaults to ArbitraryArgs.

+

Moreover, MatchAll(pargs ...PositionalArgs) enables combining existing checks with arbitrary other checks. +For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional +args that are not in the ValidArgs field of Command, you can call MatchAll on ExactArgs and OnlyValidArgs, as +shown below:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+

It is possible to set any custom validator that satisfies func(cmd *cobra.Command, args []string) error. +For example:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: func(cmd *cobra.Command, args []string) error {
+    // Optionally run one of the validators provided by cobra
+    if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
+        return err
+    }
+    // Run the custom validation logic
+    if myapp.IsValidColor(args[0]) {
+      return nil
+    }
+    return fmt.Errorf("invalid color specified: %s", args[0])
+  },
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+
+ + + + + + + +

Example

+

In the example below, we have defined three commands. Two are at the top level +and one (cmdTimes) is a child of one of the top commands. In this case the root +is not executable, meaning that a subcommand is required. This is accomplished +by not providing a ‘Run’ for the ‘rootCmd’.

+

We have only defined one flag for a single command.

+

More documentation about flags is available at https://github.com/spf13/pflag

+
package main
+
+import (
+  "fmt"
+  "strings"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+  var echoTimes int
+
+  var cmdPrint = &cobra.Command{
+    Use:   "print [string to print]",
+    Short: "Print anything to the screen",
+    Long: `print is for printing anything back to the screen.
+For many years people have printed back to the screen.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Print: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdEcho = &cobra.Command{
+    Use:   "echo [string to echo]",
+    Short: "Echo anything to the screen",
+    Long: `echo is for echoing anything back.
+Echo works a lot like print, except it has a child command.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Echo: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdTimes = &cobra.Command{
+    Use:   "times [string to echo]",
+    Short: "Echo anything to the screen more times",
+    Long: `echo things multiple times back to the user by providing
+a count and a string.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      for i := 0; i < echoTimes; i++ {
+        fmt.Println("Echo: " + strings.Join(args, " "))
+      }
+    },
+  }
+
+  cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
+
+  var rootCmd = &cobra.Command{Use: "app"}
+  rootCmd.AddCommand(cmdPrint, cmdEcho)
+  cmdEcho.AddCommand(cmdTimes)
+  rootCmd.Execute()
+}
+

For a more complete example of a larger application, please checkout Hugo.

+ + + + + + + + +

Help Command

+

Cobra automatically adds a help command to your application when you have subcommands. +This will be called when a user runs ‘app help’. Additionally, help will also +support all other commands as input. Say, for instance, you have a command called +‘create’ without any additional configuration; Cobra will work when ‘app help +create’ is called. Every command will automatically have the ‘–help’ flag added.

+ + + + + + + + +

Example

+

The following output is automatically generated by Cobra. Nothing beyond the +command and flag definitions are needed.

+
$ cobra-cli help
+
+Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.
+
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra-cli [command] --help" for more information about a command.
+
+

Help is just a command like any other. There is no special logic or behavior +around it. In fact, you can provide your own if you want.

+ + + + + + + + +

Grouping commands in help

+

Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly +defined using AddGroup() on the parent command. Then a subcommand can be added to a group using the GroupID element +of that subcommand. The groups will appear in the help output in the same order as they are defined using different +calls to AddGroup(). If you use the generated help or completion commands, you can set their group ids using +SetHelpCommandGroupId() and SetCompletionCommandGroupId() on the root command, respectively.

+ + + + + + + + +

Defining your own help

+

You can provide your own Help command or your own template for the default command to use +with the following functions:

+
cmd.SetHelpCommand(cmd *Command)
+cmd.SetHelpFunc(f func(*Command, []string))
+cmd.SetHelpTemplate(s string)
+

The latter two will also apply to any children commands.

+ + + + + + + + +

Usage Message

+

When the user provides an invalid flag or invalid command, Cobra responds by +showing the user the ‘usage’.

+ + + + + + + + +

Example

+

You may recognize this from the help above. That’s because the default help +embeds the usage as part of its output.

+
$ cobra-cli --invalid
+Error: unknown flag: --invalid
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra [command] --help" for more information about a command.
+
+ + + + + + + + +

Defining your own usage

+

You can provide your own usage function or template for Cobra to use. +Like help, the function and template are overridable through public methods:

+
cmd.SetUsageFunc(f func(*Command) error)
+cmd.SetUsageTemplate(s string)
+
+ + + + + + + +

Version Flag

+

Cobra adds a top-level ‘–version’ flag if the Version field is set on the root command. +Running an application with the ‘–version’ flag will print the version to stdout using +the version template. The template can be customized using the +cmd.SetVersionTemplate(s string) function.

+ + + + + + + + +

PreRun and PostRun Hooks

+

It 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:

+ +

An 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:

+
package main
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+
+  var rootCmd = &cobra.Command{
+    Use:   "root [sub]",
+    Short: "My root command",
+    PersistentPreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
+    },
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  var subCmd = &cobra.Command{
+    Use:   "sub [no options!]",
+    Short: "My subcommand",
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  rootCmd.AddCommand(subCmd)
+
+  rootCmd.SetArgs([]string{""})
+  rootCmd.Execute()
+  fmt.Println()
+  rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
+  rootCmd.Execute()
+}
+

Output:

+
Inside rootCmd PersistentPreRun with args: []
+Inside rootCmd PreRun with args: []
+Inside rootCmd Run with args: []
+Inside rootCmd PostRun with args: []
+Inside rootCmd PersistentPostRun with args: []
+
+Inside rootCmd PersistentPreRun with args: [arg1 arg2]
+Inside subCmd PreRun with args: [arg1 arg2]
+Inside subCmd Run with args: [arg1 arg2]
+Inside subCmd PostRun with args: [arg1 arg2]
+Inside subCmd PersistentPostRun with args: [arg1 arg2]
+
+ + + + + + + +

Suggestions when “unknown command” happens

+

Cobra 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:

+
$ hugo srever
+Error: unknown command "srever" for "hugo"
+
+Did you mean this?
+        server
+
+Run 'hugo --help' for usage.
+

Suggestions are automatically generated based on existing subcommands and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.

+

If you need to disable suggestions or tweak the string distance in your command, use:

+
command.DisableSuggestions = true
+

or

+
command.SuggestionsMinimumDistance = 1
+

You 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 which +you don’t want aliases. Example:

+
$ kubectl remove
+Error: unknown command "remove" for "kubectl"
+
+Did you mean this?
+        delete
+
+Run 'kubectl help' for usage.
+
+ + + + + + + +

Generating documentation for your command

+

Cobra can generate documentation based on subcommands, flags, etc. +Read more about it in the docs generation documentation.

+ + + + + + + + +

Generating shell completions

+

Cobra 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.

+ + + + + + + + +

Providing Active Help

+

Cobra 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.

+ + + +
+
+ +
+
+ + + diff --git a/index.xml b/index.xml new file mode 100644 index 000000000..fecffa857 --- /dev/null +++ b/index.xml @@ -0,0 +1,124 @@ + + + + Cobra documentation + https://spf13.github.io/cobra/ + Recent content on Cobra documentation + Hugo -- gohugo.io + en + + + https://spf13.github.io/cobra/active_help/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/active_help/ + Active Help Active 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. +For example, +bash-5.1$ helm repo add [tab] You must choose a name for the repo you are adding. + + + + + https://spf13.github.io/cobra/completions/bash/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/bash/ + Generating Bash Completions For Your cobra.Command Please refer to Shell Completions for details. +Bash legacy dynamic completions For 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. + + + + + https://spf13.github.io/cobra/completions/fish/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/fish/ + Generating Fish Completions For Your cobra.Command Please refer to Shell Completions for details. + + + + + https://spf13.github.io/cobra/completions/powershell/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/powershell/ + Generating PowerShell Completions For Your Own cobra.Command Please refer to Shell Completions for details. + + + + + https://spf13.github.io/cobra/completions/zsh/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/completions/zsh/ + Generating Zsh Completion For Your cobra.Command Please refer to Shell Completions for details. +Zsh completions standardization Cobra 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. +Deprecation summary See further below for more details on these deprecations. +cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) is no longer needed. It is therefore deprecated and silently ignored. cmd.MarkZshCompPositionalArgumentFile(pos, glob[]) is deprecated and silently ignored. + + + + + https://spf13.github.io/cobra/docgen/man/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/man/ + Generating Man Pages For Your Own cobra.Command Generating man pages from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } header := &amp;doc.GenManHeader{ Title: &#34;MINE&#34;, Section: &#34;3&#34;, } err := doc.GenManTree(cmd, header, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a man page /tmp/test. + + + + + https://spf13.github.io/cobra/docgen/md/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/md/ + Generating Markdown Docs For Your Own cobra.Command Generating Markdown pages from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } err := doc.GenMarkdownTree(cmd, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a Markdown document /tmp/test.md +Generate markdown docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project + + + + + https://spf13.github.io/cobra/docgen/rest/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/rest/ + Generating ReStructured Text Docs For Your Own cobra.Command Generating ReST pages from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } err := doc.GenReSTTree(cmd, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a ReST document /tmp/test.rst +Generate ReST docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project + + + + + https://spf13.github.io/cobra/docgen/yaml/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/docgen/yaml/ + Generating Yaml Docs For Your Own cobra.Command Generating yaml files from a cobra command is incredibly easy. An example is as follows: +package main import ( &#34;log&#34; &#34;github.com/spf13/cobra&#34; &#34;github.com/spf13/cobra/doc&#34; ) func main() { cmd := &amp;cobra.Command{ Use: &#34;test&#34;, Short: &#34;my test program&#34;, } err := doc.GenYamlTree(cmd, &#34;/tmp&#34;) if err != nil { log.Fatal(err) } } That will get you a Yaml document /tmp/test.yaml +Generate yaml docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project + + + + + https://spf13.github.io/cobra/projects_using_cobra/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/projects_using_cobra/ + Projects using Cobra Allero Arewefastyet Arduino CLI Bleve Cilium CloudQuery CockroachDB Constellation Cosmos SDK Datree Delve Docker (distribution) Etcd Gardener Giant Swarm&rsquo;s gsctl Git Bump GitHub CLI GitHub Labeler Golangci-lint GopherJS GoReleaser Helm Hugo Infracost Istio Kool Kubernetes Kubescape KubeVirt Linkerd Mattermost-server Mercure Meroxa CLI Metal Stack CLI Moby (former Docker) Moldy Multi-gitter Nanobox/Nanopack nFPM Okteto OpenShift Ory Hydra Ory Kratos Pixie Polygon Edge Pouch ProjectAtomic (enterprise) Prototool Pulumi QRcp Random Rclone Scaleway CLI Sia Skaffold Tendermint Twitch CLI UpCloud CLI (upctl) Vitess VMware&rsquo;s Tanzu Community Edition &amp; Tanzu Framework Werf ZITADEL + + + + + https://spf13.github.io/cobra/user_guide/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://spf13.github.io/cobra/user_guide/ + User Guide While you are welcome to provide your own organization, typically a Cobra-based application will follow the following organizational structure: +▾ appName/ ▾ cmd/ add.go your.go commands.go here.go main.go In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. +package main import ( &#34;{pathToYourApp}/cmd&#34; ) func main() { cmd.Execute() } Using the Cobra Generator Cobra-CLI is its own program that will create your application and add any commands you want. + + + + diff --git a/js/index.9eb557de32bb57d26313bf5737edf1ddeb0953be47b26637ab73a984517149f3.js b/js/index.9eb557de32bb57d26313bf5737edf1ddeb0953be47b26637ab73a984517149f3.js new file mode 100644 index 000000000..136fb8e46 --- /dev/null +++ b/js/index.9eb557de32bb57d26313bf5737edf1ddeb0953be47b26637ab73a984517149f3.js @@ -0,0 +1,56 @@ +(()=>{var hn=Object.create;var Lt=Object.defineProperty;var pn=Object.getOwnPropertyDescriptor;var gn=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,vn=Object.prototype.hasOwnProperty;var yn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var xn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of gn(t))!vn.call(e,i)&&i!==r&&Lt(e,i,{get:()=>t[i],enumerable:!(n=pn(t,i))||n.enumerable});return e};var mn=(e,t,r)=>(r=e!=null?hn(_n(e)):{},xn(t||!e||!e.__esModule?Lt(r,"default",{value:e,enumerable:!0}):r,e));var It=yn((Rt,kt)=>{(function(){var e=function(t){var r=new e.Builder;return r.pipeline.add(e.trimmer,e.stopWordFilter,e.stemmer),r.searchPipeline.add(e.stemmer),t.call(r,r),r.build()};e.version="2.3.8";e.utils={},e.utils.warn=function(t){return function(r){t.console&&console.warn&&console.warn(r)}}(this),e.utils.asString=function(t){return t==null?"":t.toString()},e.utils.clone=function(t){if(t==null)return t;for(var r=Object.create(null),n=Object.keys(t),i=0;i0){var c=e.utils.clone(r)||{};c.position=[a,l],c.index=s.length,s.push(new e.Token(n.slice(a,o),c))}a=o+1}}return s},e.tokenizer.separator=/[\s\-]+/;e.Pipeline=function(){this._stack=[]},e.Pipeline.registeredFunctions=Object.create(null),e.Pipeline.registerFunction=function(t,r){r in this.registeredFunctions&&e.utils.warn("Overwriting existing registered function: "+r),t.label=r,e.Pipeline.registeredFunctions[t.label]=t},e.Pipeline.warnIfFunctionNotRegistered=function(t){var r=t.label&&t.label in this.registeredFunctions;r||e.utils.warn(`Function is not registered with pipeline. This may cause problems when serialising the index. +`,t)},e.Pipeline.load=function(t){var r=new e.Pipeline;return t.forEach(function(n){var i=e.Pipeline.registeredFunctions[n];if(i)r.add(i);else throw new Error("Cannot load unregistered function: "+n)}),r},e.Pipeline.prototype.add=function(){var t=Array.prototype.slice.call(arguments);t.forEach(function(r){e.Pipeline.warnIfFunctionNotRegistered(r),this._stack.push(r)},this)},e.Pipeline.prototype.after=function(t,r){e.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(t);if(n==-1)throw new Error("Cannot find existingFn");n=n+1,this._stack.splice(n,0,r)},e.Pipeline.prototype.before=function(t,r){e.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(t);if(n==-1)throw new Error("Cannot find existingFn");this._stack.splice(n,0,r)},e.Pipeline.prototype.remove=function(t){var r=this._stack.indexOf(t);r!=-1&&this._stack.splice(r,1)},e.Pipeline.prototype.run=function(t){for(var r=this._stack.length,n=0;n1&&(ot&&(n=s),o!=t);)i=n-r,s=r+Math.floor(i/2),o=this.elements[s*2];if(o==t||o>t)return s*2;if(ou?c+=2:a==u&&(r+=n[l+1]*i[c+1],l+=2,c+=2);return r},e.Vector.prototype.similarity=function(t){return this.dot(t)/this.magnitude()||0},e.Vector.prototype.toArray=function(){for(var t=new Array(this.elements.length/2),r=1,n=0;r0){var o=s.str.charAt(0),a;o in s.node.edges?a=s.node.edges[o]:(a=new e.TokenSet,s.node.edges[o]=a),s.str.length==1&&(a.final=!0),i.push({node:a,editsRemaining:s.editsRemaining,str:s.str.slice(1)})}if(s.editsRemaining!=0){if("*"in s.node.edges)var u=s.node.edges["*"];else{var u=new e.TokenSet;s.node.edges["*"]=u}if(s.str.length==0&&(u.final=!0),i.push({node:u,editsRemaining:s.editsRemaining-1,str:s.str}),s.str.length>1&&i.push({node:s.node,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)}),s.str.length==1&&(s.node.final=!0),s.str.length>=1){if("*"in s.node.edges)var l=s.node.edges["*"];else{var l=new e.TokenSet;s.node.edges["*"]=l}s.str.length==1&&(l.final=!0),i.push({node:l,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)})}if(s.str.length>1){var c=s.str.charAt(0),d=s.str.charAt(1),g;d in s.node.edges?g=s.node.edges[d]:(g=new e.TokenSet,s.node.edges[d]=g),s.str.length==1&&(g.final=!0),i.push({node:g,editsRemaining:s.editsRemaining-1,str:c+s.str.slice(2)})}}}return n},e.TokenSet.fromString=function(t){for(var r=new e.TokenSet,n=r,i=0,s=t.length;i=t;r--){var n=this.uncheckedNodes[r],i=n.child.toString();i in this.minimizedNodes?n.parent.edges[n.char]=this.minimizedNodes[i]:(n.child._str=i,this.minimizedNodes[i]=n.child),this.uncheckedNodes.pop()}};e.Index=function(t){this.invertedIndex=t.invertedIndex,this.fieldVectors=t.fieldVectors,this.tokenSet=t.tokenSet,this.fields=t.fields,this.pipeline=t.pipeline},e.Index.prototype.search=function(t){return this.query(function(r){var n=new e.QueryParser(t,r);n.parse()})},e.Index.prototype.query=function(t){for(var r=new e.Query(this.fields),n=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null),a=Object.create(null),u=0;u1?this._b=1:this._b=t},e.Builder.prototype.k1=function(t){this._k1=t},e.Builder.prototype.add=function(t,r){var n=t[this._ref],i=Object.keys(this._fields);this._documents[n]=r||{},this.documentCount+=1;for(var s=0;s=this.length)return e.QueryLexer.EOS;var t=this.str.charAt(this.pos);return this.pos+=1,t},e.QueryLexer.prototype.width=function(){return this.pos-this.start},e.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},e.QueryLexer.prototype.backup=function(){this.pos-=1},e.QueryLexer.prototype.acceptDigitRun=function(){var t,r;do t=this.next(),r=t.charCodeAt(0);while(r>47&&r<58);t!=e.QueryLexer.EOS&&this.backup()},e.QueryLexer.prototype.more=function(){return this.pos1&&(t.backup(),t.emit(e.QueryLexer.TERM)),t.ignore(),t.more())return e.QueryLexer.lexText},e.QueryLexer.lexEditDistance=function(t){return t.ignore(),t.acceptDigitRun(),t.emit(e.QueryLexer.EDIT_DISTANCE),e.QueryLexer.lexText},e.QueryLexer.lexBoost=function(t){return t.ignore(),t.acceptDigitRun(),t.emit(e.QueryLexer.BOOST),e.QueryLexer.lexText},e.QueryLexer.lexEOS=function(t){t.width()>0&&t.emit(e.QueryLexer.TERM)},e.QueryLexer.termSeparator=e.tokenizer.separator,e.QueryLexer.lexText=function(t){for(;;){var r=t.next();if(r==e.QueryLexer.EOS)return e.QueryLexer.lexEOS;if(r.charCodeAt(0)==92){t.escapeCharacter();continue}if(r==":")return e.QueryLexer.lexField;if(r=="~")return t.backup(),t.width()>0&&t.emit(e.QueryLexer.TERM),e.QueryLexer.lexEditDistance;if(r=="^")return t.backup(),t.width()>0&&t.emit(e.QueryLexer.TERM),e.QueryLexer.lexBoost;if(r=="+"&&t.width()===1||r=="-"&&t.width()===1)return t.emit(e.QueryLexer.PRESENCE),e.QueryLexer.lexText;if(r.match(e.QueryLexer.termSeparator))return e.QueryLexer.lexTerm}},e.QueryParser=function(t,r){this.lexer=new e.QueryLexer(t),this.query=r,this.currentClause={},this.lexemeIdx=0},e.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var t=e.QueryParser.parseClause;t;)t=t(this);return this.query},e.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},e.QueryParser.prototype.consumeLexeme=function(){var t=this.peekLexeme();return this.lexemeIdx+=1,t},e.QueryParser.prototype.nextClause=function(){var t=this.currentClause;this.query.clause(t),this.currentClause={}},e.QueryParser.parseClause=function(t){var r=t.peekLexeme();if(r!=null)switch(r.type){case e.QueryLexer.PRESENCE:return e.QueryParser.parsePresence;case e.QueryLexer.FIELD:return e.QueryParser.parseField;case e.QueryLexer.TERM:return e.QueryParser.parseTerm;default:var n="expected either a field or a term, found "+r.type;throw r.str.length>=1&&(n+=" with value '"+r.str+"'"),new e.QueryParseError(n,r.start,r.end)}},e.QueryParser.parsePresence=function(t){var r=t.consumeLexeme();if(r!=null){switch(r.str){case"-":t.currentClause.presence=e.Query.presence.PROHIBITED;break;case"+":t.currentClause.presence=e.Query.presence.REQUIRED;break;default:var n="unrecognised presence operator'"+r.str+"'";throw new e.QueryParseError(n,r.start,r.end)}var i=t.peekLexeme();if(i==null){var n="expecting term or field, found nothing";throw new e.QueryParseError(n,r.start,r.end)}switch(i.type){case e.QueryLexer.FIELD:return e.QueryParser.parseField;case e.QueryLexer.TERM:return e.QueryParser.parseTerm;default:var n="expecting term or field, found '"+i.type+"'";throw new e.QueryParseError(n,i.start,i.end)}}},e.QueryParser.parseField=function(t){var r=t.consumeLexeme();if(r!=null){if(t.query.allFields.indexOf(r.str)==-1){var n=t.query.allFields.map(function(o){return"'"+o+"'"}).join(", "),i="unrecognised field '"+r.str+"', possible fields: "+n;throw new e.QueryParseError(i,r.start,r.end)}t.currentClause.fields=[r.str];var s=t.peekLexeme();if(s==null){var i="expecting term, found nothing";throw new e.QueryParseError(i,r.start,r.end)}switch(s.type){case e.QueryLexer.TERM:return e.QueryParser.parseTerm;default:var i="expecting term, found '"+s.type+"'";throw new e.QueryParseError(i,s.start,s.end)}}},e.QueryParser.parseTerm=function(t){var r=t.consumeLexeme();if(r!=null){t.currentClause.term=r.str.toLowerCase(),r.str.indexOf("*")!=-1&&(t.currentClause.usePipeline=!1);var n=t.peekLexeme();if(n==null){t.nextClause();return}switch(n.type){case e.QueryLexer.TERM:return t.nextClause(),e.QueryParser.parseTerm;case e.QueryLexer.FIELD:return t.nextClause(),e.QueryParser.parseField;case e.QueryLexer.EDIT_DISTANCE:return e.QueryParser.parseEditDistance;case e.QueryLexer.BOOST:return e.QueryParser.parseBoost;case e.QueryLexer.PRESENCE:return t.nextClause(),e.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+n.type+"'";throw new e.QueryParseError(i,n.start,n.end)}}},e.QueryParser.parseEditDistance=function(t){var r=t.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="edit distance must be numeric";throw new e.QueryParseError(i,r.start,r.end)}t.currentClause.editDistance=n;var s=t.peekLexeme();if(s==null){t.nextClause();return}switch(s.type){case e.QueryLexer.TERM:return t.nextClause(),e.QueryParser.parseTerm;case e.QueryLexer.FIELD:return t.nextClause(),e.QueryParser.parseField;case e.QueryLexer.EDIT_DISTANCE:return e.QueryParser.parseEditDistance;case e.QueryLexer.BOOST:return e.QueryParser.parseBoost;case e.QueryLexer.PRESENCE:return t.nextClause(),e.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new e.QueryParseError(i,s.start,s.end)}}},e.QueryParser.parseBoost=function(t){var r=t.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="boost must be numeric";throw new e.QueryParseError(i,r.start,r.end)}t.currentClause.boost=n;var s=t.peekLexeme();if(s==null){t.nextClause();return}switch(s.type){case e.QueryLexer.TERM:return t.nextClause(),e.QueryParser.parseTerm;case e.QueryLexer.FIELD:return t.nextClause(),e.QueryParser.parseField;case e.QueryLexer.EDIT_DISTANCE:return e.QueryParser.parseEditDistance;case e.QueryLexer.BOOST:return e.QueryParser.parseBoost;case e.QueryLexer.PRESENCE:return t.nextClause(),e.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new e.QueryParseError(i,s.start,s.end)}}},function(t,r){typeof define=="function"&&define.amd?define(r):typeof Rt=="object"?kt.exports=r():t.lunr=r()}(this,function(){return e})})()});var He=function(){},bn=function(e,t){He("toggleCodeblockVisibility",e,t),document.querySelectorAll(`.highlight code.language-${e}`).forEach(r=>{let n=r.closest(".highlight");n.style.display=t?"block":"none"})};function Pt(){return{tabs:[],changeLanguage:function(e){He("changeLanguage",e);for(let t=0;t{this.changeLanguage(0)})}}}var k=mn(It());var we=class{constructor(t={contentSelector:".content",markClass:"da-highlight-mark"}){this.opts=t,this.nodeStack=[]}apply(t){let r=document.createTreeWalker(this.content(),NodeFilter.SHOW_TEXT,{acceptNode:i=>i.parentNode.classList.contains(this.opts.markClass)?NodeFilter.FILTER_REJECT:/\S/.test(i.data)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT},!1),n=[];for(;r.nextNode();){let i=r.currentNode;i.data.match(t)&&n.push(i)}n.forEach(i=>{let s=i.parentNode.cloneNode(!0);s.childNodes.forEach(o=>{if(o.nodeType!==Node.TEXT_NODE)return;let a=o.data.match(t);if(!a)return;let u=o.data.indexOf(a[0],a.index);if(u===-1)return;let l=document.createElement("mark");l.classList.add(this.opts.markClass);let c=o.splitText(u);c.splitText(a[0].length);let d=c.cloneNode(!0);l.appendChild(d),s.replaceChild(l,c)}),i.parentNode&&i.parentNode.parentNode&&(this.nodeStack.push({old:i.parentNode,new:s}),i.parentNode.parentNode.replaceChild(s,i.parentNode))})}remove(){for(;this.nodeStack.length;){let t=this.nodeStack.pop();t.new.parentNode.replaceChild(t.old,t.new)}}content(){return document.querySelector(this.opts.contentSelector)}};function wn(e,t){var r=[];for(e=e.nextElementSibling;e&&!e.matches(t);)r.push(e),e=e.nextElementSibling;return r}function Qt(){var e,t=function(i){var s=new k.Builder;return s.pipeline.add(k.trimmer,k.stopWordFilter,k.stemmer),s.searchPipeline.add(k.stemmer),i.call(s,s),s.build()};function r(){e=t(function(){this.ref("id"),this.field("title",{boost:10}),this.field("body"),this.pipeline.add(k.trimmer,k.stopWordFilter),document.querySelectorAll("h1, h2").forEach(i=>{let s="";wn(i,"h1, h2").forEach(o=>{s=s.concat(" ",o.textContent)}),this.add({id:i.id,title:i.textContent,body:s})})})}let n=new we;return{query:"",results:[],init:function(){return this.$nextTick(()=>{r(),this.$watch("query",()=>{this.search()})})},search:function(){n.remove();let i=e.search(this.query).filter(s=>s.score>1e-4);this.results=i.map(s=>{var o=document.getElementById(s.ref);return{title:o.innerText,id:s.ref}}),this.results.length>0&&n.apply(new RegExp(this.query,"i"))}}}var Ft=function(){},En=()=>document.querySelectorAll(".content h1, .content h2, .content h3"),Sn=function(e,t){let r=document.querySelector(".content"),n=r.offsetHeight,i=r.offsetTop,s=Math.round((t.offsetTop-i)/n*100);e.activeHeading.title=t.innerText,e.activeHeading.progress=s};function Mt(){let e=function(t,r){if(!t.sub)return!1;let n=!1;return t.sub.forEach(i=>{i.open=r(i),i.active=i.open,i.open=i.open||e(i,r),i.open&&(n=!0)}),t.active_parent=n,n=n||r(t),t.open=n,t.active=r(t),n};return{activeHeading:{title:"",progress:0},showHeading:!0,rows:[],load:function(t){this.rows=t},transitions:function(){return{"x-transition:enter.duration.500ms":"","x-transition:leave.duration.400ms":"","x-transition.scale.origin.top.left.80":""}},rowClass:function(t){return{"x-bind:class"(){return`toc-h${t.level}${t.active?" active":""}${t.active_parent?" active-parent":""}`}}},click:function(t){this.rows.forEach(r=>{e(r,n=>t===n)})},onScroll:function(){Ft("onScroll");let t=window.scrollY;En().forEach(r=>{r.offsetTop{e(i,s=>s.id===r.id)}),Sn(this,r)),window.innerHeight+t>=document.body.offsetHeight&&(this.activeHeading.progress=100)})}}}var Ye=!1,Je=!1,q=[];function Tn(e){On(e)}function On(e){q.includes(e)||q.push(e),Cn()}function qt(e){let t=q.indexOf(e);t!==-1&&q.splice(t,1)}function Cn(){!Je&&!Ye&&(Ye=!0,queueMicrotask(An))}function An(){Ye=!1,Je=!0;for(let e=0;ee.effect(t,{scheduler:r=>{Xe?Tn(r):r()}}),Ht=e.raw}function Nt(e){de=e}function Rn(e){let t=()=>{};return[n=>{let i=de(n);return e._x_effects||(e._x_effects=new Set,e._x_runEffects=()=>{e._x_effects.forEach(s=>s())}),e._x_effects.add(i),t=()=>{i!==void 0&&(e._x_effects.delete(i),Le(i))},i},()=>{t()}]}var Wt=[],Kt=[],Ut=[];function kn(e){Ut.push(e)}function Gt(e,t){typeof t=="function"?(e._x_cleanups||(e._x_cleanups=[]),e._x_cleanups.push(t)):(t=e,Kt.push(t))}function In(e){Wt.push(e)}function Yt(e,t,r){e._x_attributeCleanups||(e._x_attributeCleanups={}),e._x_attributeCleanups[t]||(e._x_attributeCleanups[t]=[]),e._x_attributeCleanups[t].push(r)}function Jt(e,t){e._x_attributeCleanups&&Object.entries(e._x_attributeCleanups).forEach(([r,n])=>{(t===void 0||t.includes(r))&&(n.forEach(i=>i()),delete e._x_attributeCleanups[r])})}var dt=new MutationObserver(gt),ht=!1;function Xt(){dt.observe(document,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0}),ht=!0}function Zt(){Qn(),dt.disconnect(),ht=!1}var ue=[],We=!1;function Qn(){ue=ue.concat(dt.takeRecords()),ue.length&&!We&&(We=!0,queueMicrotask(()=>{Fn(),We=!1}))}function Fn(){gt(ue),ue.length=0}function A(e){if(!ht)return e();Zt();let t=e();return Xt(),t}var pt=!1,Oe=[];function Mn(){pt=!0}function Nn(){pt=!1,gt(Oe),Oe=[]}function gt(e){if(pt){Oe=Oe.concat(e);return}let t=[],r=[],n=new Map,i=new Map;for(let s=0;so.nodeType===1&&t.push(o)),e[s].removedNodes.forEach(o=>o.nodeType===1&&r.push(o))),e[s].type==="attributes")){let o=e[s].target,a=e[s].attributeName,u=e[s].oldValue,l=()=>{n.has(o)||n.set(o,[]),n.get(o).push({name:a,value:o.getAttribute(a)})},c=()=>{i.has(o)||i.set(o,[]),i.get(o).push(a)};o.hasAttribute(a)&&u===null?l():o.hasAttribute(a)?(c(),l()):c()}i.forEach((s,o)=>{Jt(o,s)}),n.forEach((s,o)=>{Wt.forEach(a=>a(o,s))});for(let s of r)if(!t.includes(s)&&(Kt.forEach(o=>o(s)),s._x_cleanups))for(;s._x_cleanups.length;)s._x_cleanups.pop()();t.forEach(s=>{s._x_ignoreSelf=!0,s._x_ignore=!0});for(let s of t)r.includes(s)||s.isConnected&&(delete s._x_ignoreSelf,delete s._x_ignore,Ut.forEach(o=>o(s)),s._x_ignore=!0,s._x_ignoreSelf=!0);t.forEach(s=>{delete s._x_ignoreSelf,delete s._x_ignore}),t=null,r=null,n=null,i=null}function er(e){return pe(J(e))}function he(e,t,r){return e._x_dataStack=[t,...J(r||e)],()=>{e._x_dataStack=e._x_dataStack.filter(n=>n!==t)}}function $t(e,t){let r=e._x_dataStack[0];Object.entries(t).forEach(([n,i])=>{r[n]=i})}function J(e){return e._x_dataStack?e._x_dataStack:typeof ShadowRoot=="function"&&e instanceof ShadowRoot?J(e.host):e.parentNode?J(e.parentNode):[]}function pe(e){let t=new Proxy({},{ownKeys:()=>Array.from(new Set(e.flatMap(r=>Object.keys(r)))),has:(r,n)=>e.some(i=>i.hasOwnProperty(n)),get:(r,n)=>(e.find(i=>{if(i.hasOwnProperty(n)){let s=Object.getOwnPropertyDescriptor(i,n);if(s.get&&s.get._x_alreadyBound||s.set&&s.set._x_alreadyBound)return!0;if((s.get||s.set)&&s.enumerable){let o=s.get,a=s.set,u=s;o=o&&o.bind(t),a=a&&a.bind(t),o&&(o._x_alreadyBound=!0),a&&(a._x_alreadyBound=!0),Object.defineProperty(i,n,{...u,get:o,set:a})}return!0}return!1})||{})[n],set:(r,n,i)=>{let s=e.find(o=>o.hasOwnProperty(n));return s?s[n]=i:e[e.length-1][n]=i,!0}});return t}function tr(e){let t=n=>typeof n=="object"&&!Array.isArray(n)&&n!==null,r=(n,i="")=>{Object.entries(Object.getOwnPropertyDescriptors(n)).forEach(([s,{value:o,enumerable:a}])=>{if(a===!1||o===void 0)return;let u=i===""?s:`${i}.${s}`;typeof o=="object"&&o!==null&&o._x_interceptor?n[s]=o.initialize(e,u,s):t(o)&&o!==n&&!(o instanceof Element)&&r(o,u)})};return r(e)}function rr(e,t=()=>{}){let r={initialValue:void 0,_x_interceptor:!0,initialize(n,i,s){return e(this.initialValue,()=>$n(n,i),o=>Ze(n,i,o),i,s)}};return t(r),n=>{if(typeof n=="object"&&n!==null&&n._x_interceptor){let i=r.initialize.bind(r);r.initialize=(s,o,a)=>{let u=n.initialize(s,o,a);return r.initialValue=u,i(s,o,a)}}else r.initialValue=n;return r}}function $n(e,t){return t.split(".").reduce((r,n)=>r[n],e)}function Ze(e,t,r){if(typeof t=="string"&&(t=t.split(".")),t.length===1)e[t[0]]=r;else{if(t.length===0)throw error;return e[t[0]]||(e[t[0]]={}),Ze(e[t[0]],t.slice(1),r)}}var nr={};function Q(e,t){nr[e]=t}function et(e,t){return Object.entries(nr).forEach(([r,n])=>{Object.defineProperty(e,`$${r}`,{get(){let[i,s]=lr(t);return i={interceptor:rr,...i},Gt(t,s),n(t,i)},enumerable:!1})}),{obj:e,cleanup:()=>{t=null}}}function jn(e,t,r,...n){try{return r(...n)}catch(i){fe(i,e,t)}}function fe(e,t,r=void 0){Object.assign(e,{el:t,expression:r}),console.warn(`Alpine Expression Error: ${e.message} + +${r?'Expression: "'+r+`" + +`:""}`,t),setTimeout(()=>{throw e},0)}var Te=!0;function Dn(e){let t=Te;Te=!1,e(),Te=t}function Y(e,t,r={}){let n;return L(e,t)(i=>n=i,r),n}function L(...e){return ir(...e)}var ir=sr;function Bn(e){ir=e}function sr(e,t){let r={},n=et(r,e).cleanup;Yt(e,"evaluator",n);let i=[r,...J(e)];if(typeof t=="function")return zn(i,t);let s=qn(i,t,e);return jn.bind(null,e,t,s)}function zn(e,t){return(r=()=>{},{scope:n={},params:i=[]}={})=>{let s=t.apply(pe([n,...e]),i);Ce(r,s)}}var Ke={};function Vn(e,t){if(Ke[e])return Ke[e];let r=Object.getPrototypeOf(async function(){}).constructor,n=/^[\n\s]*if.*\(.*\)/.test(e)||/^(let|const)\s/.test(e)?`(() => { ${e} })()`:e,s=(()=>{try{return new r(["__self","scope"],`with (scope) { __self.result = ${n} }; __self.finished = true; return __self.result;`)}catch(o){return fe(o,t,e),Promise.resolve()}})();return Ke[e]=s,s}function qn(e,t,r){let n=Vn(t,r);return(i=()=>{},{scope:s={},params:o=[]}={})=>{n.result=void 0,n.finished=!1;let a=pe([s,...e]);if(typeof n=="function"){let u=n(n,a).catch(l=>fe(l,r,t));n.finished?(Ce(i,n.result,a,o,r),n.result=void 0):u.then(l=>{Ce(i,l,a,o,r)}).catch(l=>fe(l,r,t)).finally(()=>n.result=void 0)}}}function Ce(e,t,r,n,i){if(Te&&typeof t=="function"){let s=t.apply(r,n);s instanceof Promise?s.then(o=>Ce(e,o,r,n)).catch(o=>fe(o,i,t)):e(s)}else e(t)}var _t="x-";function te(e=""){return _t+e}function Hn(e){_t=e}var or={};function C(e,t){or[e]=t}function vt(e,t,r){if(t=Array.from(t),e._x_virtualDirectives){let s=Object.entries(e._x_virtualDirectives).map(([a,u])=>({name:a,value:u})),o=ar(s);s=s.map(a=>o.find(u=>u.name===a.name)?{name:`x-bind:${a.name}`,value:`"${a.value}"`}:a),t=t.concat(s)}let n={};return t.map(dr((s,o)=>n[s]=o)).filter(pr).map(Un(n,r)).sort(Gn).map(s=>Kn(e,s))}function ar(e){return Array.from(e).map(dr()).filter(t=>!pr(t))}var tt=!1,ae=new Map,ur=Symbol();function Wn(e){tt=!0;let t=Symbol();ur=t,ae.set(t,[]);let r=()=>{for(;ae.get(t).length;)ae.get(t).shift()();ae.delete(t)},n=()=>{tt=!1,r()};e(r),n()}function lr(e){let t=[],r=a=>t.push(a),[n,i]=Rn(e);return t.push(i),[{Alpine:ge,effect:n,cleanup:r,evaluateLater:L.bind(L,e),evaluate:Y.bind(Y,e)},()=>t.forEach(a=>a())]}function Kn(e,t){let r=()=>{},n=or[t.type]||r,[i,s]=lr(e);Yt(e,t.original,s);let o=()=>{e._x_ignore||e._x_ignoreSelf||(n.inline&&n.inline(e,t,i),n=n.bind(n,e,t,i),tt?ae.get(ur).push(n):n())};return o.runCleanups=s,o}var cr=(e,t)=>({name:r,value:n})=>(r.startsWith(e)&&(r=r.replace(e,t)),{name:r,value:n}),fr=e=>e;function dr(e=()=>{}){return({name:t,value:r})=>{let{name:n,value:i}=hr.reduce((s,o)=>o(s),{name:t,value:r});return n!==t&&e(n,t),{name:n,value:i}}}var hr=[];function yt(e){hr.push(e)}function pr({name:e}){return gr().test(e)}var gr=()=>new RegExp(`^${_t}([^:^.]+)\\b`);function Un(e,t){return({name:r,value:n})=>{let i=r.match(gr()),s=r.match(/:([a-zA-Z0-9\-:]+)/),o=r.match(/\.[^.\]]+(?=[^\]]*$)/g)||[],a=t||e[r]||r;return{type:i?i[1]:null,value:s?s[1]:null,modifiers:o.map(u=>u.replace(".","")),expression:n,original:a}}}var rt="DEFAULT",Ee=["ignore","ref","data","id","bind","init","for","mask","model","modelable","transition","show","if",rt,"teleport"];function Gn(e,t){let r=Ee.indexOf(e.type)===-1?rt:e.type,n=Ee.indexOf(t.type)===-1?rt:t.type;return Ee.indexOf(r)-Ee.indexOf(n)}function le(e,t,r={}){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,composed:!0,cancelable:!0}))}var nt=[],xt=!1;function _r(e=()=>{}){return queueMicrotask(()=>{xt||setTimeout(()=>{it()})}),new Promise(t=>{nt.push(()=>{e(),t()})})}function it(){for(xt=!1;nt.length;)nt.shift()()}function Yn(){xt=!0}function K(e,t){if(typeof ShadowRoot=="function"&&e instanceof ShadowRoot){Array.from(e.children).forEach(i=>K(i,t));return}let r=!1;if(t(e,()=>r=!0),r)return;let n=e.firstElementChild;for(;n;)K(n,t,!1),n=n.nextElementSibling}function X(e,...t){console.warn(`Alpine Warning: ${e}`,...t)}function Jn(){document.body||X("Unable to initialize. Trying to load Alpine before `` is available. Did you forget to add `defer` in Alpine's ` + + + + + + + + NAV + + + +
+ + + + + + + + + + + +
    + + +
+ + + + + + +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Active Help

+

Active 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.

+

For example,

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding.
+
+bash-5.1$ bin/helm package [tab]
+Please specify the path to the chart to package
+
+bash-5.1$ bin/helm package [tab][tab]
+bin/    internal/    scripts/    pkg/     testdata/
+

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.

+ + + + + + + + +

Supported shells

+

Active Help is currently only supported for the following shells:

+
    +
  • Bash (using 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.
  • +
  • Zsh
  • +
+ + + + + + + + +

Adding Active Help messages

+

As 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.

+

Adding 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.

+ + + + + + + + +

Active Help for nouns

+

Adding 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:

+
cmd := &cobra.Command{
+	Use:   "add [NAME] [URL]",
+	Short: "add a chart repository",
+	Args:  require.ExactArgs(2),
+	RunE: func(cmd *cobra.Command, args []string) error {
+		return addRepo(args)
+	},
+	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		var comps []string
+		if len(args) == 0 {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		} else if len(args) == 1 {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		} else {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+		return comps, cobra.ShellCompDirectiveNoFileComp
+	},
+}
+

The 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:

+
bash-5.1$ helm repo add [tab]
+You must choose a name for the repo you are adding
+
+bash-5.1$ helm repo add grafana [tab]
+You must specify the URL for the repo you are adding
+
+bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
+This command does not take any more arguments
+

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.

+ + + + + + + + +

Active Help for flags

+

Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:

+
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+		if len(args) != 2 {
+			return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
+		}
+		return compVersionFlag(args[1], toComplete)
+	})
+

The example above prints an Active Help message when not enough information was given by the user to complete the --version flag.

+
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
+You must first specify the chart to install before the --version flag can be completed
+
+bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
+2.0.1  2.0.2  2.0.3
+
+ + + + + + + +

User control of Active Help

+

You 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. +Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.

+

The way to configure Active Help is to use the program’s Active Help environment +variable. That variable is named <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of your +program in uppercase with any - replaced by an _. The variable should be set by the user to whatever +Active Help configuration values are supported by the program.

+

For example, say helm has chosen to support three levels for Active Help: on, off, local. Then a user +would set the desired behavior to local by doing export HELM_ACTIVE_HELP=local in their shell.

+

For simplicity, when in cmd.ValidArgsFunction(...) or a flag’s completion function, the program should read the +Active Help configuration using the cobra.GetActiveHelpConfig(cmd) function and select what Active Help messages +should or should not be added (instead of reading the environment variable directly).

+

For example:

+
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+	activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
+
+	var comps []string
+	if len(args) == 0 {
+		if activeHelpLevel != "off"  {
+			comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
+		}
+	} else if len(args) == 1 {
+		if activeHelpLevel != "off" {
+			comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
+		}
+	} else {
+		if activeHelpLevel == "local" {
+			comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
+		}
+	}
+	return comps, cobra.ShellCompDirectiveNoFileComp
+},
+

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.

+

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.

+

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.

+ + + + + + + + +

Active Help with Cobra’s default completion command

+

Cobra provides a default completion command for programs that wish to use it. +When using the default completion command, Active Help is configurable in the same +fashion as described above using environment variables. You may wish to document this in more +details for your users.

+ + + + + + + + +

Debugging Active Help

+

Debugging 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 for details.

+

When 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:

+
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+_activeHelp_ WARNING: cannot re-use a name that is still in use
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
+bitnami/haproxy
+bitnami/harbor
+:0
+Completion ended with directive: ShellCompDirectiveDefault
+
+ + + + + + + + + +

Generating Bash Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Bash legacy dynamic completions

+

For 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.

+

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.

+

The 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.

+

Some code that works in kubernetes:

+
const (
+        bash_completion_func = `__kubectl_parse_get()
+{
+    local kubectl_output out
+    if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
+        out=($(echo "${kubectl_output}" | awk '{print $1}'))
+        COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
+    fi
+}
+
+__kubectl_get_resource()
+{
+    if [[ ${#nouns[@]} -eq 0 ]]; then
+        return 1
+    fi
+    __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
+    if [[ $? -eq 0 ]]; then
+        return 0
+    fi
+}
+
+__kubectl_custom_func() {
+    case ${last_command} in
+        kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
+            __kubectl_get_resource
+            return
+            ;;
+        *)
+            ;;
+    esac
+}
+`)
+

And then I set that in my command definition:

+
cmds := &cobra.Command{
+	Use:   "kubectl",
+	Short: "kubectl controls the Kubernetes cluster manager",
+	Long: `kubectl controls the Kubernetes cluster manager.
+
+Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
+	Run: runHelp,
+	BashCompletionFunction: bash_completion_func,
+}
+

The BashCompletionFunction option is really only valid/useful on the root command. Doing the above will cause __kubectl_custom_func() (__<command-use>_custom_func()) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like kubectl get pod [mypod]. If you type kubectl get pod [tab][tab] the __kubectl_customc_func() will run because the cobra.Command only understood “kubectl” and “get.” __kubectl_custom_func() will see that the cobra.Command is “kubectl_get” and will thus call another helper __kubectl_get_resource(). __kubectl_get_resource will look at the ’nouns’ collected. In our example the only noun will be pod. So it will call __kubectl_parse_get pod. __kubectl_parse_get will actually call out to kubernetes and get any pods. It will then set COMPREPLY to valid pods!

+

Similarly, for flags:

+
	annotation := make(map[string][]string)
+	annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
+
+	flag := &pflag.Flag{
+		Name:        "namespace",
+		Usage:       usage,
+		Annotations: annotation,
+	}
+	cmd.Flags().AddFlag(flag)
+

In addition add the __kubectl_get_namespaces implementation in the BashCompletionFunction +value, e.g.:

+
__kubectl_get_namespaces()
+{
+    local template
+    template="{{ range .items  }}{{ .metadata.name }} {{ end }}"
+    local kubectl_out
+    if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
+        COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
+    fi
+}
+
+ + + + + + + + + +

Generating Fish Completions For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating PowerShell Completions For Your Own cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + + + +

Generating Zsh Completion For Your cobra.Command

+

Please refer to Shell Completions for details.

+ + + + + + + + +

Zsh completions standardization

+

Cobra 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.

+ + + + + + + + +

Deprecation summary

+

See further below for more details on these deprecations.

+
    +
  • cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) is no longer needed. It is therefore deprecated and silently ignored.
  • +
  • cmd.MarkZshCompPositionalArgumentFile(pos, glob[]) is deprecated and silently ignored. +
      +
    • Instead use ValidArgsFunction with ShellCompDirectiveFilterFileExt.
    • +
    +
  • +
  • cmd.MarkZshCompPositionalArgumentWords() is deprecated and silently ignored. +
      +
    • Instead use ValidArgsFunction.
    • +
    +
  • +
+ + + + + + + + +

Behavioral changes

+

Noun completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
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
Completion of flag names without the - prefix having been typedFlag names are only completed if the user has typed the first -
cmd.MarkZshCompPositionalArgumentFile(pos, []string{}) used to turn on file completion on a per-argument position basisFile completion for all arguments by default; cmd.MarkZshCompPositionalArgumentFile() is deprecated and silently ignored
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)
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
+

Flag-value completion

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old behaviorNew behavior
No file completion by default (opposite of bash)File completion by default; use RegisterFlagCompletionFunc() with ShellCompDirectiveNoFileComp to turn off file completion
cmd.MarkFlagFilename(flag, []string{}) and similar used to turn on file completionFile completion by default; cmd.MarkFlagFilename(flag, []string{}) no longer needed in this context and silently ignored
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"})
cmd.MarkFlagDirname(flag) only completes directories (zsh-specific)Has been added for all shells
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
Completion of a flag name does not provide the = form (unlike bash)Retained for zsh and added to fish
+

Improvements

+
    +
  • Custom completion support (ValidArgsFunction and RegisterFlagCompletionFunc())
  • +
  • File completion by default if no other completions found
  • +
  • Handling of required flags
  • +
  • File extension filtering no longer mutually exclusive with bash usage
  • +
  • Completion of directory names within another directory
  • +
  • Support for = form of flags
  • +
+ + + + + + + + + + +

Generating Man Pages For Your Own cobra.Command

+

Generating man pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &doc.GenManHeader{
+		Title: "MINE",
+		Section: "3",
+	}
+	err := doc.GenManTree(cmd, header, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a man page /tmp/test.3

+ + + + + + + + + + +

Generating Markdown Docs For Your Own cobra.Command

+

Generating Markdown pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenMarkdownTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Markdown document /tmp/test.md

+ + + + + + + + +

Generate markdown docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenMarkdownTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate markdown docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenMarkdown(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the markdown doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + +

Customize the output

+

Both GenMarkdown and GenMarkdownTree have alternate versions with callbacks to get some control of the output:

+
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Generating ReStructured Text Docs For Your Own cobra.Command

+

Generating ReST pages from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenReSTTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a ReST document /tmp/test.rst

+ + + + + + + + +

Generate ReST docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"log"
+	"io/ioutil"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenReSTTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate ReST docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	err := doc.GenReST(cmd, out)
+	if err != nil {
+		log.Fatal(err)
+	}
+

This will write the ReST doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenReST and GenReSTTree have alternate versions with callbacks to get some control of the output:

+
func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
+	//...
+}
+
func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The 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:

+
// Sphinx cross-referencing format
+linkHandler := func(name, ref string) string {
+    return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
+}
+
+ + + + + + + + + +

Generating Yaml Docs For Your Own cobra.Command

+

Generating yaml files from a cobra command is incredibly easy. An example is as follows:

+
package main
+
+import (
+	"log"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	err := doc.GenYamlTree(cmd, "/tmp")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

That will get you a Yaml document /tmp/test.yaml

+ + + + + + + + +

Generate yaml docs for the entire command tree

+

This program can actually generate docs for the kubectl command in the kubernetes project

+
package main
+
+import (
+	"io/ioutil"
+	"log"
+	"os"
+
+	"k8s.io/kubernetes/pkg/kubectl/cmd"
+	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
+
+	"github.com/spf13/cobra/doc"
+)
+
+func main() {
+	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+	err := doc.GenYamlTree(kubectl, "./")
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+

This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case “./”)

+ + + + + + + + +

Generate yaml docs for a single command

+

You 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

+
	out := new(bytes.Buffer)
+	doc.GenYaml(cmd, out)
+

This will write the yaml doc for ONLY “cmd” into the out, buffer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Customize the output

+

Both GenYaml and GenYamlTree have alternate versions with callbacks to get some control of the output:

+
func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
+	//...
+}
+
func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
+	//...
+}
+

The 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:

+
const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+

The linkHandler can be used to customize the rendered internal links to the commands, given a filename:

+
linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+
+ + + + + + + + + +

Projects using Cobra

+ + + + + + + + + + + +

User Guide

+

While you are welcome to provide your own organization, typically a Cobra-based +application will follow the following organizational structure:

+
  ▾ appName/
+    ▾ cmd/
+        add.go
+        your.go
+        commands.go
+        here.go
+      main.go
+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Using the Cobra Generator

+

Cobra-CLI is its own program that will create your application and add any commands you want. +It’s the easiest way to incorporate Cobra into your application.

+

For complete details on using the Cobra generator, please refer to The Cobra-CLI Generator README

+ + + + + + + + +

Using the Cobra Library

+

To manually implement Cobra you need to create a bare main.go file and a rootCmd file. +You will optionally provide additional commands as you see fit.

+ + + + + + + + +

Create rootCmd

+

Cobra doesn’t require any special constructors. Simply create your commands.

+

Ideally you place this in app/cmd/root.go:

+
var rootCmd = &cobra.Command{
+  Use:   "hugo",
+  Short: "Hugo is a very fast static site generator",
+  Long: `A Fast and Flexible Static Site Generator built with
+                love by spf13 and friends in Go.
+                Complete documentation is available at https://gohugo.io/documentation/`,
+  Run: func(cmd *cobra.Command, args []string) {
+    // Do Stuff Here
+  },
+}
+
+func Execute() {
+  if err := rootCmd.Execute(); err != nil {
+    fmt.Fprintln(os.Stderr, err)
+    os.Exit(1)
+  }
+}
+

You will additionally define flags and handle configuration in your init() function.

+

For example cmd/root.go:

+
package cmd
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+var (
+	// Used for flags.
+	cfgFile     string
+	userLicense string
+
+	rootCmd = &cobra.Command{
+		Use:   "cobra-cli",
+		Short: "A generator for Cobra based Applications",
+		Long: `Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.`,
+	}
+)
+
+// Execute executes the root command.
+func Execute() error {
+	return rootCmd.Execute()
+}
+
+func init() {
+	cobra.OnInitialize(initConfig)
+
+	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+	rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
+	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
+	rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
+	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
+	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+	viper.SetDefault("license", "apache")
+
+	rootCmd.AddCommand(addCmd)
+	rootCmd.AddCommand(initCmd)
+}
+
+func initConfig() {
+	if cfgFile != "" {
+		// Use config file from the flag.
+		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := os.UserHomeDir()
+		cobra.CheckErr(err)
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigType("yaml")
+		viper.SetConfigName(".cobra")
+	}
+
+	viper.AutomaticEnv()
+
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}
+
+ + + + + + + +

Create your main.go

+

With the root command you need to have your main function execute it. +Execute should be run on the root for clarity, though it can be called on any command.

+

In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.

+
package main
+
+import (
+  "{pathToYourApp}/cmd"
+)
+
+func main() {
+  cmd.Execute()
+}
+
+ + + + + + + +

Create additional commands

+

Additional commands can be defined and typically are each given their own file +inside of the cmd/ directory.

+

If you wanted to create a version command you would create cmd/version.go and +populate it with the following:

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(versionCmd)
+}
+
+var versionCmd = &cobra.Command{
+  Use:   "version",
+  Short: "Print the version number of Hugo",
+  Long:  `All software has versions. This is Hugo's`,
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
+  },
+}
+
+ + + + + + + +

Organizing subcommands

+

A command may have subcommands which in turn may have other subcommands. This is achieved by using +AddCommand. In some cases, especially in larger applications, each subcommand may be defined in +its own go package.

+

The suggested approach is for the parent command to use AddCommand to add its most immediate +subcommands. For example, consider the following directory structure:

+
├── cmd
+│   ├── root.go
+│   └── sub1
+│       ├── sub1.go
+│       └── sub2
+│           ├── leafA.go
+│           ├── leafB.go
+│           └── sub2.go
+└── main.go
+

In this case:

+
    +
  • The init function of root.go adds the command defined in sub1.go to the root command.
  • +
  • The init function of sub1.go adds the command defined in sub2.go to the sub1 command.
  • +
  • The init function of sub2.go adds the commands defined in leafA.go and leafB.go to the +sub2 command.
  • +
+

This approach ensures the subcommands are always included at compile time while avoiding cyclic +references.

+ + + + + + + + +

Returning and handling errors

+

If you wish to return an error to the caller of a command, RunE can be used.

+
package cmd
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func init() {
+  rootCmd.AddCommand(tryCmd)
+}
+
+var tryCmd = &cobra.Command{
+  Use:   "try",
+  Short: "Try and possibly fail at something",
+  RunE: func(cmd *cobra.Command, args []string) error {
+    if err := someFunc(); err != nil {
+	return err
+    }
+    return nil
+  },
+}
+

The error can then be caught at the execute function call.

+ + + + + + + + +

Working with Flags

+

Flags provide modifiers to control how the action command operates.

+ + + + + + + + +

Assign flags to a command

+

Since the flags are defined and used in different locations, we need to +define a variable outside with the correct scope to assign the flag to +work with.

+
var Verbose bool
+var Source string
+

There are two different approaches to assign a flag.

+ + + + + + + + +

Persistent Flags

+

A flag can be ‘persistent’, meaning that this flag will be available to the +command it’s assigned to as well as every command under that command. For +global flags, assign a flag as a persistent flag on the root.

+
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
+
+ + + + + + + +

Local Flags

+

A flag can also be assigned locally, which will only apply to that specific command.

+
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
+
+ + + + + + + +

Local Flag on Parent Commands

+

By default, Cobra only parses local flags on the target command, and any local flags on +parent commands are ignored. By enabling Command.TraverseChildren, Cobra will +parse local flags on each command before executing the target command.

+
command := cobra.Command{
+  Use: "print [OPTIONS] [COMMANDS]",
+  TraverseChildren: true,
+}
+
+ + + + + + + +

Bind Flags with Config

+

You can also bind your flags with viper:

+
var author string
+
+func init() {
+  rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
+  viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+}
+

In this example, the persistent flag author is bound with viper. +Note: the variable author will not be set to the value from config, +when the --author flag is provided by user.

+

More in viper documentation.

+ + + + + + + + +

Required flags

+

Flags are optional by default. If instead you wish your command to report an error +when a flag has not been set, mark it as required:

+
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkFlagRequired("region")
+

Or, for persistent flags:

+
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
+rootCmd.MarkPersistentFlagRequired("region")
+
+ + + + + + + +

Flag Groups

+

If 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) then +Cobra can enforce that requirement:

+
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
+rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
+rootCmd.MarkFlagsRequiredTogether("username", "password")
+

You can also prevent different flags from being provided together if they represent mutually +exclusive options such as specifying an output format as either --json or --yaml but never both:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

If you want to require at least one flag from a group to be present, you can use MarkFlagsOneRequired. +This can be combined with MarkFlagsMutuallyExclusive to enforce exactly one flag from a given group:

+
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
+rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
+rootCmd.MarkFlagsOneRequired("json", "yaml")
+rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
+

In these cases:

+
    +
  • both local and persistent flags can be used +
      +
    • NOTE: the group is only enforced on commands where every flag is defined
    • +
    +
  • +
  • a flag may appear in multiple groups
  • +
  • a group may contain any number of flags
  • +
+ + + + + + + + +

Positional and Custom Arguments

+

Validation of positional arguments can be specified using the Args field of Command. +The following validators are built in:

+
    +
  • Number of arguments: +
      +
    • NoArgs - report an error if there are any positional args.
    • +
    • ArbitraryArgs - accept any number of args.
    • +
    • MinimumNArgs(int) - report an error if less than N positional args are provided.
    • +
    • MaximumNArgs(int) - report an error if more than N positional args are provided.
    • +
    • ExactArgs(int) - report an error if there are not exactly N positional args.
    • +
    • RangeArgs(min, max) - report an error if the number of args is not between min and max.
    • +
    +
  • +
  • Content of the arguments: +
      +
    • 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.
    • +
    +
  • +
+

If Args is undefined or nil, it defaults to ArbitraryArgs.

+

Moreover, MatchAll(pargs ...PositionalArgs) enables combining existing checks with arbitrary other checks. +For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional +args that are not in the ValidArgs field of Command, you can call MatchAll on ExactArgs and OnlyValidArgs, as +shown below:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+

It is possible to set any custom validator that satisfies func(cmd *cobra.Command, args []string) error. +For example:

+
var cmd = &cobra.Command{
+  Short: "hello",
+  Args: func(cmd *cobra.Command, args []string) error {
+    // Optionally run one of the validators provided by cobra
+    if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
+        return err
+    }
+    // Run the custom validation logic
+    if myapp.IsValidColor(args[0]) {
+      return nil
+    }
+    return fmt.Errorf("invalid color specified: %s", args[0])
+  },
+  Run: func(cmd *cobra.Command, args []string) {
+    fmt.Println("Hello, World!")
+  },
+}
+
+ + + + + + + +

Example

+

In the example below, we have defined three commands. Two are at the top level +and one (cmdTimes) is a child of one of the top commands. In this case the root +is not executable, meaning that a subcommand is required. This is accomplished +by not providing a ‘Run’ for the ‘rootCmd’.

+

We have only defined one flag for a single command.

+

More documentation about flags is available at https://github.com/spf13/pflag

+
package main
+
+import (
+  "fmt"
+  "strings"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+  var echoTimes int
+
+  var cmdPrint = &cobra.Command{
+    Use:   "print [string to print]",
+    Short: "Print anything to the screen",
+    Long: `print is for printing anything back to the screen.
+For many years people have printed back to the screen.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Print: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdEcho = &cobra.Command{
+    Use:   "echo [string to echo]",
+    Short: "Echo anything to the screen",
+    Long: `echo is for echoing anything back.
+Echo works a lot like print, except it has a child command.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Println("Echo: " + strings.Join(args, " "))
+    },
+  }
+
+  var cmdTimes = &cobra.Command{
+    Use:   "times [string to echo]",
+    Short: "Echo anything to the screen more times",
+    Long: `echo things multiple times back to the user by providing
+a count and a string.`,
+    Args: cobra.MinimumNArgs(1),
+    Run: func(cmd *cobra.Command, args []string) {
+      for i := 0; i < echoTimes; i++ {
+        fmt.Println("Echo: " + strings.Join(args, " "))
+      }
+    },
+  }
+
+  cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
+
+  var rootCmd = &cobra.Command{Use: "app"}
+  rootCmd.AddCommand(cmdPrint, cmdEcho)
+  cmdEcho.AddCommand(cmdTimes)
+  rootCmd.Execute()
+}
+

For a more complete example of a larger application, please checkout Hugo.

+ + + + + + + + +

Help Command

+

Cobra automatically adds a help command to your application when you have subcommands. +This will be called when a user runs ‘app help’. Additionally, help will also +support all other commands as input. Say, for instance, you have a command called +‘create’ without any additional configuration; Cobra will work when ‘app help +create’ is called. Every command will automatically have the ‘–help’ flag added.

+ + + + + + + + +

Example

+

The following output is automatically generated by Cobra. Nothing beyond the +command and flag definitions are needed.

+
$ cobra-cli help
+
+Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.
+
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra-cli [command] --help" for more information about a command.
+
+

Help is just a command like any other. There is no special logic or behavior +around it. In fact, you can provide your own if you want.

+ + + + + + + + +

Grouping commands in help

+

Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly +defined using AddGroup() on the parent command. Then a subcommand can be added to a group using the GroupID element +of that subcommand. The groups will appear in the help output in the same order as they are defined using different +calls to AddGroup(). If you use the generated help or completion commands, you can set their group ids using +SetHelpCommandGroupId() and SetCompletionCommandGroupId() on the root command, respectively.

+ + + + + + + + +

Defining your own help

+

You can provide your own Help command or your own template for the default command to use +with the following functions:

+
cmd.SetHelpCommand(cmd *Command)
+cmd.SetHelpFunc(f func(*Command, []string))
+cmd.SetHelpTemplate(s string)
+

The latter two will also apply to any children commands.

+ + + + + + + + +

Usage Message

+

When the user provides an invalid flag or invalid command, Cobra responds by +showing the user the ‘usage’.

+ + + + + + + + +

Example

+

You may recognize this from the help above. That’s because the default help +embeds the usage as part of its output.

+
$ cobra-cli --invalid
+Error: unknown flag: --invalid
+Usage:
+  cobra-cli [command]
+
+Available Commands:
+  add         Add a command to a Cobra Application
+  completion  Generate the autocompletion script for the specified shell
+  help        Help about any command
+  init        Initialize a Cobra Application
+
+Flags:
+  -a, --author string    author name for copyright attribution (default "YOUR NAME")
+      --config string    config file (default is $HOME/.cobra.yaml)
+  -h, --help             help for cobra-cli
+  -l, --license string   name of license for the project
+      --viper            use Viper for configuration
+
+Use "cobra [command] --help" for more information about a command.
+
+ + + + + + + + +

Defining your own usage

+

You can provide your own usage function or template for Cobra to use. +Like help, the function and template are overridable through public methods:

+
cmd.SetUsageFunc(f func(*Command) error)
+cmd.SetUsageTemplate(s string)
+
+ + + + + + + +

Version Flag

+

Cobra adds a top-level ‘–version’ flag if the Version field is set on the root command. +Running an application with the ‘–version’ flag will print the version to stdout using +the version template. The template can be customized using the +cmd.SetVersionTemplate(s string) function.

+ + + + + + + + +

PreRun and PostRun Hooks

+

It 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:

+
    +
  • PersistentPreRun
  • +
  • PreRun
  • +
  • Run
  • +
  • PostRun
  • +
  • PersistentPostRun
  • +
+

An 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:

+
package main
+
+import (
+  "fmt"
+
+  "github.com/spf13/cobra"
+)
+
+func main() {
+
+  var rootCmd = &cobra.Command{
+    Use:   "root [sub]",
+    Short: "My root command",
+    PersistentPreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
+    },
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  var subCmd = &cobra.Command{
+    Use:   "sub [no options!]",
+    Short: "My subcommand",
+    PreRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
+    },
+    Run: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd Run with args: %v\n", args)
+    },
+    PostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
+    },
+    PersistentPostRun: func(cmd *cobra.Command, args []string) {
+      fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
+    },
+  }
+
+  rootCmd.AddCommand(subCmd)
+
+  rootCmd.SetArgs([]string{""})
+  rootCmd.Execute()
+  fmt.Println()
+  rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
+  rootCmd.Execute()
+}
+

Output:

+
Inside rootCmd PersistentPreRun with args: []
+Inside rootCmd PreRun with args: []
+Inside rootCmd Run with args: []
+Inside rootCmd PostRun with args: []
+Inside rootCmd PersistentPostRun with args: []
+
+Inside rootCmd PersistentPreRun with args: [arg1 arg2]
+Inside subCmd PreRun with args: [arg1 arg2]
+Inside subCmd Run with args: [arg1 arg2]
+Inside subCmd PostRun with args: [arg1 arg2]
+Inside subCmd PersistentPostRun with args: [arg1 arg2]
+
+ + + + + + + +

Suggestions when “unknown command” happens

+

Cobra 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:

+
$ hugo srever
+Error: unknown command "srever" for "hugo"
+
+Did you mean this?
+        server
+
+Run 'hugo --help' for usage.
+

Suggestions are automatically generated based on existing subcommands and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.

+

If you need to disable suggestions or tweak the string distance in your command, use:

+
command.DisableSuggestions = true
+

or

+
command.SuggestionsMinimumDistance = 1
+

You 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 which +you don’t want aliases. Example:

+
$ kubectl remove
+Error: unknown command "remove" for "kubectl"
+
+Did you mean this?
+        delete
+
+Run 'kubectl help' for usage.
+
+ + + + + + + +

Generating documentation for your command

+

Cobra can generate documentation based on subcommands, flags, etc. +Read more about it in the docs generation documentation.

+ + + + + + + + +

Generating shell completions

+

Cobra 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.

+ + + + + + + + +

Providing Active Help

+

Cobra 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.

+ + + +
+
+ +
+
+ + + diff --git a/tags/index.xml b/tags/index.xml new file mode 100644 index 000000000..990cb71f9 --- /dev/null +++ b/tags/index.xml @@ -0,0 +1,10 @@ + + + + Tags on Cobra documentation + https://spf13.github.io/cobra/tags/ + Recent content in Tags on Cobra documentation + Hugo -- gohugo.io + en + +