Add parseAsync (#1118)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* First cut at parseAsync * Add await parseSync test * Fix typo in JSDoc * Add parseAsync to README Some noise in TOC due to changes in plugin which maintains TOC.
authored by John Gee · committed by GitHub · parent 1d9cc72 · Browse files · 5 files·+71 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+71 added−6 removed
- tests:+16 added−0 removed
- other:+55 added−6 removed
Provenance
- Commit
7bcf117- Tree
c709997- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
1d9cc72
5 files changed+71 added−6 removed
modified:tests/command.action.test.js+16 added
86 unmodified lines8788899091929394959697989910010110210310410510686 unmodified lines program.parse(['node', 'test', 'a']);
expect(actionMock).toHaveBeenCalledWith('a', program);});
test('when action is async then can await parseAsync', async() => { let asyncFinished = false; async function delay() { await new Promise(resolve => setTimeout(resolve, 100)); asyncFinished = true; }; const program = new commander.Command(); program .action(delay);
const later = program.parseAsync(['node', 'test']); expect(asyncFinished).toBe(false); await later; expect(asyncFinished).toBe(true);});modified:typings/commander-tests.ts+6 added
131 unmodified lines132 });133 134 program.parse(process.argv);135 136+program.parseAsync(process.argv).then(() => {137+ console.log('parseAsync success');138+}).catch(err => {139+ console.log('parseAsync failed');140+});141+142 console.log('stuff');modified:typings/index.d.ts+11 added-2 removed
195 unmodified lines196 */197 allowUnknownOption(arg?: boolean): Command;198 199 /**200- * Parse `argv`, settings options and invoking commands when defined.200+ * Parse `argv`, setting options and invoking commands when defined.201 *202- * @returns {Command} for chaining202+ * @returns Command for chaining203 */204 parse(argv: string[]): Command;205 206 /**207+ * Parse `argv`, setting options and invoking commands when defined.208+ * 209+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.210+ *211+ * @returns Promise212+ */213+ parseAsync(argv: string[]): Promise<any>;214+215+ /**216 * Parse options from `argv` returning `argv` void of these options.217 */218 parseOptions(argv: string[]): commander.ParseOptionsResult;219 92 unmodified linesmodified:index.js+23 added-2 removed
127 unmodified lines128 this._name = name || '';129 this._optionValues = {};130 this._storeOptionsAsProperties = true; // backwards compatible by default131 this._passCommandToAction = true; // backwards compatible by default132+ this._actionResults = [];133 134 this._helpFlags = '-h, --help';135 this._helpDescription = 'output usage information';136 this._helpShortFlag = '-h';229 unmodified lines366 if (args.length > expectedArgsCount) {367 actionArgs.push(args.slice(expectedArgsCount));368 }369 369- fn.apply(self, actionArgs);370+ const actionResult = fn.apply(self, actionArgs);371+ // Remember result in case it is async. Assume parseAsync getting called on root.372+ let rootCommand = self;373+ while (rootCommand.parent) {374+ rootCommand = rootCommand.parent;375+ }376+ rootCommand._actionResults.push(actionResult);377 };378 var parent = this.parent || this;379 var name = parent === this ? '*' : this._name;380 parent.on('command:' + name, listener);229 unmodified lines610 return this._optionValues[key];611 };612 613 /**607- * Parse `argv`, settings options and invoking commands when defined.614+ * Parse `argv`, setting options and invoking commands when defined.615 *616 * @param {Array} argv617 * @return {Command} for chaining618 * @api public76 unmodified lines695 return result;696 };697 698 /**699+ * Parse `argv`, setting options and invoking commands when defined.700+ *701+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.702+ *703+ * @param {Array} argv704+ * @return {Promise}705+ * @api public706+ */707+Command.prototype.parseAsync = function(argv) {708+ this.parse(argv);709+ return Promise.all(this._actionResults);710+};711+712+/**713 * Execute a sub-command executable.714 *715 * @param {Array} argv716 * @param {Array} args933 unmodified linesmodified:Readme.md+15 added-2 removed
9 unmodified lines10 Read this in other languages: English | [简体中文](./Readme_zh-CN.md)11 12 - [Commander.js](#commanderjs)13 - [Installation](#installation)14- - [Declaring _program_ variable](#declaring-program-variable)14+ - [Declaring program variable](#declaring-program-variable)15 - [Options](#options)16 - [Common option types, boolean and value](#common-option-types-boolean-and-value)17 - [Default option value](#default-option-value)18 - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue)13 unmodified lines32 - [Custom event listeners](#custom-event-listeners)33 - [Bits and pieces](#bits-and-pieces)34 - [Avoiding option name clashes](#avoiding-option-name-clashes)35 - [TypeScript](#typescript)36- - [Node options such as `--harmony`](#node-options-such-as---harmony)36+ - [Node options such as --harmony](#node-options-such-as---harmony)37 - [Node debugging](#node-debugging)38 - [Override exit handling](#override-exit-handling)39 - [Examples](#examples)40 - [License](#license)335 unmodified lines376 377 program.parse(process.argv)378 ```379 380+You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.381+382+```js383+async function run() { /* code goes here */ }384+385+async function main() {386+ program387+ .command('run')388+ .action(run);389+ await program.parseAsync(process.argv);390+}391+```392+393 A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.394 395 Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output.396 317 unmodified lines