Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

reviewGuideTour.ts

203 lines7.1 KB

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