-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmdconfig.go
59 lines (53 loc) · 1.34 KB
/
cmdconfig.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
package commands
import (
"fmt"
"strings"
"github.com/cnrancher/tcr-access-control/pkg/cmdconfig"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
)
func initializeFlagsConfig(cmd *cobra.Command, cfg cmdconfig.Provider) {
if cmd.Parent() != nil {
initializeFlagsConfig(cmd.Parent(), cfg)
}
flags := cmd.Flags()
cmd.Flags().VisitAll(func(f *flag.Flag) {
setValueFromFlag(flags, f.Name, cfg, "")
})
if cfg.GetBool("debug") {
logrus.SetLevel(logrus.DebugLevel)
}
}
func setValueFromFlag(flags *flag.FlagSet, key string, cfg cmdconfig.Provider, targetKey string) {
key = strings.TrimSpace(key)
if flags.Lookup(key) != nil || flags.Changed(key) {
f := flags.Lookup(key)
configKey := key
if targetKey != "" {
configKey = targetKey
}
// Gotta love this API too.
switch f.Value.Type() {
case "bool":
bv, _ := flags.GetBool(key)
cfg.Set(configKey, bv)
case "string":
cfg.Set(configKey, f.Value.String())
case "stringSlice":
sv, _ := flags.GetStringSlice(key)
cfg.Set(configKey, sv)
case "int":
iv, _ := flags.GetInt(key)
cfg.Set(configKey, iv)
case "int32":
iv, _ := flags.GetInt32(key)
cfg.Set(configKey, iv)
case "int64":
iv, _ := flags.GetInt64(key)
cfg.Set(configKey, iv)
default:
panic(fmt.Sprintf("update switch with %s", f.Value.Type()))
}
}
}