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

reviewCommentContext.ts

459 lines14.2 KB

1import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";
2import * as Schema from "effect/Schema";
3​
4export const ReviewCommentContextSchema = Schema.Struct({
5 id: Schema.String,
6 sectionId: Schema.String,
7 sectionTitle: Schema.String,
8 filePath: Schema.String,
9 startIndex: Schema.Number,
10 endIndex: Schema.Number,
11 rangeLabel: Schema.String,
12 text: Schema.String,
13 diff: Schema.String,
14 fenceLanguage: Schema.optional(Schema.String),
15});
16​
17export interface ReviewCommentContext {
18 readonly id: string;
19 readonly sectionId: string;
20 readonly sectionTitle: string;
21 readonly filePath: string;
22 readonly startIndex: number;
23 readonly endIndex: number;
24 readonly rangeLabel: string;
25 readonly text: string;
26 readonly diff: string;
27 readonly fenceLanguage?: string | undefined;
29​
30interface DiffReviewLine {
31 readonly change: "context" | "add" | "delete";
32 readonly oldLineNumber: number | null;
33 readonly newLineNumber: number | null;
34 readonly content: string;
36​
37export type ReviewCommentMessageSegment =
38 | {
39 readonly kind: "text";
40 readonly id: string;
41 readonly text: string;
42 }
43 | {
44 readonly kind: "review-comment";
45 readonly comment: ReviewCommentContext;
46 };
47​
48const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
49const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
50const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
51​
52function escapeReviewCommentAttribute(value: string): string {
53 return value
54 .replace(/&/g, "&amp;")
55 .replace(/"/g, "&quot;")
56 .replace(/</g, "&lt;")
57 .replace(/>/g, "&gt;");
59​
60function unescapeReviewCommentAttribute(value: string): string {
61 return value
62 .replace(/&lt;/g, "<")
63 .replace(/&gt;/g, ">")
64 .replace(/&quot;/g, '"')
65 .replace(/&amp;/g, "&");
67​
68function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
69 const attributes: Record<string, string> = {};
70 for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
71 attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
72 }
73 return attributes;
75​
76function readNonNegativeInteger(value: string | undefined): number | null {
77 if (value === undefined || !/^\d+$/.test(value)) {
78 return null;
79 }
80 return Number(value);
82​
83function extractReviewCommentBody(rawBody: string): {
84 text: string;
85 language: string;
86 contents: string;
87} {
88 const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
89 const match = matches.at(-1);
90 const fenceIndex = match?.index;
91 return {
92 text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
93 language: match?.[2]?.trim() || "diff",
94 contents: match?.[3] ?? "",
95 };
97​
98function parseReviewCommentContext(
99 rawAttributes: string,
100 rawBody: string,
101 index: number,
102): ReviewCommentContext | null {
103 const attributes = readReviewCommentAttributes(rawAttributes);
104 const startIndex = readNonNegativeInteger(attributes.startIndex);
105 const endIndex = readNonNegativeInteger(attributes.endIndex);
106 const filePath = attributes.filePath?.trim();
107 const sectionId = attributes.sectionId?.trim();
108 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
109 return null;
110 }
111 const body = extractReviewCommentBody(rawBody);
112​
113 return {
114 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
115 sectionId,
116 sectionTitle: attributes.sectionTitle?.trim() || "Review",
117 filePath,
118 startIndex: Math.min(startIndex, endIndex),
119 endIndex: Math.max(startIndex, endIndex),
120 rangeLabel: attributes.rangeLabel?.trim() || "line",
121 text: body.text,
122 diff: body.contents,
123 fenceLanguage: body.language,
124 };
126​
127export function parseReviewCommentMessageSegments(
128 value: string,
129): ReadonlyArray<ReviewCommentMessageSegment> {
130 const segments: ReviewCommentMessageSegment[] = [];
131 let cursor = 0;
132 let parsedCommentIndex = 0;
133​
134 for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
135 const matchIndex = match.index ?? 0;
136 const beforeText = value.slice(cursor, matchIndex);
137 if (beforeText.length > 0) {
138 segments.push({
139 kind: "text",
140 id: `review-comment-text:${cursor}`,
141 text: beforeText,
142 });
143 }
144​
145 const comment = parseReviewCommentContext(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
146 if (comment) {
147 segments.push({ kind: "review-comment", comment });
148 parsedCommentIndex += 1;
149 } else {
150 segments.push({
151 kind: "text",
152 id: `review-comment-invalid:${matchIndex}`,
153 text: match[0],
154 });
155 }
156​
157 cursor = matchIndex + match[0].length;
158 }
159​
160 const rest = value.slice(cursor);
161 if (rest.length > 0) {
162 segments.push({
163 kind: "text",
164 id: `review-comment-text:${cursor}`,
165 text: rest,
166 });
167 }
168​
169 return segments;
171​
172export function hasReviewCommentMessageSegments(value: string): boolean {
173 return parseReviewCommentMessageSegments(value).some(
174 (segment) => segment.kind === "review-comment",
175 );
177​
178export function formatReviewCommentFence(language: string, contents: string): string {
179 const longestBacktickRun = Math.max(
180 0,
181 ...Array.from(contents.matchAll(/`+/g), (match) => match[0].length),
182 );
183 const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
184 return [`${fence}${language}`, contents.trimEnd(), fence].join("\n");
186​
187export function formatReviewCommentContext(comment: ReviewCommentContext): string {
188 return [
189 [
190 "<review_comment",
191 ` sectionId="${escapeReviewCommentAttribute(comment.sectionId)}"`,
192 ` sectionTitle="${escapeReviewCommentAttribute(comment.sectionTitle)}"`,
193 ` filePath="${escapeReviewCommentAttribute(comment.filePath)}"`,
194 ` startIndex="${comment.startIndex}"`,
195 ` endIndex="${comment.endIndex}"`,
196 ` rangeLabel="${escapeReviewCommentAttribute(comment.rangeLabel)}"`,
197 ">",
198 ].join(""),
199 comment.text.trim(),
200 formatReviewCommentFence(comment.fenceLanguage ?? "diff", comment.diff),
201 "</review_comment>",
202 ].join("\n");
204​
205export function appendReviewCommentsToPrompt(
206 prompt: string,
207 comments: ReadonlyArray<ReviewCommentContext>,
208): string {
209 const blocks = comments.map(formatReviewCommentContext);
210 if (blocks.length === 0) return prompt;
211 const trimmedPrompt = prompt.trim();
212 return trimmedPrompt.length > 0
213 ? `${trimmedPrompt}\n\n${blocks.join("\n\n")}`
214 : blocks.join("\n\n");
216​
217export function buildFileReviewComment(input: {
218 id: string;
219 filePath: string;
220 startLine: number;
221 endLine: number;
222 text: string;
223 contents: string;
224}): ReviewCommentContext {
225 const startLine = Math.max(1, Math.min(input.startLine, input.endLine));
226 const endLine = Math.max(startLine, Math.max(input.startLine, input.endLine));
227 const selectedLines = input.contents.split("\n").slice(startLine - 1, endLine);
228 return {
229 id: input.id,
230 sectionId: `file:${input.filePath}`,
231 sectionTitle: "File comment",
232 filePath: input.filePath,
233 startIndex: startLine - 1,
234 endIndex: endLine - 1,
235 rangeLabel: startLine === endLine ? `L${startLine}` : `L${startLine} to L${endLine}`,
236 text: input.text.trim(),
237 diff: selectedLines.join("\n"),
238 fenceLanguage: inferReviewCommentFenceLanguage(input.filePath),
239 };
241​
242export function inferReviewCommentFenceLanguage(filePath: string): string {
243 const normalizedPath = filePath.replaceAll("\\", "/");
244 const fileName = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1).toLowerCase();
245 const extensionIndex = fileName.lastIndexOf(".");
246 if (extensionIndex > 0 && extensionIndex < fileName.length - 1) {
247 return fileName.slice(extensionIndex + 1);
248 }
249 if (fileName.startsWith(".") && fileName.length > 1) {
250 return fileName.slice(1);
251 }
252 return "text";
254​
255function stripTrailingNewline(value: string): string {
256 return value.endsWith("\n") ? value.slice(0, -1) : value;
258​
259function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffReviewLine> {
260 const rows: DiffReviewLine[] = [];
261​
262 for (const hunk of fileDiff.hunks) {
263 let oldLineNumber = hunk.deletionStart;
264 let newLineNumber = hunk.additionStart;
265 let deletionLineIndex = hunk.deletionLineIndex;
266 let additionLineIndex = hunk.additionLineIndex;
267​
268 for (const segment of hunk.hunkContent) {
269 if (segment.type === "context") {
270 for (let index = 0; index < segment.lines; index += 1) {
271 rows.push({
272 change: "context",
273 oldLineNumber,
274 newLineNumber,
275 content: stripTrailingNewline(
276 fileDiff.additionLines[additionLineIndex] ??
277 fileDiff.deletionLines[deletionLineIndex] ??
278 "",
279 ),
280 });
281 oldLineNumber += 1;
282 newLineNumber += 1;
283 deletionLineIndex += 1;
284 additionLineIndex += 1;
285 }
286 continue;
287 }
288​
289 for (let index = 0; index < segment.deletions; index += 1) {
290 rows.push({
291 change: "delete",
292 oldLineNumber,
293 newLineNumber: null,
294 content: stripTrailingNewline(fileDiff.deletionLines[deletionLineIndex] ?? ""),
295 });
296 oldLineNumber += 1;
297 deletionLineIndex += 1;
298 }
299​
300 for (let index = 0; index < segment.additions; index += 1) {
301 rows.push({
302 change: "add",
303 oldLineNumber: null,
304 newLineNumber,
305 content: stripTrailingNewline(fileDiff.additionLines[additionLineIndex] ?? ""),
306 });
307 newLineNumber += 1;
308 additionLineIndex += 1;
309 }
310 }
311 }
312​
313 return rows;
315​
316function getDiffReviewSelectionPoint(
317 line: DiffReviewLine,
318): { lineNumber: number; side: SelectionSide } | null {
319 if (line.change === "delete" && line.oldLineNumber !== null) {
320 return { lineNumber: line.oldLineNumber, side: "deletions" };
321 }
322 if (line.newLineNumber !== null) {
323 return { lineNumber: line.newLineNumber, side: "additions" };
324 }
325 if (line.oldLineNumber !== null) {
326 return { lineNumber: line.oldLineNumber, side: "deletions" };
327 }
328 return null;
330​
331export function restoreDiffReviewCommentRange(
332 fileDiff: FileDiffMetadata,
333 comment: ReviewCommentContext,
334): SelectedLineRange | null {
335 const lines = buildDiffReviewLines(fileDiff);
336 const startLine = lines[comment.startIndex];
337 const endLine = lines[comment.endIndex];
338 if (!startLine || !endLine) return null;
339 const start = getDiffReviewSelectionPoint(startLine);
340 const end = getDiffReviewSelectionPoint(endLine);
341 if (!start || !end) return null;
342 return {
343 start: start.lineNumber,
344 side: start.side,
345 end: end.lineNumber,
346 endSide: end.side,
347 };
349​
350function findDiffReviewLineIndex(
351 lines: ReadonlyArray<DiffReviewLine>,
352 lineNumber: number,
353 side: SelectionSide | undefined,
354): number {
355 const preferredKey = side === "deletions" ? "oldLineNumber" : "newLineNumber";
356 const preferredIndex = lines.findIndex((line) => line[preferredKey] === lineNumber);
357 if (preferredIndex >= 0) return preferredIndex;
358 const fallbackKey = preferredKey === "oldLineNumber" ? "newLineNumber" : "oldLineNumber";
359 return lines.findIndex((line) => line[fallbackKey] === lineNumber);
361​
362function getDiffRange(
363 lines: ReadonlyArray<DiffReviewLine>,
364 key: "oldLineNumber" | "newLineNumber",
365): { start: number; count: number } {
366 const numberedLines = lines.filter((line) => line[key] !== null);
367 return {
368 start: numberedLines[0]?.[key] ?? 0,
369 count: numberedLines.length,
370 };
372​
373function getDiffChangeMarker(change: DiffReviewLine["change"]): string {
374 if (change === "add") return "+";
375 if (change === "delete") return "-";
376 return " ";
378​
379function formatDiffReviewRangeLabel(lines: ReadonlyArray<DiffReviewLine>): string {
380 const firstLine = lines[0];
381 const lastLine = lines.at(-1);
382 if (!firstLine || !lastLine) return "line";
383 const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber;
384 const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber;
385 if (firstNumber === null || lastNumber === null) {
386 return lines.length === 1 ? "line" : `${lines.length} lines`;
387 }
388​
389 const firstMarker = getDiffChangeMarker(firstLine.change).trim();
390 const marker =
391 firstMarker.length > 0 && lines.every((line) => line.change === firstLine.change)
392 ? firstMarker
393 : "";
394 return firstNumber === lastNumber
395 ? `${marker}${firstNumber}`
396 : `${marker}${firstNumber} to ${marker}${lastNumber}`;
398​
399export function buildDiffReviewComment(input: {
400 id: string;
401 sectionId: string;
402 sectionTitle: string;
403 filePath: string;
404 fileDiff: FileDiffMetadata;
405 range: SelectedLineRange;
406 text: string;
407}): ReviewCommentContext | null {
408 const lines = buildDiffReviewLines(input.fileDiff);
409 const startIndex = findDiffReviewLineIndex(lines, input.range.start, input.range.side);
410 const endIndex = findDiffReviewLineIndex(
411 lines,
412 input.range.end,
413 input.range.endSide ?? input.range.side,
414 );
415 if (startIndex < 0 || endIndex < 0) return null;
416​
417 const normalizedStartIndex = Math.min(startIndex, endIndex);
418 const normalizedEndIndex = Math.max(startIndex, endIndex);
419 const selectedLines = lines.slice(normalizedStartIndex, normalizedEndIndex + 1);
420 const oldRange = getDiffRange(selectedLines, "oldLineNumber");
421 const newRange = getDiffRange(selectedLines, "newLineNumber");
422​
423 return {
424 id: input.id,
425 sectionId: input.sectionId,
426 sectionTitle: input.sectionTitle,
427 filePath: input.filePath,
428 startIndex: normalizedStartIndex,
429 endIndex: normalizedEndIndex,
430 rangeLabel: formatDiffReviewRangeLabel(selectedLines),
431 text: input.text.trim(),
432 diff: [
433 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
434 ...selectedLines.map((line) => `${getDiffChangeMarker(line.change)}${line.content}`),
435 ].join("\n"),
436 fenceLanguage: "diff",
437 };
439​
440export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
441 if ((comment.fenceLanguage ?? "diff") !== "diff") {
442 return "";
443 }
444 const diff = comment.diff.trim();
445 if (diff.length === 0) {
446 return "";
447 }
448 if (diff.startsWith("diff --git ")) {
449 return diff;
450 }
451​
452 const normalizedPath = comment.filePath.replaceAll("\\", "/");
453 return [
454 `diff --git a/${normalizedPath} b/${normalizedPath}`,
455 `--- a/${normalizedPath}`,
456 `+++ b/${normalizedPath}`,
457 diff,
458 ].join("\n");