Merge `execPath` and `nodePath` options (#812)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 07a9890 · Browse files · 8 files·+132 added−109 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+132 added−109 removed
- tests:+52 added−14 removed
- other:+80 added−95 removed
Provenance
- Commit
fa04e3c- Tree
6d2ba8e- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
07a9890
8 files changed+132 added−109 removed
modified:lib/cwd.js+6 added-6 removed
12345667891011121314151617181915161718192021222326 unmodified linesimport {statSync} from 'node:fs';import {resolve} from 'node:path';import {fileURLToPath} from 'node:url';import process from 'node:process';
export const getDefaultCwd = () => {export const normalizeCwd = (cwd = getDefaultCwd()) => { const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option'); return resolve(cwdString);};
const getDefaultCwd = () => { try { return process.cwd(); } catch (error) { error.message = `The current directory does not exist.\n${error.message}`; throw error; }};
export const normalizeCwd = cwd => { const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option'); return resolve(cwdString);};
export const safeNormalizeFileUrl = (file, name) => { const fileString = normalizeFileUrl(file);
if (typeof fileString !== 'string') {26 unmodified linesmodified:lib/escape.js+9 added-18 removed
12345612345679891011111213141516171819202112const normalizeArgs = (file, args = []) => { if (!Array.isArray(args)) { return [file]; }
return [file, ...args];export const joinCommand = (filePath, rawArgs) => { const fileAndArgs = [filePath, ...rawArgs]; const command = fileAndArgs.join(' '); const escapedCommand = fileAndArgs.map(arg => escapeArg(arg)).join(' '); return {command, escapedCommand};};
const NO_ESCAPE_REGEXP = /^[\w.-]+$/;const escapeArg = arg => typeof arg === 'string' && !NO_ESCAPE_REGEXP.test(arg) ? `"${arg.replaceAll('"', '\\"')}"` : arg;
const escapeArg = arg => { if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { return arg; }
return `"${arg.replaceAll('"', '\\"')}"`;};
export const joinCommand = (file, rawArgs) => normalizeArgs(file, rawArgs).join(' ');
export const getEscapedCommand = (file, rawArgs) => normalizeArgs(file, rawArgs).map(arg => escapeArg(arg)).join(' ');const NO_ESCAPE_REGEXP = /^[\w.-]+$/;modified:lib/node.js+14 added-4 removed
122345678910111213141516171819202112222324252627282920303122323334import {execPath, execArgv} from 'node:process';import {basename} from 'node:path';import {basename, resolve} from 'node:path';import {safeNormalizeFileUrl} from './cwd.js';
export const handleNodeOption = (file, args, { node: shouldHandleNode = false, nodePath = execPath, nodeOptions = execArgv.filter(arg => !arg.startsWith('--inspect')), cwd, execPath: formerNodePath, ...options}) => { if (formerNodePath !== undefined) { throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.'); }
const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option'); const resolvedNodePath = resolve(cwd, normalizedNodePath); const newOptions = {...options, nodePath: resolvedNodePath, cwd};
if (!shouldHandleNode) { return [file, args, options]; return [file, args, newOptions]; }
if (basename(file, '.exe') === 'node') { throw new TypeError('When the "node" option is true, the first argument does not need to be "node".'); }
return [ safeNormalizeFileUrl(nodePath, 'The "nodePath" option'), resolvedNodePath, [...nodeOptions, file, ...args], {ipc: true, ...options, shell: false}, {ipc: true, ...newOptions, shell: false}, ];};modified:test/node.js+52 added-14 removed
1-import {dirname} from 'node:path';1+import {dirname, relative} from 'node:path';2 import process from 'node:process';3 import {pathToFileURL} from 'node:url';4 import test from 'ava';5 import getNode from 'get-node';4 unmodified lines10 import {foobarString} from './helpers/input.js';11 12 process.chdir(FIXTURES_DIR);13 14-const runWithNodeOption = (file, args = [], options = {}) => execa(file, args, {...options, node: true});15-const runWithNodeOptionSync = (file, args = [], options = {}) => execaSync(file, args, {...options, node: true});14+const runWithNodeOption = (file, args, options) => Array.isArray(args)15+ ? execa(file, args, {...options, node: true})16+ : execa(file, {...options, node: true});17+const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)18+ ? execaSync(file, args, {...options, node: true})19+ : execaSync(file, {...options, node: true});20 const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});21 22 const testNodeSuccess = async (t, execaMethod) => {23 const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);10 unmodified lines34 execaNode('empty.js', {node: false});35 }, {message: /The "node" option cannot be false/});36 });37 34-const testDoubleNode = (t, execPath, execaMethod) => {38+const testDoubleNode = (t, nodePath, execaMethod) => {39 t.throws(() => {36- execaMethod(execPath, ['noop.js']);40+ execaMethod(nodePath, ['noop.js']);41 }, {message: /does not need to be "node"/});42 };43 44 test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);19 unmodified lines64 test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);65 test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);66 test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);67 test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);68+test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);69+test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);70 71 const testNodePathDefault = async (t, execaMethod) => {72 const {stdout} = await execaMethod('--version');73 t.is(stdout, process.version);74 };75 76 test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);77 test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);78+test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);79 80 const testNodePathInvalid = (t, execaMethod) => {81 t.throws(() => {82 execaMethod('noop.js', [], {nodePath: true});3 unmodified lines86 test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);87 test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);88 test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);89 90+const testFormerNodePath = (t, execaMethod) => {91+ t.throws(() => {92+ execaMethod('noop.js', [], {execPath: process.execPath});93+ }, {message: /The "execPath" option has been removed/});94+};95+96+test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);97+test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);98+test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);99+100 const nodePathArguments = ['node', ['-p', 'process.env.Path || process.env.PATH']];101 85-const testExecPath = async (t, mapPath) => {86- const execPath = mapPath(await getNodePath());87- const {stdout} = await execa(...nodePathArguments, {preferLocal: true, execPath});102+const testChildNodePath = async (t, mapPath) => {103+ const nodePath = mapPath(await getNodePath());104+ const {stdout} = await execa(...nodePathArguments, {preferLocal: true, nodePath});105 t.true(stdout.includes(TEST_NODE_VERSION));106 };107 91-test.serial('The "execPath" option can be used', testExecPath, identity);92-test.serial('The "execPath" option can be a file URL', testExecPath, pathToFileURL);108+test.serial('The "nodePath" option impacts the child process', testChildNodePath, identity);109+test.serial('The "nodePath" option can be a file URL', testChildNodePath, pathToFileURL);110 94-test('The "execPath" option defaults to the current Node.js binary', async t => {111+test('The "nodePath" option defaults to the current Node.js binary in the child process', async t => {112 const {stdout} = await execa(...nodePathArguments, {preferLocal: true});113 t.true(stdout.includes(dirname(process.execPath)));114 });115 99-test.serial('The "execPath" option requires "preferLocal: true"', async t => {100- const execPath = await getNodePath();101- const {stdout} = await execa(...nodePathArguments, {execPath});116+test.serial('The "nodePath" option requires "preferLocal: true" to impact the child process', async t => {117+ const nodePath = await getNodePath();118+ const {stdout} = await execa(...nodePathArguments, {nodePath});119 t.false(stdout.includes(TEST_NODE_VERSION));120 });121 122+test.serial('The "nodePath" option is relative to "cwd" when used in the child process', async t => {123+ const nodePath = await getNodePath();124+ const cwd = dirname(dirname(nodePath));125+ const relativeExecPath = relative(cwd, nodePath);126+ const {stdout} = await execa(...nodePathArguments, {preferLocal: true, nodePath: relativeExecPath, cwd});127+ t.true(stdout.includes(TEST_NODE_VERSION));128+});129+130+const testCwdNodePath = async (t, execaMethod) => {131+ const nodePath = await getNodePath();132+ const cwd = dirname(dirname(nodePath));133+ const relativeExecPath = relative(cwd, nodePath);134+ const {stdout} = await execaMethod('--version', [], {nodePath: relativeExecPath, cwd});135+ t.is(stdout, `v${TEST_NODE_VERSION}`);136+};137+138+test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);139+test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);140+test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);141+142 const testNodeOptions = async (t, execaMethod) => {143 const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});144 t.is(stdout, process.version);145 };146 147 test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);148 test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);149+test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);150 151 const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(152 'node',153 [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],96 unmodified linesmodified:index.d.ts+5 added-14 removed
283 unmodified lines284 */285 readonly node?: boolean;286 287 /**288- Node.js executable used to create the child process.288+ Path to the Node.js executable.289 290- Requires the `node` option to be `true`.290+ When the `node` option is `true`, this is used to to create the child process. When the `preferLocal` option is `true`, this is used in the child process itself.291 292+ For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.293+294 @default [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)295 */296 readonly nodePath?: string | URL;297 6 unmodified lines304 */305 readonly nodeOptions?: string[];306 307 /**306- Path to the Node.js executable to use in child processes.307-308- Requires the `preferLocal` option to be `true`.309-310- For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.311-312- @default [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)313- */314- readonly execPath?: string | URL;315-316- /**308 Write some input to the child process' `stdin`.309 310 See also the `inputFile` and `stdin` options.311 */113 unmodified lines425 426 /**427 Current working directory of the child process.428 438- This is also used to resolve the `execPath` option when it is a relative path.429+ This is also used to resolve the `nodePath` option when it is a relative path.430 431 @default process.cwd()432 */433 readonly cwd?: string | URL;871 unmodified linesmodified:index.js+42 added-36 removed
12 unmodified lines13 import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14 import {pipeToProcess} from './lib/pipe.js';15 import {getSpawnedResult, makeAllStream} from './lib/stream.js';16 import {mergePromise} from './lib/promise.js';17-import {joinCommand, getEscapedCommand} from './lib/escape.js';17+import {joinCommand} from './lib/escape.js';18 import {parseCommand} from './lib/command.js';19-import {getDefaultCwd, normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './lib/cwd.js';19+import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './lib/cwd.js';20 import {parseTemplates} from './lib/script.js';21 import {logCommand, verboseDefault} from './lib/verbose.js';22 import {bufferToUint8Array} from './lib/stdio/utils.js';23 24 const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;25 26-const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {26+const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, nodePath}) => {27 const env = extendEnv ? {...process.env, ...envOption} : envOption;28 29 if (preferLocal) {30- return npmRunPathEnv({env, cwd: localDir, execPath});30+ return npmRunPathEnv({env, cwd: localDir, execPath: nodePath});31 }32 33 return env;34 };35 36-const getFilePath = rawFile => safeNormalizeFileUrl(rawFile, 'First argument');36+const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {37+ [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);38+ const {file, args, command, escapedCommand, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);39+ const options = handleAsyncOptions(normalizedOptions);40+ return {file, args, command, escapedCommand, options};41+};42 38-const handleArguments = (rawFile, rawArgs, rawOptions = {}) => {39- const filePath = getFilePath(rawFile);40- const command = joinCommand(filePath, rawArgs);41- const escapedCommand = getEscapedCommand(filePath, rawArgs);43+// Prevent passing the `timeout` option directly to `child_process.spawn()`44+const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});45 46+const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {47+ [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);48+ const syncOptions = normalizeSyncOptions(rawOptions);49+ const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, syncOptions);50+ validateSyncOptions(options);51+ return {file, args, command, escapedCommand, options};52+};53+54+const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;55+56+const validateSyncOptions = ({ipc}) => {57+ if (ipc) {58+ throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');59+ }60+};61+62+const handleOptionalArguments = (args = [], options = {}) => Array.isArray(args)63+ ? [args, options]64+ : [[], args];65+66+const handleArguments = (rawFile, rawArgs, rawOptions) => {67+ const filePath = safeNormalizeFileUrl(rawFile, 'First argument');68+ const {command, escapedCommand} = joinCommand(filePath, rawArgs);69+70+ rawOptions.cwd = normalizeCwd(rawOptions.cwd);71 const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);72 73 const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);74 1 unmodified line76 validateTimeout(options);77 options.shell = normalizeFileUrl(options.shell);78 options.env = getEnv(options);79 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);52- options.cwd = normalizeCwd(options.cwd);80 81 if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') {82 // #11683 args.unshift('/q');9 unmodified lines93 buffer = true,94 stripFinalNewline = true,95 extendEnv = true,96 preferLocal = false,70- cwd = getDefaultCwd(),97+ cwd,98 localDir = cwd,72- execPath = process.execPath,99 encoding = 'utf8',100 reject = true,101 cleanup = true,102 all = false,12 unmodified lines115 extendEnv,116 preferLocal,117 cwd,118 localDir,93- execPath,119 encoding,120 reject,121 cleanup,122 all,4 unmodified lines127 lines,128 ipc,129 });130 106-// Prevent passing the `timeout` option directly to `child_process.spawn()`107-const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});108-131 const handleOutput = (options, value) => {132 if (value === undefined || value === null) {133 return;134 }9 unmodified lines144 return options.stripFinalNewline ? stripFinalNewline(value) : value;145 };146 147 export function execa(rawFile, rawArgs, rawOptions) {126- const {file, args, command, escapedCommand, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);127- const options = handleAsyncOptions(normalizedOptions);128-148+ const {file, args, command, escapedCommand, options} = handleAsyncArguments(rawFile, rawArgs, rawOptions);149 const stdioStreamsGroups = handleInputAsync(options);150 151 let spawned;152 try {84 unmodified lines237 };238 };239 240 export function execaSync(rawFile, rawArgs, rawOptions) {221- const syncOptions = normalizeSyncOptions(rawOptions);222- const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, syncOptions);223- validateSyncOptions(options);224-241+ const {file, args, command, escapedCommand, options} = handleSyncArguments(rawFile, rawArgs, rawOptions);242 const stdioStreamsGroups = handleInputSync(options);243 244 let result;245 try {55 unmodified lines301 stdio,302 };303 }304 288-const normalizeSyncOptions = (options = {}) => options.node && !options.ipc ? {...options, ipc: false} : options;289-290-const validateSyncOptions = ({ipc}) => {291- if (ipc) {292- throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');293- }294-};295-305 const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined306 ? {stdin: 'inherit'}307 : {};308 38 unmodified lines347 const [file, ...args] = parseCommand(command);348 return execaSync(file, args, options);349 }350 342-export function execaNode(file, args = [], options = {}) {343- if (!Array.isArray(args)) {344- options = args;345- args = [];346- }351+export function execaNode(file, args, options) {352+ [args, options] = handleOptionalArguments(args, options);353 354 if (options.node === false) {355 throw new TypeError('The "node" option cannot be false with `execaNode()`.');356 }3 unmodified linesmodified:index.test-d.ts-4 removed
720 unmodified lines721 execa('unicorns', {localDir: fileUrl});722 execaSync('unicorns', {localDir: fileUrl});723 expectError(execa('unicorns', {encoding: 'unknownEncoding'}));724 expectError(execaSync('unicorns', {encoding: 'unknownEncoding'}));725-execa('unicorns', {execPath: '/path'});726-execaSync('unicorns', {execPath: '/path'});727-execa('unicorns', {execPath: fileUrl});728-execaSync('unicorns', {execPath: fileUrl});725 execa('unicorns', {buffer: false});726 expectError(execaSync('unicorns', {buffer: false}));727 execa('unicorns', {lines: false});728 expectError(execaSync('unicorns', {lines: false}));664 unmodified linesmodified:readme.md+4 added-13 removed
514 unmodified lines515 Default: `process.cwd()`516 517 Current working directory of the child process.518 519-This is also used to resolve the [`execPath`](#execpath) option when it is a relative path.519+This is also used to resolve the [`nodePath`](#nodepath) option when it is a relative path.520 521 #### env522 523 Type: `object`\46 unmodified lines570 571 Type: `string | URL`\572 Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)573 574-Node.js executable used to create the child process.574+Path to the Node.js executable.575 576-Requires the [`node`](#node) option to be `true`.576+When the [`node`](#node) option is `true`, this is used to to create the child process. When the [`preferLocal`](#preferlocal) option is `true`, this is used in the child process itself.577 578-#### execPath578+For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.579 580-Type: `string | URL`\581-Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)582-583-Path to the Node.js executable to use in child processes.584-585-Requires the [`preferLocal`](#preferlocal) option to be `true`.586-587-For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.588-580 #### verbose581 582 Type: `boolean`\583 Default: `false`374 unmodified lines