forked from jawher/mow.cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.go
More file actions
424 lines (363 loc) · 10 KB
/
commands.go
File metadata and controls
424 lines (363 loc) · 10 KB
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
package cli
import (
"bytes"
"flag"
"fmt"
"strings"
"text/tabwriter"
)
/*
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 error handling strategy
ErrorHandling flag.ErrorHandling
init CmdInitializer
name string
desc string
commands []*Cmd
options []*opt
optionsIdx map[string]*opt
args []*arg
argsIdx map[string]*arg
parents []string
fsm *state
}
/*
BoolParam represents a Bool option or argument
*/
type BoolParam interface{}
/*
StringParam represents a String option or argument
*/
type StringParam interface{}
/*
IntParam represents an Int option or argument
*/
type IntParam interface{}
/*
StringsParam represents a string slice option or argument
*/
type StringsParam interface{}
/*
IntsParam represents an int slice option or argument
*/
type IntsParam interface{}
/*
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) {
c.commands = append(c.commands, &Cmd{
ErrorHandling: c.ErrorHandling,
name: name,
desc: desc,
init: init,
commands: []*Cmd{},
options: []*opt{},
optionsIdx: map[string]*opt{},
args: []*arg{},
argsIdx: map[string]*arg{},
})
}
/*
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 {
switch x := p.(type) {
case BoolOpt:
return c.mkOpt(opt{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*bool)
case BoolArg:
return c.mkArg(arg{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*bool)
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 {
switch x := p.(type) {
case StringOpt:
return c.mkOpt(opt{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*string)
case StringArg:
return c.mkArg(arg{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*string)
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 {
switch x := p.(type) {
case IntOpt:
return c.mkOpt(opt{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*int)
case IntArg:
return c.mkArg(arg{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*int)
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 {
switch x := p.(type) {
case StringsOpt:
return c.mkOpt(opt{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*[]string)
case StringsArg:
return c.mkArg(arg{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*[]string)
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 {
switch x := p.(type) {
case IntsOpt:
return c.mkOpt(opt{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*[]int)
case IntsArg:
return c.mkArg(arg{name: x.Name, desc: x.Desc, envVar: x.EnvVar, hideValue: x.HideValue}, x.Value).(*[]int)
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 + " "
}
}
fsm, err := uParse(c)
if err != nil {
return err
}
c.fsm = fsm
return nil
}
func (c *Cmd) onError(err error) {
if err != nil {
switch c.ErrorHandling {
case flag.ExitOnError:
exiter(2)
case flag.PanicOnError:
panic(err)
}
} else {
if c.ErrorHandling == flag.ExitOnError {
exiter(2)
}
}
}
/*
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() {
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")
if len(c.desc) > 0 {
fmt.Fprintf(stdErr, "%s\n", c.desc)
}
w := tabwriter.NewWriter(stdErr, 15, 1, 3, ' ', 0)
if len(c.args) > 0 {
fmt.Fprintf(stdErr, "\nArguments:\n")
for _, arg := range c.args {
desc := c.formatDescription(arg.desc, arg.envVar)
value := c.formatArgValue(arg)
fmt.Fprintf(w, " %s%s\t%s\n", arg.name, value, desc)
}
w.Flush()
}
if len(c.options) > 0 {
fmt.Fprintf(stdErr, "\nOptions:\n")
for _, opt := range c.options {
desc := c.formatDescription(opt.desc, opt.envVar)
value := c.formatOptValue(opt)
fmt.Fprintf(w, " %s%s\t%s\n", strings.Join(opt.names, ", "), value, desc)
}
w.Flush()
}
if len(c.commands) > 0 {
fmt.Fprintf(stdErr, "\nCommands:\n")
for _, c := range c.commands {
fmt.Fprintf(w, " %s\t%s\n", c.name, c.desc)
}
w.Flush()
}
if len(c.commands) > 0 {
fmt.Fprintf(stdErr, "\nRun '%s COMMAND --help' for more information on a command.\n", path)
}
}
func (c *Cmd) formatArgValue(arg *arg) string {
if arg.hideValue {
return " "
}
return "=" + arg.helpFormatter(arg.get())
}
func (c *Cmd) formatOptValue(opt *opt) string {
if opt.hideValue {
return " "
}
return "=" + opt.helpFormatter(opt.get())
}
func (c *Cmd) formatDescription(desc, envVar string) string {
var b bytes.Buffer
b.WriteString(desc)
if len(envVar) > 0 {
b.WriteString(" (")
sep := ""
for _, envVal := range strings.Split(envVar, " ") {
b.WriteString(fmt.Sprintf("%s$%s", sep, envVal))
sep = " "
}
b.WriteString(")")
}
return strings.TrimSpace(b.String())
}
func (c *Cmd) parse(args []string, entry, inFlow, outFlow *step) error {
if c.helpRequested(args) {
c.PrintHelp()
c.onError(nil)
return nil
}
nargsLen := c.getOptsAndArgs(args)
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 := &step{
do: c.Before,
error: outFlow,
desc: fmt.Sprintf("%s.Before", c.name),
}
inFlow.success = newInFlow
newOutFlow := &step{
do: c.After,
success: outFlow,
error: outFlow,
desc: fmt.Sprintf("%s.After", c.name),
}
args = args[nargsLen:]
if len(args) == 0 {
if c.Action != nil {
newInFlow.success = &step{
do: c.Action,
success: newOutFlow,
error: newOutFlow,
desc: fmt.Sprintf("%s.Action", c.name),
}
entry.run(nil)
return nil
}
c.PrintHelp()
c.onError(nil)
return nil
}
arg := args[0]
for _, sub := range c.commands {
if arg == sub.name {
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) isArgSet(args []string, searchArgs []string) bool {
for _, arg := range args {
for _, sub := range c.commands {
if arg == sub.name {
return false
}
}
for _, searchArg := range searchArgs {
if arg == searchArg {
return true
}
}
}
return false
}
func (c *Cmd) helpRequested(args []string) bool {
return c.isArgSet(args, []string{"-h", "--help"})
}
func (c *Cmd) getOptsAndArgs(args []string) int {
consumed := 0
for _, arg := range args {
for _, sub := range c.commands {
if arg == sub.name {
return consumed
}
}
consumed++
}
return consumed
}