-
Notifications
You must be signed in to change notification settings - Fork 263
/
cmd_flags.go
63 lines (53 loc) · 1.5 KB
/
cmd_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
package cmdconfig
import (
"fmt"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var requiredColor = color.New(color.Bold).SprintfFunc()
type flagOpt func(c *cobra.Command, name string, key string)
// FlagOptions :: shortcut for common flag options
var FlagOptions = struct {
Required func() flagOpt
Hidden func() flagOpt
Deprecated func(string) flagOpt
NoOptDefVal func(string) flagOpt
WithShortHand func(string) flagOpt
}{
Required: requiredOpt,
Hidden: hiddenOpt,
Deprecated: deprecatedOpt,
NoOptDefVal: noOptDefValOpt,
WithShortHand: withShortHand,
}
// Helper function to mark a flag as required
func requiredOpt() flagOpt {
return func(c *cobra.Command, name, key string) {
c.MarkFlagRequired(key)
key = fmt.Sprintf("required.%s", key)
viper.GetViper().Set(key, true)
u := c.Flag(name).Usage
c.Flag(name).Usage = fmt.Sprintf("%s %s", u, requiredColor("(required)"))
}
}
func hiddenOpt() flagOpt {
return func(c *cobra.Command, name, _ string) {
c.Flag(name).Hidden = true
}
}
func deprecatedOpt(replacement string) flagOpt {
return func(c *cobra.Command, name, _ string) {
c.Flag(name).Deprecated = fmt.Sprintf("please use %s", replacement)
}
}
func noOptDefValOpt(noOptDefVal string) flagOpt {
return func(c *cobra.Command, name, _ string) {
c.Flag(name).NoOptDefVal = noOptDefVal
}
}
func withShortHand(shorthand string) flagOpt {
return func(c *cobra.Command, name, _ string) {
c.Flag(name).Shorthand = shorthand
}
}