基于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

相关内容

热门资讯

强外贸拓市场 宜宾19家企业亮... 4月15日至5月5日,第139届中国进出口商品交易会(简称“广交会”)在广州举办。活动期间,宜宾市商...
原创 运... 运-20运输机近日再一次展现了其非凡能力——为救治一名身处西藏阿里高原的重病边防战士,它完成了一次跨...
水井坊总经理再变动!胡庭洲在任... 在刚刚披露完2025年报和2026年一季报后,水井坊再次迎来核心高管的变动。 5月6日,水井坊发布公...
康宁公司(GLW)维持超过14... 康宁公司(GLW)维持超过14%的涨幅,持稳于185美元附近,美股盘初曾达到195.81美元——盘中...
原创 国... 阅读须知:本文内容所有信息和数据,均为作者查阅官方信息和网络已知数据整合解析,旨在让读者更清晰了解相...
原创 金... 2026年5月6日,国内金价继续从高位回落,上海黄金交易所的AU9999报每克1013元,沪金期货主...
新华鲜报丨交易笔数大增 从支付...   新华社北京5月6日电(记者吴雨)消费市场活力十足,尽显中国经济强劲韧性。中国人民银行5月6日发布...
原创 安... - 对外直接投资[1]:2026年一季度中国全行业对外直接投资445亿美元,同比增长8.9%;非金融...
龙芯中科:现在公司主打性价比,... 证券日报网5月6日讯 ,龙芯中科在接受调研者提问时表示,公司过去主打芯片自主性,所以是应用导向的,比...
新华鲜报|交易笔数大增 从支付... 消费市场活力十足,尽显中国经济强劲韧性。中国人民银行5月6日发布的数据显示,今年“五一”假期支付交易...
马斯克同意支付150万美元罚款 据路透社报道,4日提交的一份法庭文件显示,美国证券交易委员会已经与美国企业家马斯克就收购推特期间涉嫌...
福建沙县农商银行被罚170万元 【大河财立方消息】5月6日,国家金融监督管理总局三明监管分局披露的行政处罚信息显示,因违规下达存款考...
原创 只... 此前盛传三星要暴砍中国市场产品线的消息,终于落地了。 5月6日,三星在官网正式发布公告,停止在中国大...
珀莱雅上市9年首次“双降”,二... 出品 |达摩财经 此次是珀莱雅第二次向港交所递表。去年8月,珀莱雅发布公告称,为加快国际化战略和海...
沿河县中界镇创新“三营联动”发... 沿河县中界镇创新“三营联动” 发展壮大农村集体经济 近年来,沿河县中界镇聚焦“强村富民”目标,创新推...
老牌私募打新违规被“点名”! 来源:金融时报 一家老牌私募机构因网下打新违规被“点名”。 近日,中国证券业协会(以下简称“中证协”...
和讯信息张杨:五月开门红!存储... 5月开门红,存储芯片大涨还能不能在科技里躺平了?和讯信息张杨分析,首先是假期外围大涨,导致今天芯片大...
警报响起!30年期美债收益率再... 全球股市处于历史高位,但债券市场的警示信号越来越清晰。 30年期美国国债收益率重新站上5%的关口,再...
五粮液急了!先推80亿元至10... 年报推迟公布之后,五粮液摊上事了。股民纷纷质疑五粮液“修改数据”,二级市场,公司股价今日逆市下跌近5...
收假必看!央行+海关新政落地,... 来源:市场资讯 (来源:矿业俱乐部) 央行、海关总署联合发布公告,自2026年6月1日起升级黄金及...