-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoptionparser.go
456 lines (426 loc) · 12.3 KB
/
optionparser.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
// Package optionparser is a library for defining and parsing command line
// options. It aims to provide a natural language interface for defining short
// and long parameters and mandatory and optional arguments. It provides the
// user for nice output formatting on the built in method '--help'.
package optionparser
import (
"fmt"
"os"
"regexp"
"strings"
)
// A command is a non-dash option (with a helptext)
type command struct {
name string
helptext string
}
// OptionParser contains the methods to parse options and the settings to
// influence the output of --help. Set the Banner and Coda for usage info, set
// Start and Stop for output of the long description text.
type OptionParser struct {
Extra []string
Banner string
Coda string
Start int
Stop int
options []*allowedOptions
short map[string]*allowedOptions
long map[string]*allowedOptions
commands []command
}
type argumentDescription struct {
argument string
param string
optional bool
short bool
negate bool
}
type allowedOptions struct {
optional bool
param string
short string
long string
boolParameter bool
function func(string)
functionNoArgs func()
boolvalue *bool
stringvalue *string
stringmap map[string]string
stringslice *[]string
helptext string
}
var (
isOptionRe = regexp.MustCompile("^-.+")
doubleDashRe = regexp.MustCompile("^--")
singleDashRe = regexp.MustCompile("^-[^-]")
spaceOrEqualRe = regexp.MustCompile("[ =]")
)
// Return true if s starts with a dash ('-s' for example)
func isOption(s string) bool {
return isOptionRe.MatchString(s)
}
func wordwrap(s string, wd int) []string {
// if the string is shorter than the width, we can just return it
if len(s) <= wd {
return []string{s}
}
// Otherwise, we return the first part
// split at the last occurrence of space before wd
stop := strings.LastIndex(s[0:wd], " ")
// no space found in the next wd characters, impossible to split
if stop < 0 {
stop = strings.Index(s, " ")
if stop < 0 { // no space found in the remaining characters
return []string{s}
}
}
a := []string{s[0:stop]}
j := wordwrap(s[stop+1:], wd)
return append(a, j...)
}
// Analyze the given argument such as '-s' or 'foo=bar' and
// return an argumentDescription
func splitOn(arg string) *argumentDescription {
var (
argument string
param string
optional bool
short bool
negate bool
)
if doubleDashRe.MatchString(arg) {
short = false
} else if singleDashRe.MatchString(arg) {
short = true
} else {
panic("can't happen")
}
var init int
if short {
init = 1
} else {
init = 2
}
if len(arg) > init+2 {
if arg[init:init+3] == "no-" {
negate = true
init = init + 3
}
}
loc := spaceOrEqualRe.FindStringIndex(arg)
if len(loc) == 0 {
// no optional parameter, we know everything we need to know
return &argumentDescription{
argument: arg[init:],
optional: false,
short: short,
negate: negate,
}
}
// Now we know that the option requires an argument, it could be optional
argument = arg[init:loc[0]]
pos := loc[1]
length := len(arg)
if arg[loc[1]:loc[1]+1] == "[" {
pos++
length--
optional = true
} else {
optional = false
}
param = arg[pos:length]
a := argumentDescription{
argument,
param,
optional,
short,
negate,
}
return &a
}
// prints the nice help output
func formatAndOutput(start int, stop int, dashShort string, short string, comma string, dashLong string, long string, lines []string) {
if long == "" && len(short) > 2 {
formatString := fmt.Sprintf("%%-1s%%-%d.%ds %%s\n", start-3, stop-3)
// the formatString now looks like this: "%-1s%-2s%1s %-2s%-22.71s %s"
fmt.Printf(formatString, dashShort, short, lines[0])
} else {
formatString := fmt.Sprintf("%%-1s%%-1s%%1s %%-2s%%-%d.%ds %%s\n", start-8, stop-8)
// the formatString now looks like this: "%-1s%-2s%1s %-2s%-22.71s %s"
fmt.Printf(formatString, dashShort, short, comma, dashLong, long, lines[0])
}
if len(lines) > 0 {
formatString := fmt.Sprintf("%%%ds%%s\n", start-1)
for i := 1; i < len(lines); i++ {
fmt.Printf(formatString, " ", lines[i])
}
}
}
func set(obj *allowedOptions, hasNoPrefix bool, param string) {
if obj.function != nil {
obj.function(param)
}
if obj.stringvalue != nil {
*obj.stringvalue = param
}
if obj.stringmap != nil {
var name string
var value string
switch {
case obj.long != "":
name = obj.long
case obj.short != "":
name = obj.short
}
// return error if no name given
if param != "" {
value = param
} else {
if hasNoPrefix {
value = "false"
} else {
value = "true"
}
}
obj.stringmap[name] = value
}
if obj.stringslice != nil {
eachParam := strings.Split(param, ",")
*obj.stringslice = append(*obj.stringslice, eachParam...)
}
if obj.functionNoArgs != nil {
obj.functionNoArgs()
}
if obj.boolvalue != nil {
if hasNoPrefix {
*obj.boolvalue = false
} else {
*obj.boolvalue = true
}
}
}
// Command defines optional arguments to the command line. These are written in
// a separate section called 'Commands' on --help.
func (op *OptionParser) Command(cmd string, helptext string) {
cmds := command{cmd, helptext}
op.commands = append(op.commands, cmds)
}
// On defines arguments and parameters. Each argument is one of:
// - a short option, such as "-x",
// - a long option, such as "--extra",
// - a long option with an argument such as "--extra FOO" (or "--extra=FOO") for a mandatory argument,
// - a long option with an argument in brackets, e.g. "--extra [FOO]" for a parameter with optional argument,
// - a string (not starting with "-") used for the parameter description, e.g. "This parameter does this and that",
// - a string variable in the form of &str that is used for saving the result of the argument,
// - a variable of type map[string]string which is used to store the result (the parameter name is the key, the value is either the string true or the argument given on the command line)
// - a variable of type *[]string which gets a comma separated list of values,
// - a bool variable (in the form &bool) to hold a boolean value, or
// - a function in the form of func() or in the form of func(string) which gets called if the command line parameter is found.
//
// On panics if the user supplies is an type in its argument other the ones
// given above.
//
// op := optionparser.NewOptionParser()
// op.On("-a", "--func", "call myfunc", myfunc)
// op.On("--bstring FOO", "set string to FOO", &somestring)
// op.On("-c", "set boolean option (try -no-c)", options)
// op.On("-d", "--dlong VAL", "set option", options)
// op.On("-e", "--elong [VAL]", "set option with optional parameter", options)
// op.On("-f", "boolean option", &truefalse)
// op.On("-g VALUES", "give multiple values", &stringslice)
//
// and running the program with --help gives the following output:
//
// go run main.go --help
// Usage: [parameter] command
// -h, --help Show this help
// -a, --func call myfunc
// --bstring=FOO set string to FOO
// -c set boolean option (try -no-c)
// -d, --dlong=VAL set option
// -e, --elong[=VAL] set option with optional parameter
// -f boolean option
// -g=VALUES give multiple values
func (op *OptionParser) On(a ...interface{}) {
option := new(allowedOptions)
op.options = append(op.options, option)
for _, i := range a {
switch x := i.(type) {
case string:
// a short option, a long option or a help text
if isOption(x) {
ret := splitOn(x)
if ret.short {
// short argument ('-s')
op.short[ret.argument] = option
option.short = ret.argument
} else {
// long argument ('--something')
op.long[ret.argument] = option
option.long = ret.argument
}
if ret.optional {
option.optional = true
}
if ret.param != "" {
option.param = ret.param
}
if ret.negate {
option.boolParameter = true
}
} else {
// a string, probably the help text
option.helptext = x
}
case func(string):
option.function = x
case func():
option.functionNoArgs = x
case *bool:
option.boolvalue = x
case *string:
option.stringvalue = x
case map[string]string:
option.stringmap = x
case *[]string:
option.stringslice = x
default:
panic(fmt.Sprintf("Unknown parameter type: %#T\n", x))
}
}
}
// ParseFrom takes a slice of string arguments and interprets them. If it finds
// an unknown option or a missing mandatory argument, it returns an error.
func (op *OptionParser) ParseFrom(args []string) error {
i := 1
for i < len(args) {
switch {
// Users can pass -- to mark the end of flag parsing. This
// check must come first since isOption will treat -- as
// a malformed option.
case args[i] == "--":
op.Extra = append(op.Extra, args[i+1:]...)
return nil
case isOption(args[i]):
ret := splitOn(args[i])
var option *allowedOptions
if ret.short {
option = op.short[ret.argument]
} else {
option = op.long[ret.argument]
}
if option == nil {
return fmt.Errorf("unknown option %s", ret.argument)
}
// the parameter in ret.param is only set by `splitOn()` when used with
// the equal sign: "--foo=bar". If the user gives a parameter with "--foo bar"
// it is not in ret.param. So we look at the next thing in our args array
// and if its not a parameter (starting with `-`), we take this as the perhaps
// optional parameter
if ret.param == "" && i < len(args)-1 && !isOption(args[i+1]) {
// next could be a parameter
ret.param = args[i+1]
// delete this possible parameter from the args list
args = append(args[:i+1], args[i+2:]...)
}
if ret.param != "" {
if option.param != "" {
// OK, we've got a parameter and we expect one
set(option, ret.negate, ret.param)
} else {
// we've got a parameter but didn't expect one,
// so let's push it onto the stack
op.Extra = append(op.Extra, ret.param)
set(option, ret.negate, "")
}
} else {
// no parameter found
if option.param != "" {
// parameter expected
if !option.optional {
// No parameter found but expected
return fmt.Errorf("parameter expected but none given %s", ret.argument)
}
}
set(option, ret.negate, "")
}
default:
// not an option, we push it onto the extra array
op.Extra = append(op.Extra, args[i])
}
i++
}
return nil
}
// Parse takes the command line arguments as found in os.Args and interprets
// them. If it finds an unknown option or a missing mandatory argument, it
// returns an error.
func (op *OptionParser) Parse() error {
return op.ParseFrom(os.Args)
}
// Help prints help text generated from the "On" commands
func (op *OptionParser) Help() {
fmt.Println(op.Banner)
wd := op.Stop - op.Start
for _, o := range op.options {
short := o.short
long := o.long
if o.boolParameter {
long = "[no-]" + o.long
}
if o.long != "" {
if o.param != "" {
if o.optional {
long = fmt.Sprintf("%s[=%s]", o.long, o.param)
} else {
long = fmt.Sprintf("%s=%s", o.long, o.param)
}
}
} else {
// short
if o.param != "" {
if o.optional {
short = fmt.Sprintf("%s[=%s]", o.short, o.param)
} else {
short = fmt.Sprintf("%s=%s", o.short, o.param)
}
}
}
dashShort := "-"
dashLong := "--"
comma := ","
if short == "" {
dashShort = ""
comma = ""
}
if long == "" {
dashLong = ""
comma = ""
}
lines := wordwrap(o.helptext, wd)
formatAndOutput(op.Start, op.Stop, dashShort, short, comma, dashLong, long, lines)
}
if len(op.commands) > 0 {
fmt.Println("\nCommands")
for _, cmd := range op.commands {
lines := wordwrap(cmd.helptext, wd)
formatAndOutput(op.Start, op.Stop, "", "", "", "", cmd.name, lines)
}
}
if op.Coda != "" {
fmt.Println(op.Coda)
}
}
// NewOptionParser initializes the OptionParser struct with sane settings for
// Banner, Start and Stop and adds a "-h", "--help" option for convenience.
func NewOptionParser() *OptionParser {
a := &OptionParser{}
a.Extra = []string{}
a.Banner = "Usage: [parameter] command"
a.Start = 30
a.Stop = 79
a.short = map[string]*allowedOptions{}
a.long = map[string]*allowedOptions{}
a.On("-h", "--help", "Show this help", func() { a.Help(); os.Exit(0) })
return a
}