Open History to see the last commit
1export interface DiffExcerptLine {
2 readonly change: "context" | "add" | "delete";
3 readonly oldLineNumber: number | null;
4 readonly newLineNumber: number | null;
5 /** Where the row sits on each side, including the side it does not consume. */
6 readonly oldPosition: number;
7 readonly newPosition: number;
8 readonly content: string;
9}
10
11export function diffChangeMarker(change: DiffExcerptLine["change"]): string {
12 if (change === "add") return "+";
13 if (change === "delete") return "-";
14 return " ";
15}
16
17function diffRange(
18 lines: ReadonlyArray<DiffExcerptLine>,
19 side: "old" | "new",
20): { start: number; count: number } {
21 const [numberKey, positionKey] =
22 side === "old"
23 ? (["oldLineNumber", "oldPosition"] as const)
24 : (["newLineNumber", "newPosition"] as const);
25 const count = lines.filter((line) => line[numberKey] !== null).length;
26 const position = lines[0]?.[positionKey] ?? 1;
27 // A side with no lines names the line before the change, as unified diffs do.
28 return { start: count === 0 ? position - 1 : position, count };
29}
30
31/**
32 * Formats selected diff rows as a unified diff. A selection can span hunks whose gap is not
33 * loaded, so each run of consecutive lines gets its own header to keep the line numbers.
34 */
35export function formatDiffExcerpt(lines: ReadonlyArray<DiffExcerptLine>): string {
36 const runs: DiffExcerptLine[][] = [];
37 let previous: DiffExcerptLine | undefined;
38 for (const line of lines) {
39 const run = runs.at(-1);
40 if (
41 !run ||
42 !previous ||
43 line.oldPosition !== previous.oldPosition + (previous.oldLineNumber === null ? 0 : 1) ||
44 line.newPosition !== previous.newPosition + (previous.newLineNumber === null ? 0 : 1)
45 ) {
46 runs.push([line]);
47 } else {
48 run.push(line);
49 }
50 previous = line;
51 }
52 return runs
53 .flatMap((run) => {
54 const oldRange = diffRange(run, "old");
55 const newRange = diffRange(run, "new");
56 return [
57 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
58 ...run.map((line) => `${diffChangeMarker(line.change)}${line.content}`),
59 ];
60 })
61 .join("\n");
62}