当前位置:网站首页>Cobra quick start - designed for command line programs
Cobra quick start - designed for command line programs
2022-07-06 18:33:00 【Hua Weiyun】
I've been reading it lately Istio( One Service Mesh
frame ) Relevant stuff , When I saw its source code, I found a new thing Cobra
, A check found that this is a good thing , There are a lot of places to use , such as :Docker
、Kubernetes
And so on have its presence . In order to better understand these open source frameworks ( Such as ,Istio
、Kubernetes
etc. ), There is bound to be a need for Cobra
Make a detailed understanding , It may be used in many places in the future . Today Cobra
Make an overall introduction , Let's know something about it , Maybe you will use it in your project in the future .
1、Cobra Introduce
1.1 Cobra summary
Cobra
It's a Golang package , It provides a simple interface to create a command line program . meanwhile ,Cobra
It's also an application , Used to generate application framework , So as to develop Cobra
Based applications .
1.2 The main function
Cobra The main functions are as follows :
- 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 (cobra init appname
andcobra add cmdname
). - Provide intelligent tips ( Such as , Output
app srver
command , Will prompt You are going to enterapp server
Do you ?). - Automatic generation
commands
andflags
Help for . - Automatically generate detailed
help
Information , Such asapp -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
andusage
Information . - Optional and
viper
The tight integration of .
For command line programs , The above functions are tailor-made .
1.3 Application, for example,
Cobra
Used in many Go In the project , for example :Kubernetes、Hugo and Github CLI etc. , More widely used projects are :
( originate :https://github.com/spf13/cobra/blob/master/projects_using_cobra.md)
- Arduino CLI
- Bleve
- CockroachDB
- Cosmos SDK
- Delve
- Docker (distribution)
- Etcd
- Gardener
- Giant Swarm’s gsctl
- Git Bump
- Github CLI
- GitHub Labeler
- Golangci-lint
- GopherJS
- Helm
- Hugo
- Istio
- Kool
- Kubernetes
- Linkerd
- Mattermost-server
- Metal Stack CLI
- Moby (former Docker)
- Nanobox/Nanopack
- OpenShift
- Ory Hydra
- Ory Kratos
- Pouch
- ProjectAtomic (enterprise)
- Prototool
- Random
- Rclone
- Skaffold
- Tendermint
- Twitch CLI
- Werf
Look at these. , One word “ Fabulous ”, Two words “ good ”!
I understand Cobra
after , Look at these again Kubernetes
、etcd
、Registry
When waiting for the code of open source projects , I probably know how to see it , This is what I learn Cobra
Purpose .
2、 Concept
Cobra It's command based (commands
)、 Parameters (arguments
)、 Options (flags
) And created .
In specific understanding 、 Use Cobra There are some concepts that need to be known in advance : command (commands
)、 Parameters (arguments
)、 Options (flags
) These concepts .
- commands: Commands represent actions , Generally speaking action, That is, the running binary command service . You can also have subcommands (children commands)
- arguments: Parameters represent command line parameters .
- flags: Options represent changes to command behavior , Command line options . Configuration parameters for binary commands , Can correspond to the configuration file . Parameters can be divided into global parameters and subcommand parameters .
The best command-line program in practical use , It should be like reading a beautiful sentence , Be able to know more intuitively how to interact with users . Executing command-line programs should follow the general format : APPNAME VERB NOUN --ADJECTIVE
or APPNAME COMMAND ARG --FLAG
.
Consider the following example :
# server yes commands,port yes flaghugo server --port=1313# clone yes commands,URL yes arguments,brae yes flaggit clone URL --bare
Another example :
[email protected] ~ % docker info --help Usage: docker info [OPTIONS]Display system-wide informationOptions: -f, --format string Format the output using the given Go template
You're not mistaken , image Docker Such complex commands are used Cobra It's realized , It must be outstanding , In the next section, let's take a look at how to implement a set of our own command-line tools !
3、Cobra actual combat
Practice is the best way to learn ! This section will give you a quick start from a real battle Cobra.
3.1 Environmental preparation
3.1.1 Prerequisite & Environmental Science
- operating system :MacOS
- Go Environmental Science :go 1.16
- Go Development IDE:VSCode
( The above environment can depend on your personal environment , No restrictions )
3.1.2 Cobra install
Use go get
Command to get the latest version of Cobra library . The following command will install Cobra And its related dependent packages :
go get -u github.com/spf13/cobra/cobra
Download and install complete Cobra after , open GOPATH Catalog , stay bin It will be downloaded in the directory cobra Program (Window: cobra.exe, MacOS: cobra).
3.1.3 Engineering initialization (Cobra Code generator )
Suppose you now need to develop a system based on Cobra Of CLI The command line program for , Name it cobra-demo
.
because Cobra Provides the function of a code generator , We can use it directly Cobra Initialization command provided cobra init
Perform quick initialization and create Cobra engineering .
Switch to GOPATH
Catalog ( Such as ,/Users/xcbeyond/github
), Carry out orders cobra init --pkg-name
, as follows :
[email protected] github % .\bin\cobra init cobra-demo --pkg-name github.com/xcbeyond/cobra-demoYour Cobra application is ready at/Users/xcbeyond/github/cobra-demo
After successful initialization ,cobra-demo The program directory structure is as follows :
.├── cmd│ ├── root.go│ └── show.go├── go.mod├── go.sum└── main.go
3.1.4 function
Carry out orders go run
function :
[email protected] cobra-demo % go run main.goA longer description that spans multiple lines and likely containsexamples 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 filesto quickly create a Cobra application.
3.2 actual combat
Here's a simple time
Command as an example , Explain how to Cobra Develop a command .
Function as follows :
show
: View current time .parse
: Specify the time format –format,parse by show Subcommand for
3.2.1 Realization show command (Command command )
- add to show Command pass command
cobra add
add to show command :
[email protected] cobra-demo % ../bin/cobra add showshow created at /Users/xcbeyond/github/cobra-demo
- here , A... Will be created under the project directory
show.go
file , In this file, the specific operation logic of the command can be completed . Here isshow.go
The initial code of the file :
// showCmd represents the show commandvar showCmd = &cobra.Command{ Use: "show", Short: "A brief description of your command", Long: `A longer description that spans multiple lines and likely contains examplesand usage of using your command. For example:Cobra is a CLI library for Go that empowers applications.This application is a tool to generate the needed filesto quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("show called") },}func init() { rootCmd.AddCommand(showCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // showCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // showCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")}
&cobra.Command
As the definition of the command , There are the following variables :
Use
: Used to specify specific commands , Such as :show.Short
: A short description of the command .Long
: A detailed description of the order .Run
: Command execution entry , The specific processing logic used to implement the command .
rootCmd.AddCommand(showCmd)
Add command , Add command to root command .(Cobra Subcommands that support commands )
- Realize the logic of displaying the current time
stay &cobra.Command.Run Add the logic to get the current timetime.Now()
:
var showCmd = &cobra.Command{ Use: "show", Short: "A brief description of your command", Long: `A longer description that spans multiple lines and likely contains examplesand usage of using your command. For example:Cobra is a CLI library for Go that empowers applications.This application is a tool to generate the needed filesto quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { // show current time fmt.Println(time.Now()) },}
- modify help command
help There are two orders , One is short, One is lang, Obviously short The command is used to define a short description ,lang Commands are used to define detailed descriptions , Let's modify show Ordered help:
var showCmd = &cobra.Command{ Use: "show", Short: "Displays the current time", Long: `You can use the time show command to view the current time. For example:$ ./cobra-demo show2021-03-19 14:34:20.9320241 +0800 CST m=+0.378845301`, Run: func(cmd *cobra.Command, args []string) { // show current time fmt.Println(time.Now()) },}
- function
perform show command :
[email protected] cobra-demo % go run main.go show2021-07-31 14:49:27.3582836 +0800 CST m=+0.176660901
perform show –help command :
[email protected] cobra-demo % go run main.go show --helpYou can use the time show command to view the current time. For example:$ ./cobra-demo show2021-07-31 14:34:20.9320241 +0800 CST m=+0.378845301Usage:cobra-demo show [flags]Flags:-h, --help help for showGlobal Flags: --config string config file (default is $HOME/.cobra-demo.yaml)
4、 summary
Cobra-demo Just a brief description of the composition of several parts , In the actual project, it is much more complicated than this , It usually has multiple subcommands , But the core content is similar .
边栏推荐
- C language college laboratory reservation registration system
- I want to say more about this communication failure
- Picture zoom Center
- Five data structures of redis
- 用友OA漏洞学习——NCFindWeb 目录遍历漏洞
- std::true_type和std::false_type
- 287. Find duplicates
- 转载:基于深度学习的工业品组件缺陷检测技术
- Grafana 9.0 正式发布!堪称最强!
- STM32 key state machine 2 - state simplification and long press function addition
猜你喜欢
Alibaba cloud international ECS cannot log in to the pagoda panel console
Grafana 9.0 is officially released! It's the strongest!
Ms-tct: INRIA & SBU proposed a multi-scale time transformer for motion detection. The effect is SOTA! Open source! (CVPR2022)...
std::true_type和std::false_type
面向程序员的精品开源字体
Declval (example of return value of guidance function)
Numerical analysis: least squares and ridge regression (pytoch Implementation)
MS-TCT:Inria&SBU提出用于动作检测的多尺度时间Transformer,效果SOTA!已开源!(CVPR2022)...
44所高校入选!分布式智能计算项目名单公示
UDP协议:因性善而简单,难免碰到“城会玩”
随机推荐
传输层 拥塞控制-慢开始和拥塞避免 快重传 快恢复
JDBC驱动器、C3P0、Druid和JDBCTemplate相关依赖jar包
High precision operation
Bonecp uses data sources
[.Net core] solution to error reporting due to too long request length
使用cpolar建立一个商业网站(1)
UDP protocol: simple because of good nature, it is inevitable to encounter "city can play"
Jerry is the custom background specified by the currently used dial enable [chapter]
华为0基金会——图片整理
287. Find duplicates
Cobra 快速入门 - 专为命令行程序而生
Take you through ancient Rome, the meta universe bus is coming # Invisible Cities
【LeetCode第 300 场周赛】
node の SQLite
用友OA漏洞学习——NCFindWeb 目录遍历漏洞
重磅硬核 | 一文聊透对象在 JVM 中的内存布局,以及内存对齐和压缩指针的原理及应用
Implementation of queue
【剑指 Offer】 60. n个骰子的点数
Splay
Docker安装Redis