-
Notifications
You must be signed in to change notification settings - Fork 59
/
parse.go
328 lines (287 loc) · 8 KB
/
parse.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package ff
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
iofs "io/fs"
"os"
"strings"
)
// FlagSetAny must be either a [Flags] interface, or a concrete [*flag.FlagSet].
// Any other value will produce a runtime error.
//
// The intent is to make the signature of functions like [Parse] more intuitive.
type FlagSetAny any
// Parse the flag set with the provided args. [Option] values can be used to
// influence parse behavior. For example, options exist to read flags from
// environment variables, config files, etc.
func Parse(fs FlagSetAny, args []string, options ...Option) error {
switch reified := fs.(type) {
case Flags:
return parse(reified, args, options...)
case *flag.FlagSet:
return parse(NewFlagSetFrom(reified.Name(), reified), args, options...)
default:
return fmt.Errorf("unsupported flag set %T", fs)
}
}
func parse(fs Flags, args []string, options ...Option) error {
// The parse context manages options.
var pc ParseContext
for _, option := range options {
option(&pc)
}
// Index valid flags by env var key, to support .env config files (below).
env2flag := map[string]Flag{}
{
if err := fs.WalkFlags(func(f Flag) error {
for _, name := range getNameStrings(f) {
key := getEnvVarKey(name, pc.envVarPrefix)
if existing, ok := env2flag[key]; ok {
return fmt.Errorf("%s: %w (%s)", getNameString(f), ErrDuplicateFlag, getNameString(existing))
}
env2flag[key] = f
}
return nil
}); err != nil {
return err
}
}
// After each stage of parsing, record the flags that have been provided.
// Subsequent lower-priority stages can't set these already-provided flags.
var provided flagSetSlice
markProvided := func() {
fs.WalkFlags(func(f Flag) error {
if f.IsSet() {
provided.add(f)
}
return nil
})
}
// First priority: the commandline, i.e. the user.
{
if err := fs.Parse(args); err != nil {
return fmt.Errorf("parse args: %w", err)
}
markProvided()
}
// Second priority: the environment, i.e. the session.
{
if pc.envVarEnabled {
if err := fs.WalkFlags(func(f Flag) error {
// If the flag has already been set, we can't do anything.
if provided.has(f) {
return nil
}
// Look in the environment for each of the flag names.
for _, name := range getNameStrings(f) {
// Transform the flag name to an env var key.
key := getEnvVarKey(name, pc.envVarPrefix)
// Look up the value from the environment.
val := os.Getenv(key)
if val == "" {
continue
}
// The value may need to be split.
vals := []string{val}
if pc.envVarSplit != "" {
vals = splitEscape(val, pc.envVarSplit)
}
// Set the flag to the value(s).
for _, v := range vals {
if err := f.SetValue(v); err != nil {
return fmt.Errorf("%s=%q: %w", key, val, err)
}
}
}
return nil
}); err != nil {
return fmt.Errorf("parse environment: %w", err)
}
}
markProvided()
}
// Third priority: the config file, i.e. the host.
{
// First, prefer an explicit filename string.
var configFile string
if pc.configFileName != "" {
configFile = pc.configFileName
}
// Next, check the flag name.
if configFile == "" && pc.configFlagName != "" {
if f, ok := fs.GetFlag(pc.configFlagName); ok {
configFile = f.GetValue()
}
}
// If they didn't provide an open func, set the default.
if pc.configOpenFunc == nil {
pc.configOpenFunc = func(s string) (iofs.File, error) {
return os.Open(s)
}
}
// Config files require both a filename and a parser.
var (
haveConfigFile = configFile != ""
haveParser = pc.configParseFunc != nil
parseConfigFile = haveConfigFile && haveParser
)
if parseConfigFile {
configFile, err := pc.configOpenFunc(configFile)
switch {
case err == nil:
defer configFile.Close()
if err := pc.configParseFunc(configFile, func(name, value string) error {
// The parser calls us with a name=value pair. We want to
// allow the name to be either the actual flag name, or its
// env var representation (to support .env files).
var (
setFlag, fromSet = fs.GetFlag(name)
envFlag, fromEnv = env2flag[name]
target Flag
)
switch {
case fromSet:
target = setFlag
case !fromSet && fromEnv:
target = envFlag
case !fromSet && !fromEnv && pc.configIgnoreUndefinedFlags:
return nil
case !fromSet && !fromEnv && !pc.configIgnoreUndefinedFlags:
return fmt.Errorf("%s: %w", name, ErrUnknownFlag)
}
// If the flag was already provided by commandline args or
// env vars, then don't set it again. But be sure to allow
// config files to specify the same flag multiple times.
if provided.has(target) {
return nil
}
if err := target.SetValue(value); err != nil {
return fmt.Errorf("%s: %w", name, err)
}
return nil
}); err != nil {
return fmt.Errorf("parse config file: %w", err)
}
case errors.Is(err, iofs.ErrNotExist) && pc.configAllowMissingFile:
// no problem
default:
return err
}
}
markProvided()
}
return nil
}
//
//
//
// PlainParser is a parser for config files in an extremely simple format. Each
// line is tokenized as a single key/value pair. The first space-delimited token
// in the line is interpreted as the flag name, and the rest of the line is
// interpreted as the flag value.
//
// Any leading hyphens on the flag name are ignored. Lines with a flag name but
// no value are interpreted as booleans, and the value is set to true.
//
// Flag values are trimmed of leading and trailing whitespace, but are otherwise
// unmodified. In particular, values are not quote-unescaped, and control
// characters like \n are not evaluated and instead passed through as literals.
//
// Comments are supported via "#". End-of-line comments require a space between
// the end of the line and the "#" character.
//
// An example config file follows.
//
// # this is a full-line comment
// timeout 250ms # this is an end-of-line comment
// foo abc def # set foo to `abc def`
// foo 12345678 # repeated flags result in repeated calls to Set
// bar "abc def" # set bar to `"abc def"`, including quotes
// baz x\ny # set baz to `x\ny`, passing \n literally
// verbose # equivalent to `verbose true`
func PlainParser(r io.Reader, set func(name, value string) error) error {
s := bufio.NewScanner(r)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" {
continue // skip empties
}
if line[0] == '#' {
continue // skip comments
}
var (
name string
value string
index = strings.IndexRune(line, ' ')
)
if index < 0 {
name, value = line, "true" // boolean option
} else {
name, value = line[:index], strings.TrimSpace(line[index:])
}
if i := strings.Index(value, " #"); i >= 0 {
value = strings.TrimSpace(value[:i])
}
if err := set(name, value); err != nil {
return err
}
}
return s.Err()
}
//
//
//
var envVarSeparators = strings.NewReplacer(
"-", "_",
".", "_",
"/", "_",
)
func getEnvVarKey(flagName, envVarPrefix string) string {
var key string
key = flagName
key = strings.TrimLeft(key, "-")
key = strings.ToUpper(key)
key = envVarSeparators.Replace(key)
key = maybePrefix(key, envVarPrefix)
return key
}
func maybePrefix(key string, prefix string) string {
if prefix != "" {
key = strings.ToUpper(prefix) + "_" + key
}
return key
}
func splitEscape(s string, separator string) []string {
escape := `\`
tokens := strings.Split(s, separator)
for i := len(tokens) - 2; i >= 0; i-- {
if strings.HasSuffix(tokens[i], escape) {
tokens[i] = tokens[i][:len(tokens[i])-len(escape)] + separator + tokens[i+1]
tokens = append(tokens[:i+1], tokens[i+2:]...)
}
}
return tokens
}
//
//
//
type flagSetSlice []Flag
func (fss *flagSetSlice) add(f Flag) {
for _, ff := range *fss {
if f == ff {
return
}
}
*fss = append(*fss, f)
}
func (fss *flagSetSlice) has(f Flag) bool {
for _, ff := range *fss {
if f == ff {
return true
}
}
return false
}