Merge reviewed PR #3671

This commit is contained in:
haelyra committed 2026-11-05 23:10:45 -05:00
commit 912fc63c41
4 files changed
+536 -19

No files matched your search

+13 -9
View File
@@ -192,21 +192,25 @@ const DEV_PATTERN = /\b(npm\s+run\s+dev|pnpm(?:\s+run)?\s+dev|yarn(?:\s+run)?\s+
*/
function collectCheckSegments(cmd) {
const segments = [...splitShellSegments(cmd)];
const queue = [cmd];
// Expanded here-document bodies enter through splitShellSegments, so their
// segments must also be scanned for substitutions nested inside them.
const queue = [cmd, ...segments];
const seen = new Set();
while (queue.length) {
const current = queue.shift();
// Read by index: shift() copies the queue each time, which is quadratic on a long command.
for (let head = 0; head < queue.length; head++) {
const current = queue[head];
if (seen.has(current)) continue;
seen.add(current);
for (const body of extractCommandSubstitutions(current)) {
for (const seg of splitShellSegments(body)) segments.push(seg);
queue.push(body);
}
for (const body of extractSubshellGroups(current)) {
for (const seg of splitShellSegments(body)) segments.push(seg);
for (const body of [...extractCommandSubstitutions(current), ...extractSubshellGroups(current)]) {
const bodySegments = splitShellSegments(body);
// One at a time: spreading a long command's segments into push() exceeds the argument limit.
queue.push(body);
for (const segment of bodySegments) {
segments.push(segment);
queue.push(segment);
}
}
}
+280 -7
View File
@@ -1,26 +1,263 @@
'use strict';
// $'...' quoting, in which a backslash also escapes the closing quote
const ANSI_C_QUOTED_RE = /\$'((?:\\[\s\S]|[^'\\])*)'/y;
const ANSI_C_ESCAPES = { a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v' };
// A byte escape (\xHH, \NNN), another escape, or a run of text in $'...' quoting
const ANSI_C_TOKEN_RE = /\\(x[0-9A-Fa-f]{1,2}|[0-7]{1,3})|\\(u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|c[\s\S]|[\s\S])|[^\\]+|\\/g;
// The character that an ANSI-C escape other than a byte escape stands for, or the escape itself.
function ansiCEscape(code, escape) {
if ('uU'.includes(code[0]) && code.length > 1) {
const value = parseInt(code.slice(1), 16);
return value <= 0x10ffff ? String.fromCodePoint(value) : escape;
}
if (code[0] === 'c' && code.length > 1) return String.fromCharCode(code.charCodeAt(1) & 0x1f);
return ANSI_C_ESCAPES[code] ?? (`\\'"?`.includes(code) ? code : escape);
}
const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
// The text of $'...' quoting with its escapes decoded, as Bash decodes them, or null when the
// bytes are not UTF-8. Hex and octal escapes are bytes, so $'\xc3\xa9' is the UTF-8 text é.
function decodeAnsiC(text) {
const chunks = [];
for (const [token, byte, code] of text.matchAll(ANSI_C_TOKEN_RE)) {
if (byte !== undefined) {
chunks.push(Buffer.of(byte[0] === 'x' ? parseInt(byte.slice(1), 16) : parseInt(byte, 8) & 0xff));
} else {
chunks.push(Buffer.from(code === undefined ? token : ansiCEscape(code, token), 'utf8'));
}
}
try {
return UTF8.decode(Buffer.concat(chunks));
} catch {
return null;
}
}
// The shell word at `start`, up to an unquoted space, tab, newline or operator character, with
// its quoting removed, and whether any part of it was quoted. As in Bash, a carriage return is
// part of the word. Null if a quote does not close. The word is
// null when it holds bytes that are not UTF-8: no line of the command can then be equal to it.
function readWord(command, start) {
let word = '';
let quote = null;
let quoted = false;
let utf8 = true;
let i = start;
for (; i < command.length; i++) {
const ch = command[i];
// $$ is the process-ID parameter, so a quote right after it is not $'...'
if (!quote && ch === '$' && command[i + 1] === '$') {
word += '$$';
i++;
continue;
}
ANSI_C_QUOTED_RE.lastIndex = i;
const ansiC = !quote && ch === '$' ? ANSI_C_QUOTED_RE.exec(command) : null;
if (quote) {
if (quote === '"' && ch === '\\' && i + 1 < command.length && '$`"\\\n'.includes(command[i + 1])) {
const next = command[++i];
if (next !== '\n') word += next;
} else if (ch === quote) quote = null;
else word += ch;
} else if (ansiC) {
// $'...' decodes its escapes, so $'E\x4fF' is EOF
const decoded = decodeAnsiC(ansiC[1]);
if (decoded === null) utf8 = false;
// Bash ends the decoded string at a NUL, so $'EOF\0X' is EOF
else word += decoded.split('\0', 1)[0];
quoted = true;
i += ansiC[0].length - 1;
} else if (ch === "'" || ch === '"') {
quote = ch;
quoted = true;
} else if (ch === '$' && command[i + 1] === '"') {
// $"..." is double quoting; the $ is not part of the word
continue;
} else if (ch === '\\' && i + 1 < command.length) {
const next = command[++i];
if (next !== '\n') {
word += next;
quoted = true;
}
} else if (/[ \t\n|&;()<>]/.test(ch)) {
break;
} else {
word += ch;
}
}
return quote ? null : { word: utf8 ? word : null, quoted, end: i };
}
// A here-document opener at `index`, but not a here-string (<<<): `<<` or `<<-`, then the
// delimiter, a shell word whose quotes are removed (`<<'EOF'`, `<<E"OF"`, `<<$'EOF'`,
// `<<EOF/END`, `<<123`, and `<<''`, whose body ends at the first empty line). Unless part of the
// word is quoted, Bash expands the body, so its command substitutions run.
function heredocAt(command, index) {
if (command[index - 1] === '<' || command[index + 2] === '<') return null;
let i = index + 2;
const stripTabs = command[i] === '-';
if (stripTabs) i++;
while (command[i] === ' ' || command[i] === '\t') i++;
const word = readWord(command, i);
if (!word || (!word.word && !word.quoted)) return null;
return { text: command.slice(index, word.end), delimiter: word.word, stripTabs, expands: !word.quoted };
}
// The index after the `)` that closes the `(` at `index`, or -1. Quoted parentheses and escaped
// characters do not count.
function endOfParens(command, index) {
let depth = 0;
let quote = null;
for (let i = index; i < command.length; i++) {
const ch = command[i];
if (ch === '\\' && quote !== "'") i++;
else if (quote) quote = ch === quote ? null : quote;
else if (ch === "'" || ch === '"') quote = ch;
else if (ch === '(') depth++;
else if (ch === ')' && --depth === 0) return i + 1;
}
return -1;
}
// The index after the `))` that closes the arithmetic `((` at `index`, or -1.
function endOfArithmetic(command, index) {
const end = endOfParens(command, index);
return end !== -1 && command[end - 2] === ')' ? end : -1;
}
// The commands of the `$(...)` and backquoted substitutions in an expanded here-document body.
// Bash runs them while it reads the body, where quotes are plain text and a backslash escapes.
function commandSubstitutions(body) {
const commands = [];
let i = 0;
while (i < body.length) {
const backquoted = body[i] === '`';
if (body[i] === '\\') {
i += 2;
} else if (backquoted || (body[i] === '$' && body[i + 1] === '(')) {
const end = backquoted ? body.indexOf('`', i + 1) + 1 : endOfParens(body, i + 1);
if (end <= 0) break;
commands.push(body.slice(backquoted ? i + 1 : i + 2, end - 1));
i = end;
} else {
i++;
}
}
return commands;
}
// Whether the character at `index` is escaped by an odd run of backslashes before it.
function isEscaped(command, index) {
let count = 0;
for (let i = index - 1; i >= 0 && command[i] === '\\'; i--) count++;
return count % 2 === 1;
}
// Whether the character at `index` starts a word: it is the first of the command, or it follows an
// unescaped blank or operator character. Bash removes a backslash-newline pair first, so the
// character before the pair is the one that counts.
function startsWord(command, index, current) {
if (current === '') return true;
let before = index - 1;
while (before >= 1 && command[before] === '\n' && command[before - 1] === '\\' && !isEscaped(command, before - 1)) {
before -= 2;
}
// Bash's blanks are a space and a tab; a carriage return or a no-break space is part of a word.
return before < 0 || (/[ \t\n;&|(]/.test(command[before]) && !isEscaped(command, before));
}
// The end of a span copied as is, or -1: a comment, which runs to the end of its line, or an
// arithmetic expression such as $((x << n)), whose `<<` is a shift and `&&` an operator.
function literalSpanEnd(command, index, atWordStart) {
if (command[index] === '#' && atWordStart) {
const newline = command.indexOf('\n', index);
return newline === -1 ? command.length : newline;
}
return command[index] === '(' && command[index + 1] === '(' ? endOfArithmetic(command, index) : -1;
}
// Whether `text` ends in an odd number of backslashes, the last of which escapes what follows.
function endsInEscape(text) {
let count = 0;
while (count < text.length && text[text.length - 1 - count] === '\\') count++;
return count % 2 === 1;
}
// The here-document bodies that start at `start`, one after the other: the index after them,
// and the commands that the expanded ones run through command substitution.
function readHeredocBodies(command, start, heredocs) {
let end = start;
const substitutions = [];
for (const { delimiter, stripTabs, expands } of heredocs) {
const bodyStart = end;
let bodyEnd = command.length;
while (end < command.length) {
const lineStart = end;
let line = '';
for (;;) {
const newline = command.indexOf('\n', end);
const lineEnd = newline === -1 ? command.length : newline;
const part = command.slice(end, lineEnd);
end = lineEnd + 1;
// In an expanded body, Bash joins a line that ends in an escaping backslash with the
// next one before it compares the line with the delimiter.
if (!expands || newline === -1 || !endsInEscape(part)) {
line += part;
break;
}
line += part.slice(0, -1);
}
if ((stripTabs ? line.replace(/^\t+/, '') : line) === delimiter) {
bodyEnd = lineStart;
break;
}
}
if (expands) substitutions.push(...commandSubstitutions(command.slice(bodyStart, bodyEnd)));
}
return { end: Math.min(end, command.length), substitutions };
}
// At the newline at `index` the command ends. The bodies of the here-documents opened on its
// line follow it. They are data, not commands, so they are left out of the segments, except for
// the commands that an expanded body runs. Returns the index after the bodies.
function endLine(command, index, current, heredocs, segments) {
if (current.trim()) segments.push(current.trim());
const { end, substitutions } = readHeredocBodies(command, index + 1, heredocs);
for (const substitution of substitutions) segments.push(...splitShellSegments(substitution));
return end;
}
/**
* Split a shell command into segments by operators (&&, ||, ;, &)
* while respecting quoting (single/double) and escaped characters.
* Redirection operators (&>, >&, 2>&1) are NOT treated as separators.
* Split a shell command into segments by operators (&&, ||, ;, &) and by
* newlines, while respecting quoting (single/double) and escaped characters.
* Redirection operators (&>, >&, 2>&1) are NOT treated as separators, and the
* body of a here-document, which is data, is left out of the segments.
*/
function splitShellSegments(command) {
const segments = [];
let current = '';
let quote = null;
// Here-documents opened on the current line, read after its newline.
let heredocs = [];
for (let i = 0; i < command.length; i++) {
const ch = command[i];
// Inside quotes: handle escapes and closing quote
// Ordinary single quotes are literal. ANSI-C $'...' quotes also allow
// backslash escapes, including an apostrophe that must not close them.
// Inside double quotes, a backslash escapes only $, `, ", \\ and newline.
if (quote) {
if (ch === '\\' && i + 1 < command.length) {
if (ch === '\\' && i + 1 < command.length &&
(quote === "$'" || (quote === '"' && '$`"\\\n'.includes(command[i + 1])))) {
current += ch + command[i + 1];
i++;
continue;
}
if (ch === quote) quote = null;
if (ch === (quote === "$'" ? "'" : quote)) quote = null;
current += ch;
continue;
}
@@ -32,7 +269,20 @@ function splitShellSegments(command) {
continue;
}
// Opening quote
// $$ is the process-ID parameter, so a quote right after it is not $'...'
if (ch === '$' && command[i + 1] === '$') {
current += '$$';
i++;
continue;
}
// Opening quote. Keep ANSI-C quoting distinct from literal single quotes.
if (ch === '$' && command[i + 1] === "'") {
quote = "$'";
current += "$'";
i++;
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
current += ch;
@@ -42,6 +292,29 @@ function splitShellSegments(command) {
const next = command[i + 1] || '';
const prev = i > 0 ? command[i - 1] : '';
const spanEnd = literalSpanEnd(command, i, ch === '#' && startsWord(command, i, current));
if (spanEnd !== -1) {
current += command.slice(i, spanEnd);
i = spanEnd - 1;
continue;
}
const heredoc = ch === '<' && next === '<' ? heredocAt(command, i) : null;
if (heredoc) {
heredocs.push(heredoc);
current += heredoc.text;
i += heredoc.text.length - 1;
continue;
}
// A newline ends a command, after the bodies of the here-documents opened on its line
if (ch === '\n') {
i = endLine(command, i, current, heredocs, segments) - 1;
heredocs = [];
current = '';
continue;
}
// && operator
if (ch === '&' && next === '&') {
if (current.trim()) segments.push(current.trim());
@@ -49,6 +49,30 @@ function runTests() {
assert.ok(result.stderr.includes('BLOCKED'), `Expected stderr to contain BLOCKED, got: ${result.stderr}`);
}) ? passed++ : failed++);
(test('blocks dev launch after an ANSI-C escaped apostrophe', () => {
for (const command of ["export x=$'it\\'s here'; npm run dev", "export x=$'it\\'s here'\nnpm run dev"]) {
const result = runScript(command);
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${command}, got ${result.code}`);
}
}) ? passed++ : failed++);
(test('blocks dev launch after a $$ that a quote follows', () => {
for (const command of ["echo $$'\\'; npm run dev", "cat <<$$'EOF'\nbody\n$$EOF\nnpm run dev"]) {
const result = runScript(command);
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`);
}
}) ? passed++ : failed++);
(test('allows a dev command quoted after a $$', () => {
const result = runScript("echo $$'; npm run dev'");
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`);
}) ? passed++ : failed++);
(test('allows a dev command mentioned inside an ANSI-C quoted string', () => {
const result = runScript("echo $'x\\' && npm run dev'");
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`);
}) ? passed++ : failed++);
(test('blocks pnpm dev (exit code 2)', () => {
const result = runScript('pnpm dev');
assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`);
@@ -267,6 +291,78 @@ function runTests() {
}) ? passed++ : failed++);
}
// --- Newlines ---
if (!isWindows) {
(test('blocks a dev server after a single-quoted backslash and a separator', () => {
for (const command of ["echo 'x\\'; npm run dev", "echo 'x\\'\nnpm run dev"]) {
const result = runScript(command);
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`);
}
}) ? passed++ : failed++);
(test('blocks a dev server started on a later line of a multi-line command', () => {
const result = runScript('cd app\nnpm run dev');
assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`);
}) ? passed++ : failed++);
(test('blocks a dev server after a here-document with an ANSI-C quoted delimiter', () => {
const result = runScript("cat <<$'EOF'\ntext\nEOF\nnpm run dev");
assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`);
}) ? passed++ : failed++);
(test('blocks a dev server after a here-document with an escaped quote in its delimiter', () => {
const command = 'cat <<E"F\\"O"\nEF"O\nnpm run dev';
const result = runScript(command);
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`);
}) ? passed++ : failed++);
(test('blocks a dev server started by a substitution in a here-document body', () => {
for (const command of ["npm --version <<EOF\n'$(npm run dev)'\nEOF", "cat <<EOF\n'$(npm run dev)'\nEOF"]) {
const result = runScript(command);
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`);
}
}) ? passed++ : failed++);
(test('blocks a dev command in a substitution with a very long body', () => {
const command = `echo "$(npm run dev; ${'true; '.repeat(150000)})"`;
const result = runScript(command);
assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`);
}) ? passed++ : failed++);
(test('blocks nested dev commands in expanded here-document substitutions', () => {
for (const command of [
'cat <<EOF\n\'$(echo "$(npm run dev)")\'\nEOF',
"cat <<EOF\n'$( (npm run dev) )'\nEOF",
]) {
const result = runScript(command);
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`);
}
const quoted = "cat <<'EOF'\n'$(echo \"$(npm run dev)\")'\nEOF";
assert.strictEqual(runScript(quoted).code, 0, 'quoted here-document must remain literal');
}) ? passed++ : failed++);
}
(test('allows a here-document that only mentions a dev server', () => {
const result = runScript('cat <<EOF > README.md\nStart it with:\nnpm run dev\nEOF');
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`);
}) ? passed++ : failed++);
(test('allows a here-document body that follows an operator', () => {
const result = runScript('cat <<EOF &&\nnpm run dev\nEOF\necho done');
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`);
}) ? passed++ : failed++);
(test('allows a here-document body whose ANSI-C quoted delimiter has an escape', () => {
const result = runScript("cat <<$'E\\x4fF'\nE\\x4fF\nnpm run dev\nEOF");
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`);
}) ? passed++ : failed++);
(test('allows a here-document body fed to a package manager command', () => {
const result = runScript('npm --version <<EOF && cat\nnpm run dev\nEOF');
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`);
}) ? passed++ : failed++);
// --- Edge cases ---
(test('empty/invalid input passes through (exit code 0)', () => {
+147 -3
View File
@@ -1,5 +1,6 @@
'use strict';
const assert = require('assert');
const { spawnSync } = require('child_process');
const { splitShellSegments } = require('../../scripts/lib/shell-split');
console.log('=== Testing shell-split.js ===\n');
@@ -69,9 +70,65 @@ test('escaped double quote inside double quotes', () => {
const segs = splitShellSegments('echo "hello \\"world\\"" && echo bye');
assert.strictEqual(segs.length, 2);
});
test('escaped single quote inside single quotes', () => {
const segs = splitShellSegments("echo 'hello \\'world\\'' && echo bye");
assert.strictEqual(segs.length, 2);
test('a backslash inside single quotes cannot escape the closing quote', () => {
assert.deepStrictEqual(splitShellSegments("echo 'x\\'; npm run dev"), ["echo 'x\\'", 'npm run dev']);
assert.deepStrictEqual(splitShellSegments("echo 'x\\'\nnpm run dev"), ["echo 'x\\'", 'npm run dev']);
});
test('ANSI-C quotes keep escaped apostrophes and shell operators as data', () => {
const actualLaunch = "export x=$'it\\'s here'; npm run dev";
const literalInstruction = "echo $'x\\' && npm run dev'";
assert.deepStrictEqual(splitShellSegments(actualLaunch), ["export x=$'it\\'s here'", 'npm run dev']);
assert.deepStrictEqual(splitShellSegments("export x=$'it\\'s here'\nnpm run dev"), ["export x=$'it\\'s here'", 'npm run dev']);
assert.deepStrictEqual(splitShellSegments(literalInstruction), [literalInstruction]);
if (process.platform !== 'win32') {
const syntax = spawnSync('/bin/bash', ['-n', '-c', actualLaunch], { encoding: 'utf8' });
assert.strictEqual(syntax.status, 0, syntax.stderr);
const value = spawnSync('/bin/bash', ['-c', "export x=$'it\\'s here'; printf '%s' \"$x\""], { encoding: 'utf8' });
assert.strictEqual(value.status, 0, value.stderr);
assert.strictEqual(value.stdout, "it's here");
const text = spawnSync('/bin/bash', ['-c', literalInstruction], { encoding: 'utf8' });
assert.strictEqual(text.status, 0, text.stderr);
assert.strictEqual(text.stdout, "x' && npm run dev\n");
}
});
test('$$ before a quote is the process ID, not the start of ANSI-C quoting', () => {
const launch = "echo $$'\\'; npm run dev";
const heredoc = "cat <<$$'EOF'\nbody\n$$EOF\nnpm run dev";
const literalInstruction = "echo $$'; npm run dev'";
assert.deepStrictEqual(splitShellSegments(launch), ["echo $$'\\'", 'npm run dev']);
assert.deepStrictEqual(splitShellSegments(heredoc), ["cat <<$$'EOF'", 'npm run dev']);
assert.deepStrictEqual(splitShellSegments(literalInstruction), [literalInstruction]);
if (process.platform !== 'win32') {
const run = command => spawnSync('/bin/bash', ['-c', command.replace('npm run dev', "printf 'ran\\n'")], { encoding: 'utf8' });
const ran = run(launch);
assert.strictEqual(ran.status, 0, ran.stderr);
assert.ok(ran.stdout.endsWith('\\\nran\n'), ran.stdout);
const body = run(heredoc);
assert.strictEqual(body.status, 0, body.stderr);
assert.strictEqual(body.stdout, 'body\nran\n');
const text = spawnSync('/bin/bash', ['-c', literalInstruction], { encoding: 'utf8' });
assert.strictEqual(text.status, 0, text.stderr);
assert.ok(text.stdout.endsWith('; npm run dev\n'), text.stdout);
}
});
test('bash ends a decoded ANSI-C delimiter at a NUL', () => {
const command = "cat <<$'EOF\\0X'\nbody\nEOF\nnpm run dev";
assert.deepStrictEqual(splitShellSegments(command), ["cat <<$'EOF\\0X'", 'npm run dev']);
if (process.platform !== 'win32') {
const ran = spawnSync('/bin/bash', ['-c', command.replace('npm run dev', "printf 'ran\\n'")], { encoding: 'utf8' });
assert.strictEqual(ran.stdout, 'body\nran\n', ran.stderr);
}
});
test('a # after a carriage return or a no-break space is part of the word', () => {
for (const blankLike of ['\r', ' ']) {
const command = `echo foo${blankLike}# && npm run dev`;
assert.deepStrictEqual(splitShellSegments(command), [`echo foo${blankLike}#`, 'npm run dev']);
if (process.platform !== 'win32') {
const ran = spawnSync('/bin/bash', ['-c', command.replace('npm run dev', "printf 'ran\\n'")], { encoding: 'utf8' });
assert.ok(ran.stdout.endsWith('ran\n'), JSON.stringify(ran.stdout));
}
}
});
// Escaped operators outside quotes
@@ -110,5 +167,92 @@ test('single command no operators', () => {
assert.deepStrictEqual(splitShellSegments('npm run dev'), ['npm run dev']);
});
// Newlines and here-documents
console.log('\nNewlines and here-documents:');
test('a newline splits into two segments', () => {
assert.deepStrictEqual(splitShellSegments('cd app\nnpm run dev'), ['cd app', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('a && b\n\nc'), ['a', 'b', 'c']);
});
test('an escaped or quoted newline does not split', () => {
assert.deepStrictEqual(splitShellSegments('npm run \\\ndev'), ['npm run \\\ndev']);
assert.deepStrictEqual(splitShellSegments('echo "a\nb"'), ['echo "a\nb"']);
});
test('a here-document body is data, left out of the segments', () => {
assert.deepStrictEqual(splitShellSegments('cat <<EOF > notes.md\na && b\nnpm run dev\nEOF\nls'), ['cat <<EOF > notes.md', 'ls']);
assert.deepStrictEqual(splitShellSegments("cat <<-'END'\n\tnpm run dev\n\tEND\nls"), ["cat <<-'END'", 'ls']);
assert.deepStrictEqual(splitShellSegments('cat <<A <<B\na\nA\nb\nB\nnext'), ['cat <<A <<B', 'next']);
});
test('a here-string or a shift is not a here-document', () => {
assert.deepStrictEqual(splitShellSegments('cat <<< x && y'), ['cat <<< x', 'y']);
assert.deepStrictEqual(splitShellSegments('echo $((x << 2))\nnext'), ['echo $((x << 2))', 'next']);
assert.deepStrictEqual(splitShellSegments('echo $((x << n))\nnpm run dev'), ['echo $((x << n))', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('(( n << 2 )) && npm run dev'), ['(( n << 2 ))', 'npm run dev']);
});
test('a << in a comment is not a here-document, and a comment is not split', () => {
assert.deepStrictEqual(splitShellSegments('echo ok # <<EOF\nnpm run dev'), ['echo ok # <<EOF', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('echo hi # a && b'), ['echo hi # a && b']);
assert.deepStrictEqual(splitShellSegments('echo a#b ${#x} && c'), ['echo a#b ${#x}', 'c']);
});
test('a here-document delimiter is a shell word, read without its quotes', () => {
assert.deepStrictEqual(splitShellSegments('cat <<EOF/END\nnpm run dev\nEOF/END\nls'), ['cat <<EOF/END', 'ls']);
assert.deepStrictEqual(splitShellSegments('cat <<E"OF"\nnpm run dev\nEOF\nls'), ['cat <<E"OF"', 'ls']);
assert.deepStrictEqual(splitShellSegments('cat <<123\nnpm run dev\n123\nls'), ['cat <<123', 'ls']);
assert.deepStrictEqual(splitShellSegments("cat <<$'EOF'\ntext\nEOF\nnpm run dev"), ["cat <<$'EOF'", 'npm run dev']);
// $'...' decodes its escapes: $'E\x4fF' is EOF, and $'it\'s' is it's
assert.deepStrictEqual(splitShellSegments("cat <<$'E\\x4fF'\nE\\x4fF\nnpm run dev\nEOF\nls"), ["cat <<$'E\\x4fF'", 'ls']);
assert.deepStrictEqual(splitShellSegments("cat <<$'it\\'s'\nnpm run dev\nit's\nls"), ["cat <<$'it\\'s'", 'ls']);
// Bash keeps a double-quoted delimiter open across an escaped quote.
assert.deepStrictEqual(splitShellSegments('cat <<E"F\\"O"\nEF"O\nnpm run dev'), ['cat <<E"F\\"O"', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('cat <<EO\\\nF\nEOF\nnpm run dev'), ['cat <<EO\\\nF', 'npm run dev']);
// Hex and octal escapes are bytes, so both of these are the UTF-8 delimiter é
assert.deepStrictEqual(splitShellSegments("cat <<$'\\xc3\\xa9'\n\u00c3\u00a9\nnpm run dev\n\u00e9\nls"), ["cat <<$'\\xc3\\xa9'", 'ls']);
assert.deepStrictEqual(splitShellSegments("cat <<$'\\303\\251'\nnpm run dev\n\u00e9\nls"), ["cat <<$'\\303\\251'", 'ls']);
// A delimiter whose bytes are not UTF-8 matches no line, so the body runs to the end
assert.deepStrictEqual(splitShellSegments("cat <<$'\\xff'\n\ufffd\nnpm run dev"), ["cat <<$'\\xff'"]);
// A long delimiter is read in one pass
const long = 'a'.repeat(200000);
assert.deepStrictEqual(splitShellSegments(`cat <<$'${long}'\ntext\n${long}\nnpm run dev`), [`cat <<$'${long}'`, 'npm run dev']);
// An empty delimiter ends the body at the first empty line
assert.deepStrictEqual(splitShellSegments("cat <<''\nnpm run dev\n\nls"), ["cat <<''", 'ls']);
});
test('an expanded here-document body exposes the commands its substitutions run', () => {
// Quotes are plain text in the body, so Bash still runs the substitution
assert.deepStrictEqual(splitShellSegments("npm --version <<EOF\n'$(npm run dev)'\nEOF"), ['npm --version <<EOF', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('cat <<EOF\n`npm run dev`\nEOF'), ['cat <<EOF', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('cat <<EOF\nStarted: ${x:-$(npm run dev)}\nEOF'), ['cat <<EOF', 'npm run dev']);
// An escaped substitution, or a body whose delimiter is quoted, is not expanded
assert.deepStrictEqual(splitShellSegments('cat <<EOF\n\\$(npm run dev)\nEOF'), ['cat <<EOF']);
assert.deepStrictEqual(splitShellSegments("cat <<'EOF'\n$(npm run dev)\nEOF"), ["cat <<'EOF'"]);
assert.deepStrictEqual(splitShellSegments('cat <<\\EOF\n$(npm run dev)\nEOF'), ['cat <<\\EOF']);
});
test('a here-document body after an operator is left out too', () => {
assert.deepStrictEqual(splitShellSegments('cat <<EOF &&\nnpm run dev\nEOF\necho done'), ['cat <<EOF', 'echo done']);
assert.deepStrictEqual(splitShellSegments('npm --version <<EOF && cat\nnpm run dev\nEOF'), ['npm --version <<EOF', 'cat']);
});
test('a here-document delimiter on a CRLF line still ends the body', () => {
assert.deepStrictEqual(splitShellSegments('cat <<EOF\r\ntext\r\nEOF\r\nnpm run dev'), ['cat <<EOF', 'npm run dev']);
// The \r is part of the line, so after an LF delimiter a CRLF line does not end the body
assert.deepStrictEqual(splitShellSegments('cat <<EOF\nEOF\r\nnpm run dev\nEOF'), ['cat <<EOF']);
});
test('an expanded here-document body joins a line that ends in an escaping backslash', () => {
assert.deepStrictEqual(splitShellSegments('cat <<EOF\nbody\nEO\\\nF\nnpm run dev'), ['cat <<EOF', 'npm run dev']);
// An escaped backslash does not join, and a quoted delimiter keeps the lines as they are
assert.deepStrictEqual(splitShellSegments('cat <<EOF\nEOF\\\\\nnpm run dev\nEOF'), ['cat <<EOF']);
assert.deepStrictEqual(splitShellSegments("cat <<'EOF'\nEO\\\nF\nEOF\nnpm run dev"), ["cat <<'EOF'", 'npm run dev']);
});
test('a # after an escaped blank does not start a comment', () => {
assert.deepStrictEqual(splitShellSegments('echo foo\\ # && npm run dev'), ['echo foo\\ #', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('echo foo # && npm run dev'), ['echo foo # && npm run dev']);
// An escaped backslash leaves the blank after it unescaped
assert.deepStrictEqual(splitShellSegments('echo a\\\\ # && npm run dev'), ['echo a\\\\ # && npm run dev']);
});
test('a # after a line continuation is read as bash reads the joined line', () => {
// Bash drops the backslash-newline, so the blank before it makes # start a comment
assert.deepStrictEqual(splitShellSegments('echo \\\n# <<EOF\ntrue && npm run dev'), ['echo \\\n# <<EOF', 'true', 'npm run dev']);
// Without a blank before the continuation, # is part of the word
assert.deepStrictEqual(splitShellSegments('echo foo\\\n#bar && npm run dev'), ['echo foo\\\n#bar', 'npm run dev']);
assert.deepStrictEqual(splitShellSegments('echo foo\\ \\\n# x && npm run dev'), ['echo foo\\ \\\n# x', 'npm run dev']);
});
console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`);
if (failed > 0) process.exit(1);