-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflag.go
536 lines (450 loc) · 12.2 KB
/
flag.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package gg
import (
"encoding"
r "reflect"
)
/*
Parses CLI flags into an instance of the given type, which must be a struct.
For parsing rules, see `FlagParser`.
*/
func FlagParseTo[A any](src []string) (out A) {
FlagParse(src, &out)
return
}
/*
Parses CLI flags into the given value, which must be a struct.
Panics on error. For parsing rules, see `FlagParser`.
*/
func FlagParse[A any](src []string, out *A) {
if out != nil {
FlagParseReflect(src, r.ValueOf(AnyNoEscUnsafe(out)).Elem())
}
}
/*
Parses CLI flags into the given value, which must be a struct.
For parsing rules, see `FlagParser`.
*/
func FlagParseCatch[A any](src []string, out *A) (err error) {
defer Rec(&err)
FlagParse(src, out)
return
}
/*
Parses CLI flags into the given output, which must be a settable struct value.
For parsing rules, see `FlagParser`.
*/
func FlagParseReflect(src []string, out r.Value) {
if !out.IsValid() {
return
}
var par FlagParser
par.Init(out)
par.Args(src)
par.Default()
}
/*
Tool for parsing lists of CLI flags into structs. Partial replacement for the
standard library package "flag". Example:
type Opt struct {
Args []string `flag:""`
Help bool `flag:"-h" desc:"Print help and exit."`
Verb bool `flag:"-v" desc:"Verbose logging."`
Src string `flag:"-s" init:"." desc:"Source path."`
Out string `flag:"-o" desc:"Destination path."`
}
func (self *Opt) Init() {
gg.FlagParse(os.Args[1:], self)
if self.Help {
log.Println(gg.FlagHelp[Opt]())
os.Exit(0)
}
if gg.IsZero(self.Out) {
log.Println(`missing output path: "-o"`)
os.Exit(1)
}
}
Supported struct tags:
* `flag`: must be "" or a valid flag like "-v" or "--verbose".
Fields without the `flag` tag are ignored. Flags must be unique.
* Field with `flag:""` is used for remaining non-flag args.
It must have a type convertible to `[]string`.
* `init`: initial value. Used if the flag was not provided.
* `desc`: description. Used for help printing.
Parsing rules:
* Supports all primitive types.
* Supports slices of arbitrary types.
* Supports `gg.Parser`.
* Supports `encoding.TextUnmarshaler`.
* Supports `flag.Value`.
* Each flag may be listed multiple times.
* If the target is a parser, invoke its parsing method.
* If the target is a scalar, replace the old value with the new value.
* If the target is a slice, append the new value.
*/
type FlagParser struct {
Tar r.Value
Def FlagDef
Got Set[string]
}
/*
Initializes the parser for the given destination, which must be a settable
struct value.
*/
func (self *FlagParser) Init(tar r.Value) {
self.Tar = tar
self.Def = FlagDefCache.Get(tar.Type())
self.Got = make(Set[string], len(self.Def.Flags))
}
/*
Parses the given CLI args into the destination. May be called multiple times.
Must be called after `(*FlagParser).Init`, and before `FlagParser.Default`.
*/
func (self FlagParser) Args(src []string) {
for IsNotEmpty(src) {
if !isCliFlag(Head(src)) {
self.SetArgs(src)
return
}
head := PopHead(&src)
key, val, split := cliFlagSplit(head)
if split {
self.Got.Add(key)
self.Flag(key, val)
continue
}
self.Got.Add(head)
if IsEmpty(src) || isCliFlag(Head(src)) {
self.TrailingFlag(head)
continue
}
if self.TrailingBool(head) {
continue
}
self.Flag(head, PopHead(&src))
}
}
// For internal use.
func (self FlagParser) SetArgs(src []string) {
field := self.Def.Args
if field.IsValid() {
self.Tar.
FieldByIndex(field.Index).
Set(r.ValueOf(src).Convert(field.Type))
return
}
if IsEmpty(src) {
return
}
panic(Errf(`unexpected non-flag args: %q`, src))
}
// For internal use.
func (self FlagParser) FlagField(key string) r.Value {
return self.Tar.FieldByIndex(self.Def.Get(key).Index)
}
// For internal use.
func (self FlagParser) Flag(key, src string) {
self.FieldParse(src, self.FlagField(key))
}
// For internal use.
func (self FlagParser) FieldParse(src string, out r.Value) {
var nested bool
interfaces:
ptr := out.Addr().Interface()
// Part of the `flag.Value` interface.
setter, _ := ptr.(interface{ Set(string) error })
if setter != nil {
Try(setter.Set(src))
return
}
parser, _ := ptr.(Parser)
if parser != nil {
Try(parser.Parse(src))
return
}
unmarshaler, _ := ptr.(encoding.TextUnmarshaler)
if unmarshaler != nil {
Try(unmarshaler.UnmarshalText(ToBytes(src)))
return
}
if out.Kind() == r.Slice {
growLenReflect(out)
out = out.Index(out.Len() - 1)
if !nested {
nested = true
goto interfaces
}
}
if out.Kind() == r.Bool && src == `` {
src = `true`
}
Try(ParseReflectCatch(src, out.Addr()))
}
// For internal use.
func (self FlagParser) TrailingFlag(key string) {
// TODO: consider supporting various parser interfaces here.
if self.TrailingBool(key) {
return
}
panic(Errf(`missing value for trailing flag %q`, key))
}
// For internal use.
func (self FlagParser) TrailingBool(key string) bool {
/**
Following the established conventions, bool flags don't support
"-flag value", only "-flag=value". A boolean flag always terminates
immediately, without looking for a following space-separated value.
*/
tar := self.FlagField(key)
if tar.Kind() == r.Bool {
tar.SetBool(true)
return true
}
if tar.Kind() == r.Slice && tar.Type().Elem().Kind() == r.Bool {
growLenReflect(tar)
tar.Index(tar.Len() - 1).SetBool(true)
return true
}
return false
}
/*
Applies defaults to all flags which have not been found during parsing.
Explicitly providing an empty value suppresses a default, although
an empty string may not be a viable input to some types.
*/
func (self FlagParser) Default() {
for _, field := range self.Def.Flags {
if !self.Got.Has(field.Flag) {
if field.InitHas {
self.FieldParse(field.Init, self.Tar.FieldByIndex(field.Index))
}
}
}
}
// Returns a help string for the given struct type, using `FlagFmtDefault`.
func FlagHelp[A any]() string {
return FlagDefCache.Get(Type[A]()).Help()
}
// Stores cached `FlagDef` definitions for struct types.
var FlagDefCache = TypeCacheOf[FlagDef]()
/*
Struct type definition suitable for flag parsing. Used internally by
`FlagParser`. User code shouldn't have to use this type, but it's exported for
customization purposes.
*/
type FlagDef struct {
Type r.Type
Args FlagDefField
Flags []FlagDefField
Index map[string]int
}
// For internal use.
func (self *FlagDef) Init(src r.Type) {
self.Type = src
Each(StructDeepPublicFieldCache.Get(src), self.AddField)
}
// For internal use.
func (self *FlagDef) AddField(src r.StructField) {
var field FlagDefField
field.Set(src)
if !field.FlagHas {
return
}
if MapHas(self.Index, field.Flag) ||
(field.Flag == `` && self.Args.IsValid()) {
panic(Errf(`redundant flag %q in type %v`, field.Flag, self.Type))
}
if field.Flag == `` {
if !field.Type.ConvertibleTo(Type[[]string]()) {
panic(Errf(
`invalid type %v in field %q of type %v: args field must be convertible to []string`,
field.Type, field.Name, self.Type,
))
}
self.Args = field
return
}
if !isCliFlagValid(field.Flag) {
panic(Errf(
`invalid flag %q in field %q of type %v`,
field.Flag, field.Name, self.Type,
))
}
MapInit(&self.Index)[field.Flag] = len(self.Flags)
Append(&self.Flags, field)
}
// For internal use.
func (self FlagDef) Got(key string) (FlagDefField, bool) {
ind, ok := self.Index[key]
if !ok {
return Zero[FlagDefField](), false
}
return Got(self.Flags, ind)
}
// For internal use.
func (self FlagDef) Get(key string) FlagDefField {
val, ok := self.Got(key)
if !ok {
panic(Errf(`unable to find flag %q in type %v`, key, self.Type))
}
return val
}
// Creates a help string listing the available flags, using `FlagFmtDefault`.
func (self FlagDef) Help() string { return FlagFmtDefault.String(self) }
// Used internally by `FlagDef`.
type FlagDefField struct {
r.StructField
Flag string
FlagHas bool
FlagLen int
Init string
InitHas bool
InitLen int
Desc string
DescHas bool
DescLen int
}
func (self FlagDefField) IsValid() bool { return IsNotZero(self) }
func (self *FlagDefField) Set(src r.StructField) {
self.StructField = src
self.Flag, self.FlagHas = self.Tag.Lookup(`flag`)
self.Init, self.InitHas = self.Tag.Lookup(`init`)
self.Desc = self.Tag.Get(`desc`)
self.FlagLen = CharCount(self.Flag)
self.InitLen = CharCount(self.Init)
self.DescLen = CharCount(self.Desc)
self.DescHas = self.DescLen > 0
}
func (self FlagDefField) GetFlagHas() bool { return self.FlagHas }
func (self FlagDefField) GetInitHas() bool { return self.InitHas }
func (self FlagDefField) GetDescHas() bool { return self.DescHas }
func (self FlagDefField) GetFlagLen() int { return self.FlagLen }
func (self FlagDefField) GetInitLen() int { return self.InitLen }
func (self FlagDefField) GetDescLen() int { return self.DescLen }
// Default help formatter, used by `FlagHelp` and `FlagDef.Help`.
var FlagFmtDefault = With((*FlagFmt).Default)
/*
Table-like formatter for listing available flags, initial values, and
descriptions. Used via `FlagFmtDefault`, `FlagHelp`, `FlagDef.Help`.
To customize printing, mutate `FlagFmtDefault`.
*/
type FlagFmt struct {
Prefix string // Prepended before each line.
Infix string // Inserted between columns.
Head bool // If true, print table header.
FlagHead string // Title for header cell "flag".
InitHead string // Title for header cell "init".
DescHead string // Title for header cell "desc".
HeadUnder string // Separator between table header and body.
}
// Sets default values.
func (self *FlagFmt) Default() {
self.Infix = ` `
self.Head = true
self.FlagHead = `flag`
self.InitHead = `init`
self.DescHead = `desc`
self.HeadUnder = `-`
}
// Returns a table-like help string for the given definition.
func (self FlagFmt) String(def FlagDef) string {
return ToString(self.AppendTo(nil, def))
}
/*
Appends table-like help for the given definition. Known limitation: assumes
monospace, doesn't support wider characters such as kanji or emoji.
*/
func (self FlagFmt) AppendTo(src []byte, def FlagDef) []byte {
flags := def.Flags
if IsEmpty(flags) {
return src
}
prefixLen := CharCount(self.Prefix)
sepLen := CharCount(self.Infix)
newlineLen := CharCount(Newline)
flagLen := MaxPrimBy(flags, FlagDefField.GetFlagLen)
var flagHeadLen int
if self.Head {
flagHeadLen = CharCount(self.FlagHead)
flagLen = MaxPrim2(flagHeadLen, flagLen)
}
var initHeadLen int
var initLen int
if Some(flags, FlagDefField.GetInitHas) {
if self.Head {
initHeadLen = CharCount(self.InitHead)
}
initLen = MaxPrim2(
initHeadLen,
MaxPrimBy(flags, FlagDefField.GetInitLen),
)
}
var initLenOuter int
if initLen > 0 {
initLenOuter = sepLen + initLen
}
var descHeadLen int
var descLen int
if Some(flags, FlagDefField.GetDescHas) {
if self.Head {
descHeadLen = CharCount(self.DescHead)
}
descLen = MaxPrim2(
descHeadLen,
MaxPrimBy(flags, FlagDefField.GetDescLen),
)
}
var descLenOuter int
if descLen > 0 {
descLenOuter = sepLen + descLen
}
rowLenInner := prefixLen + flagLen + initLenOuter + descLenOuter
rowLen := rowLenInner + newlineLen
headUnderLen := CharCount(self.HeadUnder)
buf := Buf(src)
buf.GrowCap(((2 + len(flags)) * rowLen))
if self.Head {
buf.AppendString(self.Prefix)
buf.AppendString(self.FlagHead)
buf.AppendSpaces(flagLen - flagHeadLen)
if initLen > 0 || descLen > 0 {
buf.AppendSpaces(flagLen - flagHeadLen)
}
if initLen > 0 {
buf.AppendString(self.Infix)
buf.AppendString(self.InitHead)
if descLen > 0 {
buf.AppendSpaces(initLen - initHeadLen)
}
}
if descLen > 0 {
buf.AppendString(self.Infix)
buf.AppendString(self.DescHead)
}
buf.AppendString(Newline)
if rowLenInner > 0 && headUnderLen > 0 {
buf.AppendString(self.Prefix)
buf.AppendStringN(self.HeadUnder, rowLenInner/headUnderLen)
buf.AppendString(Newline)
}
}
for _, field := range flags {
buf.AppendString(self.Prefix)
buf.AppendString(field.Flag)
if initLen > 0 || descLen > 0 {
buf.AppendSpaces(flagLen - field.FlagLen)
}
if initLen > 0 {
buf.AppendString(self.Infix)
buf.AppendString(field.Init)
if descLen > 0 {
buf.AppendSpaces(initLen - field.InitLen)
}
}
if descLen > 0 {
buf.AppendString(self.Infix)
buf.AppendString(field.Desc)
}
buf.AppendString(Newline)
}
return buf
}