1 ![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) |
1 ![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) |
2 |
2 |
3 Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. |
3 Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. |
4 |
4 |
5 Many of the most widely used Go projects are built using Cobra, such as: |
5 Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/), |
6 [Kubernetes](http://kubernetes.io/), |
6 [Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to |
7 [Hugo](http://gohugo.io), |
7 name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. |
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), |
|
26 [Gardener](https://github.com/gardener/gardenctl), |
|
27 etc. |
|
28 |
8 |
29 [![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) |
9 [![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) |
30 [![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra) |
|
31 [![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) |
10 [![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) |
|
11 [![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) |
|
12 [![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) |
32 |
13 |
33 # Table of Contents |
14 # Table of Contents |
34 |
15 |
35 - [Overview](#overview) |
16 - [Overview](#overview) |
36 - [Concepts](#concepts) |
17 - [Concepts](#concepts) |
37 * [Commands](#commands) |
18 * [Commands](#commands) |
38 * [Flags](#flags) |
19 * [Flags](#flags) |
39 - [Installing](#installing) |
20 - [Installing](#installing) |
40 - [Getting Started](#getting-started) |
21 - [Usage](#usage) |
41 * [Using the Cobra Generator](#using-the-cobra-generator) |
22 * [Using the Cobra Generator](user_guide.md#using-the-cobra-generator) |
42 * [Using the Cobra Library](#using-the-cobra-library) |
23 * [Using the Cobra Library](user_guide.md#using-the-cobra-library) |
43 * [Working with Flags](#working-with-flags) |
24 * [Working with Flags](user_guide.md#working-with-flags) |
44 * [Positional and Custom Arguments](#positional-and-custom-arguments) |
25 * [Positional and Custom Arguments](user_guide.md#positional-and-custom-arguments) |
45 * [Example](#example) |
26 * [Example](user_guide.md#example) |
46 * [Help Command](#help-command) |
27 * [Help Command](user_guide.md#help-command) |
47 * [Usage Message](#usage-message) |
28 * [Usage Message](user_guide.md#usage-message) |
48 * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks) |
29 * [PreRun and PostRun Hooks](user_guide.md#prerun-and-postrun-hooks) |
49 * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens) |
30 * [Suggestions when "unknown command" happens](user_guide.md#suggestions-when-unknown-command-happens) |
50 * [Generating documentation for your command](#generating-documentation-for-your-command) |
31 * [Generating documentation for your command](user_guide.md#generating-documentation-for-your-command) |
51 * [Generating bash completions](#generating-bash-completions) |
32 * [Generating shell completions](user_guide.md#generating-shell-completions) |
52 * [Generating zsh completions](#generating-zsh-completions) |
33 - [Contributing](CONTRIBUTING.md) |
53 - [Contributing](#contributing) |
|
54 - [License](#license) |
34 - [License](#license) |
55 |
35 |
56 # Overview |
36 # Overview |
57 |
37 |
58 Cobra is a library providing a simple interface to create powerful modern CLI |
38 Cobra is a library providing a simple interface to create powerful modern CLI |
126 # Installing |
106 # Installing |
127 Using Cobra is easy. First, use `go get` to install the latest version |
107 Using Cobra is easy. First, use `go get` to install the latest version |
128 of the library. This command will install the `cobra` generator executable |
108 of the library. This command will install the `cobra` generator executable |
129 along with the library and its dependencies: |
109 along with the library and its dependencies: |
130 |
110 |
131 go get -u github.com/spf13/cobra/cobra |
111 go get -u github.com/spf13/cobra |
132 |
112 |
133 Next, include Cobra in your application: |
113 Next, include Cobra in your application: |
134 |
114 |
135 ```go |
115 ```go |
136 import "github.com/spf13/cobra" |
116 import "github.com/spf13/cobra" |
137 ``` |
117 ``` |
138 |
118 |
139 # Getting Started |
119 # Usage |
140 |
120 |
141 While you are welcome to provide your own organization, typically a Cobra-based |
121 See [User Guide](user_guide.md). |
142 application will follow the following organizational structure: |
|
143 |
|
144 ``` |
|
145 ▾ appName/ |
|
146 ▾ cmd/ |
|
147 add.go |
|
148 your.go |
|
149 commands.go |
|
150 here.go |
|
151 main.go |
|
152 ``` |
|
153 |
|
154 In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. |
|
155 |
|
156 ```go |
|
157 package main |
|
158 |
|
159 import ( |
|
160 "{pathToYourApp}/cmd" |
|
161 ) |
|
162 |
|
163 func main() { |
|
164 cmd.Execute() |
|
165 } |
|
166 ``` |
|
167 |
|
168 ## Using the Cobra Generator |
|
169 |
|
170 Cobra provides its own program that will create your application and add any |
|
171 commands you want. It's the easiest way to incorporate Cobra into your application. |
|
172 |
|
173 [Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. |
|
174 |
|
175 ## Using the Cobra Library |
|
176 |
|
177 To manually implement Cobra you need to create a bare main.go file and a rootCmd file. |
|
178 You will optionally provide additional commands as you see fit. |
|
179 |
|
180 ### Create rootCmd |
|
181 |
|
182 Cobra doesn't require any special constructors. Simply create your commands. |
|
183 |
|
184 Ideally you place this in app/cmd/root.go: |
|
185 |
|
186 ```go |
|
187 var rootCmd = &cobra.Command{ |
|
188 Use: "hugo", |
|
189 Short: "Hugo is a very fast static site generator", |
|
190 Long: `A Fast and Flexible Static Site Generator built with |
|
191 love by spf13 and friends in Go. |
|
192 Complete documentation is available at http://hugo.spf13.com`, |
|
193 Run: func(cmd *cobra.Command, args []string) { |
|
194 // Do Stuff Here |
|
195 }, |
|
196 } |
|
197 |
|
198 func Execute() { |
|
199 if err := rootCmd.Execute(); err != nil { |
|
200 fmt.Println(err) |
|
201 os.Exit(1) |
|
202 } |
|
203 } |
|
204 ``` |
|
205 |
|
206 You will additionally define flags and handle configuration in your init() function. |
|
207 |
|
208 For example cmd/root.go: |
|
209 |
|
210 ```go |
|
211 import ( |
|
212 "fmt" |
|
213 "os" |
|
214 |
|
215 homedir "github.com/mitchellh/go-homedir" |
|
216 "github.com/spf13/cobra" |
|
217 "github.com/spf13/viper" |
|
218 ) |
|
219 |
|
220 func init() { |
|
221 cobra.OnInitialize(initConfig) |
|
222 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") |
|
223 rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/") |
|
224 rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution") |
|
225 rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)") |
|
226 rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration") |
|
227 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) |
|
228 viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase")) |
|
229 viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) |
|
230 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>") |
|
231 viper.SetDefault("license", "apache") |
|
232 } |
|
233 |
|
234 func initConfig() { |
|
235 // Don't forget to read config either from cfgFile or from home directory! |
|
236 if cfgFile != "" { |
|
237 // Use config file from the flag. |
|
238 viper.SetConfigFile(cfgFile) |
|
239 } else { |
|
240 // Find home directory. |
|
241 home, err := homedir.Dir() |
|
242 if err != nil { |
|
243 fmt.Println(err) |
|
244 os.Exit(1) |
|
245 } |
|
246 |
|
247 // Search config in home directory with name ".cobra" (without extension). |
|
248 viper.AddConfigPath(home) |
|
249 viper.SetConfigName(".cobra") |
|
250 } |
|
251 |
|
252 if err := viper.ReadInConfig(); err != nil { |
|
253 fmt.Println("Can't read config:", err) |
|
254 os.Exit(1) |
|
255 } |
|
256 } |
|
257 ``` |
|
258 |
|
259 ### Create your main.go |
|
260 |
|
261 With the root command you need to have your main function execute it. |
|
262 Execute should be run on the root for clarity, though it can be called on any command. |
|
263 |
|
264 In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra. |
|
265 |
|
266 ```go |
|
267 package main |
|
268 |
|
269 import ( |
|
270 "{pathToYourApp}/cmd" |
|
271 ) |
|
272 |
|
273 func main() { |
|
274 cmd.Execute() |
|
275 } |
|
276 ``` |
|
277 |
|
278 ### Create additional commands |
|
279 |
|
280 Additional commands can be defined and typically are each given their own file |
|
281 inside of the cmd/ directory. |
|
282 |
|
283 If you wanted to create a version command you would create cmd/version.go and |
|
284 populate it with the following: |
|
285 |
|
286 ```go |
|
287 package cmd |
|
288 |
|
289 import ( |
|
290 "fmt" |
|
291 |
|
292 "github.com/spf13/cobra" |
|
293 ) |
|
294 |
|
295 func init() { |
|
296 rootCmd.AddCommand(versionCmd) |
|
297 } |
|
298 |
|
299 var versionCmd = &cobra.Command{ |
|
300 Use: "version", |
|
301 Short: "Print the version number of Hugo", |
|
302 Long: `All software has versions. This is Hugo's`, |
|
303 Run: func(cmd *cobra.Command, args []string) { |
|
304 fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") |
|
305 }, |
|
306 } |
|
307 ``` |
|
308 |
|
309 ## Working with Flags |
|
310 |
|
311 Flags provide modifiers to control how the action command operates. |
|
312 |
|
313 ### Assign flags to a command |
|
314 |
|
315 Since the flags are defined and used in different locations, we need to |
|
316 define a variable outside with the correct scope to assign the flag to |
|
317 work with. |
|
318 |
|
319 ```go |
|
320 var Verbose bool |
|
321 var Source string |
|
322 ``` |
|
323 |
|
324 There are two different approaches to assign a flag. |
|
325 |
|
326 ### Persistent Flags |
|
327 |
|
328 A flag can be 'persistent' meaning that this flag will be available to the |
|
329 command it's assigned to as well as every command under that command. For |
|
330 global flags, assign a flag as a persistent flag on the root. |
|
331 |
|
332 ```go |
|
333 rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") |
|
334 ``` |
|
335 |
|
336 ### Local Flags |
|
337 |
|
338 A flag can also be assigned locally which will only apply to that specific command. |
|
339 |
|
340 ```go |
|
341 localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") |
|
342 ``` |
|
343 |
|
344 ### Local Flag on Parent Commands |
|
345 |
|
346 By default Cobra only parses local flags on the target command, any local flags on |
|
347 parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will |
|
348 parse local flags on each command before executing the target command. |
|
349 |
|
350 ```go |
|
351 command := cobra.Command{ |
|
352 Use: "print [OPTIONS] [COMMANDS]", |
|
353 TraverseChildren: true, |
|
354 } |
|
355 ``` |
|
356 |
|
357 ### Bind Flags with Config |
|
358 |
|
359 You can also bind your flags with [viper](https://github.com/spf13/viper): |
|
360 ```go |
|
361 var author string |
|
362 |
|
363 func init() { |
|
364 rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") |
|
365 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) |
|
366 } |
|
367 ``` |
|
368 |
|
369 In this example the persistent flag `author` is bound with `viper`. |
|
370 **Note**, that the variable `author` will not be set to the value from config, |
|
371 when the `--author` flag is not provided by user. |
|
372 |
|
373 More in [viper documentation](https://github.com/spf13/viper#working-with-flags). |
|
374 |
|
375 ### Required flags |
|
376 |
|
377 Flags are optional by default. If instead you wish your command to report an error |
|
378 when a flag has not been set, mark it as required: |
|
379 ```go |
|
380 rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") |
|
381 rootCmd.MarkFlagRequired("region") |
|
382 ``` |
|
383 |
|
384 ## Positional and Custom Arguments |
|
385 |
|
386 Validation of positional arguments can be specified using the `Args` field |
|
387 of `Command`. |
|
388 |
|
389 The following validators are built in: |
|
390 |
|
391 - `NoArgs` - the command will report an error if there are any positional args. |
|
392 - `ArbitraryArgs` - the command will accept any args. |
|
393 - `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. |
|
394 - `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. |
|
395 - `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. |
|
396 - `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. |
|
397 - `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` |
|
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 |
|
400 An example of setting the custom validator: |
|
401 |
|
402 ```go |
|
403 var 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 a color argument") |
|
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 |
|
422 In the example below, we have defined three commands. Two are at the top level |
|
423 and one (cmdTimes) is a child of one of the top commands. In this case the root |
|
424 is not executable meaning that a subcommand is required. This is accomplished |
|
425 by not providing a 'Run' for the 'rootCmd'. |
|
426 |
|
427 We have only defined one flag for a single command. |
|
428 |
|
429 More documentation about flags is available at https://github.com/spf13/pflag |
|
430 |
|
431 ```go |
|
432 package main |
|
433 |
|
434 import ( |
|
435 "fmt" |
|
436 "strings" |
|
437 |
|
438 "github.com/spf13/cobra" |
|
439 ) |
|
440 |
|
441 func 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. |
|
448 For 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. |
|
459 Echo 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 [string to echo]", |
|
468 Short: "Echo anything to the screen more times", |
|
469 Long: `echo things multiple times back to the user by providing |
|
470 a 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 |
|
488 For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). |
|
489 |
|
490 ## Help Command |
|
491 |
|
492 Cobra automatically adds a help command to your application when you have subcommands. |
|
493 This will be called when a user runs 'app help'. Additionally, help will also |
|
494 support 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 |
|
496 create' is called. Every command will automatically have the '--help' flag added. |
|
497 |
|
498 ### Example |
|
499 |
|
500 The following output is automatically generated by Cobra. Nothing beyond the |
|
501 command 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 |
|
527 Help is just a command like any other. There is no special logic or behavior |
|
528 around it. In fact, you can provide your own if you want. |
|
529 |
|
530 ### Defining your own help |
|
531 |
|
532 You can provide your own Help command or your own template for the default command to use |
|
533 with following functions: |
|
534 |
|
535 ```go |
|
536 cmd.SetHelpCommand(cmd *Command) |
|
537 cmd.SetHelpFunc(f func(*Command, []string)) |
|
538 cmd.SetHelpTemplate(s string) |
|
539 ``` |
|
540 |
|
541 The latter two will also apply to any children commands. |
|
542 |
|
543 ## Usage Message |
|
544 |
|
545 When the user provides an invalid flag or invalid command, Cobra responds by |
|
546 showing the user the 'usage'. |
|
547 |
|
548 ### Example |
|
549 You may recognize this from the help above. That's because the default help |
|
550 embeds 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 |
|
572 You can provide your own usage function or template for Cobra to use. |
|
573 Like help, the function and template are overridable through public methods: |
|
574 |
|
575 ```go |
|
576 cmd.SetUsageFunc(f func(*Command) error) |
|
577 cmd.SetUsageTemplate(s string) |
|
578 ``` |
|
579 |
|
580 ## Version Flag |
|
581 |
|
582 Cobra adds a top-level '--version' flag if the Version field is set on the root command. |
|
583 Running an application with the '--version' flag will print the version to stdout using |
|
584 the version template. The template can be customized using the |
|
585 `cmd.SetVersionTemplate(s string)` function. |
|
586 |
|
587 ## PreRun and PostRun Hooks |
|
588 |
|
589 It 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 |
|
597 An 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 |
|
600 package main |
|
601 |
|
602 import ( |
|
603 "fmt" |
|
604 |
|
605 "github.com/spf13/cobra" |
|
606 ) |
|
607 |
|
608 func 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 |
|
657 Output: |
|
658 ``` |
|
659 Inside rootCmd PersistentPreRun with args: [] |
|
660 Inside rootCmd PreRun with args: [] |
|
661 Inside rootCmd Run with args: [] |
|
662 Inside rootCmd PostRun with args: [] |
|
663 Inside rootCmd PersistentPostRun with args: [] |
|
664 |
|
665 Inside rootCmd PersistentPreRun with args: [arg1 arg2] |
|
666 Inside subCmd PreRun with args: [arg1 arg2] |
|
667 Inside subCmd Run with args: [arg1 arg2] |
|
668 Inside subCmd PostRun with args: [arg1 arg2] |
|
669 Inside subCmd PersistentPostRun with args: [arg1 arg2] |
|
670 ``` |
|
671 |
|
672 ## Suggestions when "unknown command" happens |
|
673 |
|
674 Cobra 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 |
|
678 Error: unknown command "srever" for "hugo" |
|
679 |
|
680 Did you mean this? |
|
681 server |
|
682 |
|
683 Run 'hugo --help' for usage. |
|
684 ``` |
|
685 |
|
686 Suggestions 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 |
|
688 If you need to disable suggestions or tweak the string distance in your command, use: |
|
689 |
|
690 ```go |
|
691 command.DisableSuggestions = true |
|
692 ``` |
|
693 |
|
694 or |
|
695 |
|
696 ```go |
|
697 command.SuggestionsMinimumDistance = 1 |
|
698 ``` |
|
699 |
|
700 You 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 |
|
704 Error: unknown command "remove" for "kubectl" |
|
705 |
|
706 Did you mean this? |
|
707 delete |
|
708 |
|
709 Run 'kubectl help' for usage. |
|
710 ``` |
|
711 |
|
712 ## Generating documentation for your command |
|
713 |
|
714 Cobra 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 |
|
722 Cobra 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 ## Generating zsh completions |
|
725 |
|
726 Cobra can generate zsh-completion file. Read more about it in |
|
727 [Zsh Completions](zsh_completions.md). |
|
728 |
|
729 # Contributing |
|
730 |
|
731 1. Fork it |
|
732 2. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) |
|
733 3. Create your feature branch (`git checkout -b my-new-feature`) |
|
734 4. Make changes and add them (`git add .`) |
|
735 5. Commit your changes (`git commit -m 'Add some feature'`) |
|
736 6. Push to the branch (`git push origin my-new-feature`) |
|
737 7. Create new pull request |
|
738 |
122 |
739 # License |
123 # License |
740 |
124 |
741 Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) |
125 Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) |