command.js 68 KB

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