Skip to content
Myr

user_guide.md

This file

Path

user_guide.md

662 lines · 19.6 KiB · Markdown

Last changed by

Add ability to mark flags as required or exclusive as a group (#1654)John Schnakebefore adoption68b6b24

History of this file

Take it

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 1–31why, one step back
1# User Guide
23While you are welcome to provide your own organization, typically a Cobra-based4application will follow the following organizational structure:56```7 ▾ appName/8 ▾ cmd/9 add.go10 your.go11 commands.go12 here.go13 main.go14```1516In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.1718```go19package main2021import (22 "{pathToYourApp}/cmd"23)2425func main() {26 cmd.Execute()27}28```2930## Using the Cobra Generator31

Removes viper dependency by removing cobra/ CLI tool (#1604)John McBridebefore adoption5b2b9e9

line 32why, one step back
32Cobra-CLI is its own program that will create your application and add any

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 33–34why, one step back
33commands you want. It's the easiest way to incorporate Cobra into your application.
34

Changed branch name in the cobra generator link to 'main' (#1645)Neville Bokdawallabefore adoptiond622355

line 35why, one step back
35For 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)

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 36–88why, one step back
36
37## Using the Cobra Library3839To manually implement Cobra you need to create a bare main.go file and a rootCmd file.40You will optionally provide additional commands as you see fit.4142### Create rootCmd4344Cobra doesn't require any special constructors. Simply create your commands.4546Ideally you place this in app/cmd/root.go:4748```go49var rootCmd = &cobra.Command{50 Use: "hugo",51 Short: "Hugo is a very fast static site generator",52 Long: `A Fast and Flexible Static Site Generator built with53 love by spf13 and friends in Go.54 Complete documentation is available at http://hugo.spf13.com`,55 Run: func(cmd *cobra.Command, args []string) {56 // Do Stuff Here57 },58}5960func Execute() {61 if err := rootCmd.Execute(); err != nil {62 fmt.Fprintln(os.Stderr, err)63 os.Exit(1)64 }65}66```6768You will additionally define flags and handle configuration in your init() function.6970For example cmd/root.go:7172```go73package cmd7475import (76 "fmt"77 "os"7879 "github.com/spf13/cobra"80 "github.com/spf13/viper"81)8283var (84 // Used for flags.85 cfgFile string86 userLicense string8788 rootCmd = &cobra.Command{

Removes viper dependency by removing cobra/ CLI tool (#1604)John McBridebefore adoption5b2b9e9

line 89why, one step back
89 Use: "cobra-cli",

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 90–123why, one step back
90 Short: "A generator for Cobra based Applications",
91 Long: `Cobra is a CLI library for Go that empowers applications.92This application is a tool to generate the needed files93to quickly create a Cobra application.`,94 }95)9697// Execute executes the root command.98func Execute() error {99 return rootCmd.Execute()100}101102func init() {103 cobra.OnInitialize(initConfig)104105 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")106 rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")107 rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")108 rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")109 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))110 viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))111 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")112 viper.SetDefault("license", "apache")113114 rootCmd.AddCommand(addCmd)115 rootCmd.AddCommand(initCmd)116}117118func initConfig() {119 if cfgFile != "" {120 // Use config file from the flag.121 viper.SetConfigFile(cfgFile)122 } else {123 // Find home directory.

drop mitchellh/go-homedir (#853)umarcorbefore adoption8eaca5f

line 124why, one step back
124 home, err := os.UserHomeDir()

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 125–283why, one step back
125 cobra.CheckErr(err)
126127 // Search config in home directory with name ".cobra" (without extension).128 viper.AddConfigPath(home)129 viper.SetConfigType("yaml")130 viper.SetConfigName(".cobra")131 }132133 viper.AutomaticEnv()134135 if err := viper.ReadInConfig(); err == nil {136 fmt.Println("Using config file:", viper.ConfigFileUsed())137 }138}139```140141### Create your main.go142143With the root command you need to have your main function execute it.144Execute should be run on the root for clarity, though it can be called on any command.145146In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.147148```go149package main150151import (152 "{pathToYourApp}/cmd"153)154155func main() {156 cmd.Execute()157}158```159160### Create additional commands161162Additional commands can be defined and typically are each given their own file163inside of the cmd/ directory.164165If you wanted to create a version command you would create cmd/version.go and166populate it with the following:167168```go169package cmd170171import (172 "fmt"173174 "github.com/spf13/cobra"175)176177func init() {178 rootCmd.AddCommand(versionCmd)179}180181var versionCmd = &cobra.Command{182 Use: "version",183 Short: "Print the version number of Hugo",184 Long: `All software has versions. This is Hugo's`,185 Run: func(cmd *cobra.Command, args []string) {186 fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")187 },188}189```190191### Returning and handling errors192193If you wish to return an error to the caller of a command, `RunE` can be used.194195```go196package cmd197198import (199 "fmt"200201 "github.com/spf13/cobra"202)203204func init() {205 rootCmd.AddCommand(tryCmd)206}207208var tryCmd = &cobra.Command{209 Use: "try",210 Short: "Try and possibly fail at something",211 RunE: func(cmd *cobra.Command, args []string) error {212 if err := someFunc(); err != nil {213 return err214 }215 return nil216 },217}218```219220The error can then be caught at the execute function call.221222## Working with Flags223224Flags provide modifiers to control how the action command operates.225226### Assign flags to a command227228Since the flags are defined and used in different locations, we need to229define a variable outside with the correct scope to assign the flag to230work with.231232```go233var Verbose bool234var Source string235```236237There are two different approaches to assign a flag.238239### Persistent Flags240241A flag can be 'persistent', meaning that this flag will be available to the242command it's assigned to as well as every command under that command. For243global flags, assign a flag as a persistent flag on the root.244245```go246rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")247```248249### Local Flags250251A flag can also be assigned locally, which will only apply to that specific command.252253```go254localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")255```256257### Local Flag on Parent Commands258259By default, Cobra only parses local flags on the target command, and any local flags on260parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will261parse local flags on each command before executing the target command.262263```go264command := cobra.Command{265 Use: "print [OPTIONS] [COMMANDS]",266 TraverseChildren: true,267}268```269270### Bind Flags with Config271272You can also bind your flags with [viper](https://github.com/spf13/viper):273```go274var author string275276func init() {277 rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")278 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))279}280```281282In this example, the persistent flag `author` is bound with `viper`.283**Note**: the variable `author` will not be set to the value from config,

Small correction in User Guide (#1009)Nickolas Krausbefore adoption3c84bf8

line 284why, one step back
284when the `--author` flag is provided by user.

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 285–302why, one step back
285
286More in [viper documentation](https://github.com/spf13/viper#working-with-flags).287288### Required flags289290Flags are optional by default. If instead you wish your command to report an error291when a flag has not been set, mark it as required:292```go293rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")294rootCmd.MarkFlagRequired("region")295```296297Or, for persistent flags:298```go299rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")300rootCmd.MarkPersistentFlagRequired("region")301```302

Add ability to mark flags as required or exclusive as a group (#1654)John Schnakebefore adoption68b6b24

lines 303–326why, one step back
303### Flag Groups
304305If 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 306Cobra can enforce that requirement:307```go308rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")309rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")310rootCmd.MarkFlagsRequiredTogether("username", "password")311``` 312313You can also prevent different flags from being provided together if they represent mutually 314exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:315```go316rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")317rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")318rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")319```320321In both of these cases:322 - both local and persistent flags can be used323 - **NOTE:** the group is only enforced on commands where every flag is defined324 - a flag may appear in multiple groups325 - a group may contain any number of flags326

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 327–341why, one step back
327## Positional and Custom Arguments
328329Validation of positional arguments can be specified using the `Args` field330of `Command`.331332The following validators are built in:333334- `NoArgs` - the command will report an error if there are any positional args.335- `ArbitraryArgs` - the command will accept any args.336- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.337- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.338- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.339- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.340- `ExactValidArgs(int)` - the command will 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`341- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.

enable composing PositionalArgs (#896)Nelzbefore adoption45e521e

line 342why, one step back
342- `MatchAll(pargs ...PositionalArgs)` - enables combining existing checks with arbitrary other checks (e.g. you want to check the ExactArgs length along with other qualities).

readme: split 'Getting Started' into 'user_guide.md'umarcorbefore adoptionace6b14

lines 343–662why, one step back
343
344An example of setting the custom validator:345346```go347var cmd = &cobra.Command{348 Short: "hello",349 Args: func(cmd *cobra.Command, args []string) error {350 if len(args) < 1 {351 return errors.New("requires a color argument")352 }353 if myapp.IsValidColor(args[0]) {354 return nil355 }356 return fmt.Errorf("invalid color specified: %s", args[0])357 },358 Run: func(cmd *cobra.Command, args []string) {359 fmt.Println("Hello, World!")360 },361}362```363364## Example365366In the example below, we have defined three commands. Two are at the top level367and one (cmdTimes) is a child of one of the top commands. In this case the root368is not executable, meaning that a subcommand is required. This is accomplished369by not providing a 'Run' for the 'rootCmd'.370371We have only defined one flag for a single command.372373More documentation about flags is available at https://github.com/spf13/pflag374375```go376package main377378import (379 "fmt"380 "strings"381382 "github.com/spf13/cobra"383)384385func main() {386 var echoTimes int387388 var cmdPrint = &cobra.Command{389 Use: "print [string to print]",390 Short: "Print anything to the screen",391 Long: `print is for printing anything back to the screen.392For many years people have printed back to the screen.`,393 Args: cobra.MinimumNArgs(1),394 Run: func(cmd *cobra.Command, args []string) {395 fmt.Println("Print: " + strings.Join(args, " "))396 },397 }398399 var cmdEcho = &cobra.Command{400 Use: "echo [string to echo]",401 Short: "Echo anything to the screen",402 Long: `echo is for echoing anything back.403Echo works a lot like print, except it has a child command.`,404 Args: cobra.MinimumNArgs(1),405 Run: func(cmd *cobra.Command, args []string) {406 fmt.Println("Echo: " + strings.Join(args, " "))407 },408 }409410 var cmdTimes = &cobra.Command{411 Use: "times [string to echo]",412 Short: "Echo anything to the screen more times",413 Long: `echo things multiple times back to the user by providing414a count and a string.`,415 Args: cobra.MinimumNArgs(1),416 Run: func(cmd *cobra.Command, args []string) {417 for i := 0; i < echoTimes; i++ {418 fmt.Println("Echo: " + strings.Join(args, " "))419 }420 },421 }422423 cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")424425 var rootCmd = &cobra.Command{Use: "app"}426 rootCmd.AddCommand(cmdPrint, cmdEcho)427 cmdEcho.AddCommand(cmdTimes)428 rootCmd.Execute()429}430```431432For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).433434## Help Command435436Cobra automatically adds a help command to your application when you have subcommands.437This will be called when a user runs 'app help'. Additionally, help will also438support all other commands as input. Say, for instance, you have a command called439'create' without any additional configuration; Cobra will work when 'app help440create' is called. Every command will automatically have the '--help' flag added.441442### Example443444The following output is automatically generated by Cobra. Nothing beyond the445command and flag definitions are needed.446447 $ cobra help448449 Cobra is a CLI library for Go that empowers applications.450 This application is a tool to generate the needed files451 to quickly create a Cobra application.452453 Usage:454 cobra [command]455456 Available Commands:457 add Add a command to a Cobra Application458 help Help about any command459 init Initialize a Cobra Application460461 Flags:462 -a, --author string author name for copyright attribution (default "YOUR NAME")463 --config string config file (default is $HOME/.cobra.yaml)464 -h, --help help for cobra465 -l, --license string name of license for the project466 --viper use Viper for configuration (default true)467468 Use "cobra [command] --help" for more information about a command.469470471Help is just a command like any other. There is no special logic or behavior472around it. In fact, you can provide your own if you want.473474### Defining your own help475476You can provide your own Help command or your own template for the default command to use477with following functions:478479```go480cmd.SetHelpCommand(cmd *Command)481cmd.SetHelpFunc(f func(*Command, []string))482cmd.SetHelpTemplate(s string)483```484485The latter two will also apply to any children commands.486487## Usage Message488489When the user provides an invalid flag or invalid command, Cobra responds by490showing the user the 'usage'.491492### Example493You may recognize this from the help above. That's because the default help494embeds the usage as part of its output.495496 $ cobra --invalid497 Error: unknown flag: --invalid498 Usage:499 cobra [command]500501 Available Commands:502 add Add a command to a Cobra Application503 help Help about any command504 init Initialize a Cobra Application505506 Flags:507 -a, --author string author name for copyright attribution (default "YOUR NAME")508 --config string config file (default is $HOME/.cobra.yaml)509 -h, --help help for cobra510 -l, --license string name of license for the project511 --viper use Viper for configuration (default true)512513 Use "cobra [command] --help" for more information about a command.514515### Defining your own usage516You can provide your own usage function or template for Cobra to use.517Like help, the function and template are overridable through public methods:518519```go520cmd.SetUsageFunc(f func(*Command) error)521cmd.SetUsageTemplate(s string)522```523524## Version Flag525526Cobra adds a top-level '--version' flag if the Version field is set on the root command.527Running an application with the '--version' flag will print the version to stdout using528the version template. The template can be customized using the529`cmd.SetVersionTemplate(s string)` function.530531## PreRun and PostRun Hooks532533It 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:534535- `PersistentPreRun`536- `PreRun`537- `Run`538- `PostRun`539- `PersistentPostRun`540541An 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`:542543```go544package main545546import (547 "fmt"548549 "github.com/spf13/cobra"550)551552func main() {553554 var rootCmd = &cobra.Command{555 Use: "root [sub]",556 Short: "My root command",557 PersistentPreRun: func(cmd *cobra.Command, args []string) {558 fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)559 },560 PreRun: func(cmd *cobra.Command, args []string) {561 fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)562 },563 Run: func(cmd *cobra.Command, args []string) {564 fmt.Printf("Inside rootCmd Run with args: %v\n", args)565 },566 PostRun: func(cmd *cobra.Command, args []string) {567 fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)568 },569 PersistentPostRun: func(cmd *cobra.Command, args []string) {570 fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)571 },572 }573574 var subCmd = &cobra.Command{575 Use: "sub [no options!]",576 Short: "My subcommand",577 PreRun: func(cmd *cobra.Command, args []string) {578 fmt.Printf("Inside subCmd PreRun with args: %v\n", args)579 },580 Run: func(cmd *cobra.Command, args []string) {581 fmt.Printf("Inside subCmd Run with args: %v\n", args)582 },583 PostRun: func(cmd *cobra.Command, args []string) {584 fmt.Printf("Inside subCmd PostRun with args: %v\n", args)585 },586 PersistentPostRun: func(cmd *cobra.Command, args []string) {587 fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)588 },589 }590591 rootCmd.AddCommand(subCmd)592593 rootCmd.SetArgs([]string{""})594 rootCmd.Execute()595 fmt.Println()596 rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})597 rootCmd.Execute()598}599```600601Output:602```603Inside rootCmd PersistentPreRun with args: []604Inside rootCmd PreRun with args: []605Inside rootCmd Run with args: []606Inside rootCmd PostRun with args: []607Inside rootCmd PersistentPostRun with args: []608609Inside rootCmd PersistentPreRun with args: [arg1 arg2]610Inside subCmd PreRun with args: [arg1 arg2]611Inside subCmd Run with args: [arg1 arg2]612Inside subCmd PostRun with args: [arg1 arg2]613Inside subCmd PersistentPostRun with args: [arg1 arg2]614```615616## Suggestions when "unknown command" happens617618Cobra 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:619620```621$ hugo srever622Error: unknown command "srever" for "hugo"623624Did you mean this?625 server626627Run 'hugo --help' for usage.628```629630Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.631632If you need to disable suggestions or tweak the string distance in your command, use:633634```go635command.DisableSuggestions = true636```637638or639640```go641command.SuggestionsMinimumDistance = 1642```643644You 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 makes sense in your set of commands and for some which you don't want aliases. Example:645646```647$ kubectl remove648Error: unknown command "remove" for "kubectl"649650Did you mean this?651 delete652653Run 'kubectl help' for usage.654```655656## Generating documentation for your command657658Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).659660## Generating shell completions661662Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md).