您好,欢迎访问一九零五行业门户网

Cobra 命令行开发

问题在网上查找过很多关于 cobra 的开发资料,大多数都是复制官网的教程,极度缺乏参考价值;所以在开发完项目之后,准备自己来写一篇 cobra 的开发教程。
cobra 概述cobra 是一个库,它提供了一个简单的界面来创建强大的现代 cli 界面,类似于 git 和 go 工具。
眼镜蛇提供:
简单的基于子命令的 cli:app server、app fetch等。完全符合 posix 的标志(包括短版和长版)嵌套子命令全局、本地和级联标志明智的建议(app srver......你的意思是app server?)命令和标志的自动帮助生成-h,--help等的自动帮助标志识别为您的应用程序自动生成 shell 自动完成功能(bash、zsh、fish、powershell)为您的应用程序自动生成的手册页命令别名,这样您就可以在不破坏它们的情况下进行更改定义您自己的帮助、使用等的灵活性。可选与viper[1]无缝集成,用于 12-factor 应用程序。安装使用 cobra 很容易。首先,用于go get安装最新版本的库。
go get -u github.com/spf13/cobra@latest
接下来,在您的应用程序中包含 cobra:
import "github.com/spf13/cobra"
用法使用 cobra 自带的 cli 工具 生成项目安装 cli 工具go install github.com/spf13/cobra-cli@latest
使用方式
创建一个新的文件夹cd 到这个文件夹里面去运行 go mod init <modname> 来创建一个go mod 项目例如:
cd $home/code mkdir myappcd myappgo mod init github.com/spf13/myapp
初始化 cobra cli 应用程序从 go 模块中运行 cobra-cli init。这将创建一个新的基本项目让您修改。
您将需要打开并编辑 cmd/root.go 并提供您自己的描述和逻辑。
例如:
cd $home/code/myappcobra-cli initgo run main.go
将命令添加到项目初始化 cobra 应用程序后,您可以继续使用 cobra 生成器向您的应用程序添加其他命令。执行此操作的命令是cobra-cli add.
在您的项目目录(您的 main.go 文件所在的位置)中,您将运行以下命令:
cobra-cli add servecobra-cli add configcobra-cli add create -p 'configcmd'
其中还有很多标志我这里就不在细说了,需要了解的可以访问 cobra-cli[2] 自行查看。
采用手动进行项目开发我们先来看一下 cobra 推荐的项目目录结构
▾ appname/ ▾ cmd/ add.go your.go commands.go here.go main.go
并且在main.go 中应该非常的简单:
package mainimport ( "{pathtoyourapp}/cmd")func main() { cmd.execute()}
然后需要创建一个 rootcmd 来当做 命令的入口 (在 cmd/root.go 中)
var rootcmd = &cobra.command{ use: "hugo", short: "hugo is a very fast static site generator", long: `a fast and flexible static site generator built with love by spf13 and friends in go. complete documentation is available at http://hugo.spf13.com`, run: func(cmd *cobra.command, args []string) { // do stuff here },}func execute() { if err := rootcmd.execute(); err != nil { fmt.fprintln(os.stderr, err) os.exit(1) }}
您将在 init() 函数中另外定义标志和句柄配置。
package cmdimport ( "fmt" "os" "github.com/spf13/cobra" "github.com/spf13/viper")var ( // used for flags. cfgfile string userlicense string rootcmd = &cobra.command{})// execute executes the root command.func execute() error { return rootcmd.execute()}func init() { cobra.oninitialize(initconfig) rootcmd.persistentflags().stringvar(&cfgfile, "config", "", "config file (default is $home/.cobra.yaml)") rootcmd.persistentflags().stringp("author", "a", "your name", "author name for copyright attribution") rootcmd.persistentflags().stringvarp(&userlicense, "license", "l", "", "name of license for the project") rootcmd.persistentflags().bool("viper", true, "use viper for configuration") viper.bindpflag("author", rootcmd.persistentflags().lookup("author")) viper.bindpflag("useviper", rootcmd.persistentflags().lookup("viper")) viper.setdefault("author", "name here <email address>") viper.setdefault("license", "apache") rootcmd.addcommand(addcmd) rootcmd.addcommand(initcmd)}func initconfig() { if cfgfile != "" { // use config file from the flag. viper.setconfigfile(cfgfile) } else { // find home directory. home, err := os.userhomedir() cobra.checkerr(err) // search config in home directory with name ".cobra" (without extension). viper.addconfigpath(home) viper.setconfigtype("yaml") viper.setconfigname(".cobra") } viper.automaticenv() if err := viper.readinconfig(); err == nil { fmt.println("using config file:", viper.configfileused()) }}
接下来就是开发 配置各种 cobra cmd 的参数,在配置之前,我们先来熟悉一下 cmd 的内容。
type command struct { // 使用是单行使用消息。 // 推荐的语法如下: // [ ] 标识一个可选参数。未括在括号中的参数是必需的。 // ... 表示您可以为前一个参数指定多个值。 // |表示互斥信息。您可以使用分隔符左侧的参数或分隔符右侧的参数。您不能在一次使用该命令时同时使用这两个参数。 // { } 分隔一组互斥参数,当需要其中一个参数时。如果参数是可选的,则将它们括在方括号 ([ ]) 中。 // 示例:add [-f file | -d dir]... [-f format] profile use string // aliases 是一个别名数组,可以用来代替 use 中的第一个单词。 aliases []string // suggestfor 是一个命令名称数组,将为其建议该命令 - 类似于别名,但只是建议。 suggestfor []string // short 是“帮助”输出中显示的简短描述。 short string // long 是“help <this-command>”输出中显示的长消息。 long string // example is examples of how to use the command. example string // validargs 是 shell 完成中接受的所有有效非标志参数的列表,(提供的自动补全的参数) validargs []string // validargsfunction 是一个可选函数,它为 shell 完成提供有效的非标志参数。 // 它是使用 validargs 的动态版本。只有 validargs 和 validargsfunction 之一可用于命令。 validargsfunction func(cmd *command, args []string, tocomplete string) ([]string, shellcompdirective) // 判断参数的格式,内置多种验证格式。 args positionalargs // argaliases 是 validargs 的别名列表。这些不是在 shell 完成中向用户建议的,但如果手动输入则接受。 argaliases []string // bashcompletionfunction 是传统 bash 自动完成生成器使用的自定义 bash 函数。 // 为了与其他 shell 的可移植性,建议改用 validargsfunction bashcompletionfunction string // deprecated defines, if this command is deprecated and should print this string when used. deprecated string // annotations are key/value pairs that can be used by applications to identify or // group commands. annotations map[string]string // version defines the version for this command. if this value is non-empty and the command does not // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, // will print content of the "version" variable. a shorthand "v" flag will also be added if the // command does not define one. version string // run 函数按以下顺序执行: // * persistentprerun() // * prerun() // * run() // * postrun() // * persistentpostrun() // 所有函数都获得相同的参数,即命令名称后面的参数。 // // persistentprerun: 该命令的子级将继承并执行。 persistentprerun func(cmd *command, args []string) // persistentprerune: 上面的返回错误形式 persistentprerune func(cmd *command, args []string) error // prerun: 此命令的子级不会继承。 prerun func(cmd *command, args []string) // prerune: 上面的返回错误形式 prerune func(cmd *command, args []string) error // run: 通常是实际的功函数。大多数命令只会实现这一点。 run func(cmd *command, args []string) // rune: 上面返回错误的形式 rune func(cmd *command, args []string) error // postrun: 在 run 命令之后运行。 postrun func(cmd *command, args []string) // postrune: 上面返回错误的形式。 postrune func(cmd *command, args []string) error // persistentpostrun: 该命令的子命令将在 postrun 之后继承并执行。 persistentpostrun func(cmd *command, args []string) // persistentpostrune: 上面返回错误的形式。 persistentpostrune func(cmd *command, args []string) error ... //fparseerrwhitelist flag parse errors to be ignored fparseerrwhitelist fparseerrwhitelist // completionoptions 是一组用于控制 shell 完成处理的选项 (下面给出了对应的结构体) completionoptions completionoptions ... // traversechildren 在执行子命令之前解析所有父项的标志。 traversechildren bool // hidden defines, 如果此命令被隐藏并且不应该出现在可用命令列表中。 hidden bool ...}
// completionoptions are the options to control shell completiontype completionoptions struct { // disabledefaultcmd 防止 cobra 创建默认的“完成”命令 (禁用这么默认的 cmd 命令) disabledefaultcmd bool // 防止 cobra 为支持完成描述的 shell 创建“--no-descriptions”标志 disablenodescflag bool // disabledescriptions 关闭支持它们的 shell 的所有完成描述 disabledescriptions bool // hiddendefaultcmd 隐藏默认的“完成”命令 (一般情况下,采用隐藏这个 cmd ) hiddendefaultcmd bool}
这里大概就看了 cmd  的大概使用的结构体和字段,在开发的时候对应需要的东西,直接设置对应的值即可。
short 的描述使用 shell 自动完成提示信息使用。
long 的描述用于 -h 或 help  打印使用。
生成自动提示命令的功能具体的操作步骤可以看 生成外壳完成[3]
在这里需要说一句的是:使用命令生成的时候默认是打印在 控制台,需要自己重定义在指定的目录文件中去。
在根据不同的平台终端,配置好这个文件,然后就可以使用 自动提示完成的 功能了。
以上就是cobra 命令行开发的详细内容。
其它类似信息

推荐信息