Skip to content
Myr

Improve `cwd` option (#803)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent 72836f3 · Browse files · 10 files+199 added−75 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+199 added−75 removed

  • tests:+132 added−51 removed
  • other:+67 added−24 removed

10 files+199 added−75 removed

added:lib/cwd.js+49 added
modified:lib/error.js+4 added-3 removed
modified:test/helpers/fixtures-dir.js+3 added-3 removed
added:test/cwd.js+103 added
1import {mkdir, rmdir} from 'node:fs/promises';2import {relative, toNamespacedPath} from 'node:path';3import process from 'node:process';4import {pathToFileURL, fileURLToPath} from 'node:url';5import tempfile from 'tempfile';6import test from 'ava';7import {execa, execaSync} from '../index.js';8import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';910setFixtureDir();1112const isWindows = process.platform === 'win32';1314const testOptionCwdString = async (t, execaMethod) => {15 const cwd = '/';16 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd});17 t.is(toNamespacedPath(stdout), toNamespacedPath(cwd));18};1920test('The "cwd" option can be a string', testOptionCwdString, execa);21test('The "cwd" option can be a string - sync', testOptionCwdString, execaSync);2223const testOptionCwdUrl = async (t, execaMethod) => {24 const cwd = '/';25 const cwdUrl = pathToFileURL(cwd);26 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd: cwdUrl});27 t.is(toNamespacedPath(stdout), toNamespacedPath(cwd));28};2930test('The "cwd" option can be a URL', testOptionCwdUrl, execa);31test('The "cwd" option can be a URL - sync', testOptionCwdUrl, execaSync);3233const testOptionCwdInvalid = (t, execaMethod) => {34 t.throws(() => {35 execaMethod('empty.js', {cwd: true});36 }, {message: /The "cwd" option must be a string or a file URL: true/});37};3839test('The "cwd" option cannot be an invalid type', testOptionCwdInvalid, execa);40test('The "cwd" option cannot be an invalid type - sync', testOptionCwdInvalid, execaSync);4142const testErrorCwdDefault = async (t, execaMethod) => {43 const {cwd} = await execaMethod('empty.js');44 t.is(cwd, process.cwd());45};4647test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);48test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);4950// Windows does not allow removing a directory used as `cwd` of a running process51if (!isWindows) {52 const testCwdPreSpawn = async (t, execaMethod) => {53 const currentCwd = process.cwd();54 const filePath = tempfile();55 await mkdir(filePath);56 process.chdir(filePath);57 await rmdir(filePath);5859 try {60 t.throws(() => {61 execaMethod('empty.js');62 }, {message: /The current directory does not exist/});63 } finally {64 process.chdir(currentCwd);65 }66 };6768 test.serial('The "cwd" option default fails if current cwd is missing', testCwdPreSpawn, execa);69 test.serial('The "cwd" option default fails if current cwd is missing - sync', testCwdPreSpawn, execaSync);70}7172const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};73const cwdTooLong = {cwd: '.'.repeat(1e5), expectedCode: 'ENAMETOOLONG', expectedMessage: 'The "cwd" option is invalid'};74const cwdNotDir = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};7576const testCwdPostSpawn = async (t, {cwd, expectedCode, expectedMessage}, execaMethod) => {77 const {failed, code, message} = await execaMethod('empty.js', {cwd, reject: false});78 t.true(failed);79 t.is(code, expectedCode);80 t.true(message.includes(expectedMessage));81 t.true(message.includes(cwd));82};8384test('The "cwd" option must be an existing file', testCwdPostSpawn, cwdNotExisting, execa);85test('The "cwd" option must be an existing file - sync', testCwdPostSpawn, cwdNotExisting, execaSync);86test('The "cwd" option must not be too long', testCwdPostSpawn, cwdTooLong, execa);87test('The "cwd" option must not be too long - sync', testCwdPostSpawn, cwdTooLong, execaSync);88test('The "cwd" option must be a directory', testCwdPostSpawn, cwdNotDir, execa);89test('The "cwd" option must be a directory - sync', testCwdPostSpawn, cwdNotDir, execaSync);9091const successProperties = {fixtureName: 'empty.js', expectedFailed: false};92const errorProperties = {fixtureName: 'fail.js', expectedFailed: true};9394const testErrorCwd = async (t, execaMethod, {fixtureName, expectedFailed}) => {95 const {failed, cwd} = await execaMethod(fixtureName, {cwd: relative('.', FIXTURES_DIR), reject: false});96 t.is(failed, expectedFailed);97 t.is(cwd, FIXTURES_DIR);98};99100test('result.cwd is defined', testErrorCwd, execa, successProperties);101test('result.cwd is defined - sync', testErrorCwd, execaSync, successProperties);102test('error.cwd is defined', testErrorCwd, execa, errorProperties);103test('error.cwd is defined - sync', testErrorCwd, execaSync, errorProperties);
modified:test/error.js+6 added-16 removed
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../index.js';4import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';4import {setFixtureDir} from './helpers/fixtures-dir.js';5import {fullStdio, getStdio} from './helpers/stdio.js';6import {noopGenerator, outputObjectGenerator} from './helpers/generator.js';7import {foobarString} from './helpers/input.js';8
7 unmodified lines
16 const result = await execa('empty.js', {...fullStdio, all: true});17 t.deepEqual(Reflect.ownKeys(result), [18 'command',19 'escapedCommand',20 'cwd',21 'failed',22 'timedOut',23 'isCanceled',24 'isTerminated',
160 unmodified lines
185test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');186test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');187188test('Original error.message is kept', async t => {188 const {originalMessage} = await t.throwsAsync(execa('noop.js', {cwd: 1}));189 t.true(originalMessage.startsWith('The "options.cwd" property must be of type string or an instance of Buffer or URL. Received type number'));189 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));190 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');191});192193test('failed is false on success', async t => {194 const {failed} = await execa('noop.js', ['foo']);
125 unmodified lines
320 t.is(code, undefined);321});322323test('error.code is defined on failure if applicable', async t => {323 const {code} = await t.throwsAsync(execa('noop.js', {cwd: 1}));324 const {code} = await t.throwsAsync(execa('noop.js', {uid: true}));325 t.is(code, 'ERR_INVALID_ARG_TYPE');326});327327test('error.cwd is defined on failure if applicable', async t => {328 const {cwd} = await t.throwsAsync(execa('fail.js', [], {cwd: FIXTURES_DIR}));329 t.is(cwd, FIXTURES_DIR);330});331332test('error.cwd is undefined on failure if not passed as options', async t => {333 const expectedCwd = process.cwd();334 const {cwd} = await t.throwsAsync(execa('fail.js'));335 t.is(cwd, expectedCwd);336});337328const testUnusualError = async (t, error) => {329 const childProcess = execa('empty.js');330 childProcess.emit('error', error);331 const {message, originalMessage} = await t.throwsAsync(childProcess);
24 unmodified lines
356357test('error instance can be shared', async t => {358 const originalMessage = foobarString;359 const error = new Error(originalMessage);370 const fixtureName = 'noop.js';360 const fixtureName = 'empty.js';361362 const firstArgument = 'one';363 const childProcess = execa(fixtureName, [firstArgument]);364 childProcess.emit('error', error);
25 unmodified lines
modified:test/kill.js+5 added-5 removed
8 unmodified lines
9import {setFixtureDir} from './helpers/fixtures-dir.js';1011setFixtureDir();1213const isWindows = process.platform === 'win32';14const TIMEOUT_REGEXP = /timed out after/;1516const spawnNoKillable = async (forceKillAfterDelay, options) => {17 const subprocess = execa('no-killable.js', {
29 unmodified lines
47test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4849// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).50// Therefore, this feature and those tests must be different on Windows.50if (process.platform === 'win32') {51if (isWindows) {52 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {53 const {subprocess} = await spawnNoKillable(1);54 subprocess.kill();55
233 unmodified lines
289// if `options.detached: true`290// - on Linux subprocesses are never killed regardless of `options.detached`291// With `options.cleanup`, subprocesses are always killed292// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled292const exitIfWindows = process.platform === 'win32';293test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, exitIfWindows]);294test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, exitIfWindows]);293test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);294test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);295test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);296test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, exitIfWindows]);296test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);297test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);298test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);299test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);300test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);
133 unmodified lines
modified:test/test.js+15 added-27 removed
1import path from 'node:path';1import {delimiter, join, basename} from 'node:path';2import process from 'node:process';3import {fileURLToPath, pathToFileURL} from 'node:url';4import test from 'ava';5import isRunning from 'is-running';
6 unmodified lines
1213setFixtureDir();14process.env.FOO = 'foo';1516const isWindows = process.platform === 'win32';16const ENOENT_REGEXP = process.platform === 'win32' ? /failed with exit code 1/ : /spawn.* ENOENT/;17const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;1819const testOutput = async (t, index, execaMethod) => {20 const {stdout, stderr, stdio} = await execaMethod('noop-fd.js', [`${index}`, 'foobar'], fullStdio);21 t.is(stdio[index], 'foobar');
24 unmodified lines
46 const {stdio} = await execa('stdin-fd.js', ['3'], getStdio(3, [['foobar']]));47 t.is(stdio[3], undefined);48});4949if (process.platform === 'win32') {50if (isWindows) {51 test('execa() - cmd file', async t => {52 const {stdout} = await execa('hello.cmd');53 t.is(stdout, 'Hello World');54 });
57 unmodified lines
112 t.deepEqual(stdout, ['foobar\n']);113});114115const getPathWithoutLocalDir = () => {115 const newPath = process.env[PATH_KEY].split(path.delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(path.delimiter);116 const newPath = process.env[PATH_KEY].split(delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(delimiter);117 return {[PATH_KEY]: newPath};118};119120const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;
18 unmodified lines
139 t.notThrows(() => $({env: getPathWithoutLocalDir()}).sync`ava --version`);140});141142test('localDir option', async t => {142 const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';143 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';144 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: '/test'});144 const envPaths = stdout.split(path.delimiter);145 const envPaths = stdout.split(delimiter);146 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));147});148149test('execa() returns a promise with pid', async t => {
44 unmodified lines
194 t.is(stdout2, 'foo');195});196197test('use relative path with \'..\' chars', async t => {197 const pathViaParentDir = path.join('..', path.basename(fileURLToPath(new URL('..', import.meta.url))), 'test', 'fixtures', 'noop.js');198 const pathViaParentDir = join('..', basename(fileURLToPath(new URL('..', import.meta.url))), 'test', 'fixtures', 'noop.js');199 const {stdout} = await execa(pathViaParentDir, ['foo']);200 t.is(stdout, 'foo');201});202202if (process.platform !== 'win32') {203if (!isWindows) {204 test('execa() rejects if running non-executable', async t => {205 await t.throwsAsync(execa('non-executable.js'));206 });207
1 unmodified line
209 await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES/});210 });211}212212if (process.platform !== 'win32') {213if (!isWindows) {214 test('write to fast-exit process', async t => {215 // Try-catch here is necessary, because this test is not 100% accurate216 // Sometimes process can manage to accept input before exiting217 try {
19 unmodified lines
237 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}, extendEnv: false});238 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);239});240240test('can use `options.cwd` as a string', async t => {241 const cwd = '/';242 const {stdout} = await execa('node', ['-p', 'process.cwd()'], {cwd});243 t.is(path.toNamespacedPath(stdout), path.toNamespacedPath(cwd));244});245241test('localDir option can be a URL', async t => {247 const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';242 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';243 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: pathToFileURL('/test')});249 const envPaths = stdout.split(path.delimiter);244 const envPaths = stdout.split(delimiter);245 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));246});247253test('can use `options.cwd` as a URL', async t => {254 const cwd = '/';255 const cwdUrl = pathToFileURL(cwd);256 const {stdout} = await execa('node', ['-p', 'process.cwd()'], {cwd: cwdUrl});257 t.is(path.toNamespacedPath(stdout), path.toNamespacedPath(cwd));258});259248test('can use `options.shell: true`', async t => {249 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});250 t.is(stdout, 'foo');251});252253const testShellPath = async (t, mapPath) => {266 const shellPath = process.platform === 'win32' ? 'cmd.exe' : 'bash';254 const shellPath = isWindows ? 'cmd.exe' : 'bash';255 const shell = mapPath(await which(shellPath));256 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});257 t.is(stdout, 'foo');258};
2 unmodified lines
261test('can use `options.shell: file URL`', testShellPath, pathToFileURL);262263test('use extend environment with `extendEnv: true` and `shell: true`', async t => {264 process.env.TEST = 'test';277 const command = process.platform === 'win32' ? 'echo %TEST%' : 'echo $TEST';265 const command = isWindows ? 'echo %TEST%' : 'echo $TEST';266 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});267 t.is(stdout, 'test');268 delete process.env.TEST;269});
30 unmodified lines
300301const testInvalidCommand = async (t, execaMethod) => {302 t.throws(() => {303 execaMethod(['command', 'arg']);316 }, {message: /must be a string or a file URL/});304 }, {message: /First argument must be a string or a file URL/});305};306307test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);308test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);
1 unmodified line
modified:index.d.ts+3 added-3 removed
278 unmodified lines
279280 /**281 Path to the Node.js executable to use in child processes.282283 This can be either an absolute path or a path relative to the `cwd` option.284283 Requires `preferLocal` to be `true`.284285 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.286
122 unmodified lines
409410 /**411 Current working directory of the child process.412413 This is also used to resolve the `execPath` option when it is a relative path.414415 @default process.cwd()416 */417 readonly cwd?: string | URL;418
291 unmodified lines
710 */711 signalDescription?: string;712713 /**714 The `cwd` of the command if provided in the command options. Otherwise it is `process.cwd()`.714 The current directory in which the command was run.715 */716 cwd: string;717718 /**
580 unmodified lines
modified:index.js+8 added-15 removed
1import {Buffer} from 'node:buffer';2import {setMaxListeners} from 'node:events';3import path from 'node:path';3import {basename} from 'node:path';4import childProcess from 'node:child_process';5import process from 'node:process';6import {fileURLToPath} from 'node:url';6import crossSpawn from 'cross-spawn';7import stripFinalNewline from 'strip-final-newline';8import {npmRunPathEnv} from 'npm-run-path';9import {makeError} from './lib/error.js';
4 unmodified lines
14import {getSpawnedResult, makeAllStream} from './lib/stream.js';15import {mergePromise} from './lib/promise.js';16import {joinCommand, getEscapedCommand} from './lib/escape.js';17import {parseCommand} from './lib/command.js';18import {getDefaultCwd, normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './lib/cwd.js';19import {parseTemplates} from './lib/script.js';20import {logCommand, verboseDefault} from './lib/verbose.js';21import {bufferToUint8Array} from './lib/stdio/utils.js';22
8 unmodified lines
3132 return env;33};3435const normalizeFileUrl = file => file instanceof URL ? fileURLToPath(file) : file;35const getFilePath = rawFile => safeNormalizeFileUrl(rawFile, 'First argument');3637const getFilePath = rawFile => {38 const fileString = normalizeFileUrl(rawFile);3940 if (typeof fileString !== 'string') {41 throw new TypeError('First argument must be a string or a file URL.');42 }4344 return fileString;45};4637const handleArguments = (rawFile, rawArgs, rawOptions = {}) => {38 const filePath = getFilePath(rawFile);39 const command = joinCommand(filePath, rawArgs);40 const escapedCommand = getEscapedCommand(filePath, rawArgs);
4 unmodified lines
45 validateTimeout(options);46 options.shell = normalizeFileUrl(options.shell);47 options.env = getEnv(options);48 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);49 options.cwd = normalizeCwd(options.cwd);5060 if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {51 if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') {52 // #11653 args.unshift('/q');54 }55
7 unmodified lines
63 buffer = true,64 stripFinalNewline = true,65 extendEnv = true,66 preferLocal = false,76 cwd = process.cwd(),67 cwd = getDefaultCwd(),68 localDir = cwd,69 execPath = process.execPath,70 encoding = 'utf8',71 reject = true,
128 unmodified lines
200201 return {202 command,203 escapedCommand,204 cwd: options.cwd,205 failed: false,206 timedOut: false,207 isCanceled: false,208 isTerminated: false,
59 unmodified lines
268269 return {270 command,271 escapedCommand,272 cwd: options.cwd,273 failed: false,274 timedOut: false,275 isCanceled: false,276 isTerminated: false,
77 unmodified lines
modified:readme.md+3 added-3 removed
364 unmodified lines
365#### cwd366367Type: `string`368369The `cwd` of the command if provided in the [command options](#cwd-1). Otherwise it is `process.cwd()`.369The [current directory](#cwd-1) in which the command was run.370371#### stdout372373Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`
135 unmodified lines
509Default: `process.cwd()`510511Current working directory of the child process.512513This is also used to resolve the [`execPath`](#execpath) option when it is a relative path.514515#### env516517Type: `object`\518Default: `process.env`
31 unmodified lines
550Default: `process.execPath` (Current Node.js executable)551552Path to the Node.js executable to use in child processes.553552This can be either an absolute path or a path relative to the [`cwd` option](#cwd).553554Requires [`preferLocal`](#preferlocal) to be `true`.555556For 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.557
392 unmodified lines