当前位置:网站首页>Cobra quick start - designed for command line programs

Cobra quick start - designed for command line programs

2022-07-06 18:33:00 Hua Weiyun

cobra.jpeg

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 :DockerKubernetes And so on have its presence . In order to better understand these open source frameworks ( Such as ,IstioKubernetes 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 .

image

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 and cobra add cmdname).
  • Provide intelligent tips ( Such as , Output app srver command , Will prompt You are going to enter app server Do you ?).
  • 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 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 :KubernetesHugo and Github CLI etc. , More widely used projects are :

( originate :https://github.com/spf13/cobra/blob/master/projects_using_cobra.md

Look at these. , One word “ Fabulous ”, Two words “ good ”!

I understand Cobra after , Look at these again KubernetesetcdRegistry 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 )

  1. 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
  1. 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 is show.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 )

  1. Realize the logic of displaying the current time
    stay &cobra.Command.Run Add the logic to get the current time time.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())    },}
  1. 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())    },}
  1. 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 .

原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061017417813.html