Cobra 命令选项和参数实现详解
Cobra 支持两种选项,一种是命令自身的选项,另外一种是从父命令继承过来的选项。备注:因为西部数码的虚拟主机太垃圾,好多文字写进去被拦截了,有些地方中间加了空格
命令自身的选项可以通过函数 Flags 来添加,而继承过来的选项则是父命令通过 PersistentFlags 设置的选项。
我们之前看到过kubectl get命令,这个命令有很多的子命令,比如 pod、service、ingress 等。这里举个简单的例子如下:
kubectl -n devops get -o json -l ‘app=echo-go’ pods
上面的命令意思是获取 Labels 为app=echo-go的 Pod,其中命名空间是 devops,输出的内容格式为 JSON。
让我们仔细看下这个命令,其中 -n 选项是命令 kubectl 的选项,由于这个选项不仅仅提供给 get 命令使用,还可以提供给其它的诸如 describe 命令使用,所以将这个选项定义为全局的选项是合理的,这样每个子命令就不需要再定义一次了。所以这里 get 命令则需要继承这个选项来实现自己的功能。
另外 -o 选项定义输出的内容格式,-l 选项用来指定需要根据其值过滤的标签,这两个选项都是 get 命令自身的选项。
我们可以使用 kubectl options 命令来确认下 -n 确实是 kubectl 命令的全局选项,以及 -o 和 -l 确实是 get 命令的选项。
$ kubectl options
…
-n, –namespace=”: If present, the namespace scope for this CLI request
$ kubectl get -h
…
Usage:
kubectl get
[(-o|–output=)json|yaml|wide|custom-columns=…|custom-columns-file=…|go-template=…|go-template-file=…|jsonpath=…|jsonpath-file=…]
(TYPE [NAME | -l label] | TYPE/NAME …) [flags] [options]
另外在上面的命令中,我们还看到了参数 pods。在命令行应用中除了选项参数之外,剩下的参数都可以通过 Args 来获取。
好了,让我们用一个简单的实现来验证下这个过程。
在/home/yinzhong目录下新建cobra-command-parse.go文件并写入如下代码:
// /home/yinzhong/cobra-command-parse.go
package main
import (
"fmt"
"github.com/spf13/cobra"
)
var namespace string
func main() {
rootCmd := cobra.Command{
Use: "kubectl",
}
// 添加全局的选项,所有的子命令都可以继承
rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "", "If present, the namespace scope for this CLI request")
// 一级子命令 get
var outputFormat string
var labelSelector string
getCmd := cobra.Command{
Use: "get",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print flags...")
fmt.Printf("Flags: namespace=[%s], selector=[%s], output=[%s]\n", namespace, labelSelector, outputFormat)
fmt.Println("Print args...")
for _, arg := range args {
fmt.Println("Arg:", arg)
}
},
}
// 添加命令选项,这些选项仅 get 命令可用
getCmd.Flags().StringVarP(&outputFormat, "output", "o", "", "Output format")
getCmd.Flags().StringVarP(&labelSelector, "selector", "l", "", "Selector (label query) to filter on")
// 组装命令
rootCmd.AddCommand(&getCmd)
// 执行命令
rootCmd.Ex ecute()
}
运行一下,验证下结果:
$ go build cobra-command-parse.go $ ./cobra-command-parse -n devops get -o json -l app=echo-go pods echo-go-67986c999b-vbrtl Print flags... Flags: namespace=[devops], selector=[app=echo-go], output=[json] Print args... Arg: pods Arg: echo-go-67986c999b-vbrtl

