| 1 | import { diffLines, type Change } from "diff"; |
| 2 | |
| 3 | import { DiffLine } from ".."; |
| 4 | |
| 5 | export function convertMyersChangeToDiffLines(change: Change): DiffLine[] { |
| 6 | const type: DiffLine["type"] = change.added |
| 7 | ? "new" |
| 8 | : change.removed |
| 9 | ? "old" |
| 10 | : "same"; |
| 11 | const lines = change.value.split("\n"); |
| 12 | |
| 13 | // Ignore the \n at the end of the final line, if there is one |
| 14 | if (lines[lines.length - 1] === "") { |
| 15 | lines.pop(); |
| 16 | } |
| 17 | |
| 18 | return lines.map((line) => ({ type, line })); |
| 19 | } |
| 20 | |
| 21 | // The interpretation of lines in oldContent and newContent is the same as jsdiff |
| 22 | // Lines are separated by \n, with the exception that a trailing \n does *not* |
| 23 | // represent an empty line. |
| 24 | // |
| 25 | // The default for jsdiff is that "foo" and "foo\n" are *different* single-line |
| 26 | // contents, but we can't represent that: to avoid a diff |
| 27 | // [ { type: "old", line: "foo" }, { type: "new", line: "foo" } ], we |
| 28 | // pass ignoreNewlineAtEof: true. |
| 29 | export function myersDiff(oldContent: string, newContent: string): DiffLine[] { |
| 30 | const theirFormat = diffLines(oldContent, newContent, { |
| 31 | ignoreNewlineAtEof: true, |
| 32 | }); |
| 33 | let ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines); |
| 34 | |
| 35 | // Combine consecutive old/new pairs that are identical after trimming |
| 36 | for (let i = 0; i < ourFormat.length - 1; i++) { |
| 37 | if ( |
| 38 | ourFormat[i]?.type === "old" && |
| 39 | ourFormat[i + 1]?.type === "new" && |
| 40 | ourFormat[i].line.trim() === ourFormat[i + 1].line.trim() |
| 41 | ) { |
| 42 | ourFormat[i] = { type: "same", line: ourFormat[i].line }; |
| 43 | ourFormat.splice(i + 1, 1); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // Remove trailing empty old lines |
| 48 | while ( |
| 49 | ourFormat.length > 0 && |
| 50 | ourFormat[ourFormat.length - 1].type === "old" && |
| 51 | ourFormat[ourFormat.length - 1].line === "" |
| 52 | ) { |
| 53 | ourFormat.pop(); |
| 54 | } |
| 55 | |
| 56 | return ourFormat; |
| 57 | } |