基于cobra的go语言命令行解析器

news/2024/4/17 4:24:15/文章来源:https://blog.csdn.net/qq_42931917/article/details/127929918

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 1118 21:25 ./
drwxr-xr-x 6  644 root 4096 1118 21:25 ../
-rw-r--r-- 1 root root   24 1118 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_224191.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在群晖NAS上搭建导航页_通过Web Station搭建

一、业务需求 1.1、需求说明 我们在使用群晖NAS的过程中&#xff0c;随着时间的推移会安装各种各样的软件内容和管理工具&#xff0c;而这些内容又都是一些网页界面&#xff08;特别是一些在Docker中搭建的工具&#xff09;时间久了我们也记不住那么多工具的Web界面地址&#…

简易版 图书管理系统

目录 1. Book包 1.1 Book类 1.2 BookList类 2. User包 2.1 User抽象类 2.2 AdminUser类 2.3 NormalUser类 3. Operate包 3.1 MyOperate接口 3.2 AddOperation类 3.3 DelOperation类 3.4 ExitOperation 3.5 FindOperation类 3.6 ShowOperation类 3.7 BorrowedOpe…

QT 发布文章遇到问题解决方案

提供了两种可以发布 Qt 程序的方案&#xff0c;建议使用第二种直接生成对应的文件&#xff0c;直接打包就可以 1. 手动复制需要的文件到运行目录下 我们写完 QT 程序当然是要发布或者发给其他需要用到的人&#xff0c;由于找不到Qt6Core.dll,无法继续执行代码,打开 realease …

菜小白聊聊开源和开源协议

最近想入linux的深坑&#xff0c;于是开启了马哥sre课程的探险之旅。在了解到Linux是一款自由和开放源码的类UNIX操作系统的历史时&#xff0c;深深被开源精神所折服。也强烈感受到了开源精神的伟大。也正是因为有了开放源码的精神&#xff0c;才有了国产百花齐放的android系统…

java计算机毕业设计ssm金华学校社团管理系统

项目介绍 随着计算机信息技术的迅猛发展,互联网技术大规模应用到各行各业,传统的管理系统也逐渐精细化。高校作为教书育人的场所,各种管理也更应该智能化,特别是计算机信息专业更是最早接触信息技术,为高校各部门开发必要的系统是很有意义的事情。本金华学校社团管理系统对社团…

wireshark提取视频数据之RTP包中提取H264和H265

wireshark提取视频数据之RTP包中提取H264和H265 文章目录wireshark提取视频数据之RTP包中提取H264和H2651 背景2 提取前工作3 H264视频从RTP包中提取步骤4 H265视频从RTP包中提取步骤5 后记1 背景 在流媒体相关问题分析时&#xff0c;抓包分析是非常重要的手段&#xff0c;比如…

数据结构---串(整个部分)

串基本概念&#xff1a;串是由零个或者多个字符组成的有限序列&#xff0c;一半记作Sa1,a2,a3,a4.......&#xff08;n>0&#xff0c;串的长度&#xff09; 1.S 串的名字 n 串当中字符串的个数&#xff0c;称为串的长度。 串的常用术语 1.空串&#xff08;null stri…

七夕,程序员教你5个表白代码,2分钟学会,牢牢主抓她的心

七夕。一个有人欢喜有人愁的节日&#xff0c;虽然对一些单身人士不太友好&#xff0c;但还有不少人都在等这个节日进行表白。毕竟这个日子的成功率会高一些。 情人节少不了送花送礼物&#xff0c;作为一个程序员&#xff0c;当然不会在送什么礼物上给你指点一二&#xff0c;但…

掌控安全学院SOL注入靶场

掌控安全学院SOL注入靶场靶场地址Pass-01 显错注入Pass-02Pass-03Pass-04Pass-05 POST注入Pass-06Pass-07 Head注入Pass-08Pass-09Pass-10 布尔盲注Pass-11Pass-12Pass-13 延时注入Pass-14Pass-15 宽字节注入Pass-16Pass-17总结靶场地址 http://inject2.lab.aqlab.cn Pass-01…

Java实现图书管理系统

作者&#xff1a;~小明学编程 文章专栏&#xff1a;JavaSE基础 格言&#xff1a;目之所及皆为回忆&#xff0c;心之所想皆为过往 今天给大家带来的是用Java实现的图书管理系统。 目录 需求 图书类 创建图书类 创建书架 Operation IOperation接口 添加图书AddOperation…

【考研复试】计算机专业考研复试英语常见问题三(个人选择/学业规划篇)

相关链接&#xff1a; 【考研复试】计算机专业考研复试英语常见问题一&#xff08;家庭/家乡/学校篇&#xff09;【考研复试】计算机专业考研复试英语常见问题二&#xff08;研究方向/前沿技术/本科毕设篇&#xff09;【考研复试】计算机专业考研复试英语常见问题三&#xff0…

kubernetes集群基于kubeadm部署以及常见问题解决

文章目录集群类型主机规划环境初始化检查操作系统版本关闭防火墙设置主机名主机名解析时间同步关闭 SELinux关闭 swap 分区将桥接的IPv4流量传递到iptables的链开启ipvs安装容器运行时&#xff08;Docker&#xff09;卸载Docker旧版本&#xff1a;安装 gcc 相关安装Docker设置阿…

一个Adapter+recycleview实现多种布局,区分布局中

文章目录&#x1f353;&#x1f353;简述&#x1f353;&#x1f353;效果图&#x1f353;&#x1f353;代码&#x1f96d;&#x1f96d;AllAdapter.java&#x1f96d;&#x1f96d; FuritAdapter3.java&#x1f96d;&#x1f96d;MainActivity.java(主函数)&#x1f96d;&#…

【全网热点】打造全网最全爱心代码仓库【火速领取爱心】

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;花无缺 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! 本文由 花无缺 原创 本文章收录于专栏 【代码实践】 目录&#x1f319;正文&#x1f30f;部分效果在线演示&#x1f30f;部分效果截屏&#x1f338;文末祝…

个人设计web前端大作业 基于html5制作美食菜谱网页设计作业代码

&#x1f380; 精彩专栏推荐&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb; ✍️ 作者简介: 一个热爱把逻辑思维转变为代码的技术博主 &#x1f482; 作者主页: 【主页——&#x1f680;获取更多优质源码】 &#x1f393; web前端期末大作业…

Linux的前世今生

14天学习训练营导师课程&#xff1a; 互联网老辛《 符合学习规律的超详细linux实战快速入门》 努力是为了不平庸~ 学习有些时候是枯燥的&#xff0c;但收获的快乐是加倍的&#xff0c;欢迎记录下你的那些努力时刻&#xff08;学习知识点/题解/项目实操/遇到的bug/等等&#xf…

2022年深度学习最新研究成果

一、开源深度学习编译器 二、 开源深度学习加速器 三、AITemplate引擎 四、微型机器学习框架 参考文献&#xff1a;https://arxiv.org/pdf/1510.00149.pdf 五、Contrastive Learning 对比学习综述 六、Diffusion Model 扩散模型综述 Diffusion Models: A Comprehensive Surv…

Java面向对象中阶(七)

面向对象中阶 1、包 2、访问修饰符 3、封装 4、继承 5、方法重写(override) 6、多态 7、Object类的常用方法 8、断点调试 1、包 包的本质&#xff1a; 实际上就是创建不同的文件夹来保存类文件 包的三大作用&#xff1a; 区分相同名字的类当类很多时&#xff0c;可以…

【freeRTOS】操作系统之六-低功耗模式

六&#xff0c;低功耗模式 本章节为大家讲解 FreeRTOS 本身支持的低功耗模式 tickless 实现方法&#xff0c;tickless 低功耗机制是当前小型 RTOS 所采用的通用低功耗方法&#xff0c;比如 embOS&#xff0c;RTX 和 uCOS-III&#xff08;类似方法&#xff09;都有这种机制。ti…

原来背后都是商业利益,看到网易和暴雪的解约之后,原来是要定以后的KPI,坐地起价,但是一个时代已经结束了,都留在了记忆之中

1&#xff0c;大瓜新闻&#xff0c;2023年1月暴雪游戏中国将不会续约&#xff1f;&#xff1f; 2&#xff0c;原因是主要坐地起价&#xff0c;提高分成设置KPI 还好网易有自研游戏&#xff0c;估计早知道会有现在这样的情况。 提前做好了准备。还记得有个公司叫 九城吗&#x…