spf13/cobraurfave/cli 是Go的2个优秀命令行工具:

名称 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源码出发,了解如何使用。

spf13/cobra

spf13这个哥们,感觉是个印度人,但是很优秀的样子,下面是他的简介:

spf13 @golang at @google • Author, Speaker, Developer • Creator of Hugo, Cobra & spf13-vim • former Docker & MongoDB

吃鸡蛋不用了解母鸡,但是知道母鸡是那个厂的也很重要,开源项目也是如此。google、docker和mongodb,都是不错的技术公司,hugo也是不错博客平台,我的个人博客也是用它,感觉cobra有很棒的背景。闲聊结束,下面进入正题。

docker help 命令

一个好的命令行工具,首先要有一个很方便的help指令,协助用户了解命令,这个最最重要。先看看docker的帮助:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
➜  ~ 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指令如何实现的呢。

docker-ce\components\cli\cmd\docker\docker.go的main函数开始:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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)执行命令。

docker-ce\components\cli\cmd\docker\docker.gonewDockerCommand中,可以知道root命令的实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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,
	}

从代码中可以清晰的把UseShort命令输出对应起来。

顺便在cobra.go查看到 docker help 命令

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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 的模板输出

1
2
3
4
5
6
var usageTemplate = `Usage:

....

var helpTemplate = `
{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

这样,对docker命令的输出,我们就大概了解了,对cobra如何使用也有一个初略的了解。

docker 命令注册

继续查看docker各个子命令如何注册。 docker.go的第62行,这里注册了所有的命令:

1
commands.AddCommands(cmd, dockerCli)

其对于实现在command\commands\commands.go:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 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, 这是个使用频率非常高的命令,帮助如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
➜  ~ 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 命令的别名,请看:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
➜  ~ 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 psdocker container ls 的作用都是 List containers。知道这个以后,查看代码: docker-ce\components\cli\command\container\ls.go 中有其实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// 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 的输出,可以猜测OptionsFlags的对应关系。继续查看BoolVarP的定义,在spf13/pflag/bool.go

1
2
3
4
5
// 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 -adocker ps --all 是一样的。

spf13/pflag 也是spf13 的一个库,主要处理参数量之类的。因为go是强类型的,所以用户的输入,都要合法的处理成go对应的数据类型。

ls.go 中还新建了一个命令,命名了 pscontainer ls 的别名。

1
2
3
4
5
6
func newListCommand(dockerCli command.Cli) *cobra.Command {
	cmd := *NewPsCommand(dockerCli)
	cmd.Aliases = []string{"ps", "list"}
	cmd.Use = "ls [OPTIONS]"
	return &cmd
}

cobra的简单介绍就到这里,本次实验的docker版本如下:

1
2
➜  ~ docker --version
Docker version 18.09.2, build 6247962

简单小结一下cobra使用:

  • 采用命令模式
  • 完善的帮助command及帮助option
  • 支持选项及速记选项
  • 命令支持别名

urfave/cli

drone help 命令

先看看drone的帮助信息:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
➜  ~ 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子命令:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
➜  ~ 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二级子命令:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
➜  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 命令实现

drone-cli\drone\main.go中配置了一级子命令:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
app.Commands = []cli.Command{
		build.Command,
		cron.Command,
		log.Command,
		encrypt.Command,
		exec.Command,
		info.Command,
		repo.Command,
	    ...
	}

命令的解析执行:

1
2
3
4
if err := app.Run(os.Args); err != nil {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

继续查看repo\repo.go中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 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的子命令注册。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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个函数。

根据名称查找命令:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// 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
}

判断命令名称是否一致:

1
2
3
4
5
6
7
8
9
// 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版本是:

1
2
➜  ~ drone --version
drone version 1.0.7

简单小结一下cobra使用:

  • 实现方式看起来更简单
  • 也有完善的帮助command及帮助option

总结

spf13/cobraurfave/cli 都挺棒的, urfave/cli 更简洁一些 ; spf13/cobra 支持 generator,协助生成项目,功能更强大一些。对Go感兴趣的同学,推荐都了解一下。

参考链接

What is the essential difference between urfave/cli и spf13/cobra?

Golang之使用Cobra

python命令行工具