-
Notifications
You must be signed in to change notification settings - Fork 55
/
commands.go
823 lines (694 loc) · 22 KB
/
commands.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
package cli
import (
"flag"
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/jawher/mow.cli/internal/container"
"github.com/jawher/mow.cli/internal/flow"
"github.com/jawher/mow.cli/internal/fsm"
"github.com/jawher/mow.cli/internal/lexer"
"github.com/jawher/mow.cli/internal/parser"
)
/*
Cmd represents a command (or sub command) in a CLI application. It should be constructed
by calling Command() on an app to create a top level command or by calling Command() on another
command to create a sub command
*/
type Cmd struct {
// The code to execute when this command is matched
Action func()
// The code to execute before this command or any of its children is matched
Before func()
// The code to execute after this command or any of its children is matched
After func()
// The command options and arguments
Spec string
// The command long description to be shown when help is requested
LongDesc string
// Hide this command in the help messages
Hidden bool
// The command error handling strategy
ErrorHandling flag.ErrorHandling
init CmdInitializer
name string
aliases []string
desc string
commands []*Cmd
options []*container.Container
optionsIdx map[string]*container.Container
args []*container.Container
argsIdx map[string]*container.Container
parents []string
fsm *fsm.State
}
/*
BoolParam represents a Bool option or argument
*/
type BoolParam interface {
value(into *bool) (flag.Value, *bool)
}
/*
StringParam represents a String option or argument
*/
type StringParam interface {
value(into *string) (flag.Value, *string)
}
/*
IntParam represents an Int option or argument
*/
type IntParam interface {
value(into *int) (flag.Value, *int)
}
/*
Float64Param represents an Float64 option or argument
*/
type Float64Param interface {
value(into *float64) (flag.Value, *float64)
}
/*
StringsParam represents a string slice option or argument
*/
type StringsParam interface {
value(into *[]string) (flag.Value, *[]string)
}
/*
IntsParam represents an float64 slice option or argument
*/
type IntsParam interface {
value(into *[]int) (flag.Value, *[]int)
}
/*
Floats64Param represents an float64 slice option or argument
*/
type Floats64Param interface {
value(into *[]float64) (flag.Value, *[]float64)
}
/*
VarParam represents an custom option or argument where the type and format are controlled by the developer
*/
type VarParam interface {
value() flag.Value
}
/*
CmdInitializer is a function that configures a command by adding options, arguments, a spec, sub commands and the code
to execute when the command is called
*/
type CmdInitializer func(*Cmd)
/*
Command adds a new (sub) command to c where name is the command name (what you type in the console),
description is what would be shown in the help messages, e.g.:
Usage: git [OPTIONS] COMMAND [arg...]
Commands:
$name $desc
the last argument, init, is a function that will be called by mow.cli to further configure the created
(sub) command, e.g. to add options, arguments and the code to execute
*/
func (c *Cmd) Command(name, desc string, init CmdInitializer) {
aliases := strings.Fields(name)
c.commands = append(c.commands, &Cmd{
ErrorHandling: c.ErrorHandling,
name: aliases[0],
aliases: aliases,
desc: desc,
init: init,
commands: []*Cmd{},
options: []*container.Container{},
optionsIdx: map[string]*container.Container{},
args: []*container.Container{},
argsIdx: map[string]*container.Container{},
})
}
/*
Bool can be used to add a bool option or argument to a command.
It accepts either a BoolOpt or a BoolArg struct.
The result should be stored in a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Bool(p BoolParam) *bool {
value, into := p.value(nil)
switch x := p.(type) {
case BoolOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case BoolArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
return into
}
/*
BoolPtr can be used to add a bool option or argument to a command.
It accepts either a pointer to a bool var and a BoolOpt or a BoolArg struct.
The into parameter points to a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) BoolPtr(into *bool, p BoolParam) {
value, _ := p.value(into)
switch x := p.(type) {
case BoolOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case BoolArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
/*
String can be used to add a string option or argument to a command.
It accepts either a StringOpt or a StringArg struct.
The result should be stored in a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) String(p StringParam) *string {
value, into := p.value(nil)
switch x := p.(type) {
case StringOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case StringArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
return into
}
/*
StringPtr can be used to add a string option or argument to a command.
It accepts either a pointer to a string var and a StringOpt or a StringArg struct.
The into parameter points to a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) StringPtr(into *string, p StringParam) {
value, _ := p.value(into)
switch x := p.(type) {
case StringOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case StringArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
/*
Int can be used to add an int option or argument to a command.
It accepts either a IntOpt or a IntArg struct.
The result should be stored in a variable (a pointer to an int) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Int(p IntParam) *int {
value, into := p.value(nil)
switch x := p.(type) {
case IntOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case IntArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
return into
}
/*
IntPtr can be used to add a int option or argument to a command.
It accepts either a pointer to a int var and a IntOpt or a IntArg struct.
The into parameter points to a variable (a pointer to a int) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) IntPtr(into *int, p IntParam) {
value, _ := p.value(into)
switch x := p.(type) {
case IntOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case IntArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
/*
Float64 can be used to add a float64 option or argument to a command.
It accepts either a Float64Opt or a Float64Arg struct.
The result should be stored in a variable (a pointer to a float64) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Float64(p Float64Param) *float64 {
value, into := p.value(nil)
switch x := p.(type) {
case Float64Opt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case Float64Arg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
return into
}
/*
Float64Ptr can be used to add a float64 option or argument to a command.
It accepts either a pointer to a float64 var and a Float64Opt or a Float64Arg struct.
The into parameter points to a variable (a pointer to a float64) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Float64Ptr(into *float64, p Float64Param) {
value, _ := p.value(into)
switch x := p.(type) {
case Float64Opt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case Float64Arg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
/*
Strings can be used to add a string slice option or argument to a command.
It accepts either a StringsOpt or a StringsArg struct.
The result should be stored in a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Strings(p StringsParam) *[]string {
value, into := p.value(nil)
switch x := p.(type) {
case StringsOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case StringsArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
return into
}
/*
StringsPtr can be used to add a string slice option or argument to a command.
It accepts either a pointer to a string slice var and a StringsOpt or a StringsArg struct.
The into parameter points to a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) StringsPtr(into *[]string, p StringsParam) {
value, _ := p.value(into)
switch x := p.(type) {
case StringsOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case StringsArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
/*
Ints can be used to add an int slice option or argument to a command.
It accepts either a IntsOpt or a IntsArg struct.
The result should be stored in a variable (a pointer to an int slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Ints(p IntsParam) *[]int {
value, into := p.value(nil)
switch x := p.(type) {
case IntsOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case IntsArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
return into
}
/*
IntsPtr can be used to add a int slice option or argument to a command.
It accepts either a pointer to a int slice var and a IntsOpt or a IntsArg struct.
The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) IntsPtr(into *[]int, p IntsParam) {
value, _ := p.value(into)
switch x := p.(type) {
case IntsOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case IntsArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
/*
Floats64 can be used to add an float64 slice option or argument to a command.
It accepts either a Floats64Opt or a Floats64Arg struct.
The result should be stored in a variable (a pointer to an float64 slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Floats64(p Floats64Param) *[]float64 {
value, into := p.value(nil)
switch x := p.(type) {
case Floats64Opt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case Floats64Arg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
return into
}
/*
Floats64Ptr can be used to add a float64 slice option or argument to a command.
It accepts either a pointer to a float64 slice var and a Floats64Opt or a Floats64Arg struct.
The into parameter points to a variable (a pointer to a float64 slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) Floats64Ptr(into *[]float64, p Floats64Param) {
value, _ := p.value(into)
switch x := p.(type) {
case Floats64Opt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
case Floats64Arg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: value, ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
/*
Var can be used to add a custom option or argument to a command.
It accepts either a VarOpt or a VarArg struct.
As opposed to the other built-in types, this function does not return a pointer the the value.
Instead, the VarOpt or VarOptArg structs hold the said value.
*/
func (c *Cmd) Var(p VarParam) {
switch x := p.(type) {
case VarOpt:
c.mkOpt(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: p.value(), ValueSetByUser: x.SetByUser})
case VarArg:
c.mkArg(container.Container{Name: x.Name, Desc: x.Desc, EnvVar: x.EnvVar, HideValue: x.HideValue, Value: p.value(), ValueSetByUser: x.SetByUser})
default:
panic(fmt.Sprintf("Unhandled param %v", p))
}
}
func (c *Cmd) doInit() error {
if c.init != nil {
c.init(c)
}
parents := append(c.parents, c.name)
for _, sub := range c.commands {
sub.parents = parents
}
if len(c.Spec) == 0 {
if len(c.options) > 0 {
c.Spec = "[OPTIONS] "
}
for _, arg := range c.args {
c.Spec += arg.Name + " "
}
}
tokens, err := lexer.Tokenize(c.Spec)
if err != nil {
return err
}
params := parser.Params{
Spec: c.Spec,
Options: c.options,
OptionsIdx: c.optionsIdx,
Args: c.args,
ArgsIdx: c.argsIdx,
}
s, err := parser.Parse(tokens, params)
if err != nil {
return err
}
c.fsm = s
return nil
}
func (c *Cmd) onError(err error) {
if err == errHelpRequested || err == errVersionRequested {
if c.ErrorHandling == flag.ExitOnError {
exiter(0)
}
return
}
switch c.ErrorHandling {
case flag.ExitOnError:
exiter(2)
case flag.PanicOnError:
panic(err)
}
}
/*
PrintHelp prints the command's help message.
In most cases the library users won't need to call this method, unless
a more complex validation is needed
*/
func (c *Cmd) PrintHelp() {
c.printHelp(false)
}
/*
PrintLongHelp prints the command's help message using the command long description if specified.
In most cases the library users won't need to call this method, unless
a more complex validation is needed
*/
func (c *Cmd) PrintLongHelp() {
c.printHelp(true)
}
func (c *Cmd) printHelp(longDesc bool) {
full := append(c.parents, c.name)
path := strings.Join(full, " ")
fmt.Fprintf(stdErr, "\nUsage: %s", path)
spec := strings.TrimSpace(c.Spec)
if len(spec) > 0 {
fmt.Fprintf(stdErr, " %s", spec)
}
if len(c.commands) > 0 {
fmt.Fprint(stdErr, " COMMAND [arg...]")
}
fmt.Fprint(stdErr, "\n\n")
desc := c.desc
if longDesc && len(c.LongDesc) > 0 {
desc = c.LongDesc
}
if len(desc) > 0 {
fmt.Fprintf(stdErr, "%s\n", desc)
}
w := tabwriter.NewWriter(stdErr, 15, 1, 3, ' ', 0)
if len(c.args) > 0 {
fmt.Fprint(w, "\t\nArguments:\t\n")
for _, arg := range c.args {
var (
env = formatEnvVarsForHelp(arg.EnvVar)
value = formatValueForHelp(arg.HideValue, arg.DefaultValue)
)
printTabbedRow(w, arg.Name, joinStrings(arg.Desc, env, value))
}
}
if len(c.options) > 0 {
fmt.Fprint(w, "\t\nOptions:\t\n")
for _, opt := range c.options {
var (
optNames = formatOptNamesForHelp(opt)
env = formatEnvVarsForHelp(opt.EnvVar)
value = formatValueForHelp(opt.HideValue, opt.DefaultValue)
)
printTabbedRow(w, optNames, joinStrings(opt.Desc, env, value))
}
}
commands := make([]*Cmd, 0, len(c.commands))
for _, c := range c.commands {
if err := c.doInit(); err != nil {
panic(err)
}
if c.Hidden {
continue
}
commands = append(commands, c)
}
if len(commands) > 0 {
fmt.Fprint(w, "\t\nCommands:\t\n")
for _, c := range commands {
fmt.Fprintf(w, " %s\t%s\n", strings.Join(c.aliases, ", "), c.desc)
}
}
if len(commands) > 0 {
fmt.Fprintf(w, "\t\nRun '%s COMMAND --help' for more information on a command.\n", path)
}
w.Flush()
}
func formatOptNamesForHelp(o *container.Container) string {
short, long := "", ""
for _, n := range o.Names {
if len(n) == 2 && short == "" {
short = n
}
if len(n) > 2 && long == "" {
long = n
}
}
switch {
case short != "" && long != "":
return fmt.Sprintf("%s, %s", short, long)
case short != "":
return short
case long != "":
// 2 spaces instead of the short option (-x), one space for the comma (,) and one space for the after comma blank
return fmt.Sprintf(" %s", long)
default:
return ""
}
}
func formatValueForHelp(hide bool, v string) string {
if hide {
return ""
}
if v == "" {
return ""
}
return fmt.Sprintf("(default %s)", v)
}
func formatEnvVarsForHelp(envVars string) string {
if strings.TrimSpace(envVars) == "" {
return ""
}
vars := strings.Fields(envVars)
res := "(env"
sep := " "
for i, v := range vars {
if i > 0 {
sep = ", "
}
res += fmt.Sprintf("%s$%s", sep, v)
}
res += ")"
return res
}
func (c *Cmd) parse(args []string, entry, inFlow, outFlow *flow.Step) error {
helpIndex := c.helpIndex(args)
nargsLen := c.getOptsAndArgs(args)
if helpIndex >= 0 && helpIndex < nargsLen {
c.PrintLongHelp()
c.onError(errHelpRequested)
return nil
}
// help was requested, but not for this command, skip the validation
if helpIndex >= 0 {
arg := args[nargsLen]
for _, sub := range c.commands {
if !sub.isAlias(arg) {
continue
}
if err := sub.doInit(); err != nil {
panic(err)
}
return sub.parse(args[nargsLen+1:], entry, nil, nil)
}
// impossible case
panic("wut")
}
if err := c.fsm.Parse(args[:nargsLen]); err != nil {
fmt.Fprintf(stdErr, "Error: %s\n", err.Error())
c.PrintHelp()
c.onError(err)
return err
}
newInFlow := &flow.Step{
Do: c.Before,
Error: outFlow,
Desc: fmt.Sprintf("%s.Before", c.name),
Exiter: exiter,
}
inFlow.Success = newInFlow
newOutFlow := &flow.Step{
Do: c.After,
Success: outFlow,
Error: outFlow,
Desc: fmt.Sprintf("%s.After", c.name),
Exiter: exiter,
}
args = args[nargsLen:]
if len(args) == 0 {
if c.Action != nil {
newInFlow.Success = &flow.Step{
Do: c.Action,
Success: newOutFlow,
Error: newOutFlow,
Desc: fmt.Sprintf("%s.Action", c.name),
Exiter: exiter,
}
entry.Run(nil)
return nil
}
c.PrintHelp()
c.onError(nil)
return nil
}
arg := args[0]
for _, sub := range c.commands {
if sub.isAlias(arg) {
if err := sub.doInit(); err != nil {
panic(err)
}
return sub.parse(args[1:], entry, newInFlow, newOutFlow)
}
}
var err error
switch {
case strings.HasPrefix(arg, "-"):
err = fmt.Errorf("Error: illegal option %s", arg)
fmt.Fprintln(stdErr, err.Error())
default:
err = fmt.Errorf("Error: illegal input %s", arg)
fmt.Fprintln(stdErr, err.Error())
}
c.PrintHelp()
c.onError(err)
return err
}
func (c *Cmd) helpIndex(args []string) int {
searchSet := []string{"-h", "--help"}
for i, arg := range args {
if arg == "--" {
return -1
}
for _, searchArg := range searchSet {
if arg == searchArg {
return i
}
}
}
return -1
}
func (c *Cmd) isFirstItemAmong(args []string, searchSet []string) bool {
if len(args) == 0 {
return false
}
arg := args[0]
for _, searchArg := range searchSet {
if arg == searchArg {
return true
}
}
return false
}
func (c *Cmd) getOptsAndArgs(args []string) int {
consumed := 0
for _, arg := range args {
for _, sub := range c.commands {
if sub.isAlias(arg) {
return consumed
}
}
consumed++
}
return consumed
}
func (c *Cmd) isAlias(arg string) bool {
for _, alias := range c.aliases {
if arg == alias {
return true
}
}
return false
}
func joinStrings(parts ...string) string {
res := ""
for _, part := range parts {
s := strings.TrimSpace(part)
if s == "" {
continue
}
if res != "" {
res += " "
}
res += part
}
return res
}
func printTabbedRow(w io.Writer, s1 string, s2 string) {
lines := strings.Split(s2, "\n")
fmt.Fprintf(w, " %s\t%s\n", s1, strings.TrimSpace(lines[0]))
if len(lines) == 1 {
return
}
for _, line := range lines[1:] {
fmt.Fprintf(w, " %s\t%s\n", "", strings.TrimSpace(line))
}
}