当前位置:网站首页>Golang - command line tool Cobra
Golang - command line tool Cobra
2022-07-03 13:47:00 【The wind blows on the edge of the cloud】
List of articles
Cobra
Cobra Is a Go Linguistic CLI frame . It contains a for creating powerful modern CLI The library of the application , And one for rapid generation based on Cobra Tools for applications and command files .
characteristic
- Simple subcommand mode , Such as app server, app fetch wait
- Fully compatible with posix Command line mode
- Nested sub command subcommand
- Support the overall situation , Local , Series connection flags
- Use cobra It's easy to generate applications and commands , Use cobra create appname and cobra add cmdname
- If the command is entered incorrectly , Intelligent advice will be provided , Such as app srver, Will prompt srver No, , Is it right? app server
- Automatic generation commands and flags Help for
- Automatically generate detailed help Information , Such as app help
- Automatic recognition help flag -h,–help
- Auto generate application in bash Command auto complete function
- Automatically generate application man manual
- Command line alias
- Customize help and usage Information
- Optional and viper apps The tight integration of
Concept
Cobra Is based on the command 、 The structure of parameters and signs .
Commands It's for action ,Args It's something ,Flags It's the modifier for these actions .
The best application reads like a sentence . Users will know how to use the application , Because they are born to know how to use it .
for example :
hugo server --port=1313
Command
Command Is the central point of the application . Every interaction supported by the application is contained in Command in . Commands can have subcommands , You can also operate selectively .
Flag
flag Is a way to modify command behavior .Cobra Fully support compatibility posix The logo and Go Logo pack .Cobra Commands can define flags that run through subcommands , And flags that are only available for this command .
In the example above --port
It's a flag
Global identity (Persistent Flags)
Global identity (Persistent Flags) It will act on its specified command and all subcommands of the specified command .
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
Local identification (Local Flags)
Local marking (Local Flags) Only works on its specified command .
rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
Run Hooks
Can be in the main command run
Run the function before or after the function .PersistentPreRun
and PreRun
The function will be in Run
Before execution .persistentpoststrun
and poststrun
Will be in Run
After performing . If the subclass does not declare its own Persistent*Run
function , They will be inherited by subclasses . These functions run in the following order :
- PersistentPreRun
- PreRun
- Run
- PostRun
- PersistentPostRun
Example :
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]
边栏推荐
- Kivy tutorial how to load kV file design interface by string (tutorial includes source code)
- JSON serialization case summary
- This math book, which has been written by senior ml researchers for 7 years, is available in free electronic version
- The shadow of the object at the edge of the untiy world flickers, and the shadow of the object near the far point is normal
- The network card fails to start after the cold migration of the server hard disk
- Internet of things completion -- (stm32f407 connects to cloud platform detection data)
- Flutter动态化 | Fair 2.5.0 新版本特性
- Mysql database basic operation - regular expression
- PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?
- AI 考高数得分 81,网友:AI 模型也免不了“内卷”!
猜你喜欢
Complete deep neural network CNN training with tensorflow to complete picture recognition case 2
[sort] bucket sort
The latest BSC can pay dividends. Any B usdt Shib eth dividend destruction marketing can
Screenshot of the operation steps of upload labs level 4-level 9
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
研发团队资源成本优化实践
Unity EmbeddedBrowser浏览器插件事件通讯
[email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g"/>
Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
Go language unit test 4: go language uses gomonkey to test functions or methods
Several common optimization methods matlab principle and depth analysis
随机推荐
pytorch 载入历史模型时更换gpu卡号,map_location设置
When updating mysql, the condition is a query
MapReduce implements matrix multiplication - implementation code
Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
Task5: multi type emotion analysis
树的深入和广度优先遍历(不考虑二叉树)
Kivy教程之 盒子布局 BoxLayout将子项排列在垂直或水平框中(教程含源码)
MySQL installation, uninstallation, initial password setting and general commands of Linux
SQL Injection (GET/Search)
PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?
KEIL5出现中文字体乱码的解决方法
顺序表(C语言实现)
Students who do not understand the code can also send their own token, which is easy to learn BSC
刚毕业的欧洲大学生,就能拿到美国互联网大厂 Offer?
Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe for the online account manager to open an account
Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
【556. 下一个更大元素 III】
软件测试工作那么难找,只有外包offer,我该去么?
Ocean CMS vulnerability - search php