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

reviewCommentContext.ts

651 lines21.2 KB

1import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";
2import type { PullRequestReviewPosition } from "@t3tools/contracts";
3import * as Schema from "effect/Schema";
4​
5const ReviewCommentSelectionSchema = Schema.Struct({
6 start: Schema.Number,
7 side: Schema.Literals(["additions", "deletions"]),
8 end: Schema.Number,
9 endSide: Schema.Literals(["additions", "deletions"]),
10});
11type ReviewCommentSelection = typeof ReviewCommentSelectionSchema.Type;
12​
13export const ReviewCommentContextSchema = Schema.Struct({
14 id: Schema.String,
15 sectionId: Schema.String,
16 sectionTitle: Schema.String,
17 filePath: Schema.String,
18 startIndex: Schema.Number,
19 endIndex: Schema.Number,
20 rangeLabel: Schema.String,
21 text: Schema.String,
22 diff: Schema.String,
23 fenceLanguage: Schema.optional(Schema.String),
24 selection: Schema.optional(ReviewCommentSelectionSchema),
25});
26​
27export interface ReviewCommentContext {
28 readonly id: string;
29 readonly sectionId: string;
30 readonly sectionTitle: string;
31 readonly filePath: string;
32 readonly startIndex: number;
33 readonly endIndex: number;
34 readonly rangeLabel: string;
35 readonly text: string;
36 readonly diff: string;
37 readonly fenceLanguage?: string | undefined;
38 readonly selection?: ReviewCommentSelection | undefined;
40​
41interface DiffReviewLine {
42 readonly change: "context" | "add" | "delete";
43 readonly oldLineNumber: number | null;
44 readonly newLineNumber: number | null;
45 readonly content: string;
47​
48export type ReviewCommentMessageSegment =
49 | {
50 readonly kind: "text";
51 readonly id: string;
52 readonly text: string;
53 }
54 | {
55 readonly kind: "review-comment";
56 readonly comment: ReviewCommentContext;
57 };
58​
59const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
60const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
61const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
62​
63function escapeReviewCommentAttribute(value: string): string {
64 return value
65 .replace(/&/g, "&amp;")
66 .replace(/"/g, "&quot;")
67 .replace(/</g, "&lt;")
68 .replace(/>/g, "&gt;");
70​
71function unescapeReviewCommentAttribute(value: string): string {
72 return value
73 .replace(/&lt;/g, "<")
74 .replace(/&gt;/g, ">")
75 .replace(/&quot;/g, '"')
76 .replace(/&amp;/g, "&");
78​
79function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
80 const attributes: Record<string, string> = {};
81 for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
82 attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
83 }
84 return attributes;
86​
87function readNonNegativeInteger(value: string | undefined): number | null {
88 if (value === undefined || !/^\d+$/.test(value)) {
89 return null;
90 }
91 return Number(value);
93​
94function extractReviewCommentBody(rawBody: string): {
95 text: string;
96 language: string;
97 contents: string;
98} {
99 const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
100 const match = matches.at(-1);
101 const fenceIndex = match?.index;
102 return {
103 text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
104 language: match?.[2]?.trim() || "diff",
105 contents: match?.[3] ?? "",
106 };
108​
109function parseReviewCommentContext(
110 rawAttributes: string,
111 rawBody: string,
112 index: number,
113): ReviewCommentContext | null {
114 const attributes = readReviewCommentAttributes(rawAttributes);
115 const startIndex = readNonNegativeInteger(attributes.startIndex);
116 const endIndex = readNonNegativeInteger(attributes.endIndex);
117 const filePath = attributes.filePath?.trim();
118 const sectionId = attributes.sectionId?.trim();
119 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
120 return null;
121 }
122 const body = extractReviewCommentBody(rawBody);
123​
124 return {
125 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
126 sectionId,
127 sectionTitle: attributes.sectionTitle?.trim() || "Review",
128 filePath,
129 startIndex: Math.min(startIndex, endIndex),
130 endIndex: Math.max(startIndex, endIndex),
131 rangeLabel: attributes.rangeLabel?.trim() || "line",
132 text: body.text,
133 diff: body.contents,
134 fenceLanguage: body.language,
135 };
137​
138export function parseReviewCommentMessageSegments(
139 value: string,
140): ReadonlyArray<ReviewCommentMessageSegment> {
141 const segments: ReviewCommentMessageSegment[] = [];
142 let cursor = 0;
143 let parsedCommentIndex = 0;
144​
145 for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
146 const matchIndex = match.index ?? 0;
147 const beforeText = value.slice(cursor, matchIndex);
148 if (beforeText.length > 0) {
149 segments.push({
150 kind: "text",
151 id: `review-comment-text:${cursor}`,
152 text: beforeText,
153 });
154 }
155​
156 const comment = parseReviewCommentContext(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
157 if (comment) {
158 segments.push({ kind: "review-comment", comment });
159 parsedCommentIndex += 1;
160 } else {
161 segments.push({
162 kind: "text",
163 id: `review-comment-invalid:${matchIndex}`,
164 text: match[0],
165 });
166 }
167​
168 cursor = matchIndex + match[0].length;
169 }
170​
171 const rest = value.slice(cursor);
172 if (rest.length > 0) {
173 segments.push({
174 kind: "text",
175 id: `review-comment-text:${cursor}`,
176 text: rest,
177 });
178 }
179​
180 return segments;
182​
183export function formatReviewCommentFence(language: string, contents: string): string {
184 const longestBacktickRun = Math.max(
185 0,
186 ...Array.from(contents.matchAll(/`+/g), (match) => match[0].length),
187 );
188 const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
189 return [`${fence}${language}`, contents.trimEnd(), fence].join("\n");
191​
192/**
193 * Keeps a comment's own words from closing the block they travel in. The parser ends an
194 * attachment at the first `</review_comment>`, so text carrying one would spill the rest of
195 * itself into the prompt — and could open a forged attachment naming any file it liked. Only
196 * ever the local reader's words before, but a pull request's review bodies come from whoever
197 * wrote them.
198 */
199function neutralizeReviewCommentTags(text: string): string {
200 return text.replace(/<(?=\/?review_comment\b)/giu, "&lt;");
202​
203export function formatReviewCommentContext(comment: ReviewCommentContext): string {
204 return [
205 [
206 "<review_comment",
207 ` sectionId="${escapeReviewCommentAttribute(comment.sectionId)}"`,
208 ` sectionTitle="${escapeReviewCommentAttribute(comment.sectionTitle)}"`,
209 ` filePath="${escapeReviewCommentAttribute(comment.filePath)}"`,
210 ` startIndex="${comment.startIndex}"`,
211 ` endIndex="${comment.endIndex}"`,
212 ` rangeLabel="${escapeReviewCommentAttribute(comment.rangeLabel)}"`,
213 ">",
214 ].join(""),
215 neutralizeReviewCommentTags(comment.text.trim()),
216 formatReviewCommentFence(comment.fenceLanguage ?? "diff", comment.diff),
217 "</review_comment>",
218 ].join("\n");
220​
221export function appendReviewCommentsToPrompt(
222 prompt: string,
223 comments: ReadonlyArray<ReviewCommentContext>,
224): string {
225 const blocks = comments.map(formatReviewCommentContext);
226 if (blocks.length === 0) return prompt;
227 const trimmedPrompt = prompt.trim();
228 return trimmedPrompt.length > 0
229 ? `${trimmedPrompt}\n\n${blocks.join("\n\n")}`
230 : blocks.join("\n\n");
232​
233export function buildFileReviewComment(input: {
234 id: string;
235 filePath: string;
236 startLine: number;
237 endLine: number;
238 text: string;
239 contents: string;
240}): ReviewCommentContext {
241 const startLine = Math.max(1, Math.min(input.startLine, input.endLine));
242 const endLine = Math.max(startLine, Math.max(input.startLine, input.endLine));
243 const selectedLines = input.contents.split("\n").slice(startLine - 1, endLine);
244 return {
245 id: input.id,
246 sectionId: `file:${input.filePath}`,
247 sectionTitle: "File comment",
248 filePath: input.filePath,
249 startIndex: startLine - 1,
250 endIndex: endLine - 1,
251 rangeLabel: startLine === endLine ? `L${startLine}` : `L${startLine} to L${endLine}`,
252 text: input.text.trim(),
253 diff: selectedLines.join("\n"),
254 fenceLanguage: inferReviewCommentFenceLanguage(input.filePath),
255 };
257​
258export function inferReviewCommentFenceLanguage(filePath: string): string {
259 const normalizedPath = filePath.replaceAll("\\", "/");
260 const fileName = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1).toLowerCase();
261 const extensionIndex = fileName.lastIndexOf(".");
262 if (extensionIndex > 0 && extensionIndex < fileName.length - 1) {
263 return fileName.slice(extensionIndex + 1);
264 }
265 if (fileName.startsWith(".") && fileName.length > 1) {
266 return fileName.slice(1);
267 }
268 return "text";
270​
271function stripTrailingNewline(value: string): string {
272 return value.endsWith("\n") ? value.slice(0, -1) : value;
274​
275function buildDiffReviewLines(
276 fileDiff: FileDiffMetadata,
277 includeExpandedContext: boolean,
278 slice?: { readonly startIndex: number; readonly endIndex: number },
279): ReadonlyArray<DiffReviewLine> {
280 const rows: DiffReviewLine[] = [];
281 let rowIndex = 0;
282 let oldContextStart = 1;
283 let newContextStart = 1;
284 const pushRow = (row: DiffReviewLine) => {
285 if (!slice || (rowIndex >= slice.startIndex && rowIndex <= slice.endIndex)) {
286 rows.push(row);
287 }
288 rowIndex += 1;
289 };
290 const pushContextGap = (oldStart: number, newStart: number, lineCount: number) => {
291 const count = Math.max(0, lineCount);
292 const firstOffset = slice ? Math.max(0, slice.startIndex - rowIndex) : 0;
293 const lastOffset = slice ? Math.min(count - 1, slice.endIndex - rowIndex) : count - 1;
294 for (let offset = firstOffset; offset <= lastOffset; offset += 1) {
295 rows.push({
296 change: "context",
297 oldLineNumber: oldStart + offset,
298 newLineNumber: newStart + offset,
299 content: stripTrailingNewline(fileDiff.additionLines[newStart + offset - 1] ?? ""),
300 });
301 }
302 rowIndex += count;
303 };
304​
305 for (const hunk of fileDiff.hunks) {
306 if (includeExpandedContext) {
307 const oldHunkStart = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);
308 const newHunkStart = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);
309 const contextLines = Math.min(oldHunkStart - oldContextStart, newHunkStart - newContextStart);
310 pushContextGap(oldContextStart, newContextStart, contextLines);
311 }
312​
313 let oldLineNumber = hunk.deletionStart;
314 let newLineNumber = hunk.additionStart;
315 let deletionLineIndex = hunk.deletionLineIndex;
316 let additionLineIndex = hunk.additionLineIndex;
317​
318 for (const segment of hunk.hunkContent) {
319 if (segment.type === "context") {
320 for (let index = 0; index < segment.lines; index += 1) {
321 pushRow({
322 change: "context",
323 oldLineNumber,
324 newLineNumber,
325 content: stripTrailingNewline(
326 fileDiff.additionLines[additionLineIndex] ??
327 fileDiff.deletionLines[deletionLineIndex] ??
328 "",
329 ),
330 });
331 oldLineNumber += 1;
332 newLineNumber += 1;
333 deletionLineIndex += 1;
334 additionLineIndex += 1;
335 }
336 continue;
337 }
338​
339 for (let index = 0; index < segment.deletions; index += 1) {
340 pushRow({
341 change: "delete",
342 oldLineNumber,
343 newLineNumber: null,
344 content: stripTrailingNewline(fileDiff.deletionLines[deletionLineIndex] ?? ""),
345 });
346 oldLineNumber += 1;
347 deletionLineIndex += 1;
348 }
349​
350 for (let index = 0; index < segment.additions; index += 1) {
351 pushRow({
352 change: "add",
353 oldLineNumber: null,
354 newLineNumber,
355 content: stripTrailingNewline(fileDiff.additionLines[additionLineIndex] ?? ""),
356 });
357 newLineNumber += 1;
358 additionLineIndex += 1;
359 }
360 }
361​
362 oldContextStart = hunk.deletionStart + hunk.deletionCount;
363 newContextStart = hunk.additionStart + hunk.additionCount;
364 if (hunk.deletionCount === 0) oldContextStart += 1;
365 if (hunk.additionCount === 0) newContextStart += 1;
366 }
367​
368 if (includeExpandedContext) {
369 const trailingLines = Math.min(
370 fileDiff.deletionLines.length - oldContextStart + 1,
371 fileDiff.additionLines.length - newContextStart + 1,
372 );
373 pushContextGap(oldContextStart, newContextStart, trailingLines);
374 }
375​
376 return rows;
378​
379function getDiffReviewSelectionPoint(
380 line: DiffReviewLine,
381): { lineNumber: number; side: SelectionSide } | null {
382 if (line.change === "delete" && line.oldLineNumber !== null) {
383 return { lineNumber: line.oldLineNumber, side: "deletions" };
384 }
385 if (line.newLineNumber !== null) {
386 return { lineNumber: line.newLineNumber, side: "additions" };
387 }
388 if (line.oldLineNumber !== null) {
389 return { lineNumber: line.oldLineNumber, side: "deletions" };
390 }
391 return null;
393​
394export function restoreDiffReviewCommentRange(
395 fileDiff: FileDiffMetadata,
396 comment: ReviewCommentContext,
397): SelectedLineRange | null {
398 if (comment.selection) return comment.selection;
399​
400 const includeExpandedContext = !fileDiff.isPartial;
401 const startLine = buildDiffReviewLines(fileDiff, includeExpandedContext, {
402 startIndex: comment.startIndex,
403 endIndex: comment.startIndex,
404 })[0];
405 const endLine =
406 comment.endIndex === comment.startIndex
407 ? startLine
408 : buildDiffReviewLines(fileDiff, includeExpandedContext, {
409 startIndex: comment.endIndex,
410 endIndex: comment.endIndex,
411 })[0];
412 if (!startLine || !endLine) return null;
413 const start = getDiffReviewSelectionPoint(startLine);
414 const end = getDiffReviewSelectionPoint(endLine);
415 if (!start || !end) return null;
416 return {
417 start: start.lineNumber,
418 side: start.side,
419 end: end.lineNumber,
420 endSide: end.side,
421 };
423​
424function findDiffReviewLineIndex(
425 fileDiff: FileDiffMetadata,
426 lineNumber: number,
427 side: SelectionSide | undefined,
428 includeExpandedContext = !fileDiff.isPartial,
429): number {
430 const findOnSide = (selectedSide: "left" | "right") => {
431 let rowIndex = 0;
432 let oldContextStart = 1;
433 let newContextStart = 1;
434 const findContextIndex = (oldStart: number, newStart: number, lineCount: number) => {
435 const count = Math.max(0, lineCount);
436 const selectedStart = selectedSide === "left" ? oldStart : newStart;
437 const offset = lineNumber - selectedStart;
438 return offset >= 0 && offset < count ? rowIndex + offset : -1;
439 };
440​
441 for (const hunk of fileDiff.hunks) {
442 if (includeExpandedContext) {
443 const oldContextEnd = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);
444 const newContextEnd = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);
445 const contextLines = Math.min(
446 oldContextEnd - oldContextStart,
447 newContextEnd - newContextStart,
448 );
449 const contextIndex = findContextIndex(oldContextStart, newContextStart, contextLines);
450 if (contextIndex >= 0) return contextIndex;
451 rowIndex += Math.max(0, contextLines);
452 }
453​
454 let oldLineNumber = hunk.deletionStart;
455 let newLineNumber = hunk.additionStart;
456 for (const segment of hunk.hunkContent) {
457 if (segment.type === "context") {
458 const contextIndex = findContextIndex(oldLineNumber, newLineNumber, segment.lines);
459 if (contextIndex >= 0) return contextIndex;
460 rowIndex += segment.lines;
461 oldLineNumber += segment.lines;
462 newLineNumber += segment.lines;
463 continue;
464 }
465​
466 if (
467 selectedSide === "left" &&
468 lineNumber >= oldLineNumber &&
469 lineNumber < oldLineNumber + segment.deletions
470 ) {
471 return rowIndex + lineNumber - oldLineNumber;
472 }
473 rowIndex += segment.deletions;
474 oldLineNumber += segment.deletions;
475​
476 if (
477 selectedSide === "right" &&
478 lineNumber >= newLineNumber &&
479 lineNumber < newLineNumber + segment.additions
480 ) {
481 return rowIndex + lineNumber - newLineNumber;
482 }
483 rowIndex += segment.additions;
484 newLineNumber += segment.additions;
485 }
486​
487 oldContextStart = hunk.deletionStart + hunk.deletionCount;
488 newContextStart = hunk.additionStart + hunk.additionCount;
489 if (hunk.deletionCount === 0) oldContextStart += 1;
490 if (hunk.additionCount === 0) newContextStart += 1;
491 }
492​
493 if (!includeExpandedContext) return -1;
494 const trailingLines = Math.min(
495 fileDiff.deletionLines.length - oldContextStart + 1,
496 fileDiff.additionLines.length - newContextStart + 1,
497 );
498 return findContextIndex(oldContextStart, newContextStart, trailingLines);
499 };
500​
501 const selectedSide = side === "deletions" ? "left" : "right";
502 const preferredIndex = findOnSide(selectedSide);
503 return preferredIndex >= 0
504 ? preferredIndex
505 : findOnSide(selectedSide === "left" ? "right" : "left");
507​
508/** Resolve the host-facing coordinates of a line selected in the diff viewer. */
509export function resolveDiffReviewPosition(
510 fileDiff: FileDiffMetadata,
511 lineNumber: number,
512 side: SelectionSide | undefined,
513): PullRequestReviewPosition | null {
514 const lineIndex = findDiffReviewLineIndex(fileDiff, lineNumber, side);
515 if (lineIndex < 0) return null;
516 const line = buildDiffReviewLines(fileDiff, !fileDiff.isPartial, {
517 startIndex: lineIndex,
518 endIndex: lineIndex,
519 })[0];
520 if (line === undefined) return null;
521​
522 switch (line.change) {
523 case "add":
524 return line.newLineNumber === null ? null : { kind: "added", newLine: line.newLineNumber };
525 case "delete":
526 return line.oldLineNumber === null ? null : { kind: "deleted", oldLine: line.oldLineNumber };
527 case "context":
528 return line.oldLineNumber === null || line.newLineNumber === null
529 ? null
530 : {
531 kind: "context",
532 oldLine: line.oldLineNumber,
533 newLine: line.newLineNumber,
534 side: side === "deletions" ? "left" : "right",
535 };
536 }
538​
539function getDiffRange(
540 lines: ReadonlyArray<DiffReviewLine>,
541 key: "oldLineNumber" | "newLineNumber",
542): { start: number; count: number } {
543 const numberedLines = lines.filter((line) => line[key] !== null);
544 return {
545 start: numberedLines[0]?.[key] ?? 0,
546 count: numberedLines.length,
547 };
549​
550function getDiffChangeMarker(change: DiffReviewLine["change"]): string {
551 if (change === "add") return "+";
552 if (change === "delete") return "-";
553 return " ";
555​
556function formatDiffReviewRangeLabel(lines: ReadonlyArray<DiffReviewLine>): string {
557 const firstLine = lines[0];
558 const lastLine = lines.at(-1);
559 if (!firstLine || !lastLine) return "line";
560 const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber;
561 const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber;
562 if (firstNumber === null || lastNumber === null) {
563 return lines.length === 1 ? "line" : `${lines.length} lines`;
564 }
565​
566 const firstMarker = getDiffChangeMarker(firstLine.change).trim();
567 const marker =
568 firstMarker.length > 0 && lines.every((line) => line.change === firstLine.change)
569 ? firstMarker
570 : "";
571 return firstNumber === lastNumber
572 ? `${marker}${firstNumber}`
573 : `${marker}${firstNumber} to ${marker}${lastNumber}`;
575​
576export function buildDiffReviewComment(input: {
577 id: string;
578 sectionId: string;
579 sectionTitle: string;
580 filePath: string;
581 fileDiff: FileDiffMetadata;
582 range: SelectedLineRange;
583 text: string;
584}): ReviewCommentContext | null {
585 const includeExpandedContext = !input.fileDiff.isPartial;
586 const startIndex = findDiffReviewLineIndex(
587 input.fileDiff,
588 input.range.start,
589 input.range.side,
590 includeExpandedContext,
591 );
592 const endIndex = findDiffReviewLineIndex(
593 input.fileDiff,
594 input.range.end,
595 input.range.endSide ?? input.range.side,
596 includeExpandedContext,
597 );
598 if (startIndex < 0 || endIndex < 0) return null;
599​
600 const normalizedStartIndex = Math.min(startIndex, endIndex);
601 const normalizedEndIndex = Math.max(startIndex, endIndex);
602 const selectedLines = buildDiffReviewLines(input.fileDiff, includeExpandedContext, {
603 startIndex: normalizedStartIndex,
604 endIndex: normalizedEndIndex,
605 });
606 const oldRange = getDiffRange(selectedLines, "oldLineNumber");
607 const newRange = getDiffRange(selectedLines, "newLineNumber");
608​
609 return {
610 id: input.id,
611 sectionId: input.sectionId,
612 sectionTitle: input.sectionTitle,
613 filePath: input.filePath,
614 startIndex: normalizedStartIndex,
615 endIndex: normalizedEndIndex,
616 rangeLabel: formatDiffReviewRangeLabel(selectedLines),
617 text: input.text.trim(),
618 diff: [
619 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
620 ...selectedLines.map((line) => `${getDiffChangeMarker(line.change)}${line.content}`),
621 ].join("\n"),
622 fenceLanguage: "diff",
623 selection: {
624 start: input.range.start,
625 side: input.range.side ?? "additions",
626 end: input.range.end,
627 endSide: input.range.endSide ?? input.range.side ?? "additions",
628 },
629 };
631​
632export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
633 if ((comment.fenceLanguage ?? "diff") !== "diff") {
634 return "";
635 }
636 const diff = comment.diff.trim();
637 if (diff.length === 0) {
638 return "";
639 }
640 if (diff.startsWith("diff --git ")) {
641 return diff;
642 }
643​
644 const normalizedPath = comment.filePath.replaceAll("\\", "/");
645 return [
646 `diff --git a/${normalizedPath} b/${normalizedPath}`,
647 `--- a/${normalizedPath}`,
648 `+++ b/${normalizedPath}`,
649 diff,
650 ].join("\n");