diff cleaning logic

This commit is contained in:
Nate 2025-04-21 12:09:14 -07:00
parent 4f35ca0482
commit a4cc558cf5
2 changed files with 26 additions and 1 deletions

View file

@ -41,4 +41,16 @@ describe("Test myers diff function", () => {
{ type: "same", line: "C" },
]);
});
test("should ignore single-line whitespace-only differences", () => {
const linesA = "A\n B\nC\n";
const linesB = "A\nB\nC";
const diffLines = myersDiff(linesA, linesB);
expect(diffLines).toEqual([
{ type: "same", line: "A" },
{ type: "same", line: " B" },
{ type: "same", line: "C" },
]);
});
});

View file

@ -30,8 +30,21 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
const theirFormat = diffLines(oldContent, newContent, {
ignoreNewlineAtEof: true,
});
const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
let ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
// Combine consecutive old/new pairs that are identical after trimming
for (let i = 0; i < ourFormat.length - 1; i++) {
if (
ourFormat[i]?.type === "old" &&
ourFormat[i + 1]?.type === "new" &&
ourFormat[i].line.trim() === ourFormat[i + 1].line.trim()
) {
ourFormat[i] = { type: "same", line: ourFormat[i].line };
ourFormat.splice(i + 1, 1);
}
}
// Remove trailing empty old lines
while (
ourFormat.length > 0 &&
ourFormat[ourFormat.length - 1].type === "old" &&