Skip to content
Myr

Fix template strings, `parseCommandString()` and `execaNode()` edge cases

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent d9a5689 · Browse files · 6 files+187 added−27 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+187 added−27 removed

  • tests:+136 added−0 removed
  • other:+51 added−27 removed

6 files+187 added−27 removed

modified:lib/methods/command.js+9 added-18 removed
modified:lib/methods/node.js+24 added-1 removed
modified:lib/methods/template.js+18 added-8 removed
1import {ChildProcess} from 'node:child_process';2import isPlainObject from 'is-plain-obj';3import {ASTRAL_START} from '../arguments/escape.js';4import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';5import {isExecaError} from '../return/final-error.js';67// Check whether the template string syntax is being used8export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);910// Convert execa`file ...commandArguments` to execa(file, commandArguments)11export const parseTemplates = (templates, expressions) => {12 let tokens = [];13 // Whether whitespaces separate the last token from the next one14 let isSeparated = false;1516 for (const [index, template] of templates.entries()) {14 tokens = parseTemplate({17 ({tokens, isSeparated} = parseTemplate({18 templates,19 expressions,20 tokens,21 isSeparated,22 index,23 template,20 });24 }));25 }2627 if (tokens.length === 0) {28 throw new TypeError('Template script must not be empty');
2 unmodified lines
31 const [file, ...commandArguments] = tokens;32 return [file, commandArguments, {}];33};3431const parseTemplate = ({templates, expressions, tokens, index, template}) => {35const parseTemplate = ({templates, expressions, tokens, isSeparated, index, template}) => {36 if (template === undefined) {37 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);38 }3940 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);37 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);41 const newTokens = concatTokens(tokens, nextTokens, isSeparated || leadingWhitespaces);42 // When the template has no tokens, the whitespaces before it still separate the next token, e.g. after an empty array expression43 const isTemplateSeparated = trailingWhitespaces || (nextTokens.length === 0 && isSeparated);4445 if (index === expressions.length) {40 return newTokens;46 return {tokens: newTokens, isSeparated: isTemplateSeparated};47 }4849 const expression = expressions[index];50 const expressionTokens = Array.isArray(expression)51 ? expression.map(expression => parseExpression(expression))52 : [parseExpression(expression)];47 return concatTokens(newTokens, expressionTokens, trailingWhitespaces);53 return {54 tokens: concatTokens(newTokens, expressionTokens, isTemplateSeparated),55 isSeparated: expressionTokens.length === 0 && isTemplateSeparated,56 };57};5859// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:60// - ignored when input as a backslash sequence like: `echo foo\n bar`
87 unmodified lines
148 if (typeOfExpression === 'number') {149 return String(expression);150 }151143 // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result144 if (isPlainObject(expression) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {152 // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result.153 // A failed subprocess result is an error instance instead.154 if ((isPlainObject(expression) || isExecaError(expression)) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {155 return getSubprocessResult(expression);156 }157158 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {
24 unmodified lines
modified:test/methods/command.js+53 added
98 unmodified lines
99test('parseCommandString() allows escaping backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand));100test('parseCommandString() allows escaping multiple backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand));101test('parseCommandString() allows escaping backslashes not before spaces', () => testParseCommandOutput('echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand));102103// An escaped space must not be merged with the space delimiter after it104test('parseCommandString() allows escaping spaces before a space delimiter', () => {105 assert.deepEqual(parseCommandString('echo foo\\ bar'), ['echo', 'foo ', 'bar']);106});107108test('parseCommandString() allows escaping spaces before consecutive space delimiters', () => {109 assert.deepEqual(parseCommandString('echo foo\\ bar'), ['echo', 'foo ', 'bar']);110});111112test('parseCommandString() allows escaping consecutive spaces', () => {113 assert.deepEqual(parseCommandString('echo foo\\ \\ bar'), ['echo', 'foo bar']);114});115116test('parseCommandString() allows escaped spaces as the only characters of an argument', () => {117 assert.deepEqual(parseCommandString('echo \\ bar'), ['echo', ' ', 'bar']);118});119120test('parseCommandString() allows escaping a trailing space', () => {121 assert.deepEqual(parseCommandString('echo foo\\ '), ['echo', 'foo ']);122});123124test('parseCommandString() allows escaping a trailing space followed by other spaces', () => {125 assert.deepEqual(parseCommandString('echo foo\\ '), ['echo', 'foo ']);126});127128test('parseCommandString() allows escaping a trailing space followed by other whitespaces', () => {129 assert.deepEqual(parseCommandString('echo foo\\ \n'), ['echo', 'foo ']);130});131132test('parseCommandString() does not escape trailing whitespaces other than spaces', () => {133 assert.deepEqual(parseCommandString('echo foo\\\n'), ['echo', 'foo\\']);134});135136test('parseCommandString() trims whitespaces other than spaces', () => {137 assert.deepEqual(parseCommandString('\t echo foo \n'), ['echo', 'foo']);138});139140test('parseCommandString() allows escaping a leading space', () => {141 assert.deepEqual(parseCommandString('echo \\ foo'), ['echo', ' foo']);142});143144test('parseCommandString() allows escaping a space in the first token', () => {145 assert.deepEqual(parseCommandString('foo\\ bar baz'), ['foo bar', 'baz']);146});147148test('parseCommandString() allows only an escaped space', () => {149 assert.deepEqual(parseCommandString('\\ '), [' ']);150});151152test('parseCommandString() keeps tabs inside tokens with escaped spaces', () => {153 assert.deepEqual(parseCommandString('echo foo\tbar\\ baz'), ['echo', 'foo\tbar baz']);154});155156test('parseCommandString() can get empty strings', () => {157 assert.deepEqual(parseCommandString(''), []);158});159
4 unmodified lines
modified:test/methods/node.js+50 added
222 unmodified lines
223test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk', 'nodeOption'));224test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect-brk=9223', 'execaNode'));225test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk=9223', 'nodeOption'));226227// When the current process runs `node --eval` or `node --print`, `process.execArgv` contains that code, which must not be run by the subprocess instead of its file.228// The environment variable prevents a fork bomb, if that code is run.229const indexUrl = pathToFileURL(path.resolve(FIXTURES_DIRECTORY, '../../index.js')).href;230const evalCode = `if (process.env.EXECA_TEST_EVAL) {231 console.log('eval code was run by the subprocess');232} else {233 import(${JSON.stringify(indexUrl)}).then(async execaModule => {234 const {stdout} = await execaModule.execaNode('noop.js', [${JSON.stringify(foobarString)}], {env: {EXECA_TEST_EVAL: '1'}});235 console.log(stdout);236 });237}`;238239const testEvalRemoval = async nodeArguments => {240 const {stdout} = await execa('node', nodeArguments, {cwd: FIXTURES_DIRECTORY});241 // With `--print`, the value of the code is printed too242 assert.ok(stdout.split('\n').includes(foobarString));243 assert.ok(!stdout.includes('eval code was run'));244};245246test('The "nodeOptions" option removes -e when defined by current process', () => testEvalRemoval(['-e', evalCode]));247test('The "nodeOptions" option removes --eval when defined by current process', () => testEvalRemoval(['--eval', evalCode]));248test('The "nodeOptions" option removes --eval= when defined by current process', () => testEvalRemoval([`--eval=${evalCode}`]));249test('The "nodeOptions" option removes -p when defined by current process', () => testEvalRemoval(['-p', evalCode]));250test('The "nodeOptions" option removes --print when defined by current process', () => testEvalRemoval(['--print', evalCode]));251test('The "nodeOptions" option removes -pe when defined by current process', () => testEvalRemoval(['-pe', evalCode]));252test('The "nodeOptions" option removes -p -e when defined by current process', () => testEvalRemoval(['-p', '-e', evalCode]));253test('The "nodeOptions" option removes --print --eval when defined by current process', () => testEvalRemoval(['--print', '--eval', evalCode]));254test('The "nodeOptions" option removes -e -p when defined by current process', () => testEvalRemoval(['-e', evalCode, '-p']));255test('The "nodeOptions" option removes --input-type= when defined by current process', () => testEvalRemoval(['--input-type=commonjs', '-e', evalCode]));256test('The "nodeOptions" option removes --input-type when defined by current process', () => testEvalRemoval(['--input-type', 'commonjs', '-e', evalCode]));257// `--inspect-port` does not start the inspector by itself, so this does not need a free port258test('The "nodeOptions" option removes --inspect-port with a separate value when defined by current process', () => testEvalRemoval(['--inspect-port', '9339', '-e', evalCode]));259test('The "nodeOptions" option removes --inspect-port= when defined by current process', () => testEvalRemoval(['--inspect-port=9339', '-e', evalCode]));260261const testKeptFlags = async (keptFlags, removedFlags = []) => {262 const {stdout} = await execa('node', [...keptFlags, ...removedFlags, '-e', `import(${JSON.stringify(indexUrl)}).then(async execaModule => {263 const {stdout} = await execaModule.execaNode('-p', ['process.execArgv.join(" ")']);264 console.log(stdout);265 });`], {cwd: FIXTURES_DIRECTORY});266 assert.equal(stdout, [...keptFlags, '-p', 'process.execArgv.join(" ")'].join(' '));267};268269test('The "nodeOptions" option keeps other flags when -e is defined by current process', () => testKeptFlags(['--no-warnings']));270test('The "nodeOptions" option keeps the value of other flags when -e is defined by current process', () => testKeptFlags(['-r', './empty.js'], ['--input-type', 'commonjs']));271272test('The "nodeOptions" option is not filtered when passed explicitly', async () => {273 const {stdout} = await execaNode('-p', ['process.execArgv.join(" ")'], {nodeOptions: ['--input-type=commonjs', '--inspect-port=9339']});274 assert.equal(stdout, '--input-type=commonjs --inspect-port=9339 -p process.execArgv.join(" ")');275});276277const testInspectDifferentPort = async execaMethod => {278 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');279 assert.equal(stdout, foobarString);280 assert.ok(stdio[3].includes('Debugger listening'));
77 unmodified lines
modified:test/methods/template.js+33 added
3 unmodified lines
4import {assertThrows} from '../helpers/assert.js';5import {$} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {majorNodeVersion} from '../helpers/node-version.js';8import {foobarString} from '../helpers/input.js';910setFixtureDirectory();1112const isWindows = process.platform === 'win32';
55 unmodified lines
68test('$ allows escaping spaces in commands with interpolation', () => testScriptStdout(() => $`${'command with space.js'} foo bar`, 'foo\nbar'));69test('$ trims', () => testScriptStdout(() => $` echo.js foo bar `, 'foo\nbar'));70test('$ allows array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}`, 'foo\nbar'));71test('$ allows empty array interpolation', () => testScriptStdout(() => $`echo.js foo ${[]} bar`, 'foo\nbar'));72// An empty array must not remove the whitespace before it73test('$ allows empty array interpolation followed by a token', () => testScriptStdout(() => $`echo.js foo ${[]}bar`, 'foo\nbar'));74test('$ allows empty array interpolation followed by an expression', () => testScriptStdout(() => $`echo.js foo ${[]}${'bar'}`, 'foo\nbar'));75test('$ allows multiple empty array interpolations followed by a token', () => testScriptStdout(() => $`echo.js foo ${[]}${[]}bar`, 'foo\nbar'));76test('$ allows empty array interpolation after an expression and before a token', () => testScriptStdout(() => $`echo.js ${'foo'} ${[]}bar`, 'foo\nbar'));77test('$ allows empty array interpolation without whitespaces', () => testScriptStdout(() => $`echo.js foo${[]}bar`, 'foobar'));78test('$ allows empty array interpolation without whitespaces after it', () => testScriptStdout(() => $`echo.js foo${[]} bar`, 'foo\nbar'));79test('$ allows empty array interpolation between expressions without whitespaces', () => testScriptStdout(() => $`echo.js ${'foo'}${[]}${'bar'}`, 'foobar'));80test('$ allows empty array interpolation at the start of an argument', () => testScriptStdout(() => $`echo.js ${[]}foo bar`, 'foo\nbar'));81test('$ allows empty array interpolation at the end', () => testScriptStdout(() => $`echo.js foo ${[]}`, 'foo'));82test('$ allows empty array interpolation as the only argument', () => testScriptStdout(() => $`echo.js ${[]}`, ''));83test('$ allows empty array interpolation between tabs', () => testScriptStdout(() => $`echo.js foo ${[]} bar`, 'foo\nbar'));84test('$ allows empty array interpolation followed by an empty string', () => testScriptStdout(() => $`echo.js foo ${[]}${''} bar`, 'foo\n\nbar'));85test('$ allows empty array interpolation after escaped newlines', () => testScriptStdout(() => $`echo.js foo \86${[]}bar`, 'foo\nbar'));87test('$ allows space escaped values in array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz'));88test('$ can concatenate at the end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo'));89test('$ can concatenate at the start of tokens followed by an array', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo'));90test('$ can concatenate at the start and end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar'));
242 unmodified lines
333test('$.sync allows execa return value buffer interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'}));334test('$.sync allows execa return value array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar'));335test('$.sync allows execa return value buffer array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'}));336337// A failed result is an error instance, not a plain object338const testErrorInterpolate = async (getError, getSubprocess) => {339 const error = await getError();340 assert.equal(error.failed, true);341 const {stdout} = await getSubprocess(error);342 assert.equal(stdout, `${foobarString}\nbar`);343};344345test('$ allows execa error interpolation, reject: false', () => testErrorInterpolate(() => $({reject: false})`noop-fail.js 1 ${foobarString}`, error => $`echo.js ${error} bar`));346test('$ allows execa error interpolation, rejected', () => testErrorInterpolate(() => $`noop-fail.js 1 ${foobarString}`.catch(error => error), error => $`echo.js ${error} bar`));347test('$ allows execa error array interpolation', () => testErrorInterpolate(() => $({reject: false})`noop-fail.js 1 ${foobarString}`, error => $`echo.js ${[error, 'bar']}`));348test('$ allows execa error buffer interpolation', () => testErrorInterpolate(() => $({reject: false, encoding: 'buffer'})`noop-fail.js 1 ${foobarString}`, error => $`echo.js ${error} bar`));349test('$.sync allows execa error interpolation, reject: false', () => testErrorInterpolate(() => $({reject: false}).sync`noop-fail.js 1 ${foobarString}`, error => $.sync`echo.js ${error} bar`));350test('$.sync allows execa error interpolation, thrown', () => testErrorInterpolate(() => assertThrows(() => $.sync`noop-fail.js 1 ${foobarString}`), error => $.sync`echo.js ${error} bar`));351352const testInvalidSequence = getSubprocess => {353 assertThrows(getSubprocess, {message: /Invalid backslash sequence/});354};355
40 unmodified lines
396test('$ throws on invalid expression - [true]', () => testInvalidExpression([true]));397test('$ throws on invalid expression - [{}]', () => testInvalidExpression([{}]));398test('$ throws on invalid expression - [{foo: "bar"}]', () => testInvalidExpression([{foo: 'bar'}]));399test('$ throws on invalid expression - [{stdout: 1}]', () => testInvalidExpression([{stdout: 1}]));400test('$ throws on invalid expression - new Error()', () => testInvalidExpression(new Error(foobarString)));401test('$ throws on invalid expression - Object.assign(new Error(), {stdout})', () => testInvalidExpression(Object.assign(new Error(foobarString), {stdout: foobarString})));402403const testMissingOutput = invalidExpression => {404 assertThrows(405 () => $`echo.js ${invalidExpression()}`,
22 unmodified lines