Merge reviewed PR #3672

# Conflicts:
#	scripts/hooks/pre-bash-commit-quality.js
This commit is contained in:
haelyra committed 2026-11-05 23:10:59 -05:00
commit 5d64ad64f3
2 files changed
+309 -13

No files matched your search

+130 -12
View File
@@ -166,6 +166,110 @@ function findFileIssues(filePath) {
return issues;
}
/**
* 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. In an unquoted here-document, a line that ends in an unescaped
* backslash is joined with the next one before the delimiter is looked for, so a delimiter
* line right after it does not end the body. A quoted body stays literal, as Bash 4 and later
* and zsh read it; `bash32Body` is how Bash 3.2 reads it inside "$(...)", with those lines
* joined too.
* @param {string} value
* @returns {{body: string, expands: boolean, bash32Body: string|null}|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, quote, delimiter] = opener;
const raw = value.slice(opener[0].length).split('\n');
const lines = raw.map(line => line.replace(/\r$/, ''));
// Where the delimiter line ends in `value`, for the text after the substitution.
let end = -1;
const read = joinLines => {
const body = [];
let joined = '';
let offset = opener[0].length;
for (const [index, line] of lines.entries()) {
offset += raw[index].length + 1;
// <<- strips leading tabs while the line read so far is empty, so not from a line
// that a backslash continues after some text
const text = joined + (stripTabs && !joined ? line.replace(/^\t+/, '') : line);
// An odd number of trailing backslashes escapes the newline
if (joinLines && /(?:^|[^\\])(?:\\\\)*\\$/.test(text)) {
joined = text.slice(0, -1);
continue;
}
joined = '';
if (text === delimiter) {
if (end === -1) end = Math.min(offset, value.length);
return body.join('\n');
}
body.push(text);
}
return null;
};
const expands = quote === '';
const body = read(expands);
return body === null ? null : { body, expands, bash32Body: expands ? null : read(true), end };
}
// Git drops leading blank lines and trailing whitespace, and the first line left is the subject.
function subjectOf(message) {
return (message.split('\n').find(line => line.trim()) || '').trimEnd();
}
// 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;
}
// The message a `-m "$(cat <<…)"` value gives Git, or an `issue` when the literal command
// does not show it: an expansion in an unquoted body, or commands or expansions after the
// here-document. Text after the substitution's `)` is part of the message: `$(…)."` adds a
// period to the body, whose trailing newlines the substitution drops first.
function readHeredocMessage(value, heredoc) {
if (heredoc.expands && hasHeredocExpansion(heredoc.body)) {
return { issue: {
type: 'unverifiable',
message: 'Cannot validate a commit message with unquoted here-document expansions',
suggestion: 'Quote the here-document delimiter to keep the message literal'
} };
}
const after = /^[ \t\r\n]*\)((?:\\[\s\S]|[^"\\])*)"/.exec(value.slice(heredoc.end));
// In double quotes Bash drops a backslash-newline before it expands anything, so
// `$\<newline>HOME` is `$HOME`; other escapes stay for the expansion check to skip.
const continued = after && after[1].replace(/\\([\s\S])/g, (escape, next) => (next === '\n' ? '' : escape));
if (!after || hasHeredocExpansion(continued)) {
return { issue: {
type: 'unverifiable',
message: 'Cannot validate a commit message that adds commands or expansions to its here-document',
suggestion: 'Write the whole message inside the here-document'
} };
}
const tail = after[1].replace(/\\([\n$`"\\])/g, (escape, next) => (next === '\n' ? '' : next));
const withTail = body => (tail ? body.replace(/\n+$/, '') + tail : body);
// An unquoted here-document also loses the backslash before $, ` and \.
const body = heredoc.expands ? heredoc.body.replace(/\\([$`\\])/g, '$1') : heredoc.body;
const message = withTail(body);
const bash32Message = heredoc.bash32Body === null ? null : withTail(heredoc.bash32Body);
const note = bash32Message !== null && subjectOf(bash32Message) !== subjectOf(message)
? {
type: 'shell-dependent',
message: 'Bash 3.2 joins a subject line that ends in a backslash with the next line, even with a quoted delimiter',
suggestion: 'Do not end the subject line with a backslash'
}
: null;
return { message, note };
}
/**
* Validate commit message format
* @param {string} command
@@ -173,18 +277,32 @@ function findFileIssues(filePath) {
*/
function validateCommitMessage(command) {
// Extract commit message from command (quote-aware: when quoted, capture to the
// matching closing quote, consuming escaped chars (\") 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*$)/);
// matching closing quote, consuming escaped chars (\", and a backslash before a
// 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*$)/);
if (!messageMatch) return null;
const message = messageMatch[1] ?? messageMatch[2] ?? messageMatch[3];
// A message written as -m "$(cat <<'EOF' ... EOF)", as Claude Code writes them, is the
// body of that here-document. It is read from the command itself, since it may hold quotes.
const value = command.slice(messageMatch.index + messageMatch[0].indexOf('"') + 1);
const heredoc = messageMatch[1]?.startsWith('$(') ? heredocBody(value) : null;
const fromHeredoc = heredoc && readHeredocMessage(value, heredoc);
if (fromHeredoc?.issue) return { message: null, issues: [fromHeredoc.issue] };
// 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 = fromHeredoc?.message ?? doubleQuoted ?? messageMatch[2] ?? messageMatch[3];
// The format rules apply to the subject.
const subject = subjectOf(message);
const issues = [];
if (fromHeredoc?.note) issues.push(fromHeredoc.note);
// Check conventional commit format
const conventionalCommit = /^(feat|fix|docs|style|refactor|test|chore|build|ci|perf|revert)(\(.+\))?!?:\s*.+/;
if (!conventionalCommit.test(message)) {
const conventionalCommit = /^(feat|fix|docs|style|refactor|test|chore|build|ci|perf|revert)(\(.+\))?!?:\s*.+/;
if (!conventionalCommit.test(subject)) {
issues.push({
type: 'format',
message: 'Commit message does not follow conventional commit format',
@@ -193,17 +311,17 @@ function validateCommitMessage(command) {
}
// Check message length
if (message.length > 72) {
if (subject.length > 72) {
issues.push({
type: 'length',
message: `Commit message too long (${message.length} chars, max 72)`,
message: `Commit message too long (${subject.length} chars, max 72)`,
suggestion: 'Keep the first line under 72 characters'
});
}
// Check for lowercase first letter (conventional)
if (conventionalCommit.test(message)) {
const afterColon = message.split(':')[1];
if (conventionalCommit.test(subject)) {
const afterColon = subject.split(':')[1];
if (afterColon && /^[A-Z]/.test(afterColon.trim())) {
issues.push({
type: 'capitalization',
@@ -214,7 +332,7 @@ function validateCommitMessage(command) {
}
// Check for trailing period
if (message.endsWith('.')) {
if (subject.endsWith('.')) {
issues.push({
type: 'punctuation',
message: 'Commit message should not end with a period',
+179 -1
View File
@@ -502,7 +502,7 @@ if (test('captures full single-quoted -m message containing a double quote', ()
if (test('captures full double-quoted -m message with escaped inner quotes (not truncated)', () => {
const res = hook.validateCommitMessage('git commit -m "fix: say \\"hello\\" to the user"');
assert.ok(res, 'expected a validation result');
assert.strictEqual(res.message, 'fix: say \\"hello\\" to the user');
assert.strictEqual(res.message, 'fix: say "hello" to the user');
})) passed++; else failed++;
if (test('measures length of the full message past an apostrophe (not the truncated prefix)', () => {
@@ -511,6 +511,184 @@ if (test('measures length of the full message past an apostrophe (not the trunca
assert.strictEqual(res.message, subject);
assert.ok(res.issues.some(i => i.type === 'length'), 'full (>72) message should trigger a length issue');
})) passed++; else failed++;
// --- Subject line and here-document messages ---
if (test('checks only the subject line of a multi-line message', () => {
const res = hook.validateCommitMessage(
'git commit -m "fix: handle empty input\n\nThe parser crashed on an empty string. It now returns an empty list."'
);
assert.deepStrictEqual(res.issues, []);
})) passed++; else failed++;
if (test('reads the here-document message that Claude Code writes', () => {
const body = 'feat(hooks): add a check\n\nA body line that says why, and quotes "the case" it covers.';
const res = hook.validateCommitMessage(`git commit -m "$(cat <<'EOF'\n${body}\nEOF\n)"`);
assert.strictEqual(res.message, body);
assert.deepStrictEqual(res.issues, []);
})) passed++; else failed++;
if (test('still reports a bad subject inside a here-document', () => {
const res = hook.validateCommitMessage('git commit -m "$(cat <<EOF\nUpdate stuff.\n\nbody\nEOF\n)"');
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('joins a continued line of an unquoted here-document, as Bash does', () => {
const res = hook.validateCommitMessage('git commit -m "$(cat <<EOF\nfix: \\\nUpdate input.\nEOF\n)"');
assert.strictEqual(res.message, 'fix: Update input.');
assert.deepStrictEqual(res.issues.map(i => i.type), ['capitalization', 'punctuation']);
// A delimiter line right after a continued line belongs to the body
assert.strictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<EOF\nfix: a \\\nEOF\nb\nEOF\n)"').message,
'fix: a EOF\nb'
);
// An escaped backslash does not continue the line, and the escaping backslash is dropped
assert.strictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<EOF\nfix: a \\\\\nb \\` c\nEOF\n)"').message,
'fix: a \\\nb ` c'
);
})) passed++; else failed++;
if (test('keeps a quoted here-document literal and notes that Bash 3.2 joins it', () => {
const res = hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: \\\nUpdate input.\nEOF\n)"');
assert.strictEqual(res.message, 'fix: \\\nUpdate input.');
assert.deepStrictEqual(res.issues.map(i => i.type), ['shell-dependent']);
assert.deepStrictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: add a check\n\nA body line \\\nEOF\n)"').issues,
[]
);
})) passed++; else failed++;
if (test('reads text after the substitution as part of the message', () => {
const res = hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: update input\nEOF\n)."');
assert.strictEqual(res.message, 'fix: update input.');
assert.deepStrictEqual(res.issues.map(i => i.type), ['punctuation']);
assert.strictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: a\nEOF\n)\\$HOME"').message,
'fix: a$HOME'
);
// An expansion after the substitution is not literal text.
assert.deepStrictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: a\nEOF\n)$HOME"').issues.map(i => i.type),
['unverifiable']
);
// A line continuation inside it is dropped first: `$\<newline>HOME` is `$HOME`, `\$\<newline>HOME` is not.
assert.deepStrictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: a\nEOF\n)$\\\nHOME"').issues.map(i => i.type),
['unverifiable']
);
assert.strictEqual(
hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nfix: a\nEOF\n)\\$\\\nHOME"').message,
'fix: a$HOME'
);
})) passed++; else failed++;
if (process.platform !== 'win32') {
if (test('reads the message that Bash and Git record for a here-document', () => {
const bashMajor = Number(spawnSync('/bin/bash', ['-c', 'echo "${BASH_VERSINFO[0]}"'], { encoding: 'utf8' }).stdout);
const forms = [
['EOF', 'fix: \\\nUpdate input.'],
['EOF', 'fix: a \\\nEOF\nb'],
['EOF', 'fix: a \\\\\nb \\` c'],
['-EOF', '\tfix: \\\n\tUpdate input.'],
['-EOF', '\tfix: a\n\t\\\n\tb'],
["'EOF'", 'fix: \\\nUpdate input.'],
['"EOF"', 'fix: keep \\\\ and \\$HOME'],
["'EOF'", 'fix: update input', '.'],
["'EOF'", 'fix: update input\n\nbody line', ' and more'],
["'EOF'", 'fix: a', '\\$\\\nHOME'],
];
inTempRepo(repoDir => {
for (const [delimiter, body, suffix = ''] of forms) {
const command = `git commit -q --allow-empty -m "$(cat <<${delimiter}\n${body}\nEOF\n)${suffix}"`;
const run = spawnSync('/bin/bash', ['-c', command], { cwd: repoDir, encoding: 'utf8' });
assert.strictEqual(run.status, 0, run.stderr);
const recorded = spawnSync('git', ['log', '-1', '--format=%B'], { cwd: repoDir, encoding: 'utf8' }).stdout.trimEnd();
const res = hook.validateCommitMessage(command);
if (bashMajor < 4 && res.issues.some(i => i.type === 'shell-dependent')) {
assert.notStrictEqual(recorded, res.message, `Bash 3.2 joins the quoted body of ${JSON.stringify(command)}`);
} else {
assert.strictEqual(res.message, recorded, `message of ${JSON.stringify(command)}`);
}
}
});
})) 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');
assert.deepStrictEqual(res.issues, []);
// An escaped backslash before a newline is one backslash, and the newline stays
assert.strictEqual(hook.validateCommitMessage('git commit -m "fix: path C:\\\\\nbody"').message, 'fix: path C:\\\nbody');
// Bash removes the backslash only before $ ` " \ and a newline; before a CR it stays
assert.strictEqual(hook.validateCommitMessage('git commit -m "fix: keep path\\\r\nbody."').message, 'fix: keep path\\\r\nbody.');
assert.deepStrictEqual(hook.validateCommitMessage('git commit -m "fix: keep path\\\r\nbody."').issues, []);
assert.strictEqual(hook.validateCommitMessage('git commit -m "fix: cost \\$5 in \\d+ steps"').message, 'fix: cost $5 in \\d+ steps');
})) passed++; else failed++;
if (test('reads a here-document whose body has a backslash at the end of a line', () => {
const res = hook.validateCommitMessage('git commit -m "$(cat <<\'EOF\'\nUpdate stuff.\n\nC:\\build\\\nEOF\n)"');
assert.ok(res, 'expected a validation result');
assert.strictEqual(res.message, 'Update stuff.\n\nC:\\build\\');
assert.deepStrictEqual(res.issues.map(i => i.type), ['format', 'punctuation']);
})) passed++; else failed++;
if (test('ends a here-document only at a line that holds just the delimiter', () => {
const res = hook.validateCommitMessage(
'git commit -m "$(cat <<\'EOF\'\nfix: keep reading\n\n EOF\nEOF \nmore body\nEOF\n)"'
);
assert.strictEqual(res.message, 'fix: keep reading\n\n EOF\nEOF \nmore body');
})) passed++; else failed++;
if (test('reads a <<- here-document without its leading tabs', () => {
const res = hook.validateCommitMessage('git commit -m "$(cat <<-"END"\n\tfix: tabbed subject\n\tEND\n)"');
assert.strictEqual(res.message, 'fix: tabbed subject');
assert.deepStrictEqual(res.issues, []);
})) passed++; else failed++;
if (test('needs the description on the subject line itself', () => {
const res = hook.validateCommitMessage('git commit -m "feat:\nadd a check"');
assert.ok(res.issues.some(i => i.type === 'format'), 'a subject with nothing after the colon is not conventional');
})) passed++; else failed++;
if (test('passes a valid here-document commit message end to end', () => {
inTempRepo(repoDir => {
writeAndStage(repoDir, 'index.js', 'const clean = true;\n');
const input = JSON.stringify({
tool_input: {
command: `git commit -m "$(cat <<'EOF'\nfix(hooks): read the message body\n\nA longer explanation that runs well past seventy-two characters in total.\nEOF\n)"`
}
});
const { result, stderr } = captureConsoleError(() => hook.evaluate(input));
assert.strictEqual(result.exitCode, 0);
assert.ok(!stderr.includes('Commit Message Issues'), `expected no message warnings, got: ${stderr}`);
assert.ok(stderr.includes('All checks passed'), `expected a pass, got: ${stderr}`);
});
})) passed++; else failed++;
if (test('handles hash-prefixed python comments and string false-positives', () => {
inTempRepo(repoDir => {
writeAndStage(repoDir, 'script.py', [