← Files Daybreak Defense FactoryARCHIVED FILE
.internal/defense-factory-ui/src/workbench/patch-diff-context.ts
1.96 KB · Nov 23, 2026 · 18:13 UTC
import {
hydratePartialDiff,
SPLIT_WITH_NEWLINES,
type FileDiffMetadata,
} from "@pierre/diffs";
// An empty hunk side starts *after* its numbered line. Nonempty sides include it.
function hunkStart(line: number, count: number) {
return count === 0 ? line : line - 1;
}
export function expandPatchFile(
file: FileDiffMetadata,
baseContents: string,
): FileDiffMetadata {
const baseLines = baseContents ? baseContents.split(SPLIT_WITH_NEWLINES) : [];
const updated: string[] = [];
let oldEnd = 0;
let newEnd = 0;
for (const hunk of file.hunks) {
const oldStart = hunkStart(hunk.deletionStart, hunk.deletionCount);
const newStart = hunkStart(hunk.additionStart, hunk.additionCount);
const nextOldEnd = oldStart + hunk.deletionCount;
if (
oldStart < oldEnd ||
nextOldEnd > baseLines.length ||
oldStart - oldEnd !== newStart - newEnd ||
(oldStart > 0 && !baseLines[oldStart - 1].endsWith("\n")) ||
(hunk.noEOFCRAdditions && nextOldEnd !== baseLines.length)
) {
throw new Error("Patch coordinates do not match the base file");
}
// Partial diffs store each side's context and edits together in patch order.
for (let offset = 0; offset < hunk.deletionCount; offset++) {
if (
baseLines[oldStart + offset] !==
file.deletionLines[hunk.deletionLineIndex + offset]
) {
throw new Error("Patch contents do not match the base file");
}
}
updated.push(
baseLines.slice(oldEnd, oldStart).join(""),
file.additionLines
.slice(
hunk.additionLineIndex,
hunk.additionLineIndex + hunk.additionCount,
)
.join(""),
);
oldEnd = nextOldEnd;
newEnd = newStart + hunk.additionCount;
}
updated.push(baseLines.slice(oldEnd).join(""));
return hydratePartialDiff("clone", file, {
oldFile: { name: file.prevName ?? file.name, contents: baseContents },
newFile: { name: file.name, contents: updated.join("") },
});
}
SHA-256: deeb9846ddf6106b549a883a69380a68bf6bba82e5264f405a435355d7b5c156