-
Notifications
You must be signed in to change notification settings - Fork 2
/
cmdline.go
1082 lines (1015 loc) · 30 KB
/
cmdline.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmdline
import (
"encoding/json"
"fmt"
"gopkg.in/yaml.v2"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
)
// ConfigSection defines a section of the help output, for grouping commands together
type ConfigSection struct {
Description string
Order int
}
// ConfigType describes a kind of parameter that can be used on the command line
type ConfigType struct {
name string
description string
objType reflect.Type
required bool
singleton bool
exclusive bool
hidden bool
section *ConfigSection
}
// Required means this config type must be provided
func Required(param *ConfigType) {
param.required = true
}
// Singleton means there can only be one of this config type
func Singleton(param *ConfigType) {
param.singleton = true
}
// Exclusive means if this config type exists, none other is allowed
func Exclusive(param *ConfigType) {
param.exclusive = true
}
// Hidden means this config type is not listed in help or bash completion
func Hidden(param *ConfigType) {
param.hidden = true
}
// Section means this config type should be listed within a section in the help
func Section(section *ConfigSection) func(param *ConfigType) {
return func(param *ConfigType) {
param.section = section
}
}
// Cmdline is a command-line processor object
type Cmdline struct {
configTypes []*ConfigType
out io.Writer
whatRan string
}
// NewCmdline constructs a new cmdline object
func NewCmdline() *Cmdline {
cl := &Cmdline{
out: os.Stdout,
}
return cl
}
// SetOutput configures where the output of a Cmdline instance will go
func (cl *Cmdline) SetOutput(out io.Writer) {
cl.out = out
}
// WhatRan returns the name of an exclusive command, if any, that ran on the last invocation of ParseAndRun
func (cl *Cmdline) WhatRan() string {
return cl.whatRan
}
// makeConfigTYpe constructs a new ConfigType object, applying given modifiers
func makeConfigType(name string, description string, configType interface{}, options ...func(*ConfigType)) *ConfigType {
newCT := &ConfigType{
name: name,
description: description,
objType: reflect.TypeOf(configType),
}
for _, opt := range options {
opt(newCT)
}
return newCT
}
// AddConfigType registers a new config type with the system
func (cl *Cmdline) AddConfigType(name string, description string, configType interface{}, options ...func(*ConfigType)) {
cl.configTypes = append(cl.configTypes, makeConfigType(name, description, configType, options...))
}
var globalAppConfigTypes map[string][]*ConfigType
// RegisterConfigTypeForApp globally registers a new config type that can be used with a named application
func RegisterConfigTypeForApp(appName string, name string, description string, configType interface{},
options ...func(*ConfigType)) {
if globalAppConfigTypes == nil {
globalAppConfigTypes = make(map[string][]*ConfigType)
}
appCTs, _ := globalAppConfigTypes[appName]
appCTs = append(appCTs, makeConfigType(name, description, configType, options...))
globalAppConfigTypes[appName] = appCTs
}
// AddRegisteredConfigTypes adds the registered config types for an app to the system
func (cl *Cmdline) AddRegisteredConfigTypes(appName string) {
appCTs, ok := globalAppConfigTypes[appName]
if ok {
cl.configTypes = append(cl.configTypes, appCTs...)
}
}
// printableTypeName returns a human-readable name of a type, suitable for use in help text
func printableTypeName(typ reflect.Type) string {
if typ.String() == "interface {}" {
return fmt.Sprintf("JSON data")
} else if typ.String() == "map[string]interface {}" {
return fmt.Sprintf("JSON dict with string keys")
} else if typ.Kind() == reflect.Map {
return fmt.Sprintf("JSON dict of %s to %s", printableTypeName(typ.Key()), printableTypeName(typ.Elem()))
} else if typ.Kind() == reflect.Slice {
if typ.Elem() == reflect.TypeOf("") {
return fmt.Sprintf("%s (may be repeated)", typ.String())
}
return fmt.Sprintf("JSON list of %s", printableTypeName(typ.Elem()))
} else if typ.String() == "interface {}" {
return "anything"
}
return typ.String()
}
// recursiveEnumerateFields is the recursive companion of enumerateFields and should only be called from there.
func recursiveEnumerateFields(typ reflect.Type, results chan<- reflect.StructField) {
for i := 0; i < typ.NumField(); i++ {
ctf := typ.Field(i)
ignore, err := betterParseBool(ctf.Tag.Get("ignore"))
if err == nil && ignore {
continue
}
if ctf.Type.Kind() == reflect.Struct {
recursiveEnumerateFields(ctf.Type, results)
} else {
results <- ctf
}
}
}
// enumerateFields enumerates primitive fields in a struct, including composed structs.
// If a composed struct has the same name as a struct member, that name will be returned twice.
func enumerateFields(typ reflect.Type) []reflect.StructField {
resultChan := make(chan reflect.StructField)
go func() {
recursiveEnumerateFields(typ, resultChan)
close(resultChan)
}()
results := make([]reflect.StructField, 0)
for r := range resultChan {
results = append(results, r)
}
return results
}
// printCmdHelp prints the generated help text for a single config type
func (cl *Cmdline) printCmdHelp(p *ConfigType) error {
if p.hidden {
return nil
}
var err error
_, err = fmt.Fprintf(cl.out, " --%s", strings.ToLower(p.name))
if err != nil {
return err
}
if p.description != "" {
_, err = fmt.Fprintf(cl.out, ": %s", p.description)
if err != nil {
return err
}
}
if p.required {
_, err = fmt.Fprintf(cl.out, " (required)")
if err != nil {
return err
}
}
_, err = fmt.Fprintf(cl.out, "\n")
if err != nil {
return err
}
for _, ctf := range enumerateFields(p.objType) {
_, err = fmt.Fprintf(cl.out, " %s=<%s>", strings.ToLower(ctf.Name),
printableTypeName(ctf.Type))
if err != nil {
return err
}
descr := ctf.Tag.Get("description")
if descr != "" {
_, err = fmt.Fprintf(cl.out, ": %s", descr)
if err != nil {
return err
}
}
extras := make([]string, 0)
var req bool
req, err = betterParseBool(ctf.Tag.Get("required"))
if err == nil && req {
extras = append(extras, "required")
}
def := ctf.Tag.Get("default")
if def != "" {
extras = append(extras, fmt.Sprintf("default: %s", def))
}
if len(extras) > 0 {
_, err = fmt.Fprintf(cl.out, " (%s)", strings.Join(extras, ", "))
if err != nil {
return err
}
}
_, err = fmt.Fprintf(cl.out, "\n")
if err != nil {
return err
}
}
_, err = fmt.Fprintf(cl.out, "\n")
if err != nil {
return err
}
return nil
}
// multiPrintfItem represents a single item to be printed by multiPrintf
type multiPrintfItem struct {
format string
values []interface{}
}
// mPI is a convenience function for constructing multiPrintfItems more laconically
func mPI(format string, values ...interface{}) *multiPrintfItem {
return &multiPrintfItem{
format: format,
values: values,
}
}
// multiPrintf calls fmt.Fprintf on multiple items, until there is an error
func multiPrintf(out io.Writer, items ...*multiPrintfItem) error {
for _, item := range items {
_, err := fmt.Fprintf(out, item.format, item.values...)
if err != nil {
return err
}
}
return nil
}
// ShowHelp prints command line help. It does NOT exit. If out is nil, writes to stdout.
func (cl *Cmdline) ShowHelp() error {
// Construct list of sections
sections := make([]*ConfigSection, 1)
sections[0] = &ConfigSection{
Description: "",
Order: 0,
}
for _, ct := range cl.configTypes {
if ct.section == nil || ct.hidden {
continue
}
found := false
for _, sect := range sections {
if ct.section == sect {
found = true
break
}
}
if found {
continue
}
sections = append(sections, ct.section)
}
sort.SliceStable(sections, func(i int, j int) bool {
return sections[i].Order < sections[j].Order
})
progname := path.Base(os.Args[0])
var err error
err = multiPrintf(cl.out,
mPI("Usage: %s [--<action> [<param>=<value> ...] ...]\n\n", progname),
mPI(" --help: Show this help\n\n"),
mPI(" --config <filename>: Load additional config options from a YAML file\n\n"))
if err != nil {
return err
}
if runtime.GOOS != "windows" {
err = multiPrintf(cl.out,
mPI(" --bash-completion: Generate a completion script for the bash shell\n"),
mPI(" Run \". <(%s --bash-completion)\" to activate now\n\n", progname))
if err != nil {
return err
}
}
for s, sect := range sections {
if sect.Description != "" {
_, err = fmt.Fprintf(cl.out, "%s\n\n", sect.Description)
if err != nil {
return err
}
}
for _, req := range []bool{true, false} {
for _, ct := range cl.configTypes {
if (s == 0 && ct.section != nil) || (s != 0 && ct.section != sect) || ct.hidden {
continue
}
if ct.required == req {
err = cl.printCmdHelp(ct)
if err != nil {
return err
}
}
}
}
}
return nil
}
// BashCompletion outputs a Bash script for command-line completion of the current cmdline configuration.
func (cl *Cmdline) BashCompletion() error {
var err error
cmdName := filepath.Base(os.Args[0])
err = multiPrintf(cl.out,
mPI("_%s()\n", cmdName),
mPI("{\n"),
mPI(" local cur prevdashed count DASHCMDS\n"),
mPI(" cur=${COMP_WORDS[COMP_CWORD]}\n"),
mPI(" count=$((COMP_CWORD-1))\n"),
mPI(" while [[ $count > 1 && ! ${COMP_WORDS[$count]} == --* ]]; do\n"),
mPI(" count=$((count-1))\n"),
mPI(" done\n"),
mPI(" prevdashed=${COMP_WORDS[$count]}\n"))
if err != nil {
return err
}
actions := []string{"--help", "--bash-completion", "--config", "-c"}
for _, ct := range cl.configTypes {
actions = append(actions, fmt.Sprintf("--%s", strings.ToLower(ct.name)))
}
err = multiPrintf(cl.out,
mPI(" DASHCMDS=\"%s\"\n", strings.Join(actions, " ")),
mPI(" if [[ $cur == -* ]]; then\n"),
mPI(" COMPREPLY=($(compgen -W \"$DASHCMDS\" -- ${cur}))\n"),
mPI(" else"),
mPI(" case ${prevdashed} in\n"),
mPI(" -c|--config)\n"),
mPI(" COMPREPLY=($(compgen -f -- ${cur}))\n"),
mPI(" ;;\n"))
if err != nil {
return err
}
for _, ct := range cl.configTypes {
if ct.hidden {
continue
}
_, err = fmt.Fprintf(cl.out, " --%s)\n", strings.ToLower(ct.name))
if err != nil {
return err
}
params := make([]string, 0)
for _, ctf := range enumerateFields(ct.objType) {
params = append(params, fmt.Sprintf("%s=", strings.ToLower(ctf.Name)))
}
err = multiPrintf(cl.out,
mPI(" COMPREPLY=($(compgen -W \"%s\" -- ${cur}))\n", strings.Join(params, " ")),
mPI(" ;;\n"))
if err != nil {
return err
}
}
err = multiPrintf(cl.out,
mPI(" *)\n"),
mPI(" COMPREPLY=($(compgen -W \"$DASHCMDS\" -- ${cur}))\n"),
mPI(" ;;\n"),
mPI(" esac\n"),
mPI(" fi\n"),
mPI(" [[ $COMPREPLY == *= ]] && compopt -o nospace\n"),
mPI("}\n"),
mPI("complete -F _%s %s\n", cmdName, cmdName))
if err != nil {
return err
}
return nil
}
// setValue attempts to write a single value to a struct field, performing all necessary type conversions
func setValue(field *reflect.Value, value interface{}) error {
fieldType := field.Type()
fieldKind := fieldType.Kind()
valueType := reflect.TypeOf(value)
// Handle the case where the value to be assigned is nil
if valueType == nil {
if fieldKind == reflect.Map || fieldKind == reflect.Slice {
field.Set(reflect.Zero(fieldType))
return nil
}
return fmt.Errorf("value cannot be nil")
}
valueKind := valueType.Kind()
// If the destination is a string, try some string conversions
if fieldKind == reflect.String {
switch valueKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
field.SetString(fmt.Sprintf("%d", value))
return nil
case reflect.Float32, reflect.Float64:
field.SetString(fmt.Sprintf("%f", value))
return nil
case reflect.Bool:
field.SetString(fmt.Sprintf("%t", value))
return nil
}
}
// If the value is directly convertible to the field, just set it
if valueType.ConvertibleTo(fieldType) {
field.Set(reflect.ValueOf(value).Convert(fieldType))
return nil
}
// Get string version of value
valueStr, isString := value.(string)
// If the field is a map, check if we were given a JSON-encoded string
if fieldKind == reflect.Map && valueKind == reflect.String && isString && strings.HasPrefix(valueStr, "{") {
valueType = reflect.MapOf(fieldType.Key(), fieldType.Elem())
valueKind = valueType.Kind()
dest := reflect.MakeMap(valueType)
value = dest.Interface()
err := json.Unmarshal([]byte(valueStr), &value)
if err != nil {
return err
}
// We do not return here because we still need the map copy below
}
// If the field and value are a map type, attempt to copy the keys/values
if fieldKind == reflect.Map && valueKind == reflect.Map {
fieldMap := reflect.MakeMap(reflect.MapOf(fieldType.Key(), fieldType.Elem()))
iter := reflect.ValueOf(value).MapRange()
for iter.Next() {
itemKey := reflect.ValueOf(iter.Key().Interface())
if !itemKey.Type().ConvertibleTo(fieldType.Key()) {
return fmt.Errorf("invalid key %s: must be type %s", itemKey, fieldType.Key())
}
itemValue := reflect.ValueOf(iter.Value().Interface())
if !itemValue.Type().ConvertibleTo(fieldType.Elem()) {
return fmt.Errorf("invalid value %s: must be type %s", itemValue, fieldType.Elem())
}
fieldMap.SetMapIndex(itemKey.Convert(fieldType.Key()), itemValue.Convert(fieldType.Elem()))
}
field.Set(fieldMap)
return nil
}
// If the field is a slice, check if we were given a JSON-encoded string
if fieldKind == reflect.Slice && valueKind == reflect.String && isString && strings.HasPrefix(valueStr, "[") {
valueType = reflect.SliceOf(fieldType.Elem())
valueKind = valueType.Kind()
dest := reflect.MakeSlice(valueType, 0, 0)
value = dest.Interface()
err := json.Unmarshal([]byte(valueStr), &value)
if err != nil {
return err
}
// We do not return here because we still need the slice copy below
}
// If the field and value are a slice type, attempt to copy the values
if fieldKind == reflect.Slice && valueKind == reflect.Slice {
valueSlice, ok := value.([]interface{})
if !ok {
return fmt.Errorf("invalid value for slice type")
}
fieldSlice := reflect.MakeSlice(fieldType, 0, 0)
for _, v := range valueSlice {
item := reflect.ValueOf(v)
if !item.Type().ConvertibleTo(fieldType.Elem()) {
return fmt.Errorf("invalid value %s: must be type %s", item, fieldType.Elem())
}
fieldSlice = reflect.Append(fieldSlice, item.Convert(fieldType.Elem()))
}
field.Set(fieldSlice)
return nil
}
// If the value is a string and no direct conversions were possible, try some string conversions
if isString {
switch fieldKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v, err := strconv.ParseInt(valueStr, 0, 64)
if err != nil {
return err
}
field.SetInt(v)
return nil
case reflect.Float32, reflect.Float64:
v, err := strconv.ParseFloat(valueStr, 64)
if err != nil {
return err
}
field.SetFloat(v)
return nil
case reflect.Bool:
v, err := betterParseBool(valueStr)
if err != nil {
return err
}
field.SetBool(v)
return nil
}
// If param is a string and field is a string array, append it
stringSlice, ok := field.Interface().([]string)
if ok {
stringSlice = append(stringSlice, valueStr)
field.Set(reflect.ValueOf(stringSlice))
return nil
}
}
return fmt.Errorf("type error (expected %s)", fieldType)
}
// plural returns a singular or plural string, depending on whether count is 1 or more than 1
func plural(count int, singular string, plural string) string {
if count > 1 {
return plural
}
return singular
}
// betterParseBool parses a single boolean value from a string, with a few more options than the go default
func betterParseBool(s string) (bool, error) {
switch s {
case "1", "t", "T", "Y", "true", "TRUE", "True", "yes", "Yes", "YES":
return true, nil
case "0", "f", "F", "N", "false", "FALSE", "False", "no", "No", "NO":
return false, nil
}
return false, fmt.Errorf("could not parse %s as boolean", s)
}
// convTagToBool converts a tag value to a boolean, returning a default if the tag value is empty
func convTagToBool(tag string, def bool) (bool, error) {
if tag == "" {
return def, nil
}
b, err := betterParseBool(tag)
if err != nil {
return def, fmt.Errorf("could not parse %s as boolean: %s", tag, err)
}
return b, nil
}
// getCfgObjectType case-insensitively looks up a config type in the configTypes list
func (cl *Cmdline) getCfgObjType(objType string) (*ConfigType, error) {
for _, ct := range cl.configTypes {
if objType == strings.ToLower(ct.name) {
return ct, nil
}
}
return nil, fmt.Errorf("unknown config type %s", objType)
}
// getBareParam searches a struct for a member with a true barevalue tag
func getBareParam(commandType reflect.Type) (string, error) {
for _, ctf := range enumerateFields(commandType) {
b, err := convTagToBool(ctf.Tag.Get("barevalue"), false)
if err != nil {
return "", err
}
if b {
return ctf.Name, nil
}
}
return "", fmt.Errorf("command does not allow bare values")
}
// getFieldByName searches for a field by case-insensitive name and returns it if found
func getFieldByName(obj *reflect.Value, fieldName string) (*reflect.Value, error) {
for _, ctf := range enumerateFields(obj.Type()) {
if strings.ToLower(ctf.Name) == strings.ToLower(fieldName) {
fobj := obj.FieldByName(ctf.Name)
return &fobj, nil
}
}
return nil, fmt.Errorf("unknown field name %s", fieldName)
}
// buildRequiredParams returns a map whose indexes are the parameters of a struct with a true "required" tag
func buildRequiredParams(commandType reflect.Type) (map[string]struct{}, error) {
requiredParams := make(map[string]struct{})
for _, ctf := range enumerateFields(commandType) {
req, err := convTagToBool(ctf.Tag.Get("required"), false)
if err != nil {
return nil, err
}
if req {
requiredParams[strings.ToLower(ctf.Name)] = struct{}{}
}
}
return requiredParams, nil
}
// checkRequiredParams verifies that the requiredParams map is empty, otherwise returns an error listing the fields
func checkRequiredParams(requiredParams map[string]struct{}) error {
if len(requiredParams) > 0 {
sl := make([]string, 0, len(requiredParams))
for p := range requiredParams {
sl = append(sl, p)
}
return fmt.Errorf("required parameter%s missing: %s",
plural(len(requiredParams), "", "s"),
strings.Join(sl, ", "))
}
return nil
}
// cfgObjInfo holds temporary data while parsing a config object
type cfgObjInfo struct {
obj reflect.Value
arg string
fieldsSet []string
}
// newCOI instantiates a new cfgObjInfo
func newCOI() *cfgObjInfo {
return &cfgObjInfo{
obj: reflect.Value{},
arg: "",
fieldsSet: make([]string, 0),
}
}
// loadConfigFromFile loads and parses a YAML config file
func (cl *Cmdline) loadConfigFromFile(filename string) ([]*cfgObjInfo, error) {
var err error
var ok bool
var data []byte
data, err = ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
config := make([]interface{}, 0)
err = yaml.Unmarshal(data, &config)
if err != nil {
return nil, err
}
cfgObjs := make([]*cfgObjInfo, 0)
for _, cfg := range config {
var str string
str, ok = cfg.(string)
var command string
var rawParams interface{}
if ok {
command = str
rawParams = nil
} else {
var imap map[interface{}]interface{}
imap, ok = cfg.(map[interface{}]interface{})
if ok {
if len(imap) != 1 {
return nil, fmt.Errorf("config format invalid: item has multiple names")
}
var k interface{}
var v interface{}
for k, v = range imap {
break
}
str, ok = k.(string)
if !ok {
return nil, fmt.Errorf("section key is not a string")
}
command = str
rawParams = v
} else {
return nil, fmt.Errorf("unknown config file format")
}
}
var ct *ConfigType
ct, err = cl.getCfgObjType(command)
if err != nil {
return nil, fmt.Errorf("could not get config type for command %s: %s", command, err)
}
params := make(map[string]interface{})
if rawParams == nil {
// this space intentionally left blank
} else {
str, ok = rawParams.(string)
if ok {
// param is a single string, so it is a barevalue
var bareparam string
bareparam, err = getBareParam(ct.objType)
if err != nil {
return nil, fmt.Errorf("could not get barevalue for command %s: %s", command, err)
}
params[bareparam] = str
} else {
// only other choice is for param to be a map
var pmap map[interface{}]interface{}
pmap, ok = rawParams.(map[interface{}]interface{})
if !ok {
return nil, fmt.Errorf("invalid config format for %s", command)
}
for k, v := range pmap {
var ks string
ks, ok = k.(string)
if !ok {
return nil, fmt.Errorf("invalid config format for %s", command)
}
params[ks] = v
}
}
}
if ct.singleton {
for c := range cfgObjs {
if cfgObjs[c].obj.Type() == ct.objType {
return nil, fmt.Errorf("only one %s directive is allowed", command)
}
}
}
coi := newCOI()
coi.obj = reflect.New(ct.objType).Elem()
coi.arg = command
var requiredParams map[string]struct{}
requiredParams, err = buildRequiredParams(ct.objType)
if err != nil {
return nil, err
}
for k, v := range params {
var f *reflect.Value
f, err = getFieldByName(&coi.obj, k)
if err != nil {
return nil, fmt.Errorf("field %s not defined for command %s: %s", k, command, err)
}
if !f.CanSet() {
return nil, fmt.Errorf("field %s is (maybe private)", k)
}
err = setValue(f, v)
if err != nil {
return nil, fmt.Errorf("error setting field %s in command %s: %s", k, command, err)
}
coi.fieldsSet = append(coi.fieldsSet, k)
delete(requiredParams, strings.ToLower(k))
}
err = checkRequiredParams(requiredParams)
if err != nil {
return nil, fmt.Errorf("error in %s: %s", command, err)
}
cfgObjs = append(cfgObjs, coi)
}
return cfgObjs, nil
}
// parseAndRunOptions is the configuration struct for ParseAndRun
type parseAndRunOptions struct {
helpIfNoArgs bool
}
// ShowHelpIfNoArgs means that if the user provides no arguments, print the help instead of doing anything
func ShowHelpIfNoArgs(pro *parseAndRunOptions) {
pro.helpIfNoArgs = true
}
// ParseAndRun parses the command line configuration and runs the selected actions. Phases is a list of function
// names that will be called on each config objects. If some objects need to be configured before others, use
// multiple phases. Each phase is run against all objects before moving to the next phase. The return value is
// the name of the exclusive object that was run, if any, or an empty string if the normal, non-exclusive command ran.
func (cl *Cmdline) ParseAndRun(args []string, phases []string, options ...func(*parseAndRunOptions)) error {
pro := parseAndRunOptions{}
for _, proFunc := range options {
proFunc(&pro)
}
if len(args) == 0 && pro.helpIfNoArgs {
err := cl.ShowHelp()
if err != nil {
return err
}
cl.whatRan = "help"
return nil
}
var accumulator *cfgObjInfo
var commandType reflect.Type
var requiredParams map[string]struct{}
var err error
requiredObjs := make(map[string]bool)
activeObjs := make([]*cfgObjInfo, 0)
configCmd := false
for _, ct := range cl.configTypes {
if ct.required {
requiredObjs[ct.objType.Name()] = true
}
}
for _, arg := range args {
lcarg := strings.ToLower(arg)
if lcarg == "-h" || lcarg == "--help" && cl.out != nil {
err = cl.ShowHelp()
if err != nil {
return err
}
cl.whatRan = "help"
return nil
} else if lcarg == "--bash-completion" && cl.out != nil {
err = cl.BashCompletion()
if err != nil {
return err
}
cl.whatRan = "bash-completion"
return nil
} else if lcarg[0] == '-' {
// This is a param with dashes, which starts a new action
if strings.HasPrefix(lcarg, "--") {
lcarg = lcarg[2:]
} else if strings.HasPrefix(lcarg, "-") {
lcarg = lcarg[1:]
}
// If we were accumulating an action, store it (it is now complete)
if commandType != nil && accumulator != nil {
err = checkRequiredParams(requiredParams)
if err != nil {
return fmt.Errorf("error in %s: %s", accumulator.arg, err)
}
activeObjs = append(activeObjs, accumulator)
accumulator = nil
}
if lcarg == "config" || lcarg == "c" {
configCmd = true
} else {
// Search for the command in our known config types, and start a new accumulator
var ct *ConfigType
ct, err = cl.getCfgObjType(lcarg)
if err != nil {
return fmt.Errorf("command error: %s", err)
}
commandType = ct.objType
if ct.singleton {
for c := range activeObjs {
if activeObjs[c].obj.Type() == ct.objType {
return fmt.Errorf("directive \"%s\" is only allowed once", ct.name)
}
}
}
accumulator = newCOI()
accumulator.obj = reflect.New(commandType).Elem()
accumulator.arg = arg
delete(requiredObjs, ct.objType.Name())
requiredParams, err = buildRequiredParams(ct.objType)
if err != nil {
return err
}
}
} else {
// This arg did not start with a dash, so it is a parameter to the current accumulation
if configCmd {
configCmd = false
var newObjs []*cfgObjInfo
newObjs, err = cl.loadConfigFromFile(arg)
if err != nil {
return fmt.Errorf("error loading config file: %s", err)
}
for j := range newObjs {
coi := newObjs[j]
delete(requiredObjs, coi.obj.Type().Name())
activeObjs = append(activeObjs, coi)
}
continue
}
if commandType == nil || accumulator == nil {
return fmt.Errorf("parameter specified before command")
}
sarg := strings.SplitN(arg, "=", 2)
if len(sarg) == 1 {
// This is a barevalue (not in the form x=y), so look for a barevalue-accepting parameter
var bp string
bp, err = getBareParam(commandType)
if err != nil {
return fmt.Errorf("config error: %s", err)
}
f := accumulator.obj.FieldByName(bp)
if !f.CanSet() {
return fmt.Errorf("field %s is not settable (maybe private)", bp)
}
err = setValue(&f, sarg[0])
if err != nil {
return fmt.Errorf("error setting config value for field %s: %s", bp, err)
}
accumulator.fieldsSet = append(accumulator.fieldsSet, bp)
delete(requiredParams, strings.ToLower(bp))
} else if len(sarg) == 2 {
// This is a key/value pair, so look for a parameter matching the key
lcname := strings.ToLower(sarg[0])
var f *reflect.Value
f, err = getFieldByName(&accumulator.obj, lcname)
if err != nil {
return fmt.Errorf("config error: %s", err)
}
if !f.CanSet() {
return fmt.Errorf("field %s is not settable (maybe private)", lcname)
}
err = setValue(f, sarg[1])
if err != nil {
return fmt.Errorf("error setting config value for field %s: %s", lcname, err)
}
accumulator.fieldsSet = append(accumulator.fieldsSet, lcname)
delete(requiredParams, lcname)
}
}
}
if commandType != nil && accumulator != nil {
// If we were accumulating an object, store it now since we're done
err = checkRequiredParams(requiredParams)
if err != nil {
return fmt.Errorf("error in %s: %s", accumulator.arg, err)
}
activeObjs = append(activeObjs, accumulator)
}
// Enforce exclusive objects
haveExclusive := false
exclusiveName := ""
for _, ao := range activeObjs {
found := false
for j := range cl.configTypes {
ct := cl.configTypes[j]
if ao.obj.Type() == ct.objType {
if ct.exclusive {
haveExclusive = true
exclusiveName = ct.name
}
found = true
break
}
}
if !found {
return fmt.Errorf("type %s not found", ao.obj.Type().String())
}
if haveExclusive {
break
}
}
if haveExclusive && len(activeObjs) > 1 {
return fmt.Errorf("cannot specify any other options with %s", exclusiveName)
}
// Add missing required singletons
if !haveExclusive {
for _, ct := range cl.configTypes {
if ct.singleton && ct.required {
haveThis := false
for j := range activeObjs {
ao := activeObjs[j]
if ao.obj.Type() == ct.objType {
haveThis = true
break
}
}
if !haveThis {
a := newCOI()
a.obj = reflect.New(ct.objType).Elem()
a.arg = fmt.Sprintf("implicit %s", ct.name)
var reqs map[string]struct{}
reqs, err = buildRequiredParams(ct.objType)
if err != nil {
return err
}
err = checkRequiredParams(reqs)
if err != nil {
return fmt.Errorf("error in %s: %s", a.arg, err)
}
activeObjs = append(activeObjs, a)