Refactor async support to return (possible) promise directly (#1513)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by John Gee · committed by GitHub · parent f99d6fa · Browse files · 1 file·+99 added−89 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+99 added−89 removed
- other:+99 added−89 removed
Provenance
- Commit
59c8153- Tree
d36b2e1- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
f99d6fa
1 file changed+99 added−89 removed
modified:index.js+99 added-89 removed
665 unmodified lines666 this._scriptPath = null;667 this._name = name || '';668 this._optionValues = {};669 this._storeOptionsAsProperties = false;670- this._actionResults = [];670 this._actionHandler = null;671 this._executableHandler = false;672 this._executableFile = null; // custom name for executable673 this._defaultCommandName = null;381 unmodified lines1055 actionArgs[expectedArgsCount] = this.opts();1056 }1057 actionArgs.push(this);1058 1060- const actionResult = fn.apply(this, actionArgs);1061- // Remember result in case it is async. Assume parseAsync getting called on root.1062- let rootCommand = this;1063- while (rootCommand.parent) {1064- rootCommand = rootCommand.parent;1065- }1066- rootCommand._actionResults.push(actionResult);1059+ return fn.apply(this, actionArgs);1060 };1061 this._actionHandler = listener;1062 return this;1063 };291 unmodified lines1355 return this._optionValues[key];1356 };1357 1358 /**1366- * Parse `argv`, setting options and invoking commands when defined.1359+ * Get user arguments implied or explicit arguments.1360+ * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.1361 *1368- * The default expectation is that the arguments are from node and have the application as argv[0]1369- * and the script being run in argv[1], with user parameters after that.1370- *1371- * Examples:1372- *1373- * program.parse(process.argv);1374- * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions1375- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1376- *1377- * @param {string[]} [argv] - optional, defaults to process.argv1378- * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron1379- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1380- * @return {Command} `this` command for chaining1362+ * @api private1363 */1364 1383- parse(argv, parseOptions) {1365+ _prepareUserArgs(argv, parseOptions) {1366 if (argv !== undefined && !Array.isArray(argv)) {1367 throw new Error('first parameter to parse must be array or undefined');1368 }1369 parseOptions = parseOptions || {};37 unmodified lines1407 1408 // Guess name, used in usage in help.1409 this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));1410 1429- // Let's go!1411+ return userArgs;1412+ }1413+1414+ /**1415+ * Parse `argv`, setting options and invoking commands when defined.1416+ *1417+ * The default expectation is that the arguments are from node and have the application as argv[0]1418+ * and the script being run in argv[1], with user parameters after that.1419+ *1420+ * Examples:1421+ *1422+ * program.parse(process.argv);1423+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions1424+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1425+ *1426+ * @param {string[]} [argv] - optional, defaults to process.argv1427+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron1428+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1429+ * @return {Command} `this` command for chaining1430+ */1431+1432+ parse(argv, parseOptions) {1433+ const userArgs = this._prepareUserArgs(argv, parseOptions);1434 this._parseCommand([], userArgs);1435 1436 return this;1437 };7 unmodified lines1445 * and the script being run in argv[1], with user parameters after that.1446 *1447 * Examples:1448 *1445- * program.parseAsync(process.argv);1446- * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1447- * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1449+ * await program.parseAsync(process.argv);1450+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1451+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1452 *1453 * @param {string[]} [argv]1454 * @param {Object} [parseOptions]1455 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1456 * @return {Promise}1457 */1458 1455- parseAsync(argv, parseOptions) {1456- this.parse(argv, parseOptions);1457- return Promise.all(this._actionResults).then(() => this);1459+ async parseAsync(argv, parseOptions) {1460+ const userArgs = this._prepareUserArgs(argv, parseOptions);1461+ await this._parseCommand([], userArgs);1462+1463+ return this;1464 };1465 1466 /**1467 * Execute a sub-command executable.116 unmodified lines1584 1585 if (subCommand._executableHandler) {1586 this._executeSubCommand(subCommand, operands.concat(unknown));1587 } else {1582- subCommand._parseCommand(operands, unknown);1588+ return subCommand._parseCommand(operands, unknown);1589 }1590 };1591 1592 /**48 unmodified lines1641 }1642 1643 /**1644 * Process arguments in context of this command.1645+ * Returns action result, in case it is a promise.1646 *1647 * @api private1648 */1649 3 unmodified lines1653 unknown = parsed.unknown;1654 this.args = operands.concat(unknown);1655 1656 if (operands && this._findCommand(operands[0])) {1650- this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1651- } else if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1657+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1658+ }1659+ if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1660 if (operands.length === 1) {1661 this.help();1654- } else {1655- this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1662 }1663+ return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1664+ }1657- } else if (this._defaultCommandName) {1665+ if (this._defaultCommandName) {1666 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1659- this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1660- } else {1661- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1662- // probably missing subcommand and no handler, user needs help1663- this.help({ error: true });1664- }1667+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1668+ }1669+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1670+ // probably missing subcommand and no handler, user needs help (and exit)1671+ this.help({ error: true });1672+ }1673 1666- outputHelpIfRequested(this, parsed.unknown);1667- this._checkForMissingMandatoryOptions();1674+ outputHelpIfRequested(this, parsed.unknown);1675+ this._checkForMissingMandatoryOptions();1676 1669- // We do not always call this check to avoid masking a "better" error, like unknown command.1670- const checkForUnknownOptions = () => {1671- if (parsed.unknown.length > 0) {1672- this.unknownOption(parsed.unknown[0]);1677+ // We do not always call this check to avoid masking a "better" error, like unknown command.1678+ const checkForUnknownOptions = () => {1679+ if (parsed.unknown.length > 0) {1680+ this.unknownOption(parsed.unknown[0]);1681+ }1682+ };1683+ const checkNumberOfArguments = () => {1684+ // too few1685+ this._args.forEach((arg, i) => {1686+ if (arg.required && this.args[i] == null) {1687+ this.missingArgument(arg.name());1688 }1674- };1675- const checkNumberOfArguments = () => {1676- // too few1677- this._args.forEach((arg, i) => {1678- if (arg.required && this.args[i] == null) {1679- this.missingArgument(arg.name());1680- }1681- });1682- // too many1683- if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1684- return;1685- }1686- if (this.args.length > this._args.length) {1687- this._excessArguments(this.args);1688- }1689- };1689+ });1690+ // too many1691+ if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1692+ return;1693+ }1694+ if (this.args.length > this._args.length) {1695+ this._excessArguments(this.args);1696+ }1697+ };1698 1691- const commandEvent = `command:${this.name()}`;1692- if (this._actionHandler) {1693- checkForUnknownOptions();1694- checkNumberOfArguments();1695- this._actionHandler(this._getActionArguments());1696- if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1697- } else if (this.parent && this.parent.listenerCount(commandEvent)) {1698- checkForUnknownOptions();1699- checkNumberOfArguments();1700- this.parent.emit(commandEvent, operands, unknown); // legacy1701- } else if (operands.length) {1702- if (this._findCommand('*')) { // legacy default command1703- this._dispatchSubcommand('*', operands, unknown);1704- } else if (this.listenerCount('command:*')) {1705- // skip option check, emit event for possible misspelling suggestion1706- this.emit('command:*', operands, unknown);1707- } else if (this.commands.length) {1708- this.unknownCommand();1709- } else {1710- checkForUnknownOptions();1711- checkNumberOfArguments();1712- }1699+ const commandEvent = `command:${this.name()}`;1700+ if (this._actionHandler) {1701+ checkForUnknownOptions();1702+ checkNumberOfArguments();1703+ const actionResult = this._actionHandler(this._getActionArguments());1704+ if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1705+ return actionResult;1706+ }1707+ if (this.parent && this.parent.listenerCount(commandEvent)) {1708+ checkForUnknownOptions();1709+ checkNumberOfArguments();1710+ this.parent.emit(commandEvent, operands, unknown); // legacy1711+ } else if (operands.length) {1712+ if (this._findCommand('*')) { // legacy default command1713+ return this._dispatchSubcommand('*', operands, unknown);1714+ }1715+ if (this.listenerCount('command:*')) {1716+ // skip option check, emit event for possible misspelling suggestion1717+ this.emit('command:*', operands, unknown);1718 } else if (this.commands.length) {1714- // This command has subcommands and nothing hooked up at this level, so display help.1715- this.help({ error: true });1719+ this.unknownCommand();1720 } else {1721 checkForUnknownOptions();1722 checkNumberOfArguments();1719- // fall through for caller to handle after calling .parse()1723 }1724+ } else if (this.commands.length) {1725+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).1726+ this.help({ error: true });1727+ } else {1728+ checkForUnknownOptions();1729+ checkNumberOfArguments();1730+ // fall through for caller to handle after calling .parse()1731 }1732 };1733 1734 /**692 unmodified lines