command.js 76 KB

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