git-pr-brief/lib/parse-diff.mjs
caelum0x 753fe98687 feat: git-pr-brief 1.0.0, cross-host agent-shaped PR/MR risk brief
Published to npm (git-pr-brief@1.0.0). Fetches a PR/MR's raw diff over
plain HTTPS (GitHub, GitLab, Rithub/Gitea, Bitbucket, or a raw .diff URL)
and computes offline risk flags (lockfile, env, migration, CI config,
large diff, missing tests, possible secrets) an agent can branch on via
--json / --fail-on-flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:04:45 +03:00

77 lines
1.8 KiB
JavaScript

// Minimal unified-diff parser. No dependencies, no shelling out to git —
// this works on a diff fetched from any host's raw-diff endpoint, so the
// tool never needs a local clone.
function newFile(path) {
return {
path,
additions: 0,
deletions: 0,
binary: false,
newFile: false,
deletedFile: false,
renamedFrom: null,
};
}
export function parseDiff(diffText) {
const files = [];
let current = null;
const lines = diffText.split("\n");
for (const line of lines) {
const headerMatch = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
if (headerMatch) {
current = newFile(headerMatch[2]);
files.push(current);
continue;
}
if (!current) continue;
if (line.startsWith("rename from ")) {
current.renamedFrom = line.slice("rename from ".length);
continue;
}
if (line.startsWith("new file mode")) {
current.newFile = true;
continue;
}
if (line.startsWith("deleted file mode")) {
current.deletedFile = true;
continue;
}
if (line.startsWith("Binary files ") || line.startsWith("GIT binary patch")) {
current.binary = true;
continue;
}
if (line.startsWith("+++ /dev/null")) {
current.deletedFile = true;
continue;
}
if (line.startsWith("--- /dev/null")) {
current.newFile = true;
continue;
}
if (line.startsWith("+") && !line.startsWith("+++")) {
current.additions += 1;
continue;
}
if (line.startsWith("-") && !line.startsWith("---")) {
current.deletions += 1;
continue;
}
}
const totals = files.reduce(
(acc, f) => {
acc.additions += f.additions;
acc.deletions += f.deletions;
if (f.binary) acc.binaryFiles += 1;
return acc;
},
{ additions: 0, deletions: 0, binaryFiles: 0 }
);
return { files, totals };
}