当前位置:网站首页>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 fetchwait . - Fully compatible with
posixCommand line mode . - Nested sub command
subcommand. - Support the overall situation , Local , Series connection
flags. - Use
cobraIt's easy to generate applications and commands (cobra init appnameandcobra add cmdname). - Provide intelligent tips ( Such as , Output
app srvercommand , Will prompt You are going to enterapp serverDo you ?). - Automatic generation
commandsandflagsHelp for . - Automatically generate detailed
helpInformation , Such asapp -help. - Automatic recognition help
flag、-h,--help. - Auto generate application in
bashCommand auto complete function . - Automatically generate application
manmanual . - Command line alias .
- Customize
helpandusageInformation . - Optional and
viperThe 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 --bareAnother example :
[email protected] ~ % docker info --help Usage: docker info [OPTIONS]Display system-wide informationOptions: -f, --format string Format the output using the given Go templateYou'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/cobraDownload 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-demoAfter successful initialization ,cobra-demo The program directory structure is as follows :
.├── cmd│ ├── root.go│ └── show.go├── go.mod├── go.sum└── main.go3.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 addadd 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.gofile , In this file, the specific operation logic of the command can be completed . Here isshow.goThe 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.176660901perform 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 .
边栏推荐
- celery最佳实践
- MySQL查询请求的执行过程——底层原理
- 当保存参数使用结构体时必备的开发技巧方式
- std::true_type和std::false_type
- Ms-tct: INRIA & SBU proposed a multi-scale time transformer for motion detection. The effect is SOTA! Open source! (CVPR2022)...
- [.Net core] solution to error reporting due to too long request length
- 【Swoole系列2.1】先把Swoole跑起来
- Take you through ancient Rome, the meta universe bus is coming # Invisible Cities
- Declval of template in generic programming
- 287. Find duplicates
猜你喜欢

Implementation of queue

從交互模型中蒸餾知識!中科大&美團提出VIRT,兼具雙塔模型的效率和交互模型的性能,在文本匹配上實現性能和效率的平衡!...

Transport layer congestion control - slow start and congestion avoidance, fast retransmission, fast recovery

On time and parameter selection of asemi rectifier bridge db207

Recommend easy-to-use backstage management scaffolding, everyone open source

十、进程管理

Take you through ancient Rome, the meta universe bus is coming # Invisible Cities

CSRF vulnerability analysis
![[Android] kotlin code writing standardization document](/img/d5/53d6a75e87af15799bf7e5d6eb92a5.png)
[Android] kotlin code writing standardization document
![[Sun Yat sen University] information sharing of postgraduate entrance examination and re examination](/img/a8/41e62a7a8d0a2e901e06c751c30291.jpg)
[Sun Yat sen University] information sharing of postgraduate entrance examination and re examination
随机推荐
Windows connects redis installed on Linux
具体说明 Flume介绍、安装和配置
Docker installation redis
STM32+MFRC522完成IC卡号读取、密码修改、数据读写
Introduction and case analysis of Prophet model
使用cpolar建立一个商业网站(1)
Transfer data to event object in wechat applet
DOM简要
2022暑期项目实训(一)
A method of sequentially loading Unity Resources
Easy to use PDF to SVG program
Markdown grammar - better blogging
Alibaba cloud international ECS cannot log in to the pagoda panel console
Huawei 0 foundation - image sorting
监控界的最强王者,没有之一!
STM32 key state machine 2 - state simplification and long press function addition
Transport layer congestion control - slow start and congestion avoidance, fast retransmission, fast recovery
Comparative examples of C language pointers *p++, * (p++), * ++p, * (++p), (*p) + +, +(*p)
2022 Summer Project Training (II)
Celery best practices