-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpflag.go
74 lines (63 loc) · 1.32 KB
/
pflag.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
package cli
import (
"github.com/spf13/pflag"
)
// PFlags loads option values from a pflag.FlagSet.
// The given KeyFunc is used to format the flag names:
// DotKey will create flags like "server.address",
// DashKey will create "server-address", etc.
func PFlags(fs *pflag.FlagSet, opts []*Opt, kf KeyFunc) Provider {
pf := &pflags{
KeyFunc: kf,
FlagSet: fs,
}
for _, opt := range opts {
flag := &pflagValue{opt: opt}
k := pf.keyfunc(opt.Key)
fs.VarP(flag, k, opt.Short, opt.Synopsis)
if opt.Deprecated != "" {
fs.MarkDeprecated(k, opt.Deprecated)
}
if opt.Hidden {
fs.MarkHidden(k)
}
pf.flags = append(pf.flags, flag)
}
return pf
}
type pflags struct {
KeyFunc
*pflag.FlagSet
flags []*pflagValue
}
func (f *pflags) keyfunc(key []string) string {
if f.KeyFunc == nil {
return DotKey(key)
}
return f.KeyFunc(key)
}
func (f *pflags) Provide(l *Loader) error {
for _, flag := range f.flags {
if flag.set {
l.Set(flag.opt.Key, flag.val)
}
}
return nil
}
type pflagValue struct {
opt *Opt
val interface{}
set bool
}
func (p *pflagValue) Set(v string) error {
p.val = v
p.set = true
return nil
}
func (p *pflagValue) String() string {
return p.opt.DefaultString
}
func (p *pflagValue) Type() string {
// TODO shows io.Writer, which doesn't make much sense for CLI.
return p.opt.Type
}