From 9aa60d672cf8982680b780189ee63f4af4b92d62 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Tue, 10 Nov 2026 17:31:12 -0500 Subject: [PATCH 1/6] chore: add rule helper utilities Co-Authored-By: Claude Fable 5.2 --- src/rules/utils.spec.ts | 92 +++++++++++++++++++++++++++++++ src/rules/utils.ts | 119 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 211 insertions(+) create mode 100644 src/rules/utils.spec.ts create mode 100644 src/rules/utils.ts diff --git a/src/rules/utils.spec.ts b/src/rules/utils.spec.ts new file mode 100644 index 0000000..6cfce7f --- /dev/null +++ b/src/rules/utils.spec.ts @@ -0,0 +1,92 @@ +/** + * @fileoverview Unit tests for the shared rule helpers. + */ + +import { describe, expect, it } from "vitest"; +import { splitShellCommands, spanOfTokens } from "./utils.js"; +import { parseDocker } from "../parser/parse.js"; +import type { RunInstructionNode, ShellFormNode } from "../types.js"; + +function shellForm(command: string): ShellFormNode { + const { ast } = parseDocker(`RUN ${command}\n`); + const run = ast.body[0] as RunInstructionNode; + + return run.command as ShellFormNode; +} + +describe("splitShellCommands", () => { + it("should return a single command when there are no separators", () => { + const commands = splitShellCommands( + shellForm("apt-get install -y git"), + ); + + expect(commands).toHaveLength(1); + expect(commands[0]?.words).toEqual(["apt-get", "install", "-y", "git"]); + }); + + it("should split on && and || operator tokens", () => { + const commands = splitShellCommands( + shellForm("apt-get update && apt-get install -y git || true"), + ); + + expect(commands.map(command => command.words)).toEqual([ + ["apt-get", "update"], + ["apt-get", "install", "-y", "git"], + ["true"], + ]); + }); + + it("should split on pipes and standalone semicolons", () => { + const commands = splitShellCommands( + shellForm("cat foo | grep bar ; ls"), + ); + + expect(commands.map(command => command.words)).toEqual([ + ["cat", "foo"], + ["grep", "bar"], + ["ls"], + ]); + }); + + it("should split on trailing semicolons attached to a token", () => { + const commands = splitShellCommands(shellForm("cd /app; make")); + + expect(commands.map(command => command.words)).toEqual([ + ["cd", "/app"], + ["make"], + ]); + }); + + it("should strip a leading parenthesis from the first word", () => { + const commands = splitShellCommands(shellForm("(cd /app && make)")); + + expect(commands[0]?.words[0]).toBe("cd"); + }); + + it("should not split quoted operators", () => { + const commands = splitShellCommands(shellForm('echo "a && b"')); + + // "a && b" is quoted, so the && token never stands alone. + expect(commands).toHaveLength(1); + }); + + it("should keep token nodes alongside the cleaned words", () => { + const commands = splitShellCommands(shellForm("cd /app; make")); + const first = commands[0]; + + expect(first?.tokens.map(token => token.value)).toEqual([ + "cd", + "/app;", + ]); + expect(first?.words).toEqual(["cd", "/app"]); + }); +}); + +describe("spanOfTokens", () => { + it("should span from the first to the last token", () => { + const form = shellForm("echo one two"); + const span = spanOfTokens(form.arguments); + + expect(span).toEqual({ start: 4, end: 16 }); + }); +}); diff --git a/src/rules/utils.ts b/src/rules/utils.ts new file mode 100644 index 0000000..b2e50fd --- /dev/null +++ b/src/rules/utils.ts @@ -0,0 +1,119 @@ +/** + * @fileoverview Shared helpers for rules that analyze shell-form commands. + * + * Shell-form arguments are whitespace-delimited tokens. The helpers here + * split a token list into simple commands using standalone operator tokens + * and trailing semicolons, tracking quote state so that quoted operators + * (`echo "a && b"`) do not split; they intentionally do not implement full + * shell parsing. + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import type { ArgumentNode, ShellFormNode } from "../types.js"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** Operator tokens that separate simple commands. */ +const COMMAND_SEPARATORS = new Set(["&&", "||", ";", "|", "&"]); + +/** + * A simple command inside a shell-form instruction: the tokens that make + * it up plus their cleaned-up string values. + */ +export interface ShellCommand { + /** The tokens of this command, in source order. */ + tokens: ArgumentNode[]; + + /** + * The token values with a leading `(` removed from the first word and + * a trailing `;` removed from the last word. + */ + words: string[]; +} + +/** + * Splits shell-form arguments into simple commands on `&&`, `||`, `;`, + * `|`, and `&` operator tokens, as well as on tokens ending with `;`. + */ +export function splitShellCommands(shellForm: ShellFormNode): ShellCommand[] { + const commands: ShellCommand[] = []; + let current: ArgumentNode[] = []; + + const push = (): void => { + if (current.length > 0) { + commands.push({ + tokens: current, + words: current.map((token, index) => { + let word = token.value; + + if (index === 0) { + word = word.replace(/^\(+/u, ""); + } + + if (index === current.length - 1) { + word = word.replace(/;+$/u, ""); + } + + return word; + }), + }); + current = []; + } + }; + + let quote: string | null = null; + + /** Updates the open-quote state after consuming a token. */ + const consumeQuotes = (value: string): void => { + for (let i = 0; i < value.length; i++) { + const character = value[i] as string; + + if (character === "\\" && quote !== "'") { + i++; + } else if ( + quote === null && + (character === '"' || character === "'") + ) { + quote = character; + } else if (character === quote) { + quote = null; + } + } + }; + + for (const argument of shellForm.arguments) { + if (quote === null && COMMAND_SEPARATORS.has(argument.value)) { + push(); + continue; + } + + current.push(argument); + consumeQuotes(argument.value); + + if (quote === null && argument.value.endsWith(";")) { + push(); + } + } + + push(); + + return commands; +} + +/** + * Returns the offsets spanning a list of tokens. + */ +export function spanOfTokens(tokens: ArgumentNode[]): { + start: number; + end: number; +} { + return { + start: (tokens[0] as ArgumentNode).start, + end: (tokens.at(-1) as ArgumentNode).end, + }; +} From 0fd7cb8da7a05a62b9c221ad52512848e0904b8b Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Wed, 11 Nov 2026 09:16:39 -0500 Subject: [PATCH 2/6] fix: ignore escaped semicolons when splitting shell commands An escaped or quoted trailing semicolon is literal text, not a command separator. Quoting and escaping are now read from the source text, since argument values already have some escapes resolved, so splitShellCommands takes the source text as a second argument. Co-Authored-By: Claude Opus 5.5 --- src/rules/utils.spec.ts | 64 ++++++++++++++++++++++++++++++----------- src/rules/utils.ts | 46 +++++++++++++++++++++-------- 2 files changed, 82 insertions(+), 28 deletions(-) diff --git a/src/rules/utils.spec.ts b/src/rules/utils.spec.ts index 6cfce7f..bc29e47 100644 --- a/src/rules/utils.spec.ts +++ b/src/rules/utils.spec.ts @@ -5,28 +5,37 @@ import { describe, expect, it } from "vitest"; import { splitShellCommands, spanOfTokens } from "./utils.js"; import { parseDocker } from "../parser/parse.js"; +import type { ShellCommand } from "./utils.js"; import type { RunInstructionNode, ShellFormNode } from "../types.js"; -function shellForm(command: string): ShellFormNode { - const { ast } = parseDocker(`RUN ${command}\n`); +function parseRun(command: string): { + text: string; + form: ShellFormNode; +} { + const text = `RUN ${command}\n`; + const { ast } = parseDocker(text); const run = ast.body[0] as RunInstructionNode; - return run.command as ShellFormNode; + return { text, form: run.command as ShellFormNode }; +} + +function split(command: string): ShellCommand[] { + const { text, form } = parseRun(command); + + return splitShellCommands(form, text); } describe("splitShellCommands", () => { it("should return a single command when there are no separators", () => { - const commands = splitShellCommands( - shellForm("apt-get install -y git"), - ); + const commands = split("apt-get install -y git"); expect(commands).toHaveLength(1); expect(commands[0]?.words).toEqual(["apt-get", "install", "-y", "git"]); }); it("should split on && and || operator tokens", () => { - const commands = splitShellCommands( - shellForm("apt-get update && apt-get install -y git || true"), + const commands = split( + "apt-get update && apt-get install -y git || true", ); expect(commands.map(command => command.words)).toEqual([ @@ -37,9 +46,7 @@ describe("splitShellCommands", () => { }); it("should split on pipes and standalone semicolons", () => { - const commands = splitShellCommands( - shellForm("cat foo | grep bar ; ls"), - ); + const commands = split("cat foo | grep bar ; ls"); expect(commands.map(command => command.words)).toEqual([ ["cat", "foo"], @@ -49,7 +56,7 @@ describe("splitShellCommands", () => { }); it("should split on trailing semicolons attached to a token", () => { - const commands = splitShellCommands(shellForm("cd /app; make")); + const commands = split("cd /app; make"); expect(commands.map(command => command.words)).toEqual([ ["cd", "/app"], @@ -57,21 +64,46 @@ describe("splitShellCommands", () => { ]); }); + it("should not split on escaped trailing semicolons", () => { + const commands = split("echo marker\\; sudo apt-get upgrade"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "marker;", "sudo", "apt-get", "upgrade"], + ]); + }); + + it("should not split on quoted trailing semicolons", () => { + const commands = split("echo 'marker;' sudo"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "'marker;'", "sudo"], + ]); + }); + + it("should split after an escaped backslash before a semicolon", () => { + const commands = split("echo a\\\\; make"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "a\\"], + ["make"], + ]); + }); + it("should strip a leading parenthesis from the first word", () => { - const commands = splitShellCommands(shellForm("(cd /app && make)")); + const commands = split("(cd /app && make)"); expect(commands[0]?.words[0]).toBe("cd"); }); it("should not split quoted operators", () => { - const commands = splitShellCommands(shellForm('echo "a && b"')); + const commands = split('echo "a && b"'); // "a && b" is quoted, so the && token never stands alone. expect(commands).toHaveLength(1); }); it("should keep token nodes alongside the cleaned words", () => { - const commands = splitShellCommands(shellForm("cd /app; make")); + const commands = split("cd /app; make"); const first = commands[0]; expect(first?.tokens.map(token => token.value)).toEqual([ @@ -84,7 +116,7 @@ describe("splitShellCommands", () => { describe("spanOfTokens", () => { it("should span from the first to the last token", () => { - const form = shellForm("echo one two"); + const { form } = parseRun("echo one two"); const span = spanOfTokens(form.arguments); expect(span).toEqual({ start: 4, end: 16 }); diff --git a/src/rules/utils.ts b/src/rules/utils.ts index b2e50fd..dd4c640 100644 --- a/src/rules/utils.ts +++ b/src/rules/utils.ts @@ -31,20 +31,26 @@ export interface ShellCommand { /** * The token values with a leading `(` removed from the first word and - * a trailing `;` removed from the last word. + * a trailing separator `;` (unquoted and unescaped) removed from the + * last word. */ words: string[]; } /** * Splits shell-form arguments into simple commands on `&&`, `||`, `;`, - * `|`, and `&` operator tokens, as well as on tokens ending with `;`. + * `|`, and `&` operator tokens, as well as on tokens ending with an + * unquoted, unescaped `;`. Quoting and escaping are read from the source + * text because argument values already have some escapes resolved. */ -export function splitShellCommands(shellForm: ShellFormNode): ShellCommand[] { +export function splitShellCommands( + shellForm: ShellFormNode, + sourceText: string, +): ShellCommand[] { const commands: ShellCommand[] = []; let current: ArgumentNode[] = []; - const push = (): void => { + const push = (endsWithSeparator = false): void => { if (current.length > 0) { commands.push({ tokens: current, @@ -55,8 +61,8 @@ export function splitShellCommands(shellForm: ShellFormNode): ShellCommand[] { word = word.replace(/^\(+/u, ""); } - if (index === current.length - 1) { - word = word.replace(/;+$/u, ""); + if (endsWithSeparator && index === current.length - 1) { + word = word.replace(/;$/u, ""); } return word; @@ -68,13 +74,23 @@ export function splitShellCommands(shellForm: ShellFormNode): ShellCommand[] { let quote: string | null = null; - /** Updates the open-quote state after consuming a token. */ - const consumeQuotes = (value: string): void => { + /** + * Updates the open-quote state after consuming a token. Returns whether + * the token ends with a semicolon that is neither quoted nor escaped, + * which separates commands. + */ + const consumeQuotes = (value: string): boolean => { + let endsWithSeparator = false; + for (let i = 0; i < value.length; i++) { const character = value[i] as string; + endsWithSeparator = false; + if (character === "\\" && quote !== "'") { i++; + } else if (character === ";" && quote === null) { + endsWithSeparator = true; } else if ( quote === null && (character === '"' || character === "'") @@ -84,19 +100,25 @@ export function splitShellCommands(shellForm: ShellFormNode): ShellCommand[] { quote = null; } } + + return endsWithSeparator; }; for (const argument of shellForm.arguments) { - if (quote === null && COMMAND_SEPARATORS.has(argument.value)) { + if ( + quote === null && + COMMAND_SEPARATORS.has( + sourceText.slice(argument.start, argument.end), + ) + ) { push(); continue; } current.push(argument); - consumeQuotes(argument.value); - if (quote === null && argument.value.endsWith(";")) { - push(); + if (consumeQuotes(sourceText.slice(argument.start, argument.end))) { + push(true); } } From b50af05d5516e2a185566285afcd5b07bccc9389 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Wed, 18 Nov 2026 10:35:33 -0500 Subject: [PATCH 3/6] fix: stop splitting shell commands at an unquoted comment Co-Authored-By: Claude Opus 5.5 --- src/rules/utils.spec.ts | 17 +++++++++++++++++ src/rules/utils.ts | 21 ++++++++++++--------- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/rules/utils.spec.ts b/src/rules/utils.spec.ts index bc29e47..e49ead2 100644 --- a/src/rules/utils.spec.ts +++ b/src/rules/utils.spec.ts @@ -102,6 +102,23 @@ describe("splitShellCommands", () => { expect(commands).toHaveLength(1); }); + it("should ignore words after an unquoted shell comment", () => { + const commands = split("echo ok # example && sudo id"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "ok"], + ]); + }); + + it("should not treat a quoted or mid-word # as a comment", () => { + const commands = split("echo '# a' b#c && ls"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "'#", "a'", "b#c"], + ["ls"], + ]); + }); + it("should keep token nodes alongside the cleaned words", () => { const commands = split("cd /app; make"); const first = commands[0]; diff --git a/src/rules/utils.ts b/src/rules/utils.ts index dd4c640..1d18e97 100644 --- a/src/rules/utils.ts +++ b/src/rules/utils.ts @@ -5,7 +5,8 @@ * split a token list into simple commands using standalone operator tokens * and trailing semicolons, tracking quote state so that quoted operators * (`echo "a && b"`) do not split; they intentionally do not implement full - * shell parsing. + * shell parsing. An unquoted word starting with `#` begins a shell comment + * and ends the scan. */ //------------------------------------------------------------------------------ @@ -40,7 +41,7 @@ export interface ShellCommand { /** * Splits shell-form arguments into simple commands on `&&`, `||`, `;`, * `|`, and `&` operator tokens, as well as on tokens ending with an - * unquoted, unescaped `;`. Quoting and escaping are read from the source + * unquoted, unescaped `;`. Scanning stops at an unquoted shell comment. Quoting and escaping are read from the source * text because argument values already have some escapes resolved. */ export function splitShellCommands( @@ -105,19 +106,21 @@ export function splitShellCommands( }; for (const argument of shellForm.arguments) { - if ( - quote === null && - COMMAND_SEPARATORS.has( - sourceText.slice(argument.start, argument.end), - ) - ) { + const raw = sourceText.slice(argument.start, argument.end); + + if (quote === null && raw.startsWith("#")) { + // The shell ignores the rest of the line after a comment. + break; + } + + if (quote === null && COMMAND_SEPARATORS.has(raw)) { push(); continue; } current.push(argument); - if (consumeQuotes(sourceText.slice(argument.start, argument.end))) { + if (consumeQuotes(raw)) { push(true); } } From 9e0679409e681cfe36e5a6032c758f816cd79ce5 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Fri, 20 Nov 2026 10:38:08 -0500 Subject: [PATCH 4/6] fix: handle more shell syntax in splitShellCommands - Omit standalone ( group openers and keep escaped \( in words - Stop at a comment that starts right after a semicolon - Do not start a comment after an escaped blank - Remove line continuations and comment lines before scanning tokens - Require a non-empty token list in spanOfTokens Co-Authored-By: Claude Opus 5.5 --- src/rules/utils.spec.ts | 52 ++++++++++++++++++- src/rules/utils.ts | 109 +++++++++++++++++++++++++++++++--------- 2 files changed, 135 insertions(+), 26 deletions(-) diff --git a/src/rules/utils.spec.ts b/src/rules/utils.spec.ts index e49ead2..22eac4b 100644 --- a/src/rules/utils.spec.ts +++ b/src/rules/utils.spec.ts @@ -95,6 +95,54 @@ describe("splitShellCommands", () => { expect(commands[0]?.words[0]).toBe("cd"); }); + it("should omit a standalone group opener", () => { + const commands = split("( cd /app && make )"); + + expect(commands[0]?.words).toEqual(["cd", "/app"]); + expect(commands[0]?.tokens[0].value).toBe("cd"); + }); + + it("should keep an escaped opening parenthesis", () => { + const commands = split("\\(cd /app"); + + expect(commands[0]?.words[0]).toBe("(cd"); + }); + + it("should stop at a comment right after a semicolon", () => { + const commands = split("echo ok;# note && make"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "ok"], + ]); + }); + + it("should not start a comment after an escaped blank", () => { + const commands = split("echo word\\ #tag && make"); + + expect(commands.map(command => command.words[0])).toEqual([ + "echo", + "make", + ]); + }); + + it("should ignore comment lines inside continued tokens", () => { + const commands = split('echo o\\\n# "\nk && make'); + + expect(commands.map(command => command.words[0])).toEqual([ + "echo", + "make", + ]); + }); + + it("should classify operators split by a line continuation", () => { + const commands = split("echo ok &\\\n& make"); + + expect(commands.map(command => command.words[0])).toEqual([ + "echo", + "make", + ]); + }); + it("should not split quoted operators", () => { const commands = split('echo "a && b"'); @@ -133,8 +181,8 @@ describe("splitShellCommands", () => { describe("spanOfTokens", () => { it("should span from the first to the last token", () => { - const { form } = parseRun("echo one two"); - const span = spanOfTokens(form.arguments); + const [command] = split("echo one two"); + const span = spanOfTokens((command as ShellCommand).tokens); expect(span).toEqual({ start: 4, end: 16 }); }); diff --git a/src/rules/utils.ts b/src/rules/utils.ts index 1d18e97..844708f 100644 --- a/src/rules/utils.ts +++ b/src/rules/utils.ts @@ -22,18 +22,35 @@ import type { ArgumentNode, ShellFormNode } from "../types.js"; /** Operator tokens that separate simple commands. */ const COMMAND_SEPARATORS = new Set(["&&", "||", ";", "|", "&"]); +/** + * A Dockerfile line continuation (with either escape character) plus any + * full-line comments and empty lines after it. Docker removes these + * before the shell sees the command, so they are removed from the raw + * token text before scanning it. + */ +const CONTINUATION = /[\\`][ \t]*\r?\n(?:[ \t]*(?:#[^\n]*)?\r?\n)*/gu; + +/** A token made up only of subshell group openers, such as `(`. */ +const GROUP_OPENER = /^\(+$/u; + +/** + * A list of tokens with at least one element. + */ +export type NonEmptyTokens = [ArgumentNode, ...ArgumentNode[]]; + /** * A simple command inside a shell-form instruction: the tokens that make * it up plus their cleaned-up string values. */ export interface ShellCommand { /** The tokens of this command, in source order. */ - tokens: ArgumentNode[]; + tokens: NonEmptyTokens; /** - * The token values with a leading `(` removed from the first word and - * a trailing separator `;` (unquoted and unescaped) removed from the - * last word. + * The token values with an unescaped leading `(` removed from the first + * word and a trailing separator `;` (unquoted and unescaped) removed + * from the last word. Standalone `(` tokens are omitted from both + * `tokens` and `words`. */ words: string[]; } @@ -41,8 +58,9 @@ export interface ShellCommand { /** * Splits shell-form arguments into simple commands on `&&`, `||`, `;`, * `|`, and `&` operator tokens, as well as on tokens ending with an - * unquoted, unescaped `;`. Scanning stops at an unquoted shell comment. Quoting and escaping are read from the source - * text because argument values already have some escapes resolved. + * unquoted, unescaped `;`. Scanning stops at an unquoted shell comment. + * Quoting and escaping are read from the source text because argument + * values already have some escapes resolved. */ export function splitShellCommands( shellForm: ShellFormNode, @@ -50,37 +68,58 @@ export function splitShellCommands( ): ShellCommand[] { const commands: ShellCommand[] = []; let current: ArgumentNode[] = []; + let currentRaw: string[] = []; const push = (endsWithSeparator = false): void => { - if (current.length > 0) { + // A standalone `(` opens a subshell; the command starts after it. + while ( + currentRaw.length > 0 && + GROUP_OPENER.test(currentRaw[0] ?? "") + ) { + current.shift(); + currentRaw.shift(); + } + + const [first, ...rest] = current; + + if (first) { + const tokens: NonEmptyTokens = [first, ...rest]; + const firstRaw = currentRaw[0] as string; + commands.push({ - tokens: current, - words: current.map((token, index) => { + tokens, + words: tokens.map((token, index) => { let word = token.value; - if (index === 0) { + // Only an unescaped `(` opens a group; `\(cd` is a word. + if (index === 0 && firstRaw.startsWith("(")) { word = word.replace(/^\(+/u, ""); } - if (endsWithSeparator && index === current.length - 1) { - word = word.replace(/;$/u, ""); + if (endsWithSeparator && index === tokens.length - 1) { + word = word.replace(/;(?:#.*)?$/u, ""); } return word; }), }); - current = []; } + + current = []; + currentRaw = []; }; let quote: string | null = null; /** - * Updates the open-quote state after consuming a token. Returns whether + * Updates the open-quote state after consuming a token. Reports whether * the token ends with a semicolon that is neither quoted nor escaped, - * which separates commands. + * which separates commands, and whether a comment starts right after + * such a semicolon (`ok;# note`). */ - const consumeQuotes = (value: string): boolean => { + const consumeQuotes = ( + value: string, + ): { endsWithSeparator: boolean; startsComment: boolean } => { let endsWithSeparator = false; for (let i = 0; i < value.length; i++) { @@ -91,6 +130,10 @@ export function splitShellCommands( if (character === "\\" && quote !== "'") { i++; } else if (character === ";" && quote === null) { + if (value[i + 1] === "#") { + return { endsWithSeparator: true, startsComment: true }; + } + endsWithSeparator = true; } else if ( quote === null && @@ -102,13 +145,24 @@ export function splitShellCommands( } } - return endsWithSeparator; + return { endsWithSeparator, startsComment: false }; }; - for (const argument of shellForm.arguments) { - const raw = sourceText.slice(argument.start, argument.end); + let previousEnd: number | null = null; - if (quote === null && raw.startsWith("#")) { + for (const argument of shellForm.arguments) { + const raw = sourceText + .slice(argument.start, argument.end) + .replace(CONTINUATION, ""); + const gap = + previousEnd === null + ? "" + : sourceText.slice(previousEnd, argument.start); + + previousEnd = argument.end; + + // An escaped blank (`word\ #tag`) keeps the `#` inside the word. + if (quote === null && raw.startsWith("#") && !/\\[ \t]/u.test(gap)) { // The shell ignores the rest of the line after a comment. break; } @@ -119,10 +173,17 @@ export function splitShellCommands( } current.push(argument); + currentRaw.push(raw); - if (consumeQuotes(raw)) { + const { endsWithSeparator, startsComment } = consumeQuotes(raw); + + if (endsWithSeparator) { push(true); } + + if (startsComment) { + break; + } } push(); @@ -131,14 +192,14 @@ export function splitShellCommands( } /** - * Returns the offsets spanning a list of tokens. + * Returns the offsets spanning a non-empty list of tokens. */ -export function spanOfTokens(tokens: ArgumentNode[]): { +export function spanOfTokens(tokens: Readonly): { start: number; end: number; } { return { - start: (tokens[0] as ArgumentNode).start, + start: tokens[0].start, end: (tokens.at(-1) as ArgumentNode).end, }; } From f9bc6f3c75989e947de46763c1afe51fb48aee4d Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Mon, 23 Nov 2026 13:59:10 -0500 Subject: [PATCH 5/6] fix: start a comment after an unescaped blank that follows an escaped one Co-Authored-By: Claude Opus 5.5 --- src/rules/utils.spec.ts | 12 ++++++++++++ src/rules/utils.ts | 18 ++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/rules/utils.spec.ts b/src/rules/utils.spec.ts index 22eac4b..82dc785 100644 --- a/src/rules/utils.spec.ts +++ b/src/rules/utils.spec.ts @@ -125,6 +125,18 @@ describe("splitShellCommands", () => { ]); }); + it("should start a comment after an unescaped blank that follows an escaped one", () => { + const commands = split("echo word\\ # note && make"); + + expect(commands.map(command => command.words[0])).toEqual(["echo"]); + }); + + it("should start a comment after an escaped backslash and a blank", () => { + const commands = split("echo word\\\\ # note && make"); + + expect(commands.map(command => command.words[0])).toEqual(["echo"]); + }); + it("should ignore comment lines inside continued tokens", () => { const commands = split('echo o\\\n# "\nk && make'); diff --git a/src/rules/utils.ts b/src/rules/utils.ts index 844708f..5fe3a01 100644 --- a/src/rules/utils.ts +++ b/src/rules/utils.ts @@ -30,6 +30,12 @@ const COMMAND_SEPARATORS = new Set(["&&", "||", ";", "|", "&"]); */ const CONTINUATION = /[\\`][ \t]*\r?\n(?:[ \t]*(?:#[^\n]*)?\r?\n)*/gu; +/** + * Matches text ending in a blank that is not escaped: preceded by an even + * number of backslashes. + */ +const UNESCAPED_TRAILING_BLANK = /(?:^|[^\\])(?:\\\\)*[ \t]$/u; + /** A token made up only of subshell group openers, such as `(`. */ const GROUP_OPENER = /^\(+$/u; @@ -161,8 +167,16 @@ export function splitShellCommands( previousEnd = argument.end; - // An escaped blank (`word\ #tag`) keeps the `#` inside the word. - if (quote === null && raw.startsWith("#") && !/\\[ \t]/u.test(gap)) { + // A `#` starts a comment only at the start of a word: after an + // unescaped blank. An escaped blank (`word\ #tag`) keeps the `#` + // inside the word, but `word\ #note` has a second, unescaped + // blank before it. + if ( + quote === null && + raw.startsWith("#") && + (gap === "" || + UNESCAPED_TRAILING_BLANK.test(gap.replace(CONTINUATION, ""))) + ) { // The shell ignores the rest of the line after a comment. break; } From 1264ea18f85e509b4aee84188d5611bb26f7d952 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Mon, 23 Nov 2026 14:00:48 -0500 Subject: [PATCH 6/6] feat: expose the source spelling of shell command words Co-Authored-By: Claude Opus 5.5 --- src/rules/utils.spec.ts | 9 +++++++++ src/rules/utils.ts | 41 ++++++++++++++++++++++++++++------------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/src/rules/utils.spec.ts b/src/rules/utils.spec.ts index 82dc785..be4f9e2 100644 --- a/src/rules/utils.spec.ts +++ b/src/rules/utils.spec.ts @@ -33,6 +33,15 @@ describe("splitShellCommands", () => { expect(commands[0]?.words).toEqual(["apt-get", "install", "-y", "git"]); }); + it("should keep the source spelling of each word", () => { + const commands = split("(echo a\\\"b 'c\\\n d'; make"); + + expect(commands.map(command => command.raw)).toEqual([ + ["echo", 'a\\"b', "'c", "d'"], + ["make"], + ]); + }); + it("should split on && and || operator tokens", () => { const commands = split( "apt-get update && apt-get install -y git || true", diff --git a/src/rules/utils.ts b/src/rules/utils.ts index 5fe3a01..805481b 100644 --- a/src/rules/utils.ts +++ b/src/rules/utils.ts @@ -59,6 +59,14 @@ export interface ShellCommand { * `tokens` and `words`. */ words: string[]; + + /** + * The source spelling of each word, with Dockerfile continuations + * removed but quotes and shell escapes kept, trimmed the same way as + * `words`. Use this to decode shell quoting, because `words` already + * has some escapes resolved. + */ + raw: string[]; } /** @@ -92,22 +100,29 @@ export function splitShellCommands( const tokens: NonEmptyTokens = [first, ...rest]; const firstRaw = currentRaw[0] as string; - commands.push({ - tokens, - words: tokens.map((token, index) => { - let word = token.value; + /** + * Removes a group opener from the first word and a separator + * from the last word. + */ + const trim = (word: string, index: number): string => { + let result = word; - // Only an unescaped `(` opens a group; `\(cd` is a word. - if (index === 0 && firstRaw.startsWith("(")) { - word = word.replace(/^\(+/u, ""); - } + // Only an unescaped `(` opens a group; `\(cd` is a word. + if (index === 0 && firstRaw.startsWith("(")) { + result = result.replace(/^\(+/u, ""); + } + + if (endsWithSeparator && index === tokens.length - 1) { + result = result.replace(/;(?:#.*)?$/u, ""); + } - if (endsWithSeparator && index === tokens.length - 1) { - word = word.replace(/;(?:#.*)?$/u, ""); - } + return result; + }; - return word; - }), + commands.push({ + tokens, + words: tokens.map((token, index) => trim(token.value, index)), + raw: currentRaw.map(trim), }); }