Skip to content

Commit 8526829

Browse files
committed
fix: preserve private hook checks and diagnostics
1 parent 2fda157 commit 8526829

6 files changed

Lines changed: 411 additions & 120 deletions

‎scripts/pre-commit/format-staged.sh‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ fi
4242

4343
restage_files=()
4444
for file in "${files[@]}"; do
45-
if ! git check-ignore --no-index -q -- "$file"; then
45+
# check-ignore rejects global literal magic; ./ keeps leading-colon names literal too.
46+
if ! git --no-literal-pathspecs check-ignore --no-index -q -- "./$file"; then
4647
restage_files+=("$file")
4748
fi
4849
done

‎scripts/pre-commit/guard-staged-content.mjs‎

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,20 @@
11
#!/usr/bin/env node
22
import { spawnSync } from "node:child_process";
33
import { readFileSync } from "node:fs";
4+
import { promisify } from "node:util";
45

56
const ruleSetting = "hooks.blockedLiteralsFile";
6-
const decoder = new TextDecoder("utf-8", { fatal: true });
7+
// A leading BOM is a filename character in Git output, not an encoding marker.
8+
const pathDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
79
const maxBuffer = 16 * 1024 * 1024;
10+
// Enumerated paths stay literal in both scans and restaging; retain the commit's index/context.
11+
const gitEnv = {
12+
...process.env,
13+
GIT_LITERAL_PATHSPECS: "1",
14+
GIT_GLOB_PATHSPECS: "0",
15+
GIT_NOGLOB_PATHSPECS: "0",
16+
GIT_ICASE_PATHSPECS: "0",
17+
};
818
let rules = [];
919

1020
function redact(text) {
@@ -27,9 +37,15 @@ function redact(text) {
2737
return redacted + text.slice(cursor);
2838
}
2939

40+
class GuardFailure extends Error {
41+
constructor(message, code) {
42+
super(message);
43+
this.code = code;
44+
}
45+
}
46+
3047
function fail(message, code = 1) {
31-
process.stderr.write(redact(`[pre-commit] ${message}\n[pre-commit] FAILED (exit ${code})\n`));
32-
process.exit(code);
48+
throw new GuardFailure(message, code);
3349
}
3450

3551
function nulPaths(bytes) {
@@ -39,11 +55,12 @@ function nulPaths(bytes) {
3955
if (bytes.at(-1) !== 0) {
4056
throw new Error("Invalid path list");
4157
}
42-
return decoder.decode(bytes.subarray(0, -1)).split("\0");
58+
return pathDecoder.decode(bytes.subarray(0, -1)).split("\0");
4359
}
4460

4561
function git(args, input) {
46-
const result = spawnSync("git", ["--no-pager", "--literal-pathspecs", ...args], {
62+
const result = spawnSync("git", ["--no-pager", ...args], {
63+
env: gitEnv,
4764
input,
4865
maxBuffer,
4966
stdio: ["pipe", "pipe", "pipe"],
@@ -132,8 +149,8 @@ try {
132149
}
133150
if (configured.status === 0) {
134151
try {
135-
const rulePath = decoder.decode(configured.stdout).replace(/\n$/, "");
136-
rules = decoder
152+
const rulePath = pathDecoder.decode(configured.stdout).replace(/\n$/, "");
153+
rules = new TextDecoder("utf-8", { fatal: true })
137154
.decode(readFileSync(rulePath))
138155
.split(/\r?\n/)
139156
.filter((line) => line.length > 0);
@@ -152,21 +169,35 @@ try {
152169
// Check before the formatter's sequencer early return or any working-tree restaging.
153170
scan();
154171
const formatted = spawnSync("bash", ["scripts/pre-commit/format-staged.sh"], {
172+
env: gitEnv,
155173
maxBuffer,
156174
stdio: ["inherit", "pipe", "pipe"],
157175
});
158-
process.stdout.write(redact(formatted.stdout?.toString("utf8") ?? ""));
159-
process.stderr.write(redact(formatted.stderr?.toString("utf8") ?? ""));
176+
// An incomplete capture can cut through a literal, making safe redaction impossible.
160177
if (formatted.error || formatted.signal || formatted.status === null) {
161178
fail("Formatter could not complete. Check the formatting helpers and retry.");
162179
}
180+
// Git merges hook stdout/stderr: finish stdout before the terminal stderr diagnostics.
181+
await promisify(process.stdout.write.bind(process.stdout))(
182+
redact(formatted.stdout.toString("utf8")),
183+
);
184+
process.stderr.write(redact(formatted.stderr.toString("utf8")));
163185
if (formatted.status !== 0) {
164186
fail("Formatter failed. Fix the reported error and retry.", formatted.status);
165187
}
166188
// Formatting may change bytes or stage entirely new paths; enumerate the index again.
167189
scan();
168-
} catch {
169-
fail(
170-
`The staged scan could not complete. Check ${ruleSetting} and repository state, then retry.`,
190+
} catch (error) {
191+
const failure =
192+
error instanceof GuardFailure
193+
? error
194+
: new GuardFailure(
195+
`The staged scan could not complete. Check ${ruleSetting} and repository state, then retry.`,
196+
1,
197+
);
198+
process.stderr.write(
199+
redact(`[pre-commit] ${failure.message}\n[pre-commit] FAILED (exit ${failure.code})\n`),
171200
);
201+
// Abort the main flow, then let queued pipe writes drain before terminating.
202+
process.exitCode = failure.code;
172203
}

‎scripts/test-projects.test-support.mts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2253,6 +2253,10 @@ const EXACT_TOOLING_TARGETS = new Map<string, string[]>([
22532253
]);
22542254

22552255
const SEMANTIC_TOOLING_TARGET_PATTERNS: Array<[RegExp, string[]]> = [
2256+
[
2257+
/^(?:git-hooks\/pre-commit|scripts\/pre-commit\/(?:guard-staged-content\.mjs|filter-staged-files\.mjs|format-staged\.sh|run-node-tool\.sh)|test\/git-hooks-pre-commit\.test-support\.ts)$/u,
2258+
["test/git-hooks-pre-commit.test.ts", "test/git-hooks-pre-commit-boundaries.test.ts"],
2259+
],
22562260
[/^scripts\/pr$/u, ["pr-merge", "pr-merge-outcome", "pr-operation-lock", "pr-wrappers"]],
22572261
[
22582262
/^scripts\/pr-lib\/crabbox-gate-contract\.mjs$/u,
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
import { copyFileSync, readFileSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
2+
import path from "node:path";
3+
import { afterEach, describe, expect, it } from "vitest";
4+
import {
5+
commitArgs,
6+
createContentGuardFixture,
7+
literals,
8+
rulePath,
9+
ruleSetting,
10+
run,
11+
runFailure,
12+
stageContent as stage,
13+
writeExecutable,
14+
} from "./git-hooks-pre-commit.test-support.js";
15+
import { cleanupTempDirs } from "./helpers/temp-dir.js";
16+
17+
const tempDirs: string[] = [];
18+
const fixture = () => createContentGuardFixture(tempDirs);
19+
const failureLine = "[pre-commit] FAILED (exit 23)\n";
20+
21+
afterEach(() => cleanupTempDirs(tempDirs));
22+
23+
function expectBlocked(output: string, name: string): void {
24+
expect(output).toContain("Blocked staged content");
25+
expect(output).toContain(JSON.stringify(name));
26+
expect(output).not.toContain(literals[0]);
27+
expect(output).toContain("[pre-commit] FAILED (exit 1)\n");
28+
}
29+
30+
// Only the external formatter is simulated; it emits the working-tree input completely.
31+
function diagnosticFormatter(dir: string, stream: number, exitCode: number): void {
32+
writeExecutable(
33+
path.join(dir, "node_modules/.bin"),
34+
"oxfmt",
35+
`#!/usr/bin/env node
36+
const fs = require("node:fs");
37+
const payload = fs.readFileSync("payload.ts");
38+
let written = 0;
39+
while (written < payload.length) written += fs.writeSync(${stream}, payload, written, payload.length - written);
40+
process.exitCode = ${exitCode};
41+
`,
42+
);
43+
}
44+
45+
describe("pre-commit Git path identity", () => {
46+
it.each(["staged", "restaged"])("blocks the only BOM-prefixed path when %s", (mode) => {
47+
const dir = fixture();
48+
const name = "\uFEFFpayload.txt";
49+
stage(dir, name, mode === "staged" ? literals[0] : "clean\n");
50+
writeFileSync(path.join(dir, name), literals[0]);
51+
const result = runFailure(dir, "git", commitArgs);
52+
expectBlocked(result.stderr, name);
53+
expect(runFailure(dir, "git", ["rev-parse", "--verify", "HEAD"]).status).not.toBe(0);
54+
});
55+
56+
it("accepts a benign BOM path without searching its unchanged non-BOM counterpart", () => {
57+
const dir = fixture();
58+
stage(dir, "payload.txt", literals[0]);
59+
run(dir, "git", ["commit", "-qm", "historical fixture"]);
60+
const name = "\uFEFFpayload.txt";
61+
stage(dir, name, "clean\n");
62+
run(dir, "git", commitArgs);
63+
expect(run(dir, "git", ["show", `HEAD:${name}`])).toBe("clean");
64+
expect(run(dir, "git", ["show", "HEAD:payload.txt"])).toBe(literals[0]);
65+
});
66+
67+
it.each([rulePath, "\uFEFFprivate-rules.txt"])(
68+
"consumes a rule-file BOM but preserves the configured path: %s",
69+
(name) => {
70+
const dir = fixture();
71+
writeFileSync(path.join(dir, name), `\uFEFF${literals[0]}\n`);
72+
run(dir, "git", ["config", "--local", ruleSetting, name]);
73+
stage(dir, "payload.txt", literals[0]);
74+
expectBlocked(runFailure(dir, "git", commitArgs).stderr, "payload.txt");
75+
},
76+
);
77+
78+
it.each(["--glob-pathspecs", "--icase-pathspecs", "--noglob-pathspecs", "--literal-pathspecs"])(
79+
"keeps enumerated filenames literal under %s without private rules",
80+
(flag) => {
81+
const dir = fixture();
82+
run(dir, "git", ["config", "--local", "--unset", ruleSetting]);
83+
unlinkSync(path.join(dir, rulePath));
84+
const name = "chosen[1].txt";
85+
stage(dir, name, "staged\n");
86+
stage(dir, ":(exclude)clean.txt", "literal colon\n");
87+
writeFileSync(path.join(dir, name), "restaged\n");
88+
expect(
89+
run(dir, "bash", ["-c", 'exec git "$@" 2>&1', "hook-proof", flag, ...commitArgs]),
90+
).toBe("");
91+
expect(run(dir, "git", ["show", `HEAD:${name}`])).toBe("restaged");
92+
expect(run(dir, "git", ["show", "HEAD::(exclude)clean.txt"])).toBe("literal colon");
93+
},
94+
);
95+
96+
it.each(
97+
["--glob-pathspecs", "--icase-pathspecs"].flatMap((flag) =>
98+
["only", "alternate"].map((index) => ({ flag, index })),
99+
),
100+
)("preserves $index commit index authority under $flag", ({ flag, index }) => {
101+
const dir = fixture();
102+
const name = "chosen[1].txt";
103+
stage(dir, name, "original\n");
104+
stage(dir, "excluded.txt", "original excluded\n");
105+
run(dir, "git", ["commit", "-qm", "initial fixture"]);
106+
const alternateIndex = path.join(dir, ".git/selected-index");
107+
copyFileSync(path.join(dir, ".git/index"), alternateIndex);
108+
stage(dir, "excluded.txt", literals[0]);
109+
const env =
110+
index === "alternate"
111+
? { GIT_INDEX_FILE: alternateIndex, GIT_DIR: path.join(dir, ".git"), GIT_WORK_TREE: dir }
112+
: undefined;
113+
const select = flag === "--glob-pathspecs" ? "chosen*.txt" : "CHOSEN[1].TXT";
114+
const args = [flag, ...commitArgs, ...(index === "only" ? ["--only", "--", select] : [])];
115+
writeFileSync(path.join(dir, name), "selected staged\n");
116+
run(dir, "git", ["--literal-pathspecs", "add", "--", name], env);
117+
writeFileSync(path.join(dir, name), "selected restaged\n");
118+
run(dir, "git", args, env);
119+
expect(run(dir, "git", ["show", `HEAD:${name}`])).toBe("selected restaged");
120+
expect(run(dir, "git", ["show", "HEAD:excluded.txt"])).toBe("original excluded");
121+
expect(run(dir, "git", ["show", ":excluded.txt"])).toBe(literals[0]);
122+
expect(readFileSync(path.join(dir, "excluded.txt"), "utf8")).toBe(literals[0]);
123+
const head = run(dir, "git", ["rev-parse", "HEAD"]);
124+
writeFileSync(path.join(dir, name), literals[0]);
125+
run(dir, "git", ["--literal-pathspecs", "add", "--", name], env);
126+
expectBlocked(runFailure(dir, "git", args, env).stderr, name);
127+
expect(run(dir, "git", ["rev-parse", "HEAD"])).toBe(head);
128+
expect(run(dir, "git", ["show", ":excluded.txt"])).toBe(literals[0]);
129+
});
130+
});
131+
132+
describe("pre-commit formatter capture", () => {
133+
it.each([1, 2])("discards incomplete overflow captures from stream %s", (stream) => {
134+
const dir = fixture();
135+
const token = "SYNTHETIC_CAPTURE_".padEnd(128, "x");
136+
writeFileSync(path.join(dir, rulePath), `${token}\n`);
137+
stage(dir, "payload.ts", "clean\n");
138+
const cap = 16 * 1024 * 1024;
139+
const payload = ".".repeat(cap - 131168) + token.repeat(2048) + "ACTIONABLE_TAIL\n";
140+
writeFileSync(path.join(dir, "payload.ts"), payload);
141+
diagnosticFormatter(dir, stream, 23);
142+
const result = runFailure(dir, "git", commitArgs);
143+
const output = result.stdout + result.stderr;
144+
expect(output).toContain("Formatter could not complete");
145+
// No padding, redacted capture, or cut literal may be replayed on either stream.
146+
expect(output.length).toBeLessThan(300);
147+
expect(output).not.toMatch(/\.{2}|SYNTHETIC|x{2}|REDACTED|ACTIONABLE_TAIL/);
148+
expect(output).toContain("[pre-commit] FAILED (exit 1)\n");
149+
expect(runFailure(dir, "git", ["rev-parse", "--verify", "HEAD"]).status).not.toBe(0);
150+
});
151+
152+
it.each([1, 2])("preserves and redacts complete below-cap output on stream %s", (stream) => {
153+
const dir = fixture();
154+
stage(dir, "payload.ts", "clean\n");
155+
const payload = ".".repeat(256) + `${literals[0]}\n`.repeat(2048) + "ACTIONABLE_TAIL\n";
156+
writeFileSync(path.join(dir, "payload.ts"), payload);
157+
diagnosticFormatter(dir, stream, 23);
158+
const result = runFailure(dir, "bash", ["git-hooks/pre-commit"]);
159+
const output = result.stdout + result.stderr;
160+
expect(result.status).toBe(23);
161+
expect(output.startsWith(payload.replaceAll(literals[0], "[REDACTED]"))).toBe(true);
162+
expect(output).not.toContain(literals[0]);
163+
expect(output.endsWith(failureLine)).toBe(true);
164+
// Formatter failure must abort before restaging or the second scan.
165+
expect(run(dir, "git", ["show", ":payload.ts"])).toBe("clean");
166+
});
167+
168+
it("discards captures when the formatter shell is terminated by a signal", () => {
169+
const dir = fixture();
170+
stage(dir, "payload.ts", "clean\n");
171+
writeExecutable(
172+
path.join(dir, "node_modules/.bin"),
173+
"oxfmt",
174+
`#!/usr/bin/env bash
175+
printf 'INCOMPLETE_STDOUT'
176+
printf 'INCOMPLETE_STDERR' >&2
177+
kill -TERM "$PPID"
178+
`,
179+
);
180+
const result = runFailure(dir, "git", commitArgs);
181+
expect(result.stdout + result.stderr).not.toContain("INCOMPLETE");
182+
expect(result.stderr).toContain("Formatter could not complete");
183+
expect(result.stderr).toContain("FAILED (exit 1)");
184+
});
185+
186+
it("fails safely when the formatter shell cannot be spawned", () => {
187+
const dir = fixture();
188+
stage(dir, "payload.txt", "clean\n");
189+
const bin = path.join(dir, "bin");
190+
symlinkSync(process.execPath, path.join(bin, "node"));
191+
symlinkSync(run(dir, "which", ["git"]), path.join(bin, "git"));
192+
const result = runFailure(dir, "/bin/bash", ["git-hooks/pre-commit"], { PATH: bin });
193+
expect(result.status).toBe(1);
194+
expect(result.stdout).toBe("");
195+
expect(result.stderr).toContain("Formatter could not complete");
196+
expect(result.stderr).toContain("FAILED (exit 1)");
197+
});
198+
199+
it.each([true, false].flatMap((configured) => [1, 2].map((stream) => ({ configured, stream }))))(
200+
"drains piped diagnostics: rules=$configured stream=$stream",
201+
({ configured, stream }) => {
202+
const dir = fixture();
203+
if (!configured) {
204+
run(dir, "git", ["config", "--local", "--unset", ruleSetting]);
205+
unlinkSync(path.join(dir, rulePath));
206+
}
207+
stage(dir, "payload.ts", "clean\n");
208+
const payload = "public diagnostic context\n".repeat(4000) + "ACTIONABLE_FINAL_DETAIL\n";
209+
writeFileSync(path.join(dir, "payload.ts"), payload);
210+
diagnosticFormatter(dir, stream, 23);
211+
for (const [cmd, args] of [
212+
["bash", ["git-hooks/pre-commit"]],
213+
["git", commitArgs],
214+
] as const) {
215+
const result = runFailure(dir, cmd, [...args]);
216+
const output = result.stdout + result.stderr;
217+
expect(result.status).toBe(cmd === "git" ? 1 : 23);
218+
expect(output.startsWith(payload)).toBe(true);
219+
expect(output.endsWith(failureLine)).toBe(true);
220+
expect(output.match(/\[pre-commit\] FAILED/g)).toHaveLength(1);
221+
}
222+
diagnosticFormatter(dir, stream, 0);
223+
expect(run(dir, "bash", ["-c", 'exec git "$@" 2>&1', "hook-proof", ...commitArgs])).toBe(
224+
payload.trim(),
225+
);
226+
expect(run(dir, "git", ["show", "HEAD:payload.ts"])).toBe(payload.trim());
227+
},
228+
);
229+
});

0 commit comments

Comments
 (0)