Skip to content
Myr

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

8 files+132 added−109 removed

modified:lib/cwd.js+6 added-6 removed
modified:lib/escape.js+9 added-18 removed
modified:lib/node.js+14 added-4 removed
modified:test/node.js+52 added-14 removed
1import {dirname} from 'node:path';1import {dirname, relative} from 'node:path';2import process from 'node:process';3import {pathToFileURL} from 'node:url';4import test from 'ava';5import getNode from 'get-node';
4 unmodified lines
10import {foobarString} from './helpers/input.js';1112process.chdir(FIXTURES_DIR);1314const runWithNodeOption = (file, args = [], options = {}) => execa(file, args, {...options, node: true});15const runWithNodeOptionSync = (file, args = [], options = {}) => execaSync(file, args, {...options, node: true});14const runWithNodeOption = (file, args, options) => Array.isArray(args)15 ? execa(file, args, {...options, node: true})16 : execa(file, {...options, node: true});17const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)18 ? execaSync(file, args, {...options, node: true})19 : execaSync(file, {...options, node: true});20const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});2122const testNodeSuccess = async (t, execaMethod) => {23 const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);
10 unmodified lines
34 execaNode('empty.js', {node: false});35 }, {message: /The "node" option cannot be false/});36});3734const testDoubleNode = (t, execPath, execaMethod) => {38const 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};4344test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);
19 unmodified lines
64test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);65test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);66test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);67test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);68test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);69test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);7071const testNodePathDefault = async (t, execaMethod) => {72 const {stdout} = await execaMethod('--version');73 t.is(stdout, process.version);74};7576test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);77test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);78test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);7980const testNodePathInvalid = (t, execaMethod) => {81 t.throws(() => {82 execaMethod('noop.js', [], {nodePath: true});
3 unmodified lines
86test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);87test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);88test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);8990const testFormerNodePath = (t, execaMethod) => {91 t.throws(() => {92 execaMethod('noop.js', [], {execPath: process.execPath});93 }, {message: /The "execPath" option has been removed/});94};9596test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);97test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);98test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);99100const nodePathArguments = ['node', ['-p', 'process.env.Path || process.env.PATH']];10185const testExecPath = async (t, mapPath) => {86 const execPath = mapPath(await getNodePath());87 const {stdout} = await execa(...nodePathArguments, {preferLocal: true, execPath});102const 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};10791test.serial('The "execPath" option can be used', testExecPath, identity);92test.serial('The "execPath" option can be a file URL', testExecPath, pathToFileURL);108test.serial('The "nodePath" option impacts the child process', testChildNodePath, identity);109test.serial('The "nodePath" option can be a file URL', testChildNodePath, pathToFileURL);11094test('The "execPath" option defaults to the current Node.js binary', async t => {111test('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});11599test.serial('The "execPath" option requires "preferLocal: true"', async t => {100 const execPath = await getNodePath();101 const {stdout} = await execa(...nodePathArguments, {execPath});116test.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});121122test.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});129130const 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};137138test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);139test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);140test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);141142const testNodeOptions = async (t, execaMethod) => {143 const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});144 t.is(stdout, process.version);145};146147test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);148test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);149test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);150151const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(152 'node',153 [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],
96 unmodified lines
modified:index.d.ts+5 added-14 removed
283 unmodified lines
284 */285 readonly node?: boolean;286287 /**288 Node.js executable used to create the child process.288 Path to the Node.js executable.289290 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.291292 For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.293294 @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 lines
304 */305 readonly nodeOptions?: string[];306307 /**306 Path to the Node.js executable to use in child processes.307308 Requires the `preferLocal` option to be `true`.309310 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.311312 @default [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)313 */314 readonly execPath?: string | URL;315316 /**308 Write some input to the child process' `stdin`.309310 See also the `inputFile` and `stdin` options.311 */
113 unmodified lines
425426 /**427 Current working directory of the child process.428438 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.430431 @default process.cwd()432 */433 readonly cwd?: string | URL;
871 unmodified lines
modified:index.js+42 added-36 removed
12 unmodified lines
13import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14import {pipeToProcess} from './lib/pipe.js';15import {getSpawnedResult, makeAllStream} from './lib/stream.js';16import {mergePromise} from './lib/promise.js';17import {joinCommand, getEscapedCommand} from './lib/escape.js';17import {joinCommand} from './lib/escape.js';18import {parseCommand} from './lib/command.js';19import {getDefaultCwd, normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './lib/cwd.js';19import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './lib/cwd.js';20import {parseTemplates} from './lib/script.js';21import {logCommand, verboseDefault} from './lib/verbose.js';22import {bufferToUint8Array} from './lib/stdio/utils.js';2324const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;2526const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {26const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, nodePath}) => {27 const env = extendEnv ? {...process.env, ...envOption} : envOption;2829 if (preferLocal) {30 return npmRunPathEnv({env, cwd: localDir, execPath});30 return npmRunPathEnv({env, cwd: localDir, execPath: nodePath});31 }3233 return env;34};3536const getFilePath = rawFile => safeNormalizeFileUrl(rawFile, 'First argument');36const 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};4238const 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()`44const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});4546const 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};5354const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;5556const validateSyncOptions = ({ipc}) => {57 if (ipc) {58 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');59 }60};6162const handleOptionalArguments = (args = [], options = {}) => Array.isArray(args)63 ? [args, options]64 : [[], args];6566const handleArguments = (rawFile, rawArgs, rawOptions) => {67 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');68 const {command, escapedCommand} = joinCommand(filePath, rawArgs);6970 rawOptions.cwd = normalizeCwd(rawOptions.cwd);71 const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);7273 const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);74
1 unmodified line
76 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);8081 if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') {82 // #11683 args.unshift('/q');
9 unmodified lines
93 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 lines
115 extendEnv,116 preferLocal,117 cwd,118 localDir,93 execPath,119 encoding,120 reject,121 cleanup,122 all,
4 unmodified lines
127 lines,128 ipc,129});130106// Prevent passing the `timeout` option directly to `child_process.spawn()`107const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});108131const handleOutput = (options, value) => {132 if (value === undefined || value === null) {133 return;134 }
9 unmodified lines
144 return options.stripFinalNewline ? stripFinalNewline(value) : value;145};146147export function execa(rawFile, rawArgs, rawOptions) {126 const {file, args, command, escapedCommand, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);127 const options = handleAsyncOptions(normalizedOptions);128148 const {file, args, command, escapedCommand, options} = handleAsyncArguments(rawFile, rawArgs, rawOptions);149 const stdioStreamsGroups = handleInputAsync(options);150151 let spawned;152 try {
84 unmodified lines
237 };238};239240export function execaSync(rawFile, rawArgs, rawOptions) {221 const syncOptions = normalizeSyncOptions(rawOptions);222 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, syncOptions);223 validateSyncOptions(options);224241 const {file, args, command, escapedCommand, options} = handleSyncArguments(rawFile, rawArgs, rawOptions);242 const stdioStreamsGroups = handleInputSync(options);243244 let result;245 try {
55 unmodified lines
301 stdio,302 };303}304288const normalizeSyncOptions = (options = {}) => options.node && !options.ipc ? {...options, ipc: false} : options;289290const validateSyncOptions = ({ipc}) => {291 if (ipc) {292 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');293 }294};295305const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined306 ? {stdin: 'inherit'}307 : {};308
38 unmodified lines
347 const [file, ...args] = parseCommand(command);348 return execaSync(file, args, options);349}350342export function execaNode(file, args = [], options = {}) {343 if (!Array.isArray(args)) {344 options = args;345 args = [];346 }351export function execaNode(file, args, options) {352 [args, options] = handleOptionalArguments(args, options);353354 if (options.node === false) {355 throw new TypeError('The "node" option cannot be false with `execaNode()`.');356 }
3 unmodified lines
modified:index.test-d.ts-4 removed
720 unmodified lines
721execa('unicorns', {localDir: fileUrl});722execaSync('unicorns', {localDir: fileUrl});723expectError(execa('unicorns', {encoding: 'unknownEncoding'}));724expectError(execaSync('unicorns', {encoding: 'unknownEncoding'}));725execa('unicorns', {execPath: '/path'});726execaSync('unicorns', {execPath: '/path'});727execa('unicorns', {execPath: fileUrl});728execaSync('unicorns', {execPath: fileUrl});725execa('unicorns', {buffer: false});726expectError(execaSync('unicorns', {buffer: false}));727execa('unicorns', {lines: false});728expectError(execaSync('unicorns', {lines: false}));
664 unmodified lines
modified:readme.md+4 added-13 removed
514 unmodified lines
515Default: `process.cwd()`516517Current working directory of the child process.518519This is also used to resolve the [`execPath`](#execpath) option when it is a relative path.519This is also used to resolve the [`nodePath`](#nodepath) option when it is a relative path.520521#### env522523Type: `object`\
46 unmodified lines
570571Type: `string | URL`\572Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)573574Node.js executable used to create the child process.574Path to the Node.js executable.575576Requires the [`node`](#node) option to be `true`.576When 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.577578#### execPath578For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.579580Type: `string | URL`\581Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)582583Path to the Node.js executable to use in child processes.584585Requires the [`preferLocal`](#preferlocal) option to be `true`.586587For 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.588580#### verbose581582Type: `boolean`\583Default: `false`
374 unmodified lines