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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
|
const assign = require('./lib/assign')
const Command = require('./lib/command')
const Completion = require('./lib/completion')
const Parser = require('yargs-parser')
const path = require('path')
const Usage = require('./lib/usage')
const Validation = require('./lib/validation')
const Y18n = require('y18n')
const objFilter = require('./lib/obj-filter')
const setBlocking = require('set-blocking')
var exports = module.exports = Yargs
function Yargs (processArgs, cwd, parentRequire) {
processArgs = processArgs || [] // handle calling yargs().
const self = {}
var command = null
var completion = null
var groups = {}
var output = ''
var preservedGroups = {}
var usage = null
var validation = null
const y18n = Y18n({
directory: path.resolve(__dirname, './locales'),
updateFiles: false
})
if (!cwd) cwd = process.cwd()
self.$0 = process.argv
.slice(0, 2)
.map(function (x, i) {
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
if (i === 0 && /\b(node|iojs)(\.exe)?$/.test(x)) return
var b = rebase(cwd, x)
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x
})
.join(' ').trim()
if (process.env._ !== undefined && process.argv[1] === process.env._) {
self.$0 = process.env._.replace(
path.dirname(process.execPath) + '/', ''
)
}
// use context object to keep track of resets, subcommand execution, etc
// submodules should modify and check the state of context as necessary
const context = { resets: -1, commands: [], files: [] }
self.getContext = function () {
return context
}
// puts yargs back into an initial state. any keys
// that have been set to "global" will not be reset
// by this action.
var options
self.resetOptions = self.reset = function (aliases) {
context.resets++
aliases = aliases || {}
options = options || {}
// put yargs back into an initial state, this
// logic is used to build a nested command
// hierarchy.
var tmpOptions = {}
tmpOptions.global = options.global ? options.global : []
tmpOptions.configObjects = options.configObjects ? options.configObjects : []
// if a key has been set as a global, we
// do not want to reset it or its aliases.
var globalLookup = {}
tmpOptions.global.forEach(function (g) {
globalLookup[g] = true
;(aliases[g] || []).forEach(function (a) {
globalLookup[a] = true
})
})
// preserve groups containing global keys
preservedGroups = Object.keys(groups).reduce(function (acc, groupName) {
var keys = groups[groupName].filter(function (key) {
return key in globalLookup
})
if (keys.length > 0) {
acc[groupName] = keys
}
return acc
}, {})
// groups can now be reset
groups = {}
var arrayOptions = [
'array', 'boolean', 'string', 'requiresArg', 'skipValidation',
'count', 'normalize', 'number'
]
var objectOptions = [
'narg', 'key', 'alias', 'default', 'defaultDescription',
'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
]
arrayOptions.forEach(function (k) {
tmpOptions[k] = (options[k] || []).filter(function (k) {
return globalLookup[k]
})
})
objectOptions.forEach(function (k) {
tmpOptions[k] = objFilter(options[k], function (k, v) {
return globalLookup[k]
})
})
tmpOptions.envPrefix = options.envPrefix
options = tmpOptions
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
usage = usage ? usage.reset(globalLookup) : Usage(self, y18n)
validation = validation ? validation.reset(globalLookup) : Validation(self, usage, y18n)
command = command ? command.reset() : Command(self, usage, validation)
if (!completion) completion = Completion(self, usage, command)
strict = false
completionCommand = null
output = ''
exitError = null
hasOutput = false
self.parsed = false
return self
}
self.resetOptions()
// temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
var frozen
function freeze () {
frozen = {}
frozen.options = options
frozen.configObjects = options.configObjects.slice(0)
frozen.exitProcess = exitProcess
frozen.groups = groups
usage.freeze()
validation.freeze()
command.freeze()
frozen.strict = strict
frozen.completionCommand = completionCommand
frozen.output = output
frozen.exitError = exitError
frozen.hasOutput = hasOutput
frozen.parsed = self.parsed
}
function unfreeze () {
options = frozen.options
options.configObjects = frozen.configObjects
exitProcess = frozen.exitProcess
groups = frozen.groups
output = frozen.output
exitError = frozen.exitError
hasOutput = frozen.hasOutput
self.parsed = frozen.parsed
usage.unfreeze()
validation.unfreeze()
command.unfreeze()
strict = frozen.strict
completionCommand = frozen.completionCommand
parseFn = null
parseContext = null
frozen = undefined
}
self.boolean = function (bools) {
options.boolean.push.apply(options.boolean, [].concat(bools))
return self
}
self.array = function (arrays) {
options.array.push.apply(options.array, [].concat(arrays))
return self
}
self.nargs = function (key, n) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.nargs(k, key[k])
})
} else {
options.narg[key] = n
}
return self
}
self.number = function (numbers) {
options.number.push.apply(options.number, [].concat(numbers))
return self
}
self.choices = function (key, values) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.choices(k, key[k])
})
} else {
options.choices[key] = (options.choices[key] || []).concat(values)
}
return self
}
self.normalize = function (strings) {
options.normalize.push.apply(options.normalize, [].concat(strings))
return self
}
self.config = function (key, msg, parseFn) {
// allow to pass a configuration object
if (typeof key === 'object') {
options.configObjects = (options.configObjects || []).concat(key)
return self
}
// allow to provide a parsing function
if (typeof msg === 'function') {
parseFn = msg
msg = null
}
key = key || 'config'
self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'))
;(Array.isArray(key) ? key : [key]).forEach(function (k) {
options.config[k] = parseFn || true
})
return self
}
self.example = function (cmd, description) {
usage.example(cmd, description)
return self
}
self.command = function (cmd, description, builder, handler) {
command.addHandler(cmd, description, builder, handler)
return self
}
self.commandDir = function (dir, opts) {
const req = parentRequire || require
command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts)
return self
}
self.string = function (strings) {
options.string.push.apply(options.string, [].concat(strings))
return self
}
// The 'defaults' alias is deprecated. It will be removed in the next major version.
self.default = self.defaults = function (key, value, defaultDescription) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.default(k, key[k])
})
} else {
if (defaultDescription) options.defaultDescription[key] = defaultDescription
if (typeof value === 'function') {
if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value)
value = value.call()
}
options.default[key] = value
}
return self
}
self.alias = function (x, y) {
if (typeof x === 'object') {
Object.keys(x).forEach(function (key) {
self.alias(key, x[key])
})
} else {
options.alias[x] = (options.alias[x] || []).concat(y)
}
return self
}
self.coerce = function (key, fn) {
if (typeof key === 'object' && !Array.isArray(key)) {
Object.keys(key).forEach(function (k) {
self.coerce(k, key[k])
})
} else {
[].concat(key).forEach(function (k) {
options.coerce[k] = fn
})
}
return self
}
self.count = function (counts) {
options.count.push.apply(options.count, [].concat(counts))
return self
}
// deprecated: the demand API is too overloaded, and is being
// deprecated in favor of .demandCommand() .demandOption().
self.demand = self.required = self.require = function (keys, max, msg) {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(function (key) {
self.demandOption(key, msg)
})
max = Infinity
} else if (typeof max !== 'number') {
msg = max
max = Infinity
}
if (typeof keys === 'number') {
self.demandCommand(keys, max, msg)
} else if (Array.isArray(keys)) {
keys.forEach(function (key) {
self.demandOption(key, msg)
})
} else {
if (typeof msg === 'string') {
self.demandOption(keys, msg)
} else if (msg === true || typeof msg === 'undefined') {
self.demandOption(keys)
}
}
return self
}
self.demandOption = function (key, msg) {
if (Array.isArray(key)) {
key.forEach(function (key) {
self.demandOption(key, msg)
})
} else {
if (typeof msg === 'string') {
options.demandedOptions[key] = { msg: msg }
// allow edge-case of options: {a: {demand: true}, b: {demand: false}}
} else if (msg === true || typeof msg === 'undefined') {
options.demandedOptions[key] = { msg: undefined }
}
}
return self
}
self.demandCommand = function (min, max, minMsg, maxMsg) {
if (typeof max !== 'number') {
minMsg = max
max = Infinity
}
options.demandedCommands._ = {
min: min,
max: max,
minMsg: minMsg,
maxMsg: maxMsg
}
return self
}
self.getDemandedOptions = function () {
return options.demandedOptions
}
self.getDemandedCommands = function () {
return options.demandedCommands
}
self.requiresArg = function (requiresArgs) {
options.requiresArg.push.apply(options.requiresArg, [].concat(requiresArgs))
return self
}
self.skipValidation = function (skipValidations) {
options.skipValidation.push.apply(options.skipValidation, [].concat(skipValidations))
return self
}
self.implies = function (key, value) {
validation.implies(key, value)
return self
}
self.conflicts = function (key1, key2) {
validation.conflicts(key1, key2)
return self
}
self.usage = function (msg, opts) {
if (!opts && typeof msg === 'object') {
opts = msg
msg = null
}
usage.usage(msg)
if (opts) self.options(opts)
return self
}
self.epilogue = self.epilog = function (msg) {
usage.epilog(msg)
return self
}
self.fail = function (f) {
usage.failFn(f)
return self
}
self.check = function (f) {
validation.check(f)
return self
}
self.describe = function (key, desc) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
options.key[k] = true
})
} else {
options.key[key] = true
}
usage.describe(key, desc)
return self
}
self.global = function (globals) {
options.global.push.apply(options.global, [].concat(globals))
return self
}
self.pkgConf = function (key, path) {
var conf = null
var obj = pkgUp(path)
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = obj[key]
options.configObjects = (options.configObjects || []).concat(conf)
}
return self
}
var pkgs = {}
function pkgUp (path) {
var npath = path || '*'
if (pkgs[npath]) return pkgs[npath]
const readPkgUp = require('read-pkg-up')
var obj = {}
try {
obj = readPkgUp.sync({
cwd: path || require('require-main-filename')(parentRequire || require),
normalize: false
})
} catch (noop) {}
pkgs[npath] = obj.pkg || {}
return pkgs[npath]
}
var parseFn = null
var parseContext = null
self.parse = function (args, shortCircuit, _parseFn) {
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
parseContext = shortCircuit
shortCircuit = _parseFn
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
parseFn = shortCircuit
shortCircuit = null
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) processArgs = args
freeze()
if (parseFn) exitProcess = false
var parsed = parseArgs(args, shortCircuit)
if (parseFn) parseFn(exitError, parsed, output)
unfreeze()
return parsed
}
self._hasParseCallback = function () {
return !!parseFn
}
self.option = self.options = function (key, opt) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.options(k, key[k])
})
} else {
if (typeof opt !== 'object') {
opt = {}
}
options.key[key] = true // track manually set keys.
if (opt.alias) self.alias(key, opt.alias)
var demand = opt.demand || opt.required || opt.require
if (demand) {
self.demand(key, demand)
}
if ('demandOption' in opt) {
self.demandOption(key, opt.demandOption)
}
if ('config' in opt) {
self.config(key, opt.configParser)
}
if ('default' in opt) {
self.default(key, opt.default)
}
if ('nargs' in opt) {
self.nargs(key, opt.nargs)
}
if ('normalize' in opt) {
self.normalize(key)
}
if ('choices' in opt) {
self.choices(key, opt.choices)
}
if ('coerce' in opt) {
self.coerce(key, opt.coerce)
}
if ('group' in opt) {
self.group(key, opt.group)
}
if (opt.global) {
self.global(key)
}
if (opt.boolean || opt.type === 'boolean') {
self.boolean(key)
if (opt.alias) self.boolean(opt.alias)
}
if (opt.array || opt.type === 'array') {
self.array(key)
if (opt.alias) self.array(opt.alias)
}
if (opt.number || opt.type === 'number') {
self.number(key)
if (opt.alias) self.number(opt.alias)
}
if (opt.string || opt.type === 'string') {
self.string(key)
if (opt.alias) self.string(opt.alias)
}
if (opt.count || opt.type === 'count') {
self.count(key)
}
if (opt.defaultDescription) {
options.defaultDescription[key] = opt.defaultDescription
}
if (opt.skipValidation) {
self.skipValidation(key)
}
var desc = opt.describe || opt.description || opt.desc
if (desc) {
self.describe(key, desc)
}
if (opt.requiresArg) {
self.requiresArg(key)
}
}
return self
}
self.getOptions = function () {
return options
}
self.group = function (opts, groupName) {
var existing = preservedGroups[groupName] || groups[groupName]
if (preservedGroups[groupName]) {
// the preserved group will be moved to the set of explicitly declared
// groups
delete preservedGroups[groupName]
}
var seen = {}
groups[groupName] = (existing || []).concat(opts).filter(function (key) {
if (seen[key]) return false
return (seen[key] = true)
})
return self
}
self.getGroups = function () {
// combine explicit and preserved groups. explicit groups should be first
return assign(groups, preservedGroups)
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
self.env = function (prefix) {
if (prefix === false) options.envPrefix = undefined
else options.envPrefix = prefix || ''
return self
}
self.wrap = function (cols) {
usage.wrap(cols)
return self
}
var strict = false
self.strict = function () {
strict = true
return self
}
self.getStrict = function () {
return strict
}
self.showHelp = function (level) {
if (!self.parsed) parseArgs(processArgs) // run parser, if it has not already been executed.
usage.showHelp(level)
return self
}
var versionOpt = null
self.version = function (opt, msg, ver) {
if (arguments.length === 0) {
ver = guessVersion()
opt = 'version'
} else if (arguments.length === 1) {
ver = opt
opt = 'version'
} else if (arguments.length === 2) {
ver = msg
}
versionOpt = opt
msg = msg || usage.deferY18nLookup('Show version number')
usage.version(ver || undefined)
self.boolean(versionOpt)
self.global(versionOpt)
self.describe(versionOpt, msg)
return self
}
function guessVersion () {
var obj = pkgUp()
return obj.version || 'unknown'
}
var helpOpt = null
var useHelpOptAsCommand = false // a call to .help() will enable this
self.addHelpOpt = self.help = function (opt, msg, addImplicitCmd) {
// argument shuffle
if (arguments.length === 0) {
useHelpOptAsCommand = true
} else if (arguments.length === 1) {
if (typeof opt === 'boolean') {
useHelpOptAsCommand = opt
opt = null
} else {
useHelpOptAsCommand = true
}
} else if (arguments.length === 2) {
if (typeof msg === 'boolean') {
useHelpOptAsCommand = msg
msg = null
} else {
useHelpOptAsCommand = true
}
} else {
useHelpOptAsCommand = Boolean(addImplicitCmd)
}
// use arguments, fallback to defaults for opt and msg
helpOpt = opt || 'help'
self.boolean(helpOpt)
self.global(helpOpt)
self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'))
return self
}
self.showHelpOnFail = function (enabled, message) {
usage.showHelpOnFail(enabled, message)
return self
}
var exitProcess = true
self.exitProcess = function (enabled) {
if (typeof enabled !== 'boolean') {
enabled = true
}
exitProcess = enabled
return self
}
self.getExitProcess = function () {
return exitProcess
}
var completionCommand = null
self.completion = function (cmd, desc, fn) {
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc
desc = null
}
// register the completion command.
completionCommand = cmd || 'completion'
if (!desc && desc !== false) {
desc = 'generate bash completion script'
}
self.command(completionCommand, desc)
// a function can be provided
if (fn) completion.registerFunction(fn)
return self
}
self.showCompletionScript = function ($0) {
$0 = $0 || self.$0
_logger.log(completion.generateCompletionScript($0))
return self
}
self.getCompletion = function (args, done) {
completion.getCompletion(args, done)
}
self.locale = function (locale) {
if (arguments.length === 0) {
guessLocale()
return y18n.getLocale()
}
detectLocale = false
y18n.setLocale(locale)
return self
}
self.updateStrings = self.updateLocale = function (obj) {
detectLocale = false
y18n.updateLocale(obj)
return self
}
var detectLocale = true
self.detectLocale = function (detect) {
detectLocale = detect
return self
}
self.getDetectLocale = function () {
return detectLocale
}
var hasOutput = false
var exitError = null
// maybe exit, always capture
// context about why we wanted to exit.
self.exit = function (code, err) {
hasOutput = true
exitError = err
if (exitProcess) process.exit(code)
}
// we use a custom logger that buffers output,
// so that we can print to non-CLIs, e.g., chat-bots.
var _logger = {
log: function () {
var args = Array.prototype.slice.call(arguments)
if (!self._hasParseCallback()) console.log.apply(console, args)
hasOutput = true
if (output.length) output += '\n'
output += args.join(' ')
},
error: function () {
var args = Array.prototype.slice.call(arguments)
if (!self._hasParseCallback()) console.error.apply(console, args)
hasOutput = true
if (output.length) output += '\n'
output += args.join(' ')
}
}
self._getLoggerInstance = function () {
return _logger
}
// has yargs output an error our help
// message in the current execution context.
self._hasOutput = function () {
return hasOutput
}
var recommendCommands
self.recommendCommands = function () {
recommendCommands = true
return self
}
self.getUsageInstance = function () {
return usage
}
self.getValidationInstance = function () {
return validation
}
self.getCommandInstance = function () {
return command
}
self.terminalWidth = function () {
return process.stdout.columns
}
Object.defineProperty(self, 'argv', {
get: function () {
var args = null
try {
args = parseArgs(processArgs)
} catch (err) {
usage.fail(err.message, err)
}
return args
},
enumerable: true
})
function parseArgs (args, shortCircuit) {
options.__ = y18n.__
options.configuration = pkgUp()['yargs'] || {}
const parsed = Parser.detailed(args, options)
var argv = parsed.argv
if (parseContext) argv = assign(parseContext, argv)
var aliases = parsed.aliases
argv.$0 = self.$0
self.parsed = parsed
guessLocale() // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return argv
}
if (argv._.length) {
// check for helpOpt in argv._ before running commands
// assumes helpOpt must be valid if useHelpOptAsCommand is true
if (useHelpOptAsCommand) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
var helpCmds = [helpOpt].concat(aliases[helpOpt])
var multiCharHelpCmds = helpCmds.filter(function (k) {
return k.length > 1
})
if (multiCharHelpCmds.length) helpCmds = multiCharHelpCmds
// look for and strip any helpCmds from argv._
argv._ = argv._.filter(function (cmd) {
if (~helpCmds.indexOf(cmd)) {
argv[helpOpt] = true
return false
}
return true
})
}
// if there's a handler associated with a
// command defer processing to it.
var handlerKeys = command.getCommands()
if (handlerKeys.length) {
var firstUnknownCommand
for (var i = 0, cmd; (cmd = argv._[i]) !== undefined; i++) {
if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
setPlaceholderKeys(argv)
return command.runCommand(cmd, self, parsed)
} else if (!firstUnknownCommand && cmd !== completionCommand) {
firstUnknownCommand = cmd
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (recommendCommands && firstUnknownCommand) {
validation.recommendCommands(firstUnknownCommand, handlerKeys)
}
}
// generate a completion script for adding to ~/.bashrc.
if (completionCommand && ~argv._.indexOf(completionCommand) && !argv[completion.completionKey]) {
if (exitProcess) setBlocking(true)
self.showCompletionScript()
self.exit(0)
}
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (completion.completionKey in argv) {
if (exitProcess) setBlocking(true)
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
var completionArgs = args.slice(args.indexOf('--' + completion.completionKey) + 1)
completion.getCompletion(completionArgs, function (completions) {
;(completions || []).forEach(function (completion) {
_logger.log(completion)
})
self.exit(0)
})
return setPlaceholderKeys(argv)
}
var skipValidation = false
// Handle 'help' and 'version' options
Object.keys(argv).forEach(function (key) {
if (key === helpOpt && argv[key]) {
if (exitProcess) setBlocking(true)
skipValidation = true
self.showHelp('log')
self.exit(0)
} else if (key === versionOpt && argv[key]) {
if (exitProcess) setBlocking(true)
skipValidation = true
usage.showVersion()
self.exit(0)
}
})
// Check if any of the options to skip validation were provided
if (!skipValidation && options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(function (key) {
return options.skipValidation.indexOf(key) >= 0 && argv[key] === true
})
}
// If the help or version options where used and exitProcess is false,
// or if explicitly skipped, we won't run validations
if (!skipValidation) {
if (parsed.error) throw parsed.error
// if we're executed via bash completion, don't
// bother with validation.
if (!argv[completion.completionKey]) {
validation.nonOptionCount(argv)
validation.missingArgumentValue(argv)
validation.requiredArguments(argv)
if (strict) validation.unknownArguments(argv, aliases)
validation.customChecks(argv, aliases)
validation.limitedChoices(argv)
validation.implications(argv)
validation.conflicting(argv)
}
}
return setPlaceholderKeys(argv)
}
function guessLocale () {
if (!detectLocale) return
try {
const osLocale = require('os-locale')
self.locale(osLocale.sync({ spawn: false }))
} catch (err) {
// if we explode looking up locale just noop
// we'll keep using the default language 'en'.
}
}
function setPlaceholderKeys (argv) {
Object.keys(options.key).forEach(function (key) {
// don't set placeholder keys for dot
// notation options 'foo.bar'.
if (~key.indexOf('.')) return
if (typeof argv[key] === 'undefined') argv[key] = undefined
})
return argv
}
return self
}
// rebase an absolute path to a relative one with respect to a base directory
// exported for tests
exports.rebase = rebase
function rebase (base, dir) {
return path.relative(base, dir)
}
|