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)
extensions/diff-review/__tests__/core.test.ts
Addednew file mode 100644+89 / −0 text lines
1+import { afterEach, describe, expect, it } from "bun:test"; 2+import { execFile } from "node:child_process"; 3+import { mkdtemp, rm, writeFile } from "node:fs/promises"; 4+import { tmpdir } from "node:os"; 5+import { join } from "node:path"; 6+import { promisify } from "node:util"; 7+import { parsePatchFiles } from "@pierre/diffs"; 8+import { parseArgs } from "../args.js"; 9+import { collectDiff } from "../git.js"; 11+const execFileAsync = promisify(execFile); 12+const tempDirs: string[] = []; 14+afterEach(async () => { 16+ tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })), 20+async function tempRepo() { 21+ const repo = await mkdtemp(join(tmpdir(), "diff-review-core-")); 23+ await git(repo, ["init", "-q"]); 24+ await git(repo, ["config", "user.email", "review@example.invalid"]); 25+ await git(repo, ["config", "user.name", "Review"]); 29+async function git(cwd: string, args: string[]) { 30+ await execFileAsync("git", args, { cwd, maxBuffer: 20 * 1024 * 1024 }); 33+describe("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", 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([ 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", 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, 86+ expect(diff.files[0]?.path).toBe(String.raw`a\tb.txt`); 87+ expect(files[0]?.name).toBe(String.raw`a\tb.txt`); extensions/diff-review/__tests__/harness.test.ts
Modified+47 / −0 text lines
11import { afterEach, describe, expect, it } from "bun:test";import { afterEach, describe, expect, it } from "bun:test"; 2+import { execFile } from "node:child_process"; 3+import { writeFile } from "node:fs/promises"; 24import path from "node:path";import path from "node:path"; 5+import { promisify } from "node:util"; 47 createTestSession, createTestSession, 58 type TestSession, type TestSession, 69} from "@marcfargas/pi-test-harness";} from "@marcfargas/pi-test-harness"; 11+const execFileAsync = promisify(execFile); 12+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); 814describe("diff-review pi-test-harness", () => {describe("diff-review pi-test-harness", () => { 915 let t: TestSession | undefined; let t: TestSession | undefined; 2026 expect(t.session.extensionRunner.extensions).toHaveLength(1); expect(t.session.extensionRunner.extensions).toHaveLength(1); 2127 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath); expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath); 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"); 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", 55+ .uiCallsFor("notify") 57+ .map((call) => call.args[0]), 61+ .uiCallsFor("setStatus") 63+ .filter((call) => call.args[0] === "diff-review"), 68+async function git(cwd: string, args: string[]) { 69+ await execFileAsync("git", args, { cwd, maxBuffer: 20 * 1024 * 1024 }); extensions/diff-review/args.ts
Modified+10 / −3 text lines
1919 if (token === "--base") { if (token === "--base") { 2020 const value = tokens[++i]; const value = tokens[++i]; 2121 if (!value) throw new Error("--base requires a ref"); if (!value) throw new Error("--base requires a ref"); 22+ args.base = parseBaseRef(value); 2525 if (token.startsWith("--base=")) { 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)); 3029 if (token === "--files") { if (token === "--files") { 5756 return { kind: "working-tree", ...(args.files && { files: args.files }) }; return { kind: "working-tree", ...(args.files && { files: args.files }) }; 59+function 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"); 6067function parseFiles(value: string): string[] {function parseFiles(value: string): string[] { 6168 const files = value const files = value 6269 .split(",") .split(",") extensions/diff-review/git.ts
Modified+71 / −16 text lines
1717const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/; 1818const DIFF_GIT_HEADER = /^diff --git a\/(.*) b\/(.*)$/;const DIFF_GIT_HEADER = /^diff --git a\/(.*) b\/(.*)$/; 20+type ChangedFileSpec = { paths: string[]; displayPath: string }; 2022export async function collectDiff(export async function collectDiff( 2123 cwd: string, cwd: string, 2224 args: DiffReviewArgs, args: DiffReviewArgs, 2729 const pieces = await collectRenderableDiff(repoRoot, repoArgs); const pieces = await collectRenderableDiff(repoRoot, repoArgs); 2830 const parsed = parseUnifiedDiff(pieces.diffText); const parsed = parseUnifiedDiff(pieces.diffText); 2931 const skippedFiles = [...parsed.skippedFiles, ...pieces.skippedFiles]; 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", 35+ if (!hasRenderableFile && skippedFiles.length > 0) 3136 throw new Error( throw new Error( 3237 `No renderable diff; skipped oversized/binary files: ${skippedFiles.join(", ")}`, `No renderable diff; skipped oversized/binary files: ${skippedFiles.join(", ")}`, 5863async function collectRenderableDiff(cwd: string, args: DiffReviewArgs) {async function collectRenderableDiff(cwd: string, args: DiffReviewArgs) { 59- const files = await changedFiles(cwd, args); 64+ const specs = await changedFileSpecs(cwd, args); 6065 const chunks: string[] = []; const chunks: string[] = []; 6166 const skippedFiles: string[] = []; const skippedFiles: string[] = []; 6267 let totalBytes = 0; let totalBytes = 0; 64- for (const file of files) { 69+ for (const spec of specs) { 66- const chunk = await gitDiff( 68- diffArgs(args, [file]), 71+ const chunk = normalizeDiffHeaders( 72+ await gitDiff(cwd, diffArgs(args, spec.paths), MAX_FILE_DIFF_BYTES), 7174 const bytes = Buffer.byteLength(chunk, "utf8"); const bytes = Buffer.byteLength(chunk, "utf8"); 7275 if (totalBytes + bytes > MAX_DIFF_BYTES) { if (totalBytes + bytes > MAX_DIFF_BYTES) { 73- skippedFiles.push(`${file} (review diff limit)`); 76+ skippedFiles.push(`${spec.displayPath} (review diff limit)`); 7679 totalBytes += bytes; totalBytes += bytes; 7881 } catch (err) { } catch (err) { 7982 if (err instanceof DiffTooLargeError) if (err instanceof DiffTooLargeError) 8083 skippedFiles.push( 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)`, 8386 else throw err; else throw err; 8790 return { diffText: chunks.join(""), skippedFiles }; return { diffText: chunks.join(""), skippedFiles }; 90-async function changedFiles(cwd: string, args: DiffReviewArgs) { 91- const output = await git(cwd, nameOnlyArgs(args), { 93+async function changedFileSpecs( 95+ args: DiffReviewArgs, 96+): Promise<ChangedFileSpec[]> { 97+ const output = await git(cwd, nameStatusArgs(args), { 9298 maxBuffer: DEFAULT_GIT_BUFFER_BYTES, maxBuffer: DEFAULT_GIT_BUFFER_BYTES, 94- return output.split("\0").filter(Boolean); 100+ return parseNameStatus(output); 97103function diffArgs(args: DiffReviewArgs, files = args.files): string[] {function diffArgs(args: DiffReviewArgs, files = args.files): string[] { 101107 return out; return out; 104-function nameOnlyArgs(args: DiffReviewArgs): string[] { 105- const out = [...baseDiffArgs(args), "--name-only", "-z", "--"]; 110+function nameStatusArgs(args: DiffReviewArgs): string[] { 111+ const out = [...baseDiffArgs(args), "--name-status", "-z", "--"]; 106112 if (args.files) out.push(...args.files); if (args.files) out.push(...args.files); 107113 return out; return out; 116+function 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 }); 129+ const file = parts[i++]; 130+ if (file) specs.push({ paths: [file], displayPath: file }); 110135function baseDiffArgs(args: DiffReviewArgs): string[] {function baseDiffArgs(args: DiffReviewArgs): string[] { 111136 const out = [ const out = [ 117142 "--unified=3", "--unified=3", 119144 if (args.staged) out.push("--cached"); if (args.staged) out.push("--cached"); 120- if (args.base) out.push(`${args.base}...HEAD`); 146+ if (args.base.startsWith("-")) 147+ throw new Error("--base must be a git revision, not an option"); 148+ out.push(`${args.base}...HEAD`); 121150 return out; return out; 199228 return String(e.stderr ?? "").trim() || e.message || "git failed"; return String(e.stderr ?? "").trim() || e.message || "git failed"; 231+function normalizeDiffHeaders(diffText: string): string { 236+ /^diff --git ("(?:[^"\\]|\\.)+") ("(?:[^"\\]|\\.)+")$/.exec(line); 238+ return `diff --git ${gitPathToken(quotedDiff[1]!)} ${gitPathToken(quotedDiff[2]!)}`; 239+ const quotedHeader = /^(---|\+\+\+) ("(?:[^"\\]|\\.)+")$/.exec(line); 241+ return `${quotedHeader[1]} ${gitPathToken(quotedHeader[2]!)}`; 247+function gitPathToken(token: string): string { 248+ return token.startsWith('"') && token.endsWith('"') 249+ ? token.slice(1, -1) 202253function parseUnifiedDiff(function parseUnifiedDiff( 203254 diffText: string, diffText: string, 204255): Omit<CollectedDiff, "repoRoot" | "source" | "diffText"> {): Omit<CollectedDiff, "repoRoot" | "source" | "diffText"> { 263314function finishFile(state: DiffParserState) {function finishFile(state: DiffParserState) { 264315 const file = state.current; const file = state.current; 265316 if (!file) return; 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; 267322 state.diffIndex.set(file.file, file); state.diffIndex.set(file.file, file); 268323 state.files.push(summary(file)); state.files.push(summary(file)); 269324 state.current = undefined; state.current = undefined; extensions/diff-review/index.ts
Modified+9 / −6 text lines
2222 let state: ReviewState = { round: 0, findings: [], rounds: [] }; let state: ReviewState = { round: 0, findings: [], rounds: [] }; 2323 let active: ReviewServer | undefined; let active: ReviewServer | undefined; 2424 let restoring: Promise<void> | undefined; let restoring: Promise<void> | undefined; 25+ let shuttingDown = false; 2627 pi.on("session_start", async (_event, ctx) => { pi.on("session_start", async (_event, ctx) => { 28+ shuttingDown = false; 2729 state = restoreReviewState(ctx); state = restoreReviewState(ctx); 2830 const open = openFindings(state).length; const open = openFindings(state).length; 2931 if (open > 0 && ctx.hasUI) if (open > 0 && ctx.hasUI) 4042 pi.on("session_shutdown", async () => { pi.on("session_shutdown", async () => { 4144 active?.close("shutdown"); active?.close("shutdown"); 4245 active = undefined; active = undefined; 4346 restoring = undefined; restoring = undefined; 203206 server.result.then((result) => { server.result.then((result) => { 204207 if (active?.id === server.id) active = undefined; if (active?.id === server.id) active = undefined; 208+ if (shuttingDown || result.reason === "shutdown") return; 205209 ctx.ui.setStatus(STATUS_ID, undefined); ctx.ui.setStatus(STATUS_ID, undefined); 206- if (result.reason !== "shutdown") 207- appendLiveReview(ctx, { 210- reason: result.reason, 210+ appendLiveReview(ctx, { 213+ reason: result.reason, 212215 ctx.ui.notify( ctx.ui.notify( 213216 `/diff-review ended (${result.reason})`, `/diff-review ended (${result.reason})`, 214217 result.reason === "timeout" ? "warning" : "info", result.reason === "timeout" ? "warning" : "info",