Skip to content
Myr

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

5 files+177 added−18 removed

added:tests/command.parse.test.js+54 added
modified:typings/commander-tests.ts+2 added
modified:typings/index.d.ts+30 added-8 removed
21 unmodified lines
22 description: string;23 }24 type OptionConstructor = { new (flags: string, description?: string): Option };2526 interface ParseOptions {27 from: "node" | "electron" | "user";28 }2930 interface Command {31 [key: string]: any; // options as properties3233 args: string[];
165 unmodified lines
199 allowUnknownOption(arg?: boolean): Command;200201 /**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;216217 /**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>;234235 /**236 * Parse options from `argv` removing known options,237 * and return argv split into operands and unknown arguments.
118 unmodified lines
modified:index.js+72 added-10 removed
98 unmodified lines
99 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 default
513 unmodified lines
622623 /**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 */641629 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 || {};647648 // 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();656657 // 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 }682683 // 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)));685686 // Let's go!636 this._parseCommand([], argv.slice(2));687 this._parseCommand([], userArgs);688689 return this;690 };691
1 unmodified line
693 * 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 */712651 parseAsync(argv) {652 this.parse(argv);713 parseAsync(argv, parseOptions) {714 this.parse(argv, parseOptions);715 return Promise.all(this._actionResults);716 };717718 /**
10 unmodified lines
729 // 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();731732 // 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;734735 let baseDir;736 try {737 const resolvedLink = fs.realpathSync(scriptPath);
942 unmodified lines
modified:Readme.md+19 added
31 unmodified lines
32 - [.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 lines
563```564565## Bits and pieces566567### .parse() and .parseAsync()568569The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.570571If the arguments follow different conventions than node you can pass a `from` option in the second parameter:572573- '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 user576577For example:578579```js580program.parse(process.argv); // Explicit, node conventions581program.parse(); // Implicit, and auto-detect electron582program.parse(['-f', 'filename'], { from: 'user' });583```584585### Avoiding option name clashes586587The original and default behaviour is that the option values are stored588as properties on the program, and the action handler is passed a
135 unmodified lines