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