Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  1. /**
  2. * Module dependencies.
  3. */
  4. var EventEmitter = require('events').EventEmitter;
  5. var spawn = require('child_process').spawn;
  6. var path = require('path');
  7. var dirname = path.dirname;
  8. var basename = path.basename;
  9. var fs = require('fs');
  10. /**
  11. * Inherit `Command` from `EventEmitter.prototype`.
  12. */
  13. require('util').inherits(Command, EventEmitter);
  14. /**
  15. * Expose the root command.
  16. */
  17. exports = module.exports = new Command();
  18. /**
  19. * Expose `Command`.
  20. */
  21. exports.Command = Command;
  22. /**
  23. * Expose `Option`.
  24. */
  25. exports.Option = Option;
  26. /**
  27. * Initialize a new `Option` with the given `flags` and `description`.
  28. *
  29. * @param {String} flags
  30. * @param {String} description
  31. * @api public
  32. */
  33. function Option(flags, description) {
  34. this.flags = flags;
  35. this.required = flags.indexOf('<') >= 0; // A value must be supplied when the option is specified.
  36. this.optional = flags.indexOf('[') >= 0; // A value is optional when the option is specified.
  37. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
  38. this.negate = flags.indexOf('-no-') !== -1;
  39. flags = flags.split(/[ ,|]+/);
  40. if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
  41. this.long = flags.shift();
  42. this.description = description || '';
  43. }
  44. /**
  45. * Return option name.
  46. *
  47. * @return {String}
  48. * @api private
  49. */
  50. Option.prototype.name = function() {
  51. return this.long.replace(/^--/, '');
  52. };
  53. /**
  54. * Return option name, in a camelcase format that can be used
  55. * as a object attribute key.
  56. *
  57. * @return {String}
  58. * @api private
  59. */
  60. Option.prototype.attributeName = function() {
  61. return camelcase(this.name().replace(/^no-/, ''));
  62. };
  63. /**
  64. * Check if `arg` matches the short or long flag.
  65. *
  66. * @param {String} arg
  67. * @return {Boolean}
  68. * @api private
  69. */
  70. Option.prototype.is = function(arg) {
  71. return this.short === arg || this.long === arg;
  72. };
  73. /**
  74. * CommanderError class
  75. * @class
  76. */
  77. class CommanderError extends Error {
  78. /**
  79. * Constructs the CommanderError class
  80. * @param {Number} exitCode suggested exit code which could be used with process.exit
  81. * @param {String} code an id string representing the error
  82. * @param {String} message human-readable description of the error
  83. * @constructor
  84. */
  85. constructor(exitCode, code, message) {
  86. super(message);
  87. // properly capture stack trace in Node.js
  88. Error.captureStackTrace(this, this.constructor);
  89. this.name = this.constructor.name;
  90. this.code = code;
  91. this.exitCode = exitCode;
  92. }
  93. }
  94. exports.CommanderError = CommanderError;
  95. /**
  96. * Initialize a new `Command`.
  97. *
  98. * @param {String} [name]
  99. * @api public
  100. */
  101. function Command(name) {
  102. this.commands = [];
  103. this.options = [];
  104. this._execs = new Set();
  105. this._allowUnknownOption = false;
  106. this._args = [];
  107. this._name = name || '';
  108. this._optionValues = {};
  109. this._storeOptionsAsProperties = true; // backwards compatible by default
  110. this._passCommandToAction = true; // backwards compatible by default
  111. this._actionResults = [];
  112. this._helpFlags = '-h, --help';
  113. this._helpDescription = 'output usage information';
  114. this._helpShortFlag = '-h';
  115. this._helpLongFlag = '--help';
  116. }
  117. /**
  118. * Define a command.
  119. *
  120. * There are two styles of command: pay attention to where to put the description.
  121. *
  122. * Examples:
  123. *
  124. * // Command implemented using action handler (description is supplied separately to `.command`)
  125. * program
  126. * .command('clone <source> [destination]')
  127. * .description('clone a repository into a newly created directory')
  128. * .action((source, destination) => {
  129. * console.log('clone command called');
  130. * });
  131. *
  132. * // Command implemented using separate executable file (description is second parameter to `.command`)
  133. * program
  134. * .command('start <service>', 'start named service')
  135. * .command('stop [service]', 'stop named service, or all if no name supplied');
  136. *
  137. * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
  138. * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
  139. * @param {Object} [execOpts] - configuration options (for executable)
  140. * @return {Command} returns new command for action handler, or top-level command for executable command
  141. * @api public
  142. */
  143. Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) {
  144. var desc = actionOptsOrExecDesc;
  145. var opts = execOpts;
  146. if (typeof desc === 'object' && desc !== null) {
  147. opts = desc;
  148. desc = null;
  149. }
  150. opts = opts || {};
  151. var args = nameAndArgs.split(/ +/);
  152. var cmd = new Command(args.shift());
  153. if (desc) {
  154. cmd.description(desc);
  155. this.executables = true;
  156. this._execs.add(cmd._name);
  157. if (opts.isDefault) this.defaultExecutable = cmd._name;
  158. }
  159. cmd._noHelp = !!opts.noHelp;
  160. cmd._helpFlags = this._helpFlags;
  161. cmd._helpDescription = this._helpDescription;
  162. cmd._helpShortFlag = this._helpShortFlag;
  163. cmd._helpLongFlag = this._helpLongFlag;
  164. cmd._exitCallback = this._exitCallback;
  165. cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
  166. cmd._passCommandToAction = this._passCommandToAction;
  167. cmd._executableFile = opts.executableFile; // Custom name for executable file
  168. this.commands.push(cmd);
  169. cmd.parseExpectedArgs(args);
  170. cmd.parent = this;
  171. if (desc) return this;
  172. return cmd;
  173. };
  174. /**
  175. * Define argument syntax for the top-level command.
  176. *
  177. * @api public
  178. */
  179. Command.prototype.arguments = function(desc) {
  180. return this.parseExpectedArgs(desc.split(/ +/));
  181. };
  182. /**
  183. * Add an implicit `help [cmd]` subcommand
  184. * which invokes `--help` for the given command.
  185. *
  186. * @api private
  187. */
  188. Command.prototype.addImplicitHelpCommand = function() {
  189. this.command('help [cmd]', 'display help for [cmd]');
  190. };
  191. /**
  192. * Parse expected `args`.
  193. *
  194. * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
  195. *
  196. * @param {Array} args
  197. * @return {Command} for chaining
  198. * @api public
  199. */
  200. Command.prototype.parseExpectedArgs = function(args) {
  201. if (!args.length) return;
  202. var self = this;
  203. args.forEach(function(arg) {
  204. var argDetails = {
  205. required: false,
  206. name: '',
  207. variadic: false
  208. };
  209. switch (arg[0]) {
  210. case '<':
  211. argDetails.required = true;
  212. argDetails.name = arg.slice(1, -1);
  213. break;
  214. case '[':
  215. argDetails.name = arg.slice(1, -1);
  216. break;
  217. }
  218. if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
  219. argDetails.variadic = true;
  220. argDetails.name = argDetails.name.slice(0, -3);
  221. }
  222. if (argDetails.name) {
  223. self._args.push(argDetails);
  224. }
  225. });
  226. return this;
  227. };
  228. /**
  229. * Register callback to use as replacement for calling process.exit.
  230. *
  231. * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
  232. * @return {Command} for chaining
  233. * @api public
  234. */
  235. Command.prototype.exitOverride = function(fn) {
  236. if (fn) {
  237. this._exitCallback = fn;
  238. } else {
  239. this._exitCallback = function(err) {
  240. if (err.code !== 'commander.executeSubCommandAsync') {
  241. throw err;
  242. } else {
  243. // Async callback from spawn events, not useful to throw.
  244. }
  245. };
  246. }
  247. return this;
  248. };
  249. /**
  250. * Call process.exit, and _exitCallback if defined.
  251. *
  252. * @param {Number} exitCode exit code for using with process.exit
  253. * @param {String} code an id string representing the error
  254. * @param {String} message human-readable description of the error
  255. * @return never
  256. * @api private
  257. */
  258. Command.prototype._exit = function(exitCode, code, message) {
  259. if (this._exitCallback) {
  260. this._exitCallback(new CommanderError(exitCode, code, message));
  261. // Expecting this line is not reached.
  262. }
  263. process.exit(exitCode);
  264. };
  265. /**
  266. * Register callback `fn` for the command.
  267. *
  268. * Examples:
  269. *
  270. * program
  271. * .command('help')
  272. * .description('display verbose help')
  273. * .action(function() {
  274. * // output help here
  275. * });
  276. *
  277. * @param {Function} fn
  278. * @return {Command} for chaining
  279. * @api public
  280. */
  281. Command.prototype.action = function(fn) {
  282. var self = this;
  283. var listener = function(args, unknown) {
  284. // Parse any so-far unknown options
  285. args = args || [];
  286. unknown = unknown || [];
  287. var parsed = self.parseOptions(unknown);
  288. // Output help if necessary
  289. outputHelpIfRequested(self, parsed.unknown);
  290. self._checkForMissingMandatoryOptions();
  291. // If there are still any unknown options, then we simply
  292. // die, unless someone asked for help, in which case we give it
  293. // to them, and then we die.
  294. if (parsed.unknown.length > 0) {
  295. self.unknownOption(parsed.unknown[0]);
  296. }
  297. // Leftover arguments need to be pushed back. Fixes issue #56
  298. if (parsed.args.length) args = parsed.args.concat(args);
  299. self._args.forEach(function(arg, i) {
  300. if (arg.required && args[i] == null) {
  301. self.missingArgument(arg.name);
  302. } else if (arg.variadic) {
  303. if (i !== self._args.length - 1) {
  304. self.variadicArgNotLast(arg.name);
  305. }
  306. args[i] = args.splice(i);
  307. }
  308. });
  309. // The .action callback takes an extra parameter which is the command itself.
  310. var expectedArgsCount = self._args.length;
  311. var actionArgs = args.slice(0, expectedArgsCount);
  312. if (self._passCommandToAction) {
  313. actionArgs[expectedArgsCount] = self;
  314. } else {
  315. actionArgs[expectedArgsCount] = self.opts();
  316. }
  317. // Add the extra arguments so available too.
  318. if (args.length > expectedArgsCount) {
  319. actionArgs.push(args.slice(expectedArgsCount));
  320. }
  321. const actionResult = fn.apply(self, actionArgs);
  322. // Remember result in case it is async. Assume parseAsync getting called on root.
  323. let rootCommand = self;
  324. while (rootCommand.parent) {
  325. rootCommand = rootCommand.parent;
  326. }
  327. rootCommand._actionResults.push(actionResult);
  328. };
  329. var parent = this.parent || this;
  330. var name = parent === this ? '*' : this._name;
  331. parent.on('command:' + name, listener);
  332. if (this._alias) parent.on('command:' + this._alias, listener);
  333. return this;
  334. };
  335. /**
  336. * Internal implementation shared by .option() and .requiredOption()
  337. *
  338. * @param {Object} config
  339. * @param {String} flags
  340. * @param {String} description
  341. * @param {Function|*} [fn] - custom option processing function or default vaue
  342. * @param {*} [defaultValue]
  343. * @return {Command} for chaining
  344. * @api private
  345. */
  346. Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) {
  347. var self = this,
  348. option = new Option(flags, description),
  349. oname = option.name(),
  350. name = option.attributeName();
  351. option.mandatory = !!config.mandatory;
  352. // default as 3rd arg
  353. if (typeof fn !== 'function') {
  354. if (fn instanceof RegExp) {
  355. // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.
  356. // No longer documented in README, but still present for backwards compatibility.
  357. var regex = fn;
  358. fn = function(val, def) {
  359. var m = regex.exec(val);
  360. return m ? m[0] : def;
  361. };
  362. } else {
  363. defaultValue = fn;
  364. fn = null;
  365. }
  366. }
  367. // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value
  368. if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
  369. // when --no-foo we make sure default is true, unless a --foo option is already defined
  370. if (option.negate) {
  371. const positiveLongFlag = option.long.replace(/^--no-/, '--');
  372. defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true;
  373. }
  374. // preassign only if we have a default
  375. if (defaultValue !== undefined) {
  376. self._setOptionValue(name, defaultValue);
  377. option.defaultValue = defaultValue;
  378. }
  379. }
  380. // register the option
  381. this.options.push(option);
  382. // when it's passed assign the value
  383. // and conditionally invoke the callback
  384. this.on('option:' + oname, function(val) {
  385. // coercion
  386. if (val !== null && fn) {
  387. val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name));
  388. }
  389. // unassigned or boolean value
  390. if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') {
  391. // if no value, negate false, and we have a default, then use it!
  392. if (val == null) {
  393. self._setOptionValue(name, option.negate
  394. ? false
  395. : defaultValue || true);
  396. } else {
  397. self._setOptionValue(name, val);
  398. }
  399. } else if (val !== null) {
  400. // reassign
  401. self._setOptionValue(name, option.negate ? false : val);
  402. }
  403. });
  404. return this;
  405. };
  406. /**
  407. * Define option with `flags`, `description` and optional
  408. * coercion `fn`.
  409. *
  410. * The `flags` string should contain both the short and long flags,
  411. * separated by comma, a pipe or space. The following are all valid
  412. * all will output this way when `--help` is used.
  413. *
  414. * "-p, --pepper"
  415. * "-p|--pepper"
  416. * "-p --pepper"
  417. *
  418. * Examples:
  419. *
  420. * // simple boolean defaulting to undefined
  421. * program.option('-p, --pepper', 'add pepper');
  422. *
  423. * program.pepper
  424. * // => undefined
  425. *
  426. * --pepper
  427. * program.pepper
  428. * // => true
  429. *
  430. * // simple boolean defaulting to true (unless non-negated option is also defined)
  431. * program.option('-C, --no-cheese', 'remove cheese');
  432. *
  433. * program.cheese
  434. * // => true
  435. *
  436. * --no-cheese
  437. * program.cheese
  438. * // => false
  439. *
  440. * // required argument
  441. * program.option('-C, --chdir <path>', 'change the working directory');
  442. *
  443. * --chdir /tmp
  444. * program.chdir
  445. * // => "/tmp"
  446. *
  447. * // optional argument
  448. * program.option('-c, --cheese [type]', 'add cheese [marble]');
  449. *
  450. * @param {String} flags
  451. * @param {String} description
  452. * @param {Function|*} [fn] - custom option processing function or default vaue
  453. * @param {*} [defaultValue]
  454. * @return {Command} for chaining
  455. * @api public
  456. */
  457. Command.prototype.option = function(flags, description, fn, defaultValue) {
  458. return this._optionEx({}, flags, description, fn, defaultValue);
  459. };
  460. /*
  461. * Add a required option which must have a value after parsing. This usually means
  462. * the option must be specified on the command line. (Otherwise the same as .option().)
  463. *
  464. * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
  465. *
  466. * @param {String} flags
  467. * @param {String} description
  468. * @param {Function|*} [fn] - custom option processing function or default vaue
  469. * @param {*} [defaultValue]
  470. * @return {Command} for chaining
  471. * @api public
  472. */
  473. Command.prototype.requiredOption = function(flags, description, fn, defaultValue) {
  474. return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
  475. };
  476. /**
  477. * Allow unknown options on the command line.
  478. *
  479. * @param {Boolean} arg if `true` or omitted, no error will be thrown
  480. * for unknown options.
  481. * @api public
  482. */
  483. Command.prototype.allowUnknownOption = function(arg) {
  484. this._allowUnknownOption = arguments.length === 0 || arg;
  485. return this;
  486. };
  487. /**
  488. * Whether to store option values as properties on command object,
  489. * or store separately (specify false). In both cases the option values can be accessed using .opts().
  490. *
  491. * @param {boolean} value
  492. * @return {Command} Command for chaining
  493. * @api public
  494. */
  495. Command.prototype.storeOptionsAsProperties = function(value) {
  496. this._storeOptionsAsProperties = (value === undefined) || value;
  497. if (this.options.length) {
  498. // This is for programmer, not end user.
  499. console.error('Commander usage error: call storeOptionsAsProperties before adding options');
  500. }
  501. return this;
  502. };
  503. /**
  504. * Whether to pass command to action handler,
  505. * or just the options (specify false).
  506. *
  507. * @param {boolean} value
  508. * @return {Command} Command for chaining
  509. * @api public
  510. */
  511. Command.prototype.passCommandToAction = function(value) {
  512. this._passCommandToAction = (value === undefined) || value;
  513. return this;
  514. };
  515. /**
  516. * Store option value
  517. *
  518. * @param {String} key
  519. * @param {Object} value
  520. * @api private
  521. */
  522. Command.prototype._setOptionValue = function(key, value) {
  523. if (this._storeOptionsAsProperties) {
  524. this[key] = value;
  525. } else {
  526. this._optionValues[key] = value;
  527. }
  528. };
  529. /**
  530. * Retrieve option value
  531. *
  532. * @param {String} key
  533. * @return {Object} value
  534. * @api private
  535. */
  536. Command.prototype._getOptionValue = function(key) {
  537. if (this._storeOptionsAsProperties) {
  538. return this[key];
  539. }
  540. return this._optionValues[key];
  541. };
  542. /**
  543. * Parse `argv`, setting options and invoking commands when defined.
  544. *
  545. * @param {Array} argv
  546. * @return {Command} for chaining
  547. * @api public
  548. */
  549. Command.prototype.parse = function(argv) {
  550. // implicit help
  551. if (this.executables) this.addImplicitHelpCommand();
  552. // store raw args
  553. this.rawArgs = argv;
  554. // guess name
  555. this._name = this._name || basename(argv[1], '.js');
  556. // github-style sub-commands with no sub-command
  557. if (this.executables && argv.length < 3 && !this.defaultExecutable) {
  558. // this user needs help
  559. argv.push(this._helpLongFlag);
  560. }
  561. // process argv
  562. var normalized = this.normalize(argv.slice(2));
  563. var parsed = this.parseOptions(normalized);
  564. var args = this.args = parsed.args;
  565. var result = this.parseArgs(this.args, parsed.unknown);
  566. if (args[0] === 'help' && args.length === 1) this.help();
  567. // Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed?
  568. // <cmd> --help
  569. if (args[0] === 'help') {
  570. args[0] = args[1];
  571. args[1] = this._helpLongFlag;
  572. } else {
  573. // If calling through to executable subcommand we could check for help flags before failing,
  574. // but a somewhat unlikely case since program options not passed to executable subcommands.
  575. // Wait for reports to see if check needed and what usage pattern is.
  576. this._checkForMissingMandatoryOptions();
  577. }
  578. // executable sub-commands
  579. // (Debugging note for future: args[0] is not right if an action has been called)
  580. var name = result.args[0];
  581. var subCommand = null;
  582. // Look for subcommand
  583. if (name) {
  584. subCommand = this.commands.find(function(command) {
  585. return command._name === name;
  586. });
  587. }
  588. // Look for alias
  589. if (!subCommand && name) {
  590. subCommand = this.commands.find(function(command) {
  591. return command.alias() === name;
  592. });
  593. if (subCommand) {
  594. name = subCommand._name;
  595. args[0] = name;
  596. }
  597. }
  598. // Look for default subcommand
  599. if (!subCommand && this.defaultExecutable) {
  600. name = this.defaultExecutable;
  601. args.unshift(name);
  602. subCommand = this.commands.find(function(command) {
  603. return command._name === name;
  604. });
  605. }
  606. if (this._execs.has(name)) {
  607. return this.executeSubCommand(argv, args, parsed.unknown, subCommand ? subCommand._executableFile : undefined);
  608. }
  609. return result;
  610. };
  611. /**
  612. * Parse `argv`, setting options and invoking commands when defined.
  613. *
  614. * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
  615. *
  616. * @param {Array} argv
  617. * @return {Promise}
  618. * @api public
  619. */
  620. Command.prototype.parseAsync = function(argv) {
  621. this.parse(argv);
  622. return Promise.all(this._actionResults);
  623. };
  624. /**
  625. * Execute a sub-command executable.
  626. *
  627. * @param {Array} argv
  628. * @param {Array} args
  629. * @param {Array} unknown
  630. * @param {String} executableFile
  631. * @api private
  632. */
  633. Command.prototype.executeSubCommand = function(argv, args, unknown, executableFile) {
  634. args = args.concat(unknown);
  635. if (!args.length) this.help();
  636. var isExplicitJS = false; // Whether to use node to launch "executable"
  637. // executable
  638. var pm = argv[1];
  639. // name of the subcommand, like `pm-install`
  640. var bin = basename(pm, path.extname(pm)) + '-' + args[0];
  641. if (executableFile != null) {
  642. bin = executableFile;
  643. // Check for same extensions as we scan for below so get consistent launch behaviour.
  644. var executableExt = path.extname(executableFile);
  645. isExplicitJS = executableExt === '.js' || executableExt === '.ts' || executableExt === '.mjs';
  646. }
  647. // In case of globally installed, get the base dir where executable
  648. // subcommand file should be located at
  649. var baseDir;
  650. var resolvedLink = fs.realpathSync(pm);
  651. baseDir = dirname(resolvedLink);
  652. // prefer local `./<bin>` to bin in the $PATH
  653. var localBin = path.join(baseDir, bin);
  654. // whether bin file is a js script with explicit `.js` or `.ts` extension
  655. if (exists(localBin + '.js')) {
  656. bin = localBin + '.js';
  657. isExplicitJS = true;
  658. } else if (exists(localBin + '.ts')) {
  659. bin = localBin + '.ts';
  660. isExplicitJS = true;
  661. } else if (exists(localBin + '.mjs')) {
  662. bin = localBin + '.mjs';
  663. isExplicitJS = true;
  664. } else if (exists(localBin)) {
  665. bin = localBin;
  666. }
  667. args = args.slice(1);
  668. var proc;
  669. if (process.platform !== 'win32') {
  670. if (isExplicitJS) {
  671. args.unshift(bin);
  672. // add executable arguments to spawn
  673. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  674. proc = spawn(process.argv[0], args, { stdio: 'inherit' });
  675. } else {
  676. proc = spawn(bin, args, { stdio: 'inherit' });
  677. }
  678. } else {
  679. args.unshift(bin);
  680. // add executable arguments to spawn
  681. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  682. proc = spawn(process.execPath, args, { stdio: 'inherit' });
  683. }
  684. var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  685. signals.forEach(function(signal) {
  686. process.on(signal, function() {
  687. if (proc.killed === false && proc.exitCode === null) {
  688. proc.kill(signal);
  689. }
  690. });
  691. });
  692. // By default terminate process when spawned process terminates.
  693. // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
  694. const exitCallback = this._exitCallback;
  695. if (!exitCallback) {
  696. proc.on('close', process.exit.bind(process));
  697. } else {
  698. proc.on('close', () => {
  699. exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
  700. });
  701. }
  702. proc.on('error', function(err) {
  703. if (err.code === 'ENOENT') {
  704. console.error('error: %s(1) does not exist, try --help', bin);
  705. } else if (err.code === 'EACCES') {
  706. console.error('error: %s(1) not executable. try chmod or run with root', bin);
  707. }
  708. if (!exitCallback) {
  709. process.exit(1);
  710. } else {
  711. const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
  712. wrappedError.nestedError = err;
  713. exitCallback(wrappedError);
  714. }
  715. });
  716. // Store the reference to the child process
  717. this.runningCommand = proc;
  718. };
  719. /**
  720. * Normalize `args`, splitting joined short flags. For example
  721. * the arg "-abc" is equivalent to "-a -b -c".
  722. * This also normalizes equal sign and splits "--abc=def" into "--abc def".
  723. *
  724. * @param {Array} args
  725. * @return {Array}
  726. * @api private
  727. */
  728. Command.prototype.normalize = function(args) {
  729. var ret = [],
  730. arg,
  731. lastOpt,
  732. index,
  733. short,
  734. opt;
  735. for (var i = 0, len = args.length; i < len; ++i) {
  736. arg = args[i];
  737. if (i > 0) {
  738. lastOpt = this.optionFor(args[i - 1]);
  739. }
  740. if (arg === '--') {
  741. // Honor option terminator
  742. ret = ret.concat(args.slice(i));
  743. break;
  744. } else if (lastOpt && lastOpt.required) {
  745. ret.push(arg);
  746. } else if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
  747. short = arg.slice(0, 2);
  748. opt = this.optionFor(short);
  749. if (opt && (opt.required || opt.optional)) {
  750. ret.push(short);
  751. ret.push(arg.slice(2));
  752. } else {
  753. arg.slice(1).split('').forEach(function(c) {
  754. ret.push('-' + c);
  755. });
  756. }
  757. } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
  758. ret.push(arg.slice(0, index), arg.slice(index + 1));
  759. } else {
  760. ret.push(arg);
  761. }
  762. }
  763. return ret;
  764. };
  765. /**
  766. * Parse command `args`.
  767. *
  768. * When listener(s) are available those
  769. * callbacks are invoked, otherwise the "*"
  770. * event is emitted and those actions are invoked.
  771. *
  772. * @param {Array} args
  773. * @return {Command} for chaining
  774. * @api private
  775. */
  776. Command.prototype.parseArgs = function(args, unknown) {
  777. var name;
  778. if (args.length) {
  779. name = args[0];
  780. if (this.listeners('command:' + name).length) {
  781. this.emit('command:' + args.shift(), args, unknown);
  782. } else {
  783. this.emit('command:*', args, unknown);
  784. }
  785. } else {
  786. outputHelpIfRequested(this, unknown);
  787. // If there were no args and we have unknown options,
  788. // then they are extraneous and we need to error.
  789. if (unknown.length > 0 && !this.defaultExecutable) {
  790. this.unknownOption(unknown[0]);
  791. }
  792. if (this.commands.length === 0 &&
  793. this._args.filter(function(a) { return a.required; }).length === 0) {
  794. this.emit('command:*');
  795. }
  796. }
  797. return this;
  798. };
  799. /**
  800. * Return an option matching `arg` if any.
  801. *
  802. * @param {String} arg
  803. * @return {Option}
  804. * @api private
  805. */
  806. Command.prototype.optionFor = function(arg) {
  807. for (var i = 0, len = this.options.length; i < len; ++i) {
  808. if (this.options[i].is(arg)) {
  809. return this.options[i];
  810. }
  811. }
  812. };
  813. /**
  814. * Display an error message if a mandatory option does not have a value.
  815. *
  816. * @api private
  817. */
  818. Command.prototype._checkForMissingMandatoryOptions = function() {
  819. // Walk up hierarchy so can call from action handler after checking for displaying help.
  820. for (var cmd = this; cmd; cmd = cmd.parent) {
  821. cmd.options.forEach((anOption) => {
  822. if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
  823. cmd.missingMandatoryOptionValue(anOption);
  824. }
  825. });
  826. }
  827. };
  828. /**
  829. * Parse options from `argv` returning `argv`
  830. * void of these options.
  831. *
  832. * @param {Array} argv
  833. * @return {{args: Array, unknown: Array}}
  834. * @api public
  835. */
  836. Command.prototype.parseOptions = function(argv) {
  837. var args = [],
  838. len = argv.length,
  839. literal,
  840. option,
  841. arg;
  842. var unknownOptions = [];
  843. // parse options
  844. for (var i = 0; i < len; ++i) {
  845. arg = argv[i];
  846. // literal args after --
  847. if (literal) {
  848. args.push(arg);
  849. continue;
  850. }
  851. if (arg === '--') {
  852. literal = true;
  853. continue;
  854. }
  855. // find matching Option
  856. option = this.optionFor(arg);
  857. // option is defined
  858. if (option) {
  859. // requires arg
  860. if (option.required) {
  861. arg = argv[++i];
  862. if (arg == null) return this.optionMissingArgument(option);
  863. this.emit('option:' + option.name(), arg);
  864. // optional arg
  865. } else if (option.optional) {
  866. arg = argv[i + 1];
  867. if (arg == null || (arg[0] === '-' && arg !== '-')) {
  868. arg = null;
  869. } else {
  870. ++i;
  871. }
  872. this.emit('option:' + option.name(), arg);
  873. // flag
  874. } else {
  875. this.emit('option:' + option.name());
  876. }
  877. continue;
  878. }
  879. // looks like an option
  880. if (arg.length > 1 && arg[0] === '-') {
  881. unknownOptions.push(arg);
  882. // If the next argument looks like it might be
  883. // an argument for this option, we pass it on.
  884. // If it isn't, then it'll simply be ignored
  885. if ((i + 1) < argv.length && (argv[i + 1][0] !== '-' || argv[i + 1] === '-')) {
  886. unknownOptions.push(argv[++i]);
  887. }
  888. continue;
  889. }
  890. // arg
  891. args.push(arg);
  892. }
  893. return { args: args, unknown: unknownOptions };
  894. };
  895. /**
  896. * Return an object containing options as key-value pairs
  897. *
  898. * @return {Object}
  899. * @api public
  900. */
  901. Command.prototype.opts = function() {
  902. if (this._storeOptionsAsProperties) {
  903. // Preserve original behaviour so backwards compatible when still using properties
  904. var result = {},
  905. len = this.options.length;
  906. for (var i = 0; i < len; i++) {
  907. var key = this.options[i].attributeName();
  908. result[key] = key === this._versionOptionName ? this._version : this[key];
  909. }
  910. return result;
  911. }
  912. return this._optionValues;
  913. };
  914. /**
  915. * Argument `name` is missing.
  916. *
  917. * @param {String} name
  918. * @api private
  919. */
  920. Command.prototype.missingArgument = function(name) {
  921. const message = `error: missing required argument '${name}'`;
  922. console.error(message);
  923. this._exit(1, 'commander.missingArgument', message);
  924. };
  925. /**
  926. * `Option` is missing an argument, but received `flag` or nothing.
  927. *
  928. * @param {Option} option
  929. * @param {String} [flag]
  930. * @api private
  931. */
  932. Command.prototype.optionMissingArgument = function(option, flag) {
  933. let message;
  934. if (flag) {
  935. message = `error: option '${option.flags}' argument missing, got '${flag}'`;
  936. } else {
  937. message = `error: option '${option.flags}' argument missing`;
  938. }
  939. console.error(message);
  940. this._exit(1, 'commander.optionMissingArgument', message);
  941. };
  942. /**
  943. * `Option` does not have a value, and is a mandatory option.
  944. *
  945. * @param {Option} option
  946. * @api private
  947. */
  948. Command.prototype.missingMandatoryOptionValue = function(option) {
  949. const message = `error: required option '${option.flags}' not specified`;
  950. console.error(message);
  951. this._exit(1, 'commander.missingMandatoryOptionValue', message);
  952. };
  953. /**
  954. * Unknown option `flag`.
  955. *
  956. * @param {String} flag
  957. * @api private
  958. */
  959. Command.prototype.unknownOption = function(flag) {
  960. if (this._allowUnknownOption) return;
  961. const message = `error: unknown option '${flag}'`;
  962. console.error(message);
  963. this._exit(1, 'commander.unknownOption', message);
  964. };
  965. /**
  966. * Variadic argument with `name` is not the last argument as required.
  967. *
  968. * @param {String} name
  969. * @api private
  970. */
  971. Command.prototype.variadicArgNotLast = function(name) {
  972. const message = `error: variadic arguments must be last '${name}'`;
  973. console.error(message);
  974. this._exit(1, 'commander.variadicArgNotLast', message);
  975. };
  976. /**
  977. * Set the program version to `str`.
  978. *
  979. * This method auto-registers the "-V, --version" flag
  980. * which will print the version number when passed.
  981. *
  982. * You can optionally supply the flags and description to override the defaults.
  983. *
  984. * @param {String} str
  985. * @param {String} [flags]
  986. * @param {String} [description]
  987. * @return {Command} for chaining
  988. * @api public
  989. */
  990. Command.prototype.version = function(str, flags, description) {
  991. if (arguments.length === 0) return this._version;
  992. this._version = str;
  993. flags = flags || '-V, --version';
  994. description = description || 'output the version number';
  995. var versionOption = new Option(flags, description);
  996. this._versionOptionName = versionOption.long.substr(2) || 'version';
  997. this.options.push(versionOption);
  998. var self = this;
  999. this.on('option:' + this._versionOptionName, function() {
  1000. process.stdout.write(str + '\n');
  1001. self._exit(0, 'commander.version', str);
  1002. });
  1003. return this;
  1004. };
  1005. /**
  1006. * Set the description to `str`.
  1007. *
  1008. * @param {String} str
  1009. * @param {Object} [argsDescription]
  1010. * @return {String|Command}
  1011. * @api public
  1012. */
  1013. Command.prototype.description = function(str, argsDescription) {
  1014. if (arguments.length === 0) return this._description;
  1015. this._description = str;
  1016. this._argsDescription = argsDescription;
  1017. return this;
  1018. };
  1019. /**
  1020. * Set an alias for the command
  1021. *
  1022. * @param {String} alias
  1023. * @return {String|Command}
  1024. * @api public
  1025. */
  1026. Command.prototype.alias = function(alias) {
  1027. var command = this;
  1028. if (this.commands.length !== 0) {
  1029. command = this.commands[this.commands.length - 1];
  1030. }
  1031. if (arguments.length === 0) return command._alias;
  1032. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  1033. command._alias = alias;
  1034. return this;
  1035. };
  1036. /**
  1037. * Set / get the command usage `str`.
  1038. *
  1039. * @param {String} [str]
  1040. * @return {String|Command}
  1041. * @api public
  1042. */
  1043. Command.prototype.usage = function(str) {
  1044. var args = this._args.map(function(arg) {
  1045. return humanReadableArgName(arg);
  1046. });
  1047. var usage = '[options]' +
  1048. (this.commands.length ? ' [command]' : '') +
  1049. (this._args.length ? ' ' + args.join(' ') : '');
  1050. if (arguments.length === 0) return this._usage || usage;
  1051. this._usage = str;
  1052. return this;
  1053. };
  1054. /**
  1055. * Get or set the name of the command
  1056. *
  1057. * @param {String} [str]
  1058. * @return {String|Command}
  1059. * @api public
  1060. */
  1061. Command.prototype.name = function(str) {
  1062. if (arguments.length === 0) return this._name;
  1063. this._name = str;
  1064. return this;
  1065. };
  1066. /**
  1067. * Return prepared commands.
  1068. *
  1069. * @return {Array}
  1070. * @api private
  1071. */
  1072. Command.prototype.prepareCommands = function() {
  1073. return this.commands.filter(function(cmd) {
  1074. return !cmd._noHelp;
  1075. }).map(function(cmd) {
  1076. var args = cmd._args.map(function(arg) {
  1077. return humanReadableArgName(arg);
  1078. }).join(' ');
  1079. return [
  1080. cmd._name +
  1081. (cmd._alias ? '|' + cmd._alias : '') +
  1082. (cmd.options.length ? ' [options]' : '') +
  1083. (args ? ' ' + args : ''),
  1084. cmd._description
  1085. ];
  1086. });
  1087. };
  1088. /**
  1089. * Return the largest command length.
  1090. *
  1091. * @return {Number}
  1092. * @api private
  1093. */
  1094. Command.prototype.largestCommandLength = function() {
  1095. var commands = this.prepareCommands();
  1096. return commands.reduce(function(max, command) {
  1097. return Math.max(max, command[0].length);
  1098. }, 0);
  1099. };
  1100. /**
  1101. * Return the largest option length.
  1102. *
  1103. * @return {Number}
  1104. * @api private
  1105. */
  1106. Command.prototype.largestOptionLength = function() {
  1107. var options = [].slice.call(this.options);
  1108. options.push({
  1109. flags: this._helpFlags
  1110. });
  1111. return options.reduce(function(max, option) {
  1112. return Math.max(max, option.flags.length);
  1113. }, 0);
  1114. };
  1115. /**
  1116. * Return the largest arg length.
  1117. *
  1118. * @return {Number}
  1119. * @api private
  1120. */
  1121. Command.prototype.largestArgLength = function() {
  1122. return this._args.reduce(function(max, arg) {
  1123. return Math.max(max, arg.name.length);
  1124. }, 0);
  1125. };
  1126. /**
  1127. * Return the pad width.
  1128. *
  1129. * @return {Number}
  1130. * @api private
  1131. */
  1132. Command.prototype.padWidth = function() {
  1133. var width = this.largestOptionLength();
  1134. if (this._argsDescription && this._args.length) {
  1135. if (this.largestArgLength() > width) {
  1136. width = this.largestArgLength();
  1137. }
  1138. }
  1139. if (this.commands && this.commands.length) {
  1140. if (this.largestCommandLength() > width) {
  1141. width = this.largestCommandLength();
  1142. }
  1143. }
  1144. return width;
  1145. };
  1146. /**
  1147. * Return help for options.
  1148. *
  1149. * @return {String}
  1150. * @api private
  1151. */
  1152. Command.prototype.optionHelp = function() {
  1153. var width = this.padWidth();
  1154. var columns = process.stdout.columns || 80;
  1155. var descriptionWidth = columns - width - 4;
  1156. // Append the help information
  1157. return this.options.map(function(option) {
  1158. const fullDesc = option.description +
  1159. ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
  1160. return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2);
  1161. }).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)])
  1162. .join('\n');
  1163. };
  1164. /**
  1165. * Return command help documentation.
  1166. *
  1167. * @return {String}
  1168. * @api private
  1169. */
  1170. Command.prototype.commandHelp = function() {
  1171. if (!this.commands.length) return '';
  1172. var commands = this.prepareCommands();
  1173. var width = this.padWidth();
  1174. var columns = process.stdout.columns || 80;
  1175. var descriptionWidth = columns - width - 4;
  1176. return [
  1177. 'Commands:',
  1178. commands.map(function(cmd) {
  1179. var desc = cmd[1] ? ' ' + cmd[1] : '';
  1180. return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);
  1181. }).join('\n').replace(/^/gm, ' '),
  1182. ''
  1183. ].join('\n');
  1184. };
  1185. /**
  1186. * Return program help documentation.
  1187. *
  1188. * @return {String}
  1189. * @api private
  1190. */
  1191. Command.prototype.helpInformation = function() {
  1192. var desc = [];
  1193. if (this._description) {
  1194. desc = [
  1195. this._description,
  1196. ''
  1197. ];
  1198. var argsDescription = this._argsDescription;
  1199. if (argsDescription && this._args.length) {
  1200. var width = this.padWidth();
  1201. var columns = process.stdout.columns || 80;
  1202. var descriptionWidth = columns - width - 5;
  1203. desc.push('Arguments:');
  1204. desc.push('');
  1205. this._args.forEach(function(arg) {
  1206. desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4));
  1207. });
  1208. desc.push('');
  1209. }
  1210. }
  1211. var cmdName = this._name;
  1212. if (this._alias) {
  1213. cmdName = cmdName + '|' + this._alias;
  1214. }
  1215. var parentCmdNames = '';
  1216. for (var parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
  1217. parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
  1218. }
  1219. var usage = [
  1220. 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),
  1221. ''
  1222. ];
  1223. var cmds = [];
  1224. var commandHelp = this.commandHelp();
  1225. if (commandHelp) cmds = [commandHelp];
  1226. var options = [
  1227. 'Options:',
  1228. '' + this.optionHelp().replace(/^/gm, ' '),
  1229. ''
  1230. ];
  1231. return usage
  1232. .concat(desc)
  1233. .concat(options)
  1234. .concat(cmds)
  1235. .join('\n');
  1236. };
  1237. /**
  1238. * Output help information for this command.
  1239. *
  1240. * When listener(s) are available for the helpLongFlag
  1241. * those callbacks are invoked.
  1242. *
  1243. * @api public
  1244. */
  1245. Command.prototype.outputHelp = function(cb) {
  1246. if (!cb) {
  1247. cb = function(passthru) {
  1248. return passthru;
  1249. };
  1250. }
  1251. const cbOutput = cb(this.helpInformation());
  1252. if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {
  1253. throw new Error('outputHelp callback must return a string or a Buffer');
  1254. }
  1255. process.stdout.write(cbOutput);
  1256. this.emit(this._helpLongFlag);
  1257. };
  1258. /**
  1259. * You can pass in flags and a description to override the help
  1260. * flags and help description for your command.
  1261. *
  1262. * @param {String} [flags]
  1263. * @param {String} [description]
  1264. * @return {Command}
  1265. * @api public
  1266. */
  1267. Command.prototype.helpOption = function(flags, description) {
  1268. this._helpFlags = flags || this._helpFlags;
  1269. this._helpDescription = description || this._helpDescription;
  1270. var splitFlags = this._helpFlags.split(/[ ,|]+/);
  1271. if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift();
  1272. this._helpLongFlag = splitFlags.shift();
  1273. return this;
  1274. };
  1275. /**
  1276. * Output help information and exit.
  1277. *
  1278. * @param {Function} [cb]
  1279. * @api public
  1280. */
  1281. Command.prototype.help = function(cb) {
  1282. this.outputHelp(cb);
  1283. // exitCode: preserving original behaviour which was calling process.exit()
  1284. // message: do not have all displayed text available so only passing placeholder.
  1285. this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');
  1286. };
  1287. /**
  1288. * Camel-case the given `flag`
  1289. *
  1290. * @param {String} flag
  1291. * @return {String}
  1292. * @api private
  1293. */
  1294. function camelcase(flag) {
  1295. return flag.split('-').reduce(function(str, word) {
  1296. return str + word[0].toUpperCase() + word.slice(1);
  1297. });
  1298. }
  1299. /**
  1300. * Pad `str` to `width`.
  1301. *
  1302. * @param {String} str
  1303. * @param {Number} width
  1304. * @return {String}
  1305. * @api private
  1306. */
  1307. function pad(str, width) {
  1308. var len = Math.max(0, width - str.length);
  1309. return str + Array(len + 1).join(' ');
  1310. }
  1311. /**
  1312. * Wraps the given string with line breaks at the specified width while breaking
  1313. * words and indenting every but the first line on the left.
  1314. *
  1315. * @param {String} str
  1316. * @param {Number} width
  1317. * @param {Number} indent
  1318. * @return {String}
  1319. * @api private
  1320. */
  1321. function wrap(str, width, indent) {
  1322. var regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
  1323. var lines = str.match(regex) || [];
  1324. return lines.map(function(line, i) {
  1325. if (line.slice(-1) === '\n') {
  1326. line = line.slice(0, line.length - 1);
  1327. }
  1328. return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight();
  1329. }).join('\n');
  1330. }
  1331. /**
  1332. * Optionally wrap the given str to a max width of width characters per line
  1333. * while indenting with indent spaces. Do not wrap if insufficient width or
  1334. * string is manually formatted.
  1335. *
  1336. * @param {String} str
  1337. * @param {Number} width
  1338. * @param {Number} indent
  1339. * @return {String}
  1340. * @api private
  1341. */
  1342. function optionalWrap(str, width, indent) {
  1343. // Detect manually wrapped and indented strings by searching for line breaks
  1344. // followed by multiple spaces/tabs.
  1345. if (str.match(/[\n]\s+/)) return str;
  1346. // Do not wrap to narrow columns (or can end up with a word per line).
  1347. const minWidth = 40;
  1348. if (width < minWidth) return str;
  1349. return wrap(str, width, indent);
  1350. }
  1351. /**
  1352. * Output help information if help flags specified
  1353. *
  1354. * @param {Command} cmd - command to output help for
  1355. * @param {Array} options - array of options to search for -h or --help
  1356. * @api private
  1357. */
  1358. function outputHelpIfRequested(cmd, options) {
  1359. options = options || [];
  1360. for (var i = 0; i < options.length; i++) {
  1361. if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) {
  1362. cmd.outputHelp();
  1363. // (Do not have all displayed text available so only passing placeholder.)
  1364. cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
  1365. }
  1366. }
  1367. }
  1368. /**
  1369. * Takes an argument and returns its human readable equivalent for help usage.
  1370. *
  1371. * @param {Object} arg
  1372. * @return {String}
  1373. * @api private
  1374. */
  1375. function humanReadableArgName(arg) {
  1376. var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
  1377. return arg.required
  1378. ? '<' + nameOutput + '>'
  1379. : '[' + nameOutput + ']';
  1380. }
  1381. // for versions before node v0.8 when there weren't `fs.existsSync`
  1382. function exists(file) {
  1383. try {
  1384. if (fs.statSync(file).isFile()) {
  1385. return true;
  1386. }
  1387. } catch (e) {
  1388. return false;
  1389. }
  1390. }
  1391. /**
  1392. * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
  1393. *
  1394. * @param {string[]} args - array of arguments from node.execArgv
  1395. * @returns {string[]}
  1396. * @api private
  1397. */
  1398. function incrementNodeInspectorPort(args) {
  1399. // Testing for these options:
  1400. // --inspect[=[host:]port]
  1401. // --inspect-brk[=[host:]port]
  1402. // --inspect-port=[host:]port
  1403. return args.map((arg) => {
  1404. var result = arg;
  1405. if (arg.indexOf('--inspect') === 0) {
  1406. var debugOption;
  1407. var debugHost = '127.0.0.1';
  1408. var debugPort = '9229';
  1409. var match;
  1410. if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
  1411. // e.g. --inspect
  1412. debugOption = match[1];
  1413. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
  1414. debugOption = match[1];
  1415. if (/^\d+$/.test(match[3])) {
  1416. // e.g. --inspect=1234
  1417. debugPort = match[3];
  1418. } else {
  1419. // e.g. --inspect=localhost
  1420. debugHost = match[3];
  1421. }
  1422. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
  1423. // e.g. --inspect=localhost:1234
  1424. debugOption = match[1];
  1425. debugHost = match[3];
  1426. debugPort = match[4];
  1427. }
  1428. if (debugOption && debugPort !== '0') {
  1429. result = `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
  1430. }
  1431. }
  1432. return result;
  1433. });
  1434. }