-
Notifications
You must be signed in to change notification settings - Fork 1
/
flag_loader.go
144 lines (108 loc) · 2.49 KB
/
flag_loader.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package bconf
import (
"fmt"
"os"
"strings"
)
func NewFlagLoader() *FlagLoader {
return NewFlagLoaderWithKeyPrefix("")
}
func NewFlagLoaderWithKeyPrefix(keyPrefix string) *FlagLoader {
return &FlagLoader{KeyPrefix: keyPrefix}
}
type FlagLoader struct {
KeyPrefix string
OverrideLookup []string
}
func (l *FlagLoader) Clone() *FlagLoader {
clone := *l
if len(l.OverrideLookup) > 0 {
_ = copy(clone.OverrideLookup, l.OverrideLookup)
}
return &clone
}
func (l *FlagLoader) CloneLoader() Loader {
return l.Clone()
}
func (l *FlagLoader) Name() string {
return "bconf_flags"
}
func (l *FlagLoader) Get(fieldSetKey, fieldKey string) (string, bool) {
values := l.flagValues()
value, found := values[fmt.Sprintf("%s_%s", fieldSetKey, fieldKey)]
if found {
return value, true
}
return "", false
}
func (l *FlagLoader) GetMap(fieldSetKey string, fieldKeys []string) map[string]string {
values := map[string]string{}
flagValues := l.flagValues()
for _, fieldKey := range fieldKeys {
value, found := flagValues[fmt.Sprintf("%s_%s", fieldSetKey, fieldKey)]
if found {
values[fieldKey] = value
}
}
return values
}
func (l *FlagLoader) HelpString(fieldSetKey, fieldKey string) string {
return fmt.Sprintf("Flag argument: '--%s'", l.flagKey(fmt.Sprintf("%s_%s", fieldSetKey, fieldKey)))
}
func (l *FlagLoader) flagKey(key string) string {
flagKey := ""
if l.KeyPrefix != "" {
flagKey = fmt.Sprintf("%s_%s", l.KeyPrefix, key)
} else {
flagKey = key
}
return strings.ToLower(flagKey)
}
func (l *FlagLoader) flagValues() map[string]string {
values := map[string]string{}
var args []string
if len(l.OverrideLookup) > 0 {
args = l.OverrideLookup
} else {
args = os.Args[1:]
}
if len(args) < 1 {
return values
}
argIdx := 0
parseArgs := true
for parseArgs && argIdx < len(args) {
arg := args[argIdx]
switch {
case strings.HasPrefix(arg, "--"):
arg = arg[2:]
case strings.HasPrefix(arg, "-"):
arg = arg[1:]
default:
argIdx++
continue
}
flagKey := ""
flagValue := ""
if splitIndex := strings.Index(arg, "="); splitIndex > -1 {
flagKey = arg[:splitIndex]
flagValue = arg[splitIndex+1:]
values[flagKey] = flagValue
argIdx++
continue
}
flagKey = arg
if argIdx+1 < len(args) {
nextArg := args[argIdx+1]
if !strings.HasPrefix(nextArg, "--") && !strings.HasPrefix(nextArg, "-") {
values[flagKey] = nextArg
argIdx += 2
continue
}
}
values[flagKey] = "true"
argIdx++
continue
}
return values
}