repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/diff-review/git.ts

Raw
File outline
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { MAX_DIFF_BYTES } from "./constants.js";
import { sourceFromArgs, type DiffReviewArgs } from "./args.js";
import type { CollectedDiff, DiffFileStatus, DiffIndex, IndexedFileDiff } from "./types.js";

const execFileAsync = promisify(execFile);

export async function collectDiff(cwd: string, args: DiffReviewArgs): Promise<CollectedDiff> {
	const repoRoot = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
	const source = sourceFromArgs(args);
	const diffArgs = buildDiffArgs(args);
	const diffText = await git(cwd, diffArgs, { maxBuffer: MAX_DIFF_BYTES + 1024 });
	if (Buffer.byteLength(diffText, "utf8") > MAX_DIFF_BYTES) throw new Error(`Diff exceeds ${Math.round(MAX_DIFF_BYTES / 1024 / 1024)} MiB limit`);
	const parsed = parseUnifiedDiff(diffText);
	return { repoRoot, source, diffText, ...parsed };
}

function buildDiffArgs(args: DiffReviewArgs): string[] {
	const base = ["diff", "--no-ext-diff", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--unified=3"];
	if (args.staged) base.push("--cached");
	if (args.base) base.push(`${args.base}...HEAD`);
	base.push("--");
	if (args.files) base.push(...args.files);
	return base;
}

async function git(cwd: string, args: string[], options: { maxBuffer?: number } = {}): Promise<string> {
	try {
		const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: options.maxBuffer ?? 1024 * 1024 * 10 });
		return typeof stdout === "string" ? stdout : String(stdout);
	} catch (err) {
		const anyErr = err as { stderr?: string | Buffer; message?: string };
		const stderr = anyErr.stderr ? String(anyErr.stderr).trim() : "";
		throw new Error(stderr || anyErr.message || "git failed");
	}
}

function parseUnifiedDiff(diffText: string): Omit<CollectedDiff, "repoRoot" | "source" | "diffText"> {
	const diffIndex: DiffIndex = new Map();
	const files: Array<{ path: string; prevPath?: string; status: DiffFileStatus; additions: number; deletions: number }> = [];
	const skippedFiles: string[] = [];
	let current: IndexedFileDiff | undefined;
	let oldLine = 0;
	let newLine = 0;

	const finish = () => {
		if (!current) return;
		if (current.status === "binary") skippedFiles.push(current.file);
		diffIndex.set(current.file, current);
		files.push({
			path: current.file,
			...(current.prevFile && current.prevFile !== current.file && { prevPath: current.prevFile }),
			status: current.status,
			additions: current.additions.size,
			deletions: current.deletions.size,
		});
	};

	for (const rawLine of diffText.split(/\r?\n/)) {
		const line = rawLine;
		if (line.startsWith("diff --git ")) {
			finish();
			const { oldPath, newPath } = parseDiffGitLine(line);
			current = { file: newPath, prevFile: oldPath, status: "modified", additions: new Map(), deletions: new Map() };
			oldLine = 0;
			newLine = 0;
			continue;
		}
		if (!current) continue;
		if (line.startsWith("new file mode ")) { current.status = "added"; continue; }
		if (line.startsWith("deleted file mode ")) { current.status = "deleted"; continue; }
		if (line.startsWith("similarity index ") || line.startsWith("rename from ") || line.startsWith("rename to ")) {
			if (current.status !== "added" && current.status !== "deleted") current.status = "renamed";
			continue;
		}
		if (line.startsWith("Binary files ")) { current.status = "binary"; continue; }
		if (line.startsWith("--- ")) {
			const path = parseHeaderPath(line.slice(4));
			if (path && path !== "/dev/null") current.prevFile = path;
			continue;
		}
		if (line.startsWith("+++ ")) {
			const path = parseHeaderPath(line.slice(4));
			if (path && path !== "/dev/null") current.file = path;
			continue;
		}
		if (line.startsWith("@@ ")) {
			const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
			if (match) {
				oldLine = Number(match[1]);
				newLine = Number(match[2]);
			}
			continue;
		}
		if (!oldLine && !newLine) continue;
		if (line.startsWith("+")) {
			current.additions.set(newLine, line.slice(1));
			newLine++;
			continue;
		}
		if (line.startsWith("-")) {
			current.deletions.set(oldLine, line.slice(1));
			oldLine++;
			continue;
		}
		if (line.startsWith(" ")) {
			oldLine++;
			newLine++;
		}
	}
	finish();

	return {
		files,
		diffIndex,
		skippedFiles,
		additions: files.reduce((sum, file) => sum + file.additions, 0),
		deletions: files.reduce((sum, file) => sum + file.deletions, 0),
	};
}

function parseDiffGitLine(line: string) {
	const match = line.match(/^diff --git a\/(.*) b\/(.*)$/);
	return { oldPath: match?.[1] ?? "", newPath: match?.[2] ?? match?.[1] ?? "" };
}

function parseHeaderPath(header: string): string | undefined {
	const trimmed = header.trim();
	if (trimmed === "/dev/null") return trimmed;
	if (trimmed.startsWith("a/") || trimmed.startsWith("b/")) return trimmed.slice(2);
	return trimmed.split(/\s+/)[0];
}