Restructure README.md
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by spf13 · committed by spf13 · parent cb63a06 · Browse files · 1 file·+211 added−38 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+211 added−38 removed
- other:+211 added−38 removed
Provenance
- Commit
6c0cb34- Tree
6fc6f09- Author
spf13 <steve.francia@gmail.com>- Committer
spf13 <steve.francia@gmail.com>- Parent
cb63a06
1 file changed+211 added−38 removed
modified:README.md+211 added-38 removed
20 unmodified lines21 [](https://circleci.com/gh/spf13/cobra)22 23 24 25-## Overview25+# Overview26 27 Cobra is a library providing a simple interface to create powerful modern CLI28 interfaces similar to git & go tools.29 21 unmodified lines51 52 Applications built with Cobra commands are designed to be as user-friendly as53 possible. Flags can be placed before or after the command (as long as a54 confusing space isn’t provided). Both short and long flags can be used. A55-command need not even be fully typed. The shortest unambiguous string will56-suffice. Help is automatically generated and available for the application or57-for a specific command using either the help command or the `--help` flag.55+command need not even be fully typed. Help is automatically generated and56+available for the application or for a specific command using either the help57+command or the `--help` flag.58 59-## Concepts59+# Concepts60 61-Cobra is built on a structure of commands & flags.61+Cobra is built on a structure of commands, arguments & flags.62 63-**Commands** represent actions and **Flags** are modifiers for those actions.63+**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.64 65+The best applications will read like sentences when used. Users will know how66+to use the application because they will natively understand how to use it.67+68+The pattern to follow is 69+`APPNAME VERB NOUN --ADJECTIVE.`70+ or71+`APPNAME COMMAND ARG --FLAG`72+73+A few good real world examples may better illustrate this point.74+75 In the following example, 'server' is a command, and 'port' is a flag:76 67- > hugo server --port=131377+ > hugo serve --port=131378 69-### Commands79+In this command we are telling Git to clone the url bare.80 81+ > git clone URL --bare82+83+## Commands84+85 Command is the central point of the application. Each interaction that86 the application supports will be contained in a Command. A command can87 have children commands and optionally run an action.88 9 unmodified lines98 Run func(cmd *Command, args []string) // Run runs the command.99 }100 ```101 88-### Flags102+## Flags103 104 A Flag is a way to modify the behavior of a command. Cobra supports105 fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).106 A Cobra command can define flags that persist through to children commands12 unmodified lines119 120 Once each command is defined with its corresponding flags, then the121 tree is assigned to the commander which is finally executed.122 109-### Installing123+# Installing124 Using Cobra is easy. First, use `go get` to install the latest version125 of the library:126 127 > go get -v github.com/spf13/cobra3 unmodified lines131 ```go132 import "github.com/spf13/cobra"133 ```134 135+# Getting Started136+137+While you are welcome to provide your own organization, typically a Cobra based138+application will follow the following organizational structure.139+140+```141+ ▾ appName/142+ ▾ cmd/143+ add.go144+ your.go145+ commands.go146+ here.go147+ main.go148+```149+150+In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.151+152+```go153+package main154+155+import "{pathToYourApp}/cmd"156+157+func main() {158+ RootCmd.Execute()159+}160+```161+162+## Using the Cobra Generator163+164+Cobra provides it's own program that will create your application and add any165+commands you want. It's the easiest way to incorporate Cobra into your application.166+167+### cobra init168+169+The `cobra init [yourApp]` command will create your initial application code170+for you. It is a very powerful application that will populate your program with171+the right structure so you can immediately enjoy all the benefits of Cobra. It172+will also automatically apply the license you specify to your application.173+174+Cobra init is pretty smart. You can provide it a full path, or simply a path175+similar to what is expected in the import.176+177+```178+cobra init github.com/spf13/newAppName179+```180+181+### cobra add182+183+Once an application is initialized Cobra can create additional commands for you.184+Let's say you created an app and you wanted the following commands for it:185+186+* app serve187+* app config188+* app config create189+190+In your project directory (where your main.go file is) you would run the following:191+192+```193+cobra add serve194+cobra add config195+cobra add create -p 'configCmd'196+```197+198+Once you have run these four commands you would have an app structure that would look like:199+200+```201+ ▾ app/202+ ▾ cmd/203+ serve.go204+ config.go205+ create.go206+ main.go207+```208+209+at this point you can run `go run main.go` and it would run your app. `go run210+main.go serve`, `go run main.go config`, `go run main.go config create` along211+with `go run main.go help serve`, etc would all work.212+213+Obviously you haven't added your own code to these yet, the commands are ready214+for you to give them their tasks. Have fun.215+216+### Configuring the cobra generator217+218+The cobra generator will be easier to use if you provide a simple configuration219+file which will help you eliminate providing a bunch of repeated information in220+flags over and over.221+222+an example ~/.cobra.yaml file:223+224+```yaml225+author: Steve Francia <spf@spf13.com>226+license: MIT227+```228+229+## Manually implementing Cobra230+231+To manually implement cobra you need to create a bare main.go file and a RootCmd file.232+You will optionally provide additional commands as you see fit.233+234 ### Create the root command235 236 The root command represents your binary itself.237 238+239+#### Manually create rootCmd240+241 Cobra doesn't require any special constructors. Simply create your commands.242 243+Ideally you place this in app/cmd/root.go:244+245 ```go128-var HugoCmd = &cobra.Command{246+var RootCmd = &cobra.Command{247 Use: "hugo",248 Short: "Hugo is a very fast static site generator",249 Long: `A Fast and Flexible Static Site Generator built with250 love by spf13 and friends in Go.3 unmodified lines254 },255 }256 ```257 258+You will additionally define flags and handle configuration in your init() function.259+260+for example cmd/root.go:261+262+```go263+func init() {264+ cobra.OnInitialize(initConfig)265+ RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")266+ RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")267+ RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")268+ RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")269+ RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")270+ viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))271+ viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))272+ viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))273+ viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")274+ viper.SetDefault("license", "apache")275+}276+```277+278+### Create your main.go279+280+With the root command you need to have your main function execute it.281+Execute should be run on the root for clarity, though it can be called on any command.282+283+In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.284+285+```go286+package main287+288+import "{pathToYourApp}/cmd"289+290+func main() {291+ RootCmd.Execute()292+}293+```294+295+296 ### Create additional commands297 142-Additional commands can be defined.298+Additional commands can be defined and typically are each given their own file299+inside of the cmd/ directory.300 301+If you wanted to create a version command you would create cmd/version.go and302+populate it with the following:303+304 ```go305+package cmd306+307+import (308+ "github.com/spf13/cobra"309+)310+311+func init() {312+ RootCmd.AddCommand(versionCmd)313+}314+315 var versionCmd = &cobra.Command{316 Use: "version",317 Short: "Print the version number of Hugo",318 Long: `All software has versions. This is Hugo's`,2 unmodified lines321 },322 }323 ```324 155-### Attach command to its parent156-In this example we are attaching it to the root, but commands can be attached at any level.325+### Attach command to its parent 326 327+328+If you notice in the above example we attach the command to it's parent. In329+this case the parent is the rootCmd. In this example we are attaching it to the330+root, but commands can be attached at any level.331+332 ```go159-HugoCmd.AddCommand(versionCmd)333+RootCmd.AddCommand(versionCmd)334 ```335 336+### Remove a command from its parent337+338+Removing a command is not a common action in simple programs, but it allows 3rd339+parties to customize an existing command tree.340+341+In this example, we remove the existing `VersionCmd` command of an existing342+root command, and we replace it with our own version:343+344+```go345+mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)346+mainlib.RootCmd.AddCommand(versionCmd)347+```348+349+## Working with Flags350+351+Flags provide modifiers to control how the action command operates.352+353 ### Assign flags to a command354 355 Since the flags are defined and used in different locations, we need to356 define a variable outside with the correct scope to assign the flag to5 unmodified lines362 ```363 364 There are two different approaches to assign a flag.365 175-#### Persistent Flags366+### Persistent Flags367 368 A flag can be 'persistent' meaning that this flag will be available to the369 command it's assigned to as well as every command under that command. For370 global flags, assign a flag as a persistent flag on the root.371 372 ```go182-HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")373+RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")374 ```375 185-#### Local Flags376+### Local Flags377 378 A flag can also be assigned locally which will only apply to that specific command.379 380 ```go190-HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")381+RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")382 ```383 193-### Remove a command from its parent384 195-Removing a command is not a common action in simple programs, but it allows 3rd parties to customize an existing command tree.196-197-In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it with our own version:198-199-```go200-mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)201-mainlib.RootCmd.AddCommand(versionCmd)202-```203-204-### Once all commands and flags are defined, Execute the commands205-206-Execute should be run on the root for clarity, though it can be called on any command.207-208-```go209-HugoCmd.Execute()210-```211-385 ## Example386 387 In the example below, we have defined three commands. Two are at the top level388 and one (cmdTimes) is a child of one of the top commands. In this case the root474 unmodified lines