index.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  1. /**
  2. * Module dependencies.
  3. */
  4. const EventEmitter = require('events').EventEmitter;
  5. const childProcess = require('child_process');
  6. const path = require('path');
  7. const fs = require('fs');
  8. // @ts-check
  9. // Although this is a class, methods are static in style to allow override using subclass or just functions.
  10. class Help {
  11. constructor() {
  12. this.helpWidth = undefined;
  13. this.sortSubcommands = false;
  14. this.sortOptions = false;
  15. }
  16. /**
  17. * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
  18. *
  19. * @param {Command} cmd
  20. * @returns {Command[]}
  21. */
  22. visibleCommands(cmd) {
  23. const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);
  24. if (cmd._hasImplicitHelpCommand()) {
  25. // Create a command matching the implicit help command.
  26. const args = cmd._helpCommandnameAndArgs.split(/ +/);
  27. const helpCommand = cmd.createCommand(args.shift())
  28. .helpOption(false);
  29. helpCommand.description(cmd._helpCommandDescription);
  30. helpCommand._parseExpectedArgs(args);
  31. visibleCommands.push(helpCommand);
  32. }
  33. if (this.sortSubcommands) {
  34. visibleCommands.sort((a, b) => {
  35. return a.name().localeCompare(b.name());
  36. });
  37. }
  38. return visibleCommands;
  39. }
  40. /**
  41. * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
  42. *
  43. * @param {Command} cmd
  44. * @returns {Option[]}
  45. */
  46. visibleOptions(cmd) {
  47. const visibleOptions = cmd.options.filter((option) => !option.hidden);
  48. // Implicit help
  49. const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
  50. const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
  51. if (showShortHelpFlag || showLongHelpFlag) {
  52. let helpOption;
  53. if (!showShortHelpFlag) {
  54. helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
  55. } else if (!showLongHelpFlag) {
  56. helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
  57. } else {
  58. helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
  59. }
  60. visibleOptions.push(helpOption);
  61. }
  62. if (this.sortOptions) {
  63. const getSortKey = (option) => {
  64. // WYSIWYG for order displayed in help with short before long, no special handling for negated.
  65. return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');
  66. };
  67. visibleOptions.sort((a, b) => {
  68. return getSortKey(a).localeCompare(getSortKey(b));
  69. });
  70. }
  71. return visibleOptions;
  72. }
  73. /**
  74. * Get an array of the arguments which have descriptions.
  75. *
  76. * @param {Command} cmd
  77. * @returns {{ term: string, description:string }[]}
  78. */
  79. visibleArguments(cmd) {
  80. if (cmd._argsDescription && cmd._args.length) {
  81. return cmd._args.map((argument) => {
  82. return { term: argument.name, description: cmd._argsDescription[argument.name] || '' };
  83. }, 0);
  84. }
  85. return [];
  86. }
  87. /**
  88. * Get the command term to show in the list of subcommands.
  89. *
  90. * @param {Command} cmd
  91. * @returns {string}
  92. */
  93. subcommandTerm(cmd) {
  94. // Legacy. Ignores custom usage string, and nested commands.
  95. const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');
  96. return cmd._name +
  97. (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
  98. (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
  99. (args ? ' ' + args : '');
  100. }
  101. /**
  102. * Get the option term to show in the list of options.
  103. *
  104. * @param {Option} option
  105. * @returns {string}
  106. */
  107. optionTerm(option) {
  108. return option.flags;
  109. }
  110. /**
  111. * Get the longest command term length.
  112. *
  113. * @param {Command} cmd
  114. * @param {Help} helper
  115. * @returns {number}
  116. */
  117. longestSubcommandTermLength(cmd, helper) {
  118. return helper.visibleCommands(cmd).reduce((max, command) => {
  119. return Math.max(max, helper.subcommandTerm(command).length);
  120. }, 0);
  121. };
  122. /**
  123. * Get the longest option term length.
  124. *
  125. * @param {Command} cmd
  126. * @param {Help} helper
  127. * @returns {number}
  128. */
  129. longestOptionTermLength(cmd, helper) {
  130. return helper.visibleOptions(cmd).reduce((max, option) => {
  131. return Math.max(max, helper.optionTerm(option).length);
  132. }, 0);
  133. };
  134. /**
  135. * Get the longest argument term length.
  136. *
  137. * @param {Command} cmd
  138. * @param {Help} helper
  139. * @returns {number}
  140. */
  141. longestArgumentTermLength(cmd, helper) {
  142. return helper.visibleArguments(cmd).reduce((max, argument) => {
  143. return Math.max(max, argument.term.length);
  144. }, 0);
  145. };
  146. /**
  147. * Get the command usage to be displayed at the top of the built-in help.
  148. *
  149. * @param {Command} cmd
  150. * @returns {string}
  151. */
  152. commandUsage(cmd) {
  153. // Usage
  154. let cmdName = cmd._name;
  155. if (cmd._aliases[0]) {
  156. cmdName = cmdName + '|' + cmd._aliases[0];
  157. }
  158. let parentCmdNames = '';
  159. for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
  160. parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
  161. }
  162. return parentCmdNames + cmdName + ' ' + cmd.usage();
  163. }
  164. /**
  165. * Get the description for the command.
  166. *
  167. * @param {Command} cmd
  168. * @returns {string}
  169. */
  170. commandDescription(cmd) {
  171. // @ts-ignore: overloaded return type
  172. return cmd.description();
  173. }
  174. /**
  175. * Get the command description to show in the list of subcommands.
  176. *
  177. * @param {Command} cmd
  178. * @returns {string}
  179. */
  180. subcommandDescription(cmd) {
  181. // @ts-ignore: overloaded return type
  182. return cmd.description();
  183. }
  184. /**
  185. * Get the option description to show in the list of options.
  186. *
  187. * @param {Option} option
  188. * @return {string}
  189. */
  190. optionDescription(option) {
  191. if (option.negate) {
  192. return option.description;
  193. }
  194. const extraInfo = [];
  195. if (option.argChoices) {
  196. extraInfo.push(
  197. // use stringify to match the display of the default value
  198. `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
  199. }
  200. if (option.defaultValue !== undefined) {
  201. extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
  202. }
  203. if (extraInfo.length > 0) {
  204. return `${option.description} (${extraInfo.join(', ')})`;
  205. }
  206. return option.description;
  207. };
  208. /**
  209. * Generate the built-in help text.
  210. *
  211. * @param {Command} cmd
  212. * @param {Help} helper
  213. * @returns {string}
  214. */
  215. formatHelp(cmd, helper) {
  216. const termWidth = helper.padWidth(cmd, helper);
  217. const helpWidth = helper.helpWidth || 80;
  218. const itemIndentWidth = 2;
  219. const itemSeparatorWidth = 2; // between term and description
  220. function formatItem(term, description) {
  221. if (description) {
  222. const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
  223. return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
  224. }
  225. return term;
  226. };
  227. function formatList(textArray) {
  228. return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
  229. }
  230. // Usage
  231. let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
  232. // Description
  233. const commandDescription = helper.commandDescription(cmd);
  234. if (commandDescription.length > 0) {
  235. output = output.concat([commandDescription, '']);
  236. }
  237. // Arguments
  238. const argumentList = helper.visibleArguments(cmd).map((argument) => {
  239. return formatItem(argument.term, argument.description);
  240. });
  241. if (argumentList.length > 0) {
  242. output = output.concat(['Arguments:', formatList(argumentList), '']);
  243. }
  244. // Options
  245. const optionList = helper.visibleOptions(cmd).map((option) => {
  246. return formatItem(helper.optionTerm(option), helper.optionDescription(option));
  247. });
  248. if (optionList.length > 0) {
  249. output = output.concat(['Options:', formatList(optionList), '']);
  250. }
  251. // Commands
  252. const commandList = helper.visibleCommands(cmd).map((cmd) => {
  253. return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));
  254. });
  255. if (commandList.length > 0) {
  256. output = output.concat(['Commands:', formatList(commandList), '']);
  257. }
  258. return output.join('\n');
  259. }
  260. /**
  261. * Calculate the pad width from the maximum term length.
  262. *
  263. * @param {Command} cmd
  264. * @param {Help} helper
  265. * @returns {number}
  266. */
  267. padWidth(cmd, helper) {
  268. return Math.max(
  269. helper.longestOptionTermLength(cmd, helper),
  270. helper.longestSubcommandTermLength(cmd, helper),
  271. helper.longestArgumentTermLength(cmd, helper)
  272. );
  273. };
  274. /**
  275. * Wrap the given string to width characters per line, with lines after the first indented.
  276. * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
  277. *
  278. * @param {string} str
  279. * @param {number} width
  280. * @param {number} indent
  281. * @param {number} [minColumnWidth=40]
  282. * @return {string}
  283. *
  284. */
  285. wrap(str, width, indent, minColumnWidth = 40) {
  286. // Detect manually wrapped and indented strings by searching for line breaks
  287. // followed by multiple spaces/tabs.
  288. if (str.match(/[\n]\s+/)) return str;
  289. // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
  290. const columnWidth = width - indent;
  291. if (columnWidth < minColumnWidth) return str;
  292. const leadingStr = str.substr(0, indent);
  293. const columnText = str.substr(indent);
  294. const indentString = ' '.repeat(indent);
  295. const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
  296. const lines = columnText.match(regex) || [];
  297. return leadingStr + lines.map((line, i) => {
  298. if (line.slice(-1) === '\n') {
  299. line = line.slice(0, line.length - 1);
  300. }
  301. return ((i > 0) ? indentString : '') + line.trimRight();
  302. }).join('\n');
  303. }
  304. }
  305. class Option {
  306. /**
  307. * Initialize a new `Option` with the given `flags` and `description`.
  308. *
  309. * @param {string} flags
  310. * @param {string} [description]
  311. */
  312. constructor(flags, description) {
  313. this.flags = flags;
  314. this.description = description || '';
  315. this.required = flags.includes('<'); // A value must be supplied when the option is specified.
  316. this.optional = flags.includes('['); // A value is optional when the option is specified.
  317. // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
  318. this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
  319. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
  320. const optionFlags = _parseOptionFlags(flags);
  321. this.short = optionFlags.shortFlag;
  322. this.long = optionFlags.longFlag;
  323. this.negate = false;
  324. if (this.long) {
  325. this.negate = this.long.startsWith('--no-');
  326. }
  327. this.defaultValue = undefined;
  328. this.defaultValueDescription = undefined;
  329. this.parseArg = undefined;
  330. this.hidden = false;
  331. this.argChoices = undefined;
  332. }
  333. /**
  334. * Set the default value, and optionally supply the description to be displayed in the help.
  335. *
  336. * @param {any} value
  337. * @param {string} [description]
  338. * @return {Option}
  339. */
  340. default(value, description) {
  341. this.defaultValue = value;
  342. this.defaultValueDescription = description;
  343. return this;
  344. };
  345. /**
  346. * Set the custom handler for processing CLI option arguments into option values.
  347. *
  348. * @param {Function} [fn]
  349. * @return {Option}
  350. */
  351. argParser(fn) {
  352. this.parseArg = fn;
  353. return this;
  354. };
  355. /**
  356. * Whether the option is mandatory and must have a value after parsing.
  357. *
  358. * @param {boolean} [mandatory=true]
  359. * @return {Option}
  360. */
  361. makeOptionMandatory(mandatory = true) {
  362. this.mandatory = !!mandatory;
  363. return this;
  364. };
  365. /**
  366. * Hide option in help.
  367. *
  368. * @param {boolean} [hide=true]
  369. * @return {Option}
  370. */
  371. hideHelp(hide = true) {
  372. this.hidden = !!hide;
  373. return this;
  374. };
  375. /**
  376. * @api private
  377. */
  378. _concatValue(value, previous) {
  379. if (previous === this.defaultValue || !Array.isArray(previous)) {
  380. return [value];
  381. }
  382. return previous.concat(value);
  383. }
  384. /**
  385. * Only allow option value to be one of choices.
  386. *
  387. * @param {string[]} values
  388. * @return {Option}
  389. */
  390. choices(values) {
  391. this.argChoices = values;
  392. this.parseArg = (arg, previous) => {
  393. if (!values.includes(arg)) {
  394. throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(', ')}.`);
  395. }
  396. if (this.variadic) {
  397. return this._concatValue(arg, previous);
  398. }
  399. return arg;
  400. };
  401. return this;
  402. };
  403. /**
  404. * Return option name.
  405. *
  406. * @return {string}
  407. */
  408. name() {
  409. if (this.long) {
  410. return this.long.replace(/^--/, '');
  411. }
  412. return this.short.replace(/^-/, '');
  413. };
  414. /**
  415. * Return option name, in a camelcase format that can be used
  416. * as a object attribute key.
  417. *
  418. * @return {string}
  419. * @api private
  420. */
  421. attributeName() {
  422. return camelcase(this.name().replace(/^no-/, ''));
  423. };
  424. /**
  425. * Check if `arg` matches the short or long flag.
  426. *
  427. * @param {string} arg
  428. * @return {boolean}
  429. * @api private
  430. */
  431. is(arg) {
  432. return this.short === arg || this.long === arg;
  433. };
  434. }
  435. /**
  436. * CommanderError class
  437. * @class
  438. */
  439. class CommanderError extends Error {
  440. /**
  441. * Constructs the CommanderError class
  442. * @param {number} exitCode suggested exit code which could be used with process.exit
  443. * @param {string} code an id string representing the error
  444. * @param {string} message human-readable description of the error
  445. * @constructor
  446. */
  447. constructor(exitCode, code, message) {
  448. super(message);
  449. // properly capture stack trace in Node.js
  450. Error.captureStackTrace(this, this.constructor);
  451. this.name = this.constructor.name;
  452. this.code = code;
  453. this.exitCode = exitCode;
  454. this.nestedError = undefined;
  455. }
  456. }
  457. /**
  458. * InvalidOptionArgumentError class
  459. * @class
  460. */
  461. class InvalidOptionArgumentError extends CommanderError {
  462. /**
  463. * Constructs the InvalidOptionArgumentError class
  464. * @param {string} [message] explanation of why argument is invalid
  465. * @constructor
  466. */
  467. constructor(message) {
  468. super(1, 'commander.invalidOptionArgument', message);
  469. // properly capture stack trace in Node.js
  470. Error.captureStackTrace(this, this.constructor);
  471. this.name = this.constructor.name;
  472. }
  473. }
  474. class Command extends EventEmitter {
  475. /**
  476. * Initialize a new `Command`.
  477. *
  478. * @param {string} [name]
  479. */
  480. constructor(name) {
  481. super();
  482. this.commands = [];
  483. this.options = [];
  484. this.parent = null;
  485. this._allowUnknownOption = false;
  486. this._allowExcessArguments = true;
  487. this._args = [];
  488. this.rawArgs = null;
  489. this._scriptPath = null;
  490. this._name = name || '';
  491. this._optionValues = {};
  492. this._storeOptionsAsProperties = false;
  493. this._actionResults = [];
  494. this._actionHandler = null;
  495. this._executableHandler = false;
  496. this._executableFile = null; // custom name for executable
  497. this._defaultCommandName = null;
  498. this._exitCallback = null;
  499. this._aliases = [];
  500. this._combineFlagAndOptionalValue = true;
  501. this._description = '';
  502. this._argsDescription = undefined;
  503. this._enablePositionalOptions = false;
  504. this._passThroughOptions = false;
  505. // see .configureOutput() for docs
  506. this._outputConfiguration = {
  507. writeOut: (str) => process.stdout.write(str),
  508. writeErr: (str) => process.stderr.write(str),
  509. getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,
  510. getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,
  511. outputError: (str, write) => write(str)
  512. };
  513. this._hidden = false;
  514. this._hasHelpOption = true;
  515. this._helpFlags = '-h, --help';
  516. this._helpDescription = 'display help for command';
  517. this._helpShortFlag = '-h';
  518. this._helpLongFlag = '--help';
  519. this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false
  520. this._helpCommandName = 'help';
  521. this._helpCommandnameAndArgs = 'help [command]';
  522. this._helpCommandDescription = 'display help for command';
  523. this._helpConfiguration = {};
  524. }
  525. /**
  526. * Define a command.
  527. *
  528. * There are two styles of command: pay attention to where to put the description.
  529. *
  530. * Examples:
  531. *
  532. * // Command implemented using action handler (description is supplied separately to `.command`)
  533. * program
  534. * .command('clone <source> [destination]')
  535. * .description('clone a repository into a newly created directory')
  536. * .action((source, destination) => {
  537. * console.log('clone command called');
  538. * });
  539. *
  540. * // Command implemented using separate executable file (description is second parameter to `.command`)
  541. * program
  542. * .command('start <service>', 'start named service')
  543. * .command('stop [service]', 'stop named service, or all if no name supplied');
  544. *
  545. * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
  546. * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
  547. * @param {Object} [execOpts] - configuration options (for executable)
  548. * @return {Command} returns new command for action handler, or `this` for executable command
  549. */
  550. command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
  551. let desc = actionOptsOrExecDesc;
  552. let opts = execOpts;
  553. if (typeof desc === 'object' && desc !== null) {
  554. opts = desc;
  555. desc = null;
  556. }
  557. opts = opts || {};
  558. const args = nameAndArgs.split(/ +/);
  559. const cmd = this.createCommand(args.shift());
  560. if (desc) {
  561. cmd.description(desc);
  562. cmd._executableHandler = true;
  563. }
  564. if (opts.isDefault) this._defaultCommandName = cmd._name;
  565. cmd._outputConfiguration = this._outputConfiguration;
  566. cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
  567. cmd._hasHelpOption = this._hasHelpOption;
  568. cmd._helpFlags = this._helpFlags;
  569. cmd._helpDescription = this._helpDescription;
  570. cmd._helpShortFlag = this._helpShortFlag;
  571. cmd._helpLongFlag = this._helpLongFlag;
  572. cmd._helpCommandName = this._helpCommandName;
  573. cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;
  574. cmd._helpCommandDescription = this._helpCommandDescription;
  575. cmd._helpConfiguration = this._helpConfiguration;
  576. cmd._exitCallback = this._exitCallback;
  577. cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
  578. cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;
  579. cmd._allowExcessArguments = this._allowExcessArguments;
  580. cmd._enablePositionalOptions = this._enablePositionalOptions;
  581. cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
  582. this.commands.push(cmd);
  583. cmd._parseExpectedArgs(args);
  584. cmd.parent = this;
  585. if (desc) return this;
  586. return cmd;
  587. };
  588. /**
  589. * Factory routine to create a new unattached command.
  590. *
  591. * See .command() for creating an attached subcommand, which uses this routine to
  592. * create the command. You can override createCommand to customise subcommands.
  593. *
  594. * @param {string} [name]
  595. * @return {Command} new command
  596. */
  597. createCommand(name) {
  598. return new Command(name);
  599. };
  600. /**
  601. * You can customise the help with a subclass of Help by overriding createHelp,
  602. * or by overriding Help properties using configureHelp().
  603. *
  604. * @return {Help}
  605. */
  606. createHelp() {
  607. return Object.assign(new Help(), this.configureHelp());
  608. };
  609. /**
  610. * You can customise the help by overriding Help properties using configureHelp(),
  611. * or with a subclass of Help by overriding createHelp().
  612. *
  613. * @param {Object} [configuration] - configuration options
  614. * @return {Command|Object} `this` command for chaining, or stored configuration
  615. */
  616. configureHelp(configuration) {
  617. if (configuration === undefined) return this._helpConfiguration;
  618. this._helpConfiguration = configuration;
  619. return this;
  620. }
  621. /**
  622. * The default output goes to stdout and stderr. You can customise this for special
  623. * applications. You can also customise the display of errors by overriding outputError.
  624. *
  625. * The configuration properties are all functions:
  626. *
  627. * // functions to change where being written, stdout and stderr
  628. * writeOut(str)
  629. * writeErr(str)
  630. * // matching functions to specify width for wrapping help
  631. * getOutHelpWidth()
  632. * getErrHelpWidth()
  633. * // functions based on what is being written out
  634. * outputError(str, write) // used for displaying errors, and not used for displaying help
  635. *
  636. * @param {Object} [configuration] - configuration options
  637. * @return {Command|Object} `this` command for chaining, or stored configuration
  638. */
  639. configureOutput(configuration) {
  640. if (configuration === undefined) return this._outputConfiguration;
  641. Object.assign(this._outputConfiguration, configuration);
  642. return this;
  643. }
  644. /**
  645. * Add a prepared subcommand.
  646. *
  647. * See .command() for creating an attached subcommand which inherits settings from its parent.
  648. *
  649. * @param {Command} cmd - new subcommand
  650. * @param {Object} [opts] - configuration options
  651. * @return {Command} `this` command for chaining
  652. */
  653. addCommand(cmd, opts) {
  654. if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
  655. // To keep things simple, block automatic name generation for deeply nested executables.
  656. // Fail fast and detect when adding rather than later when parsing.
  657. function checkExplicitNames(commandArray) {
  658. commandArray.forEach((cmd) => {
  659. if (cmd._executableHandler && !cmd._executableFile) {
  660. throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);
  661. }
  662. checkExplicitNames(cmd.commands);
  663. });
  664. }
  665. checkExplicitNames(cmd.commands);
  666. opts = opts || {};
  667. if (opts.isDefault) this._defaultCommandName = cmd._name;
  668. if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
  669. this.commands.push(cmd);
  670. cmd.parent = this;
  671. return this;
  672. };
  673. /**
  674. * Define argument syntax for the command.
  675. */
  676. arguments(desc) {
  677. return this._parseExpectedArgs(desc.split(/ +/));
  678. };
  679. /**
  680. * Override default decision whether to add implicit help command.
  681. *
  682. * addHelpCommand() // force on
  683. * addHelpCommand(false); // force off
  684. * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
  685. *
  686. * @return {Command} `this` command for chaining
  687. */
  688. addHelpCommand(enableOrNameAndArgs, description) {
  689. if (enableOrNameAndArgs === false) {
  690. this._addImplicitHelpCommand = false;
  691. } else {
  692. this._addImplicitHelpCommand = true;
  693. if (typeof enableOrNameAndArgs === 'string') {
  694. this._helpCommandName = enableOrNameAndArgs.split(' ')[0];
  695. this._helpCommandnameAndArgs = enableOrNameAndArgs;
  696. }
  697. this._helpCommandDescription = description || this._helpCommandDescription;
  698. }
  699. return this;
  700. };
  701. /**
  702. * @return {boolean}
  703. * @api private
  704. */
  705. _hasImplicitHelpCommand() {
  706. if (this._addImplicitHelpCommand === undefined) {
  707. return this.commands.length && !this._actionHandler && !this._findCommand('help');
  708. }
  709. return this._addImplicitHelpCommand;
  710. };
  711. /**
  712. * Parse expected `args`.
  713. *
  714. * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
  715. *
  716. * @param {Array} args
  717. * @return {Command} `this` command for chaining
  718. * @api private
  719. */
  720. _parseExpectedArgs(args) {
  721. if (!args.length) return;
  722. args.forEach((arg) => {
  723. const argDetails = {
  724. required: false,
  725. name: '',
  726. variadic: false
  727. };
  728. switch (arg[0]) {
  729. case '<':
  730. argDetails.required = true;
  731. argDetails.name = arg.slice(1, -1);
  732. break;
  733. case '[':
  734. argDetails.name = arg.slice(1, -1);
  735. break;
  736. }
  737. if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
  738. argDetails.variadic = true;
  739. argDetails.name = argDetails.name.slice(0, -3);
  740. }
  741. if (argDetails.name) {
  742. this._args.push(argDetails);
  743. }
  744. });
  745. this._args.forEach((arg, i) => {
  746. if (arg.variadic && i < this._args.length - 1) {
  747. throw new Error(`only the last argument can be variadic '${arg.name}'`);
  748. }
  749. });
  750. return this;
  751. };
  752. /**
  753. * Register callback to use as replacement for calling process.exit.
  754. *
  755. * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
  756. * @return {Command} `this` command for chaining
  757. */
  758. exitOverride(fn) {
  759. if (fn) {
  760. this._exitCallback = fn;
  761. } else {
  762. this._exitCallback = (err) => {
  763. if (err.code !== 'commander.executeSubCommandAsync') {
  764. throw err;
  765. } else {
  766. // Async callback from spawn events, not useful to throw.
  767. }
  768. };
  769. }
  770. return this;
  771. };
  772. /**
  773. * Call process.exit, and _exitCallback if defined.
  774. *
  775. * @param {number} exitCode exit code for using with process.exit
  776. * @param {string} code an id string representing the error
  777. * @param {string} message human-readable description of the error
  778. * @return never
  779. * @api private
  780. */
  781. _exit(exitCode, code, message) {
  782. if (this._exitCallback) {
  783. this._exitCallback(new CommanderError(exitCode, code, message));
  784. // Expecting this line is not reached.
  785. }
  786. process.exit(exitCode);
  787. };
  788. /**
  789. * Register callback `fn` for the command.
  790. *
  791. * Examples:
  792. *
  793. * program
  794. * .command('help')
  795. * .description('display verbose help')
  796. * .action(function() {
  797. * // output help here
  798. * });
  799. *
  800. * @param {Function} fn
  801. * @return {Command} `this` command for chaining
  802. */
  803. action(fn) {
  804. const listener = (args) => {
  805. // The .action callback takes an extra parameter which is the command or options.
  806. const expectedArgsCount = this._args.length;
  807. const actionArgs = args.slice(0, expectedArgsCount);
  808. if (this._storeOptionsAsProperties) {
  809. actionArgs[expectedArgsCount] = this; // backwards compatible "options"
  810. } else {
  811. actionArgs[expectedArgsCount] = this.opts();
  812. }
  813. actionArgs.push(this);
  814. const actionResult = fn.apply(this, actionArgs);
  815. // Remember result in case it is async. Assume parseAsync getting called on root.
  816. let rootCommand = this;
  817. while (rootCommand.parent) {
  818. rootCommand = rootCommand.parent;
  819. }
  820. rootCommand._actionResults.push(actionResult);
  821. };
  822. this._actionHandler = listener;
  823. return this;
  824. };
  825. /**
  826. * Factory routine to create a new unattached option.
  827. *
  828. * See .option() for creating an attached option, which uses this routine to
  829. * create the option. You can override createOption to return a custom option.
  830. *
  831. * @param {string} flags
  832. * @param {string} [description]
  833. * @return {Option} new option
  834. */
  835. createOption(flags, description) {
  836. return new Option(flags, description);
  837. };
  838. /**
  839. * Add an option.
  840. *
  841. * @param {Option} option
  842. * @return {Command} `this` command for chaining
  843. */
  844. addOption(option) {
  845. const oname = option.name();
  846. const name = option.attributeName();
  847. let defaultValue = option.defaultValue;
  848. // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value
  849. if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
  850. // when --no-foo we make sure default is true, unless a --foo option is already defined
  851. if (option.negate) {
  852. const positiveLongFlag = option.long.replace(/^--no-/, '--');
  853. defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true;
  854. }
  855. // preassign only if we have a default
  856. if (defaultValue !== undefined) {
  857. this._setOptionValue(name, defaultValue);
  858. }
  859. }
  860. // register the option
  861. this.options.push(option);
  862. // when it's passed assign the value
  863. // and conditionally invoke the callback
  864. this.on('option:' + oname, (val) => {
  865. const oldValue = this._getOptionValue(name);
  866. // custom processing
  867. if (val !== null && option.parseArg) {
  868. try {
  869. val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);
  870. } catch (err) {
  871. if (err.code === 'commander.invalidOptionArgument') {
  872. const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;
  873. this._displayError(err.exitCode, err.code, message);
  874. }
  875. throw err;
  876. }
  877. } else if (val !== null && option.variadic) {
  878. val = option._concatValue(val, oldValue);
  879. }
  880. // unassigned or boolean value
  881. if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {
  882. // if no value, negate false, and we have a default, then use it!
  883. if (val == null) {
  884. this._setOptionValue(name, option.negate
  885. ? false
  886. : defaultValue || true);
  887. } else {
  888. this._setOptionValue(name, val);
  889. }
  890. } else if (val !== null) {
  891. // reassign
  892. this._setOptionValue(name, option.negate ? false : val);
  893. }
  894. });
  895. return this;
  896. }
  897. /**
  898. * Internal implementation shared by .option() and .requiredOption()
  899. *
  900. * @api private
  901. */
  902. _optionEx(config, flags, description, fn, defaultValue) {
  903. const option = this.createOption(flags, description);
  904. option.makeOptionMandatory(!!config.mandatory);
  905. if (typeof fn === 'function') {
  906. option.default(defaultValue).argParser(fn);
  907. } else if (fn instanceof RegExp) {
  908. // deprecated
  909. const regex = fn;
  910. fn = (val, def) => {
  911. const m = regex.exec(val);
  912. return m ? m[0] : def;
  913. };
  914. option.default(defaultValue).argParser(fn);
  915. } else {
  916. option.default(fn);
  917. }
  918. return this.addOption(option);
  919. }
  920. /**
  921. * Define option with `flags`, `description` and optional
  922. * coercion `fn`.
  923. *
  924. * The `flags` string contains the short and/or long flags,
  925. * separated by comma, a pipe or space. The following are all valid
  926. * all will output this way when `--help` is used.
  927. *
  928. * "-p, --pepper"
  929. * "-p|--pepper"
  930. * "-p --pepper"
  931. *
  932. * Examples:
  933. *
  934. * // simple boolean defaulting to undefined
  935. * program.option('-p, --pepper', 'add pepper');
  936. *
  937. * program.pepper
  938. * // => undefined
  939. *
  940. * --pepper
  941. * program.pepper
  942. * // => true
  943. *
  944. * // simple boolean defaulting to true (unless non-negated option is also defined)
  945. * program.option('-C, --no-cheese', 'remove cheese');
  946. *
  947. * program.cheese
  948. * // => true
  949. *
  950. * --no-cheese
  951. * program.cheese
  952. * // => false
  953. *
  954. * // required argument
  955. * program.option('-C, --chdir <path>', 'change the working directory');
  956. *
  957. * --chdir /tmp
  958. * program.chdir
  959. * // => "/tmp"
  960. *
  961. * // optional argument
  962. * program.option('-c, --cheese [type]', 'add cheese [marble]');
  963. *
  964. * @param {string} flags
  965. * @param {string} [description]
  966. * @param {Function|*} [fn] - custom option processing function or default value
  967. * @param {*} [defaultValue]
  968. * @return {Command} `this` command for chaining
  969. */
  970. option(flags, description, fn, defaultValue) {
  971. return this._optionEx({}, flags, description, fn, defaultValue);
  972. };
  973. /**
  974. * Add a required option which must have a value after parsing. This usually means
  975. * the option must be specified on the command line. (Otherwise the same as .option().)
  976. *
  977. * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
  978. *
  979. * @param {string} flags
  980. * @param {string} [description]
  981. * @param {Function|*} [fn] - custom option processing function or default value
  982. * @param {*} [defaultValue]
  983. * @return {Command} `this` command for chaining
  984. */
  985. requiredOption(flags, description, fn, defaultValue) {
  986. return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
  987. };
  988. /**
  989. * Alter parsing of short flags with optional values.
  990. *
  991. * Examples:
  992. *
  993. * // for `.option('-f,--flag [value]'):
  994. * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
  995. * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
  996. *
  997. * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
  998. */
  999. combineFlagAndOptionalValue(combine = true) {
  1000. this._combineFlagAndOptionalValue = !!combine;
  1001. return this;
  1002. };
  1003. /**
  1004. * Allow unknown options on the command line.
  1005. *
  1006. * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
  1007. * for unknown options.
  1008. */
  1009. allowUnknownOption(allowUnknown = true) {
  1010. this._allowUnknownOption = !!allowUnknown;
  1011. return this;
  1012. };
  1013. /**
  1014. * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
  1015. *
  1016. * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
  1017. * for excess arguments.
  1018. */
  1019. allowExcessArguments(allowExcess = true) {
  1020. this._allowExcessArguments = !!allowExcess;
  1021. return this;
  1022. };
  1023. /**
  1024. * Enable positional options. Positional means global options are specified before subcommands which lets
  1025. * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
  1026. * The default behaviour is non-positional and global options may appear anywhere on the command line.
  1027. *
  1028. * @param {Boolean} [positional=true]
  1029. */
  1030. enablePositionalOptions(positional = true) {
  1031. this._enablePositionalOptions = !!positional;
  1032. return this;
  1033. };
  1034. /**
  1035. * Pass through options that come after command-arguments rather than treat them as command-options,
  1036. * so actual command-options come before command-arguments. Turning this on for a subcommand requires
  1037. * positional options to have been enabled on the program (parent commands).
  1038. * The default behaviour is non-positional and options may appear before or after command-arguments.
  1039. *
  1040. * @param {Boolean} [passThrough=true]
  1041. * for unknown options.
  1042. */
  1043. passThroughOptions(passThrough = true) {
  1044. this._passThroughOptions = !!passThrough;
  1045. if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
  1046. throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');
  1047. }
  1048. return this;
  1049. };
  1050. /**
  1051. * Whether to store option values as properties on command object,
  1052. * or store separately (specify false). In both cases the option values can be accessed using .opts().
  1053. *
  1054. * @param {boolean} [storeAsProperties=true]
  1055. * @return {Command} `this` command for chaining
  1056. */
  1057. storeOptionsAsProperties(storeAsProperties = true) {
  1058. this._storeOptionsAsProperties = !!storeAsProperties;
  1059. if (this.options.length) {
  1060. throw new Error('call .storeOptionsAsProperties() before adding options');
  1061. }
  1062. return this;
  1063. };
  1064. /**
  1065. * Store option value
  1066. *
  1067. * @param {string} key
  1068. * @param {Object} value
  1069. * @api private
  1070. */
  1071. _setOptionValue(key, value) {
  1072. if (this._storeOptionsAsProperties) {
  1073. this[key] = value;
  1074. } else {
  1075. this._optionValues[key] = value;
  1076. }
  1077. };
  1078. /**
  1079. * Retrieve option value
  1080. *
  1081. * @param {string} key
  1082. * @return {Object} value
  1083. * @api private
  1084. */
  1085. _getOptionValue(key) {
  1086. if (this._storeOptionsAsProperties) {
  1087. return this[key];
  1088. }
  1089. return this._optionValues[key];
  1090. };
  1091. /**
  1092. * Parse `argv`, setting options and invoking commands when defined.
  1093. *
  1094. * The default expectation is that the arguments are from node and have the application as argv[0]
  1095. * and the script being run in argv[1], with user parameters after that.
  1096. *
  1097. * Examples:
  1098. *
  1099. * program.parse(process.argv);
  1100. * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
  1101. * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  1102. *
  1103. * @param {string[]} [argv] - optional, defaults to process.argv
  1104. * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
  1105. * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
  1106. * @return {Command} `this` command for chaining
  1107. */
  1108. parse(argv, parseOptions) {
  1109. if (argv !== undefined && !Array.isArray(argv)) {
  1110. throw new Error('first parameter to parse must be array or undefined');
  1111. }
  1112. parseOptions = parseOptions || {};
  1113. // Default to using process.argv
  1114. if (argv === undefined) {
  1115. argv = process.argv;
  1116. // @ts-ignore: unknown property
  1117. if (process.versions && process.versions.electron) {
  1118. parseOptions.from = 'electron';
  1119. }
  1120. }
  1121. this.rawArgs = argv.slice();
  1122. // make it a little easier for callers by supporting various argv conventions
  1123. let userArgs;
  1124. switch (parseOptions.from) {
  1125. case undefined:
  1126. case 'node':
  1127. this._scriptPath = argv[1];
  1128. userArgs = argv.slice(2);
  1129. break;
  1130. case 'electron':
  1131. // @ts-ignore: unknown property
  1132. if (process.defaultApp) {
  1133. this._scriptPath = argv[1];
  1134. userArgs = argv.slice(2);
  1135. } else {
  1136. userArgs = argv.slice(1);
  1137. }
  1138. break;
  1139. case 'user':
  1140. userArgs = argv.slice(0);
  1141. break;
  1142. default:
  1143. throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
  1144. }
  1145. if (!this._scriptPath && require.main) {
  1146. this._scriptPath = require.main.filename;
  1147. }
  1148. // Guess name, used in usage in help.
  1149. this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));
  1150. // Let's go!
  1151. this._parseCommand([], userArgs);
  1152. return this;
  1153. };
  1154. /**
  1155. * Parse `argv`, setting options and invoking commands when defined.
  1156. *
  1157. * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
  1158. *
  1159. * The default expectation is that the arguments are from node and have the application as argv[0]
  1160. * and the script being run in argv[1], with user parameters after that.
  1161. *
  1162. * Examples:
  1163. *
  1164. * program.parseAsync(process.argv);
  1165. * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
  1166. * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  1167. *
  1168. * @param {string[]} [argv]
  1169. * @param {Object} [parseOptions]
  1170. * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
  1171. * @return {Promise}
  1172. */
  1173. parseAsync(argv, parseOptions) {
  1174. this.parse(argv, parseOptions);
  1175. return Promise.all(this._actionResults).then(() => this);
  1176. };
  1177. /**
  1178. * Execute a sub-command executable.
  1179. *
  1180. * @api private
  1181. */
  1182. _executeSubCommand(subcommand, args) {
  1183. args = args.slice();
  1184. let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
  1185. const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
  1186. // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
  1187. this._checkForMissingMandatoryOptions();
  1188. // Want the entry script as the reference for command name and directory for searching for other files.
  1189. let scriptPath = this._scriptPath;
  1190. // Fallback in case not set, due to how Command created or called.
  1191. if (!scriptPath && require.main) {
  1192. scriptPath = require.main.filename;
  1193. }
  1194. let baseDir;
  1195. try {
  1196. const resolvedLink = fs.realpathSync(scriptPath);
  1197. baseDir = path.dirname(resolvedLink);
  1198. } catch (e) {
  1199. baseDir = '.'; // dummy, probably not going to find executable!
  1200. }
  1201. // name of the subcommand, like `pm-install`
  1202. let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;
  1203. if (subcommand._executableFile) {
  1204. bin = subcommand._executableFile;
  1205. }
  1206. const localBin = path.join(baseDir, bin);
  1207. if (fs.existsSync(localBin)) {
  1208. // prefer local `./<bin>` to bin in the $PATH
  1209. bin = localBin;
  1210. } else {
  1211. // Look for source files.
  1212. sourceExt.forEach((ext) => {
  1213. if (fs.existsSync(`${localBin}${ext}`)) {
  1214. bin = `${localBin}${ext}`;
  1215. }
  1216. });
  1217. }
  1218. launchWithNode = sourceExt.includes(path.extname(bin));
  1219. let proc;
  1220. if (process.platform !== 'win32') {
  1221. if (launchWithNode) {
  1222. args.unshift(bin);
  1223. // add executable arguments to spawn
  1224. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  1225. proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
  1226. } else {
  1227. proc = childProcess.spawn(bin, args, { stdio: 'inherit' });
  1228. }
  1229. } else {
  1230. args.unshift(bin);
  1231. // add executable arguments to spawn
  1232. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  1233. proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
  1234. }
  1235. const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  1236. signals.forEach((signal) => {
  1237. // @ts-ignore
  1238. process.on(signal, () => {
  1239. if (proc.killed === false && proc.exitCode === null) {
  1240. proc.kill(signal);
  1241. }
  1242. });
  1243. });
  1244. // By default terminate process when spawned process terminates.
  1245. // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
  1246. const exitCallback = this._exitCallback;
  1247. if (!exitCallback) {
  1248. proc.on('close', process.exit.bind(process));
  1249. } else {
  1250. proc.on('close', () => {
  1251. exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
  1252. });
  1253. }
  1254. proc.on('error', (err) => {
  1255. // @ts-ignore
  1256. if (err.code === 'ENOENT') {
  1257. const executableMissing = `'${bin}' does not exist
  1258. - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
  1259. - if the default executable name is not suitable, use the executableFile option to supply a custom name`;
  1260. throw new Error(executableMissing);
  1261. // @ts-ignore
  1262. } else if (err.code === 'EACCES') {
  1263. throw new Error(`'${bin}' not executable`);
  1264. }
  1265. if (!exitCallback) {
  1266. process.exit(1);
  1267. } else {
  1268. const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
  1269. wrappedError.nestedError = err;
  1270. exitCallback(wrappedError);
  1271. }
  1272. });
  1273. // Store the reference to the child process
  1274. this.runningCommand = proc;
  1275. };
  1276. /**
  1277. * @api private
  1278. */
  1279. _dispatchSubcommand(commandName, operands, unknown) {
  1280. const subCommand = this._findCommand(commandName);
  1281. if (!subCommand) this.help({ error: true });
  1282. if (subCommand._executableHandler) {
  1283. this._executeSubCommand(subCommand, operands.concat(unknown));
  1284. } else {
  1285. subCommand._parseCommand(operands, unknown);
  1286. }
  1287. };
  1288. /**
  1289. * Process arguments in context of this command.
  1290. *
  1291. * @api private
  1292. */
  1293. _parseCommand(operands, unknown) {
  1294. const parsed = this.parseOptions(unknown);
  1295. operands = operands.concat(parsed.operands);
  1296. unknown = parsed.unknown;
  1297. this.args = operands.concat(unknown);
  1298. if (operands && this._findCommand(operands[0])) {
  1299. this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
  1300. } else if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
  1301. if (operands.length === 1) {
  1302. this.help();
  1303. } else {
  1304. this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
  1305. }
  1306. } else if (this._defaultCommandName) {
  1307. outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
  1308. this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
  1309. } else {
  1310. if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
  1311. // probably missing subcommand and no handler, user needs help
  1312. this.help({ error: true });
  1313. }
  1314. outputHelpIfRequested(this, parsed.unknown);
  1315. this._checkForMissingMandatoryOptions();
  1316. // We do not always call this check to avoid masking a "better" error, like unknown command.
  1317. const checkForUnknownOptions = () => {
  1318. if (parsed.unknown.length > 0) {
  1319. this.unknownOption(parsed.unknown[0]);
  1320. }
  1321. };
  1322. const commandEvent = `command:${this.name()}`;
  1323. if (this._actionHandler) {
  1324. checkForUnknownOptions();
  1325. // Check expected arguments and collect variadic together.
  1326. const args = this.args.slice();
  1327. this._args.forEach((arg, i) => {
  1328. if (arg.required && args[i] == null) {
  1329. this.missingArgument(arg.name);
  1330. } else if (arg.variadic) {
  1331. args[i] = args.splice(i);
  1332. args.length = Math.min(i + 1, args.length);
  1333. }
  1334. });
  1335. if (args.length > this._args.length) {
  1336. this._excessArguments(args);
  1337. }
  1338. this._actionHandler(args);
  1339. if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy
  1340. } else if (this.parent && this.parent.listenerCount(commandEvent)) {
  1341. checkForUnknownOptions();
  1342. this.parent.emit(commandEvent, operands, unknown); // legacy
  1343. } else if (operands.length) {
  1344. if (this._findCommand('*')) { // legacy default command
  1345. this._dispatchSubcommand('*', operands, unknown);
  1346. } else if (this.listenerCount('command:*')) {
  1347. // skip option check, emit event for possible misspelling suggestion
  1348. this.emit('command:*', operands, unknown);
  1349. } else if (this.commands.length) {
  1350. this.unknownCommand();
  1351. } else {
  1352. checkForUnknownOptions();
  1353. }
  1354. } else if (this.commands.length) {
  1355. // This command has subcommands and nothing hooked up at this level, so display help.
  1356. this.help({ error: true });
  1357. } else {
  1358. checkForUnknownOptions();
  1359. // fall through for caller to handle after calling .parse()
  1360. }
  1361. }
  1362. };
  1363. /**
  1364. * Find matching command.
  1365. *
  1366. * @api private
  1367. */
  1368. _findCommand(name) {
  1369. if (!name) return undefined;
  1370. return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
  1371. };
  1372. /**
  1373. * Return an option matching `arg` if any.
  1374. *
  1375. * @param {string} arg
  1376. * @return {Option}
  1377. * @api private
  1378. */
  1379. _findOption(arg) {
  1380. return this.options.find(option => option.is(arg));
  1381. };
  1382. /**
  1383. * Display an error message if a mandatory option does not have a value.
  1384. * Lazy calling after checking for help flags from leaf subcommand.
  1385. *
  1386. * @api private
  1387. */
  1388. _checkForMissingMandatoryOptions() {
  1389. // Walk up hierarchy so can call in subcommand after checking for displaying help.
  1390. for (let cmd = this; cmd; cmd = cmd.parent) {
  1391. cmd.options.forEach((anOption) => {
  1392. if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
  1393. cmd.missingMandatoryOptionValue(anOption);
  1394. }
  1395. });
  1396. }
  1397. };
  1398. /**
  1399. * Parse options from `argv` removing known options,
  1400. * and return argv split into operands and unknown arguments.
  1401. *
  1402. * Examples:
  1403. *
  1404. * argv => operands, unknown
  1405. * --known kkk op => [op], []
  1406. * op --known kkk => [op], []
  1407. * sub --unknown uuu op => [sub], [--unknown uuu op]
  1408. * sub -- --unknown uuu op => [sub --unknown uuu op], []
  1409. *
  1410. * @param {String[]} argv
  1411. * @return {{operands: String[], unknown: String[]}}
  1412. */
  1413. parseOptions(argv) {
  1414. const operands = []; // operands, not options or values
  1415. const unknown = []; // first unknown option and remaining unknown args
  1416. let dest = operands;
  1417. const args = argv.slice();
  1418. function maybeOption(arg) {
  1419. return arg.length > 1 && arg[0] === '-';
  1420. }
  1421. // parse options
  1422. let activeVariadicOption = null;
  1423. while (args.length) {
  1424. const arg = args.shift();
  1425. // literal
  1426. if (arg === '--') {
  1427. if (dest === unknown) dest.push(arg);
  1428. dest.push(...args);
  1429. break;
  1430. }
  1431. if (activeVariadicOption && !maybeOption(arg)) {
  1432. this.emit(`option:${activeVariadicOption.name()}`, arg);
  1433. continue;
  1434. }
  1435. activeVariadicOption = null;
  1436. if (maybeOption(arg)) {
  1437. const option = this._findOption(arg);
  1438. // recognised option, call listener to assign value with possible custom processing
  1439. if (option) {
  1440. if (option.required) {
  1441. const value = args.shift();
  1442. if (value === undefined) this.optionMissingArgument(option);
  1443. this.emit(`option:${option.name()}`, value);
  1444. } else if (option.optional) {
  1445. let value = null;
  1446. // historical behaviour is optional value is following arg unless an option
  1447. if (args.length > 0 && !maybeOption(args[0])) {
  1448. value = args.shift();
  1449. }
  1450. this.emit(`option:${option.name()}`, value);
  1451. } else { // boolean flag
  1452. this.emit(`option:${option.name()}`);
  1453. }
  1454. activeVariadicOption = option.variadic ? option : null;
  1455. continue;
  1456. }
  1457. }
  1458. // Look for combo options following single dash, eat first one if known.
  1459. if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
  1460. const option = this._findOption(`-${arg[1]}`);
  1461. if (option) {
  1462. if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
  1463. // option with value following in same argument
  1464. this.emit(`option:${option.name()}`, arg.slice(2));
  1465. } else {
  1466. // boolean option, emit and put back remainder of arg for further processing
  1467. this.emit(`option:${option.name()}`);
  1468. args.unshift(`-${arg.slice(2)}`);
  1469. }
  1470. continue;
  1471. }
  1472. }
  1473. // Look for known long flag with value, like --foo=bar
  1474. if (/^--[^=]+=/.test(arg)) {
  1475. const index = arg.indexOf('=');
  1476. const option = this._findOption(arg.slice(0, index));
  1477. if (option && (option.required || option.optional)) {
  1478. this.emit(`option:${option.name()}`, arg.slice(index + 1));
  1479. continue;
  1480. }
  1481. }
  1482. // Not a recognised option by this command.
  1483. // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
  1484. // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
  1485. if (maybeOption(arg)) {
  1486. dest = unknown;
  1487. }
  1488. // If using positionalOptions, stop processing our options at subcommand.
  1489. if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
  1490. if (this._findCommand(arg)) {
  1491. operands.push(arg);
  1492. if (args.length > 0) unknown.push(...args);
  1493. break;
  1494. } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
  1495. operands.push(arg);
  1496. if (args.length > 0) operands.push(...args);
  1497. break;
  1498. } else if (this._defaultCommandName) {
  1499. unknown.push(arg);
  1500. if (args.length > 0) unknown.push(...args);
  1501. break;
  1502. }
  1503. }
  1504. // If using passThroughOptions, stop processing options at first command-argument.
  1505. if (this._passThroughOptions) {
  1506. dest.push(arg);
  1507. if (args.length > 0) dest.push(...args);
  1508. break;
  1509. }
  1510. // add arg
  1511. dest.push(arg);
  1512. }
  1513. return { operands, unknown };
  1514. };
  1515. /**
  1516. * Return an object containing options as key-value pairs
  1517. *
  1518. * @return {Object}
  1519. */
  1520. opts() {
  1521. if (this._storeOptionsAsProperties) {
  1522. // Preserve original behaviour so backwards compatible when still using properties
  1523. const result = {};
  1524. const len = this.options.length;
  1525. for (let i = 0; i < len; i++) {
  1526. const key = this.options[i].attributeName();
  1527. result[key] = key === this._versionOptionName ? this._version : this[key];
  1528. }
  1529. return result;
  1530. }
  1531. return this._optionValues;
  1532. };
  1533. /**
  1534. * Internal bottleneck for handling of parsing errors.
  1535. *
  1536. * @api private
  1537. */
  1538. _displayError(exitCode, code, message) {
  1539. this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
  1540. this._exit(exitCode, code, message);
  1541. }
  1542. /**
  1543. * Argument `name` is missing.
  1544. *
  1545. * @param {string} name
  1546. * @api private
  1547. */
  1548. missingArgument(name) {
  1549. const message = `error: missing required argument '${name}'`;
  1550. this._displayError(1, 'commander.missingArgument', message);
  1551. };
  1552. /**
  1553. * `Option` is missing an argument.
  1554. *
  1555. * @param {Option} option
  1556. * @api private
  1557. */
  1558. optionMissingArgument(option) {
  1559. const message = `error: option '${option.flags}' argument missing`;
  1560. this._displayError(1, 'commander.optionMissingArgument', message);
  1561. };
  1562. /**
  1563. * `Option` does not have a value, and is a mandatory option.
  1564. *
  1565. * @param {Option} option
  1566. * @api private
  1567. */
  1568. missingMandatoryOptionValue(option) {
  1569. const message = `error: required option '${option.flags}' not specified`;
  1570. this._displayError(1, 'commander.missingMandatoryOptionValue', message);
  1571. };
  1572. /**
  1573. * Unknown option `flag`.
  1574. *
  1575. * @param {string} flag
  1576. * @api private
  1577. */
  1578. unknownOption(flag) {
  1579. if (this._allowUnknownOption) return;
  1580. const message = `error: unknown option '${flag}'`;
  1581. this._displayError(1, 'commander.unknownOption', message);
  1582. };
  1583. /**
  1584. * Excess arguments, more than expected.
  1585. *
  1586. * @param {string[]} receivedArgs
  1587. * @api private
  1588. */
  1589. _excessArguments(receivedArgs) {
  1590. if (this._allowExcessArguments) return;
  1591. const expected = this._args.length;
  1592. const s = (expected === 1) ? '' : 's';
  1593. const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
  1594. const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
  1595. this._displayError(1, 'commander.excessArguments', message);
  1596. };
  1597. /**
  1598. * Unknown command.
  1599. *
  1600. * @api private
  1601. */
  1602. unknownCommand() {
  1603. const partCommands = [this.name()];
  1604. for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
  1605. partCommands.unshift(parentCmd.name());
  1606. }
  1607. const fullCommand = partCommands.join(' ');
  1608. const message = `error: unknown command '${this.args[0]}'.` +
  1609. (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');
  1610. this._displayError(1, 'commander.unknownCommand', message);
  1611. };
  1612. /**
  1613. * Set the program version to `str`.
  1614. *
  1615. * This method auto-registers the "-V, --version" flag
  1616. * which will print the version number when passed.
  1617. *
  1618. * You can optionally supply the flags and description to override the defaults.
  1619. *
  1620. * @param {string} str
  1621. * @param {string} [flags]
  1622. * @param {string} [description]
  1623. * @return {this | string} `this` command for chaining, or version string if no arguments
  1624. */
  1625. version(str, flags, description) {
  1626. if (str === undefined) return this._version;
  1627. this._version = str;
  1628. flags = flags || '-V, --version';
  1629. description = description || 'output the version number';
  1630. const versionOption = this.createOption(flags, description);
  1631. this._versionOptionName = versionOption.attributeName();
  1632. this.options.push(versionOption);
  1633. this.on('option:' + versionOption.name(), () => {
  1634. this._outputConfiguration.writeOut(`${str}\n`);
  1635. this._exit(0, 'commander.version', str);
  1636. });
  1637. return this;
  1638. };
  1639. /**
  1640. * Set the description to `str`.
  1641. *
  1642. * @param {string} [str]
  1643. * @param {Object} [argsDescription]
  1644. * @return {string|Command}
  1645. */
  1646. description(str, argsDescription) {
  1647. if (str === undefined && argsDescription === undefined) return this._description;
  1648. this._description = str;
  1649. this._argsDescription = argsDescription;
  1650. return this;
  1651. };
  1652. /**
  1653. * Set an alias for the command.
  1654. *
  1655. * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
  1656. *
  1657. * @param {string} [alias]
  1658. * @return {string|Command}
  1659. */
  1660. alias(alias) {
  1661. if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
  1662. let command = this;
  1663. if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
  1664. // assume adding alias for last added executable subcommand, rather than this
  1665. command = this.commands[this.commands.length - 1];
  1666. }
  1667. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  1668. command._aliases.push(alias);
  1669. return this;
  1670. };
  1671. /**
  1672. * Set aliases for the command.
  1673. *
  1674. * Only the first alias is shown in the auto-generated help.
  1675. *
  1676. * @param {string[]} [aliases]
  1677. * @return {string[]|Command}
  1678. */
  1679. aliases(aliases) {
  1680. // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
  1681. if (aliases === undefined) return this._aliases;
  1682. aliases.forEach((alias) => this.alias(alias));
  1683. return this;
  1684. };
  1685. /**
  1686. * Set / get the command usage `str`.
  1687. *
  1688. * @param {string} [str]
  1689. * @return {String|Command}
  1690. */
  1691. usage(str) {
  1692. if (str === undefined) {
  1693. if (this._usage) return this._usage;
  1694. const args = this._args.map((arg) => {
  1695. return humanReadableArgName(arg);
  1696. });
  1697. return [].concat(
  1698. (this.options.length || this._hasHelpOption ? '[options]' : []),
  1699. (this.commands.length ? '[command]' : []),
  1700. (this._args.length ? args : [])
  1701. ).join(' ');
  1702. }
  1703. this._usage = str;
  1704. return this;
  1705. };
  1706. /**
  1707. * Get or set the name of the command
  1708. *
  1709. * @param {string} [str]
  1710. * @return {string|Command}
  1711. */
  1712. name(str) {
  1713. if (str === undefined) return this._name;
  1714. this._name = str;
  1715. return this;
  1716. };
  1717. /**
  1718. * Return program help documentation.
  1719. *
  1720. * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
  1721. * @return {string}
  1722. */
  1723. helpInformation(contextOptions) {
  1724. const helper = this.createHelp();
  1725. if (helper.helpWidth === undefined) {
  1726. helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
  1727. }
  1728. return helper.formatHelp(this, helper);
  1729. };
  1730. /**
  1731. * @api private
  1732. */
  1733. _getHelpContext(contextOptions) {
  1734. contextOptions = contextOptions || {};
  1735. const context = { error: !!contextOptions.error };
  1736. let write;
  1737. if (context.error) {
  1738. write = (arg) => this._outputConfiguration.writeErr(arg);
  1739. } else {
  1740. write = (arg) => this._outputConfiguration.writeOut(arg);
  1741. }
  1742. context.write = contextOptions.write || write;
  1743. context.command = this;
  1744. return context;
  1745. }
  1746. /**
  1747. * Output help information for this command.
  1748. *
  1749. * Outputs built-in help, and custom text added using `.addHelpText()`.
  1750. *
  1751. * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
  1752. */
  1753. outputHelp(contextOptions) {
  1754. let deprecatedCallback;
  1755. if (typeof contextOptions === 'function') {
  1756. deprecatedCallback = contextOptions;
  1757. contextOptions = undefined;
  1758. }
  1759. const context = this._getHelpContext(contextOptions);
  1760. const groupListeners = [];
  1761. let command = this;
  1762. while (command) {
  1763. groupListeners.push(command); // ordered from current command to root
  1764. command = command.parent;
  1765. }
  1766. groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));
  1767. this.emit('beforeHelp', context);
  1768. let helpInformation = this.helpInformation(context);
  1769. if (deprecatedCallback) {
  1770. helpInformation = deprecatedCallback(helpInformation);
  1771. if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
  1772. throw new Error('outputHelp callback must return a string or a Buffer');
  1773. }
  1774. }
  1775. context.write(helpInformation);
  1776. this.emit(this._helpLongFlag); // deprecated
  1777. this.emit('afterHelp', context);
  1778. groupListeners.forEach(command => command.emit('afterAllHelp', context));
  1779. };
  1780. /**
  1781. * You can pass in flags and a description to override the help
  1782. * flags and help description for your command. Pass in false to
  1783. * disable the built-in help option.
  1784. *
  1785. * @param {string | boolean} [flags]
  1786. * @param {string} [description]
  1787. * @return {Command} `this` command for chaining
  1788. */
  1789. helpOption(flags, description) {
  1790. if (typeof flags === 'boolean') {
  1791. this._hasHelpOption = flags;
  1792. return this;
  1793. }
  1794. this._helpFlags = flags || this._helpFlags;
  1795. this._helpDescription = description || this._helpDescription;
  1796. const helpFlags = _parseOptionFlags(this._helpFlags);
  1797. this._helpShortFlag = helpFlags.shortFlag;
  1798. this._helpLongFlag = helpFlags.longFlag;
  1799. return this;
  1800. };
  1801. /**
  1802. * Output help information and exit.
  1803. *
  1804. * Outputs built-in help, and custom text added using `.addHelpText()`.
  1805. *
  1806. * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
  1807. */
  1808. help(contextOptions) {
  1809. this.outputHelp(contextOptions);
  1810. let exitCode = process.exitCode || 0;
  1811. if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
  1812. exitCode = 1;
  1813. }
  1814. // message: do not have all displayed text available so only passing placeholder.
  1815. this._exit(exitCode, 'commander.help', '(outputHelp)');
  1816. };
  1817. /**
  1818. * Add additional text to be displayed with the built-in help.
  1819. *
  1820. * Position is 'before' or 'after' to affect just this command,
  1821. * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
  1822. *
  1823. * @param {string} position - before or after built-in help
  1824. * @param {string | Function} text - string to add, or a function returning a string
  1825. * @return {Command} `this` command for chaining
  1826. */
  1827. addHelpText(position, text) {
  1828. const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
  1829. if (!allowedValues.includes(position)) {
  1830. throw new Error(`Unexpected value for position to addHelpText.
  1831. Expecting one of '${allowedValues.join("', '")}'`);
  1832. }
  1833. const helpEvent = `${position}Help`;
  1834. this.on(helpEvent, (context) => {
  1835. let helpStr;
  1836. if (typeof text === 'function') {
  1837. helpStr = text({ error: context.error, command: context.command });
  1838. } else {
  1839. helpStr = text;
  1840. }
  1841. // Ignore falsy value when nothing to output.
  1842. if (helpStr) {
  1843. context.write(`${helpStr}\n`);
  1844. }
  1845. });
  1846. return this;
  1847. }
  1848. };
  1849. /**
  1850. * Expose the root command.
  1851. */
  1852. exports = module.exports = new Command();
  1853. exports.program = exports; // More explicit access to global command.
  1854. /**
  1855. * Expose classes
  1856. */
  1857. exports.Command = Command;
  1858. exports.Option = Option;
  1859. exports.CommanderError = CommanderError;
  1860. exports.InvalidOptionArgumentError = InvalidOptionArgumentError;
  1861. exports.Help = Help;
  1862. /**
  1863. * Camel-case the given `flag`
  1864. *
  1865. * @param {string} flag
  1866. * @return {string}
  1867. * @api private
  1868. */
  1869. function camelcase(flag) {
  1870. return flag.split('-').reduce((str, word) => {
  1871. return str + word[0].toUpperCase() + word.slice(1);
  1872. });
  1873. }
  1874. /**
  1875. * Output help information if help flags specified
  1876. *
  1877. * @param {Command} cmd - command to output help for
  1878. * @param {Array} args - array of options to search for help flags
  1879. * @api private
  1880. */
  1881. function outputHelpIfRequested(cmd, args) {
  1882. const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
  1883. if (helpOption) {
  1884. cmd.outputHelp();
  1885. // (Do not have all displayed text available so only passing placeholder.)
  1886. cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
  1887. }
  1888. }
  1889. /**
  1890. * Takes an argument and returns its human readable equivalent for help usage.
  1891. *
  1892. * @param {Object} arg
  1893. * @return {string}
  1894. * @api private
  1895. */
  1896. function humanReadableArgName(arg) {
  1897. const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
  1898. return arg.required
  1899. ? '<' + nameOutput + '>'
  1900. : '[' + nameOutput + ']';
  1901. }
  1902. /**
  1903. * Parse the short and long flag out of something like '-m,--mixed <value>'
  1904. *
  1905. * @api private
  1906. */
  1907. function _parseOptionFlags(flags) {
  1908. let shortFlag;
  1909. let longFlag;
  1910. // Use original very loose parsing to maintain backwards compatibility for now,
  1911. // which allowed for example unintended `-sw, --short-word` [sic].
  1912. const flagParts = flags.split(/[ |,]+/);
  1913. if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
  1914. longFlag = flagParts.shift();
  1915. // Add support for lone short flag without significantly changing parsing!
  1916. if (!shortFlag && /^-[^-]$/.test(longFlag)) {
  1917. shortFlag = longFlag;
  1918. longFlag = undefined;
  1919. }
  1920. return { shortFlag, longFlag };
  1921. }
  1922. /**
  1923. * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
  1924. *
  1925. * @param {string[]} args - array of arguments from node.execArgv
  1926. * @returns {string[]}
  1927. * @api private
  1928. */
  1929. function incrementNodeInspectorPort(args) {
  1930. // Testing for these options:
  1931. // --inspect[=[host:]port]
  1932. // --inspect-brk[=[host:]port]
  1933. // --inspect-port=[host:]port
  1934. return args.map((arg) => {
  1935. if (!arg.startsWith('--inspect')) {
  1936. return arg;
  1937. }
  1938. let debugOption;
  1939. let debugHost = '127.0.0.1';
  1940. let debugPort = '9229';
  1941. let match;
  1942. if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
  1943. // e.g. --inspect
  1944. debugOption = match[1];
  1945. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
  1946. debugOption = match[1];
  1947. if (/^\d+$/.test(match[3])) {
  1948. // e.g. --inspect=1234
  1949. debugPort = match[3];
  1950. } else {
  1951. // e.g. --inspect=localhost
  1952. debugHost = match[3];
  1953. }
  1954. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
  1955. // e.g. --inspect=localhost:1234
  1956. debugOption = match[1];
  1957. debugHost = match[3];
  1958. debugPort = match[4];
  1959. }
  1960. if (debugOption && debugPort !== '0') {
  1961. return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
  1962. }
  1963. return arg;
  1964. });
  1965. }