command.js 85 KB

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