command.js 61 KB

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