• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

cobra/H27-Apr-2017-

doc/H27-Apr-2017-

.gitignoreH A D27-Apr-2017467

.mailmapH A D27-Apr-2017172

.travis.ymlH A D27-Apr-2017607

README.mdH A D27-Apr-201729.5 KiB

bash_completions.goH A D27-Apr-201717.2 KiB

bash_completions.mdH A D27-Apr-20176.6 KiB

bash_completions_test.goH A D27-Apr-20175.1 KiB

cobra.goH A D27-Apr-20174.9 KiB

cobra_test.goH A D27-Apr-201731.1 KiB

command.goH A D27-Apr-201735.7 KiB

command_notwin.goH A D27-Apr-201768

command_test.goH A D27-Apr-20176.6 KiB

command_win.goH A D27-Apr-2017482

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 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* [Docker](https://github.com/docker/docker)
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
23
24[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
25[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra)
26[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra)
27
28![cobra](https://cloud.githubusercontent.com/assets/173412/10911369/84832a8e-8212-11e5-9f82-cc96660a4794.gif)
29
30# Overview
31
32Cobra is a library providing a simple interface to create powerful modern CLI
33interfaces similar to git & go tools.
34
35Cobra is also an application that will generate your application scaffolding to rapidly
36develop a Cobra-based application.
37
38Cobra provides:
39* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
40* Fully POSIX-compliant flags (including short & long versions)
41* Nested subcommands
42* Global, local and cascading flags
43* Easy generation of applications & commands with `cobra create appname` & `cobra add cmdname`
44* Intelligent suggestions (`app srver`... did you mean `app server`?)
45* Automatic help generation for commands and flags
46* Automatic detailed help for `app help [command]`
47* Automatic help flag recognition of `-h`, `--help`, etc.
48* Automatically generated bash autocomplete for your application
49* Automatically generated man pages for your application
50* Command aliases so you can change things without breaking them
51* The flexibilty to define your own help, usage, etc.
52* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
53
54Cobra has an exceptionally clean interface and simple design without needless
55constructors or initialization methods.
56
57Applications built with Cobra commands are designed to be as user-friendly as
58possible. Flags can be placed before or after the command (as long as a
59confusing space isn’t provided). Both short and long flags can be used. A
60command need not even be fully typed.  Help is automatically generated and
61available for the application or for a specific command using either the help
62command or the `--help` flag.
63
64# Concepts
65
66Cobra is built on a structure of commands, arguments & flags.
67
68**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
69
70The best applications will read like sentences when used. Users will know how
71to use the application because they will natively understand how to use it.
72
73The pattern to follow is
74`APPNAME VERB NOUN --ADJECTIVE.`
75    or
76`APPNAME COMMAND ARG --FLAG`
77
78A few good real world examples may better illustrate this point.
79
80In the following example, 'server' is a command, and 'port' is a flag:
81
82    > hugo server --port=1313
83
84In this command we are telling Git to clone the url bare.
85
86    > git clone URL --bare
87
88## Commands
89
90Command is the central point of the application. Each interaction that
91the application supports will be contained in a Command. A command can
92have children commands and optionally run an action.
93
94In the example above, 'server' is the command.
95
96A Command has the following structure:
97
98```go
99type Command struct {
100    Use string // The one-line usage message.
101    Short string // The short description shown in the 'help' output.
102    Long string // The long message shown in the 'help <this-command>' output.
103    Run func(cmd *Command, args []string) // Run runs the command.
104}
105```
106
107## Flags
108
109A Flag is a way to modify the behavior of a command. Cobra supports
110fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
111A Cobra command can define flags that persist through to children commands
112and flags that are only available to that command.
113
114In the example above, 'port' is the flag.
115
116Flag functionality is provided by the [pflag
117library](https://github.com/ogier/pflag), a fork of the flag standard library
118which maintains the same interface while adding POSIX compliance.
119
120## Usage
121
122Cobra works by creating a set of commands and then organizing them into a tree.
123The tree defines the structure of the application.
124
125Once each command is defined with its corresponding flags, then the
126tree is assigned to the commander which is finally executed.
127
128# Installing
129Using Cobra is easy. First, use `go get` to install the latest version
130of the library. This command will install the `cobra` generator executible
131along with the library:
132
133    > go get -v github.com/spf13/cobra/cobra
134
135Next, include Cobra in your application:
136
137```go
138import "github.com/spf13/cobra"
139```
140
141# Getting Started
142
143While you are welcome to provide your own organization, typically a Cobra based
144application will follow the following organizational structure.
145
146```
147  ▾ appName/
148    ▾ cmd/
149        add.go
150        your.go
151        commands.go
152        here.go
153      main.go
154```
155
156In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
157
158```go
159package main
160
161import (
162	"fmt"
163	"os"
164
165	"{pathToYourApp}/cmd"
166)
167
168func main() {
169	if err := cmd.RootCmd.Execute(); err != nil {
170		fmt.Println(err)
171		os.Exit(1)
172	}
173}
174```
175
176## Using the Cobra Generator
177
178Cobra provides its own program that will create your application and add any
179commands you want. It's the easiest way to incorporate Cobra into your application.
180
181In order to use the cobra command, compile it using the following command:
182
183    > go get github.com/spf13/cobra/cobra
184
185This will create the cobra executable under your `$GOPATH/bin` directory.
186
187### cobra init
188
189The `cobra init [yourApp]` command will create your initial application code
190for you. It is a very powerful application that will populate your program with
191the right structure so you can immediately enjoy all the benefits of Cobra. It
192will also automatically apply the license you specify to your application.
193
194Cobra init is pretty smart. You can provide it a full path, or simply a path
195similar to what is expected in the import.
196
197```
198cobra init github.com/spf13/newAppName
199```
200
201### cobra add
202
203Once an application is initialized Cobra can create additional commands for you.
204Let's say you created an app and you wanted the following commands for it:
205
206* app serve
207* app config
208* app config create
209
210In your project directory (where your main.go file is) you would run the following:
211
212```
213cobra add serve
214cobra add config
215cobra add create -p 'configCmd'
216```
217
218Once you have run these three commands you would have an app structure that would look like:
219
220```
221  ▾ app/
222    ▾ cmd/
223        serve.go
224        config.go
225        create.go
226      main.go
227```
228
229at this point you can run `go run main.go` and it would run your app. `go run
230main.go serve`, `go run main.go config`, `go run main.go config create` along
231with `go run main.go help serve`, etc would all work.
232
233Obviously you haven't added your own code to these yet, the commands are ready
234for you to give them their tasks. Have fun.
235
236### Configuring the cobra generator
237
238The cobra generator will be easier to use if you provide a simple configuration
239file which will help you eliminate providing a bunch of repeated information in
240flags over and over.
241
242An example ~/.cobra.yaml file:
243
244```yaml
245author: Steve Francia <spf@spf13.com>
246license: MIT
247```
248
249You can specify no license by setting `license` to `none` or you can specify
250a custom license:
251
252```yaml
253license:
254  header: This file is part of {{ .appName }}.
255  text: |
256    {{ .copyright }}
257
258    This is my license. There are many like it, but this one is mine.
259    My license is my best friend. It is my life. I must master it as I must
260    master my life.
261```
262
263You can also use built-in licenses. For example, **GPLv2**, **GPLv3**, **LGPL**,
264**AGPL**, **MIT**, **2-Clause BSD** or **3-Clause BSD**.
265
266## Manually implementing Cobra
267
268To manually implement cobra you need to create a bare main.go file and a RootCmd file.
269You will optionally provide additional commands as you see fit.
270
271### Create the root command
272
273The root command represents your binary itself.
274
275
276#### Manually create rootCmd
277
278Cobra doesn't require any special constructors. Simply create your commands.
279
280Ideally you place this in app/cmd/root.go:
281
282```go
283var RootCmd = &cobra.Command{
284	Use:   "hugo",
285	Short: "Hugo is a very fast static site generator",
286	Long: `A Fast and Flexible Static Site Generator built with
287                love by spf13 and friends in Go.
288                Complete documentation is available at http://hugo.spf13.com`,
289	Run: func(cmd *cobra.Command, args []string) {
290		// Do Stuff Here
291	},
292}
293```
294
295You will additionally define flags and handle configuration in your init() function.
296
297for example cmd/root.go:
298
299```go
300func init() {
301	cobra.OnInitialize(initConfig)
302	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
303	RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")
304	RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
305	RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
306	RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
307	viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
308	viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
309	viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
310	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
311	viper.SetDefault("license", "apache")
312}
313```
314
315### Create your main.go
316
317With the root command you need to have your main function execute it.
318Execute should be run on the root for clarity, though it can be called on any command.
319
320In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
321
322```go
323package main
324
325import (
326	"fmt"
327	"os"
328
329	"{pathToYourApp}/cmd"
330)
331
332func main() {
333	if err := cmd.RootCmd.Execute(); err != nil {
334		fmt.Println(err)
335		os.Exit(1)
336	}
337}
338```
339
340
341### Create additional commands
342
343Additional commands can be defined and typically are each given their own file
344inside of the cmd/ directory.
345
346If you wanted to create a version command you would create cmd/version.go and
347populate it with the following:
348
349```go
350package cmd
351
352import (
353	"github.com/spf13/cobra"
354	"fmt"
355)
356
357func init() {
358	RootCmd.AddCommand(versionCmd)
359}
360
361var versionCmd = &cobra.Command{
362	Use:   "version",
363	Short: "Print the version number of Hugo",
364	Long:  `All software has versions. This is Hugo's`,
365	Run: func(cmd *cobra.Command, args []string) {
366		fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
367	},
368}
369```
370
371### Attach command to its parent
372
373
374If you notice in the above example we attach the command to its parent. In
375this case the parent is the rootCmd. In this example we are attaching it to the
376root, but commands can be attached at any level.
377
378```go
379RootCmd.AddCommand(versionCmd)
380```
381
382### Remove a command from its parent
383
384Removing a command is not a common action in simple programs, but it allows 3rd
385parties to customize an existing command tree.
386
387In this example, we remove the existing `VersionCmd` command of an existing
388root command, and we replace it with our own version:
389
390```go
391mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
392mainlib.RootCmd.AddCommand(versionCmd)
393```
394
395## Working with Flags
396
397Flags provide modifiers to control how the action command operates.
398
399### Assign flags to a command
400
401Since the flags are defined and used in different locations, we need to
402define a variable outside with the correct scope to assign the flag to
403work with.
404
405```go
406var Verbose bool
407var Source string
408```
409
410There are two different approaches to assign a flag.
411
412### Persistent Flags
413
414A flag can be 'persistent' meaning that this flag will be available to the
415command it's assigned to as well as every command under that command. For
416global flags, assign a flag as a persistent flag on the root.
417
418```go
419RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
420```
421
422### Local Flags
423
424A flag can also be assigned locally which will only apply to that specific command.
425
426```go
427RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
428```
429
430
431## Example
432
433In the example below, we have defined three commands. Two are at the top level
434and one (cmdTimes) is a child of one of the top commands. In this case the root
435is not executable meaning that a subcommand is required. This is accomplished
436by not providing a 'Run' for the 'rootCmd'.
437
438We have only defined one flag for a single command.
439
440More documentation about flags is available at https://github.com/spf13/pflag
441
442```go
443package main
444
445import (
446	"fmt"
447	"strings"
448
449	"github.com/spf13/cobra"
450)
451
452func main() {
453
454	var echoTimes int
455
456	var cmdPrint = &cobra.Command{
457		Use:   "print [string to print]",
458		Short: "Print anything to the screen",
459		Long: `print is for printing anything back to the screen.
460            For many years people have printed back to the screen.
461            `,
462		Run: func(cmd *cobra.Command, args []string) {
463			fmt.Println("Print: " + strings.Join(args, " "))
464		},
465	}
466
467	var cmdEcho = &cobra.Command{
468		Use:   "echo [string to echo]",
469		Short: "Echo anything to the screen",
470		Long: `echo is for echoing anything back.
471            Echo works a lot like print, except it has a child command.
472            `,
473		Run: func(cmd *cobra.Command, args []string) {
474			fmt.Println("Print: " + strings.Join(args, " "))
475		},
476	}
477
478	var cmdTimes = &cobra.Command{
479		Use:   "times [# times] [string to echo]",
480		Short: "Echo anything to the screen more times",
481		Long: `echo things multiple times back to the user by providing
482            a count and a string.`,
483		Run: func(cmd *cobra.Command, args []string) {
484			for i := 0; i < echoTimes; i++ {
485				fmt.Println("Echo: " + strings.Join(args, " "))
486			}
487		},
488	}
489
490	cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
491
492	var rootCmd = &cobra.Command{Use: "app"}
493	rootCmd.AddCommand(cmdPrint, cmdEcho)
494	cmdEcho.AddCommand(cmdTimes)
495	rootCmd.Execute()
496}
497```
498
499For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
500
501## The Help Command
502
503Cobra automatically adds a help command to your application when you have subcommands.
504This will be called when a user runs 'app help'. Additionally, help will also
505support all other commands as input. Say, for instance, you have a command called
506'create' without any additional configuration; Cobra will work when 'app help
507create' is called.  Every command will automatically have the '--help' flag added.
508
509### Example
510
511The following output is automatically generated by Cobra. Nothing beyond the
512command and flag definitions are needed.
513
514    > hugo help
515
516    hugo is the main command, used to build your Hugo site.
517
518    Hugo is a Fast and Flexible Static Site Generator
519    built with love by spf13 and friends in Go.
520
521    Complete documentation is available at http://gohugo.io/.
522
523    Usage:
524      hugo [flags]
525      hugo [command]
526
527    Available Commands:
528      server          Hugo runs its own webserver to render the files
529      version         Print the version number of Hugo
530      config          Print the site configuration
531      check           Check content in the source directory
532      benchmark       Benchmark hugo by building a site a number of times.
533      convert         Convert your content to different formats
534      new             Create new content for your site
535      list            Listing out various types of content
536      undraft         Undraft changes the content's draft status from 'True' to 'False'
537      genautocomplete Generate shell autocompletion script for Hugo
538      gendoc          Generate Markdown documentation for the Hugo CLI.
539      genman          Generate man page for Hugo
540      import          Import your site from others.
541
542    Flags:
543      -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
544      -D, --buildDrafts[=false]: include content marked as draft
545      -F, --buildFuture[=false]: include content with publishdate in the future
546          --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
547          --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
548          --config="": config file (default is path/config.yaml|json|toml)
549      -d, --destination="": filesystem path to write files to
550          --disableRSS[=false]: Do not build RSS files
551          --disableSitemap[=false]: Do not build Sitemap file
552          --editor="": edit new content with this editor, if provided
553          --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
554          --log[=false]: Enable Logging
555          --logFile="": Log File path (if set, logging enabled automatically)
556          --noTimes[=false]: Don't sync modification time of files
557          --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
558          --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
559      -s, --source="": filesystem path to read files relative from
560          --stepAnalysis[=false]: display memory and timing of different steps of the program
561      -t, --theme="": theme to use (located in /themes/THEMENAME/)
562          --uglyURLs[=false]: if true, use /filename.html instead of /filename/
563      -v, --verbose[=false]: verbose output
564          --verboseLog[=false]: verbose logging
565      -w, --watch[=false]: watch filesystem for changes and recreate as needed
566
567    Use "hugo [command] --help" for more information about a command.
568
569
570Help is just a command like any other. There is no special logic or behavior
571around it. In fact, you can provide your own if you want.
572
573### Defining your own help
574
575You can provide your own Help command or your own template for the default command to use.
576
577The default help command is
578
579```go
580func (c *Command) initHelp() {
581	if c.helpCommand == nil {
582		c.helpCommand = &Command{
583			Use:   "help [command]",
584			Short: "Help about any command",
585			Long: `Help provides help for any command in the application.
586        Simply type ` + c.Name() + ` help [path to command] for full details.`,
587			Run: c.HelpFunc(),
588		}
589	}
590	c.AddCommand(c.helpCommand)
591}
592```
593
594You can provide your own command, function or template through the following methods:
595
596```go
597command.SetHelpCommand(cmd *Command)
598
599command.SetHelpFunc(f func(*Command, []string))
600
601command.SetHelpTemplate(s string)
602```
603
604The latter two will also apply to any children commands.
605
606## Usage
607
608When the user provides an invalid flag or invalid command, Cobra responds by
609showing the user the 'usage'.
610
611### Example
612You may recognize this from the help above. That's because the default help
613embeds the usage as part of its output.
614
615    Usage:
616      hugo [flags]
617      hugo [command]
618
619    Available Commands:
620      server          Hugo runs its own webserver to render the files
621      version         Print the version number of Hugo
622      config          Print the site configuration
623      check           Check content in the source directory
624      benchmark       Benchmark hugo by building a site a number of times.
625      convert         Convert your content to different formats
626      new             Create new content for your site
627      list            Listing out various types of content
628      undraft         Undraft changes the content's draft status from 'True' to 'False'
629      genautocomplete Generate shell autocompletion script for Hugo
630      gendoc          Generate Markdown documentation for the Hugo CLI.
631      genman          Generate man page for Hugo
632      import          Import your site from others.
633
634    Flags:
635      -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
636      -D, --buildDrafts[=false]: include content marked as draft
637      -F, --buildFuture[=false]: include content with publishdate in the future
638          --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
639          --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
640          --config="": config file (default is path/config.yaml|json|toml)
641      -d, --destination="": filesystem path to write files to
642          --disableRSS[=false]: Do not build RSS files
643          --disableSitemap[=false]: Do not build Sitemap file
644          --editor="": edit new content with this editor, if provided
645          --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
646          --log[=false]: Enable Logging
647          --logFile="": Log File path (if set, logging enabled automatically)
648          --noTimes[=false]: Don't sync modification time of files
649          --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
650          --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
651      -s, --source="": filesystem path to read files relative from
652          --stepAnalysis[=false]: display memory and timing of different steps of the program
653      -t, --theme="": theme to use (located in /themes/THEMENAME/)
654          --uglyURLs[=false]: if true, use /filename.html instead of /filename/
655      -v, --verbose[=false]: verbose output
656          --verboseLog[=false]: verbose logging
657      -w, --watch[=false]: watch filesystem for changes and recreate as needed
658
659### Defining your own usage
660You can provide your own usage function or template for Cobra to use.
661
662The default usage function is:
663
664```go
665return func(c *Command) error {
666	err := tmpl(c.Out(), c.UsageTemplate(), c)
667	return err
668}
669```
670
671Like help, the function and template are overridable through public methods:
672
673```go
674command.SetUsageFunc(f func(*Command) error)
675
676command.SetUsageTemplate(s string)
677```
678
679## PreRun or PostRun Hooks
680
681It 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:
682
683- `PersistentPreRun`
684- `PreRun`
685- `Run`
686- `PostRun`
687- `PersistentPostRun`
688
689An 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`:
690
691```go
692package main
693
694import (
695	"fmt"
696
697	"github.com/spf13/cobra"
698)
699
700func main() {
701
702	var rootCmd = &cobra.Command{
703		Use:   "root [sub]",
704		Short: "My root command",
705		PersistentPreRun: func(cmd *cobra.Command, args []string) {
706			fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
707		},
708		PreRun: func(cmd *cobra.Command, args []string) {
709			fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
710		},
711		Run: func(cmd *cobra.Command, args []string) {
712			fmt.Printf("Inside rootCmd Run with args: %v\n", args)
713		},
714		PostRun: func(cmd *cobra.Command, args []string) {
715			fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
716		},
717		PersistentPostRun: func(cmd *cobra.Command, args []string) {
718			fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
719		},
720	}
721
722	var subCmd = &cobra.Command{
723		Use:   "sub [no options!]",
724		Short: "My subcommand",
725		PreRun: func(cmd *cobra.Command, args []string) {
726			fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
727		},
728		Run: func(cmd *cobra.Command, args []string) {
729			fmt.Printf("Inside subCmd Run with args: %v\n", args)
730		},
731		PostRun: func(cmd *cobra.Command, args []string) {
732			fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
733		},
734		PersistentPostRun: func(cmd *cobra.Command, args []string) {
735			fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
736		},
737	}
738
739	rootCmd.AddCommand(subCmd)
740
741	rootCmd.SetArgs([]string{""})
742	_ = rootCmd.Execute()
743	fmt.Print("\n")
744	rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
745	_ = rootCmd.Execute()
746}
747```
748
749
750## Alternative Error Handling
751
752Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top,
753providing a way to handle the errors in one location. The current list of functions that return an error is:
754
755* PersistentPreRunE
756* PreRunE
757* RunE
758* PostRunE
759* PersistentPostRunE
760
761If you would like to silence the default `error` and `usage` output in favor of your own, you can set `SilenceUsage`
762and `SilenceErrors` to `true` on the command. A child command respects these flags if they are set on the parent
763command.
764
765**Example Usage using RunE:**
766
767```go
768package main
769
770import (
771	"errors"
772	"log"
773
774	"github.com/spf13/cobra"
775)
776
777func main() {
778	var rootCmd = &cobra.Command{
779		Use:   "hugo",
780		Short: "Hugo is a very fast static site generator",
781		Long: `A Fast and Flexible Static Site Generator built with
782                love by spf13 and friends in Go.
783                Complete documentation is available at http://hugo.spf13.com`,
784		RunE: func(cmd *cobra.Command, args []string) error {
785			// Do Stuff Here
786			return errors.New("some random error")
787		},
788	}
789
790	if err := rootCmd.Execute(); err != nil {
791		log.Fatal(err)
792	}
793}
794```
795
796## Suggestions when "unknown command" happens
797
798Cobra 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:
799
800```
801$ hugo srever
802Error: unknown command "srever" for "hugo"
803
804Did you mean this?
805        server
806
807Run 'hugo --help' for usage.
808```
809
810Suggestions 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.
811
812If you need to disable suggestions or tweak the string distance in your command, use:
813
814```go
815command.DisableSuggestions = true
816```
817
818or
819
820```go
821command.SuggestionsMinimumDistance = 1
822```
823
824You 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:
825
826```
827$ kubectl remove
828Error: unknown command "remove" for "kubectl"
829
830Did you mean this?
831        delete
832
833Run 'kubectl help' for usage.
834```
835
836## Generating Markdown-formatted documentation for your command
837
838Cobra can generate a Markdown-formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](doc/md_docs.md).
839
840## Generating man pages for your command
841
842Cobra can generate a man page based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Man Docs](doc/man_docs.md).
843
844## Generating bash completions for your command
845
846Cobra 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).
847
848## Debugging
849
850Cobra provides a ‘DebugFlags’ method on a command which, when called, will print
851out everything Cobra knows about the flags for each command.
852
853### Example
854
855```go
856command.DebugFlags()
857```
858
859## Release Notes
860* **0.9.0** June 17, 2014
861  * flags can appears anywhere in the args (provided they are unambiguous)
862  * --help prints usage screen for app or command
863  * Prefix matching for commands
864  * Cleaner looking help and usage output
865  * Extensive test suite
866* **0.8.0** Nov 5, 2013
867  * Reworked interface to remove commander completely
868  * Command now primary structure
869  * No initialization needed
870  * Usage & Help templates & functions definable at any level
871  * Updated Readme
872* **0.7.0** Sept 24, 2013
873  * Needs more eyes
874  * Test suite
875  * Support for automatic error messages
876  * Support for help command
877  * Support for printing to any io.Writer instead of os.Stderr
878  * Support for persistent flags which cascade down tree
879  * Ready for integration into Hugo
880* **0.1.0** Sept 3, 2013
881  * Implement first draft
882
883## Extensions
884
885Libraries for extending Cobra:
886
887* [cmdns](https://github.com/gosuri/cmdns): Enables name spacing a command's immediate children. It provides an alternative way to structure subcommands, similar to `heroku apps:create` and `ovrclk clusters:launch`.
888
889## ToDo
890* Launch proper documentation site
891
892## Contributing
893
8941. Fork it
8952. Create your feature branch (`git checkout -b my-new-feature`)
8963. Commit your changes (`git commit -am 'Add some feature'`)
8974. Push to the branch (`git push origin my-new-feature`)
8985. Create new Pull Request
899
900## Contributors
901
902Names in no particular order:
903
904* [spf13](https://github.com/spf13),
905[eparis](https://github.com/eparis),
906[bep](https://github.com/bep), and many more!
907
908## License
909
910Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
911
912
913[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
914