README.md

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