1![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) 2 3Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. 4 5Many of the most widely used Go projects are built using Cobra including: 6 7* [Kubernetes](http://kubernetes.io/) 8* [Hugo](http://gohugo.io) 9* [rkt](https://github.com/coreos/rkt) 10* [etcd](https://github.com/coreos/etcd) 11* [Moby (former Docker)](https://github.com/moby/moby) 12* [Docker (distribution)](https://github.com/docker/distribution) 13* [OpenShift](https://www.openshift.com/) 14* [Delve](https://github.com/derekparker/delve) 15* [GopherJS](http://www.gopherjs.org/) 16* [CockroachDB](http://www.cockroachlabs.com/) 17* [Bleve](http://www.blevesearch.com/) 18* [ProjectAtomic (enterprise)](http://www.projectatomic.io/) 19* [GiantSwarm's swarm](https://github.com/giantswarm/cli) 20* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) 21* [rclone](http://rclone.org/) 22* [nehm](https://github.com/bogem/nehm) 23* [Pouch](https://github.com/alibaba/pouch) 24 25[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) 26[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra) 27[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) 28 29# Table of Contents 30 31- [Overview](#overview) 32- [Concepts](#concepts) 33 * [Commands](#commands) 34 * [Flags](#flags) 35- [Installing](#installing) 36- [Getting Started](#getting-started) 37 * [Using the Cobra Generator](#using-the-cobra-generator) 38 * [Using the Cobra Library](#using-the-cobra-library) 39 * [Working with Flags](#working-with-flags) 40 * [Positional and Custom Arguments](#positional-and-custom-arguments) 41 * [Example](#example) 42 * [Help Command](#help-command) 43 * [Usage Message](#usage-message) 44 * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks) 45 * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens) 46 * [Generating documentation for your command](#generating-documentation-for-your-command) 47 * [Generating bash completions](#generating-bash-completions) 48- [Contributing](#contributing) 49- [License](#license) 50 51# Overview 52 53Cobra is a library providing a simple interface to create powerful modern CLI 54interfaces similar to git & go tools. 55 56Cobra is also an application that will generate your application scaffolding to rapidly 57develop a Cobra-based application. 58 59Cobra provides: 60* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. 61* Fully POSIX-compliant flags (including short & long versions) 62* Nested subcommands 63* Global, local and cascading flags 64* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname` 65* Intelligent suggestions (`app srver`... did you mean `app server`?) 66* Automatic help generation for commands and flags 67* Automatic help flag recognition of `-h`, `--help`, etc. 68* Automatically generated bash autocomplete for your application 69* Automatically generated man pages for your application 70* Command aliases so you can change things without breaking them 71* The flexibility to define your own help, usage, etc. 72* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps 73 74# Concepts 75 76Cobra is built on a structure of commands, arguments & flags. 77 78**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. 79 80The best applications will read like sentences when used. Users will know how 81to use the application because they will natively understand how to use it. 82 83The pattern to follow is 84`APPNAME VERB NOUN --ADJECTIVE.` 85 or 86`APPNAME COMMAND ARG --FLAG` 87 88A few good real world examples may better illustrate this point. 89 90In the following example, 'server' is a command, and 'port' is a flag: 91 92 hugo server --port=1313 93 94In this command we are telling Git to clone the url bare. 95 96 git clone URL --bare 97 98## Commands 99 100Command is the central point of the application. Each interaction that 101the application supports will be contained in a Command. A command can 102have children commands and optionally run an action. 103 104In the example above, 'server' is the command. 105 106[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command) 107 108## Flags 109 110A flag is a way to modify the behavior of a command. Cobra supports 111fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). 112A Cobra command can define flags that persist through to children commands 113and flags that are only available to that command. 114 115In the example above, 'port' is the flag. 116 117Flag functionality is provided by the [pflag 118library](https://github.com/spf13/pflag), a fork of the flag standard library 119which maintains the same interface while adding POSIX compliance. 120 121# Installing 122Using Cobra is easy. First, use `go get` to install the latest version 123of the library. This command will install the `cobra` generator executable 124along with the library and its dependencies: 125 126 go get -u github.com/spf13/cobra/cobra 127 128Next, include Cobra in your application: 129 130```go 131import "github.com/spf13/cobra" 132``` 133 134# Getting Started 135 136While you are welcome to provide your own organization, typically a Cobra-based 137application will follow the following organizational structure: 138 139``` 140 ▾ appName/ 141 ▾ cmd/ 142 add.go 143 your.go 144 commands.go 145 here.go 146 main.go 147``` 148 149In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. 150 151```go 152package main 153 154import ( 155 "fmt" 156 "os" 157 158 "{pathToYourApp}/cmd" 159) 160 161func main() { 162 cmd.Execute() 163} 164``` 165 166## Using the Cobra Generator 167 168Cobra provides its own program that will create your application and add any 169commands you want. It's the easiest way to incorporate Cobra into your application. 170 171[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. 172 173## Using the Cobra Library 174 175To manually implement Cobra you need to create a bare main.go file and a rootCmd file. 176You will optionally provide additional commands as you see fit. 177 178### Create rootCmd 179 180Cobra doesn't require any special constructors. Simply create your commands. 181 182Ideally you place this in app/cmd/root.go: 183 184```go 185var rootCmd = &cobra.Command{ 186 Use: "hugo", 187 Short: "Hugo is a very fast static site generator", 188 Long: `A Fast and Flexible Static Site Generator built with 189 love by spf13 and friends in Go. 190 Complete documentation is available at http://hugo.spf13.com`, 191 Run: func(cmd *cobra.Command, args []string) { 192 // Do Stuff Here 193 }, 194} 195 196func Execute() { 197 if err := rootCmd.Execute(); err != nil { 198 fmt.Println(err) 199 os.Exit(1) 200 } 201} 202``` 203 204You will additionally define flags and handle configuration in your init() function. 205 206For example cmd/root.go: 207 208```go 209import ( 210 "fmt" 211 "os" 212 213 homedir "github.com/mitchellh/go-homedir" 214 "github.com/spf13/cobra" 215 "github.com/spf13/viper" 216) 217 218func init() { 219 cobra.OnInitialize(initConfig) 220 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") 221 rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/") 222 rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution") 223 rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)") 224 rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration") 225 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) 226 viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase")) 227 viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) 228 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>") 229 viper.SetDefault("license", "apache") 230} 231 232func initConfig() { 233 // Don't forget to read config either from cfgFile or from home directory! 234 if cfgFile != "" { 235 // Use config file from the flag. 236 viper.SetConfigFile(cfgFile) 237 } else { 238 // Find home directory. 239 home, err := homedir.Dir() 240 if err != nil { 241 fmt.Println(err) 242 os.Exit(1) 243 } 244 245 // Search config in home directory with name ".cobra" (without extension). 246 viper.AddConfigPath(home) 247 viper.SetConfigName(".cobra") 248 } 249 250 if err := viper.ReadInConfig(); err != nil { 251 fmt.Println("Can't read config:", err) 252 os.Exit(1) 253 } 254} 255``` 256 257### Create your main.go 258 259With the root command you need to have your main function execute it. 260Execute should be run on the root for clarity, though it can be called on any command. 261 262In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra. 263 264```go 265package main 266 267import ( 268 "fmt" 269 "os" 270 271 "{pathToYourApp}/cmd" 272) 273 274func main() { 275 cmd.Execute() 276} 277``` 278 279### Create additional commands 280 281Additional commands can be defined and typically are each given their own file 282inside of the cmd/ directory. 283 284If you wanted to create a version command you would create cmd/version.go and 285populate it with the following: 286 287```go 288package cmd 289 290import ( 291 "fmt" 292 293 "github.com/spf13/cobra" 294) 295 296func init() { 297 rootCmd.AddCommand(versionCmd) 298} 299 300var versionCmd = &cobra.Command{ 301 Use: "version", 302 Short: "Print the version number of Hugo", 303 Long: `All software has versions. This is Hugo's`, 304 Run: func(cmd *cobra.Command, args []string) { 305 fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") 306 }, 307} 308``` 309 310## Working with Flags 311 312Flags provide modifiers to control how the action command operates. 313 314### Assign flags to a command 315 316Since the flags are defined and used in different locations, we need to 317define a variable outside with the correct scope to assign the flag to 318work with. 319 320```go 321var Verbose bool 322var Source string 323``` 324 325There are two different approaches to assign a flag. 326 327### Persistent Flags 328 329A flag can be 'persistent' meaning that this flag will be available to the 330command it's assigned to as well as every command under that command. For 331global flags, assign a flag as a persistent flag on the root. 332 333```go 334rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") 335``` 336 337### Local Flags 338 339A flag can also be assigned locally which will only apply to that specific command. 340 341```go 342rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") 343``` 344 345### Local Flag on Parent Commands 346 347By default Cobra only parses local flags on the target command, any local flags on 348parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will 349parse local flags on each command before executing the target command. 350 351```go 352command := cobra.Command{ 353 Use: "print [OPTIONS] [COMMANDS]", 354 TraverseChildren: true, 355} 356``` 357 358### Bind Flags with Config 359 360You can also bind your flags with [viper](https://github.com/spf13/viper): 361```go 362var author string 363 364func init() { 365 rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") 366 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) 367} 368``` 369 370In this example the persistent flag `author` is bound with `viper`. 371**Note**, that the variable `author` will not be set to the value from config, 372when the `--author` flag is not provided by user. 373 374More in [viper documentation](https://github.com/spf13/viper#working-with-flags). 375 376### Required flags 377 378Flags are optional by default. If instead you wish your command to report an error 379when a flag has not been set, mark it as required: 380```go 381rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") 382rootCmd.MarkFlagRequired("region") 383``` 384 385## Positional and Custom Arguments 386 387Validation of positional arguments can be specified using the `Args` field 388of `Command`. 389 390The following validators are built in: 391 392- `NoArgs` - the command will report an error if there are any positional args. 393- `ArbitraryArgs` - the command will accept any args. 394- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. 395- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. 396- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. 397- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. 398- `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. 399 400An example of setting the custom validator: 401 402```go 403var cmd = &cobra.Command{ 404 Short: "hello", 405 Args: func(cmd *cobra.Command, args []string) error { 406 if len(args) < 1 { 407 return errors.New("requires at least one arg") 408 } 409 if myapp.IsValidColor(args[0]) { 410 return nil 411 } 412 return fmt.Errorf("invalid color specified: %s", args[0]) 413 }, 414 Run: func(cmd *cobra.Command, args []string) { 415 fmt.Println("Hello, World!") 416 }, 417} 418``` 419 420## Example 421 422In the example below, we have defined three commands. Two are at the top level 423and one (cmdTimes) is a child of one of the top commands. In this case the root 424is not executable meaning that a subcommand is required. This is accomplished 425by not providing a 'Run' for the 'rootCmd'. 426 427We have only defined one flag for a single command. 428 429More documentation about flags is available at https://github.com/spf13/pflag 430 431```go 432package main 433 434import ( 435 "fmt" 436 "strings" 437 438 "github.com/spf13/cobra" 439) 440 441func main() { 442 var echoTimes int 443 444 var cmdPrint = &cobra.Command{ 445 Use: "print [string to print]", 446 Short: "Print anything to the screen", 447 Long: `print is for printing anything back to the screen. 448For many years people have printed back to the screen.`, 449 Args: cobra.MinimumNArgs(1), 450 Run: func(cmd *cobra.Command, args []string) { 451 fmt.Println("Print: " + strings.Join(args, " ")) 452 }, 453 } 454 455 var cmdEcho = &cobra.Command{ 456 Use: "echo [string to echo]", 457 Short: "Echo anything to the screen", 458 Long: `echo is for echoing anything back. 459Echo works a lot like print, except it has a child command.`, 460 Args: cobra.MinimumNArgs(1), 461 Run: func(cmd *cobra.Command, args []string) { 462 fmt.Println("Print: " + strings.Join(args, " ")) 463 }, 464 } 465 466 var cmdTimes = &cobra.Command{ 467 Use: "times [# times] [string to echo]", 468 Short: "Echo anything to the screen more times", 469 Long: `echo things multiple times back to the user by providing 470a count and a string.`, 471 Args: cobra.MinimumNArgs(1), 472 Run: func(cmd *cobra.Command, args []string) { 473 for i := 0; i < echoTimes; i++ { 474 fmt.Println("Echo: " + strings.Join(args, " ")) 475 } 476 }, 477 } 478 479 cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") 480 481 var rootCmd = &cobra.Command{Use: "app"} 482 rootCmd.AddCommand(cmdPrint, cmdEcho) 483 cmdEcho.AddCommand(cmdTimes) 484 rootCmd.Execute() 485} 486``` 487 488For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). 489 490## Help Command 491 492Cobra automatically adds a help command to your application when you have subcommands. 493This will be called when a user runs 'app help'. Additionally, help will also 494support all other commands as input. Say, for instance, you have a command called 495'create' without any additional configuration; Cobra will work when 'app help 496create' is called. Every command will automatically have the '--help' flag added. 497 498### Example 499 500The following output is automatically generated by Cobra. Nothing beyond the 501command and flag definitions are needed. 502 503 $ cobra help 504 505 Cobra is a CLI library for Go that empowers applications. 506 This application is a tool to generate the needed files 507 to quickly create a Cobra application. 508 509 Usage: 510 cobra [command] 511 512 Available Commands: 513 add Add a command to a Cobra Application 514 help Help about any command 515 init Initialize a Cobra Application 516 517 Flags: 518 -a, --author string author name for copyright attribution (default "YOUR NAME") 519 --config string config file (default is $HOME/.cobra.yaml) 520 -h, --help help for cobra 521 -l, --license string name of license for the project 522 --viper use Viper for configuration (default true) 523 524 Use "cobra [command] --help" for more information about a command. 525 526 527Help is just a command like any other. There is no special logic or behavior 528around it. In fact, you can provide your own if you want. 529 530### Defining your own help 531 532You can provide your own Help command or your own template for the default command to use 533with following functions: 534 535```go 536cmd.SetHelpCommand(cmd *Command) 537cmd.SetHelpFunc(f func(*Command, []string)) 538cmd.SetHelpTemplate(s string) 539``` 540 541The latter two will also apply to any children commands. 542 543## Usage Message 544 545When the user provides an invalid flag or invalid command, Cobra responds by 546showing the user the 'usage'. 547 548### Example 549You may recognize this from the help above. That's because the default help 550embeds the usage as part of its output. 551 552 $ cobra --invalid 553 Error: unknown flag: --invalid 554 Usage: 555 cobra [command] 556 557 Available Commands: 558 add Add a command to a Cobra Application 559 help Help about any command 560 init Initialize a Cobra Application 561 562 Flags: 563 -a, --author string author name for copyright attribution (default "YOUR NAME") 564 --config string config file (default is $HOME/.cobra.yaml) 565 -h, --help help for cobra 566 -l, --license string name of license for the project 567 --viper use Viper for configuration (default true) 568 569 Use "cobra [command] --help" for more information about a command. 570 571### Defining your own usage 572You can provide your own usage function or template for Cobra to use. 573Like help, the function and template are overridable through public methods: 574 575```go 576cmd.SetUsageFunc(f func(*Command) error) 577cmd.SetUsageTemplate(s string) 578``` 579 580## Version Flag 581 582Cobra adds a top-level '--version' flag if the Version field is set on the root command. 583Running an application with the '--version' flag will print the version to stdout using 584the version template. The template can be customized using the 585`cmd.SetVersionTemplate(s string)` function. 586 587## PreRun and PostRun Hooks 588 589It 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: 590 591- `PersistentPreRun` 592- `PreRun` 593- `Run` 594- `PostRun` 595- `PersistentPostRun` 596 597An 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`: 598 599```go 600package main 601 602import ( 603 "fmt" 604 605 "github.com/spf13/cobra" 606) 607 608func main() { 609 610 var rootCmd = &cobra.Command{ 611 Use: "root [sub]", 612 Short: "My root command", 613 PersistentPreRun: func(cmd *cobra.Command, args []string) { 614 fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) 615 }, 616 PreRun: func(cmd *cobra.Command, args []string) { 617 fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) 618 }, 619 Run: func(cmd *cobra.Command, args []string) { 620 fmt.Printf("Inside rootCmd Run with args: %v\n", args) 621 }, 622 PostRun: func(cmd *cobra.Command, args []string) { 623 fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) 624 }, 625 PersistentPostRun: func(cmd *cobra.Command, args []string) { 626 fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) 627 }, 628 } 629 630 var subCmd = &cobra.Command{ 631 Use: "sub [no options!]", 632 Short: "My subcommand", 633 PreRun: func(cmd *cobra.Command, args []string) { 634 fmt.Printf("Inside subCmd PreRun with args: %v\n", args) 635 }, 636 Run: func(cmd *cobra.Command, args []string) { 637 fmt.Printf("Inside subCmd Run with args: %v\n", args) 638 }, 639 PostRun: func(cmd *cobra.Command, args []string) { 640 fmt.Printf("Inside subCmd PostRun with args: %v\n", args) 641 }, 642 PersistentPostRun: func(cmd *cobra.Command, args []string) { 643 fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) 644 }, 645 } 646 647 rootCmd.AddCommand(subCmd) 648 649 rootCmd.SetArgs([]string{""}) 650 rootCmd.Execute() 651 fmt.Println() 652 rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) 653 rootCmd.Execute() 654} 655``` 656 657Output: 658``` 659Inside rootCmd PersistentPreRun with args: [] 660Inside rootCmd PreRun with args: [] 661Inside rootCmd Run with args: [] 662Inside rootCmd PostRun with args: [] 663Inside rootCmd PersistentPostRun with args: [] 664 665Inside rootCmd PersistentPreRun with args: [arg1 arg2] 666Inside subCmd PreRun with args: [arg1 arg2] 667Inside subCmd Run with args: [arg1 arg2] 668Inside subCmd PostRun with args: [arg1 arg2] 669Inside subCmd PersistentPostRun with args: [arg1 arg2] 670``` 671 672## Suggestions when "unknown command" happens 673 674Cobra 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: 675 676``` 677$ hugo srever 678Error: unknown command "srever" for "hugo" 679 680Did you mean this? 681 server 682 683Run 'hugo --help' for usage. 684``` 685 686Suggestions 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. 687 688If you need to disable suggestions or tweak the string distance in your command, use: 689 690```go 691command.DisableSuggestions = true 692``` 693 694or 695 696```go 697command.SuggestionsMinimumDistance = 1 698``` 699 700You 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: 701 702``` 703$ kubectl remove 704Error: unknown command "remove" for "kubectl" 705 706Did you mean this? 707 delete 708 709Run 'kubectl help' for usage. 710``` 711 712## Generating documentation for your command 713 714Cobra can generate documentation based on subcommands, flags, etc. in the following formats: 715 716- [Markdown](doc/md_docs.md) 717- [ReStructured Text](doc/rest_docs.md) 718- [Man Page](doc/man_docs.md) 719 720## Generating bash completions 721 722Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md). 723 724# Contributing 725 7261. Fork it 7272. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) 7283. Create your feature branch (`git checkout -b my-new-feature`) 7294. Make changes and add them (`git add .`) 7305. Commit your changes (`git commit -m 'Add some feature'`) 7316. Push to the branch (`git push origin my-new-feature`) 7327. Create new pull request 733 734# License 735 736Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) 737