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

相关内容

热门资讯

扩张提速、店铺“加密”,“硬折... 北京“硬折扣”超市“迎新”。6月26日,盒马旗下平价社区超市超盒算NB首批6家门店同步开业,网点覆盖...
外媒:黄金白银遭遇“完美风暴” 参考消息网6月26日报道据西班牙《经济学家报》网站6月23日报道,贵金属在金融市场正经历一场名副其实...
原创 法... 巴黎《费加罗报》给中国扣上"拯救者"的帽子,纽约《华尔街日报》隔着大西洋默默点头。 两家立场南辕北辙...
金价大跌!有商家囤货资产缩水百... 近期,国际金价持续大幅下行。6月26日19时30分左右,伦敦金现货价格报4050美元/盎司,较年内高...
原创 人... 大家好,这里是史记文谭,闲中着色,笑里有情,不废观星问月,亦赏市井浮生。 前言 咱们每天兜里揣着的钱...
交运股份告别六年扣非亏损,更名... 本报记者 张蓓 陈炳衡 北京报道 日前,上海交运集团股份有限公司(600676.SH)召开2026年...
原创 星... 马斯克的手又伸长了。这次不是火箭回收,也不是把"星链"塞进乌克兰战壕,而是直接杀进美国消费者的手机号...
视频丨一部剧带火一座城 “追剧... 第31届上海电视节各奖项昨晚(26日)揭晓,谍战题材电视剧《沉默的荣耀》在5项重磅提名中,最终斩获评...
东京经济论坛现场观察:日本华商... 作者 | 东京谢社长 6月26日,我去东京丽嘉皇家酒店参加了东京国际商学院EMBA二期开学典礼暨...
苏州投资人问:土耳其20年免税... 苏州投资人问:土耳其20年免税到底怎么理解? 最近一段时间,苏州工业园区和外企圈子里,关于土耳其20...
刘强东为70万京东物流人员规划... 职业被智能化设备迭代替代,已经成为当下众多从业者共同的内心顾虑。近期刘强东在行业论坛的发言,再度引发...
富国基金换帅:裴长江退休卸任,... 6月26日,富国基金发布高级管理人员变更的公告,董事长裴长江因退休离任,申万宏源证券执行委员会成员王...
两部门最新发布!事关黄金及黄金... 6月26日,中国人民银行、海关总署联合发布通知,就《黄金及黄金制品进出口管理办法(征求意见稿)》向社...
中信重工重构全球矿山装备供应链... 文丨承承 编辑丨李壮 2026年盛夏,第四届“中国国际供应链促进博览会”在北京顺义拉开帷幕。在中信集...
全球爆火的ETF,纳入中国存储... 史上增长最快的新发ETF,刚刚把"中国存储龙头"买成了前十大重仓! 6月,Roundhill Mem...
金价暴跌!重回“3字头”时代 继6月24日、25日伦敦金现连续两日盘中跌破4000美元/盎司后,6月26日国际金价延续跌势。 截至...
一批站在“光”里的基金经理们,... 【导读】一批绩优“追光者”密集出手限购,年内业绩前十均已“闭门谢客” 中国基金报记者 曹雯璟 仅过了...
赛场出圈,多品类业务破局,蒙牛... 2026世界杯加持,股价逆势走高! 文/每日财报 南黎 夏日的墨西哥城阿兹特克体育场,伴随着202...
IPO抢着给科技输血,钱却在选... 2026年上半年,A股IPO市场交出81家上市、1057亿元募资的成绩单,新股首日回报率233%创近...
原创 缅... 缅甸领导人敏昂莱结束访华行程刚回到内比都,缅甸官方就向全世界扔出了一枚重磅炸弹——正式宣布发现总规模...