基于cobra的go语言命令行解析器
admin
2024-02-02 20:10:25
0

ubuntu安装cobra

$ sudo apt install cobra
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following NEW packages will be installed:cobra
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 2,873 kB of archives.
After this operation, 9,495 kB of additional disk space will be used.
Get:1 http://mirrors.tuna.tsinghua.edu.cn/ubuntu focal/universe amd64 cobra amd64 0.0.5-1 [2,873 kB]
Fetched 2,873 kB in 2s (1,272 kB/s) 
Selecting previously unselected package cobra.
(Reading database ... 188150 files and directories currently installed.)
Preparing to unpack .../cobra_0.0.5-1_amd64.deb ...
Unpacking cobra (0.0.5-1) ...
Setting up cobra (0.0.5-1) ...
Processing triggers for man-db (2.9.1-1) ...

Go在项目中使用cobra

import "github.com/spf13/cobra/cobra"

使用cobra创建项目
创建项目建议使用Go module模式,首先,创建一个go module项目,项目名称为arsenal

root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# go mod init arsenal
go: creating new go.mod: module arsenal
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ll
total 12
drwxr-xr-x 2 root root 4096 11月 18 21:25 ./
drwxr-xr-x 6  644 root 4096 11月 18 21:25 ../
-rw-r--r-- 1 root root   24 11月 18 21:25 go.mod

arsenal目录中添加cobra项目。

root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# cobra init --pkg-name arsenal
Your Cobra applicaton is ready at
/home/curtis/go_env/arsenalroot@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# tree .
.
├── cmd
│   └── root.go	# 最顶层的命令rootCmd
├── go.mod
├── LICENSE	 # license信息
└── main.go

编译之前下载几个依赖包

root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# go build
cmd/root.go:24:3: no required module provides package github.com/mitchellh/go-homedir; to add it:go get github.com/mitchellh/go-homedir
cmd/root.go:22:3: no required module provides package github.com/spf13/cobra; to add it:go get github.com/spf13/cobra
cmd/root.go:25:3: no required module provides package github.com/spf13/viper; to add it:go get github.com/spf13/viper# 执行生成的可执行文件
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal 
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.

编译出来的二进制文件arsenal默认打印的信息是怎么来的?来自rootCmd命令的长描述信息。

// cmd/root.go
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{Use:   "arsenal",Short: "A brief description of your application",Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,// Uncomment the following line if your bare application// has an action associated with it://    Run: func(cmd *cobra.Command, args []string) { },
}

尝试修改rootCmd命令的描述信息。

var rootCmd = &cobra.Command{Use:   "arsenal",Short: "A brief description of your application",Long: "This is long description of your application",	// 出现在-h的帮助信息中// Uncomment the following line if your bare application// has an action associated with it://      Run: func(cmd *cobra.Command, args []string) { },
}

执行命令

root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal 
This is long description of your application

添加子命令,比如说添加一个版本信息

root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# cobra add version
version created at /home/curtis/go_env/arsenal
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# tree .
.
├── arsenal
├── cmd
│   ├── root.go
│   └── version.go	# 新添加了一个versoin.go
├── go.mod
├── go.sum
├── LICENSE
└── main.go# go build编译之后执行命令
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal 
This is long description of your applicationUsage:arsenal [command]Available Commands:completion  Generate the autocompletion script for the specified shellhelp        Help about any command	# 添加的子命令version     This short information about version	# 可以看到version子命令的短描述信息Flags:--config string   config file (default is $HOME/.arsenal.yaml)-h, --help            help for arsenal-t, --toggle          Help message for toggleUse "arsenal [command] --help" for more information about a command.# 执行了注册的Run 函数,该函数打印了信息version called
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal version 
version called# -h 信息可以看到version 命令的长信息
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal version -h
This long information about versionUsage:arsenal version [flags]Flags:-h, --help   help for versionGlobal Flags:--config string   config file (default is $HOME/.arsenal.yaml)

如何把命令绑定到父命令中,可以无限制的往下添加。

# 不做任何处理
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# cobra add cpu
cpu created at /home/curtis/go_env/arsenalroot@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# 
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# tree .
.
├── arsenal
├── cmd
│   ├── cpu.go
│   ├── root.go
│   └── version.go
├── go.mod
├── go.sum
├── LICENSE
└── main.go1 directory, 8 files
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# go build
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal 
This is long description of your applicationUsage:arsenal [command]Available Commands:completion  Generate the autocompletion script for the specified shellcpu         A brief description of your commandhelp        Help about any commandversion     This short information about versionFlags:--config string   config file (default is $HOME/.arsenal.yaml)-h, --help            help for arsenal-t, --toggle          Help message for toggleUse "arsenal [command] --help" for more information about a command.

添加子命令
将上述cpu子命令添加到version下修改之后。

// 只需要将cpuCmd添加到versionCmd之下就可以了。
func init() {// 使用cobra add默认将命令添加到rootCmd// 可以尝试修改添加到version cmd之下versionCmd.AddCommand(cpuCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// cpuCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:// cpuCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal version -h
This long information about versionUsage:arsenal version [flags]arsenal version [command]Available Commands:cpu         A brief description of your command	# 子命令添加成功Flags:-h, --help   help for versionGlobal Flags:--config string   config file (default is $HOME/.arsenal.yaml)Use "arsenal version [command] --help" for more information about a command.

选项的接收与处理

var versionCmd = &cobra.Command{Use:   "version",Short: "This short information about version",Long:  "This long information about version",Run: func(cmd *cobra.Command, args []string) {fmt.Println("version called")// 各个选项参数获取auther, err := cmd.Flags().GetString("auther")if err != nil {fmt.Println("请输入正确的作者信息")return}fmt.Println("作者是: ", auther)},
}func init() {rootCmd.AddCommand(versionCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// versionCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:// versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")// 添加version参数auther,a为别名,默认值为cutisversionCmd.Flags().StringP("auther", "a", "curtis", "The auther name")// 添加version参数percent,p为别名,默认值为60%versionCmd.Flags().StringP("percent", "p", "60%", "The percent of cpu")
}
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal version -h
This long information about versionUsage:arsenal version [flags]arsenal version [command]Available Commands:cpu         A brief description of your commandFlags:-a, --auther string    The auther name (default "curtis")-h, --help             help for version-p, --percent string   The percent of cpu (default "60%")Global Flags:--config string   config file (default is $HOME/.arsenal.yaml)Use "arsenal version [command] --help" for more information about a command.

选项常见的类型

  • 布尔值
  • 数字(各种整形,浮点数等)
  • 字符串
  • 其他高级类型

选项的帮助信息

命令自动补全补全功能
从上面构建的工程来看,cobra已经把自动补全的功能默认添加到项目中,使用方法如下所示。

root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal completion bash -h 
Generate the autocompletion script for the bash shell.This script depends on the 'bash-completion' package.
If it is not installed already, you can install it via your OS's package manager.To load completions in your current shell session:source <(arsenal completion bash)	# 只有在当前shell终端生效To load completions for every new session, execute once:#### Linux:arsenal completion bash > /etc/bash_completion.d/arsenal	# 永久生效#### macOS:arsenal completion bash > $(brew --prefix)/etc/bash_completion.d/arsenalYou will need to start a new shell for this setup to take effect.Usage:arsenal completion bashFlags:-h, --help              help for bash--no-descriptions   disable completion descriptionsGlobal Flags:--config string   config file (default is $HOME/.arsenal.yaml)

启用自动补全功能之后,使用tab命令没有自动补全,报错如下。

root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# source <(./arsenal completion bash)
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal ver_get_comp_words_by_ref: command not found
_get_comp_words_by_ref: command not found
_get_comp_words_by_ref: command not found

可能原因是有可能没有安装bash-completion包,安装方法即开启命令自动补全如下所示。

# 安装bash-completion包
$ sudo apt install bash-completion# 启用completion功能
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# source /usr/share/bash-completion/bash_completion
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# source <(./arsenal completion bash)# 可以使用tab键自动补全命令
root@curtis-Aspire-E5-471G:/home/curtis/go_env/arsenal# ./arsenal version cpu

相关内容

热门资讯

银华专精特新量化优选股票发起式... AI基金银华专精特新量化优选股票发起式A(014668)披露2025年四季报,第四季度基金利润270...
知名脑科旗舰医院,迎来大型新院... 首都医科大学三博脑科医院东坝新院区即将启用了。 近日,三博脑科医院官微消息称,2026年1月26日,...
《经济学人》警告西方政要:被特... 最近西方舆论场悄然兴起了一种论调,即将近期多位西方国家领导人的密集访华之行解读为“向中国求救”——意...
公司热点|奥飞数据近17亿定增... 深圳商报·读创客户端记者 梁佳彤 1月22日晚间,奥飞数据(300738)发布公告称,公司召开第四届...
原创 很... 这事我反复思考了不止一遍:为啥那么多烂尾楼摆在那儿,看着唾手可得,却没有其他开发商上来“捡漏”? 真...
南向资金追踪|净买入逾52亿港... 财联社1月22日讯(编辑 冯轶)据Wind数据显示,南向资金今日成交约931.59亿港元,较前一日再...
潍坊市跨境电商+AI知识培训成... 1月20日-21日,潍坊市跨境电商+AI知识培训成功举办。我市拟开展跨境电商业务的生产性企业、外贸企...
日美成为金融市场动荡的震源 据日经中文网1月22日报道,日美正在成为导致全球金融市场发生动荡的震源地。日本方面,执政党和在野党在...
阿里巴巴美股盘前一度涨超5%,... 红星资本局1月22日消息,阿里巴巴美股(BABA.US)盘前突然走高,一度涨超5%。 消息面上,有报...
多家银行发文明确信用卡账单分期... 北京商报讯(记者 孟凡霞 周义力)消费贷贴息政策持续加码!1月20日,财政部、中国人民银行、金融监管...
大摩品质生活精选股票A:202... AI基金大摩品质生活精选股票A(000309)披露2025年四季报,第四季度基金利润1364.19万...
博裕资本再布局高端零售、拟收购... 1月22日,北京商报报道,据北京市监局官网近日公示经营者集中简易案件,博裕资本将收购北京八达岭奥莱项...
平阴龙头民企换帅:郭雷出任玫德... 近日,济南平阴最大民企玫德集团有限公司(简称“玫德集团”)发生工商变更,公司原法定代表人、董事长兼总...
特朗普宣布加征200%关税后,... 1月19日,一条震撼消息迅速在法国的酿酒界引发了巨大的反响。特朗普宣布,将对法国产的葡萄酒和香槟征收...
中国邮政在福建成立新科技公司 ... 天眼查工商信息显示,近日,福建十睿科技有限公司成立,法定代表人为吕佳宜,注册资本1000万人民币,经...
掘金港股IPO,理财公司权益投... 来源:市场资讯 文/北京商报记者 宋亦桐 2026年年初,港股市场迎来新一轮新股上市潮,一批硬科技赛...
潘功胜:专设5000亿元服务消... 据新华社报道,1月22日,中国人民银行行长潘功胜表示,引导金融机构加力支持扩大内需、科技创新、中小微...
行业动态 | 财政部发布《关于... 财库〔2026〕2号 各中央预算单位,各省、自治区、直辖市、计划单列市财政厅(局),新疆生产建设兵团...
玲珑轮胎终止港交所上市:202... 瑞财经 刘治颖1月22日,玲珑轮胎(SH601966)公告,经公司与相关中介机构进行深入探讨与审慎分...
事关贷款贴息、中小微企业贷款担... 1月20日,财政部官网连续发布5个文件,涉及个人消费贷、民间投资等领域。 “延长、扩大、提高”成为关...