1
|
var camelCase = require('camelcase')
|
2
|
var decamelize = require('decamelize')
|
3
|
var path = require('path')
|
4
|
var tokenizeArgString = require('./lib/tokenize-arg-string')
|
5
|
var util = require('util')
|
6
|
|
7
|
function parse (args, opts) {
|
8
|
if (!opts) opts = {}
|
9
|
// allow a string argument to be passed in rather
|
10
|
// than an argv array.
|
11
|
args = tokenizeArgString(args)
|
12
|
// aliases might have transitive relationships, normalize this.
|
13
|
var aliases = combineAliases(opts.alias || {})
|
14
|
var configuration = assign({
|
15
|
'short-option-groups': true,
|
16
|
'camel-case-expansion': true,
|
17
|
'dot-notation': true,
|
18
|
'parse-numbers': true,
|
19
|
'boolean-negation': true,
|
20
|
'negation-prefix': 'no-',
|
21
|
'duplicate-arguments-array': true,
|
22
|
'flatten-duplicate-arrays': true,
|
23
|
'populate--': false,
|
24
|
'combine-arrays': false,
|
25
|
'set-placeholder-key': false,
|
26
|
'halt-at-non-option': false
|
27
|
}, opts.configuration)
|
28
|
var defaults = opts.default || {}
|
29
|
var configObjects = opts.configObjects || []
|
30
|
var envPrefix = opts.envPrefix
|
31
|
var notFlagsOption = configuration['populate--']
|
32
|
var notFlagsArgv = notFlagsOption ? '--' : '_'
|
33
|
var newAliases = {}
|
34
|
// allow a i18n handler to be passed in, default to a fake one (util.format).
|
35
|
var __ = opts.__ || function (str) {
|
36
|
return util.format.apply(util, Array.prototype.slice.call(arguments))
|
37
|
}
|
38
|
var error = null
|
39
|
var flags = {
|
40
|
aliases: {},
|
41
|
arrays: {},
|
42
|
bools: {},
|
43
|
strings: {},
|
44
|
numbers: {},
|
45
|
counts: {},
|
46
|
normalize: {},
|
47
|
configs: {},
|
48
|
defaulted: {},
|
49
|
nargs: {},
|
50
|
coercions: {},
|
51
|
keys: []
|
52
|
}
|
53
|
var negative = /^-[0-9]+(\.[0-9]+)?/
|
54
|
var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)')
|
55
|
|
56
|
;[].concat(opts.array).filter(Boolean).forEach(function (opt) {
|
57
|
var key = opt.key || opt
|
58
|
|
59
|
// assign to flags[bools|strings|numbers]
|
60
|
const assignment = Object.keys(opt).map(function (key) {
|
61
|
return ({
|
62
|
boolean: 'bools',
|
63
|
string: 'strings',
|
64
|
number: 'numbers'
|
65
|
})[key]
|
66
|
}).filter(Boolean).pop()
|
67
|
|
68
|
// assign key to be coerced
|
69
|
if (assignment) {
|
70
|
flags[assignment][key] = true
|
71
|
}
|
72
|
|
73
|
flags.arrays[key] = true
|
74
|
flags.keys.push(key)
|
75
|
})
|
76
|
|
77
|
;[].concat(opts.boolean).filter(Boolean).forEach(function (key) {
|
78
|
flags.bools[key] = true
|
79
|
flags.keys.push(key)
|
80
|
})
|
81
|
|
82
|
;[].concat(opts.string).filter(Boolean).forEach(function (key) {
|
83
|
flags.strings[key] = true
|
84
|
flags.keys.push(key)
|
85
|
})
|
86
|
|
87
|
;[].concat(opts.number).filter(Boolean).forEach(function (key) {
|
88
|
flags.numbers[key] = true
|
89
|
flags.keys.push(key)
|
90
|
})
|
91
|
|
92
|
;[].concat(opts.count).filter(Boolean).forEach(function (key) {
|
93
|
flags.counts[key] = true
|
94
|
flags.keys.push(key)
|
95
|
})
|
96
|
|
97
|
;[].concat(opts.normalize).filter(Boolean).forEach(function (key) {
|
98
|
flags.normalize[key] = true
|
99
|
flags.keys.push(key)
|
100
|
})
|
101
|
|
102
|
Object.keys(opts.narg || {}).forEach(function (k) {
|
103
|
flags.nargs[k] = opts.narg[k]
|
104
|
flags.keys.push(k)
|
105
|
})
|
106
|
|
107
|
Object.keys(opts.coerce || {}).forEach(function (k) {
|
108
|
flags.coercions[k] = opts.coerce[k]
|
109
|
flags.keys.push(k)
|
110
|
})
|
111
|
|
112
|
if (Array.isArray(opts.config) || typeof opts.config === 'string') {
|
113
|
;[].concat(opts.config).filter(Boolean).forEach(function (key) {
|
114
|
flags.configs[key] = true
|
115
|
})
|
116
|
} else {
|
117
|
Object.keys(opts.config || {}).forEach(function (k) {
|
118
|
flags.configs[k] = opts.config[k]
|
119
|
})
|
120
|
}
|
121
|
|
122
|
// create a lookup table that takes into account all
|
123
|
// combinations of aliases: {f: ['foo'], foo: ['f']}
|
124
|
extendAliases(opts.key, aliases, opts.default, flags.arrays)
|
125
|
|
126
|
// apply default values to all aliases.
|
127
|
Object.keys(defaults).forEach(function (key) {
|
128
|
(flags.aliases[key] || []).forEach(function (alias) {
|
129
|
defaults[alias] = defaults[key]
|
130
|
})
|
131
|
})
|
132
|
|
133
|
var argv = { _: [] }
|
134
|
|
135
|
Object.keys(flags.bools).forEach(function (key) {
|
136
|
if (Object.prototype.hasOwnProperty.call(defaults, key)) {
|
137
|
setArg(key, defaults[key])
|
138
|
setDefaulted(key)
|
139
|
}
|
140
|
})
|
141
|
|
142
|
var notFlags = []
|
143
|
|
144
|
for (var i = 0; i < args.length; i++) {
|
145
|
var arg = args[i]
|
146
|
var broken
|
147
|
var key
|
148
|
var letters
|
149
|
var m
|
150
|
var next
|
151
|
var value
|
152
|
|
153
|
// -- separated by =
|
154
|
if (arg.match(/^--.+=/) || (
|
155
|
!configuration['short-option-groups'] && arg.match(/^-.+=/)
|
156
|
)) {
|
157
|
// Using [\s\S] instead of . because js doesn't support the
|
158
|
// 'dotall' regex modifier. See:
|
159
|
// http://stackoverflow.com/a/1068308/13216
|
160
|
m = arg.match(/^--?([^=]+)=([\s\S]*)$/)
|
161
|
|
162
|
// nargs format = '--f=monkey washing cat'
|
163
|
if (checkAllAliases(m[1], flags.nargs)) {
|
164
|
args.splice(i + 1, 0, m[2])
|
165
|
i = eatNargs(i, m[1], args)
|
166
|
// arrays format = '--f=a b c'
|
167
|
} else if (checkAllAliases(m[1], flags.arrays) && args.length > i + 1) {
|
168
|
args.splice(i + 1, 0, m[2])
|
169
|
i = eatArray(i, m[1], args)
|
170
|
} else {
|
171
|
setArg(m[1], m[2])
|
172
|
}
|
173
|
} else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
|
174
|
key = arg.match(negatedBoolean)[1]
|
175
|
setArg(key, false)
|
176
|
|
177
|
// -- seperated by space.
|
178
|
} else if (arg.match(/^--.+/) || (
|
179
|
!configuration['short-option-groups'] && arg.match(/^-.+/)
|
180
|
)) {
|
181
|
key = arg.match(/^--?(.+)/)[1]
|
182
|
|
183
|
// nargs format = '--foo a b c'
|
184
|
if (checkAllAliases(key, flags.nargs)) {
|
185
|
i = eatNargs(i, key, args)
|
186
|
// array format = '--foo a b c'
|
187
|
} else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
|
188
|
i = eatArray(i, key, args)
|
189
|
} else {
|
190
|
next = args[i + 1]
|
191
|
|
192
|
if (next !== undefined && (!next.match(/^-/) ||
|
193
|
next.match(negative)) &&
|
194
|
!checkAllAliases(key, flags.bools) &&
|
195
|
!checkAllAliases(key, flags.counts)) {
|
196
|
setArg(key, next)
|
197
|
i++
|
198
|
} else if (/^(true|false)$/.test(next)) {
|
199
|
setArg(key, next)
|
200
|
i++
|
201
|
} else {
|
202
|
setArg(key, defaultForType(guessType(key, flags)))
|
203
|
}
|
204
|
}
|
205
|
|
206
|
// dot-notation flag seperated by '='.
|
207
|
} else if (arg.match(/^-.\..+=/)) {
|
208
|
m = arg.match(/^-([^=]+)=([\s\S]*)$/)
|
209
|
setArg(m[1], m[2])
|
210
|
|
211
|
// dot-notation flag seperated by space.
|
212
|
} else if (arg.match(/^-.\..+/)) {
|
213
|
next = args[i + 1]
|
214
|
key = arg.match(/^-(.\..+)/)[1]
|
215
|
|
216
|
if (next !== undefined && !next.match(/^-/) &&
|
217
|
!checkAllAliases(key, flags.bools) &&
|
218
|
!checkAllAliases(key, flags.counts)) {
|
219
|
setArg(key, next)
|
220
|
i++
|
221
|
} else {
|
222
|
setArg(key, defaultForType(guessType(key, flags)))
|
223
|
}
|
224
|
} else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
|
225
|
letters = arg.slice(1, -1).split('')
|
226
|
broken = false
|
227
|
|
228
|
for (var j = 0; j < letters.length; j++) {
|
229
|
next = arg.slice(j + 2)
|
230
|
|
231
|
if (letters[j + 1] && letters[j + 1] === '=') {
|
232
|
value = arg.slice(j + 3)
|
233
|
key = letters[j]
|
234
|
|
235
|
// nargs format = '-f=monkey washing cat'
|
236
|
if (checkAllAliases(key, flags.nargs)) {
|
237
|
args.splice(i + 1, 0, value)
|
238
|
i = eatNargs(i, key, args)
|
239
|
// array format = '-f=a b c'
|
240
|
} else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
|
241
|
args.splice(i + 1, 0, value)
|
242
|
i = eatArray(i, key, args)
|
243
|
} else {
|
244
|
setArg(key, value)
|
245
|
}
|
246
|
|
247
|
broken = true
|
248
|
break
|
249
|
}
|
250
|
|
251
|
if (next === '-') {
|
252
|
setArg(letters[j], next)
|
253
|
continue
|
254
|
}
|
255
|
|
256
|
// current letter is an alphabetic character and next value is a number
|
257
|
if (/[A-Za-z]/.test(letters[j]) &&
|
258
|
/^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
|
259
|
setArg(letters[j], next)
|
260
|
broken = true
|
261
|
break
|
262
|
}
|
263
|
|
264
|
if (letters[j + 1] && letters[j + 1].match(/\W/)) {
|
265
|
setArg(letters[j], next)
|
266
|
broken = true
|
267
|
break
|
268
|
} else {
|
269
|
setArg(letters[j], defaultForType(guessType(letters[j], flags)))
|
270
|
}
|
271
|
}
|
272
|
|
273
|
key = arg.slice(-1)[0]
|
274
|
|
275
|
if (!broken && key !== '-') {
|
276
|
// nargs format = '-f a b c'
|
277
|
if (checkAllAliases(key, flags.nargs)) {
|
278
|
i = eatNargs(i, key, args)
|
279
|
// array format = '-f a b c'
|
280
|
} else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
|
281
|
i = eatArray(i, key, args)
|
282
|
} else {
|
283
|
next = args[i + 1]
|
284
|
|
285
|
if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
|
286
|
next.match(negative)) &&
|
287
|
!checkAllAliases(key, flags.bools) &&
|
288
|
!checkAllAliases(key, flags.counts)) {
|
289
|
setArg(key, next)
|
290
|
i++
|
291
|
} else if (/^(true|false)$/.test(next)) {
|
292
|
setArg(key, next)
|
293
|
i++
|
294
|
} else {
|
295
|
setArg(key, defaultForType(guessType(key, flags)))
|
296
|
}
|
297
|
}
|
298
|
}
|
299
|
} else if (arg === '--') {
|
300
|
notFlags = args.slice(i + 1)
|
301
|
break
|
302
|
} else if (configuration['halt-at-non-option']) {
|
303
|
notFlags = args.slice(i)
|
304
|
break
|
305
|
} else {
|
306
|
argv._.push(maybeCoerceNumber('_', arg))
|
307
|
}
|
308
|
}
|
309
|
|
310
|
// order of precedence:
|
311
|
// 1. command line arg
|
312
|
// 2. value from env var
|
313
|
// 3. value from config file
|
314
|
// 4. value from config objects
|
315
|
// 5. configured default value
|
316
|
applyEnvVars(argv, true) // special case: check env vars that point to config file
|
317
|
applyEnvVars(argv, false)
|
318
|
setConfig(argv)
|
319
|
setConfigObjects()
|
320
|
applyDefaultsAndAliases(argv, flags.aliases, defaults)
|
321
|
applyCoercions(argv)
|
322
|
if (configuration['set-placeholder-key']) setPlaceholderKeys(argv)
|
323
|
|
324
|
// for any counts either not in args or without an explicit default, set to 0
|
325
|
Object.keys(flags.counts).forEach(function (key) {
|
326
|
if (!hasKey(argv, key.split('.'))) setArg(key, 0)
|
327
|
})
|
328
|
|
329
|
// '--' defaults to undefined.
|
330
|
if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = []
|
331
|
notFlags.forEach(function (key) {
|
332
|
argv[notFlagsArgv].push(key)
|
333
|
})
|
334
|
|
335
|
// how many arguments should we consume, based
|
336
|
// on the nargs option?
|
337
|
function eatNargs (i, key, args) {
|
338
|
var ii
|
339
|
const toEat = checkAllAliases(key, flags.nargs)
|
340
|
|
341
|
// nargs will not consume flag arguments, e.g., -abc, --foo,
|
342
|
// and terminates when one is observed.
|
343
|
var available = 0
|
344
|
for (ii = i + 1; ii < args.length; ii++) {
|
345
|
if (!args[ii].match(/^-[^0-9]/)) available++
|
346
|
else break
|
347
|
}
|
348
|
|
349
|
if (available < toEat) error = Error(__('Not enough arguments following: %s', key))
|
350
|
|
351
|
const consumed = Math.min(available, toEat)
|
352
|
for (ii = i + 1; ii < (consumed + i + 1); ii++) {
|
353
|
setArg(key, args[ii])
|
354
|
}
|
355
|
|
356
|
return (i + consumed)
|
357
|
}
|
358
|
|
359
|
// if an option is an array, eat all non-hyphenated arguments
|
360
|
// following it... YUM!
|
361
|
// e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
|
362
|
function eatArray (i, key, args) {
|
363
|
var start = i + 1
|
364
|
var argsToSet = []
|
365
|
var multipleArrayFlag = i > 0
|
366
|
for (var ii = i + 1; ii < args.length; ii++) {
|
367
|
if (/^-/.test(args[ii]) && !negative.test(args[ii])) {
|
368
|
if (ii === start) {
|
369
|
setArg(key, defaultForType('array'))
|
370
|
}
|
371
|
multipleArrayFlag = true
|
372
|
break
|
373
|
}
|
374
|
i = ii
|
375
|
argsToSet.push(args[ii])
|
376
|
}
|
377
|
if (multipleArrayFlag) {
|
378
|
setArg(key, argsToSet.map(function (arg) {
|
379
|
return processValue(key, arg)
|
380
|
}))
|
381
|
} else {
|
382
|
argsToSet.forEach(function (arg) {
|
383
|
setArg(key, arg)
|
384
|
})
|
385
|
}
|
386
|
|
387
|
return i
|
388
|
}
|
389
|
|
390
|
function setArg (key, val) {
|
391
|
unsetDefaulted(key)
|
392
|
|
393
|
if (/-/.test(key) && configuration['camel-case-expansion']) {
|
394
|
var alias = key.split('.').map(function (prop) {
|
395
|
return camelCase(prop)
|
396
|
}).join('.')
|
397
|
addNewAlias(key, alias)
|
398
|
}
|
399
|
|
400
|
var value = processValue(key, val)
|
401
|
|
402
|
var splitKey = key.split('.')
|
403
|
setKey(argv, splitKey, value)
|
404
|
|
405
|
// handle populating aliases of the full key
|
406
|
if (flags.aliases[key]) {
|
407
|
flags.aliases[key].forEach(function (x) {
|
408
|
x = x.split('.')
|
409
|
setKey(argv, x, value)
|
410
|
})
|
411
|
}
|
412
|
|
413
|
// handle populating aliases of the first element of the dot-notation key
|
414
|
if (splitKey.length > 1 && configuration['dot-notation']) {
|
415
|
;(flags.aliases[splitKey[0]] || []).forEach(function (x) {
|
416
|
x = x.split('.')
|
417
|
|
418
|
// expand alias with nested objects in key
|
419
|
var a = [].concat(splitKey)
|
420
|
a.shift() // nuke the old key.
|
421
|
x = x.concat(a)
|
422
|
|
423
|
setKey(argv, x, value)
|
424
|
})
|
425
|
}
|
426
|
|
427
|
// Set normalize getter and setter when key is in 'normalize' but isn't an array
|
428
|
if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
|
429
|
var keys = [key].concat(flags.aliases[key] || [])
|
430
|
keys.forEach(function (key) {
|
431
|
argv.__defineSetter__(key, function (v) {
|
432
|
val = path.normalize(v)
|
433
|
})
|
434
|
|
435
|
argv.__defineGetter__(key, function () {
|
436
|
return typeof val === 'string' ? path.normalize(val) : val
|
437
|
})
|
438
|
})
|
439
|
}
|
440
|
}
|
441
|
|
442
|
function addNewAlias (key, alias) {
|
443
|
if (!(flags.aliases[key] && flags.aliases[key].length)) {
|
444
|
flags.aliases[key] = [alias]
|
445
|
newAliases[alias] = true
|
446
|
}
|
447
|
if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
|
448
|
addNewAlias(alias, key)
|
449
|
}
|
450
|
}
|
451
|
|
452
|
function processValue (key, val) {
|
453
|
// handle parsing boolean arguments --foo=true --bar false.
|
454
|
if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
|
455
|
if (typeof val === 'string') val = val === 'true'
|
456
|
}
|
457
|
|
458
|
var value = maybeCoerceNumber(key, val)
|
459
|
|
460
|
// increment a count given as arg (either no value or value parsed as boolean)
|
461
|
if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
|
462
|
value = increment
|
463
|
}
|
464
|
|
465
|
// Set normalized value when key is in 'normalize' and in 'arrays'
|
466
|
if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
|
467
|
if (Array.isArray(val)) value = val.map(path.normalize)
|
468
|
else value = path.normalize(val)
|
469
|
}
|
470
|
return value
|
471
|
}
|
472
|
|
473
|
function maybeCoerceNumber (key, value) {
|
474
|
if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) {
|
475
|
const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && (
|
476
|
Number.isSafeInteger(Math.floor(value))
|
477
|
)
|
478
|
if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value)
|
479
|
}
|
480
|
return value
|
481
|
}
|
482
|
|
483
|
// set args from config.json file, this should be
|
484
|
// applied last so that defaults can be applied.
|
485
|
function setConfig (argv) {
|
486
|
var configLookup = {}
|
487
|
|
488
|
// expand defaults/aliases, in-case any happen to reference
|
489
|
// the config.json file.
|
490
|
applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
|
491
|
|
492
|
Object.keys(flags.configs).forEach(function (configKey) {
|
493
|
var configPath = argv[configKey] || configLookup[configKey]
|
494
|
if (configPath) {
|
495
|
try {
|
496
|
var config = null
|
497
|
var resolvedConfigPath = path.resolve(process.cwd(), configPath)
|
498
|
|
499
|
if (typeof flags.configs[configKey] === 'function') {
|
500
|
try {
|
501
|
config = flags.configs[configKey](resolvedConfigPath)
|
502
|
} catch (e) {
|
503
|
config = e
|
504
|
}
|
505
|
if (config instanceof Error) {
|
506
|
error = config
|
507
|
return
|
508
|
}
|
509
|
} else {
|
510
|
config = require(resolvedConfigPath)
|
511
|
}
|
512
|
|
513
|
setConfigObject(config)
|
514
|
} catch (ex) {
|
515
|
if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
|
516
|
}
|
517
|
}
|
518
|
})
|
519
|
}
|
520
|
|
521
|
// set args from config object.
|
522
|
// it recursively checks nested objects.
|
523
|
function setConfigObject (config, prev) {
|
524
|
Object.keys(config).forEach(function (key) {
|
525
|
var value = config[key]
|
526
|
var fullKey = prev ? prev + '.' + key : key
|
527
|
|
528
|
// if the value is an inner object and we have dot-notation
|
529
|
// enabled, treat inner objects in config the same as
|
530
|
// heavily nested dot notations (foo.bar.apple).
|
531
|
if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
|
532
|
// if the value is an object but not an array, check nested object
|
533
|
setConfigObject(value, fullKey)
|
534
|
} else {
|
535
|
// setting arguments via CLI takes precedence over
|
536
|
// values within the config file.
|
537
|
if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
|
538
|
setArg(fullKey, value)
|
539
|
}
|
540
|
}
|
541
|
})
|
542
|
}
|
543
|
|
544
|
// set all config objects passed in opts
|
545
|
function setConfigObjects () {
|
546
|
if (typeof configObjects === 'undefined') return
|
547
|
configObjects.forEach(function (configObject) {
|
548
|
setConfigObject(configObject)
|
549
|
})
|
550
|
}
|
551
|
|
552
|
function applyEnvVars (argv, configOnly) {
|
553
|
if (typeof envPrefix === 'undefined') return
|
554
|
|
555
|
var prefix = typeof envPrefix === 'string' ? envPrefix : ''
|
556
|
Object.keys(process.env).forEach(function (envVar) {
|
557
|
if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
|
558
|
// get array of nested keys and convert them to camel case
|
559
|
var keys = envVar.split('__').map(function (key, i) {
|
560
|
if (i === 0) {
|
561
|
key = key.substring(prefix.length)
|
562
|
}
|
563
|
return camelCase(key)
|
564
|
})
|
565
|
|
566
|
if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) {
|
567
|
setArg(keys.join('.'), process.env[envVar])
|
568
|
}
|
569
|
}
|
570
|
})
|
571
|
}
|
572
|
|
573
|
function applyCoercions (argv) {
|
574
|
var coerce
|
575
|
var applied = {}
|
576
|
Object.keys(argv).forEach(function (key) {
|
577
|
if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
|
578
|
coerce = checkAllAliases(key, flags.coercions)
|
579
|
if (typeof coerce === 'function') {
|
580
|
try {
|
581
|
var value = coerce(argv[key])
|
582
|
;([].concat(flags.aliases[key] || [], key)).forEach(ali => {
|
583
|
applied[ali] = argv[ali] = value
|
584
|
})
|
585
|
} catch (err) {
|
586
|
error = err
|
587
|
}
|
588
|
}
|
589
|
}
|
590
|
})
|
591
|
}
|
592
|
|
593
|
function setPlaceholderKeys (argv) {
|
594
|
flags.keys.forEach((key) => {
|
595
|
// don't set placeholder keys for dot notation options 'foo.bar'.
|
596
|
if (~key.indexOf('.')) return
|
597
|
if (typeof argv[key] === 'undefined') argv[key] = undefined
|
598
|
})
|
599
|
return argv
|
600
|
}
|
601
|
|
602
|
function applyDefaultsAndAliases (obj, aliases, defaults) {
|
603
|
Object.keys(defaults).forEach(function (key) {
|
604
|
if (!hasKey(obj, key.split('.'))) {
|
605
|
setKey(obj, key.split('.'), defaults[key])
|
606
|
|
607
|
;(aliases[key] || []).forEach(function (x) {
|
608
|
if (hasKey(obj, x.split('.'))) return
|
609
|
setKey(obj, x.split('.'), defaults[key])
|
610
|
})
|
611
|
}
|
612
|
})
|
613
|
}
|
614
|
|
615
|
function hasKey (obj, keys) {
|
616
|
var o = obj
|
617
|
|
618
|
if (!configuration['dot-notation']) keys = [keys.join('.')]
|
619
|
|
620
|
keys.slice(0, -1).forEach(function (key) {
|
621
|
o = (o[key] || {})
|
622
|
})
|
623
|
|
624
|
var key = keys[keys.length - 1]
|
625
|
|
626
|
if (typeof o !== 'object') return false
|
627
|
else return key in o
|
628
|
}
|
629
|
|
630
|
function setKey (obj, keys, value) {
|
631
|
var o = obj
|
632
|
|
633
|
if (!configuration['dot-notation']) keys = [keys.join('.')]
|
634
|
|
635
|
keys.slice(0, -1).forEach(function (key, index) {
|
636
|
if (typeof o === 'object' && o[key] === undefined) {
|
637
|
o[key] = {}
|
638
|
}
|
639
|
|
640
|
if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
|
641
|
// ensure that o[key] is an array, and that the last item is an empty object.
|
642
|
if (Array.isArray(o[key])) {
|
643
|
o[key].push({})
|
644
|
} else {
|
645
|
o[key] = [o[key], {}]
|
646
|
}
|
647
|
|
648
|
// we want to update the empty object at the end of the o[key] array, so set o to that object
|
649
|
o = o[key][o[key].length - 1]
|
650
|
} else {
|
651
|
o = o[key]
|
652
|
}
|
653
|
})
|
654
|
|
655
|
var key = keys[keys.length - 1]
|
656
|
|
657
|
var isTypeArray = checkAllAliases(keys.join('.'), flags.arrays)
|
658
|
var isValueArray = Array.isArray(value)
|
659
|
var duplicate = configuration['duplicate-arguments-array']
|
660
|
|
661
|
if (value === increment) {
|
662
|
o[key] = increment(o[key])
|
663
|
} else if (Array.isArray(o[key])) {
|
664
|
if (duplicate && isTypeArray && isValueArray) {
|
665
|
o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value])
|
666
|
} else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
|
667
|
o[key] = value
|
668
|
} else {
|
669
|
o[key] = o[key].concat([value])
|
670
|
}
|
671
|
} else if (o[key] === undefined && isTypeArray) {
|
672
|
o[key] = isValueArray ? value : [value]
|
673
|
} else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) {
|
674
|
o[key] = [ o[key], value ]
|
675
|
} else {
|
676
|
o[key] = value
|
677
|
}
|
678
|
}
|
679
|
|
680
|
// extend the aliases list with inferred aliases.
|
681
|
function extendAliases () {
|
682
|
Array.prototype.slice.call(arguments).forEach(function (obj) {
|
683
|
Object.keys(obj || {}).forEach(function (key) {
|
684
|
// short-circuit if we've already added a key
|
685
|
// to the aliases array, for example it might
|
686
|
// exist in both 'opts.default' and 'opts.key'.
|
687
|
if (flags.aliases[key]) return
|
688
|
|
689
|
flags.aliases[key] = [].concat(aliases[key] || [])
|
690
|
// For "--option-name", also set argv.optionName
|
691
|
flags.aliases[key].concat(key).forEach(function (x) {
|
692
|
if (/-/.test(x) && configuration['camel-case-expansion']) {
|
693
|
var c = camelCase(x)
|
694
|
if (c !== key && flags.aliases[key].indexOf(c) === -1) {
|
695
|
flags.aliases[key].push(c)
|
696
|
newAliases[c] = true
|
697
|
}
|
698
|
}
|
699
|
})
|
700
|
// For "--optionName", also set argv['option-name']
|
701
|
flags.aliases[key].concat(key).forEach(function (x) {
|
702
|
if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
|
703
|
var c = decamelize(x, '-')
|
704
|
if (c !== key && flags.aliases[key].indexOf(c) === -1) {
|
705
|
flags.aliases[key].push(c)
|
706
|
newAliases[c] = true
|
707
|
}
|
708
|
}
|
709
|
})
|
710
|
flags.aliases[key].forEach(function (x) {
|
711
|
flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
|
712
|
return x !== y
|
713
|
}))
|
714
|
})
|
715
|
})
|
716
|
})
|
717
|
}
|
718
|
|
719
|
// check if a flag is set for any of a key's aliases.
|
720
|
function checkAllAliases (key, flag) {
|
721
|
var isSet = false
|
722
|
var toCheck = [].concat(flags.aliases[key] || [], key)
|
723
|
|
724
|
toCheck.forEach(function (key) {
|
725
|
if (flag[key]) isSet = flag[key]
|
726
|
})
|
727
|
|
728
|
return isSet
|
729
|
}
|
730
|
|
731
|
function setDefaulted (key) {
|
732
|
[].concat(flags.aliases[key] || [], key).forEach(function (k) {
|
733
|
flags.defaulted[k] = true
|
734
|
})
|
735
|
}
|
736
|
|
737
|
function unsetDefaulted (key) {
|
738
|
[].concat(flags.aliases[key] || [], key).forEach(function (k) {
|
739
|
delete flags.defaulted[k]
|
740
|
})
|
741
|
}
|
742
|
|
743
|
// return a default value, given the type of a flag.,
|
744
|
// e.g., key of type 'string' will default to '', rather than 'true'.
|
745
|
function defaultForType (type) {
|
746
|
var def = {
|
747
|
boolean: true,
|
748
|
string: '',
|
749
|
number: undefined,
|
750
|
array: []
|
751
|
}
|
752
|
|
753
|
return def[type]
|
754
|
}
|
755
|
|
756
|
// given a flag, enforce a default type.
|
757
|
function guessType (key, flags) {
|
758
|
var type = 'boolean'
|
759
|
|
760
|
if (checkAllAliases(key, flags.strings)) type = 'string'
|
761
|
else if (checkAllAliases(key, flags.numbers)) type = 'number'
|
762
|
else if (checkAllAliases(key, flags.arrays)) type = 'array'
|
763
|
|
764
|
return type
|
765
|
}
|
766
|
|
767
|
function isNumber (x) {
|
768
|
if (typeof x === 'number') return true
|
769
|
if (/^0x[0-9a-f]+$/i.test(x)) return true
|
770
|
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
|
771
|
}
|
772
|
|
773
|
function isUndefined (num) {
|
774
|
return num === undefined
|
775
|
}
|
776
|
|
777
|
return {
|
778
|
argv: argv,
|
779
|
error: error,
|
780
|
aliases: flags.aliases,
|
781
|
newAliases: newAliases,
|
782
|
configuration: configuration
|
783
|
}
|
784
|
}
|
785
|
|
786
|
// if any aliases reference each other, we should
|
787
|
// merge them together.
|
788
|
function combineAliases (aliases) {
|
789
|
var aliasArrays = []
|
790
|
var change = true
|
791
|
var combined = {}
|
792
|
|
793
|
// turn alias lookup hash {key: ['alias1', 'alias2']} into
|
794
|
// a simple array ['key', 'alias1', 'alias2']
|
795
|
Object.keys(aliases).forEach(function (key) {
|
796
|
aliasArrays.push(
|
797
|
[].concat(aliases[key], key)
|
798
|
)
|
799
|
})
|
800
|
|
801
|
// combine arrays until zero changes are
|
802
|
// made in an iteration.
|
803
|
while (change) {
|
804
|
change = false
|
805
|
for (var i = 0; i < aliasArrays.length; i++) {
|
806
|
for (var ii = i + 1; ii < aliasArrays.length; ii++) {
|
807
|
var intersect = aliasArrays[i].filter(function (v) {
|
808
|
return aliasArrays[ii].indexOf(v) !== -1
|
809
|
})
|
810
|
|
811
|
if (intersect.length) {
|
812
|
aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
|
813
|
aliasArrays.splice(ii, 1)
|
814
|
change = true
|
815
|
break
|
816
|
}
|
817
|
}
|
818
|
}
|
819
|
}
|
820
|
|
821
|
// map arrays back to the hash-lookup (de-dupe while
|
822
|
// we're at it).
|
823
|
aliasArrays.forEach(function (aliasArray) {
|
824
|
aliasArray = aliasArray.filter(function (v, i, self) {
|
825
|
return self.indexOf(v) === i
|
826
|
})
|
827
|
combined[aliasArray.pop()] = aliasArray
|
828
|
})
|
829
|
|
830
|
return combined
|
831
|
}
|
832
|
|
833
|
function assign (defaults, configuration) {
|
834
|
var o = {}
|
835
|
configuration = configuration || {}
|
836
|
|
837
|
Object.keys(defaults).forEach(function (k) {
|
838
|
o[k] = defaults[k]
|
839
|
})
|
840
|
Object.keys(configuration).forEach(function (k) {
|
841
|
o[k] = configuration[k]
|
842
|
})
|
843
|
|
844
|
return o
|
845
|
}
|
846
|
|
847
|
// this function should only be called when a count is given as an arg
|
848
|
// it is NOT called to set a default value
|
849
|
// thus we can start the count at 1 instead of 0
|
850
|
function increment (orig) {
|
851
|
return orig !== undefined ? orig + 1 : 1
|
852
|
}
|
853
|
|
854
|
function Parser (args, opts) {
|
855
|
var result = parse(args.slice(), opts)
|
856
|
|
857
|
return result.argv
|
858
|
}
|
859
|
|
860
|
// parse arguments and return detailed
|
861
|
// meta information, aliases, etc.
|
862
|
Parser.detailed = function (args, opts) {
|
863
|
return parse(args.slice(), opts)
|
864
|
}
|
865
|
|
866
|
module.exports = Parser
|