当前位置:网站首页>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 .
边栏推荐
- 第三季百度网盘AI大赛盛夏来袭,寻找热爱AI的你!
- The third season of Baidu online AI competition is coming in midsummer, looking for you who love AI!
- Echart simple component packaging
- This article discusses the memory layout of objects in the JVM, as well as the principle and application of memory alignment and compression pointer
- Cocos2d Lua smaller and smaller sample memory game
- CRMEB 商城系统如何助力营销?
- Declval of template in generic programming
- bonecp使用数据源
- 面向程序员的精品开源字体
- The latest financial report release + tmall 618 double top, Nike energy leads the next 50 years
猜你喜欢
STM32 key state machine 2 - state simplification and long press function addition
小程序在产业互联网中的作用
Introduction to the usage of model view delegate principal-agent mechanism in QT
推荐好用的后台管理脚手架,人人开源
Distill knowledge from the interaction model! China University of science and Technology & meituan proposed virt, which combines the efficiency of the two tower model and the performance of the intera
[swoole series 2.1] run the swoole first
The third season of Baidu online AI competition is coming in midsummer, looking for you who love AI!
On time and parameter selection of asemi rectifier bridge db207
declval(指导函数返回值范例)
徐翔妻子应莹回应“股评”:自己写的!
随机推荐
图之广度优先遍历
测试123
STM32+ENC28J60+UIP协议栈实现WEB服务器示例
Declval of template in generic programming
Brief description of SQL optimization problems
Docker安装Redis
Cocos2d Lua 越来越小样本 内存游戏
Transfer data to event object in wechat applet
I want to say more about this communication failure
FMT open source self driving instrument | FMT middleware: a high real-time distributed log module Mlog
第三季百度网盘AI大赛盛夏来袭,寻找热爱AI的你!
Ms-tct: INRIA & SBU proposed a multi-scale time transformer for motion detection. The effect is SOTA! Open source! (CVPR2022)...
Numerical analysis: least squares and ridge regression (pytoch Implementation)
徐翔妻子应莹回应“股评”:自己写的!
Windows连接Linux上安装的Redis
监控界的最强王者,没有之一!
【中山大学】考研初试复试资料分享
Tree-LSTM的一些理解以及DGL代码实现
This article discusses the memory layout of objects in the JVM, as well as the principle and application of memory alignment and compression pointer
With the implementation of MapReduce job de emphasis, a variety of output folders