Parse argument conventions (#1172)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add "from" parameter to .parse() * Add docs for ParseOptions * Add .parse options to README * Lint, whitespace * Fill in parseAsync docs
authored by John Gee · committed by GitHub · parent fbdd132 · Browse files · 5 files·+177 added−18 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+177 added−18 removed
- tests:+54 added−0 removed
- other:+123 added−18 removed
Provenance
- Commit
30ae4ac- Tree
cfcb71a- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
fbdd132
5 files changed+177 added−18 removed
added:tests/command.parse.test.js+54 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354const commander = require('../');
// Testing some Electron conventions but not directly using Electron to avoid overheads.// https://github.com/electron/electron/issues/4690#issuecomment-217435222// https://www.electronjs.org/docs/api/process#processdefaultapp-readonly
describe('.parse() user args', () => { test('when no args then use process.argv and app/script/args', () => { const program = new commander.Command(); const hold = process.argv; process.argv = 'node script.js user'.split(' '); program.parse(); process.argv = hold; expect(program.args).toEqual(['user']); });
// implicit also supports detecting electron but more implementation knowledge required than useful to test
test('when args then app/script/args', () => { const program = new commander.Command(); program.parse('node script.js user'.split(' ')); expect(program.args).toEqual(['user']); });
test('when args from "node" then app/script/args', () => { const program = new commander.Command(); program.parse('node script.js user'.split(' '), { from: 'node' }); expect(program.args).toEqual(['user']); });
test('when args from "electron" and not default app then app/args', () => { const program = new commander.Command(); const hold = process.defaultApp; process.defaultApp = undefined; program.parse('customApp user'.split(' '), { from: 'electron' }); process.defaultApp = hold; expect(program.args).toEqual(['user']); });
test('when args from "electron" and default app then app/script/args', () => { const program = new commander.Command(); const hold = process.defaultApp; process.defaultApp = true; program.parse('electron script user'.split(' '), { from: 'electron' }); process.defaultApp = hold; expect(program.args).toEqual(['user']); });
test('when args from "user" then args', () => { const program = new commander.Command(); program.parse('user'.split(' '), { from: 'user' }); expect(program.args).toEqual(['user']); });});modified:typings/commander-tests.ts+2 added
143 unmodified linesExpand all1441451461471481491501511521538 unmodified lines143 unmodified linesExpand all }});
program.parse(process.argv);program.parse();program.parse(["foo"], { from: "user" });
program.parseAsync(process.argv).then(() => { console.log('parseAsync success');}).catch(err => {8 unmodified linesmodified:typings/index.d.ts+30 added-8 removed
21 unmodified lines22 description: string;23 }24 type OptionConstructor = { new (flags: string, description?: string): Option };25 26+ interface ParseOptions {27+ from: "node" | "electron" | "user";28+ }29+30 interface Command {31 [key: string]: any; // options as properties32 33 args: string[];165 unmodified lines199 allowUnknownOption(arg?: boolean): Command;200 201 /**202 * Parse `argv`, setting options and invoking commands when defined.203+ * 204+ * The default expectation is that the arguments are from node and have the application as argv[0]205+ * and the script being run in argv[1], with user parameters after that.206 *207+ * Examples:208+ *209+ * program.parse(process.argv);210+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions211+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]212+ * 213 * @returns Command for chaining214 */202- parse(argv: string[]): Command;215+ parse(argv?: string[], options?: ParseOptions): Command;216 217 /**205- * Parse `argv`, setting options and invoking commands when defined.206- * 207- * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.208- *209- * @returns Promise210- */211- parseAsync(argv: string[]): Promise<any>;218+ * Parse `argv`, setting options and invoking commands when defined.219+ * 220+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.221+ * 222+ * The default expectation is that the arguments are from node and have the application as argv[0]223+ * and the script being run in argv[1], with user parameters after that.224+ *225+ * Examples:226+ *227+ * program.parseAsync(process.argv);228+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions229+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]230+ *231+ * @returns Promise232+ */233+ parseAsync(argv?: string[], options?: ParseOptions): Promise<any>;234 235 /**236 * Parse options from `argv` removing known options,237 * and return argv split into operands and unknown arguments.118 unmodified linesmodified:index.js+72 added-10 removed
98 unmodified lines99 this.commands = [];100 this.options = [];101 this._allowUnknownOption = false;102 this._args = [];103+ this.rawArgs = null;104+ this._scriptPath = null;105 this._name = name || '';106 this._optionValues = {};107 this._storeOptionsAsProperties = true; // backwards compatible by default108 this._passCommandToAction = true; // backwards compatible by default513 unmodified lines622 623 /**624 * Parse `argv`, setting options and invoking commands when defined.625 *624- * @param {Array} argv626+ * The default expectation is that the arguments are from node and have the application as argv[0]627+ * and the script being run in argv[1], with user parameters after that.628+ *629+ * Examples:630+ *631+ * program.parse(process.argv);632+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions633+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]634+ *635+ * @param {string[]} [argv] - optional, defaults to process.argv636+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron637+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'638 * @return {Command} for chaining639 * @api public640 */641 629- parse(argv) {630- // store raw args631- this.rawArgs = argv;642+ parse(argv, parseOptions) {643+ if (argv !== undefined && !Array.isArray(argv)) {644+ throw new Error('first parameter to parse must be array or undefined');645+ }646+ parseOptions = parseOptions || {};647 648+ // Default to using process.argv649+ if (argv === undefined) {650+ argv = process.argv;651+ if (process.versions && process.versions.electron) {652+ parseOptions.from = 'electron';653+ }654+ }655+ this.rawArgs = argv.slice();656+657+ // make it a little easier for callers by supporting various argv conventions658+ let userArgs;659+ switch (parseOptions.from) {660+ case undefined:661+ case 'node':662+ this._scriptPath = argv[1];663+ userArgs = argv.slice(2);664+ break;665+ case 'electron':666+ if (process.defaultApp) {667+ this._scriptPath = argv[1];668+ userArgs = argv.slice(2);669+ } else {670+ userArgs = argv.slice(1);671+ }672+ break;673+ case 'user':674+ userArgs = argv.slice(0);675+ break;676+ default:677+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);678+ }679+ if (!this._scriptPath && process.mainModule) {680+ this._scriptPath = process.mainModule.filename;681+ }682+683 // Guess name, used in usage in help.634- this._name = this._name || path.basename(argv[1], path.extname(argv[1]));684+ this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));685 686+ // Let's go!636- this._parseCommand([], argv.slice(2));687+ this._parseCommand([], userArgs);688 689 return this;690 };691 1 unmodified line693 * Parse `argv`, setting options and invoking commands when defined.694 *695 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.696 *646- * @param {Array} argv697+ * The default expectation is that the arguments are from node and have the application as argv[0]698+ * and the script being run in argv[1], with user parameters after that.699+ *700+ * Examples:701+ *702+ * program.parseAsync(process.argv);703+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions704+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]705+ *706+ * @param {string[]} [argv]707+ * @param {Object} [parseOptions]708+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'709 * @return {Promise}710 * @api public711 */712 651- parseAsync(argv) {652- this.parse(argv);713+ parseAsync(argv, parseOptions) {714+ this.parse(argv, parseOptions);715 return Promise.all(this._actionResults);716 };717 718 /**10 unmodified lines729 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.730 this._checkForMissingMandatoryOptions();731 732 // Want the entry script as the reference for command name and directory for searching for other files.671- const scriptPath = this.rawArgs[1];733+ const scriptPath = this._scriptPath;734 735 let baseDir;736 try {737 const resolvedLink = fs.realpathSync(scriptPath);942 unmodified linesmodified:Readme.md+19 added
31 unmodified lines32 - [.helpOption(flags, description)](#helpoptionflags-description)33 - [.addHelpCommand()](#addhelpcommand)34 - [Custom event listeners](#custom-event-listeners)35 - [Bits and pieces](#bits-and-pieces)36+ - [.parse() and .parseAsync()](#parse-and-parseasync)37 - [Avoiding option name clashes](#avoiding-option-name-clashes)38 - [TypeScript](#typescript)39 - [Node options such as `--harmony`](#node-options-such-as---harmony)40 - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)522 unmodified lines563 ```564 565 ## Bits and pieces566 567+### .parse() and .parseAsync()568+569+The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.570+571+If the arguments follow different conventions than node you can pass a `from` option in the second parameter:572+573+- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that574+- 'electron': `argv[1]` varies depending on whether the electron application is packaged575+- 'user': all of the arguments from the user576+577+For example:578+579+```js580+program.parse(process.argv); // Explicit, node conventions581+program.parse(); // Implicit, and auto-detect electron582+program.parse(['-f', 'filename'], { from: 'user' });583+```584+585 ### Avoiding option name clashes586 587 The original and default behaviour is that the option values are stored588 as properties on the program, and the action handler is passed a135 unmodified lines