Allow the first argument of `execa()` to be a file URL (#631)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent be739e7 · Browse files · 6 files·+79 added−23 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+79 added−23 removed
- tests:+35 added−3 removed
- other:+44 added−20 removed
Provenance
- Commit
3bbd8ae- Tree
60d9d9f- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
be739e7
6 files changed+79 added−23 removed
modified:test/helpers/fixtures-dir.js+2 added-1 removed
2 unmodified lines345677891011123 unmodified lines2 unmodified linesimport {fileURLToPath} from 'node:url';import pathKey from 'path-key';
export const PATH_KEY = pathKey();export const FIXTURES_DIR = fileURLToPath(new URL('../fixtures', import.meta.url));export const FIXTURES_DIR_URL = new URL('../fixtures/', import.meta.url);export const FIXTURES_DIR = fileURLToPath(FIXTURES_DIR_URL);
// Add the fixtures directory to PATH so fixtures can be executed without adding// `node`. This is only meant to make writing tests simpler.export const setFixtureDir = () => {3 unmodified linesmodified:test/test.js+33 added-2 removed
2 unmodified lines3 import {fileURLToPath, pathToFileURL} from 'node:url';4 import test from 'ava';5 import isRunning from 'is-running';6 import getNode from 'get-node';7-import {execa, execaSync, $} from '../index.js';8-import {setFixtureDir, PATH_KEY} from './helpers/fixtures-dir.js';7+import {execa, execaSync, execaNode, $} from '../index.js';8+import {setFixtureDir, PATH_KEY, FIXTURES_DIR_URL} from './helpers/fixtures-dir.js';9 10 setFixtureDir();11 process.env.FOO = 'foo';12 247 unmodified lines260 t.true(isRunning(pid));261 262 process.kill(pid, 'SIGKILL');263 });264+265+const testFileUrl = async (t, execaMethod) => {266+ const command = new URL('noop.js', FIXTURES_DIR_URL);267+ const {stdout} = await execaMethod(command, ['foobar']);268+ t.is(stdout, 'foobar');269+};270+271+test('execa()\'s command argument can be a file URL', testFileUrl, execa);272+test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);273+test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);274+275+const testInvalidFileUrl = async (t, execaMethod) => {276+ const invalidUrl = new URL('https://invalid.com');277+ t.throws(() => {278+ execaMethod(invalidUrl);279+ }, {code: 'ERR_INVALID_URL_SCHEME'});280+};281+282+test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);283+test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);284+test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);285+286+const testInvalidCommand = async (t, execaMethod) => {287+ t.throws(() => {288+ execaMethod(['command', 'arg']);289+ }, {message: /must be a string or a file URL/});290+};291+292+test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);293+test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);294+test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, execaNode);modified:index.d.ts+14 added-11 removed
550 unmodified lines551 ExecaChildPromise<StdoutStderrType> &552 Promise<ExecaReturnValue<StdoutStderrType>>;553 554 /**555-Executes a command using `file ...arguments`. `arguments` are specified as an array of strings. Returns a `childProcess`.555+Executes a command using `file ...arguments`. `file` is a string or a file URL. `arguments` are an array of strings. Returns a `childProcess`.556 557 Arguments are automatically escaped. They can contain any character, including spaces.558 559 This is the preferred method when executing single commands.560 561-@param file - The program/script to execute.561+@param file - The program/script to execute, as a string or file URL562 @param arguments - Arguments to pass to `file` on execution.563 @returns An `ExecaChildProcess` that is both:564 - a `Promise` resolving or rejecting with a `childProcessResult`.565 - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.96 unmodified lines662 }, 1000);663 ```664 */665 export function execa<EncodingType extends EncodingOption = DefaultEncodingOption>(666- file: string,666+ file: string | URL,667 arguments?: readonly string[],668 options?: Options<EncodingType>669 ): ExecaChildProcess<GetStdoutStderrType<EncodingType>>;670 export function execa<EncodingType extends EncodingOption = DefaultEncodingOption>(671- file: string, options?: Options<EncodingType>671+ file: string | URL,672+ options?: Options<EncodingType>673 ): ExecaChildProcess<GetStdoutStderrType<EncodingType>>;674 675 /**676 Same as `execa()` but synchronous.677 677-@param file - The program/script to execute.678+@param file - The program/script to execute, as a string or file URL679 @param arguments - Arguments to pass to `file` on execution.680 @returns A `childProcessResult` object681 @throws A `childProcessResult` error682 49 unmodified lines732 }733 ```734 */735 export function execaSync<EncodingType extends EncodingOption = DefaultEncodingOption>(735- file: string,736+ file: string | URL,737 arguments?: readonly string[],738 options?: SyncOptions<EncodingType>739 ): ExecaSyncReturnValue<GetStdoutStderrType<EncodingType>>;740 export function execaSync<EncodingType extends EncodingOption = DefaultEncodingOption>(740- file: string, options?: SyncOptions<EncodingType>741+ file: string | URL,742+ options?: SyncOptions<EncodingType>743 ): ExecaSyncReturnValue<GetStdoutStderrType<EncodingType>>;744 745 /**746 Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a `childProcess`.236 unmodified lines983 */984 export const $: Execa$;985 986 /**985-Execute a Node.js script as a child process.987+Executes a Node.js file using `node scriptPath ...arguments`. `file` is a string or a file URL. `arguments` are an array of strings. Returns a `childProcess`.988 989 Arguments are automatically escaped. They can contain any character, including spaces.990 991 This is the preferred method when executing Node.js files.2 unmodified lines994 - the current Node version and options are used. This can be overridden using the `nodePath` and `nodeOptions` options.995 - the `shell` option cannot be used996 - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to `stdio`997 996-@param scriptPath - Node.js script to execute.998+@param scriptPath - Node.js script to execute, as a string or file URL999 @param arguments - Arguments to pass to `scriptPath` on execution.1000 @returns An `ExecaChildProcess` that is both:1001 - a `Promise` resolving or rejecting with a `childProcessResult`.1002 - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.6 unmodified lines1009 await execaNode('scriptPath', ['argument']);1010 ```1011 */1012 export function execaNode<EncodingType extends EncodingOption = DefaultEncodingOption>(1011- scriptPath: string,1013+ scriptPath: string | URL,1014 arguments?: readonly string[],1015 options?: NodeOptions<EncodingType>1016 ): ExecaChildProcess<GetStdoutStderrType<EncodingType>>;1017 export function execaNode<EncodingType extends EncodingOption = DefaultEncodingOption>(1016- scriptPath: string, options?: NodeOptions<EncodingType>1018+ scriptPath: string | URL,1019+ options?: NodeOptions<EncodingType>1020 ): ExecaChildProcess<GetStdoutStderrType<EncodingType>>;modified:index.js+22 added-7 removed
1 import {Buffer} from 'node:buffer';2 import path from 'node:path';3 import childProcess from 'node:child_process';4 import process from 'node:process';5+import {fileURLToPath} from 'node:url';6 import crossSpawn from 'cross-spawn';7 import stripFinalNewline from 'strip-final-newline';8 import {npmRunPathEnv} from 'npm-run-path';9 import onetime from 'onetime';19 unmodified lines29 30 return env;31 };32 33+const getFilePath = file => {34+ if (file instanceof URL) {35+ return fileURLToPath(file);36+ }37+38+ if (typeof file !== 'string') {39+ throw new TypeError('First argument must be a string or a file URL.');40+ }41+42+ return file;43+};44+45 const handleArguments = (file, args, options = {}) => {46 const parsed = crossSpawn._parse(file, args, options);47 file = parsed.command;48 args = parsed.args;47 unmodified lines96 return value;97 };98 99 export function execa(file, args, options) {100+ const filePath = getFilePath(file);87- const parsed = handleArguments(file, args, options);101+ const parsed = handleArguments(filePath, args, options);102 const stdioStreams = handleInputAsync(parsed.options);103 validateTimeout(parsed.options);104 91- const command = joinCommand(file, args);92- const escapedCommand = getEscapedCommand(file, args);105+ const command = joinCommand(filePath, args);106+ const escapedCommand = getEscapedCommand(filePath, args);107 logCommand(escapedCommand, parsed.options);108 109 let spawned;110 try {78 unmodified lines189 return spawned;190 }191 192 export function execaSync(file, args, options) {193+ const filePath = getFilePath(file);179- const parsed = handleArguments(file, args, options);194+ const parsed = handleArguments(filePath, args, options);195 const stdioStreams = handleInputSync(parsed.options);196 182- const command = joinCommand(file, args);183- const escapedCommand = getEscapedCommand(file, args);197+ const command = joinCommand(filePath, args);198+ const escapedCommand = getEscapedCommand(filePath, args);199 logCommand(escapedCommand, parsed.options);200 201 let result;202 try {113 unmodified lines316 return execa(317 nodePath,318 [319 ...nodeOptions,305- scriptPath,320+ getFilePath(scriptPath),321 ...(Array.isArray(args) ? args : []),322 ],323 {324 ...options,8 unmodified linesmodified:index.test-d.ts+6 added
228 unmodified lines229 execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: false});230 execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: 42});231 execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: undefined});232 233+expectError(execa(['unicorns', 'arg']));234 expectType<ExecaChildProcess>(execa('unicorns'));235+expectType<ExecaChildProcess>(execa(new URL('file:///test')));236 expectType<ExecaReturnValue>(await execa('unicorns'));237 expectType<ExecaReturnValue>(238 await execa('unicorns', {encoding: 'utf8'}),239 );4 unmodified lines244 expectType<ExecaReturnValue<Uint8Array>>(245 await execa('unicorns', ['foo'], {encoding: 'buffer'}),246 );247 248+expectError(execaSync(['unicorns', 'arg']));249 expectType<ExecaSyncReturnValue>(execaSync('unicorns'));250+expectType<ExecaSyncReturnValue>(execaSync(new URL('file:///test')));251 expectType<ExecaSyncReturnValue>(252 execaSync('unicorns', {encoding: 'utf8'}),253 );254 expectType<ExecaSyncReturnValue<Uint8Array>>(18 unmodified lines273 expectType<ExecaSyncReturnValue<Uint8Array>>(execaCommandSync('unicorns', {encoding: 'buffer'}));274 expectType<ExecaSyncReturnValue>(execaCommandSync('unicorns foo', {encoding: 'utf8'}));275 expectType<ExecaSyncReturnValue<Uint8Array>>(execaCommandSync('unicorns foo', {encoding: 'buffer'}));276 277+expectError(execaNode(['unicorns', 'arg']));278 expectType<ExecaChildProcess>(execaNode('unicorns'));279 expectType<ExecaReturnValue>(await execaNode('unicorns'));280+expectType<ExecaReturnValue>(await execaNode(new URL('file:///test')));281 expectType<ExecaReturnValue>(282 await execaNode('unicorns', {encoding: 'utf8'}),283 );284 expectType<ExecaReturnValue<Uint8Array>>(await execaNode('unicorns', {encoding: 'buffer'}));71 unmodified linesmodified:readme.md+2 added-2 removed
236 unmodified lines237 ### Methods238 239 #### execa(file, arguments?, options?)240 241-Executes a command using `file ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess).241+Executes a command using `file ...arguments`. `file` is a string or a file URL. `arguments` are an array of strings. Returns a [`childProcess`](#childprocess).242 243 Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.244 245 This is the preferred method when executing single commands.246 247 #### execaNode(scriptPath, arguments?, options?)248 249-Executes a Node.js file using `node scriptPath ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess).249+Executes a Node.js file using `node scriptPath ...arguments`. `file` is a string or a file URL. `arguments` are an array of strings. Returns a [`childProcess`](#childprocess).250 251 Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.252 253 This is the preferred method when executing Node.js files.568 unmodified lines