command.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179
  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, env, cli etc
  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. return this.setOptionValueWithSource(key, value, undefined);
  709. }
  710. /**
  711. * Store option value and where the value came from.
  712. *
  713. * @param {string} key
  714. * @param {Object} value
  715. * @param {string} source - expected values are default/config/env/cli/implied
  716. * @return {Command} `this` command for chaining
  717. */
  718. setOptionValueWithSource(key, value, source) {
  719. if (this._storeOptionsAsProperties) {
  720. this[key] = value;
  721. } else {
  722. this._optionValues[key] = value;
  723. }
  724. this._optionValueSources[key] = source;
  725. return this;
  726. }
  727. /**
  728. * Get source of option value.
  729. * Expected values are default | config | env | cli | implied
  730. *
  731. * @param {string} key
  732. * @return {string}
  733. */
  734. getOptionValueSource(key) {
  735. return this._optionValueSources[key];
  736. }
  737. /**
  738. * Get source of option value. See also .optsWithGlobals().
  739. * Expected values are default | config | env | cli | implied
  740. *
  741. * @param {string} key
  742. * @return {string}
  743. */
  744. getOptionValueSourceWithGlobals(key) {
  745. // global overwrites local, like optsWithGlobals
  746. let source;
  747. getCommandAndParents(this).forEach((cmd) => {
  748. if (cmd.getOptionValueSource(key) !== undefined) {
  749. source = cmd.getOptionValueSource(key);
  750. }
  751. });
  752. return source;
  753. }
  754. /**
  755. * Get user arguments from implied or explicit arguments.
  756. * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
  757. *
  758. * @api private
  759. */
  760. _prepareUserArgs(argv, parseOptions) {
  761. if (argv !== undefined && !Array.isArray(argv)) {
  762. throw new Error('first parameter to parse must be array or undefined');
  763. }
  764. parseOptions = parseOptions || {};
  765. // Default to using process.argv
  766. if (argv === undefined) {
  767. argv = process.argv;
  768. // @ts-ignore: unknown property
  769. if (process.versions && process.versions.electron) {
  770. parseOptions.from = 'electron';
  771. }
  772. }
  773. this.rawArgs = argv.slice();
  774. // make it a little easier for callers by supporting various argv conventions
  775. let userArgs;
  776. switch (parseOptions.from) {
  777. case undefined:
  778. case 'node':
  779. this._scriptPath = argv[1];
  780. userArgs = argv.slice(2);
  781. break;
  782. case 'electron':
  783. // @ts-ignore: unknown property
  784. if (process.defaultApp) {
  785. this._scriptPath = argv[1];
  786. userArgs = argv.slice(2);
  787. } else {
  788. userArgs = argv.slice(1);
  789. }
  790. break;
  791. case 'user':
  792. userArgs = argv.slice(0);
  793. break;
  794. default:
  795. throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
  796. }
  797. // Find default name for program from arguments.
  798. if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
  799. this._name = this._name || 'program';
  800. return userArgs;
  801. }
  802. /**
  803. * Parse `argv`, setting options and invoking commands when defined.
  804. *
  805. * The default expectation is that the arguments are from node and have the application as argv[0]
  806. * and the script being run in argv[1], with user parameters after that.
  807. *
  808. * @example
  809. * program.parse(process.argv);
  810. * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
  811. * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  812. *
  813. * @param {string[]} [argv] - optional, defaults to process.argv
  814. * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
  815. * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
  816. * @return {Command} `this` command for chaining
  817. */
  818. parse(argv, parseOptions) {
  819. const userArgs = this._prepareUserArgs(argv, parseOptions);
  820. this._parseCommand([], userArgs);
  821. return this;
  822. }
  823. /**
  824. * Parse `argv`, setting options and invoking commands when defined.
  825. *
  826. * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
  827. *
  828. * The default expectation is that the arguments are from node and have the application as argv[0]
  829. * and the script being run in argv[1], with user parameters after that.
  830. *
  831. * @example
  832. * await program.parseAsync(process.argv);
  833. * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
  834. * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  835. *
  836. * @param {string[]} [argv]
  837. * @param {Object} [parseOptions]
  838. * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
  839. * @return {Promise}
  840. */
  841. async parseAsync(argv, parseOptions) {
  842. const userArgs = this._prepareUserArgs(argv, parseOptions);
  843. await this._parseCommand([], userArgs);
  844. return this;
  845. }
  846. /**
  847. * Execute a sub-command executable.
  848. *
  849. * @api private
  850. */
  851. _executeSubCommand(subcommand, args) {
  852. args = args.slice();
  853. let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
  854. const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
  855. function findFile(baseDir, baseName) {
  856. // Look for specified file
  857. const localBin = path.resolve(baseDir, baseName);
  858. if (fs.existsSync(localBin)) return localBin;
  859. // Stop looking if candidate already has an expected extension.
  860. if (sourceExt.includes(path.extname(baseName))) return undefined;
  861. // Try all the extensions.
  862. const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));
  863. if (foundExt) return `${localBin}${foundExt}`;
  864. return undefined;
  865. }
  866. // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
  867. this._checkForMissingMandatoryOptions();
  868. this._checkForConflictingOptions();
  869. // executableFile and executableDir might be full path, or just a name
  870. let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
  871. let executableDir = this._executableDir || '';
  872. if (this._scriptPath) {
  873. let resolvedScriptPath; // resolve possible symlink for installed npm binary
  874. try {
  875. resolvedScriptPath = fs.realpathSync(this._scriptPath);
  876. } catch (err) {
  877. resolvedScriptPath = this._scriptPath;
  878. }
  879. executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
  880. }
  881. // Look for a local file in preference to a command in PATH.
  882. if (executableDir) {
  883. let localFile = findFile(executableDir, executableFile);
  884. // Legacy search using prefix of script name instead of command name
  885. if (!localFile && !subcommand._executableFile && this._scriptPath) {
  886. const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
  887. if (legacyName !== this._name) {
  888. localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
  889. }
  890. }
  891. executableFile = localFile || executableFile;
  892. }
  893. launchWithNode = sourceExt.includes(path.extname(executableFile));
  894. let proc;
  895. if (process.platform !== 'win32') {
  896. if (launchWithNode) {
  897. args.unshift(executableFile);
  898. // add executable arguments to spawn
  899. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  900. proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
  901. } else {
  902. proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
  903. }
  904. } else {
  905. args.unshift(executableFile);
  906. // add executable arguments to spawn
  907. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  908. proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
  909. }
  910. if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
  911. const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  912. signals.forEach((signal) => {
  913. // @ts-ignore
  914. process.on(signal, () => {
  915. if (proc.killed === false && proc.exitCode === null) {
  916. proc.kill(signal);
  917. }
  918. });
  919. });
  920. }
  921. // By default terminate process when spawned process terminates.
  922. // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
  923. const exitCallback = this._exitCallback;
  924. if (!exitCallback) {
  925. proc.on('close', process.exit.bind(process));
  926. } else {
  927. proc.on('close', () => {
  928. exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
  929. });
  930. }
  931. proc.on('error', (err) => {
  932. // @ts-ignore
  933. if (err.code === 'ENOENT') {
  934. const executableDirMessage = executableDir
  935. ? `searched for local subcommand relative to directory '${executableDir}'`
  936. : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
  937. const executableMissing = `'${executableFile}' does not exist
  938. - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
  939. - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
  940. - ${executableDirMessage}`;
  941. throw new Error(executableMissing);
  942. // @ts-ignore
  943. } else if (err.code === 'EACCES') {
  944. throw new Error(`'${executableFile}' not executable`);
  945. }
  946. if (!exitCallback) {
  947. process.exit(1);
  948. } else {
  949. const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
  950. wrappedError.nestedError = err;
  951. exitCallback(wrappedError);
  952. }
  953. });
  954. // Store the reference to the child process
  955. this.runningCommand = proc;
  956. }
  957. /**
  958. * @api private
  959. */
  960. _dispatchSubcommand(commandName, operands, unknown) {
  961. const subCommand = this._findCommand(commandName);
  962. if (!subCommand) this.help({ error: true });
  963. let hookResult;
  964. hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, 'preSubcommand');
  965. hookResult = this._chainOrCall(hookResult, () => {
  966. if (subCommand._executableHandler) {
  967. this._executeSubCommand(subCommand, operands.concat(unknown));
  968. } else {
  969. return subCommand._parseCommand(operands, unknown);
  970. }
  971. });
  972. return hookResult;
  973. }
  974. /**
  975. * Check this.args against expected this._args.
  976. *
  977. * @api private
  978. */
  979. _checkNumberOfArguments() {
  980. // too few
  981. this._args.forEach((arg, i) => {
  982. if (arg.required && this.args[i] == null) {
  983. this.missingArgument(arg.name());
  984. }
  985. });
  986. // too many
  987. if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {
  988. return;
  989. }
  990. if (this.args.length > this._args.length) {
  991. this._excessArguments(this.args);
  992. }
  993. }
  994. /**
  995. * Process this.args using this._args and save as this.processedArgs!
  996. *
  997. * @api private
  998. */
  999. _processArguments() {
  1000. const myParseArg = (argument, value, previous) => {
  1001. // Extra processing for nice error message on parsing failure.
  1002. let parsedValue = value;
  1003. if (value !== null && argument.parseArg) {
  1004. try {
  1005. parsedValue = argument.parseArg(value, previous);
  1006. } catch (err) {
  1007. if (err.code === 'commander.invalidArgument') {
  1008. const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;
  1009. this.error(message, { exitCode: err.exitCode, code: err.code });
  1010. }
  1011. throw err;
  1012. }
  1013. }
  1014. return parsedValue;
  1015. };
  1016. this._checkNumberOfArguments();
  1017. const processedArgs = [];
  1018. this._args.forEach((declaredArg, index) => {
  1019. let value = declaredArg.defaultValue;
  1020. if (declaredArg.variadic) {
  1021. // Collect together remaining arguments for passing together as an array.
  1022. if (index < this.args.length) {
  1023. value = this.args.slice(index);
  1024. if (declaredArg.parseArg) {
  1025. value = value.reduce((processed, v) => {
  1026. return myParseArg(declaredArg, v, processed);
  1027. }, declaredArg.defaultValue);
  1028. }
  1029. } else if (value === undefined) {
  1030. value = [];
  1031. }
  1032. } else if (index < this.args.length) {
  1033. value = this.args[index];
  1034. if (declaredArg.parseArg) {
  1035. value = myParseArg(declaredArg, value, declaredArg.defaultValue);
  1036. }
  1037. }
  1038. processedArgs[index] = value;
  1039. });
  1040. this.processedArgs = processedArgs;
  1041. }
  1042. /**
  1043. * Once we have a promise we chain, but call synchronously until then.
  1044. *
  1045. * @param {Promise|undefined} promise
  1046. * @param {Function} fn
  1047. * @return {Promise|undefined}
  1048. * @api private
  1049. */
  1050. _chainOrCall(promise, fn) {
  1051. // thenable
  1052. if (promise && promise.then && typeof promise.then === 'function') {
  1053. // already have a promise, chain callback
  1054. return promise.then(() => fn());
  1055. }
  1056. // callback might return a promise
  1057. return fn();
  1058. }
  1059. /**
  1060. *
  1061. * @param {Promise|undefined} promise
  1062. * @param {string} event
  1063. * @return {Promise|undefined}
  1064. * @api private
  1065. */
  1066. _chainOrCallHooks(promise, event) {
  1067. let result = promise;
  1068. const hooks = [];
  1069. getCommandAndParents(this)
  1070. .reverse()
  1071. .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)
  1072. .forEach(hookedCommand => {
  1073. hookedCommand._lifeCycleHooks[event].forEach((callback) => {
  1074. hooks.push({ hookedCommand, callback });
  1075. });
  1076. });
  1077. if (event === 'postAction') {
  1078. hooks.reverse();
  1079. }
  1080. hooks.forEach((hookDetail) => {
  1081. result = this._chainOrCall(result, () => {
  1082. return hookDetail.callback(hookDetail.hookedCommand, this);
  1083. });
  1084. });
  1085. return result;
  1086. }
  1087. /**
  1088. *
  1089. * @param {Promise|undefined} promise
  1090. * @param {Command} subCommand
  1091. * @param {string} event
  1092. * @return {Promise|undefined}
  1093. * @api private
  1094. */
  1095. _chainOrCallSubCommandHook(promise, subCommand, event) {
  1096. let result = promise;
  1097. if (this._lifeCycleHooks[event] !== undefined) {
  1098. this._lifeCycleHooks[event].forEach((hook) => {
  1099. result = this._chainOrCall(result, () => {
  1100. return hook(this, subCommand);
  1101. });
  1102. });
  1103. }
  1104. return result;
  1105. }
  1106. /**
  1107. * Process arguments in context of this command.
  1108. * Returns action result, in case it is a promise.
  1109. *
  1110. * @api private
  1111. */
  1112. _parseCommand(operands, unknown) {
  1113. const parsed = this.parseOptions(unknown);
  1114. this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
  1115. this._parseOptionsImplied();
  1116. operands = operands.concat(parsed.operands);
  1117. unknown = parsed.unknown;
  1118. this.args = operands.concat(unknown);
  1119. if (operands && this._findCommand(operands[0])) {
  1120. return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
  1121. }
  1122. if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
  1123. if (operands.length === 1) {
  1124. this.help();
  1125. }
  1126. return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
  1127. }
  1128. if (this._defaultCommandName) {
  1129. outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
  1130. return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
  1131. }
  1132. if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
  1133. // probably missing subcommand and no handler, user needs help (and exit)
  1134. this.help({ error: true });
  1135. }
  1136. outputHelpIfRequested(this, parsed.unknown);
  1137. this._checkForMissingMandatoryOptions();
  1138. this._checkForConflictingOptions();
  1139. // We do not always call this check to avoid masking a "better" error, like unknown command.
  1140. const checkForUnknownOptions = () => {
  1141. if (parsed.unknown.length > 0) {
  1142. this.unknownOption(parsed.unknown[0]);
  1143. }
  1144. };
  1145. const commandEvent = `command:${this.name()}`;
  1146. if (this._actionHandler) {
  1147. checkForUnknownOptions();
  1148. this._processArguments();
  1149. let actionResult;
  1150. actionResult = this._chainOrCallHooks(actionResult, 'preAction');
  1151. actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));
  1152. if (this.parent) {
  1153. actionResult = this._chainOrCall(actionResult, () => {
  1154. this.parent.emit(commandEvent, operands, unknown); // legacy
  1155. });
  1156. }
  1157. actionResult = this._chainOrCallHooks(actionResult, 'postAction');
  1158. return actionResult;
  1159. }
  1160. if (this.parent && this.parent.listenerCount(commandEvent)) {
  1161. checkForUnknownOptions();
  1162. this._processArguments();
  1163. this.parent.emit(commandEvent, operands, unknown); // legacy
  1164. } else if (operands.length) {
  1165. if (this._findCommand('*')) { // legacy default command
  1166. return this._dispatchSubcommand('*', operands, unknown);
  1167. }
  1168. if (this.listenerCount('command:*')) {
  1169. // skip option check, emit event for possible misspelling suggestion
  1170. this.emit('command:*', operands, unknown);
  1171. } else if (this.commands.length) {
  1172. this.unknownCommand();
  1173. } else {
  1174. checkForUnknownOptions();
  1175. this._processArguments();
  1176. }
  1177. } else if (this.commands.length) {
  1178. checkForUnknownOptions();
  1179. // This command has subcommands and nothing hooked up at this level, so display help (and exit).
  1180. this.help({ error: true });
  1181. } else {
  1182. checkForUnknownOptions();
  1183. this._processArguments();
  1184. // fall through for caller to handle after calling .parse()
  1185. }
  1186. }
  1187. /**
  1188. * Find matching command.
  1189. *
  1190. * @api private
  1191. */
  1192. _findCommand(name) {
  1193. if (!name) return undefined;
  1194. return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
  1195. }
  1196. /**
  1197. * Return an option matching `arg` if any.
  1198. *
  1199. * @param {string} arg
  1200. * @return {Option}
  1201. * @api private
  1202. */
  1203. _findOption(arg) {
  1204. return this.options.find(option => option.is(arg));
  1205. }
  1206. /**
  1207. * Display an error message if a mandatory option does not have a value.
  1208. * Called after checking for help flags in leaf subcommand.
  1209. *
  1210. * @api private
  1211. */
  1212. _checkForMissingMandatoryOptions() {
  1213. // Walk up hierarchy so can call in subcommand after checking for displaying help.
  1214. for (let cmd = this; cmd; cmd = cmd.parent) {
  1215. cmd.options.forEach((anOption) => {
  1216. if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {
  1217. cmd.missingMandatoryOptionValue(anOption);
  1218. }
  1219. });
  1220. }
  1221. }
  1222. /**
  1223. * Display an error message if conflicting options are used together in this.
  1224. *
  1225. * @api private
  1226. */
  1227. _checkForConflictingLocalOptions() {
  1228. const definedNonDefaultOptions = this.options.filter(
  1229. (option) => {
  1230. const optionKey = option.attributeName();
  1231. if (this.getOptionValue(optionKey) === undefined) {
  1232. return false;
  1233. }
  1234. return this.getOptionValueSource(optionKey) !== 'default';
  1235. }
  1236. );
  1237. const optionsWithConflicting = definedNonDefaultOptions.filter(
  1238. (option) => option.conflictsWith.length > 0
  1239. );
  1240. optionsWithConflicting.forEach((option) => {
  1241. const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
  1242. option.conflictsWith.includes(defined.attributeName())
  1243. );
  1244. if (conflictingAndDefined) {
  1245. this._conflictingOption(option, conflictingAndDefined);
  1246. }
  1247. });
  1248. }
  1249. /**
  1250. * Display an error message if conflicting options are used together.
  1251. * Called after checking for help flags in leaf subcommand.
  1252. *
  1253. * @api private
  1254. */
  1255. _checkForConflictingOptions() {
  1256. // Walk up hierarchy so can call in subcommand after checking for displaying help.
  1257. for (let cmd = this; cmd; cmd = cmd.parent) {
  1258. cmd._checkForConflictingLocalOptions();
  1259. }
  1260. }
  1261. /**
  1262. * Parse options from `argv` removing known options,
  1263. * and return argv split into operands and unknown arguments.
  1264. *
  1265. * Examples:
  1266. *
  1267. * argv => operands, unknown
  1268. * --known kkk op => [op], []
  1269. * op --known kkk => [op], []
  1270. * sub --unknown uuu op => [sub], [--unknown uuu op]
  1271. * sub -- --unknown uuu op => [sub --unknown uuu op], []
  1272. *
  1273. * @param {String[]} argv
  1274. * @return {{operands: String[], unknown: String[]}}
  1275. */
  1276. parseOptions(argv) {
  1277. const operands = []; // operands, not options or values
  1278. const unknown = []; // first unknown option and remaining unknown args
  1279. let dest = operands;
  1280. const args = argv.slice();
  1281. function maybeOption(arg) {
  1282. return arg.length > 1 && arg[0] === '-';
  1283. }
  1284. // parse options
  1285. let activeVariadicOption = null;
  1286. while (args.length) {
  1287. const arg = args.shift();
  1288. // literal
  1289. if (arg === '--') {
  1290. if (dest === unknown) dest.push(arg);
  1291. dest.push(...args);
  1292. break;
  1293. }
  1294. if (activeVariadicOption && !maybeOption(arg)) {
  1295. this.emit(`option:${activeVariadicOption.name()}`, arg);
  1296. continue;
  1297. }
  1298. activeVariadicOption = null;
  1299. if (maybeOption(arg)) {
  1300. const option = this._findOption(arg);
  1301. // recognised option, call listener to assign value with possible custom processing
  1302. if (option) {
  1303. if (option.required) {
  1304. const value = args.shift();
  1305. if (value === undefined) this.optionMissingArgument(option);
  1306. this.emit(`option:${option.name()}`, value);
  1307. } else if (option.optional) {
  1308. let value = null;
  1309. // historical behaviour is optional value is following arg unless an option
  1310. if (args.length > 0 && !maybeOption(args[0])) {
  1311. value = args.shift();
  1312. }
  1313. this.emit(`option:${option.name()}`, value);
  1314. } else { // boolean flag
  1315. this.emit(`option:${option.name()}`);
  1316. }
  1317. activeVariadicOption = option.variadic ? option : null;
  1318. continue;
  1319. }
  1320. }
  1321. // Look for combo options following single dash, eat first one if known.
  1322. if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
  1323. const option = this._findOption(`-${arg[1]}`);
  1324. if (option) {
  1325. if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
  1326. // option with value following in same argument
  1327. this.emit(`option:${option.name()}`, arg.slice(2));
  1328. } else {
  1329. // boolean option, emit and put back remainder of arg for further processing
  1330. this.emit(`option:${option.name()}`);
  1331. args.unshift(`-${arg.slice(2)}`);
  1332. }
  1333. continue;
  1334. }
  1335. }
  1336. // Look for known long flag with value, like --foo=bar
  1337. if (/^--[^=]+=/.test(arg)) {
  1338. const index = arg.indexOf('=');
  1339. const option = this._findOption(arg.slice(0, index));
  1340. if (option && (option.required || option.optional)) {
  1341. this.emit(`option:${option.name()}`, arg.slice(index + 1));
  1342. continue;
  1343. }
  1344. }
  1345. // Not a recognised option by this command.
  1346. // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
  1347. // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
  1348. if (maybeOption(arg)) {
  1349. dest = unknown;
  1350. }
  1351. // If using positionalOptions, stop processing our options at subcommand.
  1352. if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
  1353. if (this._findCommand(arg)) {
  1354. operands.push(arg);
  1355. if (args.length > 0) unknown.push(...args);
  1356. break;
  1357. } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
  1358. operands.push(arg);
  1359. if (args.length > 0) operands.push(...args);
  1360. break;
  1361. } else if (this._defaultCommandName) {
  1362. unknown.push(arg);
  1363. if (args.length > 0) unknown.push(...args);
  1364. break;
  1365. }
  1366. }
  1367. // If using passThroughOptions, stop processing options at first command-argument.
  1368. if (this._passThroughOptions) {
  1369. dest.push(arg);
  1370. if (args.length > 0) dest.push(...args);
  1371. break;
  1372. }
  1373. // add arg
  1374. dest.push(arg);
  1375. }
  1376. return { operands, unknown };
  1377. }
  1378. /**
  1379. * Return an object containing local option values as key-value pairs.
  1380. *
  1381. * @return {Object}
  1382. */
  1383. opts() {
  1384. if (this._storeOptionsAsProperties) {
  1385. // Preserve original behaviour so backwards compatible when still using properties
  1386. const result = {};
  1387. const len = this.options.length;
  1388. for (let i = 0; i < len; i++) {
  1389. const key = this.options[i].attributeName();
  1390. result[key] = key === this._versionOptionName ? this._version : this[key];
  1391. }
  1392. return result;
  1393. }
  1394. return this._optionValues;
  1395. }
  1396. /**
  1397. * Return an object containing merged local and global option values as key-value pairs.
  1398. *
  1399. * @return {Object}
  1400. */
  1401. optsWithGlobals() {
  1402. // globals overwrite locals
  1403. return getCommandAndParents(this).reduce(
  1404. (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
  1405. {}
  1406. );
  1407. }
  1408. /**
  1409. * Display error message and exit (or call exitOverride).
  1410. *
  1411. * @param {string} message
  1412. * @param {Object} [errorOptions]
  1413. * @param {string} [errorOptions.code] - an id string representing the error
  1414. * @param {number} [errorOptions.exitCode] - used with process.exit
  1415. */
  1416. error(message, errorOptions) {
  1417. // output handling
  1418. this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
  1419. if (typeof this._showHelpAfterError === 'string') {
  1420. this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
  1421. } else if (this._showHelpAfterError) {
  1422. this._outputConfiguration.writeErr('\n');
  1423. this.outputHelp({ error: true });
  1424. }
  1425. // exit handling
  1426. const config = errorOptions || {};
  1427. const exitCode = config.exitCode || 1;
  1428. const code = config.code || 'commander.error';
  1429. this._exit(exitCode, code, message);
  1430. }
  1431. /**
  1432. * Apply any option related environment variables, if option does
  1433. * not have a value from cli or client code.
  1434. *
  1435. * @api private
  1436. */
  1437. _parseOptionsEnv() {
  1438. this.options.forEach((option) => {
  1439. if (option.envVar && option.envVar in process.env) {
  1440. const optionKey = option.attributeName();
  1441. // Priority check. Do not overwrite cli or options from unknown source (client-code).
  1442. if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {
  1443. if (option.required || option.optional) { // option can take a value
  1444. // keep very simple, optional always takes value
  1445. this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
  1446. } else { // boolean
  1447. // keep very simple, only care that envVar defined and not the value
  1448. this.emit(`optionEnv:${option.name()}`);
  1449. }
  1450. }
  1451. }
  1452. });
  1453. }
  1454. /**
  1455. * Apply any implied option values, if option is undefined or default value.
  1456. *
  1457. * @api private
  1458. */
  1459. _parseOptionsImplied() {
  1460. const dualHelper = new DualOptions(this.options);
  1461. const hasCustomOptionValue = (optionKey) => {
  1462. return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));
  1463. };
  1464. this.options
  1465. .filter(option => (option.implied !== undefined) &&
  1466. hasCustomOptionValue(option.attributeName()) &&
  1467. dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))
  1468. .forEach((option) => {
  1469. Object.keys(option.implied)
  1470. .filter(impliedKey => !hasCustomOptionValue(impliedKey))
  1471. .forEach(impliedKey => {
  1472. this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');
  1473. });
  1474. });
  1475. }
  1476. /**
  1477. * Argument `name` is missing.
  1478. *
  1479. * @param {string} name
  1480. * @api private
  1481. */
  1482. missingArgument(name) {
  1483. const message = `error: missing required argument '${name}'`;
  1484. this.error(message, { code: 'commander.missingArgument' });
  1485. }
  1486. /**
  1487. * `Option` is missing an argument.
  1488. *
  1489. * @param {Option} option
  1490. * @api private
  1491. */
  1492. optionMissingArgument(option) {
  1493. const message = `error: option '${option.flags}' argument missing`;
  1494. this.error(message, { code: 'commander.optionMissingArgument' });
  1495. }
  1496. /**
  1497. * `Option` does not have a value, and is a mandatory option.
  1498. *
  1499. * @param {Option} option
  1500. * @api private
  1501. */
  1502. missingMandatoryOptionValue(option) {
  1503. const message = `error: required option '${option.flags}' not specified`;
  1504. this.error(message, { code: 'commander.missingMandatoryOptionValue' });
  1505. }
  1506. /**
  1507. * `Option` conflicts with another option.
  1508. *
  1509. * @param {Option} option
  1510. * @param {Option} conflictingOption
  1511. * @api private
  1512. */
  1513. _conflictingOption(option, conflictingOption) {
  1514. // The calling code does not know whether a negated option is the source of the
  1515. // value, so do some work to take an educated guess.
  1516. const findBestOptionFromValue = (option) => {
  1517. const optionKey = option.attributeName();
  1518. const optionValue = this.getOptionValue(optionKey);
  1519. const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());
  1520. const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());
  1521. if (negativeOption && (
  1522. (negativeOption.presetArg === undefined && optionValue === false) ||
  1523. (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)
  1524. )) {
  1525. return negativeOption;
  1526. }
  1527. return positiveOption || option;
  1528. };
  1529. const getErrorMessage = (option) => {
  1530. const bestOption = findBestOptionFromValue(option);
  1531. const optionKey = bestOption.attributeName();
  1532. const source = this.getOptionValueSource(optionKey);
  1533. if (source === 'env') {
  1534. return `environment variable '${bestOption.envVar}'`;
  1535. }
  1536. return `option '${bestOption.flags}'`;
  1537. };
  1538. const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
  1539. this.error(message, { code: 'commander.conflictingOption' });
  1540. }
  1541. /**
  1542. * Unknown option `flag`.
  1543. *
  1544. * @param {string} flag
  1545. * @api private
  1546. */
  1547. unknownOption(flag) {
  1548. if (this._allowUnknownOption) return;
  1549. let suggestion = '';
  1550. if (flag.startsWith('--') && this._showSuggestionAfterError) {
  1551. // Looping to pick up the global options too
  1552. let candidateFlags = [];
  1553. let command = this;
  1554. do {
  1555. const moreFlags = command.createHelp().visibleOptions(command)
  1556. .filter(option => option.long)
  1557. .map(option => option.long);
  1558. candidateFlags = candidateFlags.concat(moreFlags);
  1559. command = command.parent;
  1560. } while (command && !command._enablePositionalOptions);
  1561. suggestion = suggestSimilar(flag, candidateFlags);
  1562. }
  1563. const message = `error: unknown option '${flag}'${suggestion}`;
  1564. this.error(message, { code: 'commander.unknownOption' });
  1565. }
  1566. /**
  1567. * Excess arguments, more than expected.
  1568. *
  1569. * @param {string[]} receivedArgs
  1570. * @api private
  1571. */
  1572. _excessArguments(receivedArgs) {
  1573. if (this._allowExcessArguments) return;
  1574. const expected = this._args.length;
  1575. const s = (expected === 1) ? '' : 's';
  1576. const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
  1577. const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
  1578. this.error(message, { code: 'commander.excessArguments' });
  1579. }
  1580. /**
  1581. * Unknown command.
  1582. *
  1583. * @api private
  1584. */
  1585. unknownCommand() {
  1586. const unknownName = this.args[0];
  1587. let suggestion = '';
  1588. if (this._showSuggestionAfterError) {
  1589. const candidateNames = [];
  1590. this.createHelp().visibleCommands(this).forEach((command) => {
  1591. candidateNames.push(command.name());
  1592. // just visible alias
  1593. if (command.alias()) candidateNames.push(command.alias());
  1594. });
  1595. suggestion = suggestSimilar(unknownName, candidateNames);
  1596. }
  1597. const message = `error: unknown command '${unknownName}'${suggestion}`;
  1598. this.error(message, { code: 'commander.unknownCommand' });
  1599. }
  1600. /**
  1601. * Set the program version to `str`.
  1602. *
  1603. * This method auto-registers the "-V, --version" flag
  1604. * which will print the version number when passed.
  1605. *
  1606. * You can optionally supply the flags and description to override the defaults.
  1607. *
  1608. * @param {string} str
  1609. * @param {string} [flags]
  1610. * @param {string} [description]
  1611. * @return {this | string} `this` command for chaining, or version string if no arguments
  1612. */
  1613. version(str, flags, description) {
  1614. if (str === undefined) return this._version;
  1615. this._version = str;
  1616. flags = flags || '-V, --version';
  1617. description = description || 'output the version number';
  1618. const versionOption = this.createOption(flags, description);
  1619. this._versionOptionName = versionOption.attributeName();
  1620. this.options.push(versionOption);
  1621. this.on('option:' + versionOption.name(), () => {
  1622. this._outputConfiguration.writeOut(`${str}\n`);
  1623. this._exit(0, 'commander.version', str);
  1624. });
  1625. return this;
  1626. }
  1627. /**
  1628. * Set the description.
  1629. *
  1630. * @param {string} [str]
  1631. * @param {Object} [argsDescription]
  1632. * @return {string|Command}
  1633. */
  1634. description(str, argsDescription) {
  1635. if (str === undefined && argsDescription === undefined) return this._description;
  1636. this._description = str;
  1637. if (argsDescription) {
  1638. this._argsDescription = argsDescription;
  1639. }
  1640. return this;
  1641. }
  1642. /**
  1643. * Set the summary. Used when listed as subcommand of parent.
  1644. *
  1645. * @param {string} [str]
  1646. * @return {string|Command}
  1647. */
  1648. summary(str) {
  1649. if (str === undefined) return this._summary;
  1650. this._summary = str;
  1651. return this;
  1652. }
  1653. /**
  1654. * Set an alias for the command.
  1655. *
  1656. * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
  1657. *
  1658. * @param {string} [alias]
  1659. * @return {string|Command}
  1660. */
  1661. alias(alias) {
  1662. if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
  1663. /** @type {Command} */
  1664. let command = this;
  1665. if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
  1666. // assume adding alias for last added executable subcommand, rather than this
  1667. command = this.commands[this.commands.length - 1];
  1668. }
  1669. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  1670. command._aliases.push(alias);
  1671. return this;
  1672. }
  1673. /**
  1674. * Set aliases for the command.
  1675. *
  1676. * Only the first alias is shown in the auto-generated help.
  1677. *
  1678. * @param {string[]} [aliases]
  1679. * @return {string[]|Command}
  1680. */
  1681. aliases(aliases) {
  1682. // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
  1683. if (aliases === undefined) return this._aliases;
  1684. aliases.forEach((alias) => this.alias(alias));
  1685. return this;
  1686. }
  1687. /**
  1688. * Set / get the command usage `str`.
  1689. *
  1690. * @param {string} [str]
  1691. * @return {String|Command}
  1692. */
  1693. usage(str) {
  1694. if (str === undefined) {
  1695. if (this._usage) return this._usage;
  1696. const args = this._args.map((arg) => {
  1697. return humanReadableArgName(arg);
  1698. });
  1699. return [].concat(
  1700. (this.options.length || this._hasHelpOption ? '[options]' : []),
  1701. (this.commands.length ? '[command]' : []),
  1702. (this._args.length ? args : [])
  1703. ).join(' ');
  1704. }
  1705. this._usage = str;
  1706. return this;
  1707. }
  1708. /**
  1709. * Get or set the name of the command.
  1710. *
  1711. * @param {string} [str]
  1712. * @return {string|Command}
  1713. */
  1714. name(str) {
  1715. if (str === undefined) return this._name;
  1716. this._name = str;
  1717. return this;
  1718. }
  1719. /**
  1720. * Set the name of the command from script filename, such as process.argv[1],
  1721. * or require.main.filename, or __filename.
  1722. *
  1723. * (Used internally and public although not documented in README.)
  1724. *
  1725. * @example
  1726. * program.nameFromFilename(require.main.filename);
  1727. *
  1728. * @param {string} filename
  1729. * @return {Command}
  1730. */
  1731. nameFromFilename(filename) {
  1732. this._name = path.basename(filename, path.extname(filename));
  1733. return this;
  1734. }
  1735. /**
  1736. * Get or set the directory for searching for executable subcommands of this command.
  1737. *
  1738. * @example
  1739. * program.executableDir(__dirname);
  1740. * // or
  1741. * program.executableDir('subcommands');
  1742. *
  1743. * @param {string} [path]
  1744. * @return {string|Command}
  1745. */
  1746. executableDir(path) {
  1747. if (path === undefined) return this._executableDir;
  1748. this._executableDir = path;
  1749. return this;
  1750. }
  1751. /**
  1752. * Return program help documentation.
  1753. *
  1754. * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
  1755. * @return {string}
  1756. */
  1757. helpInformation(contextOptions) {
  1758. const helper = this.createHelp();
  1759. if (helper.helpWidth === undefined) {
  1760. helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
  1761. }
  1762. return helper.formatHelp(this, helper);
  1763. }
  1764. /**
  1765. * @api private
  1766. */
  1767. _getHelpContext(contextOptions) {
  1768. contextOptions = contextOptions || {};
  1769. const context = { error: !!contextOptions.error };
  1770. let write;
  1771. if (context.error) {
  1772. write = (arg) => this._outputConfiguration.writeErr(arg);
  1773. } else {
  1774. write = (arg) => this._outputConfiguration.writeOut(arg);
  1775. }
  1776. context.write = contextOptions.write || write;
  1777. context.command = this;
  1778. return context;
  1779. }
  1780. /**
  1781. * Output help information for this command.
  1782. *
  1783. * Outputs built-in help, and custom text added using `.addHelpText()`.
  1784. *
  1785. * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
  1786. */
  1787. outputHelp(contextOptions) {
  1788. let deprecatedCallback;
  1789. if (typeof contextOptions === 'function') {
  1790. deprecatedCallback = contextOptions;
  1791. contextOptions = undefined;
  1792. }
  1793. const context = this._getHelpContext(contextOptions);
  1794. getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));
  1795. this.emit('beforeHelp', context);
  1796. let helpInformation = this.helpInformation(context);
  1797. if (deprecatedCallback) {
  1798. helpInformation = deprecatedCallback(helpInformation);
  1799. if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
  1800. throw new Error('outputHelp callback must return a string or a Buffer');
  1801. }
  1802. }
  1803. context.write(helpInformation);
  1804. this.emit(this._helpLongFlag); // deprecated
  1805. this.emit('afterHelp', context);
  1806. getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context));
  1807. }
  1808. /**
  1809. * You can pass in flags and a description to override the help
  1810. * flags and help description for your command. Pass in false to
  1811. * disable the built-in help option.
  1812. *
  1813. * @param {string | boolean} [flags]
  1814. * @param {string} [description]
  1815. * @return {Command} `this` command for chaining
  1816. */
  1817. helpOption(flags, description) {
  1818. if (typeof flags === 'boolean') {
  1819. this._hasHelpOption = flags;
  1820. return this;
  1821. }
  1822. this._helpFlags = flags || this._helpFlags;
  1823. this._helpDescription = description || this._helpDescription;
  1824. const helpFlags = splitOptionFlags(this._helpFlags);
  1825. this._helpShortFlag = helpFlags.shortFlag;
  1826. this._helpLongFlag = helpFlags.longFlag;
  1827. return this;
  1828. }
  1829. /**
  1830. * Output help information and exit.
  1831. *
  1832. * Outputs built-in help, and custom text added using `.addHelpText()`.
  1833. *
  1834. * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
  1835. */
  1836. help(contextOptions) {
  1837. this.outputHelp(contextOptions);
  1838. let exitCode = process.exitCode || 0;
  1839. if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
  1840. exitCode = 1;
  1841. }
  1842. // message: do not have all displayed text available so only passing placeholder.
  1843. this._exit(exitCode, 'commander.help', '(outputHelp)');
  1844. }
  1845. /**
  1846. * Add additional text to be displayed with the built-in help.
  1847. *
  1848. * Position is 'before' or 'after' to affect just this command,
  1849. * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
  1850. *
  1851. * @param {string} position - before or after built-in help
  1852. * @param {string | Function} text - string to add, or a function returning a string
  1853. * @return {Command} `this` command for chaining
  1854. */
  1855. addHelpText(position, text) {
  1856. const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
  1857. if (!allowedValues.includes(position)) {
  1858. throw new Error(`Unexpected value for position to addHelpText.
  1859. Expecting one of '${allowedValues.join("', '")}'`);
  1860. }
  1861. const helpEvent = `${position}Help`;
  1862. this.on(helpEvent, (context) => {
  1863. let helpStr;
  1864. if (typeof text === 'function') {
  1865. helpStr = text({ error: context.error, command: context.command });
  1866. } else {
  1867. helpStr = text;
  1868. }
  1869. // Ignore falsy value when nothing to output.
  1870. if (helpStr) {
  1871. context.write(`${helpStr}\n`);
  1872. }
  1873. });
  1874. return this;
  1875. }
  1876. }
  1877. /**
  1878. * Output help information if help flags specified
  1879. *
  1880. * @param {Command} cmd - command to output help for
  1881. * @param {Array} args - array of options to search for help flags
  1882. * @api private
  1883. */
  1884. function outputHelpIfRequested(cmd, args) {
  1885. const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
  1886. if (helpOption) {
  1887. cmd.outputHelp();
  1888. // (Do not have all displayed text available so only passing placeholder.)
  1889. cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
  1890. }
  1891. }
  1892. /**
  1893. * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
  1894. *
  1895. * @param {string[]} args - array of arguments from node.execArgv
  1896. * @returns {string[]}
  1897. * @api private
  1898. */
  1899. function incrementNodeInspectorPort(args) {
  1900. // Testing for these options:
  1901. // --inspect[=[host:]port]
  1902. // --inspect-brk[=[host:]port]
  1903. // --inspect-port=[host:]port
  1904. return args.map((arg) => {
  1905. if (!arg.startsWith('--inspect')) {
  1906. return arg;
  1907. }
  1908. let debugOption;
  1909. let debugHost = '127.0.0.1';
  1910. let debugPort = '9229';
  1911. let match;
  1912. if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
  1913. // e.g. --inspect
  1914. debugOption = match[1];
  1915. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
  1916. debugOption = match[1];
  1917. if (/^\d+$/.test(match[3])) {
  1918. // e.g. --inspect=1234
  1919. debugPort = match[3];
  1920. } else {
  1921. // e.g. --inspect=localhost
  1922. debugHost = match[3];
  1923. }
  1924. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
  1925. // e.g. --inspect=localhost:1234
  1926. debugOption = match[1];
  1927. debugHost = match[3];
  1928. debugPort = match[4];
  1929. }
  1930. if (debugOption && debugPort !== '0') {
  1931. return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
  1932. }
  1933. return arg;
  1934. });
  1935. }
  1936. /**
  1937. * @param {Command} startCommand
  1938. * @returns {Command[]}
  1939. * @api private
  1940. */
  1941. function getCommandAndParents(startCommand) {
  1942. const result = [];
  1943. for (let command = startCommand; command; command = command.parent) {
  1944. result.push(command);
  1945. }
  1946. return result;
  1947. }
  1948. exports.Command = Command;