Skip to content
Myr

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

1 file+211 added−38 removed

modified:README.md+211 added-38 removed
20 unmodified lines
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## Overview25# Overview2627Cobra is a library providing a simple interface to create powerful modern CLI28interfaces similar to git & go tools.29
21 unmodified lines
5152Applications 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 or57for a specific command using either the help command or the `--help` flag.55command need not even be fully typed. Help is automatically generated and56available for the application or for a specific command using either the help57command or the `--help` flag.5859## Concepts59# Concepts6061Cobra is built on a structure of commands & flags.61Cobra is built on a structure of commands, arguments & flags.6263**Commands** represent actions and **Flags** are modifiers for those actions.63**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.6465The best applications will read like sentences when used. Users will know how66to use the application because they will natively understand how to use it.6768The pattern to follow is 69`APPNAME VERB NOUN --ADJECTIVE.`70 or71`APPNAME COMMAND ARG --FLAG`7273A few good real world examples may better illustrate this point.7475In the following example, 'server' is a command, and 'port' is a flag:7667 > hugo server --port=131377 > hugo serve --port=13137869### Commands79In this command we are telling Git to clone the url bare.8081 > git clone URL --bare8283## Commands8485Command is the central point of the application. Each interaction that86the application supports will be contained in a Command. A command can87have children commands and optionally run an action.88
9 unmodified lines
98 Run func(cmd *Command, args []string) // Run runs the command.99}100```10188### Flags102## Flags103104A Flag is a way to modify the behavior of a command. Cobra supports105fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).106A Cobra command can define flags that persist through to children commands
12 unmodified lines
119120Once each command is defined with its corresponding flags, then the121tree is assigned to the commander which is finally executed.122109### Installing123# Installing124Using Cobra is easy. First, use `go get` to install the latest version125of the library:126127 > go get -v github.com/spf13/cobra
3 unmodified lines
131```go132import "github.com/spf13/cobra"133```134135# Getting Started136137While you are welcome to provide your own organization, typically a Cobra based138application will follow the following organizational structure.139140```141 ▾ appName/142 ▾ cmd/143 add.go144 your.go145 commands.go146 here.go147 main.go148```149150In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.151152```go153package main154155import "{pathToYourApp}/cmd"156157func main() {158 RootCmd.Execute()159}160```161162## Using the Cobra Generator163164Cobra provides it's own program that will create your application and add any165commands you want. It's the easiest way to incorporate Cobra into your application.166167### cobra init168169The `cobra init [yourApp]` command will create your initial application code170for you. It is a very powerful application that will populate your program with171the right structure so you can immediately enjoy all the benefits of Cobra. It172will also automatically apply the license you specify to your application.173174Cobra init is pretty smart. You can provide it a full path, or simply a path175similar to what is expected in the import.176177```178cobra init github.com/spf13/newAppName179```180181### cobra add182183Once an application is initialized Cobra can create additional commands for you.184Let's say you created an app and you wanted the following commands for it:185186* app serve187* app config188* app config create189190In your project directory (where your main.go file is) you would run the following:191192```193cobra add serve194cobra add config195cobra add create -p 'configCmd'196```197198Once you have run these four commands you would have an app structure that would look like:199200```201 ▾ app/202 ▾ cmd/203 serve.go204 config.go205 create.go206 main.go207```208209at this point you can run `go run main.go` and it would run your app. `go run210main.go serve`, `go run main.go config`, `go run main.go config create` along211with `go run main.go help serve`, etc would all work.212213Obviously you haven't added your own code to these yet, the commands are ready214for you to give them their tasks. Have fun.215216### Configuring the cobra generator217218The cobra generator will be easier to use if you provide a simple configuration219file which will help you eliminate providing a bunch of repeated information in220flags over and over.221222an example ~/.cobra.yaml file:223224```yaml225author: Steve Francia <spf@spf13.com>226license: MIT227```228229## Manually implementing Cobra230231To manually implement cobra you need to create a bare main.go file and a RootCmd file.232You will optionally provide additional commands as you see fit.233234### Create the root command235236The root command represents your binary itself.237238239#### Manually create rootCmd240241Cobra doesn't require any special constructors. Simply create your commands.242243Ideally you place this in app/cmd/root.go:244245```go128var HugoCmd = &cobra.Command{246var 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 lines
254 },255}256```257258You will additionally define flags and handle configuration in your init() function.259260for example cmd/root.go:261262```go263func 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```277278### Create your main.go279280With the root command you need to have your main function execute it.281Execute should be run on the root for clarity, though it can be called on any command.282283In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.284285```go286package main287288import "{pathToYourApp}/cmd"289290func main() {291 RootCmd.Execute()292}293```294295296### Create additional commands297142Additional commands can be defined.298Additional commands can be defined and typically are each given their own file299inside of the cmd/ directory.300301If you wanted to create a version command you would create cmd/version.go and302populate it with the following:303304```go305package cmd306307import (308 "github.com/spf13/cobra"309)310311func init() {312 RootCmd.AddCommand(versionCmd)313}314315var 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 lines
321 },322}323```324155### Attach command to its parent156In this example we are attaching it to the root, but commands can be attached at any level.325### Attach command to its parent 326327328If you notice in the above example we attach the command to it's parent. In329this case the parent is the rootCmd. In this example we are attaching it to the330root, but commands can be attached at any level.331332```go159HugoCmd.AddCommand(versionCmd)333RootCmd.AddCommand(versionCmd)334```335336### Remove a command from its parent337338Removing a command is not a common action in simple programs, but it allows 3rd339parties to customize an existing command tree.340341In this example, we remove the existing `VersionCmd` command of an existing342root command, and we replace it with our own version:343344```go345mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)346mainlib.RootCmd.AddCommand(versionCmd)347```348349## Working with Flags350351Flags provide modifiers to control how the action command operates.352353### Assign flags to a command354355Since the flags are defined and used in different locations, we need to356define a variable outside with the correct scope to assign the flag to
5 unmodified lines
362```363364There are two different approaches to assign a flag.365175#### Persistent Flags366### Persistent Flags367368A flag can be 'persistent' meaning that this flag will be available to the369command it's assigned to as well as every command under that command. For370global flags, assign a flag as a persistent flag on the root.371372```go182HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")373RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")374```375185#### Local Flags376### Local Flags377378A flag can also be assigned locally which will only apply to that specific command.379380```go190HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")381RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")382```383193### Remove a command from its parent384195Removing a command is not a common action in simple programs, but it allows 3rd parties to customize an existing command tree.196197In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it with our own version:198199```go200mainlib.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```go209HugoCmd.Execute()210```211385## Example386387In the example below, we have defined three commands. Two are at the top level388and one (cmdTimes) is a child of one of the top commands. In this case the root
474 unmodified lines