Cobra

2019-02-24
Golang

概念

Cobra是一个go语言库,用来提供创建类似git或者go工具那样现代化的客户端。

它能提供以下功能:

  • 简易的子命令行模式,如 app server, app fetch等等
  • 完全兼容posix命令行模式
  • 嵌套子命令subcommand
  • 支持全局,局部,串联flags
  • 使用Cobra很容易的生成应用程序和命令,使用cobra create appname和cobra add cmdname
  • 如果命令输入错误,将提供智能建议,如 app srver,将提示srver没有,是否是app server
  • 自动生成commands和flags的帮助信息
  • 自动生成详细的help信息,如app help
  • 自动识别-h,–help帮助flag
  • 自动生成应用程序在bash下命令自动完成功能
  • 自动生成应用程序的man手册
  • 命令行别名
  • 自定义help和usage信息
  • 可选的紧密集成的viper apps

使用

安装

使用go get下载cobra:

1
go get -u github.com/spf13/cobra/cobra

使用时在程序中加入:

1
import "github.com/spf13/cobra"

使用Cobra

一般的go语言程序组织是这样的:

1
2
3
4
5
6
7
▾ appName/
▾ cmd/
add.go
your.go
commands.go
here.go
main.go

在Cobra应用中,main.go的内容非常少,它只有一个目的,初始化Cobra:

1
2
3
4
5
6
7
8
9
package main

import (
"{pathToYourApp}/cmd"
)

func main() {
cmd.Execute()
}

Cobra项目生成

我们可以使用init来初始化一个demo项目:

1
cobra init leitty/demo

会以$GOPATH为初始路径

生成以下内容:

1
2
3
4
5
6
root@root:~/go/src/leitty# tree demo/
demo/
├── cmd
│   └── root.go
├── LICENSE
└── main.go

如果你的demo程序没有subcommands,那么cobra生成应用程序的操作就结束了。如果有类似demo serve、demo config的命令可以继续执行

1
cobra add serve

执行后目录结构如下:

1
2
3
4
5
6
7
root@root:~/go/src/leitty# tree demo/
demo/
├── cmd
│   ├── serve.go
│   └── root.go
├── LICENSE
└── main.go

我们给demo加上一个-a命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
cmd/root.go

// Copyright © 2019 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"fmt"
"os"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var cfgFile string
var author string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "demo",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples 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 files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello demo user, %s\n", author)
},
}

// 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() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
rootCmd.PersistentFlags().StringVarP(&author, "author", "a", "YOUR NAME", "Author name for copyright attribution")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// Search config in home directory with name ".demo" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".demo")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

在root.go中我们首先增加了一个参数:

1
var author string

增加了rootCmd的行为:

1
2
3
Run: func(cmd *cobra.Command, args []string) { 
fmt.Printf("Hello demo user, %s\n", author)
},

增加了-a命令行的内容:

1
rootCmd.PersistentFlags().StringVarP(&author, "author", "a", "YOUR NAME", "Author name for copyright attribution")

通过go install .之后我们就可以使用demo -a lei命令了

子命令

刚才执行cobra add serve后会在cmd下生成serve.go文件,serve.go文件的内容和root.go的内容相似,通过编辑Run完成想要的逻辑:

1
2
3
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("serve called")
},

Flags

Flags用来调节命令操作。

持久化Flags

在上面的demo例子中,我们定义了string类型的变量author

1
var author string

并将其绑定到持久化Flags:

1
rootCmd.PersistentFlags().StringVarP(&author, "author", "a", "YOUR NAME", "Author name for copyright attribution")

对于bool类型的变量,有不同的方式分配flag:

1
2
var Verbose bool
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")

一个持久化的flag的含义是这个flag可以在它被分配的命令下使用,那个命令下的每个命令都是如此,比如在上面的例子中,author被分配到rootCmd下,还可以与其他持久化flags一起使用。分配一个持久flag到root下,就是全局flags。

本地Flags

一个本地的Flag只能单独使用

1
rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")

父命令下的本地Flag

默认情况下Cobra只解析目标命令下的本地flags,父命令下的本地命令都将忽略。通过设置Command.TraverseChildren,Cobra将在执行目标命令前解析本地命令。

1
2
3
4
command := cobra.Command{
Use: "print [OPTIONS] [COMMANDS]",
TraverseChildren: true,
}

将Flags和配置绑定

可以通过viper绑定flags

1
2
3
4
5
6
var author string

func init() {
rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
}

在这个例子中,持久flag author被绑定到viper。注意,当--author没被使用者提供时,author将不被设置。

更多内容,请查看viper文档

必输flags

flags一般是可选的。但是也可以设置为必输:

1
2
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkFlagRequired("region")

常用参数

以下的校验是内建的:

  • NoArgs
  • ArbitraryArgs
  • OnlyValidArgs
  • MinimumNArgs(int)
  • MaximumNArgs(int)
  • ExactArgs(int)
  • ExactValidArgs(int)
  • RangeArgs(min, max)

设置常用的校验器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var cmd = &cobra.Command{
Short: "hello",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires at least one arg")
}
if myapp.IsValidColor(args[0]) {
return nil
}
return fmt.Errorf("invalid color specified: %s", args[0])
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
},
}

1
2
3
4
5
6
7
8
9
10
var cmdPrint = &cobra.Command{
Use: "print [string to print]",
Short: "Print anything to the screen",
Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}

例子

在上面的例子中,我们使用cobra生成的模板,当然也可以直接编写cobra命令,可以将命令置于main.go文件中,我们定义三条命令,其中cmdPrint, cmdEcho是顶级命令,cmdTimes是cmdEcho的子命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import (
"fmt"
"strings"

"github.com/spf13/cobra"
)

func main() {
var echoTimes int

var cmdPrint = &cobra.Command{
Use: "print [string to print]",
Short: "Print anything to the screen",
Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}

var cmdEcho = &cobra.Command{
Use: "echo [string to echo]",
Short: "Echo anything to the screen",
Long: `echo is for echoing anything back.
Echo works a lot like print, except it has a child command.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}

var cmdTimes = &cobra.Command{
Use: "times [# times] [string to echo]",
Short: "Echo anything to the screen more times",
Long: `echo things multiple times back to the user by providing
a count and a string.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for i := 0; i < echoTimes; i++ {
fmt.Println("Echo: " + strings.Join(args, " "))
}
},
}

cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")

//注册命令
var rootCmd = &cobra.Command{Use: "app"}
rootCmd.AddCommand(cmdPrint, cmdEcho)
cmdEcho.AddCommand(cmdTimes)
rootCmd.Execute()
}

Help命令

Cobra 自动增加help命令,当然也可以自定:

1
2
3
cmd.SetHelpCommand(cmd *Command)
cmd.SetHelpFunc(f func(*Command, []string))
cmd.SetHelpTemplate(s string)

参考

https://github.com/spf13/cobra

https://www.cnblogs.com/borey/p/5715641.html

https://godoc.org/github.com/spf13/cobra#Command