repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(diff-review): harden diff collection

927dc29003700035215b001c16af7e91db9a5863

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

+226 / −25 text lines

Diff layout

extensions/diff-review/__tests__/core.test.ts

Added
new file mode 100644

+89 / −0 text lines

1import { afterEach, describe, expect, it } from "bun:test";
2import { execFile } from "node:child_process";
3import { mkdtemp, rm, writeFile } from "node:fs/promises";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { promisify } from "node:util";
7import { parsePatchFiles } from "@pierre/diffs";
8import { parseArgs } from "../args.js";
9import { collectDiff } from "../git.js";
11const execFileAsync = promisify(execFile);
12const tempDirs: string[] = [];
14afterEach(async () => {
15 await Promise.all(
16 tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })),
17 );
18});
20async function tempRepo() {
21 const repo = await mkdtemp(join(tmpdir(), "diff-review-core-"));
22 tempDirs.push(repo);
23 await git(repo, ["init", "-q"]);
24 await git(repo, ["config", "user.email", "review@example.invalid"]);
25 await git(repo, ["config", "user.name", "Review"]);
26 return repo;
27}
29async function git(cwd: string, args: string[]) {
30 await execFileAsync("git", args, { cwd, maxBuffer: 20 * 1024 * 1024 });
31}
33describe("diff-review core regressions", () => {
34 it("rejects option-shaped base refs before invoking git", () => {
35 expect(() => parseArgs("--base=--output=/tmp/diff-review-pwn")).toThrow(
36 "--base must be a git revision, not an option",
37 );
38 });
40 it("preserves staged rename metadata when collecting per-file diffs", async () => {
41 const repo = await tempRepo();
42 await writeFile(join(repo, "old.txt"), "one\n");
43 await git(repo, ["add", "old.txt"]);
44 await git(repo, ["commit", "-qm", "initial"]);
45 await git(repo, ["mv", "old.txt", "new.txt"]);
47 const diff = await collectDiff(repo, parseArgs("--staged"));
49 expect(diff.diffText).toContain("diff --git a/old.txt b/new.txt");
50 expect(diff.files).toEqual([
51 {
52 path: "new.txt",
53 prevPath: "old.txt",
54 status: "renamed",
55 additions: 0,
56 deletions: 0,
57 },
58 ]);
59 });
61 it("rejects binary-only diffs instead of launching an empty review", async () => {
62 const repo = await tempRepo();
63 await writeFile(join(repo, "bin.dat"), Buffer.from([0, 1, 2]));
64 await git(repo, ["add", "bin.dat"]);
65 await git(repo, ["commit", "-qm", "initial"]);
66 await writeFile(join(repo, "bin.dat"), Buffer.from([3, 4, 5]));
68 await expect(collectDiff(repo, parseArgs(""))).rejects.toThrow(
69 "No renderable diff; skipped oversized/binary files: bin.dat",
70 );
71 });
73 it("normalizes quoted git paths into Pierre-parseable diff headers", async () => {
74 const repo = await tempRepo();
75 const path = "a\tb.txt";
76 await writeFile(join(repo, path), "one\n");
77 await git(repo, ["add", path]);
78 await git(repo, ["commit", "-qm", "initial"]);
79 await writeFile(join(repo, path), "two\n");
81 const diff = await collectDiff(repo, parseArgs(""));
82 const files = parsePatchFiles(diff.diffText, "quoted-path", true).flatMap(
83 (patch) => patch.files,
84 );
86 expect(diff.files[0]?.path).toBe(String.raw`a\tb.txt`);
87 expect(files[0]?.name).toBe(String.raw`a\tb.txt`);
88 });
89});

extensions/diff-review/__tests__/harness.test.ts

Modified

+47 / −0 text lines

11import { afterEach, describe, expect, it } from "bun:test";
2import { execFile } from "node:child_process";
3import { writeFile } from "node:fs/promises";
24import path from "node:path";
5import { promisify } from "node:util";
36import {
47 createTestSession,
58 type TestSession,
69} from "@marcfargas/pi-test-harness";
11const execFileAsync = promisify(execFile);
12const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
814describe("diff-review pi-test-harness", () => {
915 let t: TestSession | undefined;
2026 expect(t.session.extensionRunner.extensions).toHaveLength(1);
2127 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
2228 });
30 it("does not mutate UI after shutdown closes an active review server", async () => {
31 const extensionPath = path.resolve(import.meta.dir, "../index.ts");
32 t = await createTestSession({ extensions: [extensionPath] });
33 await git(t.cwd, ["init", "-q"]);
34 await git(t.cwd, ["config", "user.email", "review@example.invalid"]);
35 await git(t.cwd, ["config", "user.name", "Review"]);
36 await writeFile(path.join(t.cwd, "file.txt"), "old\n");
37 await git(t.cwd, ["add", "file.txt"]);
38 await git(t.cwd, ["commit", "-qm", "initial"]);
39 await writeFile(path.join(t.cwd, "file.txt"), "new\n");
41 const command =
42 t.session.extensionRunner.extensions[0].commands.get("diff-review");
43 await command.handler("", t.session.extensionRunner.createCommandContext());
44 const notifyCount = t.events.uiCallsFor("notify").length;
45 const statusCount = t.events.uiCallsFor("setStatus").length;
47 await t.session.extensionRunner.emit({
48 type: "session_shutdown",
49 reason: "quit",
50 });
51 await sleep(30);
53 expect(
54 t.events
55 .uiCallsFor("notify")
56 .slice(notifyCount)
57 .map((call) => call.args[0]),
58 ).toEqual([]);
59 expect(
60 t.events
61 .uiCallsFor("setStatus")
62 .slice(statusCount)
63 .filter((call) => call.args[0] === "diff-review"),
64 ).toEqual([]);
65 });
2366});
68async function git(cwd: string, args: string[]) {
69 await execFileAsync("git", args, { cwd, maxBuffer: 20 * 1024 * 1024 });
70}

extensions/diff-review/args.ts

Modified

+10 / −3 text lines

1919 if (token === "--base") {
2020 const value = tokens[++i];
2121 if (!value) throw new Error("--base requires a ref");
22 args.base = value;
22 args.base = parseBaseRef(value);
2323 continue;
2424 }
2525 if (token.startsWith("--base=")) {
26 args.base = token.slice("--base=".length);
27 if (!args.base) throw new Error("--base requires a ref");
26 args.base = parseBaseRef(token.slice("--base=".length));
2827 continue;
2928 }
3029 if (token === "--files") {
5756 return { kind: "working-tree", ...(args.files && { files: args.files }) };
59function parseBaseRef(value: string): string {
60 if (!value) throw new Error("--base requires a ref");
61 if (value.startsWith("-"))
62 throw new Error("--base must be a git revision, not an option");
63 if (value.includes("\0")) throw new Error("--base cannot contain NUL");
64 return value;
65}
6067function parseFiles(value: string): string[] {
6168 const files = value
6269 .split(",")

extensions/diff-review/git.ts

Modified

+71 / −16 text lines

1717const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
1818const DIFF_GIT_HEADER = /^diff --git a\/(.*) b\/(.*)$/;
20type ChangedFileSpec = { paths: string[]; displayPath: string };
2022export async function collectDiff(
2123 cwd: string,
2224 args: DiffReviewArgs,
2729 const pieces = await collectRenderableDiff(repoRoot, repoArgs);
2830 const parsed = parseUnifiedDiff(pieces.diffText);
2931 const skippedFiles = [...parsed.skippedFiles, ...pieces.skippedFiles];
30 if (!pieces.diffText.trim() && skippedFiles.length > 0)
32 const hasRenderableFile = parsed.files.some(
33 (file) => file.status !== "binary",
34 );
35 if (!hasRenderableFile && skippedFiles.length > 0)
3136 throw new Error(
3237 `No renderable diff; skipped oversized/binary files: ${skippedFiles.join(", ")}`,
3338 );
5863async function collectRenderableDiff(cwd: string, args: DiffReviewArgs) {
59 const files = await changedFiles(cwd, args);
64 const specs = await changedFileSpecs(cwd, args);
6065 const chunks: string[] = [];
6166 const skippedFiles: string[] = [];
6267 let totalBytes = 0;
64 for (const file of files) {
69 for (const spec of specs) {
6570 try {
66 const chunk = await gitDiff(
67 cwd,
68 diffArgs(args, [file]),
69 MAX_FILE_DIFF_BYTES,
71 const chunk = normalizeDiffHeaders(
72 await gitDiff(cwd, diffArgs(args, spec.paths), MAX_FILE_DIFF_BYTES),
7073 );
7174 const bytes = Buffer.byteLength(chunk, "utf8");
7275 if (totalBytes + bytes > MAX_DIFF_BYTES) {
73 skippedFiles.push(`${file} (review diff limit)`);
76 skippedFiles.push(`${spec.displayPath} (review diff limit)`);
7477 continue;
7578 }
7679 totalBytes += bytes;
7881 } catch (err) {
7982 if (err instanceof DiffTooLargeError)
8083 skippedFiles.push(
81 `${file} (${Math.round(MAX_FILE_DIFF_BYTES / 1024 / 1024)} MiB per-file limit)`,
84 `${spec.displayPath} (${Math.round(MAX_FILE_DIFF_BYTES / 1024 / 1024)} MiB per-file limit)`,
8285 );
8386 else throw err;
8487 }
8790 return { diffText: chunks.join(""), skippedFiles };
90async function changedFiles(cwd: string, args: DiffReviewArgs) {
91 const output = await git(cwd, nameOnlyArgs(args), {
93async function changedFileSpecs(
94 cwd: string,
95 args: DiffReviewArgs,
96): Promise<ChangedFileSpec[]> {
97 const output = await git(cwd, nameStatusArgs(args), {
9298 maxBuffer: DEFAULT_GIT_BUFFER_BYTES,
9399 });
94 return output.split("\0").filter(Boolean);
100 return parseNameStatus(output);
97103function diffArgs(args: DiffReviewArgs, files = args.files): string[] {
101107 return out;
104function nameOnlyArgs(args: DiffReviewArgs): string[] {
105 const out = [...baseDiffArgs(args), "--name-only", "-z", "--"];
110function nameStatusArgs(args: DiffReviewArgs): string[] {
111 const out = [...baseDiffArgs(args), "--name-status", "-z", "--"];
106112 if (args.files) out.push(...args.files);
107113 return out;
116function parseNameStatus(output: string): ChangedFileSpec[] {
117 const parts = output.split("\0");
118 const specs: ChangedFileSpec[] = [];
119 for (let i = 0; i < parts.length; ) {
120 const status = parts[i++];
121 if (!status) continue;
122 if (status.startsWith("R") || status.startsWith("C")) {
123 const oldPath = parts[i++];
124 const newPath = parts[i++];
125 if (oldPath && newPath)
126 specs.push({ paths: [oldPath, newPath], displayPath: newPath });
127 continue;
128 }
129 const file = parts[i++];
130 if (file) specs.push({ paths: [file], displayPath: file });
131 }
132 return specs;
133}
110135function baseDiffArgs(args: DiffReviewArgs): string[] {
111136 const out = [
112137 "diff",
117142 "--unified=3",
118143 ];
119144 if (args.staged) out.push("--cached");
120 if (args.base) out.push(`${args.base}...HEAD`);
145 if (args.base) {
146 if (args.base.startsWith("-"))
147 throw new Error("--base must be a git revision, not an option");
148 out.push(`${args.base}...HEAD`);
149 }
121150 return out;
199228 return String(e.stderr ?? "").trim() || e.message || "git failed";
231function normalizeDiffHeaders(diffText: string): string {
232 return diffText
233 .split(/\r?\n/)
234 .map((line) => {
235 const quotedDiff =
236 /^diff --git ("(?:[^"\\]|\\.)+") ("(?:[^"\\]|\\.)+")$/.exec(line);
237 if (quotedDiff)
238 return `diff --git ${gitPathToken(quotedDiff[1]!)} ${gitPathToken(quotedDiff[2]!)}`;
239 const quotedHeader = /^(---|\+\+\+) ("(?:[^"\\]|\\.)+")$/.exec(line);
240 if (quotedHeader)
241 return `${quotedHeader[1]} ${gitPathToken(quotedHeader[2]!)}`;
242 return line;
243 })
244 .join("\n");
245}
247function gitPathToken(token: string): string {
248 return token.startsWith('"') && token.endsWith('"')
249 ? token.slice(1, -1)
250 : token;
251}
202253function parseUnifiedDiff(
203254 diffText: string,
204255): Omit<CollectedDiff, "repoRoot" | "source" | "diffText"> {
263314function finishFile(state: DiffParserState) {
264315 const file = state.current;
265316 if (!file) return;
266 if (file.status === "binary") state.skippedFiles.push(file.file);
317 if (file.status === "binary") {
318 state.skippedFiles.push(file.file);
319 state.current = undefined;
320 return;
321 }
267322 state.diffIndex.set(file.file, file);
268323 state.files.push(summary(file));
269324 state.current = undefined;

extensions/diff-review/index.ts

Modified

+9 / −6 text lines

2222 let state: ReviewState = { round: 0, findings: [], rounds: [] };
2323 let active: ReviewServer | undefined;
2424 let restoring: Promise<void> | undefined;
25 let shuttingDown = false;
2627 pi.on("session_start", async (_event, ctx) => {
28 shuttingDown = false;
2729 state = restoreReviewState(ctx);
2830 const open = openFindings(state).length;
2931 if (open > 0 && ctx.hasUI)
3840 });
4042 pi.on("session_shutdown", async () => {
43 shuttingDown = true;
4144 active?.close("shutdown");
4245 active = undefined;
4346 restoring = undefined;
202205 });
203206 server.result.then((result) => {
204207 if (active?.id === server.id) active = undefined;
208 if (shuttingDown || result.reason === "shutdown") return;
205209 ctx.ui.setStatus(STATUS_ID, undefined);
206 if (result.reason !== "shutdown")
207 appendLiveReview(ctx, {
208 ...live,
209 status: "closed",
210 reason: result.reason,
211 });
210 appendLiveReview(ctx, {
211 ...live,
212 status: "closed",
213 reason: result.reason,
214 });
212215 ctx.ui.notify(
213216 `/diff-review ended (${result.reason})`,
214217 result.reason === "timeout" ? "warning" : "info",