Add auto-detection of args when node evaluating script code on command-line (#2164)
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 f7b8475 · Browse files · 4 files·+96 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+96 added−39 removed
- tests:+19 added−0 removed
- other:+77 added−39 removed
Provenance
- Commit
b9ca390- Tree
65245f4- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
f7b8475
4 files changed+96 added−39 removed
modified:lib/command.js+44 added-19 removed
971 unmodified lines972 throw new Error('first parameter to parse must be array or undefined');973 }974 parseOptions = parseOptions || {};975 976- // Default to using process.argv977- if (argv === undefined) {978- argv = process.argv;979- if (process.versions && process.versions.electron) {976+ // auto-detect argument conventions if nothing supplied977+ if (argv === undefined && parseOptions.from === undefined) {978+ if (process.versions?.electron) {979 parseOptions.from = 'electron';980 }981+ // check node specific options for scenarios where user CLI args follow executable without scriptname982+ const execArgv = process.execArgv ?? [];983+ if (984+ execArgv.includes('-e') ||985+ execArgv.includes('--eval') ||986+ execArgv.includes('-p') ||987+ execArgv.includes('--print')988+ ) {989+ parseOptions.from = 'eval'; // internal usage, not documented990+ }991 }992+993+ // default to using process.argv994+ if (argv === undefined) {995+ argv = process.argv;996+ }997 this.rawArgs = argv.slice();998 985- // make it a little easier for callers by supporting various argv conventions999+ // extract the user args and scriptPath1000 let userArgs;1001 switch (parseOptions.from) {1002 case undefined:1003 case 'node':11 unmodified lines1015 break;1016 case 'user':1017 userArgs = argv.slice(0);1018 break;1019+ case 'eval':1020+ userArgs = argv.slice(1);1021+ break;1022 default:1023 throw new Error(1024 `unexpected parse option { from: '${parseOptions.from}' }`,1025 );9 unmodified lines1035 1036 /**1037 * Parse `argv`, setting options and invoking commands when defined.1038 *1022- * The default expectation is that the arguments are from node and have the application as argv[0]1023- * and the script being run in argv[1], with user parameters after that.1039+ * Use parseAsync instead of parse if any of your action handlers are async.1040 *1041+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1042+ *1043+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1044+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1045+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1046+ * - `'user'`: just user arguments1047+ *1048 * @example1026- * program.parse(process.argv);1027- * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions1049+ * program.parse(); // parse process.argv and auto-detect electron and special node flags1050+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script1051 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1052 *1030- * @param {string[]} [argv] - optional, defaults to process.argv1031- * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron1032- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1053+ * @param {string[]} [argv]1054+ * @param {object} [parseOptions]1055+ * @param {string} parseOptions.from - one of 'node', 'user', 'electron'1056 * @return {Command} `this` command for chaining1057 */1058 1059 parse(argv, parseOptions) {5 unmodified lines1065 1066 /**1067 * Parse `argv`, setting options and invoking commands when defined.1068 *1046- * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.1069+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1070 *1048- * The default expectation is that the arguments are from node and have the application as argv[0]1049- * and the script being run in argv[1], with user parameters after that.1071+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1072+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1073+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1074+ * - `'user'`: just user arguments1075 *1076 * @example1052- * await program.parseAsync(process.argv);1053- * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1077+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1078+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script1079 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1080 *1081 * @param {string[]} [argv]1057- * @param {Object} [parseOptions]1058- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1082+ * @param {object} [parseOptions]1083+ * @param {string} parseOptions.from - one of 'node', 'user', 'electron'1084 * @return {Promise}1085 */1086 1087 async parseAsync(argv, parseOptions) {1417 unmodified linesmodified:tests/command.parse.test.js+19 added
2 unmodified lines34567891011121355 unmodified lines69707172737475767778798081828384858687888990919291 unmodified lines2 unmodified lines// 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
// (If mutating process.argv and process.execArgv causes problems, could add utility// functions to get them and then mock the functions for tests.)
describe('.parse() args from', () => { test('when no args then use process.argv and app/script/args', () => { const program = new commander.Command(); const hold = process.argv;55 unmodified lines expect(() => { program.parse(['node', 'script.js'], { from: 'silly' }); }).toThrow(); });
test.each(['-e', '--eval', '-p', '--print'])( 'when node execArgv includes %s then app/args', (flag) => { const program = new commander.Command(); const holdExecArgv = process.execArgv; const holdArgv = process.argv; process.argv = ['node', 'user-arg']; process.execArgv = [flag, 'console.log("hello, world")']; program.parse(); process.argv = holdArgv; process.execArgv = holdExecArgv; expect(program.args).toEqual(['user-arg']); process.execArgv = holdExecArgv; }, );});
describe('return type', () => { test('when call .parse then returns program', () => {91 unmodified linesmodified:typings/index.d.ts+23 added-12 removed
724 unmodified lines725 726 /**727 * Parse `argv`, setting options and invoking commands when defined.728 *729- * The default expectation is that the arguments are from node and have the application as argv[0]730- * and the script being run in argv[1], with user parameters after that.729+ * Use parseAsync instead of parse if any of your action handlers are async.730 *731+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!732+ *733+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:734+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that735+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged736+ * - `'user'`: just user arguments737+ *738 * @example739 * ```734- * program.parse(process.argv);735- * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions740+ * program.parse(); // parse process.argv and auto-detect electron and special node flags741+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script742 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]743 * ```744 *745 * @returns `this` command for chaining746 */741- parse(argv?: readonly string[], options?: ParseOptions): this;747+ parse(argv?: readonly string[], parseOptions?: ParseOptions): this;748 749 /**750 * Parse `argv`, setting options and invoking commands when defined.751 *746- * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.752+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!753 *748- * The default expectation is that the arguments are from node and have the application as argv[0]749- * and the script being run in argv[1], with user parameters after that.754+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:755+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that756+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged757+ * - `'user'`: just user arguments758 *759 * @example760 * ```753- * program.parseAsync(process.argv);754- * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions755- * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]761+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags762+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script763+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]764 * ```765 *766 * @returns Promise767 */760- parseAsync(argv?: readonly string[], options?: ParseOptions): Promise<this>;768+ parseAsync(769+ argv?: readonly string[],770+ parseOptions?: ParseOptions,771+ ): Promise<this>;772 773 /**774 * Parse options from `argv` removing known options,775 * and return argv split into operands and unknown arguments.201 unmodified linesmodified:Readme.md+10 added-8 removed
953 unmodified lines954 ## Bits and pieces955 956 ### .parse() and .parseAsync()957 958-The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.958+Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!959 960-If the arguments follow different conventions than node you can pass a `from` option in the second parameter:960+Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:961 962-- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that963-- 'electron': `argv[1]` varies depending on whether the electron application is packaged964-- 'user': all of the arguments from the user962+- `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that963+- `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged964+- `'user'`: just user arguments965 966 For example:967 968 ```js969-program.parse(process.argv); // Explicit, node conventions970-program.parse(); // Implicit, and auto-detect electron971-program.parse(['-f', 'filename'], { from: 'user' });969+program.parse(); // parse process.argv and auto-detect electron and special node flags970+program.parse(process.argv); // assume argv[0] is app and argv[1] is script971+program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0]972 ```973 974+Use parseAsync instead of parse if any of your action handlers are async.975+976 If you want to parse multiple times, create a new program each time. Calling parse does not clear out any previous state.977 978 ### Parsing Configuration979 178 unmodified lines