Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. /**
  2. * Module dependencies.
  3. */
  4. const EventEmitter = require('events').EventEmitter;
  5. const spawn = require('child_process').spawn;
  6. const path = require('path');
  7. const fs = require('fs');
  8. // @ts-check
  9. class Option {
  10. /**
  11. * Initialize a new `Option` with the given `flags` and `description`.
  12. *
  13. * @param {string} flags
  14. * @param {string} description
  15. * @api public
  16. */
  17. constructor(flags, description) {
  18. this.flags = flags;
  19. this.required = flags.indexOf('<') >= 0; // A value must be supplied when the option is specified.
  20. this.optional = flags.indexOf('[') >= 0; // A value is optional when the option is specified.
  21. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
  22. this.negate = flags.indexOf('-no-') !== -1;
  23. const flagParts = flags.split(/[ ,|]+/);
  24. if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) this.short = flagParts.shift();
  25. this.long = flagParts.shift();
  26. this.description = description || '';
  27. this.defaultValue = undefined;
  28. }
  29. /**
  30. * Return option name.
  31. *
  32. * @return {string}
  33. * @api private
  34. */
  35. name() {
  36. return this.long.replace(/^--/, '');
  37. };
  38. /**
  39. * Return option name, in a camelcase format that can be used
  40. * as a object attribute key.
  41. *
  42. * @return {string}
  43. * @api private
  44. */
  45. attributeName() {
  46. return camelcase(this.name().replace(/^no-/, ''));
  47. };
  48. /**
  49. * Check if `arg` matches the short or long flag.
  50. *
  51. * @param {string} arg
  52. * @return {boolean}
  53. * @api private
  54. */
  55. is(arg) {
  56. return this.short === arg || this.long === arg;
  57. };
  58. }
  59. /**
  60. * CommanderError class
  61. * @class
  62. */
  63. class CommanderError extends Error {
  64. /**
  65. * Constructs the CommanderError class
  66. * @param {number} exitCode suggested exit code which could be used with process.exit
  67. * @param {string} code an id string representing the error
  68. * @param {string} message human-readable description of the error
  69. * @constructor
  70. */
  71. constructor(exitCode, code, message) {
  72. super(message);
  73. // properly capture stack trace in Node.js
  74. Error.captureStackTrace(this, this.constructor);
  75. this.name = this.constructor.name;
  76. this.code = code;
  77. this.exitCode = exitCode;
  78. this.nestedError = undefined;
  79. }
  80. }
  81. class Command extends EventEmitter {
  82. /**
  83. * Initialize a new `Command`.
  84. *
  85. * @param {string} [name]
  86. * @api public
  87. */
  88. constructor(name) {
  89. super();
  90. this.commands = [];
  91. this.options = [];
  92. this.parent = null;
  93. this._allowUnknownOption = false;
  94. this._args = [];
  95. this.rawArgs = null;
  96. this._scriptPath = null;
  97. this._name = name || '';
  98. this._optionValues = {};
  99. this._storeOptionsAsProperties = true; // backwards compatible by default
  100. this._passCommandToAction = true; // backwards compatible by default
  101. this._actionResults = [];
  102. this._actionHandler = null;
  103. this._executableHandler = false;
  104. this._executableFile = null; // custom name for executable
  105. this._defaultCommandName = null;
  106. this._exitCallback = null;
  107. this._aliases = [];
  108. this._hidden = false;
  109. this._helpFlags = '-h, --help';
  110. this._helpDescription = 'display help for command';
  111. this._helpShortFlag = '-h';
  112. this._helpLongFlag = '--help';
  113. this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false
  114. this._helpCommandName = 'help';
  115. this._helpCommandnameAndArgs = 'help [command]';
  116. this._helpCommandDescription = 'display help for command';
  117. }
  118. /**
  119. * Define a command.
  120. *
  121. * There are two styles of command: pay attention to where to put the description.
  122. *
  123. * Examples:
  124. *
  125. * // Command implemented using action handler (description is supplied separately to `.command`)
  126. * program
  127. * .command('clone <source> [destination]')
  128. * .description('clone a repository into a newly created directory')
  129. * .action((source, destination) => {
  130. * console.log('clone command called');
  131. * });
  132. *
  133. * // Command implemented using separate executable file (description is second parameter to `.command`)
  134. * program
  135. * .command('start <service>', 'start named service')
  136. * .command('stop [service]', 'stop named service, or all if no name supplied');
  137. *
  138. * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
  139. * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
  140. * @param {Object} [execOpts] - configuration options (for executable)
  141. * @return {Command} returns new command for action handler, or `this` for executable command
  142. * @api public
  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 args = nameAndArgs.split(/ +/);
  153. const cmd = this.createCommand(args.shift());
  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);
  160. cmd._helpFlags = this._helpFlags;
  161. cmd._helpDescription = this._helpDescription;
  162. cmd._helpShortFlag = this._helpShortFlag;
  163. cmd._helpLongFlag = this._helpLongFlag;
  164. cmd._helpCommandName = this._helpCommandName;
  165. cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;
  166. cmd._helpCommandDescription = this._helpCommandDescription;
  167. cmd._exitCallback = this._exitCallback;
  168. cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
  169. cmd._passCommandToAction = this._passCommandToAction;
  170. cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
  171. this.commands.push(cmd);
  172. cmd._parseExpectedArgs(args);
  173. cmd.parent = this;
  174. if (desc) return this;
  175. return cmd;
  176. };
  177. /**
  178. * Factory routine to create a new unattached command.
  179. *
  180. * See .command() for creating an attached subcommand, which uses this routine to
  181. * create the command. You can override createCommand to customise subcommands.
  182. *
  183. * @param {string} [name]
  184. * @return {Command} new command
  185. * @api public
  186. */
  187. createCommand(name) {
  188. return new Command(name);
  189. };
  190. /**
  191. * Add a prepared subcommand.
  192. *
  193. * See .command() for creating an attached subcommand which inherits settings from its parent.
  194. *
  195. * @param {Command} cmd - new subcommand
  196. * @param {Object} [opts] - configuration options
  197. * @return {Command} `this` command for chaining
  198. * @api public
  199. */
  200. addCommand(cmd, opts) {
  201. if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
  202. // To keep things simple, block automatic name generation for deeply nested executables.
  203. // Fail fast and detect when adding rather than later when parsing.
  204. function checkExplicitNames(commandArray) {
  205. commandArray.forEach((cmd) => {
  206. if (cmd._executableHandler && !cmd._executableFile) {
  207. throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);
  208. }
  209. checkExplicitNames(cmd.commands);
  210. });
  211. }
  212. checkExplicitNames(cmd.commands);
  213. opts = opts || {};
  214. if (opts.isDefault) this._defaultCommandName = cmd._name;
  215. if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
  216. this.commands.push(cmd);
  217. cmd.parent = this;
  218. return this;
  219. };
  220. /**
  221. * Define argument syntax for the command.
  222. *
  223. * @api public
  224. */
  225. arguments(desc) {
  226. return this._parseExpectedArgs(desc.split(/ +/));
  227. };
  228. /**
  229. * Override default decision whether to add implicit help command.
  230. *
  231. * addHelpCommand() // force on
  232. * addHelpCommand(false); // force off
  233. * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom detais
  234. *
  235. * @return {Command} `this` command for chaining
  236. * @api public
  237. */
  238. addHelpCommand(enableOrNameAndArgs, description) {
  239. if (enableOrNameAndArgs === false) {
  240. this._hasImplicitHelpCommand = false;
  241. } else {
  242. this._hasImplicitHelpCommand = true;
  243. if (typeof enableOrNameAndArgs === 'string') {
  244. this._helpCommandName = enableOrNameAndArgs.split(' ')[0];
  245. this._helpCommandnameAndArgs = enableOrNameAndArgs;
  246. }
  247. this._helpCommandDescription = description || this._helpCommandDescription;
  248. }
  249. return this;
  250. };
  251. /**
  252. * @return {boolean}
  253. * @api private
  254. */
  255. _lazyHasImplicitHelpCommand() {
  256. if (this._hasImplicitHelpCommand === undefined) {
  257. this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help');
  258. }
  259. return this._hasImplicitHelpCommand;
  260. };
  261. /**
  262. * Parse expected `args`.
  263. *
  264. * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
  265. *
  266. * @param {Array} args
  267. * @return {Command} `this` command for chaining
  268. * @api private
  269. */
  270. _parseExpectedArgs(args) {
  271. if (!args.length) return;
  272. args.forEach((arg) => {
  273. const argDetails = {
  274. required: false,
  275. name: '',
  276. variadic: false
  277. };
  278. switch (arg[0]) {
  279. case '<':
  280. argDetails.required = true;
  281. argDetails.name = arg.slice(1, -1);
  282. break;
  283. case '[':
  284. argDetails.name = arg.slice(1, -1);
  285. break;
  286. }
  287. if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
  288. argDetails.variadic = true;
  289. argDetails.name = argDetails.name.slice(0, -3);
  290. }
  291. if (argDetails.name) {
  292. this._args.push(argDetails);
  293. }
  294. });
  295. this._args.forEach((arg, i) => {
  296. if (arg.variadic && i < this._args.length - 1) {
  297. throw new Error(`only the last argument can be variadic '${arg.name}'`);
  298. }
  299. });
  300. return this;
  301. };
  302. /**
  303. * Register callback to use as replacement for calling process.exit.
  304. *
  305. * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
  306. * @return {Command} `this` command for chaining
  307. * @api public
  308. */
  309. exitOverride(fn) {
  310. if (fn) {
  311. this._exitCallback = fn;
  312. } else {
  313. this._exitCallback = (err) => {
  314. if (err.code !== 'commander.executeSubCommandAsync') {
  315. throw err;
  316. } else {
  317. // Async callback from spawn events, not useful to throw.
  318. }
  319. };
  320. }
  321. return this;
  322. };
  323. /**
  324. * Call process.exit, and _exitCallback if defined.
  325. *
  326. * @param {number} exitCode exit code for using with process.exit
  327. * @param {string} code an id string representing the error
  328. * @param {string} message human-readable description of the error
  329. * @return never
  330. * @api private
  331. */
  332. _exit(exitCode, code, message) {
  333. if (this._exitCallback) {
  334. this._exitCallback(new CommanderError(exitCode, code, message));
  335. // Expecting this line is not reached.
  336. }
  337. process.exit(exitCode);
  338. };
  339. /**
  340. * Register callback `fn` for the command.
  341. *
  342. * Examples:
  343. *
  344. * program
  345. * .command('help')
  346. * .description('display verbose help')
  347. * .action(function() {
  348. * // output help here
  349. * });
  350. *
  351. * @param {Function} fn
  352. * @return {Command} `this` command for chaining
  353. * @api public
  354. */
  355. action(fn) {
  356. const listener = (args) => {
  357. // The .action callback takes an extra parameter which is the command or options.
  358. const expectedArgsCount = this._args.length;
  359. const actionArgs = args.slice(0, expectedArgsCount);
  360. if (this._passCommandToAction) {
  361. actionArgs[expectedArgsCount] = this;
  362. } else {
  363. actionArgs[expectedArgsCount] = this.opts();
  364. }
  365. // Add the extra arguments so available too.
  366. if (args.length > expectedArgsCount) {
  367. actionArgs.push(args.slice(expectedArgsCount));
  368. }
  369. const actionResult = fn.apply(this, actionArgs);
  370. // Remember result in case it is async. Assume parseAsync getting called on root.
  371. let rootCommand = this;
  372. while (rootCommand.parent) {
  373. rootCommand = rootCommand.parent;
  374. }
  375. rootCommand._actionResults.push(actionResult);
  376. };
  377. this._actionHandler = listener;
  378. return this;
  379. };
  380. /**
  381. * Internal implementation shared by .option() and .requiredOption()
  382. *
  383. * @param {Object} config
  384. * @param {string} flags
  385. * @param {string} description
  386. * @param {Function|*} [fn] - custom option processing function or default vaue
  387. * @param {*} [defaultValue]
  388. * @return {Command} `this` command for chaining
  389. * @api private
  390. */
  391. _optionEx(config, flags, description, fn, defaultValue) {
  392. const option = new Option(flags, description);
  393. const oname = option.name();
  394. const name = option.attributeName();
  395. option.mandatory = !!config.mandatory;
  396. // default as 3rd arg
  397. if (typeof fn !== 'function') {
  398. if (fn instanceof RegExp) {
  399. // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.
  400. // No longer documented in README, but still present for backwards compatibility.
  401. const regex = fn;
  402. fn = (val, def) => {
  403. const m = regex.exec(val);
  404. return m ? m[0] : def;
  405. };
  406. } else {
  407. defaultValue = fn;
  408. fn = null;
  409. }
  410. }
  411. // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value
  412. if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
  413. // when --no-foo we make sure default is true, unless a --foo option is already defined
  414. if (option.negate) {
  415. const positiveLongFlag = option.long.replace(/^--no-/, '--');
  416. defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true;
  417. }
  418. // preassign only if we have a default
  419. if (defaultValue !== undefined) {
  420. this._setOptionValue(name, defaultValue);
  421. option.defaultValue = defaultValue;
  422. }
  423. }
  424. // register the option
  425. this.options.push(option);
  426. // when it's passed assign the value
  427. // and conditionally invoke the callback
  428. this.on('option:' + oname, (val) => {
  429. // coercion
  430. if (val !== null && fn) {
  431. val = fn(val, this._getOptionValue(name) === undefined ? defaultValue : this._getOptionValue(name));
  432. }
  433. // unassigned or boolean value
  434. if (typeof this._getOptionValue(name) === 'boolean' || typeof this._getOptionValue(name) === 'undefined') {
  435. // if no value, negate false, and we have a default, then use it!
  436. if (val == null) {
  437. this._setOptionValue(name, option.negate
  438. ? false
  439. : defaultValue || true);
  440. } else {
  441. this._setOptionValue(name, val);
  442. }
  443. } else if (val !== null) {
  444. // reassign
  445. this._setOptionValue(name, option.negate ? false : val);
  446. }
  447. });
  448. return this;
  449. };
  450. /**
  451. * Define option with `flags`, `description` and optional
  452. * coercion `fn`.
  453. *
  454. * The `flags` string should contain both the short and long flags,
  455. * separated by comma, a pipe or space. The following are all valid
  456. * all will output this way when `--help` is used.
  457. *
  458. * "-p, --pepper"
  459. * "-p|--pepper"
  460. * "-p --pepper"
  461. *
  462. * Examples:
  463. *
  464. * // simple boolean defaulting to undefined
  465. * program.option('-p, --pepper', 'add pepper');
  466. *
  467. * program.pepper
  468. * // => undefined
  469. *
  470. * --pepper
  471. * program.pepper
  472. * // => true
  473. *
  474. * // simple boolean defaulting to true (unless non-negated option is also defined)
  475. * program.option('-C, --no-cheese', 'remove cheese');
  476. *
  477. * program.cheese
  478. * // => true
  479. *
  480. * --no-cheese
  481. * program.cheese
  482. * // => false
  483. *
  484. * // required argument
  485. * program.option('-C, --chdir <path>', 'change the working directory');
  486. *
  487. * --chdir /tmp
  488. * program.chdir
  489. * // => "/tmp"
  490. *
  491. * // optional argument
  492. * program.option('-c, --cheese [type]', 'add cheese [marble]');
  493. *
  494. * @param {string} flags
  495. * @param {string} description
  496. * @param {Function|*} [fn] - custom option processing function or default vaue
  497. * @param {*} [defaultValue]
  498. * @return {Command} `this` command for chaining
  499. * @api public
  500. */
  501. option(flags, description, fn, defaultValue) {
  502. return this._optionEx({}, flags, description, fn, defaultValue);
  503. };
  504. /*
  505. * Add a required option which must have a value after parsing. This usually means
  506. * the option must be specified on the command line. (Otherwise the same as .option().)
  507. *
  508. * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
  509. *
  510. * @param {string} flags
  511. * @param {string} description
  512. * @param {Function|*} [fn] - custom option processing function or default vaue
  513. * @param {*} [defaultValue]
  514. * @return {Command} `this` command for chaining
  515. * @api public
  516. */
  517. requiredOption(flags, description, fn, defaultValue) {
  518. return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
  519. };
  520. /**
  521. * Allow unknown options on the command line.
  522. *
  523. * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown
  524. * for unknown options.
  525. * @api public
  526. */
  527. allowUnknownOption(arg) {
  528. this._allowUnknownOption = (arg === undefined) || arg;
  529. return this;
  530. };
  531. /**
  532. * Whether to store option values as properties on command object,
  533. * or store separately (specify false). In both cases the option values can be accessed using .opts().
  534. *
  535. * @param {boolean} value
  536. * @return {Command} `this` command for chaining
  537. * @api public
  538. */
  539. storeOptionsAsProperties(value) {
  540. this._storeOptionsAsProperties = (value === undefined) || value;
  541. if (this.options.length) {
  542. throw new Error('call .storeOptionsAsProperties() before adding options');
  543. }
  544. return this;
  545. };
  546. /**
  547. * Whether to pass command to action handler,
  548. * or just the options (specify false).
  549. *
  550. * @param {boolean} value
  551. * @return {Command} `this` command for chaining
  552. * @api public
  553. */
  554. passCommandToAction(value) {
  555. this._passCommandToAction = (value === undefined) || value;
  556. return this;
  557. };
  558. /**
  559. * Store option value
  560. *
  561. * @param {string} key
  562. * @param {Object} value
  563. * @api private
  564. */
  565. _setOptionValue(key, value) {
  566. if (this._storeOptionsAsProperties) {
  567. this[key] = value;
  568. } else {
  569. this._optionValues[key] = value;
  570. }
  571. };
  572. /**
  573. * Retrieve option value
  574. *
  575. * @param {string} key
  576. * @return {Object} value
  577. * @api private
  578. */
  579. _getOptionValue(key) {
  580. if (this._storeOptionsAsProperties) {
  581. return this[key];
  582. }
  583. return this._optionValues[key];
  584. };
  585. /**
  586. * Parse `argv`, setting options and invoking commands when defined.
  587. *
  588. * The default expectation is that the arguments are from node and have the application as argv[0]
  589. * and the script being run in argv[1], with user parameters after that.
  590. *
  591. * Examples:
  592. *
  593. * program.parse(process.argv);
  594. * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
  595. * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  596. *
  597. * @param {string[]} [argv] - optional, defaults to process.argv
  598. * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
  599. * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
  600. * @return {Command} `this` command for chaining
  601. * @api public
  602. */
  603. parse(argv, parseOptions) {
  604. if (argv !== undefined && !Array.isArray(argv)) {
  605. throw new Error('first parameter to parse must be array or undefined');
  606. }
  607. parseOptions = parseOptions || {};
  608. // Default to using process.argv
  609. if (argv === undefined) {
  610. argv = process.argv;
  611. // @ts-ignore
  612. if (process.versions && process.versions.electron) {
  613. parseOptions.from = 'electron';
  614. }
  615. }
  616. this.rawArgs = argv.slice();
  617. // make it a little easier for callers by supporting various argv conventions
  618. let userArgs;
  619. switch (parseOptions.from) {
  620. case undefined:
  621. case 'node':
  622. this._scriptPath = argv[1];
  623. userArgs = argv.slice(2);
  624. break;
  625. case 'electron':
  626. // @ts-ignore
  627. if (process.defaultApp) {
  628. this._scriptPath = argv[1];
  629. userArgs = argv.slice(2);
  630. } else {
  631. userArgs = argv.slice(1);
  632. }
  633. break;
  634. case 'user':
  635. userArgs = argv.slice(0);
  636. break;
  637. default:
  638. throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
  639. }
  640. if (!this._scriptPath && process.mainModule) {
  641. this._scriptPath = process.mainModule.filename;
  642. }
  643. // Guess name, used in usage in help.
  644. this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));
  645. // Let's go!
  646. this._parseCommand([], userArgs);
  647. return this;
  648. };
  649. /**
  650. * Parse `argv`, setting options and invoking commands when defined.
  651. *
  652. * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
  653. *
  654. * The default expectation is that the arguments are from node and have the application as argv[0]
  655. * and the script being run in argv[1], with user parameters after that.
  656. *
  657. * Examples:
  658. *
  659. * program.parseAsync(process.argv);
  660. * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
  661. * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  662. *
  663. * @param {string[]} [argv]
  664. * @param {Object} [parseOptions]
  665. * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
  666. * @return {Promise}
  667. * @api public
  668. */
  669. parseAsync(argv, parseOptions) {
  670. this.parse(argv, parseOptions);
  671. return Promise.all(this._actionResults).then(() => this);
  672. };
  673. /**
  674. * Execute a sub-command executable.
  675. *
  676. * @api private
  677. */
  678. _executeSubCommand(subcommand, args) {
  679. args = args.slice();
  680. let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
  681. const sourceExt = ['.js', '.ts', '.mjs'];
  682. // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
  683. this._checkForMissingMandatoryOptions();
  684. // Want the entry script as the reference for command name and directory for searching for other files.
  685. const scriptPath = this._scriptPath;
  686. let baseDir;
  687. try {
  688. const resolvedLink = fs.realpathSync(scriptPath);
  689. baseDir = path.dirname(resolvedLink);
  690. } catch (e) {
  691. baseDir = '.'; // dummy, probably not going to find executable!
  692. }
  693. // name of the subcommand, like `pm-install`
  694. let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;
  695. if (subcommand._executableFile) {
  696. bin = subcommand._executableFile;
  697. }
  698. const localBin = path.join(baseDir, bin);
  699. if (fs.existsSync(localBin)) {
  700. // prefer local `./<bin>` to bin in the $PATH
  701. bin = localBin;
  702. } else {
  703. // Look for source files.
  704. sourceExt.forEach((ext) => {
  705. if (fs.existsSync(`${localBin}${ext}`)) {
  706. bin = `${localBin}${ext}`;
  707. }
  708. });
  709. }
  710. launchWithNode = sourceExt.includes(path.extname(bin));
  711. let proc;
  712. if (process.platform !== 'win32') {
  713. if (launchWithNode) {
  714. args.unshift(bin);
  715. // add executable arguments to spawn
  716. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  717. proc = spawn(process.argv[0], args, { stdio: 'inherit' });
  718. } else {
  719. proc = spawn(bin, args, { stdio: 'inherit' });
  720. }
  721. } else {
  722. args.unshift(bin);
  723. // add executable arguments to spawn
  724. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  725. proc = spawn(process.execPath, args, { stdio: 'inherit' });
  726. }
  727. const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  728. signals.forEach((signal) => {
  729. // @ts-ignore
  730. process.on(signal, () => {
  731. if (proc.killed === false && proc.exitCode === null) {
  732. proc.kill(signal);
  733. }
  734. });
  735. });
  736. // By default terminate process when spawned process terminates.
  737. // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
  738. const exitCallback = this._exitCallback;
  739. if (!exitCallback) {
  740. proc.on('close', process.exit.bind(process));
  741. } else {
  742. proc.on('close', () => {
  743. exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
  744. });
  745. }
  746. proc.on('error', (err) => {
  747. // @ts-ignore
  748. if (err.code === 'ENOENT') {
  749. const executableMissing = `'${bin}' does not exist
  750. - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
  751. - if the default executable name is not suitable, use the executableFile option to supply a custom name`;
  752. throw new Error(executableMissing);
  753. // @ts-ignore
  754. } else if (err.code === 'EACCES') {
  755. throw new Error(`'${bin}' not executable`);
  756. }
  757. if (!exitCallback) {
  758. process.exit(1);
  759. } else {
  760. const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
  761. wrappedError.nestedError = err;
  762. exitCallback(wrappedError);
  763. }
  764. });
  765. // Store the reference to the child process
  766. this.runningCommand = proc;
  767. };
  768. /**
  769. * @api private
  770. */
  771. _dispatchSubcommand(commandName, operands, unknown) {
  772. const subCommand = this._findCommand(commandName);
  773. if (!subCommand) this._helpAndError();
  774. if (subCommand._executableHandler) {
  775. this._executeSubCommand(subCommand, operands.concat(unknown));
  776. } else {
  777. subCommand._parseCommand(operands, unknown);
  778. }
  779. };
  780. /**
  781. * Process arguments in context of this command.
  782. *
  783. * @api private
  784. */
  785. _parseCommand(operands, unknown) {
  786. const parsed = this.parseOptions(unknown);
  787. operands = operands.concat(parsed.operands);
  788. unknown = parsed.unknown;
  789. this.args = operands.concat(unknown);
  790. if (operands && this._findCommand(operands[0])) {
  791. this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
  792. } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
  793. if (operands.length === 1) {
  794. this.help();
  795. } else {
  796. this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
  797. }
  798. } else if (this._defaultCommandName) {
  799. outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
  800. this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
  801. } else {
  802. if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
  803. // probaby missing subcommand and no handler, user needs help
  804. this._helpAndError();
  805. }
  806. outputHelpIfRequested(this, parsed.unknown);
  807. this._checkForMissingMandatoryOptions();
  808. if (parsed.unknown.length > 0) {
  809. this.unknownOption(parsed.unknown[0]);
  810. }
  811. if (this._actionHandler) {
  812. const args = this.args.slice();
  813. this._args.forEach((arg, i) => {
  814. if (arg.required && args[i] == null) {
  815. this.missingArgument(arg.name);
  816. } else if (arg.variadic) {
  817. args[i] = args.splice(i);
  818. }
  819. });
  820. this._actionHandler(args);
  821. this.emit('command:' + this.name(), operands, unknown);
  822. } else if (operands.length) {
  823. if (this._findCommand('*')) {
  824. this._dispatchSubcommand('*', operands, unknown);
  825. } else if (this.listenerCount('command:*')) {
  826. this.emit('command:*', operands, unknown);
  827. } else if (this.commands.length) {
  828. this.unknownCommand();
  829. }
  830. } else if (this.commands.length) {
  831. // This command has subcommands and nothing hooked up at this level, so display help.
  832. this._helpAndError();
  833. } else {
  834. // fall through for caller to handle after calling .parse()
  835. }
  836. }
  837. };
  838. /**
  839. * Find matching command.
  840. *
  841. * @api private
  842. */
  843. _findCommand(name) {
  844. if (!name) return undefined;
  845. return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
  846. };
  847. /**
  848. * Return an option matching `arg` if any.
  849. *
  850. * @param {string} arg
  851. * @return {Option}
  852. * @api private
  853. */
  854. _findOption(arg) {
  855. return this.options.find(option => option.is(arg));
  856. };
  857. /**
  858. * Display an error message if a mandatory option does not have a value.
  859. * Lazy calling after checking for help flags from leaf subcommand.
  860. *
  861. * @api private
  862. */
  863. _checkForMissingMandatoryOptions() {
  864. // Walk up hierarchy so can call in subcommand after checking for displaying help.
  865. for (let cmd = this; cmd; cmd = cmd.parent) {
  866. cmd.options.forEach((anOption) => {
  867. if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
  868. cmd.missingMandatoryOptionValue(anOption);
  869. }
  870. });
  871. }
  872. };
  873. /**
  874. * Parse options from `argv` removing known options,
  875. * and return argv split into operands and unknown arguments.
  876. *
  877. * Examples:
  878. *
  879. * argv => operands, unknown
  880. * --known kkk op => [op], []
  881. * op --known kkk => [op], []
  882. * sub --unknown uuu op => [sub], [--unknown uuu op]
  883. * sub -- --unknown uuu op => [sub --unknown uuu op], []
  884. *
  885. * @param {String[]} argv
  886. * @return {{operands: String[], unknown: String[]}}
  887. * @api public
  888. */
  889. parseOptions(argv) {
  890. const operands = []; // operands, not options or values
  891. const unknown = []; // first unknown option and remaining unknown args
  892. let dest = operands;
  893. const args = argv.slice();
  894. function maybeOption(arg) {
  895. return arg.length > 1 && arg[0] === '-';
  896. }
  897. // parse options
  898. while (args.length) {
  899. const arg = args.shift();
  900. // literal
  901. if (arg === '--') {
  902. if (dest === unknown) dest.push(arg);
  903. dest.push(...args);
  904. break;
  905. }
  906. if (maybeOption(arg)) {
  907. const option = this._findOption(arg);
  908. // recognised option, call listener to assign value with possible custom processing
  909. if (option) {
  910. if (option.required) {
  911. const value = args.shift();
  912. if (value === undefined) this.optionMissingArgument(option);
  913. this.emit(`option:${option.name()}`, value);
  914. } else if (option.optional) {
  915. let value = null;
  916. // historical behaviour is optional value is following arg unless an option
  917. if (args.length > 0 && !maybeOption(args[0])) {
  918. value = args.shift();
  919. }
  920. this.emit(`option:${option.name()}`, value);
  921. } else { // boolean flag
  922. this.emit(`option:${option.name()}`);
  923. }
  924. continue;
  925. }
  926. }
  927. // Look for combo options following single dash, eat first one if known.
  928. if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
  929. const option = this._findOption(`-${arg[1]}`);
  930. if (option) {
  931. if (option.required || option.optional) {
  932. // option with value following in same argument
  933. this.emit(`option:${option.name()}`, arg.slice(2));
  934. } else {
  935. // boolean option, emit and put back remainder of arg for further processing
  936. this.emit(`option:${option.name()}`);
  937. args.unshift(`-${arg.slice(2)}`);
  938. }
  939. continue;
  940. }
  941. }
  942. // Look for known long flag with value, like --foo=bar
  943. if (/^--[^=]+=/.test(arg)) {
  944. const index = arg.indexOf('=');
  945. const option = this._findOption(arg.slice(0, index));
  946. if (option && (option.required || option.optional)) {
  947. this.emit(`option:${option.name()}`, arg.slice(index + 1));
  948. continue;
  949. }
  950. }
  951. // looks like an option but unknown, unknowns from here
  952. if (arg.length > 1 && arg[0] === '-') {
  953. dest = unknown;
  954. }
  955. // add arg
  956. dest.push(arg);
  957. }
  958. return { operands, unknown };
  959. };
  960. /**
  961. * Return an object containing options as key-value pairs
  962. *
  963. * @return {Object}
  964. * @api public
  965. */
  966. opts() {
  967. if (this._storeOptionsAsProperties) {
  968. // Preserve original behaviour so backwards compatible when still using properties
  969. const result = {};
  970. const len = this.options.length;
  971. for (let i = 0; i < len; i++) {
  972. const key = this.options[i].attributeName();
  973. result[key] = key === this._versionOptionName ? this._version : this[key];
  974. }
  975. return result;
  976. }
  977. return this._optionValues;
  978. };
  979. /**
  980. * Argument `name` is missing.
  981. *
  982. * @param {string} name
  983. * @api private
  984. */
  985. missingArgument(name) {
  986. const message = `error: missing required argument '${name}'`;
  987. console.error(message);
  988. this._exit(1, 'commander.missingArgument', message);
  989. };
  990. /**
  991. * `Option` is missing an argument, but received `flag` or nothing.
  992. *
  993. * @param {Option} option
  994. * @param {string} [flag]
  995. * @api private
  996. */
  997. optionMissingArgument(option, flag) {
  998. let message;
  999. if (flag) {
  1000. message = `error: option '${option.flags}' argument missing, got '${flag}'`;
  1001. } else {
  1002. message = `error: option '${option.flags}' argument missing`;
  1003. }
  1004. console.error(message);
  1005. this._exit(1, 'commander.optionMissingArgument', message);
  1006. };
  1007. /**
  1008. * `Option` does not have a value, and is a mandatory option.
  1009. *
  1010. * @param {Option} option
  1011. * @api private
  1012. */
  1013. missingMandatoryOptionValue(option) {
  1014. const message = `error: required option '${option.flags}' not specified`;
  1015. console.error(message);
  1016. this._exit(1, 'commander.missingMandatoryOptionValue', message);
  1017. };
  1018. /**
  1019. * Unknown option `flag`.
  1020. *
  1021. * @param {string} flag
  1022. * @api private
  1023. */
  1024. unknownOption(flag) {
  1025. if (this._allowUnknownOption) return;
  1026. const message = `error: unknown option '${flag}'`;
  1027. console.error(message);
  1028. this._exit(1, 'commander.unknownOption', message);
  1029. };
  1030. /**
  1031. * Unknown command.
  1032. *
  1033. * @api private
  1034. */
  1035. unknownCommand() {
  1036. const partCommands = [this.name()];
  1037. for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
  1038. partCommands.unshift(parentCmd.name());
  1039. }
  1040. const fullCommand = partCommands.join(' ');
  1041. const message = `error: unknown command '${this.args[0]}'. See '${fullCommand} ${this._helpLongFlag}'.`;
  1042. console.error(message);
  1043. this._exit(1, 'commander.unknownCommand', message);
  1044. };
  1045. /**
  1046. * Set the program version to `str`.
  1047. *
  1048. * This method auto-registers the "-V, --version" flag
  1049. * which will print the version number when passed.
  1050. *
  1051. * You can optionally supply the flags and description to override the defaults.
  1052. *
  1053. * @param {string} str
  1054. * @param {string} [flags]
  1055. * @param {string} [description]
  1056. * @return {this | string} `this` command for chaining, or version string if no arguments
  1057. * @api public
  1058. */
  1059. version(str, flags, description) {
  1060. if (str === undefined) return this._version;
  1061. this._version = str;
  1062. flags = flags || '-V, --version';
  1063. description = description || 'output the version number';
  1064. const versionOption = new Option(flags, description);
  1065. this._versionOptionName = versionOption.long.substr(2) || 'version';
  1066. this.options.push(versionOption);
  1067. this.on('option:' + this._versionOptionName, () => {
  1068. process.stdout.write(str + '\n');
  1069. this._exit(0, 'commander.version', str);
  1070. });
  1071. return this;
  1072. };
  1073. /**
  1074. * Set the description to `str`.
  1075. *
  1076. * @param {string} str
  1077. * @param {Object} [argsDescription]
  1078. * @return {string|Command}
  1079. * @api public
  1080. */
  1081. description(str, argsDescription) {
  1082. if (str === undefined && argsDescription === undefined) return this._description;
  1083. this._description = str;
  1084. this._argsDescription = argsDescription;
  1085. return this;
  1086. };
  1087. /**
  1088. * Set an alias for the command.
  1089. *
  1090. * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
  1091. *
  1092. * @param {string} [alias]
  1093. * @return {string|Command}
  1094. * @api public
  1095. */
  1096. alias(alias) {
  1097. if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
  1098. let command = this;
  1099. if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
  1100. // assume adding alias for last added executable subcommand, rather than this
  1101. command = this.commands[this.commands.length - 1];
  1102. }
  1103. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  1104. command._aliases.push(alias);
  1105. return this;
  1106. };
  1107. /**
  1108. * Set aliases for the command.
  1109. *
  1110. * Only the first alias is shown in the auto-generated help.
  1111. *
  1112. * @param {string[]} [aliases]
  1113. * @return {string[]|Command}
  1114. * @api public
  1115. */
  1116. aliases(aliases) {
  1117. // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
  1118. if (aliases === undefined) return this._aliases;
  1119. aliases.forEach((alias) => this.alias(alias));
  1120. return this;
  1121. };
  1122. /**
  1123. * Set / get the command usage `str`.
  1124. *
  1125. * @param {string} [str]
  1126. * @return {String|Command}
  1127. * @api public
  1128. */
  1129. usage(str) {
  1130. if (str === undefined) {
  1131. if (this._usage) return this._usage;
  1132. const args = this._args.map((arg) => {
  1133. return humanReadableArgName(arg);
  1134. });
  1135. return '[options]' +
  1136. (this.commands.length ? ' [command]' : '') +
  1137. (this._args.length ? ' ' + args.join(' ') : '');
  1138. }
  1139. this._usage = str;
  1140. return this;
  1141. };
  1142. /**
  1143. * Get or set the name of the command
  1144. *
  1145. * @param {string} [str]
  1146. * @return {String|Command}
  1147. * @api public
  1148. */
  1149. name(str) {
  1150. if (str === undefined) return this._name;
  1151. this._name = str;
  1152. return this;
  1153. };
  1154. /**
  1155. * Return prepared commands.
  1156. *
  1157. * @return {Array}
  1158. * @api private
  1159. */
  1160. prepareCommands() {
  1161. const commandDetails = this.commands.filter((cmd) => {
  1162. return !cmd._hidden;
  1163. }).map((cmd) => {
  1164. const args = cmd._args.map((arg) => {
  1165. return humanReadableArgName(arg);
  1166. }).join(' ');
  1167. return [
  1168. cmd._name +
  1169. (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
  1170. (cmd.options.length ? ' [options]' : '') +
  1171. (args ? ' ' + args : ''),
  1172. cmd._description
  1173. ];
  1174. });
  1175. if (this._lazyHasImplicitHelpCommand()) {
  1176. commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);
  1177. }
  1178. return commandDetails;
  1179. };
  1180. /**
  1181. * Return the largest command length.
  1182. *
  1183. * @return {number}
  1184. * @api private
  1185. */
  1186. largestCommandLength() {
  1187. const commands = this.prepareCommands();
  1188. return commands.reduce((max, command) => {
  1189. return Math.max(max, command[0].length);
  1190. }, 0);
  1191. };
  1192. /**
  1193. * Return the largest option length.
  1194. *
  1195. * @return {number}
  1196. * @api private
  1197. */
  1198. largestOptionLength() {
  1199. const options = [].slice.call(this.options);
  1200. options.push({
  1201. flags: this._helpFlags
  1202. });
  1203. return options.reduce((max, option) => {
  1204. return Math.max(max, option.flags.length);
  1205. }, 0);
  1206. };
  1207. /**
  1208. * Return the largest arg length.
  1209. *
  1210. * @return {number}
  1211. * @api private
  1212. */
  1213. largestArgLength() {
  1214. return this._args.reduce((max, arg) => {
  1215. return Math.max(max, arg.name.length);
  1216. }, 0);
  1217. };
  1218. /**
  1219. * Return the pad width.
  1220. *
  1221. * @return {number}
  1222. * @api private
  1223. */
  1224. padWidth() {
  1225. let width = this.largestOptionLength();
  1226. if (this._argsDescription && this._args.length) {
  1227. if (this.largestArgLength() > width) {
  1228. width = this.largestArgLength();
  1229. }
  1230. }
  1231. if (this.commands && this.commands.length) {
  1232. if (this.largestCommandLength() > width) {
  1233. width = this.largestCommandLength();
  1234. }
  1235. }
  1236. return width;
  1237. };
  1238. /**
  1239. * Return help for options.
  1240. *
  1241. * @return {string}
  1242. * @api private
  1243. */
  1244. optionHelp() {
  1245. const width = this.padWidth();
  1246. const columns = process.stdout.columns || 80;
  1247. const descriptionWidth = columns - width - 4;
  1248. function padOptionDetails(flags, description) {
  1249. return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2);
  1250. };
  1251. // Explicit options (including version)
  1252. const help = this.options.map((option) => {
  1253. const fullDesc = option.description +
  1254. ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
  1255. return padOptionDetails(option.flags, fullDesc);
  1256. });
  1257. // Implicit help
  1258. const showShortHelpFlag = this._helpShortFlag && !this._findOption(this._helpShortFlag);
  1259. const showLongHelpFlag = !this._findOption(this._helpLongFlag);
  1260. if (showShortHelpFlag || showLongHelpFlag) {
  1261. let helpFlags = this._helpFlags;
  1262. if (!showShortHelpFlag) {
  1263. helpFlags = this._helpLongFlag;
  1264. } else if (!showLongHelpFlag) {
  1265. helpFlags = this._helpShortFlag;
  1266. }
  1267. help.push(padOptionDetails(helpFlags, this._helpDescription));
  1268. }
  1269. return help.join('\n');
  1270. };
  1271. /**
  1272. * Return command help documentation.
  1273. *
  1274. * @return {string}
  1275. * @api private
  1276. */
  1277. commandHelp() {
  1278. if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';
  1279. const commands = this.prepareCommands();
  1280. const width = this.padWidth();
  1281. const columns = process.stdout.columns || 80;
  1282. const descriptionWidth = columns - width - 4;
  1283. return [
  1284. 'Commands:',
  1285. commands.map((cmd) => {
  1286. const desc = cmd[1] ? ' ' + cmd[1] : '';
  1287. return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);
  1288. }).join('\n').replace(/^/gm, ' '),
  1289. ''
  1290. ].join('\n');
  1291. };
  1292. /**
  1293. * Return program help documentation.
  1294. *
  1295. * @return {string}
  1296. * @api public
  1297. */
  1298. helpInformation() {
  1299. let desc = [];
  1300. if (this._description) {
  1301. desc = [
  1302. this._description,
  1303. ''
  1304. ];
  1305. const argsDescription = this._argsDescription;
  1306. if (argsDescription && this._args.length) {
  1307. const width = this.padWidth();
  1308. const columns = process.stdout.columns || 80;
  1309. const descriptionWidth = columns - width - 5;
  1310. desc.push('Arguments:');
  1311. desc.push('');
  1312. this._args.forEach((arg) => {
  1313. desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4));
  1314. });
  1315. desc.push('');
  1316. }
  1317. }
  1318. let cmdName = this._name;
  1319. if (this._aliases[0]) {
  1320. cmdName = cmdName + '|' + this._aliases[0];
  1321. }
  1322. let parentCmdNames = '';
  1323. for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
  1324. parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
  1325. }
  1326. const usage = [
  1327. 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),
  1328. ''
  1329. ];
  1330. let cmds = [];
  1331. const commandHelp = this.commandHelp();
  1332. if (commandHelp) cmds = [commandHelp];
  1333. const options = [
  1334. 'Options:',
  1335. '' + this.optionHelp().replace(/^/gm, ' '),
  1336. ''
  1337. ];
  1338. return usage
  1339. .concat(desc)
  1340. .concat(options)
  1341. .concat(cmds)
  1342. .join('\n');
  1343. };
  1344. /**
  1345. * Output help information for this command.
  1346. *
  1347. * When listener(s) are available for the helpLongFlag
  1348. * those callbacks are invoked.
  1349. *
  1350. * @api public
  1351. */
  1352. outputHelp(cb) {
  1353. if (!cb) {
  1354. cb = (passthru) => {
  1355. return passthru;
  1356. };
  1357. }
  1358. const cbOutput = cb(this.helpInformation());
  1359. if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {
  1360. throw new Error('outputHelp callback must return a string or a Buffer');
  1361. }
  1362. process.stdout.write(cbOutput);
  1363. this.emit(this._helpLongFlag);
  1364. };
  1365. /**
  1366. * You can pass in flags and a description to override the help
  1367. * flags and help description for your command.
  1368. *
  1369. * @param {string} [flags]
  1370. * @param {string} [description]
  1371. * @return {Command} `this` command for chaining
  1372. * @api public
  1373. */
  1374. helpOption(flags, description) {
  1375. this._helpFlags = flags || this._helpFlags;
  1376. this._helpDescription = description || this._helpDescription;
  1377. const splitFlags = this._helpFlags.split(/[ ,|]+/);
  1378. this._helpShortFlag = undefined;
  1379. if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift();
  1380. this._helpLongFlag = splitFlags.shift();
  1381. return this;
  1382. };
  1383. /**
  1384. * Output help information and exit.
  1385. *
  1386. * @param {Function} [cb]
  1387. * @api public
  1388. */
  1389. help(cb) {
  1390. this.outputHelp(cb);
  1391. // exitCode: preserving original behaviour which was calling process.exit()
  1392. // message: do not have all displayed text available so only passing placeholder.
  1393. this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');
  1394. };
  1395. /**
  1396. * Output help information and exit. Display for error situations.
  1397. *
  1398. * @api private
  1399. */
  1400. _helpAndError() {
  1401. this.outputHelp();
  1402. // message: do not have all displayed text available so only passing placeholder.
  1403. this._exit(1, 'commander.help', '(outputHelp)');
  1404. };
  1405. };
  1406. /**
  1407. * Expose the root command.
  1408. */
  1409. exports = module.exports = new Command();
  1410. exports.program = exports; // More explicit access to global command.
  1411. /**
  1412. * Expose classes
  1413. */
  1414. exports.Command = Command;
  1415. exports.Option = Option;
  1416. exports.CommanderError = CommanderError;
  1417. /**
  1418. * Camel-case the given `flag`
  1419. *
  1420. * @param {string} flag
  1421. * @return {string}
  1422. * @api private
  1423. */
  1424. function camelcase(flag) {
  1425. return flag.split('-').reduce((str, word) => {
  1426. return str + word[0].toUpperCase() + word.slice(1);
  1427. });
  1428. }
  1429. /**
  1430. * Pad `str` to `width`.
  1431. *
  1432. * @param {string} str
  1433. * @param {number} width
  1434. * @return {string}
  1435. * @api private
  1436. */
  1437. function pad(str, width) {
  1438. const len = Math.max(0, width - str.length);
  1439. return str + Array(len + 1).join(' ');
  1440. }
  1441. /**
  1442. * Wraps the given string with line breaks at the specified width while breaking
  1443. * words and indenting every but the first line on the left.
  1444. *
  1445. * @param {string} str
  1446. * @param {number} width
  1447. * @param {number} indent
  1448. * @return {string}
  1449. * @api private
  1450. */
  1451. function wrap(str, width, indent) {
  1452. const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
  1453. const lines = str.match(regex) || [];
  1454. return lines.map((line, i) => {
  1455. if (line.slice(-1) === '\n') {
  1456. line = line.slice(0, line.length - 1);
  1457. }
  1458. return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight();
  1459. }).join('\n');
  1460. }
  1461. /**
  1462. * Optionally wrap the given str to a max width of width characters per line
  1463. * while indenting with indent spaces. Do not wrap if insufficient width or
  1464. * string is manually formatted.
  1465. *
  1466. * @param {string} str
  1467. * @param {number} width
  1468. * @param {number} indent
  1469. * @return {string}
  1470. * @api private
  1471. */
  1472. function optionalWrap(str, width, indent) {
  1473. // Detect manually wrapped and indented strings by searching for line breaks
  1474. // followed by multiple spaces/tabs.
  1475. if (str.match(/[\n]\s+/)) return str;
  1476. // Do not wrap to narrow columns (or can end up with a word per line).
  1477. const minWidth = 40;
  1478. if (width < minWidth) return str;
  1479. return wrap(str, width, indent);
  1480. }
  1481. /**
  1482. * Output help information if help flags specified
  1483. *
  1484. * @param {Command} cmd - command to output help for
  1485. * @param {Array} args - array of options to search for help flags
  1486. * @api private
  1487. */
  1488. function outputHelpIfRequested(cmd, args) {
  1489. const helpOption = args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
  1490. if (helpOption) {
  1491. cmd.outputHelp();
  1492. // (Do not have all displayed text available so only passing placeholder.)
  1493. cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
  1494. }
  1495. }
  1496. /**
  1497. * Takes an argument and returns its human readable equivalent for help usage.
  1498. *
  1499. * @param {Object} arg
  1500. * @return {string}
  1501. * @api private
  1502. */
  1503. function humanReadableArgName(arg) {
  1504. const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
  1505. return arg.required
  1506. ? '<' + nameOutput + '>'
  1507. : '[' + nameOutput + ']';
  1508. }
  1509. /**
  1510. * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
  1511. *
  1512. * @param {string[]} args - array of arguments from node.execArgv
  1513. * @returns {string[]}
  1514. * @api private
  1515. */
  1516. function incrementNodeInspectorPort(args) {
  1517. // Testing for these options:
  1518. // --inspect[=[host:]port]
  1519. // --inspect-brk[=[host:]port]
  1520. // --inspect-port=[host:]port
  1521. return args.map((arg) => {
  1522. let result = arg;
  1523. if (arg.indexOf('--inspect') === 0) {
  1524. let debugOption;
  1525. let debugHost = '127.0.0.1';
  1526. let debugPort = '9229';
  1527. let match;
  1528. if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
  1529. // e.g. --inspect
  1530. debugOption = match[1];
  1531. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
  1532. debugOption = match[1];
  1533. if (/^\d+$/.test(match[3])) {
  1534. // e.g. --inspect=1234
  1535. debugPort = match[3];
  1536. } else {
  1537. // e.g. --inspect=localhost
  1538. debugHost = match[3];
  1539. }
  1540. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
  1541. // e.g. --inspect=localhost:1234
  1542. debugOption = match[1];
  1543. debugHost = match[3];
  1544. debugPort = match[4];
  1545. }
  1546. if (debugOption && debugPort !== '0') {
  1547. result = `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
  1548. }
  1549. }
  1550. return result;
  1551. });
  1552. }