当前位置:网站首页>Golang — 命令行工具cobra
Golang — 命令行工具cobra
2022-07-03 13:11:00 【风起云边】
Cobra

Cobra是一个用于Go语言的CLI框架。它包含一个用于创建强大的现代CLI应用程序的库,以及一个用于快速生成基于Cobra的应用程序和命令文件的工具。
特性
- 简易的子命令行模式,如 app server, app fetch 等等
- 完全兼容 posix 命令行模式
- 嵌套子命令 subcommand
- 支持全局,局部,串联 flags
- 使用 cobra 很容易的生成应用程序和命令,使用 cobra create appname 和 cobra add cmdname
- 如果命令输入错误,将提供智能建议,如 app srver,将提示 srver 没有,是不是 app server
- 自动生成 commands 和 flags 的帮助信息
- 自动生成详细的 help 信息,如 app help
- 自动识别帮助 flag -h,–help
- 自动生成应用程序在 bash 下命令自动完成功能
- 自动生成应用程序的 man 手册
- 命令行别名
- 自定义 help 和 usage 信息
- 可选的与 viper apps 的紧密集成
概念
Cobra是建立在命令、参数和标志的结构上的。
Commands代表动作,Args是东西,Flags是这些动作的修饰符。
最好的应用读起来像句子。用户会知道如何使用应用程序,因为他们天生就知道如何使用它。
例如:
hugo server --port=1313
Command
Command是应用程序的中心点。应用程序支持的每个交互都包含在Command中。命令可以有子命令,也可以有选择地运行操作。
Flag
flag 是修改命令行为的一种方式。Cobra完全支持兼容posix标志以及Go标志包。Cobra命令可以定义贯穿子命令的标志,以及只对该命令可用的标志。
上面例子中--port即是一个flag
全局标识(Persistent Flags)
全局标识(Persistent Flags)会作用于其指定的命令与指定命令所有的子命令。
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
局部标识(Local Flags)
局部标示(Local Flags)仅作用于其指定命令。
rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
Run Hooks
可以在命令的主run函数之前或之后运行函数。PersistentPreRun和PreRun函数将在Run之前执行。persistentpoststrun和poststrun会在Run之后执行。如果子类不声明自己的Persistent*Run函数,它们将被子类继承。这些函数按以下顺序运行:
- PersistentPreRun
- PreRun
- Run
- PostRun
- PersistentPostRun
示例:
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{
Use: "root [sub]",
Short: "My root command",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
},
PreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd Run with args: %v\n", args)
},
PostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
},
}
var subCmd = &cobra.Command{
Use: "sub [no options!]",
Short: "My subcommand",
PreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd Run with args: %v\n", args)
},
PostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
},
}
rootCmd.AddCommand(subCmd)
rootCmd.SetArgs([]string{
""})
rootCmd.Execute()
fmt.Println()
rootCmd.SetArgs([]string{
"sub", "arg1", "arg2"})
rootCmd.Execute()
}
output:
Inside rootCmd PersistentPreRun with args: []
Inside rootCmd PreRun with args: []
Inside rootCmd Run with args: []
Inside rootCmd PostRun with args: []
Inside rootCmd PersistentPostRun with args: []
Inside rootCmd PersistentPreRun with args: [arg1 arg2]
Inside subCmd PreRun with args: [arg1 arg2]
Inside subCmd Run with args: [arg1 arg2]
Inside subCmd PostRun with args: [arg1 arg2]
Inside subCmd PersistentPostRun with args: [arg1 arg2]
边栏推荐
- MySQL installation, uninstallation, initial password setting and general commands of Linux
- KEIL5出现中文字体乱码的解决方法
- 106. 如何提高 SAP UI5 应用路由 url 的可读性
- stm32和电机开发(从mcu到架构设计)
- Can newly graduated European college students get an offer from a major Internet company in the United States?
- Useful blog links
- 常见的几种最优化方法Matlab原理和深度分析
- Smbms project
- The difference between stratifiedkfold (classification) and kfold (regression)
- Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
猜你喜欢

The shortage of graphics cards finally came to an end: 3070ti for more than 4000 yuan, 2000 yuan cheaper than the original price, and 3090ti

使用Tensorflow进行完整的深度神经网络CNN训练完成图片识别案例2

JSP and filter

Servlet

Internet of things completion -- (stm32f407 connects to cloud platform detection data)

This math book, which has been written by senior ml researchers for 7 years, is available in free electronic version

Today's sleep quality record 77 points

stm32和电机开发(从mcu到架构设计)

刚毕业的欧洲大学生,就能拿到美国互联网大厂 Offer?

Mysql database basic operation - regular expression
随机推荐
rxjs Observable filter Operator 的实现原理介绍
【被动收入如何挣个一百万】
JS convert pseudo array to array
Resource Cost Optimization Practice of R & D team
今日睡眠质量记录77分
STM32 and motor development (from MCU to architecture design)
Libuv Library - Design Overview (Chinese version)
Flink SQL knows why (17): Zeppelin, a sharp tool for developing Flink SQL
实现CNN图像的识别和训练通过tensorflow框架对cifar10数据集等方法的处理
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
Task5: multi type emotion analysis
JSON serialization case summary
106. How to improve the readability of SAP ui5 application routing URL
Father and basketball
Stack application (balancer)
栈应用(平衡符)
Flink SQL knows why (13): is it difficult to join streams? (next)
R语言使用data函数获取当前R环境可用的示例数据集:获取datasets包中的所有示例数据集、获取所有包的数据集、获取特定包的数据集
(first) the most complete way to become God of Flink SQL in history (full text 180000 words, 138 cases, 42 pictures)
Oracle memory management