Open History to see the last commit
1import type { FileDiffMetadata } from "@pierre/diffs";
2import type { PullRequestReviewGuideExcerpt, PullRequestReviewGuideStop } from "@t3tools/contracts";
3import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
4import { mFallback, msg } from "gt-i18n";
5import type { MFunctionType } from "gt-i18n/types";
6
7export function stepTourPosition(current: number, delta: 1 | -1, stopCount: number): number {
8 return Math.max(Math.min(current + delta, stopCount - 1), 0);
9}
10
11export function stopFilePaths(stop: PullRequestReviewGuideStop): ReadonlyArray<string> {
12 return [
13 ...new Set([
14 ...stop.excerpts.map((excerpt) => excerpt.path),
15 ...stop.files.map((file) => file.path),
16 ]),
17 ];
18}
19
20export function stopSubline(
21 stop: PullRequestReviewGuideStop,
22 resolve: MFunctionType = mFallback,
23): string {
24 const count = stopFilePaths(stop).length;
25 if (count === 0) return resolve(msg("Context, no code"));
26 return resolve(msg("{count, plural, one {{count} file} other {{count} files}}", { count }));
27}
28
29function noteMarker(index: number): string {
30 return index < 26 ? String.fromCharCode(65 + index) : String(index + 1);
31}
32
33export interface DiffRow {
34 readonly kind: "context" | "addition" | "deletion";
35 readonly oldLine: number | null;
36 readonly newLine: number | null;
37 readonly oldAt: number;
38 readonly newAt: number;
39 readonly text: string;
40 readonly hunk: number;
41}
42
43export function fileDiffRows(file: FileDiffMetadata): ReadonlyArray<DiffRow> {
44 const rows: DiffRow[] = [];
45 file.hunks.forEach((hunk, hunkIndex) => {
46 let oldAt = hunk.deletionStart;
47 let newAt = hunk.additionStart;
48 for (const content of hunk.hunkContent) {
49 if (content.type === "context") {
50 for (let offset = 0; offset < content.lines; offset += 1) {
51 rows.push({
52 kind: "context",
53 oldLine: oldAt,
54 newLine: newAt,
55 oldAt,
56 newAt,
57 text: file.additionLines[content.additionLineIndex + offset] ?? "",
58 hunk: hunkIndex,
59 });
60 oldAt += 1;
61 newAt += 1;
62 }
63 continue;
64 }
65 for (let offset = 0; offset < content.deletions; offset += 1) {
66 rows.push({
67 kind: "deletion",
68 oldLine: oldAt,
69 newLine: null,
70 oldAt,
71 newAt,
72 text: file.deletionLines[content.deletionLineIndex + offset] ?? "",
73 hunk: hunkIndex,
74 });
75 oldAt += 1;
76 }
77 for (let offset = 0; offset < content.additions; offset += 1) {
78 rows.push({
79 kind: "addition",
80 oldLine: null,
81 newLine: newAt,
82 oldAt,
83 newAt,
84 text: file.additionLines[content.additionLineIndex + offset] ?? "",
85 hunk: hunkIndex,
86 });
87 newAt += 1;
88 }
89 }
90 });
91 return rows;
92}
93
94export function excerptRows(
95 rows: ReadonlyArray<DiffRow>,
96 excerpt: Pick<PullRequestReviewGuideExcerpt, "side" | "start" | "end">,
97): ReadonlyArray<DiffRow> {
98 const lineOf = (row: DiffRow) => (excerpt.side === "new" ? row.newLine : row.oldLine);
99 const inRange = (row: DiffRow) => {
100 const line = lineOf(row);
101 return line !== null && line >= excerpt.start && line <= excerpt.end;
102 };
103 let first = rows.findIndex(inRange);
104 if (first === -1) return [];
105 let last = rows.findLastIndex(inRange);
106 const sameHunk = (index: number, anchor: number) => rows[index]?.hunk === rows[anchor]?.hunk;
107 if (excerpt.side === "new" && rows[first]?.kind === "addition") {
108 while (first > 0 && rows[first - 1]?.kind === "deletion" && sameHunk(first - 1, first)) {
109 first -= 1;
110 }
111 }
112 if (excerpt.side === "old" && rows[last]?.kind === "deletion") {
113 while (
114 last < rows.length - 1 &&
115 rows[last + 1]?.kind === "addition" &&
116 sameHunk(last + 1, last)
117 ) {
118 last += 1;
119 }
120 }
121 return rows.slice(first, last + 1);
122}
123
124const ROW_PREFIX = { context: " ", addition: "+", deletion: "-" } as const;
125
126export function rowsToPatch(
127 path: string,
128 previousPath: string,
129 rows: ReadonlyArray<DiffRow>,
130): string {
131 if (rows.length === 0) return "";
132 const oldName = quoteGitPatchPath(`a/${previousPath}`);
133 const newName = quoteGitPatchPath(`b/${path}`);
134 const lines = [`diff --git ${oldName} ${newName}`, `--- ${oldName}`, `+++ ${newName}`];
135 let start = 0;
136 while (start < rows.length) {
137 let end = start;
138 while (end + 1 < rows.length && rows[end + 1]?.hunk === rows[start]?.hunk) end += 1;
139 const group = rows.slice(start, end + 1);
140 const head = group[0]!;
141 const oldCount = group.filter((row) => row.oldLine !== null).length;
142 const newCount = group.filter((row) => row.newLine !== null).length;
143 // Git names the line before an empty side, so a pure insertion after line 9 is `-9,0`.
144 const oldStart = oldCount === 0 ? Math.max(head.oldAt - 1, 0) : head.oldAt;
145 const newStart = newCount === 0 ? Math.max(head.newAt - 1, 0) : head.newAt;
146 lines.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
147 for (const row of group) {
148 lines.push(`${ROW_PREFIX[row.kind]}${row.text.replace(/\n$/, "")}`);
149 if (!row.text.endsWith("\n")) lines.push("\\ No newline at end of file");
150 }
151 start = end + 1;
152 }
153 return `${lines.join("\n")}\n`;
154}
155
156/**
157 * The renderer fills the code around a hunk from both files and needs them to agree
158 * outside it, which the real old file does not wherever another hunk changed lines.
159 */
160export function excerptExpansionOldContents(
161 newContents: string,
162 rows: ReadonlyArray<DiffRow>,
163): string | null {
164 const head = rows[0];
165 if (head === undefined || rows.some((row) => row.hunk !== head.hunk)) return null;
166 const newLines = newContents.match(/[^\n]*\n|[^\n]+$/g) ?? [];
167 const before = head.newAt - 1;
168 const newCount = rows.filter((row) => row.newLine !== null).length;
169 const oldBefore = head.oldAt - 1;
170 const prefix = newLines.slice(0, before);
171 const oldPrefix =
172 oldBefore >= prefix.length
173 ? [...Array.from({ length: oldBefore - prefix.length }, () => "\n"), ...prefix]
174 : prefix.slice(prefix.length - oldBefore);
175 const oldRows = rows.filter((row) => row.oldLine !== null).map((row) => row.text);
176 const suffix = newLines.slice(before + newCount);
177 // Synthetic context still needs its own line after an old EOF row.
178 if (suffix.length > 0 && oldRows.at(-1)?.endsWith("\n") === false) oldRows.push("\n");
179 return [...oldPrefix, ...oldRows, ...suffix].join("");
180}
181
182export function letterStopNotes(stop: PullRequestReviewGuideStop) {
183 const lettered = stop.notes.map((note, index) => ({ marker: noteMarker(index), note }));
184 const byExcerpt = stop.excerpts.map((excerpt) => {
185 const lines = new Map<number, Array<{ marker: string; title: string }>>();
186 for (const { marker, note } of lettered) {
187 if (note.path !== excerpt.path || note.line < excerpt.start || note.line > excerpt.end) {
188 continue;
189 }
190 const entry = { marker, title: note.title };
191 const list = lines.get(note.line);
192 if (list === undefined) lines.set(note.line, [entry]);
193 else list.push(entry);
194 }
195 return [...lines].map(([line, markers]) => ({ line, markers }));
196 });
197 return { lettered, byExcerpt };
198}