Viper的兄弟Cobra

Tendermint也使用了Cobra工具,Cobra跟Viper是兄弟关系的,都是spf13下面的项目,摘下github上的描述

(spf13何许人也,这么牛逼,写了这么多开源工具。

看了下简介应该是google golang团队的大牛,这些工具也都是基于go语言开发的)

https://github.com/spf13/cobra

Cobra is a library providing a simple interface to create powerful modern CLI interfaces similar to git & go tools.

Cobra is also an application that will generate your application scaffolding to rapidly develop a Cobra-based application.

Cobra provides:

Easy subcommand-based CLIs: app server, app fetch, etc.
Fully POSIX-compliant flags (including short & long versions)
Nested subcommands
Global, local and cascading flags
Easy generation of applications & commands with cobra init appname & cobra add cmdname
Intelligent suggestions (app srver... did you mean app server?)
Automatic help generation for commands and flags
Automatic help flag recognition of -h, --help, etc.
Automatically generated bash autocomplete for your application
Automatically generated man pages for your application
Command aliases so you can change things without breaking them
The flexibility to define your own help, usage, etc.
Optional tight integration with viper for 12-factor apps

大意是COBRA是一个提供简单界面的库,用来创建类似Git和GO工具的强大的现代CLI(command -line interface)接口,能快速开发基于Cobra的应用程序

还是先简单介绍下怎么使用Cobra吧

定义Cobra command:

// nodeCmd is the entry point for this binary
var nodeCmd = &cobra.Command{
	Use:   "node",
	Short: "Ultron Network",
	Run:   func(cmd *cobra.Command, args []string) { cmd.Help() },
}

添加command:

nodeCmd.AddCommand(
	basecmd.InitCmd,
	basecmd.GetStartCmd(),
)

把这些command都append到map []*Command内

比如InitCmd的定义

var InitCmd = GetInitCmd()

func GetInitCmd() *cobra.Command {
	initCmd := &cobra.Command{
		Use:   "init",
		Short: "Initialize",
		RunE:  initFiles,
	}
	initCmd.Flags().String(FlagChainID, "local", "Chain ID")
	return initCmd
}

func initFiles(cmd *cobra.Command, args []string) error {
	initTendermint()
	return initEthermint(args)
}

运行

basecmd.SetUpRoot(TravisCmd)
executor := cli.PrepareMainCmd(TravisCmd, "UL", os.ExpandEnv("$HOME/.travis-cli"))
executor.Execute()

命令行使用

命令行使用的时候就是使用定义的Cobra command,使用command我们大都用过,格式如下:

$cmd  $sub_cmd --$flag $value

比如node init的用法就是:

./travis node init --home $home

travis就是根命令

node就是子命令

init也是一个子命令

home就是flag,value就是具体的值

这样不同的参数会调用到不同的cobra command去,比如ndoe init最终调用到了initFiles,输入的参数作为函数的参数传递过去

一般简单的程序处理命令以及参数的做法,就是switch命令去做不同的处理,

cobra做了一层有效的封装,方便开发

总结:

使用cobra处理输入cli命令方便了不少,可以作为一个有利的开发工具

我发现牛逼的项目在于组合了牛逼的项目简化开发,专注实现自己的核心功能,组合出了更加牛逼的项目

平时还是接触其他项目太少,知识广度不够。程序员也应该跟文人墨客一样,饱读程序,这样写起代码就可以信手拈来,随意组合,也许就能创造出划时代的项目(不过重要的还是想法,没有想法的引用代码只能算是简单的堆砌

猜你喜欢

转载自blog.csdn.net/csds319/article/details/81110757