-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule_gen.go
89 lines (78 loc) · 1.81 KB
/
rule_gen.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
85
86
87
88
89
// Code generated by flag-validator; DO NOT EDIT.
package pflagvalidator
import flag "github.com/spf13/pflag"
type (
Rule interface {
Validate(fs *flag.FlagSet) error
Error(message string) Rule
}
RuleFunc func(fs *flag.FlagSet) error
RuleSet struct {
rules []Rule
}
)
func (v RuleFunc) Validate(fs *flag.FlagSet) error {
return v(fs)
}
func (v RuleFunc) Error(message string) Rule {
return errorRuleFunc(v, message)
}
// errorRuleFunc is processing for Rule.Error() implementation.
func errorRuleFunc(r Rule, message string) Rule {
return RuleFunc(func(fs *flag.FlagSet) error {
err := r.Validate(fs)
if err != nil {
return WrapError(err).SetMessage(message)
}
return nil
})
}
func NewRuleSet(rules ...Rule) *RuleSet {
return &RuleSet{
rules: rules,
}
}
func (rs *RuleSet) Validate(fs *flag.FlagSet) error {
for _, rule := range rs.rules {
err := rule.Validate(fs)
if err != nil {
return err
}
}
return nil
}
// NumberOfArgs returns the validation rule that checks if
// the number of specified argments is equal to n.
func NumberOfArgs(n int) Rule {
return RuleFunc(func(fs *flag.FlagSet) error {
if fs.NArg() != n {
return NewError(
getMessage("NumberOfArgs"),
presetParams(fs),
map[string]any{
"want": n,
"actual": fs.NArg(),
},
)
}
return nil
})
}
// MutuallyExclusive returns the validation rule that checks if
// the given list of flags are not specified more than once.
func MutuallyExclusive(flags ...*Flags) Rule {
return RuleFunc(func(fs *flag.FlagSet) error {
var isOtherGrouopSet bool
for _, f := range flags {
isSet := f.IsSet().Evaluate(fs)
if isOtherGrouopSet && isSet {
return NewError(
getMessage("MutuallyExclusive"),
presetParams(fs),
)
}
isOtherGrouopSet = isOtherGrouopSet || isSet
}
return nil
})
}