Skip to content
Myr

Copyedit README.md

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Anthony Fok · committed by Anthony Fok · parent f06ae19 · Browse files · 1 file+198 added−120 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+198 added−120 removed

  • other:+198 added−120 removed

1 file+198 added−120 removed

modified:README.md+198 added-120 removed
15 unmodified lines
16* [ProjectAtomic (enterprise)](http://www.projectatomic.io/)17* [Parse (CLI)](https://parse.com/)181920[![Build Status](https://travis-ci.org/spf13/cobra.svg)](https://travis-ci.org/spf13/cobra)20[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) 21[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra)2223![cobra](https://cloud.githubusercontent.com/assets/173412/10911369/84832a8e-8212-11e5-9f82-cc96660a4794.gif)2425## Overview
1 unmodified line
27Cobra is a library providing a simple interface to create powerful modern CLI28interfaces similar to git & go tools.2930Cobra is also an application that will generate your application scaffolding to rapidly30develop a Cobra based application.31develop a Cobra-based application.3233Cobra provides:33* Easy sub-command based CLIs: `app server`, `app fetch`, etc.34* Fully posix compliant flags (including short & long versions)35* Nested sub commands34* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.35* Fully POSIX-compliant flags (including short & long versions)36* Nested subcommands37* Global, local and cascading flags38* Easy generation of applications & commands with `cobra create appname` & `cobra add cmdname`38* Intelligent suggestions (`app srver`.. did you mean `app server`)39* Intelligent suggestions (`app srver`... did you mean `app server`?)40* Automatic help generation for commands and flags41* Automatic detailed help for `app help [command]`42* Automatic help flag recognition of `-h`, `--help`, etc.43* Automatically generated bash autocomplete for your application44* Automatically generated man pages for your application45* Command aliases so you can change things without breaking them45* The flexibilty to define your own help, usage, etc46* Optional tight integration with [viper](http://github.com/spf13/viper) for 12 factor apps46* The flexibilty to define your own help, usage, etc.47* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps4849Cobra has an exceptionally clean interface and simple design without needless50constructors or initialization methods.5151Applications built with Cobra commands are designed to be as user friendly as52Applications built with Cobra commands are designed to be as user-friendly as53possible. Flags can be placed before or after the command (as long as a54confusing space isn’t provided). Both short and long flags can be used. A55command need not even be fully typed. The shortest unambiguous string will56suffice. Help is automatically generated and available for the application or56for a specific command using either the help command or the --help flag.57for a specific command using either the help command or the `--help` flag.5859## Concepts6061Cobra is built on a structure of commands & flags.6263**Commands** represent actions and **Flags** are modifiers for those actions.6464In the following example 'server' is a command and 'port' is a flag.65In the following example, 'server' is a command, and 'port' is a flag:6666 hugo server --port=131367 > hugo server --port=13136869### Commands7071Command is the central point of the application. Each interaction that72the application supports will be contained in a Command. A command can73have children commands and optionally run an action.7474In the example above 'server' is the command75In the example above, 'server' is the command.7677A Command has the following structure:7879```go78 type Command struct {79 Use string // The one-line usage message.80 Short string // The short description shown in the 'help' output.81 Long string // The long message shown in the 'help <this-command>' output.82 Run func(cmd *Command, args []string) // Run runs the command.83 }80type Command struct {81 Use string // The one-line usage message.82 Short string // The short description shown in the 'help' output.83 Long string // The long message shown in the 'help <this-command>' output.84 Run func(cmd *Command, args []string) // Run runs the command.85}86```8788### Flags8987A Flag is a way to modify the behavior of an command. Cobra supports88fully posix compliant flags as well as the go flag package.90A Flag is a way to modify the behavior of a command. Cobra supports91fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).92A Cobra command can define flags that persist through to children commands93and flags that are only available to that command.9492In the example above 'port' is the flag.95In the example above, 'port' is the flag.9697Flag functionality is provided by the [pflag98library](https://github.com/ogier/pflag), a fork of the flag standard library96which maintains the same interface while adding posix compliance.99which maintains the same interface while adding POSIX compliance.100101## Usage102103Cobra works by creating a set of commands and then organizing them into a tree.104The tree defines the structure of the application.105103Once each command is defined with it's corresponding flags, then the106Once each command is defined with its corresponding flags, then the107tree is assigned to the commander which is finally executed.108109### Installing107Using Cobra is easy. First use go get to install the latest version108of the library.110Using Cobra is easy. First, use `go get` to install the latest version111of the library:112110 $ go get github.com/spf13/cobra113 > go get -v github.com/spf13/cobra114112Next include cobra in your application.115Next, include Cobra in your application:116117```go114 import "github.com/spf13/cobra"118import "github.com/spf13/cobra"119```120121### Create the root command122123The root command represents your binary itself.
30 unmodified lines
154155### Attach command to its parent156In this example we are attaching it to the root, but commands can be attached at any level.157158```go153 HugoCmd.AddCommand(versionCmd)159HugoCmd.AddCommand(versionCmd)160```161162### Assign flags to a command163164Since the flags are defined and used in different locations, we need to165define a variable outside with the correct scope to assign the flag to166work with.167168```go161 var Verbose bool162 var Source string169var Verbose bool170var Source string171```172173There are two different approaches to assign a flag.174175#### Persistent Flags176177A flag can be 'persistent' meaning that this flag will be available to the178command it's assigned to as well as every command under that command. For170global flags assign a flag as a persistent flag on the root.179global flags, assign a flag as a persistent flag on the root.180181```go172 HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")182HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")183```184185#### Local Flags186187A flag can also be assigned locally which will only apply to that specific command.188189```go178 HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")190HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")191```192193### Remove a command from its parent194182Removing a command is not a common action in simple programs but it allows 3rd parties to customize an existing command tree.195Removing a command is not a common action in simple programs, but it allows 3rd parties to customize an existing command tree.196184In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it by our own version.197In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it with our own version:198199```go186 mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)187 mainlib.RootCmd.AddCommand(versionCmd)200mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)201mainlib.RootCmd.AddCommand(versionCmd)202```203204### Once all commands and flags are defined, Execute the commands205206Execute should be run on the root for clarity, though it can be called on any command.207208```go193 HugoCmd.Execute()209HugoCmd.Execute()210```211212## Example213197In the example below we have defined three commands. Two are at the top level214In the example below, we have defined three commands. Two are at the top level215and one (cmdTimes) is a child of one of the top commands. In this case the root216is not executable meaning that a subcommand is required. This is accomplished217by not providing a 'Run' for the 'rootCmd'.218219We have only defined one flag for a single command.220221More documentation about flags is available at https://github.com/spf13/pflag222223```go224package main225226import (
48 unmodified lines
275 cmdEcho.AddCommand(cmdTimes)276 rootCmd.Execute()277}278```261For a more complete example of a larger application, please checkout [Hugo](http://hugo.spf13.com)279280For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).281282## The Help Command283284Cobra automatically adds a help command to your application when you have subcommands.266This will be called when a user runs 'app help'. Additionally help will also267support all other commands as input. Say for instance you have a command called268'create' without any additional configuration cobra will work when 'app help285This will be called when a user runs 'app help'. Additionally, help will also286support all other commands as input. Say, for instance, you have a command called287'create' without any additional configuration; Cobra will work when 'app help288create' is called. Every command will automatically have the '--help' flag added.289290### Example291273The following output is automatically generated by cobra. Nothing beyond the292The following output is automatically generated by Cobra. Nothing beyond the293command and flag definitions are needed.294295 > hugo help277278 A Fast and Flexible Static Site Generator built with279 love by spf13 and friends in Go.280281 Complete documentation is available at http://hugo.spf13.com282296 297 hugo is the main command, used to build your Hugo site.298 299 Hugo is a Fast and Flexible Static Site Generator300 built with love by spf13 and friends in Go.301 302 Complete documentation is available at http://gohugo.io/.303 304 Usage:305 hugo [flags]306 hugo [command]286307 308 Available Commands:288 server :: Hugo runs it's own a webserver to render the files289 version :: Print the version number of Hugo290 check :: Check content in the source directory291 benchmark :: Benchmark hugo by building a site a number of times292 help [command] :: Help about any command293294 Available Flags:295 -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/296 -D, --build-drafts=false: include content marked as draft309 server Hugo runs its own webserver to render the files310 version Print the version number of Hugo311 config Print the site configuration312 check Check content in the source directory313 benchmark Benchmark hugo by building a site a number of times.314 convert Convert your content to different formats315 new Create new content for your site316 list Listing out various types of content317 undraft Undraft changes the content's draft status from 'True' to 'False'318 genautocomplete Generate shell autocompletion script for Hugo319 gendoc Generate Markdown documentation for the Hugo CLI.320 genman Generate man page for Hugo321 import Import your site from others.322 323 Flags:324 -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/325 -D, --buildDrafts[=false]: include content marked as draft326 -F, --buildFuture[=false]: include content with publishdate in the future327 --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/328 --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL329 --config="": config file (default is path/config.yaml|json|toml)330 -d, --destination="": filesystem path to write files to331 --disableRSS[=false]: Do not build RSS files332 --disableSitemap[=false]: Do not build Sitemap file333 --editor="": edit new content with this editor, if provided334 --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it335 --log[=false]: Enable Logging336 --logFile="": Log File path (if set, logging enabled automatically)337 --noTimes[=false]: Don't sync modification time of files338 --pluralizeListTitles[=true]: Pluralize titles in lists using inflect339 --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")340 -s, --source="": filesystem path to read files relative from300 --stepAnalysis=false: display memory and timing of different steps of the program301 --uglyurls=false: if true, use /filename.html instead of /filename/302 -v, --verbose=false: verbose output303 -w, --watch=false: watch filesystem for changes and recreate as needed341 --stepAnalysis[=false]: display memory and timing of different steps of the program342 -t, --theme="": theme to use (located in /themes/THEMENAME/)343 --uglyURLs[=false]: if true, use /filename.html instead of /filename/344 -v, --verbose[=false]: verbose output345 --verboseLog[=false]: verbose logging346 -w, --watch[=false]: watch filesystem for changes and recreate as needed347 348 Use "hugo [command] --help" for more information about a command.349305 Use "hugo help [command]" for more information about that command.350307308351Help is just a command like any other. There is no special logic or behavior310around it. In fact you can provide your own if you want.352around it. In fact, you can provide your own if you want.353354### Defining your own help355356You can provide your own Help command or you own template for the default command to use.
14 unmodified lines
371 c.AddCommand(c.helpCommand)372}373```374333You can provide your own command, function or template through the following methods.375You can provide your own command, function or template through the following methods:376377```go335 command.SetHelpCommand(cmd *Command)378command.SetHelpCommand(cmd *Command)379337 command.SetHelpFunc(f func(*Command, []string))380command.SetHelpFunc(f func(*Command, []string))381339 command.SetHelpTemplate(s string)382command.SetHelpTemplate(s string)383```384385The latter two will also apply to any children commands.386387## Usage388345When the user provides an invalid flag or invalid command Cobra responds by346showing the user the 'usage'389When the user provides an invalid flag or invalid command, Cobra responds by390showing the user the 'usage'.391392### Example393You may recognize this from the help above. That's because the default help350embeds the usage as part of it's output.394embeds the usage as part of its output.395396 Usage:397 hugo [flags]398 hugo [command]355399 400 Available Commands:357 server Hugo runs it's own a webserver to render the files401 server Hugo runs its own webserver to render the files402 version Print the version number of Hugo403 config Print the site configuration404 check Check content in the source directory360 benchmark Benchmark hugo by building a site a number of times361 help [command] Help about any command362363 Available Flags:364 -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/365 -D, --build-drafts=false: include content marked as draft405 benchmark Benchmark hugo by building a site a number of times.406 convert Convert your content to different formats407 new Create new content for your site408 list Listing out various types of content409 undraft Undraft changes the content's draft status from 'True' to 'False'410 genautocomplete Generate shell autocompletion script for Hugo411 gendoc Generate Markdown documentation for the Hugo CLI.412 genman Generate man page for Hugo413 import Import your site from others.414 415 Flags:416 -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/417 -D, --buildDrafts[=false]: include content marked as draft418 -F, --buildFuture[=false]: include content with publishdate in the future419 --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/420 --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL421 --config="": config file (default is path/config.yaml|json|toml)422 -d, --destination="": filesystem path to write files to423 --disableRSS[=false]: Do not build RSS files424 --disableSitemap[=false]: Do not build Sitemap file425 --editor="": edit new content with this editor, if provided426 --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it427 --log[=false]: Enable Logging428 --logFile="": Log File path (if set, logging enabled automatically)429 --noTimes[=false]: Don't sync modification time of files430 --pluralizeListTitles[=true]: Pluralize titles in lists using inflect431 --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")432 -s, --source="": filesystem path to read files relative from369 --stepAnalysis=false: display memory and timing of different steps of the program370 --uglyurls=false: if true, use /filename.html instead of /filename/371 -v, --verbose=false: verbose output372 -w, --watch=false: watch filesystem for changes and recreate as needed433 --stepAnalysis[=false]: display memory and timing of different steps of the program434 -t, --theme="": theme to use (located in /themes/THEMENAME/)435 --uglyURLs[=false]: if true, use /filename.html instead of /filename/436 -v, --verbose[=false]: verbose output437 --verboseLog[=false]: verbose logging438 -w, --watch[=false]: watch filesystem for changes and recreate as needed439440### Defining your own usage375You can provide your own usage function or template for cobra to use.441You can provide your own usage function or template for Cobra to use.442377The default usage function is443The default usage function is:444445```go379 return func(c *Command) error {380 err := tmpl(c.Out(), c.UsageTemplate(), c)381 return err382 }446return func(c *Command) error {447 err := tmpl(c.Out(), c.UsageTemplate(), c)448 return err449}450```451384Like help the function and template are over ridable through public methods.452Like help, the function and template are overridable through public methods:453454```go386 command.SetUsageFunc(f func(*Command) error)455command.SetUsageFunc(f func(*Command) error)456388 command.SetUsageTemplate(s string)457command.SetUsageTemplate(s string)458```459460## PreRun or PostRun Hooks461462It 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 inherrited by children if they do not declare their own. These function are run in the following order:
3 unmodified lines
466- `Run`467- `PostRun`468- `PersistentPostRun`469400And example of two commands which use all of these features is below. When the subcommand in executed it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`470An 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`:471472```go473package main474
26 unmodified lines
501 }502503 var subCmd = &cobra.Command{504 Use: "sub [no options!]",435 Short: "My sub command",505 Short: "My subcommand",506 PreRun: func(cmd *cobra.Command, args []string) {507 fmt.Printf("Inside subCmd PreRun with args: %v\n", args)508 },509 Run: func(cmd *cobra.Command, args []string) {
19 unmodified lines
529530531## Alternative Error Handling532463Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, providing a way to handle the errors in one location. The current list of functions that return an error is:533Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, providing a way to handle the errors in one location. The current list of functions that return an error is:534535* PersistentPreRunE536* PreRunE537* RunE
32 unmodified lines
570```571572## Suggestions when "unknown command" happens573504Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behavior similarly to the `git` command when a typo happens. For example:574Cobra 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:575576```577$ hugo srever508unknown command "srever" for "hugo"578Error: unknown command "srever" for "hugo"579580Did you mean this?511 server581 server582583Run 'hugo --help' for usage.584```585516Suggestions are automatic based on every subcommand registered and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.586Suggestions 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.587588If you need to disable suggestions or tweak the string distance in your command, use:589590```go520 command.DisableSuggestions = true591command.DisableSuggestions = true592```593594or595596```go524 command.SuggestionsMinimumDistance = 1597command.SuggestionsMinimumDistance = 1598```599600You 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:601602```529$ hugo delete530unknown command "delete" for "hugo"603$ kubectl remove604Error: unknown command "remove" for "kubectl"605606Did you mean this?533 remove607 delete608535Run 'hugo --help' for usage.609Run 'kubectl help' for usage.610```611538## Generating markdown formatted documentation for your command612## Generating Markdown-formatted documentation for your command613540Cobra 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](md_docs.md)614Cobra 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](md_docs.md).615616## Generating man pages for your command617544Cobra 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](man_docs.md)618Cobra 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](man_docs.md).619620## Generating bash completions for your command621548Cobra can generate a bash completions file. If you add more information to your command these completions can be amazingly powerful and flexible. Read more about [Bash Completions](bash_completions.md)622Cobra 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).623624## Debugging625552Cobra provides a ‘DebugFlags’ method on a command which when called will print553out everything Cobra knows about the flags for each command626Cobra provides a ‘DebugFlags’ method on a command which, when called, will print627out everything Cobra knows about the flags for each command.628629### Example630631```go557 command.DebugFlags()632command.DebugFlags()633```634635## Release Notes636* **0.9.0** June 17, 2014637 * flags can appears anywhere in the args (provided they are unambiguous)
21 unmodified lines
659## Extensions660661Libraries for extending Cobra:662587* [cmdns](https://github.com/gosuri/cmdns): Enables name spacing a command's immediate children. It provides an alternative way to structure sub commands, similar to `heroku apps:create` and `ovrclk clusters:launch`.663* [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`.664665## ToDo666* Launch proper documentation site667
8 unmodified lines
676## Contributors677678Names in no particular order:679604* [spf13](https://github.com/spf13)680* [spf13](https://github.com/spf13), 681[eparis](https://github.com/eparis), 682[bep](https://github.com/bep), ...683684## License685686Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
3 unmodified lines