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

reviewCommentContext.ts

521 lines18.4 KB

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