-
Notifications
You must be signed in to change notification settings - Fork 350
/
listflag.go
81 lines (64 loc) · 1.24 KB
/
listflag.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
package config
import (
"fmt"
"strings"
)
type listFlag struct {
sep string
allowed map[string]bool
value string
values []string
}
func newListFlag(sep string, allowed ...string) *listFlag {
lf := &listFlag{
sep: sep,
allowed: make(map[string]bool),
}
for _, a := range allowed {
lf.allowed[a] = true
}
return lf
}
func commaListFlag(allowed ...string) *listFlag {
return newListFlag(",", allowed...)
}
func (lf *listFlag) Set(value string) error {
if lf == nil {
return nil
}
if value == "" {
lf.value = ""
lf.values = nil
} else {
lf.value = value
lf.values = strings.Split(value, lf.sep)
}
if err := lf.validate(); err != nil {
return err
}
return nil
}
func (lf *listFlag) UnmarshalYAML(unmarshal func(interface{}) error) error {
var values []string
if err := unmarshal(&values); err != nil {
return err
}
lf.value = strings.Join(values, lf.sep)
lf.values = values
if err := lf.validate(); err != nil {
return err
}
return nil
}
func (lf *listFlag) validate() error {
if len(lf.allowed) == 0 {
return nil
}
for _, v := range lf.values {
if !lf.allowed[v] {
return fmt.Errorf("value not allowed: %s", v)
}
}
return nil
}
func (lf listFlag) String() string { return lf.value }