spf13/cobra
和 urfave/cli
是Go的2個優秀命令行工具:python
名稱 | star | 簡介 | 應用項目 |
---|---|---|---|
spf13/cobra | 11571 | A Commander for modern Go CLI interactions | docker, kubernetes, istio, hugo ... |
urfave/cli | 10501 | A simple, fast, and fun package for building command line apps in Go | drone, peach, gogs ... |
兩個項目的簡介都挺有意思,各自的應用項目也很出色。咱們一塊兒來學一學,從docker和drone源碼出發,瞭解如何使用。linux
spf13這個哥們,感受是個印度人,可是很優秀的樣子,下面是他的簡介:git
spf13 @golang at @google • Author, Speaker, Developer • Creator of Hugo, Cobra & spf13-vim • former Docker & MongoDBgithub
吃雞蛋不用瞭解母雞,可是知道母雞是那個廠的也很重要,開源項目也是如此。google、docker和mongodb,都是不錯的技術公司,hugo也是不錯博客平臺,個人我的博客也是用它,感受cobra有很棒的背景。閒聊結束,下面進入正題。golang
一個好的命令行工具,首先要有一個很方便的help
指令,協助用戶瞭解命令,這個最最重要。先看看docker
的幫助:web
➜ ~ docker
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default "/Users/tu/.docker")
-D, --debug Enable debug mode
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/Users/tu/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/Users/tu/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/Users/tu/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Management Commands:
builder Manage builds
...
container Manage containers
...
Commands:
...
ps List containers
...
Run 'docker COMMAND --help' for more information on a command.
複製代碼
docker
的幫助很詳細的,這裏爲避免篇幅太長,省略了其中部分輸出,保留重點分析介紹的命令(下同),使用過程當中很是方便。這種help
指令如何實現的呢。mongodb
從docker-ce\components\cli\cmd\docker\docker.go
的main函數開始:docker
func main() {
// Set terminal emulation based on platform as required.
stdin, stdout, stderr := term.StdStreams()
logrus.SetOutput(stderr)
dockerCli := command.NewDockerCli(stdin, stdout, stderr, contentTrustEnabled(), containerizedengine.NewClient)
cmd := newDockerCommand(dockerCli)
if err := cmd.Execute(); err != nil {
if sterr, ok := err.(cli.StatusError); ok {
if sterr.Status != "" {
fmt.Fprintln(stderr, sterr.Status)
}
// StatusError should only be used for errors, and all errors should
// have a non-zero exit status, so never exit with 0
if sterr.StatusCode == 0 {
os.Exit(1)
}
os.Exit(sterr.StatusCode)
}
fmt.Fprintln(stderr, err)
os.Exit(1)
}
}
複製代碼
代碼很是清晰,作了三件事:1)讀取命令行輸入 2)解析查找命令 3)執行命令。vim
在docker-ce\components\cli\cmd\docker\docker.go
的newDockerCommand
中,能夠知道root命令的實現:bash
cmd := &cobra.Command{
Use: "docker [OPTIONS] COMMAND [ARG...]",
Short: "A self-sufficient runtime for containers",
SilenceUsage: true,
SilenceErrors: true,
TraverseChildren: true,
Args: noArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return command.ShowHelp(dockerCli.Err())(cmd, args)
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// flags must be the top-level command flags, not cmd.Flags()
opts.Common.SetDefaultOptions(flags)
dockerPreRun(opts)
if err := dockerCli.Initialize(opts); err != nil {
return err
}
return isSupported(cmd, dockerCli)
},
Version: fmt.Sprintf("%s, build %s", cli.Version, cli.GitCommit),
DisableFlagsInUseLine: true,
}
複製代碼
從代碼中能夠清晰的把Use
和Short
命令輸出對應起來。
順便在cobra.go
查看到 docker help
命令
var helpCommand = &cobra.Command{
Use: "help [command]",
Short: "Help about the command",
PersistentPreRun: func(cmd *cobra.Command, args []string) {},
PersistentPostRun: func(cmd *cobra.Command, args []string) {},
RunE: func(c *cobra.Command, args []string) error {
cmd, args, e := c.Root().Find(args)
if cmd == nil || e != nil || len(args) > 0 {
return errors.Errorf("unknown help topic: %v", strings.Join(args, " "))
}
helpFunc := cmd.HelpFunc()
helpFunc(cmd, args)
return nil
},
}
複製代碼
以及 docker help
的模板輸出
var usageTemplate = `Usage:
....
var helpTemplate = `
{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
複製代碼
這樣,對docker
命令的輸出,咱們就大概瞭解了,對cobra
如何使用也有一個初略的瞭解。
繼續查看docker各個子命令如何註冊。 docker.go
的第62行,這裏註冊了全部的命令:
commands.AddCommands(cmd, dockerCli)
複製代碼
其對於實如今command\commands\commands.go
:
// AddCommands adds all the commands from cli/command to the root command
func AddCommands(cmd *cobra.Command, dockerCli command.Cli) {
cmd.AddCommand(
// checkpoint
checkpoint.NewCheckpointCommand(dockerCli),
// config
config.NewConfigCommand(dockerCli),
// container
container.NewContainerCommand(dockerCli),
container.NewRunCommand(dockerCli),
...
)
if runtime.GOOS == "linux" {
// engine
cmd.AddCommand(engine.NewEngineCommand(dockerCli))
}
}
複製代碼
一級命令都註冊到docker
中了,繼續查看一下container
這樣的二級命令註冊, 在 docker-ce\components\cli\command\container\cmd.go
// NewContainerCommand returns a cobra command for `container` subcommands
func NewContainerCommand(dockerCli command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "container",
Short: "Manage containers",
Args: cli.NoArgs,
RunE: command.ShowHelp(dockerCli.Err()),
}
cmd.AddCommand(
NewAttachCommand(dockerCli),
NewCommitCommand(dockerCli),
NewCopyCommand(dockerCli),
NewCreateCommand(dockerCli),
NewDiffCommand(dockerCli),
NewExecCommand(dockerCli),
NewExportCommand(dockerCli),
NewKillCommand(dockerCli),
NewLogsCommand(dockerCli),
NewPauseCommand(dockerCli),
....
)
return cmd
}
複製代碼
能夠清晰的看到docker contianer
的子命令是同樣是經過AddCommand
接口註冊的。
docker ps
, 這是個使用頻率很是高的命令,幫助以下:
➜ ~ docker ps --help
Usage: docker ps [OPTIONS]
List containers
Options:
-a, --all Show all containers (default shows just running)
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print containers using a Go template
-n, --last int Show n last created containers (includes all states) (default -1)
-l, --latest Show the latest created container (includes all states)
--no-trunc Don't truncate output -q, --quiet Only display numeric IDs -s, --size Display total file sizes 複製代碼
docker ps
其實是 docker contianer ls
命令的別名,請看:
➜ ~ docker container --help
Usage: docker container COMMAND
Manage containers
Commands:
...
ls List containers
...
Run 'docker container COMMAND --help' for more information on a command.
複製代碼
可見 docker ps
和 docker container ls
的做用都是 List containers
。知道這個之後,查看代碼: docker-ce\components\cli\command\container\ls.go
中有其實現:
// NewPsCommand creates a new cobra.Command for `docker ps`
func NewPsCommand(dockerCli command.Cli) *cobra.Command {
options := psOptions{filter: opts.NewFilterOpt()}
cmd := &cobra.Command{
Use: "ps [OPTIONS]",
Short: "List containers",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runPs(dockerCli, &options)
},
}
flags := cmd.Flags()
flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display numeric IDs")
flags.BoolVarP(&options.size, "size", "s", false, "Display total file sizes")
flags.BoolVarP(&options.all, "all", "a", false, "Show all containers (default shows just running)")
flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output")
flags.BoolVarP(&options.nLatest, "latest", "l", false, "Show the latest created container (includes all states)")
flags.IntVarP(&options.last, "last", "n", -1, "Show n last created containers (includes all states)")
flags.StringVarP(&options.format, "format", "", "", "Pretty-print containers using a Go template")
flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
return cmd
}
複製代碼
結合 docker ps --help
的輸出,能夠猜想Options
和Flags
的對應關係。繼續查看BoolVarP
的定義,在spf13/pflag/bool.go
// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage)
flag.NoOptDefVal = "true"
}
複製代碼
配合註釋說明,這樣就很是清楚了,option名稱使用--
速記名稱使用-
。docker ps -a
和 docker ps --all
是同樣的。
spf13/pflag 也是spf13 的一個庫,主要處理參數量之類的。由於go是強類型的,因此用戶的輸入,都要合法的處理成go對應的數據類型。
在 ls.go
中還新建了一個命令,命名了 ps
是 container ls
的別名。
func newListCommand(dockerCli command.Cli) *cobra.Command {
cmd := *NewPsCommand(dockerCli)
cmd.Aliases = []string{"ps", "list"}
cmd.Use = "ls [OPTIONS]"
return &cmd
}
複製代碼
cobra
的簡單介紹就到這裏,本次實驗的docker
版本以下:
➜ ~ docker --version
Docker version 18.09.2, build 6247962
複製代碼
簡單小結一下cobra使用:
先看看drone
的幫助信息:
➜ ~ drone --help
NAME:
drone - command line utility
USAGE:
drone [global options] command [command options] [arguments...]
VERSION:
1.0.7
COMMANDS:
...
repo manage repositories
...
GLOBAL OPTIONS:
-t value, --token value server auth token [$DRONE_TOKEN]
-s value, --server value server address [$DRONE_SERVER]
--autoscaler value autoscaler address [$DRONE_AUTOSCALER]
--help, -h show help
--version, -v print the version
複製代碼
而後是drone repo
子命令:
➜ ~ drone repo
NAME:
drone repo - manage repositories
USAGE:
drone repo command [command options] [arguments...]
COMMANDS:
ls list all repos
info show repository details
enable enable a repository
update update a repository
disable disable a repository
repair repair repository webhooks
chown assume ownership of a repository
sync synchronize the repository list
OPTIONS:
--help, -h show help
複製代碼
再看看drone repo ls
二級子命令:
➜ rone repo ls --help
NAME:
drone repo ls - list all repos
USAGE:
drone repo ls [command options]
OPTIONS:
--format value format output (default: "{{ .Slug }}")
--org value filter by organization
複製代碼
drone-cli\drone\main.go
中配置了一級子命令:
app.Commands = []cli.Command{
build.Command,
cron.Command,
log.Command,
encrypt.Command,
exec.Command,
info.Command,
repo.Command,
...
}
複製代碼
命令的解析執行:
if err := app.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
複製代碼
繼續查看repo\repo.go
中:
// Command exports the repository command.
var Command = cli.Command{
Name: "repo",
Usage: "manage repositories",
Subcommands: []cli.Command{
repoListCmd,
repoInfoCmd,
repoAddCmd,
repoUpdateCmd,
repoRemoveCmd,
repoRepairCmd,
repoChownCmd,
repoSyncCmd,
},
}
複製代碼
能夠看到drone repo
的子命令註冊。
var repoListCmd = cli.Command{
Name: "ls",
Usage: "list all repos",
ArgsUsage: " ",
Action: repoList,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format",
Usage: "format output",
Value: tmplRepoList,
},
cli.StringFlag{
Name: "org",
Usage: "filter by organization",
},
},
}
複製代碼
最後,再來了解一下命令如何查找,主要是下面2個函數。
根據名稱查找命令:
// Command returns the named command on App. Returns nil if the command does not exist
func (a *App) Command(name string) *Command {
for _, c := range a.Commands {
if c.HasName(name) {
return &c
}
}
return nil
}
複製代碼
判斷命令名稱是否一致:
// HasName returns true if Command.Name or Command.ShortName matches given name
func (c Command) HasName(name string) bool {
for _, n := range c.Names() {
if n == name {
return true
}
}
return false
}
複製代碼
本次實驗的drone版本是:
➜ ~ drone --version
drone version 1.0.7
複製代碼
簡單小結一下cobra使用:
spf13/cobra
和 urfave/cli
都挺棒的, urfave/cli
更簡潔一些 ; spf13/cobra
支持 generator,協助生成項目,功能更強大一些。對Go感興趣的同窗,推薦都瞭解一下。
What is the essential difference between urfave/cli и spf13/cobra?