mirror of
https://github.com/spf13/cobra
synced 2024-11-24 22:57:12 +00:00
Copyedit README.md
This commit is contained in:
parent
f06ae19d96
commit
9324f3657d
1 changed files with 198 additions and 120 deletions
286
README.md
286
README.md
|
@ -17,7 +17,8 @@ Many of the most widely used Go projects are built using Cobra including:
|
||||||
* [Parse (CLI)](https://parse.com/)
|
* [Parse (CLI)](https://parse.com/)
|
||||||
|
|
||||||
|
|
||||||
[![Build Status](https://travis-ci.org/spf13/cobra.svg)](https://travis-ci.org/spf13/cobra)
|
[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
|
||||||
|
[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra)
|
||||||
|
|
||||||
![cobra](https://cloud.githubusercontent.com/assets/173412/10911369/84832a8e-8212-11e5-9f82-cc96660a4794.gif)
|
![cobra](https://cloud.githubusercontent.com/assets/173412/10911369/84832a8e-8212-11e5-9f82-cc96660a4794.gif)
|
||||||
|
|
||||||
|
@ -27,33 +28,33 @@ Cobra is a library providing a simple interface to create powerful modern CLI
|
||||||
interfaces similar to git & go tools.
|
interfaces similar to git & go tools.
|
||||||
|
|
||||||
Cobra is also an application that will generate your application scaffolding to rapidly
|
Cobra is also an application that will generate your application scaffolding to rapidly
|
||||||
develop a Cobra based application.
|
develop a Cobra-based application.
|
||||||
|
|
||||||
Cobra provides:
|
Cobra provides:
|
||||||
* Easy sub-command based CLIs: `app server`, `app fetch`, etc.
|
* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
|
||||||
* Fully posix compliant flags (including short & long versions)
|
* Fully POSIX-compliant flags (including short & long versions)
|
||||||
* Nested sub commands
|
* Nested subcommands
|
||||||
* Global, local and cascading flags
|
* Global, local and cascading flags
|
||||||
* Easy generation of applications & commands with `cobra create appname` & `cobra add cmdname`
|
* Easy generation of applications & commands with `cobra create appname` & `cobra add cmdname`
|
||||||
* Intelligent suggestions (`app srver`.. did you mean `app server`)
|
* Intelligent suggestions (`app srver`... did you mean `app server`?)
|
||||||
* Automatic help generation for commands and flags
|
* Automatic help generation for commands and flags
|
||||||
* Automatic detailed help for `app help [command]`
|
* Automatic detailed help for `app help [command]`
|
||||||
* Automatic help flag recognition of `-h`, `--help`, etc.
|
* Automatic help flag recognition of `-h`, `--help`, etc.
|
||||||
* Automatically generated bash autocomplete for your application
|
* Automatically generated bash autocomplete for your application
|
||||||
* Automatically generated man pages for your application
|
* Automatically generated man pages for your application
|
||||||
* Command aliases so you can change things without breaking them
|
* Command aliases so you can change things without breaking them
|
||||||
* The flexibilty to define your own help, usage, etc
|
* The flexibilty to define your own help, usage, etc.
|
||||||
* Optional tight integration with [viper](http://github.com/spf13/viper) for 12 factor apps
|
* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
|
||||||
|
|
||||||
Cobra has an exceptionally clean interface and simple design without needless
|
Cobra has an exceptionally clean interface and simple design without needless
|
||||||
constructors or initialization methods.
|
constructors or initialization methods.
|
||||||
|
|
||||||
Applications built with Cobra commands are designed to be as user friendly as
|
Applications built with Cobra commands are designed to be as user-friendly as
|
||||||
possible. Flags can be placed before or after the command (as long as a
|
possible. Flags can be placed before or after the command (as long as a
|
||||||
confusing space isn’t provided). Both short and long flags can be used. A
|
confusing space isn’t provided). Both short and long flags can be used. A
|
||||||
command need not even be fully typed. The shortest unambiguous string will
|
command need not even be fully typed. The shortest unambiguous string will
|
||||||
suffice. Help is automatically generated and available for the application or
|
suffice. Help is automatically generated and available for the application or
|
||||||
for a specific command using either the help command or the --help flag.
|
for a specific command using either the help command or the `--help` flag.
|
||||||
|
|
||||||
## Concepts
|
## Concepts
|
||||||
|
|
||||||
|
@ -61,9 +62,9 @@ Cobra is built on a structure of commands & flags.
|
||||||
|
|
||||||
**Commands** represent actions and **Flags** are modifiers for those actions.
|
**Commands** represent actions and **Flags** are modifiers for those actions.
|
||||||
|
|
||||||
In the following example 'server' is a command and 'port' is a flag.
|
In the following example, 'server' is a command, and 'port' is a flag:
|
||||||
|
|
||||||
hugo server --port=1313
|
> hugo server --port=1313
|
||||||
|
|
||||||
### Commands
|
### Commands
|
||||||
|
|
||||||
|
@ -71,47 +72,51 @@ Command is the central point of the application. Each interaction that
|
||||||
the application supports will be contained in a Command. A command can
|
the application supports will be contained in a Command. A command can
|
||||||
have children commands and optionally run an action.
|
have children commands and optionally run an action.
|
||||||
|
|
||||||
In the example above 'server' is the command
|
In the example above, 'server' is the command.
|
||||||
|
|
||||||
A Command has the following structure:
|
A Command has the following structure:
|
||||||
|
|
||||||
type Command struct {
|
```go
|
||||||
|
type Command struct {
|
||||||
Use string // The one-line usage message.
|
Use string // The one-line usage message.
|
||||||
Short string // The short description shown in the 'help' output.
|
Short string // The short description shown in the 'help' output.
|
||||||
Long string // The long message shown in the 'help <this-command>' output.
|
Long string // The long message shown in the 'help <this-command>' output.
|
||||||
Run func(cmd *Command, args []string) // Run runs the command.
|
Run func(cmd *Command, args []string) // Run runs the command.
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Flags
|
### Flags
|
||||||
|
|
||||||
A Flag is a way to modify the behavior of an command. Cobra supports
|
A Flag is a way to modify the behavior of a command. Cobra supports
|
||||||
fully posix compliant flags as well as the go flag package.
|
fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
|
||||||
A Cobra command can define flags that persist through to children commands
|
A Cobra command can define flags that persist through to children commands
|
||||||
and flags that are only available to that command.
|
and flags that are only available to that command.
|
||||||
|
|
||||||
In the example above 'port' is the flag.
|
In the example above, 'port' is the flag.
|
||||||
|
|
||||||
Flag functionality is provided by the [pflag
|
Flag functionality is provided by the [pflag
|
||||||
library](https://github.com/ogier/pflag), a fork of the flag standard library
|
library](https://github.com/ogier/pflag), a fork of the flag standard library
|
||||||
which maintains the same interface while adding posix compliance.
|
which maintains the same interface while adding POSIX compliance.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Cobra works by creating a set of commands and then organizing them into a tree.
|
Cobra works by creating a set of commands and then organizing them into a tree.
|
||||||
The tree defines the structure of the application.
|
The tree defines the structure of the application.
|
||||||
|
|
||||||
Once each command is defined with it's corresponding flags, then the
|
Once each command is defined with its corresponding flags, then the
|
||||||
tree is assigned to the commander which is finally executed.
|
tree is assigned to the commander which is finally executed.
|
||||||
|
|
||||||
### Installing
|
### Installing
|
||||||
Using Cobra is easy. First use go get to install the latest version
|
Using Cobra is easy. First, use `go get` to install the latest version
|
||||||
of the library.
|
of the library:
|
||||||
|
|
||||||
$ go get github.com/spf13/cobra
|
> go get -v github.com/spf13/cobra
|
||||||
|
|
||||||
Next include cobra in your application.
|
Next, include Cobra in your application:
|
||||||
|
|
||||||
import "github.com/spf13/cobra"
|
```go
|
||||||
|
import "github.com/spf13/cobra"
|
||||||
|
```
|
||||||
|
|
||||||
### Create the root command
|
### Create the root command
|
||||||
|
|
||||||
|
@ -150,7 +155,9 @@ var versionCmd = &cobra.Command{
|
||||||
### Attach command to its parent
|
### Attach command to its parent
|
||||||
In this example we are attaching it to the root, but commands can be attached at any level.
|
In this example we are attaching it to the root, but commands can be attached at any level.
|
||||||
|
|
||||||
HugoCmd.AddCommand(versionCmd)
|
```go
|
||||||
|
HugoCmd.AddCommand(versionCmd)
|
||||||
|
```
|
||||||
|
|
||||||
### Assign flags to a command
|
### Assign flags to a command
|
||||||
|
|
||||||
|
@ -158,8 +165,10 @@ Since 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
|
define a variable outside with the correct scope to assign the flag to
|
||||||
work with.
|
work with.
|
||||||
|
|
||||||
var Verbose bool
|
```go
|
||||||
var Source string
|
var Verbose bool
|
||||||
|
var Source string
|
||||||
|
```
|
||||||
|
|
||||||
There are two different approaches to assign a flag.
|
There are two different approaches to assign a flag.
|
||||||
|
|
||||||
|
@ -167,34 +176,42 @@ There are two different approaches to assign a flag.
|
||||||
|
|
||||||
A flag can be 'persistent' meaning that this flag will be available to the
|
A flag can be 'persistent' meaning that this flag will be available to the
|
||||||
command it's assigned to as well as every command under that command. For
|
command it's assigned to as well as every command under that command. For
|
||||||
global flags assign a flag as a persistent flag on the root.
|
global flags, assign a flag as a persistent flag on the root.
|
||||||
|
|
||||||
HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
|
```go
|
||||||
|
HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
|
||||||
|
```
|
||||||
|
|
||||||
#### Local Flags
|
#### Local Flags
|
||||||
|
|
||||||
A flag can also be assigned locally which will only apply to that specific command.
|
A flag can also be assigned locally which will only apply to that specific command.
|
||||||
|
|
||||||
HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
|
```go
|
||||||
|
HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
|
||||||
|
```
|
||||||
|
|
||||||
### Remove a command from its parent
|
### Remove a command from its parent
|
||||||
|
|
||||||
Removing a command is not a common action in simple programs but it allows 3rd parties to customize an existing command tree.
|
Removing a command is not a common action in simple programs, but it allows 3rd parties to customize an existing command tree.
|
||||||
|
|
||||||
In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it by our own version.
|
In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it with our own version:
|
||||||
|
|
||||||
mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
|
```go
|
||||||
mainlib.RootCmd.AddCommand(versionCmd)
|
mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
|
||||||
|
mainlib.RootCmd.AddCommand(versionCmd)
|
||||||
|
```
|
||||||
|
|
||||||
### Once all commands and flags are defined, Execute the commands
|
### Once all commands and flags are defined, Execute the commands
|
||||||
|
|
||||||
Execute should be run on the root for clarity, though it can be called on any command.
|
Execute should be run on the root for clarity, though it can be called on any command.
|
||||||
|
|
||||||
HugoCmd.Execute()
|
```go
|
||||||
|
HugoCmd.Execute()
|
||||||
|
```
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
In the example below we have defined three commands. Two are at the top level
|
In the example below, we have defined three commands. Two are at the top level
|
||||||
and one (cmdTimes) is a child of one of the top commands. In this case the root
|
and one (cmdTimes) is a child of one of the top commands. In this case the root
|
||||||
is not executable meaning that a subcommand is required. This is accomplished
|
is not executable meaning that a subcommand is required. This is accomplished
|
||||||
by not providing a 'Run' for the 'rootCmd'.
|
by not providing a 'Run' for the 'rootCmd'.
|
||||||
|
@ -202,6 +219,7 @@ by not providing a 'Run' for the 'rootCmd'.
|
||||||
We have only defined one flag for a single command.
|
We have only defined one flag for a single command.
|
||||||
|
|
||||||
More documentation about flags is available at https://github.com/spf13/pflag
|
More documentation about flags is available at https://github.com/spf13/pflag
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
@ -258,56 +276,80 @@ func main() {
|
||||||
rootCmd.Execute()
|
rootCmd.Execute()
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
For a more complete example of a larger application, please checkout [Hugo](http://hugo.spf13.com)
|
|
||||||
|
For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
|
||||||
|
|
||||||
## The Help Command
|
## The Help Command
|
||||||
|
|
||||||
Cobra automatically adds a help command to your application when you have subcommands.
|
Cobra automatically adds a help command to your application when you have subcommands.
|
||||||
This will be called when a user runs 'app help'. Additionally help will also
|
This will be called when a user runs 'app help'. Additionally, help will also
|
||||||
support all other commands as input. Say for instance you have a command called
|
support all other commands as input. Say, for instance, you have a command called
|
||||||
'create' without any additional configuration cobra will work when 'app help
|
'create' without any additional configuration; Cobra will work when 'app help
|
||||||
create' is called. Every command will automatically have the '--help' flag added.
|
create' is called. Every command will automatically have the '--help' flag added.
|
||||||
|
|
||||||
### Example
|
### Example
|
||||||
|
|
||||||
The following output is automatically generated by cobra. Nothing beyond the
|
The following output is automatically generated by Cobra. Nothing beyond the
|
||||||
command and flag definitions are needed.
|
command and flag definitions are needed.
|
||||||
|
|
||||||
> hugo help
|
> hugo help
|
||||||
|
|
||||||
A Fast and Flexible Static Site Generator built with
|
hugo is the main command, used to build your Hugo site.
|
||||||
love by spf13 and friends in Go.
|
|
||||||
|
|
||||||
Complete documentation is available at http://hugo.spf13.com
|
Hugo is a Fast and Flexible Static Site Generator
|
||||||
|
built with love by spf13 and friends in Go.
|
||||||
|
|
||||||
|
Complete documentation is available at http://gohugo.io/.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
hugo [flags]
|
hugo [flags]
|
||||||
hugo [command]
|
hugo [command]
|
||||||
|
|
||||||
Available Commands:
|
Available Commands:
|
||||||
server :: Hugo runs it's own a webserver to render the files
|
server Hugo runs its own webserver to render the files
|
||||||
version :: Print the version number of Hugo
|
version Print the version number of Hugo
|
||||||
check :: Check content in the source directory
|
config Print the site configuration
|
||||||
benchmark :: Benchmark hugo by building a site a number of times
|
check Check content in the source directory
|
||||||
help [command] :: Help about any command
|
benchmark Benchmark hugo by building a site a number of times.
|
||||||
|
convert Convert your content to different formats
|
||||||
|
new Create new content for your site
|
||||||
|
list Listing out various types of content
|
||||||
|
undraft Undraft changes the content's draft status from 'True' to 'False'
|
||||||
|
genautocomplete Generate shell autocompletion script for Hugo
|
||||||
|
gendoc Generate Markdown documentation for the Hugo CLI.
|
||||||
|
genman Generate man page for Hugo
|
||||||
|
import Import your site from others.
|
||||||
|
|
||||||
Available Flags:
|
Flags:
|
||||||
-b, --base-url="": hostname (and path) to the root eg. http://spf13.com/
|
-b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
|
||||||
-D, --build-drafts=false: include content marked as draft
|
-D, --buildDrafts[=false]: include content marked as draft
|
||||||
|
-F, --buildFuture[=false]: include content with publishdate in the future
|
||||||
|
--cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
|
||||||
|
--canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
|
||||||
--config="": config file (default is path/config.yaml|json|toml)
|
--config="": config file (default is path/config.yaml|json|toml)
|
||||||
-d, --destination="": filesystem path to write files to
|
-d, --destination="": filesystem path to write files to
|
||||||
|
--disableRSS[=false]: Do not build RSS files
|
||||||
|
--disableSitemap[=false]: Do not build Sitemap file
|
||||||
|
--editor="": edit new content with this editor, if provided
|
||||||
|
--ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
|
||||||
|
--log[=false]: Enable Logging
|
||||||
|
--logFile="": Log File path (if set, logging enabled automatically)
|
||||||
|
--noTimes[=false]: Don't sync modification time of files
|
||||||
|
--pluralizeListTitles[=true]: Pluralize titles in lists using inflect
|
||||||
|
--preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
|
||||||
-s, --source="": filesystem path to read files relative from
|
-s, --source="": filesystem path to read files relative from
|
||||||
--stepAnalysis=false: display memory and timing of different steps of the program
|
--stepAnalysis[=false]: display memory and timing of different steps of the program
|
||||||
--uglyurls=false: if true, use /filename.html instead of /filename/
|
-t, --theme="": theme to use (located in /themes/THEMENAME/)
|
||||||
-v, --verbose=false: verbose output
|
--uglyURLs[=false]: if true, use /filename.html instead of /filename/
|
||||||
-w, --watch=false: watch filesystem for changes and recreate as needed
|
-v, --verbose[=false]: verbose output
|
||||||
|
--verboseLog[=false]: verbose logging
|
||||||
Use "hugo help [command]" for more information about that command.
|
-w, --watch[=false]: watch filesystem for changes and recreate as needed
|
||||||
|
|
||||||
|
Use "hugo [command] --help" for more information about a command.
|
||||||
|
|
||||||
|
|
||||||
Help is just a command like any other. There is no special logic or behavior
|
Help is just a command like any other. There is no special logic or behavior
|
||||||
around it. In fact you can provide your own if you want.
|
around it. In fact, you can provide your own if you want.
|
||||||
|
|
||||||
### Defining your own help
|
### Defining your own help
|
||||||
|
|
||||||
|
@ -330,62 +372,90 @@ func (c *Command) initHelp() {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
You can provide your own command, function or template through the following methods.
|
You can provide your own command, function or template through the following methods:
|
||||||
|
|
||||||
command.SetHelpCommand(cmd *Command)
|
```go
|
||||||
|
command.SetHelpCommand(cmd *Command)
|
||||||
|
|
||||||
command.SetHelpFunc(f func(*Command, []string))
|
command.SetHelpFunc(f func(*Command, []string))
|
||||||
|
|
||||||
command.SetHelpTemplate(s string)
|
command.SetHelpTemplate(s string)
|
||||||
|
```
|
||||||
|
|
||||||
The latter two will also apply to any children commands.
|
The latter two will also apply to any children commands.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
When the user provides an invalid flag or invalid command Cobra responds by
|
When the user provides an invalid flag or invalid command, Cobra responds by
|
||||||
showing the user the 'usage'
|
showing the user the 'usage'.
|
||||||
|
|
||||||
### Example
|
### Example
|
||||||
You may recognize this from the help above. That's because the default help
|
You may recognize this from the help above. That's because the default help
|
||||||
embeds the usage as part of it's output.
|
embeds the usage as part of its output.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
hugo [flags]
|
hugo [flags]
|
||||||
hugo [command]
|
hugo [command]
|
||||||
|
|
||||||
Available Commands:
|
Available Commands:
|
||||||
server Hugo runs it's own a webserver to render the files
|
server Hugo runs its own webserver to render the files
|
||||||
version Print the version number of Hugo
|
version Print the version number of Hugo
|
||||||
|
config Print the site configuration
|
||||||
check Check content in the source directory
|
check Check content in the source directory
|
||||||
benchmark Benchmark hugo by building a site a number of times
|
benchmark Benchmark hugo by building a site a number of times.
|
||||||
help [command] Help about any command
|
convert Convert your content to different formats
|
||||||
|
new Create new content for your site
|
||||||
|
list Listing out various types of content
|
||||||
|
undraft Undraft changes the content's draft status from 'True' to 'False'
|
||||||
|
genautocomplete Generate shell autocompletion script for Hugo
|
||||||
|
gendoc Generate Markdown documentation for the Hugo CLI.
|
||||||
|
genman Generate man page for Hugo
|
||||||
|
import Import your site from others.
|
||||||
|
|
||||||
Available Flags:
|
Flags:
|
||||||
-b, --base-url="": hostname (and path) to the root eg. http://spf13.com/
|
-b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
|
||||||
-D, --build-drafts=false: include content marked as draft
|
-D, --buildDrafts[=false]: include content marked as draft
|
||||||
|
-F, --buildFuture[=false]: include content with publishdate in the future
|
||||||
|
--cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
|
||||||
|
--canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
|
||||||
--config="": config file (default is path/config.yaml|json|toml)
|
--config="": config file (default is path/config.yaml|json|toml)
|
||||||
-d, --destination="": filesystem path to write files to
|
-d, --destination="": filesystem path to write files to
|
||||||
|
--disableRSS[=false]: Do not build RSS files
|
||||||
|
--disableSitemap[=false]: Do not build Sitemap file
|
||||||
|
--editor="": edit new content with this editor, if provided
|
||||||
|
--ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
|
||||||
|
--log[=false]: Enable Logging
|
||||||
|
--logFile="": Log File path (if set, logging enabled automatically)
|
||||||
|
--noTimes[=false]: Don't sync modification time of files
|
||||||
|
--pluralizeListTitles[=true]: Pluralize titles in lists using inflect
|
||||||
|
--preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
|
||||||
-s, --source="": filesystem path to read files relative from
|
-s, --source="": filesystem path to read files relative from
|
||||||
--stepAnalysis=false: display memory and timing of different steps of the program
|
--stepAnalysis[=false]: display memory and timing of different steps of the program
|
||||||
--uglyurls=false: if true, use /filename.html instead of /filename/
|
-t, --theme="": theme to use (located in /themes/THEMENAME/)
|
||||||
-v, --verbose=false: verbose output
|
--uglyURLs[=false]: if true, use /filename.html instead of /filename/
|
||||||
-w, --watch=false: watch filesystem for changes and recreate as needed
|
-v, --verbose[=false]: verbose output
|
||||||
|
--verboseLog[=false]: verbose logging
|
||||||
|
-w, --watch[=false]: watch filesystem for changes and recreate as needed
|
||||||
|
|
||||||
### Defining your own usage
|
### Defining your own usage
|
||||||
You can provide your own usage function or template for cobra to use.
|
You can provide your own usage function or template for Cobra to use.
|
||||||
|
|
||||||
The default usage function is
|
The default usage function is:
|
||||||
|
|
||||||
return func(c *Command) error {
|
```go
|
||||||
|
return func(c *Command) error {
|
||||||
err := tmpl(c.Out(), c.UsageTemplate(), c)
|
err := tmpl(c.Out(), c.UsageTemplate(), c)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Like help the function and template are over ridable through public methods.
|
Like help, the function and template are overridable through public methods:
|
||||||
|
|
||||||
command.SetUsageFunc(f func(*Command) error)
|
```go
|
||||||
|
command.SetUsageFunc(f func(*Command) error)
|
||||||
|
|
||||||
command.SetUsageTemplate(s string)
|
command.SetUsageTemplate(s string)
|
||||||
|
```
|
||||||
|
|
||||||
## PreRun or PostRun Hooks
|
## PreRun or PostRun Hooks
|
||||||
|
|
||||||
|
@ -397,7 +467,7 @@ It is possible to run functions before or after the main `Run` function of your
|
||||||
- `PostRun`
|
- `PostRun`
|
||||||
- `PersistentPostRun`
|
- `PersistentPostRun`
|
||||||
|
|
||||||
And 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`
|
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`:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
|
@ -432,7 +502,7 @@ func main() {
|
||||||
|
|
||||||
var subCmd = &cobra.Command{
|
var subCmd = &cobra.Command{
|
||||||
Use: "sub [no options!]",
|
Use: "sub [no options!]",
|
||||||
Short: "My sub command",
|
Short: "My subcommand",
|
||||||
PreRun: func(cmd *cobra.Command, args []string) {
|
PreRun: func(cmd *cobra.Command, args []string) {
|
||||||
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
|
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
|
||||||
},
|
},
|
||||||
|
@ -501,11 +571,11 @@ func main() {
|
||||||
|
|
||||||
## Suggestions when "unknown command" happens
|
## Suggestions when "unknown command" happens
|
||||||
|
|
||||||
Cobra 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:
|
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:
|
||||||
|
|
||||||
```
|
```
|
||||||
$ hugo srever
|
$ hugo srever
|
||||||
unknown command "srever" for "hugo"
|
Error: unknown command "srever" for "hugo"
|
||||||
|
|
||||||
Did you mean this?
|
Did you mean this?
|
||||||
server
|
server
|
||||||
|
@ -513,48 +583,54 @@ Did you mean this?
|
||||||
Run 'hugo --help' for usage.
|
Run 'hugo --help' for usage.
|
||||||
```
|
```
|
||||||
|
|
||||||
Suggestions 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.
|
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.
|
||||||
|
|
||||||
If you need to disable suggestions or tweak the string distance in your command, use:
|
If you need to disable suggestions or tweak the string distance in your command, use:
|
||||||
|
|
||||||
command.DisableSuggestions = true
|
```go
|
||||||
|
command.DisableSuggestions = true
|
||||||
|
```
|
||||||
|
|
||||||
or
|
or
|
||||||
|
|
||||||
command.SuggestionsMinimumDistance = 1
|
```go
|
||||||
|
command.SuggestionsMinimumDistance = 1
|
||||||
|
```
|
||||||
|
|
||||||
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:
|
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:
|
||||||
|
|
||||||
```
|
```
|
||||||
$ hugo delete
|
$ kubectl remove
|
||||||
unknown command "delete" for "hugo"
|
Error: unknown command "remove" for "kubectl"
|
||||||
|
|
||||||
Did you mean this?
|
Did you mean this?
|
||||||
remove
|
delete
|
||||||
|
|
||||||
Run 'hugo --help' for usage.
|
Run 'kubectl help' for usage.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Generating markdown formatted documentation for your command
|
## Generating Markdown-formatted documentation for your command
|
||||||
|
|
||||||
Cobra 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)
|
Cobra 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).
|
||||||
|
|
||||||
## Generating man pages for your command
|
## Generating man pages for your command
|
||||||
|
|
||||||
Cobra 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)
|
Cobra 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).
|
||||||
|
|
||||||
## Generating bash completions for your command
|
## Generating bash completions for your command
|
||||||
|
|
||||||
Cobra 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)
|
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).
|
||||||
|
|
||||||
## Debugging
|
## Debugging
|
||||||
|
|
||||||
Cobra provides a ‘DebugFlags’ method on a command which when called will print
|
Cobra provides a ‘DebugFlags’ method on a command which, when called, will print
|
||||||
out everything Cobra knows about the flags for each command
|
out everything Cobra knows about the flags for each command.
|
||||||
|
|
||||||
### Example
|
### Example
|
||||||
|
|
||||||
command.DebugFlags()
|
```go
|
||||||
|
command.DebugFlags()
|
||||||
|
```
|
||||||
|
|
||||||
## Release Notes
|
## Release Notes
|
||||||
* **0.9.0** June 17, 2014
|
* **0.9.0** June 17, 2014
|
||||||
|
@ -584,7 +660,7 @@ out everything Cobra knows about the flags for each command
|
||||||
|
|
||||||
Libraries for extending Cobra:
|
Libraries for extending Cobra:
|
||||||
|
|
||||||
* [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`.
|
* [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`.
|
||||||
|
|
||||||
## ToDo
|
## ToDo
|
||||||
* Launch proper documentation site
|
* Launch proper documentation site
|
||||||
|
@ -601,7 +677,9 @@ Libraries for extending Cobra:
|
||||||
|
|
||||||
Names in no particular order:
|
Names in no particular order:
|
||||||
|
|
||||||
* [spf13](https://github.com/spf13)
|
* [spf13](https://github.com/spf13),
|
||||||
|
[eparis](https://github.com/eparis),
|
||||||
|
[bep](https://github.com/bep), ...
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue