@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 536 lines 18.6 KB
Raw
1 import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";
2 import { PullRequestContextMetadata, type PullRequestReviewPosition } from "@t3tools/contracts";
3 import * as Schema from "effect/Schema";
4
5 import { isLineInFileDiff } from "./components/pullRequest/pullRequestDiff.logic";
6
7 const ReviewCommentSelectionSchema = Schema.Struct({
8 start: Schema.Number,
9 side: Schema.Literals(["additions", "deletions"]),
10 end: Schema.Number,
11 endSide: Schema.Literals(["additions", "deletions"]),
12 });
13 type ReviewCommentSelection = typeof ReviewCommentSelectionSchema.Type;
14
15 export const ReviewCommentContextSchema = Schema.Struct({
16 id: Schema.String,
17 sectionId: Schema.String,
18 sectionTitle: Schema.String,
19 filePath: Schema.String,
20 startIndex: Schema.Number,
21 endIndex: Schema.Number,
22 rangeLabel: Schema.String,
23 text: Schema.String,
24 diff: Schema.String,
25 fenceLanguage: Schema.optional(Schema.String),
26 selection: Schema.optional(ReviewCommentSelectionSchema),
27 pullRequest: Schema.optional(PullRequestContextMetadata),
28 });
29
30 export interface ReviewCommentContext {
31 readonly id: string;
32 readonly sectionId: string;
33 readonly sectionTitle: string;
34 readonly filePath: string;
35 readonly startIndex: number;
36 readonly endIndex: number;
37 readonly rangeLabel: string;
38 readonly text: string;
39 readonly diff: string;
40 readonly fenceLanguage?: string | undefined;
41 readonly selection?: ReviewCommentSelection | undefined;
42 readonly pullRequest?: PullRequestContextMetadata | undefined;
43 }
44
45 interface DiffReviewLine {
46 readonly change: "context" | "add" | "delete";
47 readonly oldLineNumber: number | null;
48 readonly newLineNumber: number | null;
49 readonly content: string;
50 }
51
52 export function formatReviewCommentFence(language: string, contents: string): string {
53 const longestBacktickRun = Math.max(
54 0,
55 ...Array.from(contents.matchAll(/`+/g), (match) => match[0].length),
56 );
57 const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
58 return [`${fence}${language}`, contents.trimEnd(), fence].join("\n");
59 }
60
61 export function buildFileReviewComment(input: {
62 id: string;
63 filePath: string;
64 startLine: number;
65 endLine: number;
66 text: string;
67 contents: string;
68 }): ReviewCommentContext {
69 const startLine = Math.max(1, Math.min(input.startLine, input.endLine));
70 const endLine = Math.max(startLine, Math.max(input.startLine, input.endLine));
71 const selectedLines = input.contents.split("\n").slice(startLine - 1, endLine);
72 return {
73 id: input.id,
74 sectionId: `file:${input.filePath}`,
75 // oxlint-disable-next-line t3code/no-untranslated-copy -- stored in the review comment record sent to the agent
76 sectionTitle: "File comment",
77 filePath: input.filePath,
78 startIndex: startLine - 1,
79 endIndex: endLine - 1,
80 // oxlint-disable-next-line t3code/no-untranslated-copy -- stored in the review comment record sent to the agent
81 rangeLabel: startLine === endLine ? `L${startLine}` : `L${startLine} to L${endLine}`,
82 text: input.text.trim(),
83 diff: selectedLines.join("\n"),
84 fenceLanguage: inferReviewCommentFenceLanguage(input.filePath),
85 };
86 }
87
88 export function inferReviewCommentFenceLanguage(filePath: string): string {
89 const normalizedPath = filePath.replaceAll("\\", "/");
90 const fileName = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1).toLowerCase();
91 const extensionIndex = fileName.lastIndexOf(".");
92 if (extensionIndex > 0 && extensionIndex < fileName.length - 1) {
93 return fileName.slice(extensionIndex + 1);
94 }
95 if (fileName.startsWith(".") && fileName.length > 1) {
96 return fileName.slice(1);
97 }
98 return "text";
99 }
100
101 function stripTrailingNewline(value: string): string {
102 return value.endsWith("\n") ? value.slice(0, -1) : value;
103 }
104
105 function buildDiffReviewLines(
106 fileDiff: FileDiffMetadata,
107 includeExpandedContext: boolean,
108 slice?: { readonly startIndex: number; readonly endIndex: number },
109 ): ReadonlyArray<DiffReviewLine> {
110 const rows: DiffReviewLine[] = [];
111 let rowIndex = 0;
112 let oldContextStart = 1;
113 let newContextStart = 1;
114 const pushRow = (row: DiffReviewLine) => {
115 if (!slice || (rowIndex >= slice.startIndex && rowIndex <= slice.endIndex)) {
116 rows.push(row);
117 }
118 rowIndex += 1;
119 };
120 const pushContextGap = (oldStart: number, newStart: number, lineCount: number) => {
121 const count = Math.max(0, lineCount);
122 const firstOffset = slice ? Math.max(0, slice.startIndex - rowIndex) : 0;
123 const lastOffset = slice ? Math.min(count - 1, slice.endIndex - rowIndex) : count - 1;
124 for (let offset = firstOffset; offset <= lastOffset; offset += 1) {
125 rows.push({
126 change: "context",
127 oldLineNumber: oldStart + offset,
128 newLineNumber: newStart + offset,
129 content: stripTrailingNewline(fileDiff.additionLines[newStart + offset - 1] ?? ""),
130 });
131 }
132 rowIndex += count;
133 };
134
135 for (const hunk of fileDiff.hunks) {
136 if (includeExpandedContext) {
137 const oldHunkStart = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);
138 const newHunkStart = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);
139 const contextLines = Math.min(oldHunkStart - oldContextStart, newHunkStart - newContextStart);
140 pushContextGap(oldContextStart, newContextStart, contextLines);
141 }
142
143 let oldLineNumber = hunk.deletionStart;
144 let newLineNumber = hunk.additionStart;
145 let deletionLineIndex = hunk.deletionLineIndex;
146 let additionLineIndex = hunk.additionLineIndex;
147
148 for (const segment of hunk.hunkContent) {
149 if (segment.type === "context") {
150 for (let index = 0; index < segment.lines; index += 1) {
151 pushRow({
152 change: "context",
153 oldLineNumber,
154 newLineNumber,
155 content: stripTrailingNewline(
156 fileDiff.additionLines[additionLineIndex] ??
157 fileDiff.deletionLines[deletionLineIndex] ??
158 "",
159 ),
160 });
161 oldLineNumber += 1;
162 newLineNumber += 1;
163 deletionLineIndex += 1;
164 additionLineIndex += 1;
165 }
166 continue;
167 }
168
169 for (let index = 0; index < segment.deletions; index += 1) {
170 pushRow({
171 change: "delete",
172 oldLineNumber,
173 newLineNumber: null,
174 content: stripTrailingNewline(fileDiff.deletionLines[deletionLineIndex] ?? ""),
175 });
176 oldLineNumber += 1;
177 deletionLineIndex += 1;
178 }
179
180 for (let index = 0; index < segment.additions; index += 1) {
181 pushRow({
182 change: "add",
183 oldLineNumber: null,
184 newLineNumber,
185 content: stripTrailingNewline(fileDiff.additionLines[additionLineIndex] ?? ""),
186 });
187 newLineNumber += 1;
188 additionLineIndex += 1;
189 }
190 }
191
192 oldContextStart = hunk.deletionStart + hunk.deletionCount;
193 newContextStart = hunk.additionStart + hunk.additionCount;
194 if (hunk.deletionCount === 0) oldContextStart += 1;
195 if (hunk.additionCount === 0) newContextStart += 1;
196 }
197
198 if (includeExpandedContext) {
199 const trailingLines = Math.min(
200 fileDiff.deletionLines.length - oldContextStart + 1,
201 fileDiff.additionLines.length - newContextStart + 1,
202 );
203 pushContextGap(oldContextStart, newContextStart, trailingLines);
204 }
205
206 return rows;
207 }
208
209 function getDiffReviewSelectionPoint(
210 line: DiffReviewLine,
211 ): { lineNumber: number; side: SelectionSide } | null {
212 if (line.change === "delete" && line.oldLineNumber !== null) {
213 return { lineNumber: line.oldLineNumber, side: "deletions" };
214 }
215 if (line.newLineNumber !== null) {
216 return { lineNumber: line.newLineNumber, side: "additions" };
217 }
218 if (line.oldLineNumber !== null) {
219 return { lineNumber: line.oldLineNumber, side: "deletions" };
220 }
221 return null;
222 }
223
224 export function restoreDiffReviewCommentRange(
225 fileDiff: FileDiffMetadata,
226 comment: ReviewCommentContext,
227 ): SelectedLineRange | null {
228 if (comment.selection) return comment.selection;
229
230 const includeExpandedContext = !fileDiff.isPartial;
231 const startLine = buildDiffReviewLines(fileDiff, includeExpandedContext, {
232 startIndex: comment.startIndex,
233 endIndex: comment.startIndex,
234 })[0];
235 const endLine =
236 comment.endIndex === comment.startIndex
237 ? startLine
238 : buildDiffReviewLines(fileDiff, includeExpandedContext, {
239 startIndex: comment.endIndex,
240 endIndex: comment.endIndex,
241 })[0];
242 if (!startLine || !endLine) return null;
243 const start = getDiffReviewSelectionPoint(startLine);
244 const end = getDiffReviewSelectionPoint(endLine);
245 if (!start || !end) return null;
246 return {
247 start: start.lineNumber,
248 side: start.side,
249 end: end.lineNumber,
250 endSide: end.side,
251 };
252 }
253
254 function findDiffReviewLineIndex(
255 fileDiff: FileDiffMetadata,
256 lineNumber: number,
257 side: SelectionSide | undefined,
258 includeExpandedContext = !fileDiff.isPartial,
259 ): number {
260 const findOnSide = (selectedSide: "left" | "right") => {
261 let rowIndex = 0;
262 let oldContextStart = 1;
263 let newContextStart = 1;
264 const findContextIndex = (oldStart: number, newStart: number, lineCount: number) => {
265 const count = Math.max(0, lineCount);
266 const selectedStart = selectedSide === "left" ? oldStart : newStart;
267 const offset = lineNumber - selectedStart;
268 return offset >= 0 && offset < count ? rowIndex + offset : -1;
269 };
270
271 for (const hunk of fileDiff.hunks) {
272 if (includeExpandedContext) {
273 const oldContextEnd = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);
274 const newContextEnd = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);
275 const contextLines = Math.min(
276 oldContextEnd - oldContextStart,
277 newContextEnd - newContextStart,
278 );
279 const contextIndex = findContextIndex(oldContextStart, newContextStart, contextLines);
280 if (contextIndex >= 0) return contextIndex;
281 rowIndex += Math.max(0, contextLines);
282 }
283
284 let oldLineNumber = hunk.deletionStart;
285 let newLineNumber = hunk.additionStart;
286 for (const segment of hunk.hunkContent) {
287 if (segment.type === "context") {
288 const contextIndex = findContextIndex(oldLineNumber, newLineNumber, segment.lines);
289 if (contextIndex >= 0) return contextIndex;
290 rowIndex += segment.lines;
291 oldLineNumber += segment.lines;
292 newLineNumber += segment.lines;
293 continue;
294 }
295
296 if (
297 selectedSide === "left" &&
298 lineNumber >= oldLineNumber &&
299 lineNumber < oldLineNumber + segment.deletions
300 ) {
301 return rowIndex + lineNumber - oldLineNumber;
302 }
303 rowIndex += segment.deletions;
304 oldLineNumber += segment.deletions;
305
306 if (
307 selectedSide === "right" &&
308 lineNumber >= newLineNumber &&
309 lineNumber < newLineNumber + segment.additions
310 ) {
311 return rowIndex + lineNumber - newLineNumber;
312 }
313 rowIndex += segment.additions;
314 newLineNumber += segment.additions;
315 }
316
317 oldContextStart = hunk.deletionStart + hunk.deletionCount;
318 newContextStart = hunk.additionStart + hunk.additionCount;
319 if (hunk.deletionCount === 0) oldContextStart += 1;
320 if (hunk.additionCount === 0) newContextStart += 1;
321 }
322
323 if (!includeExpandedContext) return -1;
324 const trailingLines = Math.min(
325 fileDiff.deletionLines.length - oldContextStart + 1,
326 fileDiff.additionLines.length - newContextStart + 1,
327 );
328 return findContextIndex(oldContextStart, newContextStart, trailingLines);
329 };
330
331 const selectedSide = side === "deletions" ? "left" : "right";
332 const preferredIndex = findOnSide(selectedSide);
333 return preferredIndex >= 0
334 ? preferredIndex
335 : findOnSide(selectedSide === "left" ? "right" : "left");
336 }
337
338 export function resolveDiffReviewPosition(
339 fileDiff: FileDiffMetadata,
340 lineNumber: number,
341 side: SelectionSide | undefined,
342 ): PullRequestReviewPosition | null {
343 const lineIndex = findDiffReviewLineIndex(fileDiff, lineNumber, side);
344 if (lineIndex < 0) return null;
345 const line = buildDiffReviewLines(fileDiff, !fileDiff.isPartial, {
346 startIndex: lineIndex,
347 endIndex: lineIndex,
348 })[0];
349 if (line === undefined) return null;
350
351 // An explicit selection must not resolve to a same-numbered line on the other side.
352 if (
353 (side === "additions" && line.newLineNumber !== lineNumber) ||
354 (side === "deletions" && line.oldLineNumber !== lineNumber)
355 ) {
356 return null;
357 }
358
359 switch (line.change) {
360 case "add":
361 return line.newLineNumber === null ? null : { kind: "added", newLine: line.newLineNumber };
362 case "delete":
363 return line.oldLineNumber === null ? null : { kind: "deleted", oldLine: line.oldLineNumber };
364 case "context":
365 // An expanded file also shows the gaps between hunks, and GitHub rejects a whole review
366 // over one comment anchored there.
367 return line.oldLineNumber === null ||
368 line.newLineNumber === null ||
369 !isLineInFileDiff(fileDiff, "right", line.newLineNumber)
370 ? null
371 : {
372 kind: "context",
373 oldLine: line.oldLineNumber,
374 newLine: line.newLineNumber,
375 side: side === "deletions" ? "left" : "right",
376 };
377 }
378 }
379
380 function reviewHunkIndex(fileDiff: FileDiffMetadata, position: PullRequestReviewPosition): number {
381 const [side, line] =
382 position.kind === "deleted"
383 ? (["left", position.oldLine] as const)
384 : (["right", position.newLine] as const);
385 return fileDiff.hunks.findIndex((hunk) =>
386 side === "left"
387 ? line >= hunk.deletionStart && line < hunk.deletionStart + hunk.deletionCount
388 : line >= hunk.additionStart && line < hunk.additionStart + hunk.additionCount,
389 );
390 }
391
392 /**
393 * Where a review comment on `range` is anchored. With `ranged`, a selection inside one hunk
394 * keeps its first line, in diff order, as `startPosition`, because hosts refuse a range that
395 * crosses hunks. Otherwise the comment sits on the line the selection ended on.
396 */
397 export function resolveDiffReviewAnchor(
398 fileDiff: FileDiffMetadata,
399 range: SelectedLineRange,
400 ranged: boolean,
401 ): {
402 readonly position: PullRequestReviewPosition;
403 readonly startPosition?: PullRequestReviewPosition;
404 } | null {
405 const endSide = range.endSide ?? range.side;
406 const last = resolveDiffReviewPosition(fileDiff, range.end, endSide);
407 if (last === null) return null;
408 const first = ranged ? resolveDiffReviewPosition(fileDiff, range.start, range.side) : null;
409 if (first === null) return { position: last };
410 const startIndex = findDiffReviewLineIndex(fileDiff, range.start, range.side);
411 const endIndex = findDiffReviewLineIndex(fileDiff, range.end, endSide);
412 if (startIndex === endIndex) return { position: last };
413 const [start, end] = startIndex < endIndex ? [first, last] : [last, first];
414 const hunk = reviewHunkIndex(fileDiff, end);
415 return hunk >= 0 && reviewHunkIndex(fileDiff, start) === hunk
416 ? { position: end, startPosition: start }
417 : { position: last };
418 }
419
420 function getDiffRange(
421 lines: ReadonlyArray<DiffReviewLine>,
422 key: "oldLineNumber" | "newLineNumber",
423 ): { start: number; count: number } {
424 const numberedLines = lines.filter((line) => line[key] !== null);
425 return {
426 start: numberedLines[0]?.[key] ?? 0,
427 count: numberedLines.length,
428 };
429 }
430
431 function getDiffChangeMarker(change: DiffReviewLine["change"]): string {
432 if (change === "add") return "+";
433 if (change === "delete") return "-";
434 return " ";
435 }
436
437 function formatDiffReviewRangeLabel(lines: ReadonlyArray<DiffReviewLine>): string {
438 const firstLine = lines[0];
439 const lastLine = lines.at(-1);
440 if (!firstLine || !lastLine) return "line";
441 const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber;
442 const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber;
443 if (firstNumber === null || lastNumber === null) {
444 return lines.length === 1 ? "line" : `${lines.length} lines`;
445 }
446
447 const firstMarker = getDiffChangeMarker(firstLine.change).trim();
448 const marker =
449 firstMarker.length > 0 && lines.every((line) => line.change === firstLine.change)
450 ? firstMarker
451 : "";
452 return firstNumber === lastNumber
453 ? `${marker}${firstNumber}`
454 : `${marker}${firstNumber} to ${marker}${lastNumber}`;
455 }
456
457 export function diffReviewSelectionId(fileKey: string, range: SelectedLineRange): string {
458 return `${fileKey}:${range.side ?? "additions"}:${range.start}:${range.endSide ?? range.side ?? "additions"}:${range.end}`;
459 }
460
461 export function buildDiffReviewComment(input: {
462 id: string;
463 sectionId: string;
464 sectionTitle: string;
465 filePath: string;
466 fileDiff: FileDiffMetadata;
467 range: SelectedLineRange;
468 text: string;
469 }): ReviewCommentContext | null {
470 const includeExpandedContext = !input.fileDiff.isPartial;
471 const startIndex = findDiffReviewLineIndex(
472 input.fileDiff,
473 input.range.start,
474 input.range.side,
475 includeExpandedContext,
476 );
477 const endIndex = findDiffReviewLineIndex(
478 input.fileDiff,
479 input.range.end,
480 input.range.endSide ?? input.range.side,
481 includeExpandedContext,
482 );
483 if (startIndex < 0 || endIndex < 0) return null;
484
485 const normalizedStartIndex = Math.min(startIndex, endIndex);
486 const normalizedEndIndex = Math.max(startIndex, endIndex);
487 const selectedLines = buildDiffReviewLines(input.fileDiff, includeExpandedContext, {
488 startIndex: normalizedStartIndex,
489 endIndex: normalizedEndIndex,
490 });
491 const oldRange = getDiffRange(selectedLines, "oldLineNumber");
492 const newRange = getDiffRange(selectedLines, "newLineNumber");
493
494 return {
495 id: input.id,
496 sectionId: input.sectionId,
497 sectionTitle: input.sectionTitle,
498 filePath: input.filePath,
499 startIndex: normalizedStartIndex,
500 endIndex: normalizedEndIndex,
501 rangeLabel: formatDiffReviewRangeLabel(selectedLines),
502 text: input.text.trim(),
503 diff: [
504 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
505 ...selectedLines.map((line) => `${getDiffChangeMarker(line.change)}${line.content}`),
506 ].join("\n"),
507 fenceLanguage: "diff",
508 selection: {
509 start: input.range.start,
510 side: input.range.side ?? "additions",
511 end: input.range.end,
512 endSide: input.range.endSide ?? input.range.side ?? "additions",
513 },
514 };
515 }
516
517 export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
518 if ((comment.fenceLanguage ?? "diff") !== "diff") {
519 return "";
520 }
521 if (comment.diff.trim().length === 0) {
522 return "";
523 }
524 const diff = comment.diff.trimStart().replace(/\n+$/, "");
525 if (diff.startsWith("diff --git ")) {
526 return diff;
527 }
528
529 const normalizedPath = comment.filePath.replaceAll("\\", "/");
530 return [
531 `diff --git a/${normalizedPath} b/${normalizedPath}`,
532 `--- a/${normalizedPath}`,
533 `+++ b/${normalizedPath}`,
534 diff,
535 ].join("\n");
536 }