博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go 优秀库推荐 - 命令行工具 cobra
阅读量:7100 次
发布时间:2019-06-28

本文共 11485 字,大约阅读时间需要 38 分钟。

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的帮助:

➜  ~ dockerUsage:	docker [OPTIONS] COMMANDA self-sufficient runtime for containersOptions:      --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 quitManagement 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函数开始:

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命令的实现:

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 命令

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各个子命令如何注册。 docker.go的第62行,这里注册了所有的命令:

commands.AddCommands(cmd, dockerCli)复制代码

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

// AddCommands adds all the commands from cli/command to the root commandfunc 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` subcommandsfunc 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, 这是个使用频率非常高的命令,帮助如下:

➜  ~ docker ps --helpUsage:	docker ps [OPTIONS]List containersOptions:  -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 --helpUsage:	docker container COMMANDManage containersCommands:  ...  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 中有其实现:

// 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

// 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 的别名。

func newListCommand(dockerCli command.Cli) *cobra.Command {	cmd := *NewPsCommand(dockerCli)	cmd.Aliases = []string{
"ps", "list"} cmd.Use = "ls [OPTIONS]" return &cmd}复制代码

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

➜  ~ docker --versionDocker version 18.09.2, build 6247962复制代码

简单小结一下cobra使用:

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

urfave/cli

drone help 命令

先看看drone的帮助信息:

➜  ~ drone --helpNAME:   drone - command line utilityUSAGE:   drone [global options] command [command options] [arguments...]VERSION:   1.0.7COMMANDS:     ...     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 repoNAME:   drone repo - manage repositoriesUSAGE:   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 listOPTIONS:   --help, -h  show help复制代码

再看看drone repo ls二级子命令:

➜  rone repo ls --helpNAME:   drone repo ls - list all reposUSAGE:   drone repo ls [command options]OPTIONS:   --format value  format output (default: "{
{ .Slug }}") --org value filter by organization复制代码

drone 命令实现

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 existfunc (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 namefunc (c Command) HasName(name string) bool {	for _, n := range c.Names() {		if n == name {			return true		}	}	return false}复制代码

本次实验的drone版本是:

➜  ~ drone --versiondrone version 1.0.7复制代码

简单小结一下cobra使用:

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

总结

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

参考链接

转载于:https://juejin.im/post/5cbd10a7f265da03b8584e47

你可能感兴趣的文章
oracle 运行startup报错failure in processing system parameters
查看>>
nginx反向代理配置及优化
查看>>
如何自定义View(转)
查看>>
虚拟化之KVM
查看>>
5步搞定CentOS6.7上MongoDB副本集搭建
查看>>
nginx信号控制
查看>>
VDA高可用,在 Delivery Controller 出现故障时可以访问桌面和应用程序
查看>>
申请APNs证书导入到XenMobile 10环境中
查看>>
Citrix Profile Management(UPM) 的高可用性和灾难恢复
查看>>
简述代理模式
查看>>
ExtJS 5正式版
查看>>
android使用系统相机拍照返回照片,并通过webservice上传到服务器上
查看>>
Python入门——简介1
查看>>
nexus的部署
查看>>
分享一个即插即用的私藏缓动动画JS小算法
查看>>
阿里云docker
查看>>
div+css+js实现鼠标略过自动切换的选项卡
查看>>
matlab-基础 figure 关闭所有的figure
查看>>
使用google插件使你的网站支持多语言
查看>>
在Cisco路由器上完整实现OSPF跨网段下IPSec Tunnel模式×××
查看>>