fix(hooks): validate Bash commit and heredoc substitutions

This commit is contained in:
haelyra committed 2026-10-25 19:19:10 -04:00
1 parent f4bf43c550
commit 7632669d28
4 files changed
+70 -14

No files matched your search

+29 -6
View File
@@ -167,22 +167,35 @@ function findFileIssues(filePath) {
}
/**
* The body of the here-document that `value` starts with, as in `$(cat <<'EOF'`, or null.
* The body and expansion mode of the here-document that `value` starts with,
* as in `$(cat <<'EOF'`, or null.
* It ends at the line that holds only the delimiter, after leading tabs for <<-, which also
* strips them from the body.
* @param {string} value
* @returns {string|null}
* @returns {{body: string, expands: boolean}|null}
*/
function heredocBody(value) {
const opener = /^\$\(\s*cat\s+<<(-?)\s*(['"]?)([A-Za-z_][\w.-]*)\2[ \t]*\r?\n/.exec(value);
if (!opener) return null;
const [, stripTabs, , delimiter] = opener;
const [, stripTabs, quote, delimiter] = opener;
const lines = value.slice(opener[0].length).split('\n').map(line => {
const text = line.replace(/\r$/, '');
return stripTabs ? text.replace(/^\t+/, '') : text;
});
const end = lines.indexOf(delimiter);
return end === -1 ? null : lines.slice(0, end).join('\n');
return end === -1 ? null : { body: lines.slice(0, end).join('\n'), expands: quote === '' };
}
// Bash expands parameters, commands and arithmetic in an unquoted here-document.
// Only backslashes before $, `, \\ and newline suppress the following character.
function hasHeredocExpansion(body) {
for (let i = 0; i < body.length; i++) {
const ch = body[i];
const next = body[i + 1] || '';
if (ch === '\\' && next && '$`\\\n'.includes(next)) { i++; continue; }
if (ch === '`' || (ch === '$' && next && (/[A-Za-z0-9_]/.test(next) || '$@*#?!-({['.includes(next)))) return true;
}
return false;
}
/**
@@ -196,7 +209,7 @@ function validateCommitMessage(command) {
// newline) so an embedded escaped quote does not truncate the subject, and allowing
// the OTHER quote char inside the body; when unquoted, capture the full remaining
// tail, not just the first token)
const messageMatch = command.match(/(?:-m|--message)[=\s]+(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([^"']+?)\s*$)/);
const messageMatch = command.match(/(?:-m|--message)[=\s]+(?:"((?:\\[\s\S]|[^"\\])*)"|'([^']*)'|([^"']+?)\s*$)/);
if (!messageMatch) return null;
// A message written as -m "$(cat <<'EOF' ... EOF)", as Claude Code writes them, is the
@@ -204,10 +217,20 @@ function validateCommitMessage(command) {
const heredoc = messageMatch[1]?.startsWith('$(')
? heredocBody(command.slice(messageMatch.index + messageMatch[0].indexOf('"') + 1))
: null;
if (heredoc?.expands && hasHeredocExpansion(heredoc.body)) {
return {
message: null,
issues: [{
type: 'unverifiable',
message: 'Cannot validate a commit message with unquoted here-document expansions',
suggestion: 'Quote the here-document delimiter to keep the message literal'
}]
};
}
// In double quotes, Bash drops the backslash before $ ` " \ and drops a backslash-newline,
// a line continuation, altogether. Before any other character the backslash stays.
const doubleQuoted = messageMatch[1]?.replace(/\\([\n$`"\\])/g, (escape, next) => (next === '\n' ? '' : next));
const message = heredoc ?? doubleQuoted ?? messageMatch[2] ?? messageMatch[3];
const message = heredoc?.body ?? doubleQuoted ?? messageMatch[2] ?? messageMatch[3];
// The format rules apply to the subject: git drops leading blank lines and trailing
// whitespace, and the first line left is the subject.
const subject = (message.split('\n').find(line => line.trim()) || '').trimEnd();
+7 -8
View File
@@ -192,7 +192,9 @@ 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) {
@@ -200,13 +202,10 @@ function collectCheckSegments(cmd) {
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);
queue.push(body);
for (const body of [...extractCommandSubstitutions(current), ...extractSubshellGroups(current)]) {
const bodySegments = splitShellSegments(body);
segments.push(...bodySegments);
queue.push(body, ...bodySegments);
}
}
@@ -525,6 +525,28 @@ if (test('still reports a bad subject inside a here-document', () => {
assert.deepStrictEqual(res.issues.map(i => i.type), ['format', 'punctuation']);
})) passed++; else failed++;
if (test('warns when an unquoted here-document can expand the commit message', () => {
const command = 'git commit -m "$(cat <<EOF\nfix: ${EMPTY}\nEOF\n)"';
const res = hook.validateCommitMessage(command);
assert.strictEqual(res.message, null);
assert.deepStrictEqual(res.issues.map(i => i.type), ['unverifiable']);
assert.deepStrictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: ${EMPTY}\nEOF\n)"').issues,
[]
);
assert.deepStrictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<EOF\nfix: \\${EMPTY}\nEOF\n)"').issues,
[]
);
})) passed++; else failed++;
if (test('treats a backslash as literal inside a single-quoted commit message', () => {
const res = hook.validateCommitMessage(String.raw`git commit -m 'Update path\'`);
assert.ok(res, 'expected a validation result for valid Bash quoting');
assert.strictEqual(res.message, 'Update path' + String.fromCharCode(92));
assert.ok(res.issues.some(issue => issue.type === 'format'));
})) passed++; else failed++;
if (test('drops a line continuation from a double-quoted message, as Bash does', () => {
const res = hook.validateCommitMessage('git commit -m "\\\nfix: handle empty input"');
assert.strictEqual(res.message, 'fix: handle empty input');
@@ -306,6 +306,18 @@ function runTests() {
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, 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', () => {