当前位置:网站首页>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]
边栏推荐
- Several common optimization methods matlab principle and depth analysis
- JSP and filter
- PowerPoint tutorial, how to save a presentation as a video in PowerPoint?
- Flink SQL knows why (XI): weight removal is not only count distinct, but also powerful duplication
- File uploading and email sending
- AI 考高数得分 81,网友:AI 模型也免不了“内卷”!
- Flutter动态化 | Fair 2.5.0 新版本特性
- MySQL functions and related cases and exercises
- Road construction issues
- 物联网毕设 --(STM32f407连接云平台检测数据)
猜你喜欢

PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?

HALCON联合C#检测表面缺陷——HALCON例程autobahn

Mobile phones and computers can be used, whole people, spoof code connections, "won't you Baidu for a while" teach you to use Baidu

Kivy tutorial how to automatically load kV files

The principle of human voice transformer

JSP and filter

MySQL installation, uninstallation, initial password setting and general commands of Linux

物联网毕设 --(STM32f407连接云平台检测数据)

这本数学书AI圈都在转,资深ML研究员历时7年之作,免费电子版可看

PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?
随机推荐
实现CNN图像的识别和训练通过tensorflow框架对cifar10数据集等方法的处理
用户和组命令练习
Error handling when adding files to SVN:.... \conf\svnserve conf:12: Option expected
PostgreSQL installation
[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]
JS convert pseudo array to array
已解决TypeError: Argument ‘parser‘ has incorrect type (expected lxml.etree._BaseParser, got type)
【历史上的今天】7 月 3 日:人体工程学标准法案;消费电子领域先驱诞生;育碧发布 Uplay
Father and basketball
mysql中的字段问题
Asp.Net Core1.1版本没了project.json,这样来生成跨平台包
rxjs Observable filter Operator 的实现原理介绍
掌握Cypress命令行选项,是真正掌握Cypress的基础
Flink SQL knows why (XV): changed the source code and realized a batch lookup join (with source code attached)
Reptile
JSP and filter
R language uses the data function to obtain the sample datasets available in the current R environment: obtain all the sample datasets in the datasets package, obtain the datasets of all packages, and
Kivy教程之 如何自动载入kv文件
Can newly graduated European college students get an offer from a major Internet company in the United States?
In the promotion season, how to reduce the preparation time of defense materials by 50% and adjust the mentality (personal experience summary)