forked from ghetzel/argonaut
/
argonaut.go
436 lines (364 loc) · 11.8 KB
/
argonaut.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
package argonaut
/*
Argonaut is a library that makes working with complex command line utilities simpler. Instead of
using complex application logic and string slices for building up command line invocations, you can
model shell commands using Golang structs, then using Argonaut, marshal those structs into valid
strings that can be used to shell out.
*/
import (
"fmt"
"os/exec"
"reflect"
"strings"
"github.com/fatih/structs"
"github.com/PerformLine/go-stockutil/maputil"
"github.com/PerformLine/go-stockutil/sliceutil"
"github.com/PerformLine/go-stockutil/stringutil"
"github.com/PerformLine/go-stockutil/typeutil"
"github.com/PerformLine/go-stockutil/utils"
)
var DefaultArgumentDelimiter = ` `
var DefaultCommandWordSeparator = `-`
var DefaultArgumentKeyPartJoiner = `.`
var DefaultArgumentKeyValueJoiner = DefaultArgumentDelimiter
type CommandName string
type ArgName string
type argonautTag struct {
Options []string
Label string
SkipName bool
Required bool
Positional bool
LongOption bool
ForceShort bool
SuffixPrevious bool
Delimiters []string
MutuallyExclusiveWith []string
KeyPartJoiner string
Joiner string
}
func (self *argonautTag) DelimiterAt(i int) string {
if len(self.Delimiters) == 0 {
return DefaultArgumentDelimiter
} else if i >= len(self.Delimiters) {
return self.Delimiters[len(self.Delimiters)-1]
} else {
return self.Delimiters[i]
}
}
// Marshals a given struct into a shell-ready command line string.
func Marshal(v interface{}) ([]byte, error) {
if command, sep, err := generateCommand(v, true); err == nil {
return []byte(strings.Join(command, sep)), nil
} else {
return nil, err
}
}
// Parses a given struct and returns slice of strings that can be used with os/exec.
func Parse(v interface{}) ([]string, error) {
if command, _, err := generateCommand(v, true); err == nil {
return command, err
} else {
return nil, err
}
}
// Parses a given struct and returns slice of strings that can be used with os/exec. Will panic if
// an error occurs.
func MustParse(v interface{}) []string {
if command, err := Parse(v); err == nil {
return command
} else {
panic(err.Error())
}
}
// Parses the given value and returns a new *exec.Cmd instance
func Command(v interface{}) (*exec.Cmd, error) {
var cmd string
var args []string
if typeutil.IsEmpty(v) {
return nil, fmt.Errorf("Cannot parse empty argument into *exec.Cmd")
}
if typeutil.IsKind(v, reflect.Struct) {
if cmdargs, err := Parse(v); err == nil {
cmd = cmdargs[0]
args = cmdargs[1:]
} else {
return nil, err
}
} else if typeutil.IsKind(v, reflect.String) || typeutil.IsArray(v) {
cmdargs := sliceutil.Stringify(sliceutil.Sliceify(v))
if len(cmdargs) > 0 {
cmd = cmdargs[0]
args = cmdargs[1:]
} else {
return nil, fmt.Errorf("Cannot parse empty argument into *exec.Cmd")
}
} else {
return nil, fmt.Errorf("Unexpected type: need struct, string, or []string, got: %T", v)
}
return exec.Command(cmd, args...), nil
}
// Parses the given value and returns a new *exec.Cmd instance. Will panic if an error occurs.
func MustCommand(v interface{}) *exec.Cmd {
if command, err := Command(v); err == nil {
return command
} else {
panic(err.Error())
}
}
func generateCommand(v interface{}, toplevel bool) ([]string, string, error) {
if !typeutil.IsKind(v, reflect.Struct) {
return nil, ``, fmt.Errorf("struct needed, got %T", v)
}
input := structs.New(v)
command := make([]string, 0)
if toplevel {
command = append(command, fmtCommandWord(input.Name()))
}
separator := DefaultArgumentDelimiter
defaults := argonautTag{
Delimiters: []string{DefaultArgumentDelimiter},
KeyPartJoiner: DefaultArgumentKeyPartJoiner,
Joiner: DefaultArgumentKeyValueJoiner,
}
for _, field := range input.Fields() {
if !field.IsExported() || field.Tag(`argonaut`) == `-` {
continue
}
if tag, err := parseTag(field.Tag(`argonaut`), &defaults); err == nil {
var primaryOpt string
// for marshaling purposes, the option name is determined as:
// - the first value of the tag, or, if that's empty...
// - the field name formatted to a common default
if len(tag.Options) > 0 && tag.Options[0] != `` {
primaryOpt = tag.Options[0]
} else {
primaryOpt = fmtCommandWord(field.Name())
}
var values []interface{}
utils.SliceEach(field.Value(), func(i int, value interface{}) error {
values = append(values, value)
return nil
}, reflect.Struct, reflect.Map)
// arrify and iterate through the field value
for _, value := range values {
// CommandName: specifies a named command and options for processing peer fields
// ---------------------------------------------------------------------------------
if _, ok := value.(CommandName); ok {
valueS := fmt.Sprintf("%v", value)
// specify how the final command should be joined together when marshalling
if len(tag.Delimiters) > 0 {
separator = tag.Delimiters[0]
}
// if these tags weren't explicitly set, then this is effectively a no-op
// if they were set, the defaults are updated here to reflect that
defaults.Delimiters = tag.Delimiters
defaults.Joiner = tag.Joiner
defaults.KeyPartJoiner = tag.KeyPartJoiner
if valueS != `` {
// prefer value of the field
command = []string{valueS}
} else if len(tag.Label) > 0 {
// fallback to label value
command = []string{tag.Label}
} else if primaryOpt != `` {
// fallback to tag value
command = []string{primaryOpt}
} else {
command = []string{fmtCommandWord(field.Name())}
}
} else if _, ok := value.(ArgName); ok {
// ArgName: specifies a named argument from within a nested struct
// ---------------------------------------------------------------------------------
var prefix string
if tag.ForceShort {
prefix = `-`
} else {
prefix = `--`
}
if len(tag.Label) > 0 {
// prefer label
command = append(command, prefix+tag.Label)
} else if primaryOpt != `` {
command = append(command, prefix+primaryOpt)
} else {
command = append(command, prefix+fmtCommandWord(field.Name()))
}
} else if typeutil.IsKind(value, reflect.Map) {
// Maps: get exploded into options
// ---------------------------------------------------------------------------------
if err := maputil.Walk(value, func(v interface{}, key []string, isLeaf bool) error {
if isLeaf {
var kv string
if tag.ForceShort {
kv += `-`
} else if tag.LongOption {
kv += `--`
}
// only non-nil values expand into [-]key=value arguments
if v != nil {
kv += strings.Join(key, tag.KeyPartJoiner)
if tag.Joiner == separator {
command = append(command, kv)
kv = ``
} else {
kv += tag.Joiner
}
kv += stringutil.MustString(v)
}
command = append(command, kv)
}
return nil
}); err != nil {
return nil, separator, err
}
} else if typeutil.IsKind(value, reflect.Struct) {
// Structs: recurses into this method
// ---------------------------------------------------------------------------------
if partial, psep, err := generateCommand(value, false); err == nil {
// if the separator used in the nested struct matches our own, just tack what
// came back onto our command stack,
//
// otherwise, join using the preferred separator and add it as one big blob
if psep == separator {
command = append(command, partial...)
} else {
command = append(command, strings.Join(partial, psep))
}
} else {
return nil, separator, err
}
} else if tag.SuffixPrevious {
// SuffixPrevious: modifies the last argument on the command stack with the current value
// ---------------------------------------------------------------------------------
if len(command) > 0 && (!typeutil.IsZero(value) || tag.Required) {
last := command[len(command)-1]
last += tag.DelimiterAt(0)
last += stringutil.MustString(value)
command[len(command)-1] = last
continue
}
} else if tag.Positional {
// Positional: puts whatever the value is into the command immediately
// ---------------------------------------------------------------------------------
command = append(command, sliceutil.Stringify(
sliceutil.Sliceify(value),
)...)
// Scalar Arguments: puts the field name in as the argument name
// boolean fields: go in as flags (false values are not added)
// everything else: if it has a value or is required, it is added
// ---------------------------------------------------------------------------------
} else {
argName := sliceutil.OrString(primaryOpt, stringutil.Underscore(field.Name()))
if field.Kind() == reflect.Bool {
if !typeutil.IsZero(value) {
command = opt(command, &tag, argName)
}
} else if value == nil {
continue
} else {
value = typeutil.ResolveValue(value)
if !typeutil.IsZero(value) || tag.Required {
command = opt(command, &tag, argName, sliceutil.Sliceify(value)...)
}
}
}
}
} else {
return nil, separator, err
}
}
return command, separator, nil
}
func fmtCommandWord(in string) string {
return strings.Replace(
stringutil.Underscore(in),
`_`,
DefaultCommandWordSeparator,
-1,
)
}
func opt(command []string, tag *argonautTag, optname string, values ...interface{}) []string {
argset := []string{}
prejoin := false
if !tag.SkipName {
if tag.LongOption && !tag.ForceShort {
argset = append(argset, `--`+optname)
prejoin = true
} else {
argset = append(argset, `-`+optname)
}
}
for _, v := range values {
argset = append(argset, stringutil.MustString(v))
}
if prejoin && len(argset) >= 2 {
command = append(command, argset[0]+tag.Joiner+argset[1])
command = append(command, argset[2:]...)
} else {
command = append(command, argset...)
}
return command
}
func parseTag(tag string, defaults *argonautTag) (argonautTag, error) {
if tag == `` {
return argonautTag{}, nil
}
parts := strings.Split(tag, `,`)
if len(parts) > 0 {
argonaut := argonautTag{
Options: sliceutil.CompactString(strings.Split(parts[0], `|`)),
Delimiters: defaults.Delimiters,
KeyPartJoiner: defaults.KeyPartJoiner,
Joiner: defaults.Joiner,
}
for _, tagopt := range parts[1:] {
optparts := strings.SplitN(tagopt, `=`, 2)
switch optparts[0] {
case `required`:
argonaut.Required = true
case `positional`:
argonaut.Positional = true
case `long`:
argonaut.LongOption = true
case `short`:
argonaut.LongOption = false
argonaut.ForceShort = true
case `suffixprev`:
argonaut.SuffixPrevious = true
case `skipname`:
argonaut.SkipName = true
default:
if len(optparts) == 1 {
return argonautTag{}, fmt.Errorf("argonaut tag option %q requires an argument", optparts[0])
}
switch optparts[0] {
case `label`:
argonaut.Label = optparts[1]
case `delimiters`, `joiner`, `keyjoiner`:
v := optparts[1]
v = strings.TrimPrefix(v, `[`)
v = strings.TrimSuffix(v, `]`)
switch optparts[0] {
case `delimiters`:
argonaut.Delimiters = strings.Split(v, ``)
case `joiner`:
argonaut.Joiner = v
case `keyjoiner`:
argonaut.KeyPartJoiner = v
}
}
}
}
// if long option wasn't specified, but multiple option names were given
// assume that the first one is a long option
if !argonaut.ForceShort && !argonaut.LongOption {
if len(argonaut.Options) > 1 {
argonaut.LongOption = true
}
}
return argonaut, nil
} else {
return argonautTag{}, nil
}
}