Skip to content
Myr

Rewrote readme

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

authored by spf13 · committed by spf13 · parent 79bdde5 · Browse files · 1 file+242 added−35 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+242 added−35 removed

  • other:+242 added−35 removed

1 file+242 added−35 removed

modified:README.md+242 added-35 removed
3 unmodified lines
45[![Build Status](https://travis-ci.org/spf13/cobra.png)](https://travis-ci.org/spf13/cobra)67## Overview8Cobra provides a simple interface to create powerful modern CLI9interfaces similar to git & go tools.811Cobra was inspired by go, go-Commander, gh and subcommand9Cobra is a commander providing a simple interface to create powerful modern CLI10interfaces similar to git & go tools. In addition to providing an iterface, Cobra11simultaneously provides a controller to organize your application code.1213Inspired by go, go-Commander, gh and subcommand, Cobra improves on these by14providing **fully posix compliant flags** (including short & long versions),15**nesting commands**, and the ability to **define your own help and usage** for any or16all commands.1718Cobra has an exceptionally clean interface and simple design without needless19constructors or initialization methods.2021## Concepts2216There are 3 different core objects to become familiar with to use Cobra.17To help illustrate these 3 items better use the following as an example:23Cobra is built on a structure of commands & flags.2419 hugo server --port=131325**Commands** represent actions and **Flags** are modifiers for those actions.2621### Commander27In the following example 'server' is a command and 'port' is a flag.2823The Commander is the head of your application. It holds the configuration24for your application. It also is responsible for all global flags.29 hugo server --port=13133026In the example above 'hugo' is the commander.31### Commands322829### Command3033Command is the central point of the application. Each interaction that34the application supports will be contained in a Command. A command can35have children commands and optionally run an action.3637In the example above 'server' is the command3839A Command has the following structure:4041 type Command struct {42 Use string // The one-line usage message.43 Short string // The short description shown in the 'help' output.44 Long string // The long message shown in the 'help <this-command>' output.45 Run func(cmd *Command, args []string) // Run runs the command.46 }4748### Flags4940A flag is a way to modify the behavior of an command. Cobra supports41fully posix compliant flags as well as remaining consistent with42the go flag package. A Cobra command has can define flags that 43persist through to children commands and flags that are only available44to that command.50A Flag is a way to modify the behavior of an command. Cobra supports51fully posix compliant flags as well as the go flag package. 52A Cobra command has can define flags that persist through to children commands53and flags that are only available to that command.5455In the example above 'port' is the flag.5657Flag functionality is provided by the [pflag58libary](https://github.com/ogier/pflag), a fork of the flag standard library59which maintains the same interface while adding posix compliance.6061## Usage6250### Implementing Cobra63Cobra works by creating a set of commands and then organizing them into a tree.64The tree defines the structure of the application.6566Once each command is defined with it's corresponding flags, then the67tree is assigned to the commander which is finally executed.6869### Installing70Using Cobra is easy. First use go get to install the latest version71of the library.7273 $ go get github.com/spf13/cobra
1 unmodified line
75Next include cobra in your application.7677 import "github.com/spf13/cobra"7861Now you are ready to implement Cobra. 79### Create the root command8063Cobra works by creating a set of commands and then organizing them into a tree.64The tree defines the structure of the application.81The root command represents your binary itself.8266Once each command is defined with it's corresponding flags, then the67tree is assigned to the commander which is finally executed.83Cobra doesn't require any special constructors. Simply create your commands.8469In the example below we have defined three commands. Two are at the top70level and one (cmdTimes) is a child of one of the top commands.85 var HugoCmd = &cobra.Command{86 Use: "hugo",87 Short: "Hugo is a very fast static site generator",88 Long: `A Fast and Flexible Static Site Generator built with89 love by spf13 and friends in Go.90 Complete documentation is available at http://hugo.spf13.com`,91 Run: func(cmd *cobra.Command, args []string) {92 // Do Stuff Here93 },94 }9572We have only defined one flag for a single command.96### Create additional commands9774More documentation about flags is available at https://github.com/spf13/pflag98Additional commands can be defined.99100 var versionCmd = &cobra.Command{101 Use: "version",102 Short: "Print the version number of Hugo",103 Long: `All software has versions. This is Hugo's`,104 Run: func(cmd *cobra.Command, args []string) {105 fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")106 },107 }108109### Attach command to it's parent110In this example we are attaching it to the root, but commands can be attached at any level.111112 HugoCmd.AddCommand(versionCmd)113114### Assign flags to a command115116Since the flags are defined and used in different locations, we need to define a variable outside with the correct scope to assign the flag to work with.117118 var Verbose bool119 var Source string120121There are two different approaches to assign a flag.122123#### Persistent Flags124125A flag can be 'persistent' meaning that this flag will be available to the126command it's assigned to as well as every command under that command. For127global flags assign a flag as a persistent flag on the root.128129 HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")130131#### Local Flags132133A flag can also be assigned locally which will only apply to that specific command.134135 HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")136137### Once all commands and flags are defined, Execute the commands138139Execute should be run on the root for clarity, though it can be called on any command.140141 HugoCmd.Execute()142143## Example144145In the example below we have defined three commands. Two are at the top level146and one (cmdTimes) is a child of one of the top commands. In this case the root147is not executible meaning that a subcommand is required. This is accomplished148by not providing a 'Run' for the 'rootCmd'.149150We have only defined one flag for a single command.151152More documentation about flags is available at https://github.com/spf13/pflag153154 Import(155 "github.com/spf13/cobra"156 "fmt"157 "strings"
36 unmodified lines
194 }195 },196 }197122198 cmdTimes().Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")199125 var commander = cobra.NewCommander()126 commander.SetName("CobraExample")127 commander.AddCommand(cmdPrint, cmdEcho)200 var rootCmd = &cobra.Command{Use: "app"}201 rootCmd.AddCommand(cmdPrint, cmdEcho)202 cmdEcho.AddCommand(cmdTimes)129 commander.Execute()203 rootCmd.Execute()204 }205206For a more complete example of a larger application, please checkout [Hugo](http://hugo.spf13.com)207208## The Help Command209210Cobra automatically adds a help command to your application.211This will be called when a user runs 'app help'. Additionally help will also212support all other commands as input. Say for instance you have a command called213'create' without any additional configuration cobra will work when 'app help214create' is called.215216### Example217218The following output is automatically generated by cobra. Nothing beyond the219command and flag definitions are needed.220221 > hugo help222223 A Fast and Flexible Static Site Generator built with224 love by spf13 and friends in Go.225226 Complete documentation is available at http://hugo.spf13.com227228 Usage:229 hugo [flags]230 hugo [command]231232 Available Commands:233 server :: Hugo runs it's own a webserver to render the files234 version :: Print the version number of Hugo235 check :: Check content in the source directory236 benchmark :: Benchmark hugo by building a site a number of times237 help [command] :: Help about any command238239 Available Flags:240 -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/241 -D, --build-drafts=false: include content marked as draft242 --config="": config file (default is path/config.yaml|json|toml)243 -d, --destination="": filesystem path to write files to244 -s, --source="": filesystem path to read files relative from245 --stepAnalysis=false: display memory and timing of different steps of the program246 --uglyurls=false: if true, use /filename.html instead of /filename/247 -v, --verbose=false: verbose output248 -w, --watch=false: watch filesystem for changes and recreate as needed249250 Use "hugo help [command]" for more information about that command.251252253254Help is just a command like any other. There is no special logic or behavior255around it. In fact you can provide your own if you want.256257### Defining your own help258259You can provide your own Help command or you own template for the default command to use.260261The default help command is 262263 func (c *Command) initHelp() {264 if c.helpCommand == nil {265 c.helpCommand = &Command{266 Use: "help [command]",267 Short: "Help about any command",268 Long: `Help provides help for any command in the application.269 Simply type ` + c.Name() + ` help [path to command] for full details.`,270 Run: c.HelpFunc(),271 }272 }273 c.AddCommand(c.helpCommand)274 }275276You can provide your own command, function or template through the following methods.277278 command.SetHelpCommand(cmd *Command)279280 command.SetHelpFunc(f func(*Command, []string))281282 command.SetHelpTemplate(s string)283284The latter two will also apply to any children commands.285286287## Usage288289When the user provides an invalid flag or invalid command Cobra responds by290showing the user the 'usage'291292### Example293You may recognize this from the help above. That's because the default help 294embeds the usage as part of it's output.295296 Usage:297 hugo [flags]298 hugo [command]299300 Available Commands:301 server :: Hugo runs it's own a webserver to render the files302 version :: Print the version number of Hugo303 check :: Check content in the source directory304 benchmark :: Benchmark hugo by building a site a number of times305 help [command] :: Help about any command306307 Available Flags:308 -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/309 -D, --build-drafts=false: include content marked as draft310 --config="": config file (default is path/config.yaml|json|toml)311 -d, --destination="": filesystem path to write files to312 -s, --source="": filesystem path to read files relative from313 --stepAnalysis=false: display memory and timing of different steps of the program314 --uglyurls=false: if true, use /filename.html instead of /filename/315 -v, --verbose=false: verbose output316 -w, --watch=false: watch filesystem for changes and recreate as needed317318### Defining your own usage319You can provide your own usage function or template for cobra to use.320321The default usage function is322323 return func(c *Command) error {324 err := tmpl(c.Out(), c.UsageTemplate(), c)325 return err326 }327328Like help the function and template are over ridable through public methods.329330 command.SetUsageFunc(f func(*Command) error)331332 command.SetUsageTemplate(s string)333334335## Release Notes336* **0.8.0** Nov 5, 2013337 * Reworked interface to remove commander completely338 * Command now primary structure339 * No initialization needed340 * Usage & Help templates & functions definable at any level341 * Updated Readme342* **0.7.0** Sept 24, 2013343 * Needs more eyes344 * Test suite345 * Support for automatic error messages
4 unmodified lines
350* **0.1.0** Sept 3, 2013351 * Implement first draft352353## ToDo145* More testing of non-runnable146* More testing354* Launch proper documentation site355356## Contributing357
15 unmodified lines