The best way to control Claude Code, Codex and more from any computer or phone

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