当前位置:网站首页>Getting started with the go Cobra command line tool

Getting started with the go Cobra command line tool

2022-06-24 12:50:00 Go and distributed im

brief introduction

Star:26.5K
 
Cobra It's a use. Go Language implementation of command line tools . And now it is used by many projects , for example :Kubernetes、Hugo and Github CLI etc. . By using Cobra, We can quickly create command line tools , Especially suitable for writing test scripts , All kinds of services Admin CLI etc. .
 
such as Mattermost project , I wrote a lot Admin CLI:
 

Why cobra

Let's look at a simple demo

Before using

package main
 
import (
    "flag"
    "fmt"
)
 
func main() {
    flag.Parse()
 
    args := flag.Args()
    if len(args) <= 0 {
        fmt.Println("Usage:  admin-cli [command]")
        return
    }
 
    switch args[0] {
    case "help":
        // ...
    case "export":
        //...
        if len(args) == 3 { //  Export to file 
            // todo
        } else if len(args) == 2 { //  export ...
            // todo
        }
    default:
        //...
    }
}

After using

package main
 
import (
    "fmt"
    "github.com/spf13/cobra"
    "os"
)
 
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
    Use:   "api",
    Short: "A brief description of your application",
    Long:  `A longer description `,
}
 
//  Command one 
var mockMsgCmd = &cobra.Command{
    Use:   "mockMsg",
    Short: " Send test text messages in batches ",
    Long:  ``,
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("mockMsg called")
    },
}
 
//  Command two 
var exportCmd = &cobra.Command{
    Use:   "export",
    Short: " Derived data ",
    Long:  ``,
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("export called")
    },
}
 
func Execute() {
    err := rootCmd.Execute()
    if err != nil {
        os.Exit(1)
    }
}
 
func init() {
    rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
 
    rootCmd.AddCommand(mockMsgCmd)
    rootCmd.AddCommand(exportCmd)
 
    exportCmd.Flags().StringP("out", "k", "./backup", " export path ")
}
 
func main() {
    Execute()
}

  

function :
$ go run main.go
A longer description
 
Usage:
  api [command]
 
Available Commands:
  completion  Generate the autocompletion script for the specified shell
  export       Derived data 
  help        Help about any command
  mockMsg      Send test text messages in batches 
 
Flags:
  -h, --help     help for api
  -t, --toggle   Help message for toggle
 
Use "api [command] --help" for more information about a command.

  

Have you found it? ? You don't have to deal with parameter combinations anymore , From then on, he was released , Just write your own business logic !

Basic concepts

Cobra It's made up of three parts :
  • command (Commands ): Represent behavior . Commands are the central point of the program , Every function of the program should be able to interact through commands , A command can have any subcommand .
  • Parameters (Args): Arguments to the command
  • sign (Flags): Decorating commands . It embellishes how the command should be done .
The official recommended command format is :
$ ./appName command args --Flag  
 
Such as hugo server --port=1313 :
  • appName: hugo 
  • command: server 
  • flag: port

install

Go pkg

Add dependency
$ go get -u github.com/spf13/[email protected]

  

Just import :
import "github.com/spf13/cobra"  

Command line tools

It is recommended to install the command line tool `cobra-cli` , To facilitate the quick creation of cobra project , increase command etc. .
 
#  Command line tools 
$ go install github.com/spf13/[email protected]

  

After installation , perform `cobra-cli --help` ( Please make sure GOBIN The configured ), Output the following information to indicate success :
$ cobra-cli --help
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
 
Usage:
  cobra-cli [command]
 
Available Commands:
  add         Add a command to a Cobra Application
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  init        Initialize a Cobra Application
 
Flags:
  -a, --author string    author name for copyright attribution (default "YOUR NAME")
      --config string    config file (default is $HOME/.cobra.yaml)
  -h, --help             help for cobra-cli
  -l, --license string   name of license for the project
      --viper            use Viper for configuration
 
Use "cobra-cli [command] --help" for more information about a command.
 

  

An introduction to the practice

newly build cobra Command line program

Installed cobra-cli After the tool , perform init Initialize create project :
$ cobra-cli init

  

here , The following files are automatically generated in the current directory :
├── LICENSE
├── cmd
│   └── root.go
└── main.go

  

main.go:
package main
 
import "tools/api/cmd"
 
func main() {
   cmd.Execute()
}

 

root.go( With deletion ):
package cmd
 
import (
   "fmt"
 
   "github.com/spf13/cobra"
)
 
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
   Use:   "api",
   Short: "A brief description of your application",
   Long:  `A longer description `,
   //Run: func(cmd *cobra.Command, args []string) {
   // fmt.Println("api called")
   //},
}
 
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
   err := rootCmd.Execute()
   if err != nil {
      os.Exit(1)
   }
}
 
func init() {
   //  overall situation flag
   // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.api.yaml)")
 
   // local flag, I don't know the use for the time being 
   rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

 

At this time to run , Do not specify parameters , Will execute rootCmd, Print instructions :
$ go build 
$ ./api

  

Output :
A longer description
 
Usage:
  api [command]
 
Available Commands:
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
 
Flags:
  -h, --help     help for api
  -t, --toggle   Help message for toggle
 
Use "api [command] --help" for more information about a command.

  

Orders constitute

Analyze the default output above :
  • Available Commands: Represents an executable command . such as ./api connect
  • Flags: Is the parameter . such as ./api connect --ip=127.0.0.1:6379,--ip Namely flag,127.0.0.1:6379 Namely flag Value .

The new command

Let's try a new command , This is also the charm of command-line programs , Perform different actions with different parameters .
grammar :
$ cobra-cli add [command]

  

such as :
$ cobra-cli add mock-msg
mockMsg created at /Users/xxx/repo/tools/api

  

here , stay cmd There will be one more file next (mock_msg.go), The contents are as follows :
package cmd
 
import (
   "fmt"
 
   "github.com/spf13/cobra"
)
 
var mockMsgCmd = &cobra.Command{
   Use:   "mockMsg",
   Short: "A brief description of your command",
   Long: `mock msg command`,
   Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("mockMsg called")
   },
}
 
func init() {
   rootCmd.AddCommand(mockMsgCmd)
}

  

Re execution rootCmd:
$ go build
$ ./api

  

Will find , One more command :
// ...
Available Commands:
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  mockMsg     A brief description of your command
// ...

  

perform mocMsg command :
$ ./api mockMsg
 
mockMsg called

  

here , Can be generated in  mock_msg.go: Run() Function , Put your own business logic code .

How to display your own command usage

A new command has been added mockMsg, adopt ./api help Printed commands and help, however `Use` Where are the specified contents printed ?
 
This is the time , Need to aim at Command In the specified help, At this point, you can print the specific usage of this command .
./api mockMsg help
 Volume production mq news 
 
Usage:
  benchmark mockmsg [flags]
 
Flags:
  -g, --goroutine int32    Concurrent routine Number  (default 1)
  -h, --help              help for mockmsg
  -p, --packet int32       Every routine Write in one second mq The number of  (default 20)

-g and -p It's new 2 individual flag:
func init() {
   mockmsgCmd.Flags().Int32P("goroutine", "g", 1, " Concurrent routine Number ")
   mockmsgCmd.Flags().Int32P("packet", "p", 20, " Every routine Write in one second mq The number of ")
 
   rootCmd.AddCommand(mockmsgCmd)
}

  

Get this 2 It's worth :
// mockmsgCmd represents the mockmsg command
var mockmsgCmd = &cobra.Command{
   Use:   "mockmsg",
   Short: " Volume production mq news ",
   Run: func(cmd *cobra.Command, args []string) {
      //  Write your full name here 
      g, _ := cmd.Flags().GetInt32("goroutine")
      p, _ := cmd.Flags().GetInt32("packet")
      fmt.Println("mockmsg called,flags:g=", g, ",p=", p, ",args:", args)
   },
}

  

perform :
$ go run main.go mockmsg -p 322 -g 5 args1 args2
mockmsg called,flags:g= 5 ,p= 322 ,args: [args1 args2]

summary

Let's take an example , Introduced the use of cobra Benefits . Through a complete introductory practice , Demonstrates creating a project 、 Add some examples of commands and usage , I hope it helped you !
 
Reference resources :
原网站

版权声明
本文为[Go and distributed im]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241033313987.html