-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathenum.go
More file actions
65 lines (54 loc) · 1.35 KB
/
enum.go
File metadata and controls
65 lines (54 loc) · 1.35 KB
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
package flags
import (
"fmt"
"strings"
"github.com/spf13/pflag"
)
type enumFlag struct {
ignoreCase bool
options []string
value string
}
// Ensure the implementation satisfies the expected interface
var _ pflag.Value = &enumFlag{}
// EnumFlag returns a flag which must be one of the given values.
// If ignoreCase is true, flag value is returned in lower case.
func EnumFlag(ignoreCase bool, defaultValue string, options ...string) *enumFlag {
if defaultValue == "" {
return &enumFlag{ignoreCase: ignoreCase, options: options}
}
validDefault := false
for _, o := range options {
if !ignoreCase && defaultValue == o {
validDefault = true
break
}
if ignoreCase && strings.EqualFold(defaultValue, o) {
validDefault = true
break
}
}
if !validDefault {
panic(fmt.Sprintf("default value %q is not one of %q", defaultValue, options))
}
return &enumFlag{ignoreCase: ignoreCase, options: options, value: defaultValue}
}
func (f *enumFlag) String() string {
return f.value
}
func (f *enumFlag) Set(value string) error {
for _, o := range f.options {
if !f.ignoreCase && value == o {
f.value = value
return nil
}
if f.ignoreCase && strings.EqualFold(value, o) {
f.value = strings.ToLower(value)
return nil
}
}
return fmt.Errorf("expected one of %q", f.options)
}
func (f *enumFlag) Type() string {
return "string"
}