Command Line Interfaces (CLI) applications are software programs that run on terminals or command prompts. The user interacts with the software by specifying commands and receiving text as feedback.
CLIs are old but very popular for their versatility, portability, and speed. CLIs are popularly used for various tasks ranging from text processing to complex systems administration tasks to save time and effort.
Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
var rootCmd = &cobra.Command{ Use: "bobo", Short: "Bobo is a very fast static site generator", Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("run bobo...") }, }
var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version number of Bobo", Long: `All software has versions. This is Bobo's`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Bobo Static Site Generator v1.0 -- HEAD") }, }
$ ./bobo version Bobo Static Site Generator v1.0 -- HEAD $ ./bobo help A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go.
Usage: bobo [flags] bobo [command]
Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command version Print the version number of Bobo
Flags: -h, --help help for bobo
Use "bobo [command] --help" for more information about a command. $ ./bobo help version All software has versions. This is Bobo's
Usage: bobo version [flags]
Flags: -h, --help help for version
Flag
PersistentFlags
如果一个标志是持久的,则意味着该标志将可用于它所分配的命令以及该命令下的所有子命令。
对于全局标志,可以定义在根命令 rootCmd 上。
1 2 3
var Verbose bool rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
Flags
标志也可以是本地的,只适用于该指定命令。
1 2
var Source string rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command print version Print the version number of Hugo
Flags: --author string Author name for copyright attribution (default "YOUR NAME") -c, --config string config file -h, --help help for hugo -s, --source string Source directory to read from -v, --verbose verbose output
Use "bobo [command] --help" for more information about a command.