user_guide.md
This file
Path
site/content/user_guide.md
887 lines · 26.6 KiB · Markdown
Last changed by
Add cobra unique args validator (#2397)takanuva15before adoptionad460ea
History of this fileTake it
Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 1–5why, one step back1# User Guide23While you are welcome to provide your own organization, typically a Cobra-based4application will follow the following organizational structure:5Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 6–13why, one step back6```console7▾ appName/8 ▾ cmd/9 add.go10 your.go11 commands.go12 here.go13 main.goMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 14–20why, one step back14```1516In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.1718```go19package main20Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
line 21why, one step back21import "{pathToYourApp}/cmd"Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 22–148why, one step back2223func main() {24 cmd.Execute()25}26```2728## Using the Cobra Generator2930Cobra-CLI is its own program that will create your application and add any commands you want.31It's the easiest way to incorporate Cobra into your application.3233For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)3435## Using the Cobra Library3637To manually implement Cobra you need to create a bare main.go file and a rootCmd file.38You will optionally provide additional commands as you see fit.3940### Create rootCmd4142Cobra doesn't require any special constructors. Simply create your commands.4344Ideally you place this in app/cmd/root.go:4546```go47var rootCmd = &cobra.Command{48 Use: "hugo",49 Short: "Hugo is a very fast static site generator",50 Long: `A Fast and Flexible Static Site Generator built with51 love by spf13 and friends in Go.52 Complete documentation is available at https://gohugo.io/documentation/`,53 Run: func(cmd *cobra.Command, args []string) {54 // Do Stuff Here55 },56}5758func Execute() {59 if err := rootCmd.Execute(); err != nil {60 fmt.Fprintln(os.Stderr, err)61 os.Exit(1)62 }63}64```6566You will additionally define flags and handle configuration in your init() function.6768For example cmd/root.go:6970```go71package cmd7273import (74 "fmt"75 "os"7677 "github.com/spf13/cobra"78 "github.com/spf13/viper"79)8081var (82 // Used for flags.83 cfgFile string84 userLicense string8586 rootCmd = &cobra.Command{87 Use: "cobra-cli",88 Short: "A generator for Cobra based Applications",89 Long: `Cobra is a CLI library for Go that empowers applications.90This application is a tool to generate the needed files91to quickly create a Cobra application.`,92 }93)9495// Execute executes the root command.96func Execute() error {97 return rootCmd.Execute()98}99100func init() {101 cobra.OnInitialize(initConfig)102103 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")104 rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")105 rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")106 rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")107 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))108 viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))109 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")110 viper.SetDefault("license", "apache")111112 rootCmd.AddCommand(addCmd)113 rootCmd.AddCommand(initCmd)114}115116func initConfig() {117 if cfgFile != "" {118 // Use config file from the flag.119 viper.SetConfigFile(cfgFile)120 } else {121 // Find home directory.122 home, err := os.UserHomeDir()123 cobra.CheckErr(err)124125 // Search config in home directory with name ".cobra" (without extension).126 viper.AddConfigPath(home)127 viper.SetConfigType("yaml")128 viper.SetConfigName(".cobra")129 }130131 viper.AutomaticEnv()132133 if err := viper.ReadInConfig(); err == nil {134 fmt.Println("Using config file:", viper.ConfigFileUsed())135 }136}137```138139### Create your main.go140141With the root command you need to have your main function execute it.142Execute should be run on the root for clarity, though it can be called on any command.143144In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.145146```go147package main148Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
line 149why, one step back149import "{pathToYourApp}/cmd"Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 150–195why, one step back150151func main() {152 cmd.Execute()153}154```155156### Create additional commands157158Additional commands can be defined and typically are each given their own file159inside of the cmd/ directory.160161If you wanted to create a version command you would create cmd/version.go and162populate it with the following:163164```go165package cmd166167import (168 "fmt"169170 "github.com/spf13/cobra"171)172173func init() {174 rootCmd.AddCommand(versionCmd)175}176177var versionCmd = &cobra.Command{178 Use: "version",179 Short: "Print the version number of Hugo",180 Long: `All software has versions. This is Hugo's`,181 Run: func(cmd *cobra.Command, args []string) {182 fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")183 },184}185```186187### Organizing subcommands188189A command may have subcommands which in turn may have other subcommands. This is achieved by using190`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in191its own go package.192193The suggested approach is for the parent command to use `AddCommand` to add its most immediate194subcommands. For example, consider the following directory structure:195Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
line 196why, one step back196```consoleMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 197–299why, one step back197├── cmd198│ ├── root.go199│ └── sub1200│ ├── sub1.go201│ └── sub2202│ ├── leafA.go203│ ├── leafB.go204│ └── sub2.go205└── main.go206```207208In this case:209210* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.211* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.212* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the213 sub2 command.214215This approach ensures the subcommands are always included at compile time while avoiding cyclic216references.217218### Returning and handling errors219220If you wish to return an error to the caller of a command, `RunE` can be used.221222```go223package cmd224225import (226 "fmt"227228 "github.com/spf13/cobra"229)230231func init() {232 rootCmd.AddCommand(tryCmd)233}234235var tryCmd = &cobra.Command{236 Use: "try",237 Short: "Try and possibly fail at something",238 RunE: func(cmd *cobra.Command, args []string) error {239 if err := someFunc(); err != nil {240 return err241 }242 return nil243 },244}245```246247The error can then be caught at the execute function call.248249## Working with Flags250251Flags provide modifiers to control how the action command operates.252253### Assign flags to a command254255Since the flags are defined and used in different locations, we need to256define a variable outside with the correct scope to assign the flag to257work with.258259```go260var Verbose bool261var Source string262```263264There are two different approaches to assign a flag.265266### Persistent Flags267268A flag can be 'persistent', meaning that this flag will be available to the269command it's assigned to as well as every command under that command. For270global flags, assign a flag as a persistent flag on the root.271272```go273rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")274```275276### Local Flags277278A flag can also be assigned locally, which will only apply to that specific command.279280```go281localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")282```283284### Local Flag on Parent Commands285286By default, Cobra only parses local flags on the target command, and any local flags on287parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will288parse local flags on each command before executing the target command.289290```go291command := cobra.Command{292 Use: "print [OPTIONS] [COMMANDS]",293 TraverseChildren: true,294}295```296297### Bind Flags with Config298299You can also bind your flags with [viper](https://github.com/spf13/viper):docs: update user guide (#2128)Xinwei Xiongbefore adoption0fc86c2
line 300why, one step back300Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 301–319why, one step back301```go302var author string303304func init() {305 rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")306 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))307}308```309310In this example, the persistent flag `author` is bound with `viper`.311**Note**: the variable `author` will not be set to the value from config,312when the `--author` flag is provided by user.313314More in [viper documentation](https://github.com/spf13/viper#working-with-flags).315316### Required flags317318Flags are optional by default. If instead you wish your command to report an error319when a flag has not been set, mark it as required:docs: update user guide (#2128)Xinwei Xiongbefore adoption0fc86c2
line 320why, one step back320Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 321–326why, one step back321```go322rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")323rootCmd.MarkFlagRequired("region")324```325326Or, for persistent flags:docs: update user guide (#2128)Xinwei Xiongbefore adoption0fc86c2
line 327why, one step back327Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 328–336why, one step back328```go329rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")330rootCmd.MarkPersistentFlagRequired("region")331```332333### Flag Groups334335If 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) then336Cobra can enforce that requirement:docs: update user guide (#2128)Xinwei Xiongbefore adoption0fc86c2
line 337why, one step back337Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 338–345why, one step back338```go339rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")340rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")341rootCmd.MarkFlagsRequiredTogether("username", "password")342```343344You can also prevent different flags from being provided together if they represent mutually345exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:docs: update user guide (#2128)Xinwei Xiongbefore adoption0fc86c2
line 346why, one step back346Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 347–352why, one step back347```go348rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")349rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")350rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")351```352Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a
lines 353–354why, one step back353If you want to require at least one flag from a group to be present, you can use `MarkFlagsOneRequired`.354This can be combined with `MarkFlagsMutuallyExclusive` to enforce exactly one flag from a given group:docs: update user guide (#2128)Xinwei Xiongbefore adoption0fc86c2
line 355why, one step back355Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a
lines 356–363why, one step back356```go357rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")358rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")359rootCmd.MarkFlagsOneRequired("json", "yaml")360rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")361```362363In these cases:Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 364–368why, one step back364 - both local and persistent flags can be used365 - **NOTE:** the group is only enforced on commands where every flag is defined366 - a flag may appear in multiple groups367 - a group may contain any number of flags368Add documentation for repeated flags functionality (#2316)Ron Vergisbefore adoptione2dd29d
lines 369–435why, one step back369### Repeated Flags370371Cobra supports two types of repeated flags, useful for implementing SSH-like verbose flags (`-v`, `-vv`, `-vvv`) or collecting multiple values.372373#### Count Flags374375For implementing verbose-style flags where repeated usage increases a counter (like SSH's `-v`, `-vv`, `-vvv`):376377```go378var verbose int379380func init() {381 // CountVarP allows the flag to be repeated to increment the counter382 rootCmd.PersistentFlags().CountVarP(&verbose, "verbose", "v", "verbose output (can be repeated: -v, -vv, -vvv)")383}384```385386Usage examples:387- `myapp -v` → verbose = 1 (info level)388- `myapp -vv` or `myapp -v -v` → verbose = 2 (debug level)389- `myapp -vvv` or `myapp -v -v -v` → verbose = 3 (trace level)390391Then in your command logic:392```go393Run: func(cmd *cobra.Command, args []string) {394 switch verbose {395 case 0:396 // Default: no verbose output397 case 1:398 // Info level logging399 log.SetLevel(log.InfoLevel)400 case 2:401 // Debug level logging402 log.SetLevel(log.DebugLevel)403 case 3:404 // Trace level logging405 log.SetLevel(log.TraceLevel)406 default:407 // Maximum verbosity408 log.SetLevel(log.TraceLevel)409 }410},411```412413#### Array/Slice Flags414415For collecting multiple values of the same flag:416417```go418var inputFiles []string419420func init() {421 // StringArrayVarP allows multiple values: --input file1.txt --input file2.txt422 rootCmd.Flags().StringArrayVarP(&inputFiles, "input", "i", []string{}, "input files (can be repeated)")423424 // Alternative: StringSliceVarP for comma-separated values425 // rootCmd.Flags().StringSliceVarP(&inputFiles, "input", "i", []string{}, "input files (comma-separated or repeated)")426}427```428429Usage examples:430- `myapp --input file1.txt --input file2.txt`431- `myapp -i file1.txt -i file2.txt`432- With StringSlice: `myapp --input file1.txt,file2.txt,file3.txt`433434**Note**: Both `CountVar` and array flags leverage the underlying [pflag](https://github.com/spf13/pflag) library's support for repeated flags.435Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 436–449why, one step back436## Positional and Custom Arguments437438Validation of positional arguments can be specified using the `Args` field of `Command`.439The following validators are built in:440441- Number of arguments:442 - `NoArgs` - report an error if there are any positional args.443 - `ArbitraryArgs` - accept any number of args.444 - `MinimumNArgs(int)` - report an error if less than N positional args are provided.445 - `MaximumNArgs(int)` - report an error if more than N positional args are provided.446 - `ExactArgs(int)` - report an error if there are not exactly N positional args.447 - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.448- Content of the arguments:449 - `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.Add cobra unique args validator (#2397)takanuva15before adoptionad460ea
line 450why, one step back450 - `NoDuplicateArgs` - report an error if any positional argument value is provided more than once.Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 451–500why, one step back451452If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.453454Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.455For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional456args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as457shown below:458459```go460var cmd = &cobra.Command{461 Short: "hello",462 Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),463 Run: func(cmd *cobra.Command, args []string) {464 fmt.Println("Hello, World!")465 },466}467```468469It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.470For example:471472```go473var cmd = &cobra.Command{474 Short: "hello",475 Args: func(cmd *cobra.Command, args []string) error {476 // Optionally run one of the validators provided by cobra477 if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {478 return err479 }480 // Run the custom validation logic481 if myapp.IsValidColor(args[0]) {482 return nil483 }484 return fmt.Errorf("invalid color specified: %s", args[0])485 },486 Run: func(cmd *cobra.Command, args []string) {487 fmt.Println("Hello, World!")488 },489}490```491492## Example493494In the example below, we have defined three commands. Two are at the top level495and one (cmdTimes) is a child of one of the top commands. In this case the root496is not executable, meaning that a subcommand is required. This is accomplished497by not providing a 'Run' for the 'rootCmd'.498499We have only defined one flag for a single command.500docs: update user guide (#2128)Xinwei Xiongbefore adoption0fc86c2
line 501why, one step back501More documentation about flags is available at https://github.com/spf13/pflag.Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 502–574why, one step back502503```go504package main505506import (507 "fmt"508 "strings"509510 "github.com/spf13/cobra"511)512513func main() {514 var echoTimes int515516 var cmdPrint = &cobra.Command{517 Use: "print [string to print]",518 Short: "Print anything to the screen",519 Long: `print is for printing anything back to the screen.520For many years people have printed back to the screen.`,521 Args: cobra.MinimumNArgs(1),522 Run: func(cmd *cobra.Command, args []string) {523 fmt.Println("Print: " + strings.Join(args, " "))524 },525 }526527 var cmdEcho = &cobra.Command{528 Use: "echo [string to echo]",529 Short: "Echo anything to the screen",530 Long: `echo is for echoing anything back.531Echo works a lot like print, except it has a child command.`,532 Args: cobra.MinimumNArgs(1),533 Run: func(cmd *cobra.Command, args []string) {534 fmt.Println("Echo: " + strings.Join(args, " "))535 },536 }537538 var cmdTimes = &cobra.Command{539 Use: "times [string to echo]",540 Short: "Echo anything to the screen more times",541 Long: `echo things multiple times back to the user by providing542a count and a string.`,543 Args: cobra.MinimumNArgs(1),544 Run: func(cmd *cobra.Command, args []string) {545 for i := 0; i < echoTimes; i++ {546 fmt.Println("Echo: " + strings.Join(args, " "))547 }548 },549 }550551 cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")552553 var rootCmd = &cobra.Command{Use: "app"}554 rootCmd.AddCommand(cmdPrint, cmdEcho)555 cmdEcho.AddCommand(cmdTimes)556 rootCmd.Execute()557}558```559560For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).561562## Help Command563564Cobra automatically adds a help command to your application when you have subcommands.565This will be called when a user runs 'app help'. Additionally, help will also566support all other commands as input. Say, for instance, you have a command called567'create' without any additional configuration; Cobra will work when 'app help568create' is called. Every command will automatically have the '--help' flag added.569570### Example571572The following output is automatically generated by Cobra. Nothing beyond the573command and flag definitions are needed.574Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 575–576why, one step back575```console576$ cobra-cli helpMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 577why, one step back577Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 578–580why, one step back578Cobra is a CLI library for Go that empowers applications.579This application is a tool to generate the needed files580to quickly create a Cobra application.Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 581why, one step back581Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 582–583why, one step back582Usage:583 cobra-cli [command]Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 584why, one step back584Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 585–589why, one step back585Available Commands:586 add Add a command to a Cobra Application587 completion Generate the autocompletion script for the specified shell588 help Help about any command589 init Initialize a Cobra ApplicationMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 590why, one step back590Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 591–596why, one step back591Flags:592 -a, --author string author name for copyright attribution (default "YOUR NAME")593 --config string config file (default is $HOME/.cobra.yaml)594 -h, --help help for cobra-cli595 -l, --license string name of license for the project596 --viper use Viper for configurationMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 597why, one step back597Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 598–599why, one step back598Use "cobra-cli [command] --help" for more information about a command.599```Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 600–624why, one step back600601Help is just a command like any other. There is no special logic or behavior602around it. In fact, you can provide your own if you want.603604### Grouping commands in help605606Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly607defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element608of that subcommand. The groups will appear in the help output in the same order as they are defined using different609calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using610`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.611612### Defining your own help613614You can provide your own Help command or your own template for the default command to use615with the following functions:616617```go618cmd.SetHelpCommand(cmd *Command)619cmd.SetHelpFunc(f func(*Command, []string))620cmd.SetHelpTemplate(s string)621```622623The latter two will also apply to any children commands.624Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 625–627why, one step back625Note that templates specified with `SetHelpTemplate` are evaluated using626`text/template` which can increase the size of the compiled executable.627Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 628–636why, one step back628## Usage Message629630When the user provides an invalid flag or invalid command, Cobra responds by631showing the user the 'usage'.632633### Example634You may recognize this from the help above. That's because the default help635embeds the usage as part of its output.636Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 637–641why, one step back637```console638$ cobra-cli --invalid639Error: unknown flag: --invalid640Usage:641 cobra-cli [command]Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 642why, one step back642Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 643–647why, one step back643Available Commands:644 add Add a command to a Cobra Application645 completion Generate the autocompletion script for the specified shell646 help Help about any command647 init Initialize a Cobra ApplicationMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 648why, one step back648Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 649–654why, one step back649Flags:650 -a, --author string author name for copyright attribution (default "YOUR NAME")651 --config string config file (default is $HOME/.cobra.yaml)652 -h, --help help for cobra-cli653 -l, --license string name of license for the project654 --viper use Viper for configurationMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 655why, one step back655Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
lines 656–657why, one step back656Use "cobra [command] --help" for more information about a command.657```Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 658–659why, one step back658659### Defining your own usageAllow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 660why, one step back660Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 661–668why, one step back661You can provide your own usage function or template for Cobra to use.662Like help, the function and template are overridable through public methods:663664```go665cmd.SetUsageFunc(f func(*Command) error)666cmd.SetUsageTemplate(s string)667```668Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 669–671why, one step back669Note that templates specified with `SetUsageTemplate` are evaluated using670`text/template` which can increase the size of the compiled executable.671Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 672–677why, one step back672## Version Flag673674Cobra adds a top-level '--version' flag if the Version field is set on the root command.675Running an application with the '--version' flag will print the version to stdout using676the version template. The template can be customized using the677`cmd.SetVersionTemplate(s string)` function.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 678–680why, one step back678679Note that templates specified with `SetVersionTemplate` are evaluated using680`text/template` which can increase the size of the compiled executable.Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
line 681why, one step back681Customizable error message prefix (#2023)Soumabefore adoption0c72800
lines 682–687why, one step back682## Error Message Prefix683684Cobra prints an error message when receiving a non-nil error value.685The default error message is `Error: <error contents>`.686The Prefix, `Error:` can be customized using the `cmd.SetErrPrefix(s string)` function.687Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 688–689why, one step back688## PreRun and PostRun Hooks689Add notes to doc on preRun and postRun condition (#2041)Haoming Mengbefore adoption95d8a1e
line 690why, one step back690It 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. The `*PreRun` and `*PostRun` functions will only be executed if the `Run` function of the current command has been declared. These functions are run in the following order:Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 691–772why, one step back691692- `PersistentPreRun`693- `PreRun`694- `Run`695- `PostRun`696- `PersistentPostRun`697698An 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`:699700```go701package main702703import (704 "fmt"705706 "github.com/spf13/cobra"707)708709func main() {710711 var rootCmd = &cobra.Command{712 Use: "root [sub]",713 Short: "My root command",714 PersistentPreRun: func(cmd *cobra.Command, args []string) {715 fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)716 },717 PreRun: func(cmd *cobra.Command, args []string) {718 fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)719 },720 Run: func(cmd *cobra.Command, args []string) {721 fmt.Printf("Inside rootCmd Run with args: %v\n", args)722 },723 PostRun: func(cmd *cobra.Command, args []string) {724 fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)725 },726 PersistentPostRun: func(cmd *cobra.Command, args []string) {727 fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)728 },729 }730731 var subCmd = &cobra.Command{732 Use: "sub [no options!]",733 Short: "My subcommand",734 PreRun: func(cmd *cobra.Command, args []string) {735 fmt.Printf("Inside subCmd PreRun with args: %v\n", args)736 },737 Run: func(cmd *cobra.Command, args []string) {738 fmt.Printf("Inside subCmd Run with args: %v\n", args)739 },740 PostRun: func(cmd *cobra.Command, args []string) {741 fmt.Printf("Inside subCmd PostRun with args: %v\n", args)742 },743 PersistentPostRun: func(cmd *cobra.Command, args []string) {744 fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)745 },746 }747748 rootCmd.AddCommand(subCmd)749750 rootCmd.SetArgs([]string{""})751 rootCmd.Execute()752 fmt.Println()753 rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})754 rootCmd.Execute()755}756```757758Output:759```760Inside rootCmd PersistentPreRun with args: []761Inside rootCmd PreRun with args: []762Inside rootCmd Run with args: []763Inside rootCmd PostRun with args: []764Inside rootCmd PersistentPostRun with args: []765766Inside rootCmd PersistentPreRun with args: [arg1 arg2]767Inside subCmd PreRun with args: [arg1 arg2]768Inside subCmd Run with args: [arg1 arg2]769Inside subCmd PostRun with args: [arg1 arg2]770Inside subCmd PersistentPostRun with args: [arg1 arg2]771```772Allow running persistent run hooks of all parents (#2044)vkhorozbefore adoption4cafa37
lines 773–776why, one step back773By default, only the first persistent hook found in the command chain is executed.774That is why in the above output, the `rootCmd PersistentPostRun` was not called for a child command.775Set `EnableTraverseRunHooks` global variable to `true` if you want to execute all parents' persistent hooks.776Move documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 777–780why, one step back777## Suggestions when "unknown command" happens778779Cobra 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:780Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
line 781why, one step back781```consoleMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 782–807why, one step back782$ hugo srever783Error: unknown command "srever" for "hugo"784785Did you mean this?786 server787788Run 'hugo --help' for usage.789```790791Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.792793If you need to disable suggestions or tweak the string distance in your command, use:794795```go796command.DisableSuggestions = true797```798799or800801```go802command.SuggestionsMinimumDistance = 1803```804805You 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 which806you don't want aliases. Example:807Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
line 808why, one step back808```consoleMove documentation sources to site/content (#1428)Unai Martinez-Corralbefore adoptiondcb405a
lines 809–833why, one step back809$ kubectl remove810Error: unknown command "remove" for "kubectl"811812Did you mean this?813 delete814815Run 'kubectl help' for usage.816```817818## Generating documentation for your command819820Cobra can generate documentation based on subcommands, flags, etc.821Read more about it in the [docs generation documentation](docgen/_index.md).822823## Generating shell completions824825Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell.826If you add more information to your commands, these completions can be amazingly powerful and flexible.827Read more about it in [Shell Completions](completions/_index.md).828829## Providing Active Help830831Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users.832Active Help are messages (hints, warnings, etc) printed as the program is being used.833Read more about it in [Active Help](active_help.md).Document how to create a pluginNir Sofferbefore adoption4122785
lines 834–872why, one step back834835## Creating a plugin836837When creating a plugin for tools like *kubectl*, the executable is named838`kubectl-myplugin`, but it is used as `kubectl myplugin`. To fix help839messages and completions, annotate the root command with the840`cobra.CommandDisplayNameAnnotation` annotation.841842### Example kubectl plugin843844```go845package main846847import (848 "fmt"849850 "github.com/spf13/cobra"851)852853func main() {854 rootCmd := &cobra.Command{855 Use: "kubectl-myplugin",856 Annotations: map[string]string{857 cobra.CommandDisplayNameAnnotation: "kubectl myplugin",858 },859 }860 subCmd := &cobra.Command{861 Use: "subcmd",862 Run: func(cmd *cobra.Command, args []string) {863 fmt.Println("kubectl myplugin subcmd")864 },865 }866 rootCmd.AddCommand(subCmd)867 rootCmd.Execute()868}869```870871Example run as a kubectl plugin:872Improve site formatting (#2183)Nir Sofferbefore adoptionff7c561
line 873why, one step back873```consoleDocument how to create a pluginNir Sofferbefore adoption4122785
lines 874–887why, one step back874$ kubectl myplugin875Usage:876 kubectl myplugin [command]877878Available Commands:879 completion Generate the autocompletion script for the specified shell880 help Help about any command881 subcmd882883Flags:884 -h, --help help for kubectl myplugin885886Use "kubectl myplugin [command] --help" for more information about a command.887```