Cobra支持动态自定义flag

用GO实现了一个binary,这个binary会发送API请求去服务端,服务端完成对K8S环境的部署工作。
由于后端进行了大量封装,并且参数是非常多的,所以有了一个想法,具体的要求如下:

  1. 支持自定义flag列表
  2. help信息支持展示自定义的flag列表
  3. 列表信息来自于一个专门的API

基于这些需求,查询了很多文档后,并没有成功的例子,经过一下午的尝试,最后实现了预期的需求,分享一下。
回头准备写一篇post给cobra。

在Cobra的github repo里开了issue,询问是否有更加优雅和方便的方法,没想到Cobra的Collaborator竟然回复了,看起来现在的实现方法是一个正确的方向。
https://github.com/spf13/cobra/issues/1758

API部分, python flask实现的,简单定义了数据结构,然后返回一个json结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ns.route('/custom-api')
class CustomAPI(Resource):
def get(self):
flags_list = {
"cert": {
"type": "string",
"des": "add self-signed certs for private registries. Format: registry-name1:/path/to/cert-file1,registry-name2:/path/to/cert-file2,...",
"default": ""
},
"csf-grocery": {
"type": "bool",
"des": "set up CSF Grocery",
"default": True
}
}
return json_success(flags_list)
utils/customized_flags.go
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
package utils

import (
"fmt"
"os"
"strings"

resty "github.com/go-resty/resty/v2"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/tidwall/gjson"
)

var customizedMap = make(map[string]interface{})

func ParseCutomizedFlags(url string, requiredFlags []string, cmd *cobra.Command, args []string) map[string]interface{} {

if len(requiredFlags) > 0 && len(args) == 0 {
cmd.Help()
fmt.Println()
os.Exit(0)
}

argsArrayString := strings.Join(args, "#")
for _, flag := range requiredFlags {
if !strings.Contains(argsArrayString, "--"+flag) {
fmt.Printf("required flag(s) \"%v\" not set\n", flag)
cmd.Help()
fmt.Println()
os.Exit(1)
}
}

fullURL := viper.GetString("datacenter-server-api") + url
var customizedData gjson.Result
client := resty.New()
resp, err := client.R().ForceContentType("application/json").EnableTrace().Get(fullURL)
if err == nil {
if gjson.Get(resp.String(), "status").String() == "OK" {
customizedData = gjson.Get(resp.String(), "data")
}
} else {
fmt.Println(err.Error())
os.Exit(1)
}

if len(customizedData.Map()) > 0 {
for key_name, valueMap := range customizedData.Map() {
value_type := valueMap.Get("type").String()
if value_type == "string" {
cmd.Flags().String(string(key_name), valueMap.Map()["default"].String(), valueMap.Map()["des"].String())
} else if value_type == "bool" {
cmd.Flags().Bool(string(key_name), valueMap.Map()["default"].Bool(), valueMap.Map()["des"].String())
}
}
}

cmd.DisableFlagParsing = false
err = cmd.ParseFlags(args)
if err != nil {
fmt.Println(err)
cmd.Help()
fmt.Println()
os.Exit(1)
}

if cmd.Flag("help").Value.String() == "true" {
cmd.Help()
fmt.Println()
os.Exit(0)
}

if len(customizedData.Array()) > 0 {
for key_name := range customizedData.Map() {
if cmd.Flag(key_name).Value.String() != cmd.Flag(key_name).DefValue {
customizedMap[key_name] = cmd.Flag(key_name).Value
}
}
}

return customizedMap
}


调用:

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
import (
"fmt"

"github.com/spf13/cobra"
"nuke.csf.nokia.net/nuke-cli/utils"
)

var Region string
var requiredFlags []string

var DemoClusterCreate = &cobra.Command{
Use: "demo [string to print]",
Short: "demo anything to the screen",
Long: `demo is for printing anything back to the screen. For many years people have printed back to the screen.`,
RunE: createDemoCluster,
DisableFlagParsing: true,
}

func createDemoCluster(cmd *cobra.Command, args []string) error {

var customizedMap = utils.ParseCutomizedFlags("/api/v1/demo/custom-api", requiredFlags, cmd, args)

for va := range customizedMap {
fmt.Println(va)
fmt.Println(customizedMap[va])
}

fmt.Println(Region)
return nil
}

func init() {
// DemoClusterCreate.Flags().StringVarP(&demoVersion, "version", "v", "1.14", "Venilla version, current can be set as 1.10 , 1.11 1.12")
DemoClusterCreate.Flags().StringVarP(&Region, "region", "r", "zone-a", "(required) AWS region")
// DemoClusterCreate.MarkFlagRequired("region")
//特殊处理required的参数
requiredFlags = append(requiredFlags, "region")

}

最后执行的结果:

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
skeetw@N-20HEPF12NB62 MINGW64 /d/CSF_NCM/CSF-NUKE-CLI (1.0)
$ go run nuke.go create cluster demo --cert xxxx --csf-grocery=false
required flag(s) "region" not set
demo is for printing anything back to the screen. For many years people have printed back to the screen.

Usage:
nuke create cluster demo [string to print] [flags]

Flags:
-h, --help help for demo
-r, --region string (required) AWS region (default "zone-a")

Global Flags:
--datacenter-server-api string data center server api (default "http://127.0.0.1:5678")
--log string nuke log level [debug, info] (default "info")
-o, --output string result output format. [json, yaml, file] (default "json")
--output-folder string when output type if file, all result files will be save to this folder. (default "./output/")
--wrap-processbar if need to wrap process bar when running a long task (default true)

exit status 1

skeetw@N-20HEPF12NB62 MINGW64 /d/CSF_NCM/CSF-NUKE-CLI (1.0)
$ go run nuke.go create cluster demo --cert xxxx --csf-grocery=false --region=989
csf-grocery
false
cert
xxxx
989

skeetw@N-20HEPF12NB62 MINGW64 /d/CSF_NCM/CSF-NUKE-CLI (1.0)
$ go run nuke.go create cluster demo --cert xxxx --region=989
cert
xxxx
989

skeetw@N-20HEPF12NB62 MINGW64 /d/CSF_NCM/CSF-NUKE-CLI (1.0)
$ go run nuke.go create cluster demo --region=989
989

skeetw@N-20HEPF12NB62 MINGW64 /d/CSF_NCM/CSF-NUKE-CLI (1.0)
$ go run nuke.go create cluster demo
demo is for printing anything back to the screen. For many years people have printed back to the screen.

Usage:
nuke create cluster demo [string to print] [flags]

Flags:
-h, --help help for demo
-r, --region string (required) AWS region (default "zone-a")

Global Flags:
--datacenter-server-api string data center server api (default "http://127.0.0.1:5678")
--log string nuke log level [debug, info] (default "info")
-o, --output string result output format. [json, yaml, file] (default "json")
--output-folder string when output type if file, all result files will be save to this folder. (default "./output/")
--wrap-processbar if need to wrap process bar when running a long task (default true)

Notice: 正常情况下,这里会有一个基于utteranc.es的留言系统,如果看不到,可能需要科学上网方式。