1 |
3a515b92
|
cagy
|
'use strict'
|
2 |
|
|
const argsert = require('./lib/argsert')
|
3 |
|
|
const fs = require('fs')
|
4 |
|
|
const Command = require('./lib/command')
|
5 |
|
|
const Completion = require('./lib/completion')
|
6 |
|
|
const Parser = require('yargs-parser')
|
7 |
|
|
const path = require('path')
|
8 |
|
|
const Usage = require('./lib/usage')
|
9 |
|
|
const Validation = require('./lib/validation')
|
10 |
|
|
const Y18n = require('y18n')
|
11 |
|
|
const objFilter = require('./lib/obj-filter')
|
12 |
|
|
const setBlocking = require('set-blocking')
|
13 |
|
|
const applyExtends = require('./lib/apply-extends')
|
14 |
|
|
const middlewareFactory = require('./lib/middleware')
|
15 |
|
|
const YError = require('./lib/yerror')
|
16 |
|
|
|
17 |
|
|
exports = module.exports = Yargs
|
18 |
|
|
function Yargs (processArgs, cwd, parentRequire) {
|
19 |
|
|
processArgs = processArgs || [] // handle calling yargs().
|
20 |
|
|
|
21 |
|
|
const self = {}
|
22 |
|
|
let command = null
|
23 |
|
|
let completion = null
|
24 |
|
|
let groups = {}
|
25 |
|
|
let globalMiddleware = []
|
26 |
|
|
let output = ''
|
27 |
|
|
let preservedGroups = {}
|
28 |
|
|
let usage = null
|
29 |
|
|
let validation = null
|
30 |
|
|
|
31 |
|
|
const y18n = Y18n({
|
32 |
|
|
directory: path.resolve(__dirname, './locales'),
|
33 |
|
|
updateFiles: false
|
34 |
|
|
})
|
35 |
|
|
|
36 |
|
|
self.middleware = middlewareFactory(globalMiddleware, self)
|
37 |
|
|
|
38 |
|
|
if (!cwd) cwd = process.cwd()
|
39 |
|
|
|
40 |
|
|
self.scriptName = function scriptName (scriptName) {
|
41 |
|
|
self.$0 = scriptName
|
42 |
|
|
return self
|
43 |
|
|
}
|
44 |
|
|
|
45 |
|
|
// ignore the node bin, specify this in your
|
46 |
|
|
// bin file with #!/usr/bin/env node
|
47 |
|
|
if (/\b(node|iojs|electron)(\.exe)?$/.test(process.argv[0])) {
|
48 |
|
|
self.$0 = process.argv.slice(1, 2)
|
49 |
|
|
} else {
|
50 |
|
|
self.$0 = process.argv.slice(0, 1)
|
51 |
|
|
}
|
52 |
|
|
|
53 |
|
|
self.$0 = self.$0
|
54 |
|
|
.map((x, i) => {
|
55 |
|
|
const b = rebase(cwd, x)
|
56 |
|
|
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x
|
57 |
|
|
})
|
58 |
|
|
.join(' ').trim()
|
59 |
|
|
|
60 |
|
|
if (process.env._ !== undefined && process.argv[1] === process.env._) {
|
61 |
|
|
self.$0 = process.env._.replace(
|
62 |
|
|
`${path.dirname(process.execPath)}/`, ''
|
63 |
|
|
)
|
64 |
|
|
}
|
65 |
|
|
|
66 |
|
|
// use context object to keep track of resets, subcommand execution, etc
|
67 |
|
|
// submodules should modify and check the state of context as necessary
|
68 |
|
|
const context = { resets: -1, commands: [], fullCommands: [], files: [] }
|
69 |
|
|
self.getContext = () => context
|
70 |
|
|
|
71 |
|
|
// puts yargs back into an initial state. any keys
|
72 |
|
|
// that have been set to "global" will not be reset
|
73 |
|
|
// by this action.
|
74 |
|
|
let options
|
75 |
|
|
self.resetOptions = self.reset = function resetOptions (aliases) {
|
76 |
|
|
context.resets++
|
77 |
|
|
aliases = aliases || {}
|
78 |
|
|
options = options || {}
|
79 |
|
|
// put yargs back into an initial state, this
|
80 |
|
|
// logic is used to build a nested command
|
81 |
|
|
// hierarchy.
|
82 |
|
|
const tmpOptions = {}
|
83 |
|
|
tmpOptions.local = options.local ? options.local : []
|
84 |
|
|
tmpOptions.configObjects = options.configObjects ? options.configObjects : []
|
85 |
|
|
|
86 |
|
|
// if a key has been explicitly set as local,
|
87 |
|
|
// we should reset it before passing options to command.
|
88 |
|
|
const localLookup = {}
|
89 |
|
|
tmpOptions.local.forEach((l) => {
|
90 |
|
|
localLookup[l] = true
|
91 |
|
|
;(aliases[l] || []).forEach((a) => {
|
92 |
|
|
localLookup[a] = true
|
93 |
|
|
})
|
94 |
|
|
})
|
95 |
|
|
|
96 |
|
|
// preserve all groups not set to local.
|
97 |
|
|
preservedGroups = Object.keys(groups).reduce((acc, groupName) => {
|
98 |
|
|
const keys = groups[groupName].filter(key => !(key in localLookup))
|
99 |
|
|
if (keys.length > 0) {
|
100 |
|
|
acc[groupName] = keys
|
101 |
|
|
}
|
102 |
|
|
return acc
|
103 |
|
|
}, {})
|
104 |
|
|
// groups can now be reset
|
105 |
|
|
groups = {}
|
106 |
|
|
|
107 |
|
|
const arrayOptions = [
|
108 |
|
|
'array', 'boolean', 'string', 'skipValidation',
|
109 |
|
|
'count', 'normalize', 'number',
|
110 |
|
|
'hiddenOptions'
|
111 |
|
|
]
|
112 |
|
|
|
113 |
|
|
const objectOptions = [
|
114 |
|
|
'narg', 'key', 'alias', 'default', 'defaultDescription',
|
115 |
|
|
'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
|
116 |
|
|
]
|
117 |
|
|
|
118 |
|
|
arrayOptions.forEach((k) => {
|
119 |
|
|
tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k])
|
120 |
|
|
})
|
121 |
|
|
|
122 |
|
|
objectOptions.forEach((k) => {
|
123 |
|
|
tmpOptions[k] = objFilter(options[k], (k, v) => !localLookup[k])
|
124 |
|
|
})
|
125 |
|
|
|
126 |
|
|
tmpOptions.envPrefix = options.envPrefix
|
127 |
|
|
options = tmpOptions
|
128 |
|
|
|
129 |
|
|
// if this is the first time being executed, create
|
130 |
|
|
// instances of all our helpers -- otherwise just reset.
|
131 |
|
|
usage = usage ? usage.reset(localLookup) : Usage(self, y18n)
|
132 |
|
|
validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n)
|
133 |
|
|
command = command ? command.reset() : Command(self, usage, validation, globalMiddleware)
|
134 |
|
|
if (!completion) completion = Completion(self, usage, command)
|
135 |
|
|
|
136 |
|
|
completionCommand = null
|
137 |
|
|
output = ''
|
138 |
|
|
exitError = null
|
139 |
|
|
hasOutput = false
|
140 |
|
|
self.parsed = false
|
141 |
|
|
|
142 |
|
|
return self
|
143 |
|
|
}
|
144 |
|
|
self.resetOptions()
|
145 |
|
|
|
146 |
|
|
// temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
|
147 |
|
|
let frozen
|
148 |
|
|
function freeze () {
|
149 |
|
|
frozen = {}
|
150 |
|
|
frozen.options = options
|
151 |
|
|
frozen.configObjects = options.configObjects.slice(0)
|
152 |
|
|
frozen.exitProcess = exitProcess
|
153 |
|
|
frozen.groups = groups
|
154 |
|
|
usage.freeze()
|
155 |
|
|
validation.freeze()
|
156 |
|
|
command.freeze()
|
157 |
|
|
frozen.strict = strict
|
158 |
|
|
frozen.completionCommand = completionCommand
|
159 |
|
|
frozen.output = output
|
160 |
|
|
frozen.exitError = exitError
|
161 |
|
|
frozen.hasOutput = hasOutput
|
162 |
|
|
frozen.parsed = self.parsed
|
163 |
|
|
}
|
164 |
|
|
function unfreeze () {
|
165 |
|
|
options = frozen.options
|
166 |
|
|
options.configObjects = frozen.configObjects
|
167 |
|
|
exitProcess = frozen.exitProcess
|
168 |
|
|
groups = frozen.groups
|
169 |
|
|
output = frozen.output
|
170 |
|
|
exitError = frozen.exitError
|
171 |
|
|
hasOutput = frozen.hasOutput
|
172 |
|
|
self.parsed = frozen.parsed
|
173 |
|
|
usage.unfreeze()
|
174 |
|
|
validation.unfreeze()
|
175 |
|
|
command.unfreeze()
|
176 |
|
|
strict = frozen.strict
|
177 |
|
|
completionCommand = frozen.completionCommand
|
178 |
|
|
parseFn = null
|
179 |
|
|
parseContext = null
|
180 |
|
|
frozen = undefined
|
181 |
|
|
}
|
182 |
|
|
|
183 |
|
|
self.boolean = function (keys) {
|
184 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
185 |
|
|
populateParserHintArray('boolean', keys)
|
186 |
|
|
return self
|
187 |
|
|
}
|
188 |
|
|
|
189 |
|
|
self.array = function (keys) {
|
190 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
191 |
|
|
populateParserHintArray('array', keys)
|
192 |
|
|
return self
|
193 |
|
|
}
|
194 |
|
|
|
195 |
|
|
self.number = function (keys) {
|
196 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
197 |
|
|
populateParserHintArray('number', keys)
|
198 |
|
|
return self
|
199 |
|
|
}
|
200 |
|
|
|
201 |
|
|
self.normalize = function (keys) {
|
202 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
203 |
|
|
populateParserHintArray('normalize', keys)
|
204 |
|
|
return self
|
205 |
|
|
}
|
206 |
|
|
|
207 |
|
|
self.count = function (keys) {
|
208 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
209 |
|
|
populateParserHintArray('count', keys)
|
210 |
|
|
return self
|
211 |
|
|
}
|
212 |
|
|
|
213 |
|
|
self.string = function (keys) {
|
214 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
215 |
|
|
populateParserHintArray('string', keys)
|
216 |
|
|
return self
|
217 |
|
|
}
|
218 |
|
|
|
219 |
|
|
self.requiresArg = function (keys) {
|
220 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
221 |
|
|
populateParserHintObject(self.nargs, false, 'narg', keys, 1)
|
222 |
|
|
return self
|
223 |
|
|
}
|
224 |
|
|
|
225 |
|
|
self.skipValidation = function (keys) {
|
226 |
|
|
argsert('<array|string>', [keys], arguments.length)
|
227 |
|
|
populateParserHintArray('skipValidation', keys)
|
228 |
|
|
return self
|
229 |
|
|
}
|
230 |
|
|
|
231 |
|
|
function populateParserHintArray (type, keys, value) {
|
232 |
|
|
keys = [].concat(keys)
|
233 |
|
|
keys.forEach((key) => {
|
234 |
|
|
options[type].push(key)
|
235 |
|
|
})
|
236 |
|
|
}
|
237 |
|
|
|
238 |
|
|
self.nargs = function (key, value) {
|
239 |
|
|
argsert('<string|object|array> [number]', [key, value], arguments.length)
|
240 |
|
|
populateParserHintObject(self.nargs, false, 'narg', key, value)
|
241 |
|
|
return self
|
242 |
|
|
}
|
243 |
|
|
|
244 |
|
|
self.choices = function (key, value) {
|
245 |
|
|
argsert('<object|string|array> [string|array]', [key, value], arguments.length)
|
246 |
|
|
populateParserHintObject(self.choices, true, 'choices', key, value)
|
247 |
|
|
return self
|
248 |
|
|
}
|
249 |
|
|
|
250 |
|
|
self.alias = function (key, value) {
|
251 |
|
|
argsert('<object|string|array> [string|array]', [key, value], arguments.length)
|
252 |
|
|
populateParserHintObject(self.alias, true, 'alias', key, value)
|
253 |
|
|
return self
|
254 |
|
|
}
|
255 |
|
|
|
256 |
|
|
// TODO: actually deprecate self.defaults.
|
257 |
|
|
self.default = self.defaults = function (key, value, defaultDescription) {
|
258 |
|
|
argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length)
|
259 |
|
|
if (defaultDescription) options.defaultDescription[key] = defaultDescription
|
260 |
|
|
if (typeof value === 'function') {
|
261 |
|
|
if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value)
|
262 |
|
|
value = value.call()
|
263 |
|
|
}
|
264 |
|
|
populateParserHintObject(self.default, false, 'default', key, value)
|
265 |
|
|
return self
|
266 |
|
|
}
|
267 |
|
|
|
268 |
|
|
self.describe = function (key, desc) {
|
269 |
|
|
argsert('<object|string|array> [string]', [key, desc], arguments.length)
|
270 |
|
|
populateParserHintObject(self.describe, false, 'key', key, true)
|
271 |
|
|
usage.describe(key, desc)
|
272 |
|
|
return self
|
273 |
|
|
}
|
274 |
|
|
|
275 |
|
|
self.demandOption = function (keys, msg) {
|
276 |
|
|
argsert('<object|string|array> [string]', [keys, msg], arguments.length)
|
277 |
|
|
populateParserHintObject(self.demandOption, false, 'demandedOptions', keys, msg)
|
278 |
|
|
return self
|
279 |
|
|
}
|
280 |
|
|
|
281 |
|
|
self.coerce = function (keys, value) {
|
282 |
|
|
argsert('<object|string|array> [function]', [keys, value], arguments.length)
|
283 |
|
|
populateParserHintObject(self.coerce, false, 'coerce', keys, value)
|
284 |
|
|
return self
|
285 |
|
|
}
|
286 |
|
|
|
287 |
|
|
function populateParserHintObject (builder, isArray, type, key, value) {
|
288 |
|
|
if (Array.isArray(key)) {
|
289 |
|
|
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
|
290 |
|
|
const temp = {}
|
291 |
|
|
key.forEach((k) => {
|
292 |
|
|
temp[k] = value
|
293 |
|
|
})
|
294 |
|
|
builder(temp)
|
295 |
|
|
} else if (typeof key === 'object') {
|
296 |
|
|
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
|
297 |
|
|
Object.keys(key).forEach((k) => {
|
298 |
|
|
builder(k, key[k])
|
299 |
|
|
})
|
300 |
|
|
} else {
|
301 |
|
|
// a single key value pair 'x', parse() {}
|
302 |
|
|
if (isArray) {
|
303 |
|
|
options[type][key] = (options[type][key] || []).concat(value)
|
304 |
|
|
} else {
|
305 |
|
|
options[type][key] = value
|
306 |
|
|
}
|
307 |
|
|
}
|
308 |
|
|
}
|
309 |
|
|
|
310 |
|
|
function deleteFromParserHintObject (optionKey) {
|
311 |
|
|
// delete from all parsing hints:
|
312 |
|
|
// boolean, array, key, alias, etc.
|
313 |
|
|
Object.keys(options).forEach((hintKey) => {
|
314 |
|
|
const hint = options[hintKey]
|
315 |
|
|
if (Array.isArray(hint)) {
|
316 |
|
|
if (~hint.indexOf(optionKey)) hint.splice(hint.indexOf(optionKey), 1)
|
317 |
|
|
} else if (typeof hint === 'object') {
|
318 |
|
|
delete hint[optionKey]
|
319 |
|
|
}
|
320 |
|
|
})
|
321 |
|
|
// now delete the description from usage.js.
|
322 |
|
|
delete usage.getDescriptions()[optionKey]
|
323 |
|
|
}
|
324 |
|
|
|
325 |
|
|
self.config = function config (key, msg, parseFn) {
|
326 |
|
|
argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length)
|
327 |
|
|
// allow a config object to be provided directly.
|
328 |
|
|
if (typeof key === 'object') {
|
329 |
|
|
key = applyExtends(key, cwd)
|
330 |
|
|
options.configObjects = (options.configObjects || []).concat(key)
|
331 |
|
|
return self
|
332 |
|
|
}
|
333 |
|
|
|
334 |
|
|
// allow for a custom parsing function.
|
335 |
|
|
if (typeof msg === 'function') {
|
336 |
|
|
parseFn = msg
|
337 |
|
|
msg = null
|
338 |
|
|
}
|
339 |
|
|
|
340 |
|
|
key = key || 'config'
|
341 |
|
|
self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'))
|
342 |
|
|
;(Array.isArray(key) ? key : [key]).forEach((k) => {
|
343 |
|
|
options.config[k] = parseFn || true
|
344 |
|
|
})
|
345 |
|
|
|
346 |
|
|
return self
|
347 |
|
|
}
|
348 |
|
|
|
349 |
|
|
self.example = function (cmd, description) {
|
350 |
|
|
argsert('<string> [string]', [cmd, description], arguments.length)
|
351 |
|
|
usage.example(cmd, description)
|
352 |
|
|
return self
|
353 |
|
|
}
|
354 |
|
|
|
355 |
|
|
self.command = function (cmd, description, builder, handler, middlewares) {
|
356 |
|
|
argsert('<string|array|object> [string|boolean] [function|object] [function] [array]', [cmd, description, builder, handler, middlewares], arguments.length)
|
357 |
|
|
command.addHandler(cmd, description, builder, handler, middlewares)
|
358 |
|
|
return self
|
359 |
|
|
}
|
360 |
|
|
|
361 |
|
|
self.commandDir = function (dir, opts) {
|
362 |
|
|
argsert('<string> [object]', [dir, opts], arguments.length)
|
363 |
|
|
const req = parentRequire || require
|
364 |
|
|
command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts)
|
365 |
|
|
return self
|
366 |
|
|
}
|
367 |
|
|
|
368 |
|
|
// TODO: deprecate self.demand in favor of
|
369 |
|
|
// .demandCommand() .demandOption().
|
370 |
|
|
self.demand = self.required = self.require = function demand (keys, max, msg) {
|
371 |
|
|
// you can optionally provide a 'max' key,
|
372 |
|
|
// which will raise an exception if too many '_'
|
373 |
|
|
// options are provided.
|
374 |
|
|
if (Array.isArray(max)) {
|
375 |
|
|
max.forEach((key) => {
|
376 |
|
|
self.demandOption(key, msg)
|
377 |
|
|
})
|
378 |
|
|
max = Infinity
|
379 |
|
|
} else if (typeof max !== 'number') {
|
380 |
|
|
msg = max
|
381 |
|
|
max = Infinity
|
382 |
|
|
}
|
383 |
|
|
|
384 |
|
|
if (typeof keys === 'number') {
|
385 |
|
|
self.demandCommand(keys, max, msg, msg)
|
386 |
|
|
} else if (Array.isArray(keys)) {
|
387 |
|
|
keys.forEach((key) => {
|
388 |
|
|
self.demandOption(key, msg)
|
389 |
|
|
})
|
390 |
|
|
} else {
|
391 |
|
|
if (typeof msg === 'string') {
|
392 |
|
|
self.demandOption(keys, msg)
|
393 |
|
|
} else if (msg === true || typeof msg === 'undefined') {
|
394 |
|
|
self.demandOption(keys)
|
395 |
|
|
}
|
396 |
|
|
}
|
397 |
|
|
|
398 |
|
|
return self
|
399 |
|
|
}
|
400 |
|
|
|
401 |
|
|
self.demandCommand = function demandCommand (min, max, minMsg, maxMsg) {
|
402 |
|
|
argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length)
|
403 |
|
|
|
404 |
|
|
if (typeof min === 'undefined') min = 1
|
405 |
|
|
|
406 |
|
|
if (typeof max !== 'number') {
|
407 |
|
|
minMsg = max
|
408 |
|
|
max = Infinity
|
409 |
|
|
}
|
410 |
|
|
|
411 |
|
|
self.global('_', false)
|
412 |
|
|
|
413 |
|
|
options.demandedCommands._ = {
|
414 |
|
|
min,
|
415 |
|
|
max,
|
416 |
|
|
minMsg,
|
417 |
|
|
maxMsg
|
418 |
|
|
}
|
419 |
|
|
|
420 |
|
|
return self
|
421 |
|
|
}
|
422 |
|
|
|
423 |
|
|
self.getDemandedOptions = () => {
|
424 |
|
|
argsert([], 0)
|
425 |
|
|
return options.demandedOptions
|
426 |
|
|
}
|
427 |
|
|
|
428 |
|
|
self.getDemandedCommands = () => {
|
429 |
|
|
argsert([], 0)
|
430 |
|
|
return options.demandedCommands
|
431 |
|
|
}
|
432 |
|
|
|
433 |
|
|
self.implies = function (key, value) {
|
434 |
|
|
argsert('<string|object> [number|string|array]', [key, value], arguments.length)
|
435 |
|
|
validation.implies(key, value)
|
436 |
|
|
return self
|
437 |
|
|
}
|
438 |
|
|
|
439 |
|
|
self.conflicts = function (key1, key2) {
|
440 |
|
|
argsert('<string|object> [string|array]', [key1, key2], arguments.length)
|
441 |
|
|
validation.conflicts(key1, key2)
|
442 |
|
|
return self
|
443 |
|
|
}
|
444 |
|
|
|
445 |
|
|
self.usage = function (msg, description, builder, handler) {
|
446 |
|
|
argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length)
|
447 |
|
|
|
448 |
|
|
if (description !== undefined) {
|
449 |
|
|
// .usage() can be used as an alias for defining
|
450 |
|
|
// a default command.
|
451 |
|
|
if ((msg || '').match(/^\$0( |$)/)) {
|
452 |
|
|
return self.command(msg, description, builder, handler)
|
453 |
|
|
} else {
|
454 |
|
|
throw new YError('.usage() description must start with $0 if being used as alias for .command()')
|
455 |
|
|
}
|
456 |
|
|
} else {
|
457 |
|
|
usage.usage(msg)
|
458 |
|
|
return self
|
459 |
|
|
}
|
460 |
|
|
}
|
461 |
|
|
|
462 |
|
|
self.epilogue = self.epilog = function (msg) {
|
463 |
|
|
argsert('<string>', [msg], arguments.length)
|
464 |
|
|
usage.epilog(msg)
|
465 |
|
|
return self
|
466 |
|
|
}
|
467 |
|
|
|
468 |
|
|
self.fail = function (f) {
|
469 |
|
|
argsert('<function>', [f], arguments.length)
|
470 |
|
|
usage.failFn(f)
|
471 |
|
|
return self
|
472 |
|
|
}
|
473 |
|
|
|
474 |
|
|
self.check = function (f, _global) {
|
475 |
|
|
argsert('<function> [boolean]', [f, _global], arguments.length)
|
476 |
|
|
validation.check(f, _global !== false)
|
477 |
|
|
return self
|
478 |
|
|
}
|
479 |
|
|
|
480 |
|
|
self.global = function global (globals, global) {
|
481 |
|
|
argsert('<string|array> [boolean]', [globals, global], arguments.length)
|
482 |
|
|
globals = [].concat(globals)
|
483 |
|
|
if (global !== false) {
|
484 |
|
|
options.local = options.local.filter(l => globals.indexOf(l) === -1)
|
485 |
|
|
} else {
|
486 |
|
|
globals.forEach((g) => {
|
487 |
|
|
if (options.local.indexOf(g) === -1) options.local.push(g)
|
488 |
|
|
})
|
489 |
|
|
}
|
490 |
|
|
return self
|
491 |
|
|
}
|
492 |
|
|
|
493 |
|
|
self.pkgConf = function pkgConf (key, rootPath) {
|
494 |
|
|
argsert('<string> [string]', [key, rootPath], arguments.length)
|
495 |
|
|
let conf = null
|
496 |
|
|
// prefer cwd to require-main-filename in this method
|
497 |
|
|
// since we're looking for e.g. "nyc" config in nyc consumer
|
498 |
|
|
// rather than "yargs" config in nyc (where nyc is the main filename)
|
499 |
|
|
const obj = pkgUp(rootPath || cwd)
|
500 |
|
|
|
501 |
|
|
// If an object exists in the key, add it to options.configObjects
|
502 |
|
|
if (obj[key] && typeof obj[key] === 'object') {
|
503 |
|
|
conf = applyExtends(obj[key], rootPath || cwd)
|
504 |
|
|
options.configObjects = (options.configObjects || []).concat(conf)
|
505 |
|
|
}
|
506 |
|
|
|
507 |
|
|
return self
|
508 |
|
|
}
|
509 |
|
|
|
510 |
|
|
const pkgs = {}
|
511 |
|
|
function pkgUp (rootPath) {
|
512 |
|
|
const npath = rootPath || '*'
|
513 |
|
|
if (pkgs[npath]) return pkgs[npath]
|
514 |
|
|
const findUp = require('find-up')
|
515 |
|
|
|
516 |
|
|
let obj = {}
|
517 |
|
|
try {
|
518 |
|
|
let startDir = rootPath || require('require-main-filename')(parentRequire || require)
|
519 |
|
|
|
520 |
|
|
// When called in an environment that lacks require.main.filename, such as a jest test runner,
|
521 |
|
|
// startDir is already process.cwd(), and should not be shortened.
|
522 |
|
|
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
|
523 |
|
|
if (!rootPath && path.extname(startDir)) {
|
524 |
|
|
startDir = path.dirname(startDir)
|
525 |
|
|
}
|
526 |
|
|
|
527 |
|
|
const pkgJsonPath = findUp.sync('package.json', {
|
528 |
|
|
cwd: startDir
|
529 |
|
|
})
|
530 |
|
|
obj = JSON.parse(fs.readFileSync(pkgJsonPath))
|
531 |
|
|
} catch (noop) {}
|
532 |
|
|
|
533 |
|
|
pkgs[npath] = obj || {}
|
534 |
|
|
return pkgs[npath]
|
535 |
|
|
}
|
536 |
|
|
|
537 |
|
|
let parseFn = null
|
538 |
|
|
let parseContext = null
|
539 |
|
|
self.parse = function parse (args, shortCircuit, _parseFn) {
|
540 |
|
|
argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length)
|
541 |
|
|
if (typeof args === 'undefined') {
|
542 |
|
|
return self._parseArgs(processArgs)
|
543 |
|
|
}
|
544 |
|
|
|
545 |
|
|
// a context object can optionally be provided, this allows
|
546 |
|
|
// additional information to be passed to a command handler.
|
547 |
|
|
if (typeof shortCircuit === 'object') {
|
548 |
|
|
parseContext = shortCircuit
|
549 |
|
|
shortCircuit = _parseFn
|
550 |
|
|
}
|
551 |
|
|
|
552 |
|
|
// by providing a function as a second argument to
|
553 |
|
|
// parse you can capture output that would otherwise
|
554 |
|
|
// default to printing to stdout/stderr.
|
555 |
|
|
if (typeof shortCircuit === 'function') {
|
556 |
|
|
parseFn = shortCircuit
|
557 |
|
|
shortCircuit = null
|
558 |
|
|
}
|
559 |
|
|
// completion short-circuits the parsing process,
|
560 |
|
|
// skipping validation, etc.
|
561 |
|
|
if (!shortCircuit) processArgs = args
|
562 |
|
|
|
563 |
|
|
freeze()
|
564 |
|
|
if (parseFn) exitProcess = false
|
565 |
|
|
|
566 |
|
|
const parsed = self._parseArgs(args, shortCircuit)
|
567 |
|
|
if (parseFn) parseFn(exitError, parsed, output)
|
568 |
|
|
unfreeze()
|
569 |
|
|
|
570 |
|
|
return parsed
|
571 |
|
|
}
|
572 |
|
|
|
573 |
|
|
self._getParseContext = () => parseContext || {}
|
574 |
|
|
|
575 |
|
|
self._hasParseCallback = () => !!parseFn
|
576 |
|
|
|
577 |
|
|
self.option = self.options = function option (key, opt) {
|
578 |
|
|
argsert('<string|object> [object]', [key, opt], arguments.length)
|
579 |
|
|
if (typeof key === 'object') {
|
580 |
|
|
Object.keys(key).forEach((k) => {
|
581 |
|
|
self.options(k, key[k])
|
582 |
|
|
})
|
583 |
|
|
} else {
|
584 |
|
|
if (typeof opt !== 'object') {
|
585 |
|
|
opt = {}
|
586 |
|
|
}
|
587 |
|
|
|
588 |
|
|
options.key[key] = true // track manually set keys.
|
589 |
|
|
|
590 |
|
|
if (opt.alias) self.alias(key, opt.alias)
|
591 |
|
|
|
592 |
|
|
const demand = opt.demand || opt.required || opt.require
|
593 |
|
|
|
594 |
|
|
// deprecated, use 'demandOption' instead
|
595 |
|
|
if (demand) {
|
596 |
|
|
self.demand(key, demand)
|
597 |
|
|
}
|
598 |
|
|
|
599 |
|
|
if (opt.demandOption) {
|
600 |
|
|
self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined)
|
601 |
|
|
}
|
602 |
|
|
|
603 |
|
|
if ('conflicts' in opt) {
|
604 |
|
|
self.conflicts(key, opt.conflicts)
|
605 |
|
|
}
|
606 |
|
|
|
607 |
|
|
if ('default' in opt) {
|
608 |
|
|
self.default(key, opt.default)
|
609 |
|
|
}
|
610 |
|
|
|
611 |
|
|
if ('implies' in opt) {
|
612 |
|
|
self.implies(key, opt.implies)
|
613 |
|
|
}
|
614 |
|
|
|
615 |
|
|
if ('nargs' in opt) {
|
616 |
|
|
self.nargs(key, opt.nargs)
|
617 |
|
|
}
|
618 |
|
|
|
619 |
|
|
if (opt.config) {
|
620 |
|
|
self.config(key, opt.configParser)
|
621 |
|
|
}
|
622 |
|
|
|
623 |
|
|
if (opt.normalize) {
|
624 |
|
|
self.normalize(key)
|
625 |
|
|
}
|
626 |
|
|
|
627 |
|
|
if ('choices' in opt) {
|
628 |
|
|
self.choices(key, opt.choices)
|
629 |
|
|
}
|
630 |
|
|
|
631 |
|
|
if ('coerce' in opt) {
|
632 |
|
|
self.coerce(key, opt.coerce)
|
633 |
|
|
}
|
634 |
|
|
|
635 |
|
|
if ('group' in opt) {
|
636 |
|
|
self.group(key, opt.group)
|
637 |
|
|
}
|
638 |
|
|
|
639 |
|
|
if (opt.boolean || opt.type === 'boolean') {
|
640 |
|
|
self.boolean(key)
|
641 |
|
|
if (opt.alias) self.boolean(opt.alias)
|
642 |
|
|
}
|
643 |
|
|
|
644 |
|
|
if (opt.array || opt.type === 'array') {
|
645 |
|
|
self.array(key)
|
646 |
|
|
if (opt.alias) self.array(opt.alias)
|
647 |
|
|
}
|
648 |
|
|
|
649 |
|
|
if (opt.number || opt.type === 'number') {
|
650 |
|
|
self.number(key)
|
651 |
|
|
if (opt.alias) self.number(opt.alias)
|
652 |
|
|
}
|
653 |
|
|
|
654 |
|
|
if (opt.string || opt.type === 'string') {
|
655 |
|
|
self.string(key)
|
656 |
|
|
if (opt.alias) self.string(opt.alias)
|
657 |
|
|
}
|
658 |
|
|
|
659 |
|
|
if (opt.count || opt.type === 'count') {
|
660 |
|
|
self.count(key)
|
661 |
|
|
}
|
662 |
|
|
|
663 |
|
|
if (typeof opt.global === 'boolean') {
|
664 |
|
|
self.global(key, opt.global)
|
665 |
|
|
}
|
666 |
|
|
|
667 |
|
|
if (opt.defaultDescription) {
|
668 |
|
|
options.defaultDescription[key] = opt.defaultDescription
|
669 |
|
|
}
|
670 |
|
|
|
671 |
|
|
if (opt.skipValidation) {
|
672 |
|
|
self.skipValidation(key)
|
673 |
|
|
}
|
674 |
|
|
|
675 |
|
|
const desc = opt.describe || opt.description || opt.desc
|
676 |
|
|
self.describe(key, desc)
|
677 |
|
|
if (opt.hidden) {
|
678 |
|
|
self.hide(key)
|
679 |
|
|
}
|
680 |
|
|
|
681 |
|
|
if (opt.requiresArg) {
|
682 |
|
|
self.requiresArg(key)
|
683 |
|
|
}
|
684 |
|
|
}
|
685 |
|
|
|
686 |
|
|
return self
|
687 |
|
|
}
|
688 |
|
|
self.getOptions = () => options
|
689 |
|
|
|
690 |
|
|
self.positional = function (key, opts) {
|
691 |
|
|
argsert('<string> <object>', [key, opts], arguments.length)
|
692 |
|
|
if (context.resets === 0) {
|
693 |
|
|
throw new YError(".positional() can only be called in a command's builder function")
|
694 |
|
|
}
|
695 |
|
|
|
696 |
|
|
// .positional() only supports a subset of the configuration
|
697 |
|
|
// options availble to .option().
|
698 |
|
|
const supportedOpts = ['default', 'implies', 'normalize',
|
699 |
|
|
'choices', 'conflicts', 'coerce', 'type', 'describe',
|
700 |
|
|
'desc', 'description', 'alias']
|
701 |
|
|
opts = objFilter(opts, (k, v) => {
|
702 |
|
|
let accept = supportedOpts.indexOf(k) !== -1
|
703 |
|
|
// type can be one of string|number|boolean.
|
704 |
|
|
if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1) accept = false
|
705 |
|
|
return accept
|
706 |
|
|
})
|
707 |
|
|
|
708 |
|
|
// copy over any settings that can be inferred from the command string.
|
709 |
|
|
const fullCommand = context.fullCommands[context.fullCommands.length - 1]
|
710 |
|
|
const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : {
|
711 |
|
|
array: [],
|
712 |
|
|
alias: {},
|
713 |
|
|
default: {},
|
714 |
|
|
demand: {}
|
715 |
|
|
}
|
716 |
|
|
Object.keys(parseOptions).forEach((pk) => {
|
717 |
|
|
if (Array.isArray(parseOptions[pk])) {
|
718 |
|
|
if (parseOptions[pk].indexOf(key) !== -1) opts[pk] = true
|
719 |
|
|
} else {
|
720 |
|
|
if (parseOptions[pk][key] && !(pk in opts)) opts[pk] = parseOptions[pk][key]
|
721 |
|
|
}
|
722 |
|
|
})
|
723 |
|
|
self.group(key, usage.getPositionalGroupName())
|
724 |
|
|
return self.option(key, opts)
|
725 |
|
|
}
|
726 |
|
|
|
727 |
|
|
self.group = function group (opts, groupName) {
|
728 |
|
|
argsert('<string|array> <string>', [opts, groupName], arguments.length)
|
729 |
|
|
const existing = preservedGroups[groupName] || groups[groupName]
|
730 |
|
|
if (preservedGroups[groupName]) {
|
731 |
|
|
// we now only need to track this group name in groups.
|
732 |
|
|
delete preservedGroups[groupName]
|
733 |
|
|
}
|
734 |
|
|
|
735 |
|
|
const seen = {}
|
736 |
|
|
groups[groupName] = (existing || []).concat(opts).filter((key) => {
|
737 |
|
|
if (seen[key]) return false
|
738 |
|
|
return (seen[key] = true)
|
739 |
|
|
})
|
740 |
|
|
return self
|
741 |
|
|
}
|
742 |
|
|
// combine explicit and preserved groups. explicit groups should be first
|
743 |
|
|
self.getGroups = () => Object.assign({}, groups, preservedGroups)
|
744 |
|
|
|
745 |
|
|
// as long as options.envPrefix is not undefined,
|
746 |
|
|
// parser will apply env vars matching prefix to argv
|
747 |
|
|
self.env = function (prefix) {
|
748 |
|
|
argsert('[string|boolean]', [prefix], arguments.length)
|
749 |
|
|
if (prefix === false) options.envPrefix = undefined
|
750 |
|
|
else options.envPrefix = prefix || ''
|
751 |
|
|
return self
|
752 |
|
|
}
|
753 |
|
|
|
754 |
|
|
self.wrap = function (cols) {
|
755 |
|
|
argsert('<number|null|undefined>', [cols], arguments.length)
|
756 |
|
|
usage.wrap(cols)
|
757 |
|
|
return self
|
758 |
|
|
}
|
759 |
|
|
|
760 |
|
|
let strict = false
|
761 |
|
|
self.strict = function (enabled) {
|
762 |
|
|
argsert('[boolean]', [enabled], arguments.length)
|
763 |
|
|
strict = enabled !== false
|
764 |
|
|
return self
|
765 |
|
|
}
|
766 |
|
|
self.getStrict = () => strict
|
767 |
|
|
|
768 |
|
|
self.showHelp = function (level) {
|
769 |
|
|
argsert('[string|function]', [level], arguments.length)
|
770 |
|
|
if (!self.parsed) self._parseArgs(processArgs) // run parser, if it has not already been executed.
|
771 |
|
|
if (command.hasDefaultCommand()) {
|
772 |
|
|
context.resets++ // override the restriction on top-level positoinals.
|
773 |
|
|
command.runDefaultBuilderOn(self, true)
|
774 |
|
|
}
|
775 |
|
|
usage.showHelp(level)
|
776 |
|
|
return self
|
777 |
|
|
}
|
778 |
|
|
|
779 |
|
|
let versionOpt = null
|
780 |
|
|
self.version = function version (opt, msg, ver) {
|
781 |
|
|
const defaultVersionOpt = 'version'
|
782 |
|
|
argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length)
|
783 |
|
|
|
784 |
|
|
// nuke the key previously configured
|
785 |
|
|
// to return version #.
|
786 |
|
|
if (versionOpt) {
|
787 |
|
|
deleteFromParserHintObject(versionOpt)
|
788 |
|
|
usage.version(undefined)
|
789 |
|
|
versionOpt = null
|
790 |
|
|
}
|
791 |
|
|
|
792 |
|
|
if (arguments.length === 0) {
|
793 |
|
|
ver = guessVersion()
|
794 |
|
|
opt = defaultVersionOpt
|
795 |
|
|
} else if (arguments.length === 1) {
|
796 |
|
|
if (opt === false) { // disable default 'version' key.
|
797 |
|
|
return self
|
798 |
|
|
}
|
799 |
|
|
ver = opt
|
800 |
|
|
opt = defaultVersionOpt
|
801 |
|
|
} else if (arguments.length === 2) {
|
802 |
|
|
ver = msg
|
803 |
|
|
msg = null
|
804 |
|
|
}
|
805 |
|
|
|
806 |
|
|
versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt
|
807 |
|
|
msg = msg || usage.deferY18nLookup('Show version number')
|
808 |
|
|
|
809 |
|
|
usage.version(ver || undefined)
|
810 |
|
|
self.boolean(versionOpt)
|
811 |
|
|
self.describe(versionOpt, msg)
|
812 |
|
|
return self
|
813 |
|
|
}
|
814 |
|
|
|
815 |
|
|
function guessVersion () {
|
816 |
|
|
const obj = pkgUp()
|
817 |
|
|
|
818 |
|
|
return obj.version || 'unknown'
|
819 |
|
|
}
|
820 |
|
|
|
821 |
|
|
let helpOpt = null
|
822 |
|
|
self.addHelpOpt = self.help = function addHelpOpt (opt, msg) {
|
823 |
|
|
const defaultHelpOpt = 'help'
|
824 |
|
|
argsert('[string|boolean] [string]', [opt, msg], arguments.length)
|
825 |
|
|
|
826 |
|
|
// nuke the key previously configured
|
827 |
|
|
// to return help.
|
828 |
|
|
if (helpOpt) {
|
829 |
|
|
deleteFromParserHintObject(helpOpt)
|
830 |
|
|
helpOpt = null
|
831 |
|
|
}
|
832 |
|
|
|
833 |
|
|
if (arguments.length === 1) {
|
834 |
|
|
if (opt === false) return self
|
835 |
|
|
}
|
836 |
|
|
|
837 |
|
|
// use arguments, fallback to defaults for opt and msg
|
838 |
|
|
helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt
|
839 |
|
|
self.boolean(helpOpt)
|
840 |
|
|
self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'))
|
841 |
|
|
return self
|
842 |
|
|
}
|
843 |
|
|
|
844 |
|
|
const defaultShowHiddenOpt = 'show-hidden'
|
845 |
|
|
options.showHiddenOpt = defaultShowHiddenOpt
|
846 |
|
|
self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt (opt, msg) {
|
847 |
|
|
argsert('[string|boolean] [string]', [opt, msg], arguments.length)
|
848 |
|
|
|
849 |
|
|
if (arguments.length === 1) {
|
850 |
|
|
if (opt === false) return self
|
851 |
|
|
}
|
852 |
|
|
|
853 |
|
|
const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt
|
854 |
|
|
self.boolean(showHiddenOpt)
|
855 |
|
|
self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options'))
|
856 |
|
|
options.showHiddenOpt = showHiddenOpt
|
857 |
|
|
return self
|
858 |
|
|
}
|
859 |
|
|
|
860 |
|
|
self.hide = function hide (key) {
|
861 |
|
|
argsert('<string|object>', [key], arguments.length)
|
862 |
|
|
options.hiddenOptions.push(key)
|
863 |
|
|
return self
|
864 |
|
|
}
|
865 |
|
|
|
866 |
|
|
self.showHelpOnFail = function showHelpOnFail (enabled, message) {
|
867 |
|
|
argsert('[boolean|string] [string]', [enabled, message], arguments.length)
|
868 |
|
|
usage.showHelpOnFail(enabled, message)
|
869 |
|
|
return self
|
870 |
|
|
}
|
871 |
|
|
|
872 |
|
|
var exitProcess = true
|
873 |
|
|
self.exitProcess = function (enabled) {
|
874 |
|
|
argsert('[boolean]', [enabled], arguments.length)
|
875 |
|
|
if (typeof enabled !== 'boolean') {
|
876 |
|
|
enabled = true
|
877 |
|
|
}
|
878 |
|
|
exitProcess = enabled
|
879 |
|
|
return self
|
880 |
|
|
}
|
881 |
|
|
self.getExitProcess = () => exitProcess
|
882 |
|
|
|
883 |
|
|
var completionCommand = null
|
884 |
|
|
self.completion = function (cmd, desc, fn) {
|
885 |
|
|
argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length)
|
886 |
|
|
|
887 |
|
|
// a function to execute when generating
|
888 |
|
|
// completions can be provided as the second
|
889 |
|
|
// or third argument to completion.
|
890 |
|
|
if (typeof desc === 'function') {
|
891 |
|
|
fn = desc
|
892 |
|
|
desc = null
|
893 |
|
|
}
|
894 |
|
|
|
895 |
|
|
// register the completion command.
|
896 |
|
|
completionCommand = cmd || 'completion'
|
897 |
|
|
if (!desc && desc !== false) {
|
898 |
|
|
desc = 'generate bash completion script'
|
899 |
|
|
}
|
900 |
|
|
self.command(completionCommand, desc)
|
901 |
|
|
|
902 |
|
|
// a function can be provided
|
903 |
|
|
if (fn) completion.registerFunction(fn)
|
904 |
|
|
|
905 |
|
|
return self
|
906 |
|
|
}
|
907 |
|
|
|
908 |
|
|
self.showCompletionScript = function ($0) {
|
909 |
|
|
argsert('[string]', [$0], arguments.length)
|
910 |
|
|
$0 = $0 || self.$0
|
911 |
|
|
_logger.log(completion.generateCompletionScript($0, completionCommand))
|
912 |
|
|
return self
|
913 |
|
|
}
|
914 |
|
|
|
915 |
|
|
self.getCompletion = function (args, done) {
|
916 |
|
|
argsert('<array> <function>', [args, done], arguments.length)
|
917 |
|
|
completion.getCompletion(args, done)
|
918 |
|
|
}
|
919 |
|
|
|
920 |
|
|
self.locale = function (locale) {
|
921 |
|
|
argsert('[string]', [locale], arguments.length)
|
922 |
|
|
if (arguments.length === 0) {
|
923 |
|
|
guessLocale()
|
924 |
|
|
return y18n.getLocale()
|
925 |
|
|
}
|
926 |
|
|
detectLocale = false
|
927 |
|
|
y18n.setLocale(locale)
|
928 |
|
|
return self
|
929 |
|
|
}
|
930 |
|
|
|
931 |
|
|
self.updateStrings = self.updateLocale = function (obj) {
|
932 |
|
|
argsert('<object>', [obj], arguments.length)
|
933 |
|
|
detectLocale = false
|
934 |
|
|
y18n.updateLocale(obj)
|
935 |
|
|
return self
|
936 |
|
|
}
|
937 |
|
|
|
938 |
|
|
let detectLocale = true
|
939 |
|
|
self.detectLocale = function (detect) {
|
940 |
|
|
argsert('<boolean>', [detect], arguments.length)
|
941 |
|
|
detectLocale = detect
|
942 |
|
|
return self
|
943 |
|
|
}
|
944 |
|
|
self.getDetectLocale = () => detectLocale
|
945 |
|
|
|
946 |
|
|
var hasOutput = false
|
947 |
|
|
var exitError = null
|
948 |
|
|
// maybe exit, always capture
|
949 |
|
|
// context about why we wanted to exit.
|
950 |
|
|
self.exit = (code, err) => {
|
951 |
|
|
hasOutput = true
|
952 |
|
|
exitError = err
|
953 |
|
|
if (exitProcess) process.exit(code)
|
954 |
|
|
}
|
955 |
|
|
|
956 |
|
|
// we use a custom logger that buffers output,
|
957 |
|
|
// so that we can print to non-CLIs, e.g., chat-bots.
|
958 |
|
|
const _logger = {
|
959 |
|
|
log () {
|
960 |
|
|
const args = []
|
961 |
|
|
for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
|
962 |
|
|
if (!self._hasParseCallback()) console.log.apply(console, args)
|
963 |
|
|
hasOutput = true
|
964 |
|
|
if (output.length) output += '\n'
|
965 |
|
|
output += args.join(' ')
|
966 |
|
|
},
|
967 |
|
|
error () {
|
968 |
|
|
const args = []
|
969 |
|
|
for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
|
970 |
|
|
if (!self._hasParseCallback()) console.error.apply(console, args)
|
971 |
|
|
hasOutput = true
|
972 |
|
|
if (output.length) output += '\n'
|
973 |
|
|
output += args.join(' ')
|
974 |
|
|
}
|
975 |
|
|
}
|
976 |
|
|
self._getLoggerInstance = () => _logger
|
977 |
|
|
// has yargs output an error our help
|
978 |
|
|
// message in the current execution context.
|
979 |
|
|
self._hasOutput = () => hasOutput
|
980 |
|
|
|
981 |
|
|
self._setHasOutput = () => {
|
982 |
|
|
hasOutput = true
|
983 |
|
|
}
|
984 |
|
|
|
985 |
|
|
let recommendCommands
|
986 |
|
|
self.recommendCommands = function (recommend) {
|
987 |
|
|
argsert('[boolean]', [recommend], arguments.length)
|
988 |
|
|
recommendCommands = typeof recommend === 'boolean' ? recommend : true
|
989 |
|
|
return self
|
990 |
|
|
}
|
991 |
|
|
|
992 |
|
|
self.getUsageInstance = () => usage
|
993 |
|
|
|
994 |
|
|
self.getValidationInstance = () => validation
|
995 |
|
|
|
996 |
|
|
self.getCommandInstance = () => command
|
997 |
|
|
|
998 |
|
|
self.terminalWidth = () => {
|
999 |
|
|
argsert([], 0)
|
1000 |
|
|
return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
|
1001 |
|
|
}
|
1002 |
|
|
|
1003 |
|
|
Object.defineProperty(self, 'argv', {
|
1004 |
|
|
get: () => self._parseArgs(processArgs),
|
1005 |
|
|
enumerable: true
|
1006 |
|
|
})
|
1007 |
|
|
|
1008 |
|
|
self._parseArgs = function parseArgs (args, shortCircuit, _skipValidation, commandIndex) {
|
1009 |
|
|
let skipValidation = !!_skipValidation
|
1010 |
|
|
args = args || processArgs
|
1011 |
|
|
|
1012 |
|
|
options.__ = y18n.__
|
1013 |
|
|
options.configuration = pkgUp()['yargs'] || {}
|
1014 |
|
|
|
1015 |
|
|
const parsed = Parser.detailed(args, options)
|
1016 |
|
|
let argv = parsed.argv
|
1017 |
|
|
if (parseContext) argv = Object.assign({}, argv, parseContext)
|
1018 |
|
|
const aliases = parsed.aliases
|
1019 |
|
|
|
1020 |
|
|
argv.$0 = self.$0
|
1021 |
|
|
self.parsed = parsed
|
1022 |
|
|
|
1023 |
|
|
try {
|
1024 |
|
|
guessLocale() // guess locale lazily, so that it can be turned off in chain.
|
1025 |
|
|
|
1026 |
|
|
// while building up the argv object, there
|
1027 |
|
|
// are two passes through the parser. If completion
|
1028 |
|
|
// is being performed short-circuit on the first pass.
|
1029 |
|
|
if (shortCircuit) {
|
1030 |
|
|
return argv
|
1031 |
|
|
}
|
1032 |
|
|
|
1033 |
|
|
// if there's a handler associated with a
|
1034 |
|
|
// command defer processing to it.
|
1035 |
|
|
if (helpOpt) {
|
1036 |
|
|
// consider any multi-char helpOpt alias as a valid help command
|
1037 |
|
|
// unless all helpOpt aliases are single-char
|
1038 |
|
|
// note that parsed.aliases is a normalized bidirectional map :)
|
1039 |
|
|
const helpCmds = [helpOpt]
|
1040 |
|
|
.concat(aliases[helpOpt] || [])
|
1041 |
|
|
.filter(k => k.length > 1)
|
1042 |
|
|
// check if help should trigger and strip it from _.
|
1043 |
|
|
if (~helpCmds.indexOf(argv._[argv._.length - 1])) {
|
1044 |
|
|
argv._.pop()
|
1045 |
|
|
argv[helpOpt] = true
|
1046 |
|
|
}
|
1047 |
|
|
}
|
1048 |
|
|
|
1049 |
|
|
const handlerKeys = command.getCommands()
|
1050 |
|
|
const requestCompletions = completion.completionKey in argv
|
1051 |
|
|
const skipRecommendation = argv[helpOpt] || requestCompletions
|
1052 |
|
|
const skipDefaultCommand = skipRecommendation && (handlerKeys.length > 1 || handlerKeys[0] !== '$0')
|
1053 |
|
|
|
1054 |
|
|
if (argv._.length) {
|
1055 |
|
|
if (handlerKeys.length) {
|
1056 |
|
|
let firstUnknownCommand
|
1057 |
|
|
for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) {
|
1058 |
|
|
cmd = String(argv._[i])
|
1059 |
|
|
if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
|
1060 |
|
|
// commands are executed using a recursive algorithm that executes
|
1061 |
|
|
// the deepest command first; we keep track of the position in the
|
1062 |
|
|
// argv._ array that is currently being executed.
|
1063 |
|
|
return command.runCommand(cmd, self, parsed, i + 1)
|
1064 |
|
|
} else if (!firstUnknownCommand && cmd !== completionCommand) {
|
1065 |
|
|
firstUnknownCommand = cmd
|
1066 |
|
|
break
|
1067 |
|
|
}
|
1068 |
|
|
}
|
1069 |
|
|
|
1070 |
|
|
// run the default command, if defined
|
1071 |
|
|
if (command.hasDefaultCommand() && !skipDefaultCommand) {
|
1072 |
|
|
return command.runCommand(null, self, parsed)
|
1073 |
|
|
}
|
1074 |
|
|
|
1075 |
|
|
// recommend a command if recommendCommands() has
|
1076 |
|
|
// been enabled, and no commands were found to execute
|
1077 |
|
|
if (recommendCommands && firstUnknownCommand && !skipRecommendation) {
|
1078 |
|
|
validation.recommendCommands(firstUnknownCommand, handlerKeys)
|
1079 |
|
|
}
|
1080 |
|
|
}
|
1081 |
|
|
|
1082 |
|
|
// generate a completion script for adding to ~/.bashrc.
|
1083 |
|
|
if (completionCommand && ~argv._.indexOf(completionCommand) && !requestCompletions) {
|
1084 |
|
|
if (exitProcess) setBlocking(true)
|
1085 |
|
|
self.showCompletionScript()
|
1086 |
|
|
self.exit(0)
|
1087 |
|
|
}
|
1088 |
|
|
} else if (command.hasDefaultCommand() && !skipDefaultCommand) {
|
1089 |
|
|
return command.runCommand(null, self, parsed)
|
1090 |
|
|
}
|
1091 |
|
|
|
1092 |
|
|
// we must run completions first, a user might
|
1093 |
|
|
// want to complete the --help or --version option.
|
1094 |
|
|
if (requestCompletions) {
|
1095 |
|
|
if (exitProcess) setBlocking(true)
|
1096 |
|
|
|
1097 |
|
|
// we allow for asynchronous completions,
|
1098 |
|
|
// e.g., loading in a list of commands from an API.
|
1099 |
|
|
const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1)
|
1100 |
|
|
completion.getCompletion(completionArgs, (completions) => {
|
1101 |
|
|
;(completions || []).forEach((completion) => {
|
1102 |
|
|
_logger.log(completion)
|
1103 |
|
|
})
|
1104 |
|
|
|
1105 |
|
|
self.exit(0)
|
1106 |
|
|
})
|
1107 |
|
|
return argv
|
1108 |
|
|
}
|
1109 |
|
|
|
1110 |
|
|
// Handle 'help' and 'version' options
|
1111 |
|
|
// if we haven't already output help!
|
1112 |
|
|
if (!hasOutput) {
|
1113 |
|
|
Object.keys(argv).forEach((key) => {
|
1114 |
|
|
if (key === helpOpt && argv[key]) {
|
1115 |
|
|
if (exitProcess) setBlocking(true)
|
1116 |
|
|
|
1117 |
|
|
skipValidation = true
|
1118 |
|
|
self.showHelp('log')
|
1119 |
|
|
self.exit(0)
|
1120 |
|
|
} else if (key === versionOpt && argv[key]) {
|
1121 |
|
|
if (exitProcess) setBlocking(true)
|
1122 |
|
|
|
1123 |
|
|
skipValidation = true
|
1124 |
|
|
usage.showVersion()
|
1125 |
|
|
self.exit(0)
|
1126 |
|
|
}
|
1127 |
|
|
})
|
1128 |
|
|
}
|
1129 |
|
|
|
1130 |
|
|
// Check if any of the options to skip validation were provided
|
1131 |
|
|
if (!skipValidation && options.skipValidation.length > 0) {
|
1132 |
|
|
skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true)
|
1133 |
|
|
}
|
1134 |
|
|
|
1135 |
|
|
// If the help or version options where used and exitProcess is false,
|
1136 |
|
|
// or if explicitly skipped, we won't run validations.
|
1137 |
|
|
if (!skipValidation) {
|
1138 |
|
|
if (parsed.error) throw new YError(parsed.error.message)
|
1139 |
|
|
|
1140 |
|
|
// if we're executed via bash completion, don't
|
1141 |
|
|
// bother with validation.
|
1142 |
|
|
if (!requestCompletions) {
|
1143 |
|
|
self._runValidation(argv, aliases, {}, parsed.error)
|
1144 |
|
|
}
|
1145 |
|
|
}
|
1146 |
|
|
} catch (err) {
|
1147 |
|
|
if (err instanceof YError) usage.fail(err.message, err)
|
1148 |
|
|
else throw err
|
1149 |
|
|
}
|
1150 |
|
|
|
1151 |
|
|
return argv
|
1152 |
|
|
}
|
1153 |
|
|
|
1154 |
|
|
self._runValidation = function runValidation (argv, aliases, positionalMap, parseErrors) {
|
1155 |
|
|
if (parseErrors) throw new YError(parseErrors.message)
|
1156 |
|
|
validation.nonOptionCount(argv)
|
1157 |
|
|
validation.requiredArguments(argv)
|
1158 |
|
|
if (strict) validation.unknownArguments(argv, aliases, positionalMap)
|
1159 |
|
|
validation.customChecks(argv, aliases)
|
1160 |
|
|
validation.limitedChoices(argv)
|
1161 |
|
|
validation.implications(argv)
|
1162 |
|
|
validation.conflicting(argv)
|
1163 |
|
|
}
|
1164 |
|
|
|
1165 |
|
|
function guessLocale () {
|
1166 |
|
|
if (!detectLocale) return
|
1167 |
|
|
|
1168 |
|
|
try {
|
1169 |
|
|
const osLocale = require('os-locale')
|
1170 |
|
|
self.locale(osLocale.sync({ spawn: false }))
|
1171 |
|
|
} catch (err) {
|
1172 |
|
|
// if we explode looking up locale just noop
|
1173 |
|
|
// we'll keep using the default language 'en'.
|
1174 |
|
|
}
|
1175 |
|
|
}
|
1176 |
|
|
|
1177 |
|
|
// an app should almost always have --version and --help,
|
1178 |
|
|
// if you *really* want to disable this use .help(false)/.version(false).
|
1179 |
|
|
self.help()
|
1180 |
|
|
self.version()
|
1181 |
|
|
|
1182 |
|
|
return self
|
1183 |
|
|
}
|
1184 |
|
|
|
1185 |
|
|
// rebase an absolute path to a relative one with respect to a base directory
|
1186 |
|
|
// exported for tests
|
1187 |
|
|
exports.rebase = rebase
|
1188 |
|
|
function rebase (base, dir) {
|
1189 |
|
|
return path.relative(base, dir)
|
1190 |
|
|
}
|