Open History to see the last commit
1import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
2import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
3import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
4import { turnChanges, turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories";
5import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
6import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
7import * as Arr from "effect/Array";
8import { pipe } from "effect/Function";
9import * as Order from "effect/Order";
10import { msg } from "gt-react-native";
11
12import { m, type MessageResolver } from "../../i18n/messages";
13
14export type ReviewSectionKind = "turn" | "working-tree" | "branch-range";
15export type ReviewGitSectionKind = Exclude<ReviewSectionKind, "turn">;
16type ReviewGitSource = ReviewDiffPreviewSource & { readonly kind: ReviewGitSectionKind };
17
18const CHANGES_SECTION_ID = "git:branch-range";
19const GIT_SECTION_KINDS = ["working-tree", "branch-range"] as const;
20const GIT_PLACEHOLDER_TITLES = {
21 "working-tree": msg("Uncommitted", { $context: "diff section: working tree" }),
22 "branch-range": msg("Changes", { $context: "diff section: branch changes" }),
23} as const satisfies Record<ReviewGitSectionKind, unknown>;
24const UNCOMMITTED_SUBTITLE = msg("Staged, unstaged, and untracked files");
25
26/** A folder of a turn's patch: the thread's own (`relativePath` empty) or a tracked repository. */
27export interface ReviewRepositoryGroup {
28 readonly key: string;
29 readonly name: string;
30 readonly relativePath: string;
31}
32
33export interface ReviewSectionItem {
34 readonly id: string;
35 readonly kind: ReviewSectionKind;
36 readonly title: string;
37 readonly subtitle: string | null;
38 readonly diff: string | null;
39 readonly isLoading: boolean;
40 readonly files?: ReviewDiffPreviewSource["files"];
41 readonly truncated?: boolean;
42 readonly source?: ReviewGitSource;
43 /** Set when a turn's patch spans more than one folder. */
44 readonly repositoryGroups?: ReadonlyArray<ReviewRepositoryGroup>;
45 /** Repositories the turn changed that have nothing recorded before it to compare with. */
46 readonly unlistedRepositories?: ReadonlyArray<string>;
47}
48
49export interface ReviewRenderableHunkRow {
50 readonly kind: "hunk";
51 readonly id: string;
52 readonly header: string;
53 readonly context: string | null;
54}
55
56export interface ReviewRenderableLineRow {
57 readonly kind: "line";
58 readonly id: string;
59 readonly change: "context" | "add" | "delete";
60 readonly oldLineNumber: number | null;
61 readonly newLineNumber: number | null;
62 readonly content: string;
63 readonly additionTokenIndex: number | null;
64 readonly deletionTokenIndex: number | null;
65 readonly comparison: {
66 readonly change: "add" | "delete";
67 readonly tokenIndex: number;
68 } | null;
69}
70
71export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLineRow;
72
73export interface ReviewRenderableFile {
74 readonly id: string;
75 readonly cacheKey: string;
76 readonly notice?: string;
77 readonly noticeTone?: "warning";
78 /** The notice row reports taps, as for loading a withheld file's diff. */
79 readonly noticeActionable?: boolean;
80 /** The host left out this file's hunks as too large; it can be loaded on its own. */
81 readonly withheld?: boolean;
82 readonly path: string;
83 readonly previousPath: string | null;
84 readonly changeType: ChangeTypes;
85 readonly additions: number;
86 readonly deletions: number;
87 readonly languageHint: string | null;
88 readonly additionLines: ReadonlyArray<string>;
89 readonly deletionLines: ReadonlyArray<string>;
90 // Only populated after validating the entire raw file block against its original hunk count.
91 readonly completePatchSource?: () => {
92 readonly oldContents: string;
93 readonly newContents: string;
94 };
95 readonly noEOFCRAdditions?: boolean;
96 readonly noEOFCRDeletions?: boolean;
97 readonly rows: ReadonlyArray<ReviewRenderableRow>;
98}
99
100export type ReviewFilePreviewState =
101 | {
102 readonly kind: "render";
103 }
104 | {
105 readonly kind: "suppressed";
106 readonly reason: "non-text" | "large";
107 readonly title: string;
108 readonly message: string;
109 readonly actionLabel: string | null;
110 };
111
112export type ReviewParsedDiff =
113 | {
114 readonly kind: "empty";
115 }
116 | {
117 readonly kind: "raw";
118 readonly text: string;
119 readonly reason: string;
120 readonly notice: string | null;
121 }
122 | {
123 readonly kind: "files";
124 readonly files: ReadonlyArray<ReviewRenderableFile>;
125 readonly fileCount: number;
126 readonly additions: number;
127 readonly deletions: number;
128 readonly notice: string | null;
129 };
130
131function checkpointTitle(checkpoint: ThreadCheckpointSummary, resolve: MessageResolver): string {
132 return resolve(msg("Turn {count}", { count: checkpoint.checkpointTurnCount }));
133}
134
135function checkpointSubtitle(checkpoint: ThreadCheckpointSummary, resolve: MessageResolver): string {
136 if (checkpoint.status !== "ready" && !turnHasChanges(checkpoint)) {
137 return resolve(msg("Diff {status}", { status: checkpoint.status }));
138 }
139 const { repositories, totals } = turnChanges(checkpoint);
140 const files = resolve(
141 msg("{count, plural, one {{count} file changed} other {{count} files changed}}", {
142 count: totals.count,
143 }),
144 );
145 return repositories.length === 0
146 ? files
147 : `${files} · ${repositories.map((repository) => repository.name).join(", ")}`;
148}
149
150function checkpointRepositoryGroups(
151 checkpoint: ThreadCheckpointSummary,
152 rootName: string,
153): ReadonlyArray<ReviewRepositoryGroup> {
154 const { repositories, rootFiles } = turnChanges(checkpoint);
155 const groups = [
156 ...(rootFiles.length === 0 ? [] : [{ key: ".", name: rootName, relativePath: "" }]),
157 ...repositories.flatMap((repository) =>
158 repository.files.length === 0 || !repository.relativePath || repository.relativePath === "."
159 ? []
160 : [
161 {
162 key: repository.repositoryPath,
163 name: repository.name,
164 relativePath: repository.relativePath,
165 },
166 ],
167 ),
168 ];
169 return groups.length > 1 ? groups : [];
170}
171
172function compareCheckpointTurnCountDescending(
173 left: ThreadCheckpointSummary,
174 right: ThreadCheckpointSummary,
175): -1 | 0 | 1 {
176 if (left.checkpointTurnCount === right.checkpointTurnCount) {
177 return 0;
178 }
179
180 return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
181}
182
183const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
184 compareCheckpointTurnCountDescending,
185);
186
187function gitSubtitle(section: ReviewDiffPreviewSource, resolve: MessageResolver): string | null {
188 if (section.kind === "working-tree") {
189 return resolve(UNCOMMITTED_SUBTITLE);
190 }
191 if (section.baseRef) {
192 return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
193 }
194 return resolve(msg("Base branch unavailable"));
195}
196
197function stripTrailingNewline(value: string): string {
198 return value.endsWith("\n") ? value.slice(0, -1) : value;
199}
200
201function splitTruncationMarker(diff: string): {
202 readonly text: string;
203 readonly truncated: boolean;
204} {
205 const marker = /(?:(?:\r?\n){1,2}|^)\[truncated\]\s*$/.exec(diff);
206 if (!marker) {
207 return { text: diff, truncated: false };
208 }
209
210 return {
211 text: diff.slice(0, marker.index),
212 truncated: true,
213 };
214}
215
216function runDiffParserSilently<T>(callback: () => T): T {
217 const originalConsoleError = console.error;
218 console.error = () => undefined;
219 try {
220 return callback();
221 } finally {
222 console.error = originalConsoleError;
223 }
224}
225
226const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
227const FNV_PRIME_32 = 0x01000193;
228const SECONDARY_HASH_SEED = 0x9e3779b9;
229const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
230const LARGE_DIFF_LINE_THRESHOLD = 400;
231const LARGE_DIFF_CHARACTER_THRESHOLD = 24_000;
232const NON_TEXT_FILE_EXTENSIONS = new Set([
233 "png",
234 "jpg",
235 "jpeg",
236 "gif",
237 "webp",
238 "bmp",
239 "ico",
240 "icns",
241 "avif",
242 "heic",
243 "tif",
244 "tiff",
245 "mp3",
246 "wav",
247 "flac",
248 "ogg",
249 "m4a",
250 "aac",
251 "mp4",
252 "mov",
253 "avi",
254 "mkv",
255 "webm",
256 "pdf",
257 "zip",
258 "gz",
259 "tgz",
260 "bz2",
261 "7z",
262 "rar",
263 "woff",
264 "woff2",
265 "ttf",
266 "otf",
267 "eot",
268 "wasm",
269 "exe",
270 "dll",
271 "so",
272 "dylib",
273]);
274
275function fnv1a32(input: string, seed: number, multiplier: number): number {
276 let hash = seed >>> 0;
277 for (let index = 0; index < input.length; index += 1) {
278 hash ^= input.charCodeAt(index);
279 hash = Math.imul(hash, multiplier) >>> 0;
280 }
281 return hash >>> 0;
282}
283
284function buildPatchCacheKey(patch: string, scope: string): string {
285 const primary = fnv1a32(patch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
286 const secondary = fnv1a32(patch, SECONDARY_HASH_SEED, SECONDARY_HASH_MULTIPLIER).toString(36);
287 return `${scope}:${patch.length}:${primary}:${secondary}`;
288}
289
290// Re-parsing an unchanged page must preserve selection/collapse state. Intern only
291// its cache key (never patch contents), keeping scoped Pierre keys off every UI row.
292const reviewPatchIds = new Map<string, string>();
293
294function getReviewPatchId(cacheKey: string): string {
295 let id = reviewPatchIds.get(cacheKey);
296 if (id === undefined) {
297 id = `p${reviewPatchIds.size.toString(36)}`;
298 reviewPatchIds.set(cacheKey, id);
299 }
300 return id;
301}
302
303function getFileExtension(path: string): string | null {
304 const match = /\.([a-z0-9]+)$/i.exec(path);
305 return match?.[1]?.toLowerCase() ?? null;
306}
307
308function countReviewRenderableLineRows(file: ReviewRenderableFile): number {
309 return file.rows.reduce((total, row) => total + (row.kind === "line" ? 1 : 0), 0);
310}
311
312function countReviewRenderableCharacters(file: ReviewRenderableFile): number {
313 return file.rows.reduce(
314 (total, row) => total + (row.kind === "line" ? row.content.length : row.header.length),
315 0,
316 );
317}
318
319export function getReviewFilePreviewState(
320 file: ReviewRenderableFile,
321 resolve: MessageResolver = m,
322): ReviewFilePreviewState {
323 const extension = getFileExtension(file.path);
324 if (extension && NON_TEXT_FILE_EXTENSIONS.has(extension)) {
325 return {
326 kind: "suppressed",
327 reason: "non-text",
328 title: resolve(msg("Non-text file")),
329 message: resolve(msg("Diff preview is not available for this file format.")),
330 actionLabel: null,
331 };
332 }
333
334 const lineCount = countReviewRenderableLineRows(file);
335 const characterCount = countReviewRenderableCharacters(file);
336 if (lineCount > LARGE_DIFF_LINE_THRESHOLD || characterCount > LARGE_DIFF_CHARACTER_THRESHOLD) {
337 return {
338 kind: "suppressed",
339 reason: "large",
340 title: resolve(msg("Large diff")),
341 message: resolve(msg("Large diffs are not rendered by default.")),
342 actionLabel: resolve(msg("Load diff")),
343 };
344 }
345
346 return { kind: "render" };
347}
348
349function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
350 return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
351}
352
353function buildRenderableRows(
354 file: FileDiffMetadata,
355 fileId: string,
356): ReadonlyArray<ReviewRenderableRow> {
357 const rows: ReviewRenderableRow[] = [];
358 let rowIndex = 0;
359
360 file.hunks.forEach((hunk, hunkIndex) => {
361 rows.push({
362 kind: "hunk",
363 id: `${fileId}:hunk:${hunkIndex}`,
364 header: fallbackHunkHeader(hunk),
365 context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,
366 });
367
368 let deletionLineNumber = hunk.deletionStart;
369 let additionLineNumber = hunk.additionStart;
370 let deletionTokenIndex = hunk.deletionLineIndex;
371 let additionTokenIndex = hunk.additionLineIndex;
372
373 hunk.hunkContent.forEach((segment) => {
374 if (segment.type === "context") {
375 for (let index = 0; index < segment.lines; index += 1) {
376 rows.push({
377 kind: "line",
378 id: `${fileId}:row:${rowIndex++}`,
379 change: "context",
380 oldLineNumber: deletionLineNumber,
381 newLineNumber: additionLineNumber,
382 content: stripTrailingNewline(
383 file.additionLines[additionTokenIndex] ??
384 file.deletionLines[deletionTokenIndex] ??
385 "",
386 ),
387 additionTokenIndex,
388 deletionTokenIndex,
389 comparison: null,
390 });
391 deletionLineNumber += 1;
392 additionLineNumber += 1;
393 deletionTokenIndex += 1;
394 additionTokenIndex += 1;
395 }
396 return;
397 }
398
399 const pairedLineCount = Math.min(segment.deletions, segment.additions);
400 const deletionTokenIndexStart = deletionTokenIndex;
401 const additionTokenIndexStart = additionTokenIndex;
402
403 for (let index = 0; index < segment.deletions; index += 1) {
404 rows.push({
405 kind: "line",
406 id: `${fileId}:row:${rowIndex++}`,
407 change: "delete",
408 oldLineNumber: deletionLineNumber,
409 newLineNumber: null,
410 content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""),
411 additionTokenIndex: null,
412 deletionTokenIndex,
413 comparison:
414 index < pairedLineCount
415 ? {
416 change: "add",
417 tokenIndex: additionTokenIndexStart + index,
418 }
419 : null,
420 });
421 deletionLineNumber += 1;
422 deletionTokenIndex += 1;
423 }
424
425 for (let index = 0; index < segment.additions; index += 1) {
426 rows.push({
427 kind: "line",
428 id: `${fileId}:row:${rowIndex++}`,
429 change: "add",
430 oldLineNumber: null,
431 newLineNumber: additionLineNumber,
432 content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""),
433 additionTokenIndex,
434 deletionTokenIndex: null,
435 comparison:
436 index < pairedLineCount
437 ? {
438 change: "delete",
439 tokenIndex: deletionTokenIndexStart + index,
440 }
441 : null,
442 });
443 additionLineNumber += 1;
444 additionTokenIndex += 1;
445 }
446 });
447 });
448
449 return rows;
450}
451
452function completePatchSource(file: FileDiffMetadata, rawPatch: string | null | undefined) {
453 if (!rawPatch || (file.type !== "new" && file.type !== "deleted") || file.hunks.length !== 1) {
454 return undefined;
455 }
456 const added = file.type === "new";
457 const a = quoteGitPatchPath(`a/${file.name}`);
458 const b = quoteGitPatchPath(`b/${file.name}`);
459 const lines = rawPatch.split("\n");
460 if (lines.pop() !== "" || rawPatch.includes("\0")) return undefined;
461 let index = 0;
462 if (lines[index++] !== `diff --git ${a} ${b}`) return undefined;
463 if (
464 !new RegExp(`^${added ? "new" : "deleted"} file mode 100(644|755)$`).test(lines[index++] ?? "")
465 ) {
466 return undefined;
467 }
468 if (lines[index]?.startsWith("index ")) {
469 if (!/^index [0-9a-f]+\.\.[0-9a-f]+(?: 100(?:644|755))?$/.test(lines[index++] ?? "")) {
470 return undefined;
471 }
472 }
473 if (lines[index++] !== `--- ${added ? "/dev/null" : a}`) return undefined;
474 if (lines[index++] !== `+++ ${added ? b : "/dev/null"}`) return undefined;
475 // Pierre repairs both underfull and overfull hunks. Its resulting counts cannot
476 // prove that patch lines cover the whole file; read the original header instead.
477 const header = lines[index++] ?? "";
478 // GitCafe's structured hunks can start the empty side at 1 instead of git's 0.
479 // Its explicit zero count still proves that side contributes no source lines.
480 const match = (added ? /^@@ -[01],0 \+1(?:,(\d+))? @@$/ : /^@@ -1(?:,(\d+))? \+[01],0 @@$/).exec(
481 header,
482 );
483 if (!match) return undefined;
484 const count = Number(match[1] ?? 1);
485 if (!Number.isSafeInteger(count) || count <= 0) return undefined;
486 const hunk = file.hunks[0]!;
487 if (
488 hunk.hunkSpecs !== `${header}\n` ||
489 (added ? hunk.additionCount : hunk.deletionCount) !== count ||
490 (added ? file.additionLines : file.deletionLines).length !== count ||
491 (added ? file.deletionLines : file.additionLines).length !== 0
492 )
493 return undefined;
494 const bodyStart = lines.slice(0, index).reduce((length, line) => length + line.length + 1, 0);
495 const prefix = added ? "+" : "-";
496 for (let line = 0; line < count; line++) {
497 if (!lines[index++]?.startsWith(prefix)) return undefined;
498 }
499 let bodyEnd = rawPatch.length;
500 if (lines[index] === "\\ No newline at end of file") {
501 // Only the patch's LF is synthetic, including when the source ends in a bare CR.
502 bodyEnd -= "\\ No newline at end of file\n".length + 1;
503 index++;
504 }
505 if (index !== lines.length) return undefined;
506 // Keep reconstruction lazy so only requested source enters the bounded source cache.
507 return () => {
508 const contents = rawPatch.slice(bodyStart + 1, bodyEnd).replace(/\n[+-]/g, "\n");
509 return added
510 ? { oldContents: "", newContents: contents }
511 : { oldContents: contents, newContents: "" };
512 };
513}
514
515function mapRenderableFile(
516 file: FileDiffMetadata,
517 id: string,
518 rawPatch?: string | null,
519): ReviewRenderableFile {
520 const path = file.name || file.prevName || "";
521 const previousPath = file.prevName || null;
522 const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
523 const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);
524 const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
525
526 return {
527 id,
528 cacheKey,
529 path,
530 previousPath,
531 changeType: file.type,
532 additions,
533 deletions,
534 languageHint: file.lang ?? null,
535 additionLines: file.additionLines,
536 deletionLines: file.deletionLines,
537 completePatchSource: completePatchSource(file, rawPatch),
538 noEOFCRAdditions: file.hunks.some((hunk) => hunk.noEOFCRAdditions),
539 noEOFCRDeletions: file.hunks.some((hunk) => hunk.noEOFCRDeletions),
540 rows: buildRenderableRows(file, id),
541 };
542}
543
544export function getReviewSectionIdForCheckpoint(
545 checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
546): string {
547 return `turn:${checkpoint.checkpointTurnCount}`;
548}
549
550export function getReadyReviewCheckpoints(
551 checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
552): ReadonlyArray<ThreadCheckpointSummary> {
553 return pipe(
554 checkpoints,
555 // A plain folder holding repositories never has a ready checkpoint of its own.
556 Arr.filter((checkpoint) => checkpoint.status === "ready" || turnHasChanges(checkpoint)),
557 Arr.sort(readyCheckpointOrder),
558 );
559}
560
561export function reviewTurnDiffsBySectionId(
562 checkpoints: ReadonlyArray<Pick<ThreadCheckpointSummary, "checkpointTurnCount">>,
563 diffByTurnCount: Readonly<Record<number, string | undefined>>,
564): Readonly<Record<string, string | undefined>> {
565 return Object.fromEntries(
566 checkpoints.map((checkpoint) => [
567 getReviewSectionIdForCheckpoint(checkpoint),
568 diffByTurnCount[checkpoint.checkpointTurnCount],
569 ]),
570 );
571}
572
573export function buildReviewSectionItems(input: {
574 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
575 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
576 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
577 readonly gitSectionStates: Readonly<Record<ReviewGitSectionKind, "loading" | "failed" | null>>;
578 /** Names the thread folder's own files beside its repositories. */
579 readonly rootName?: string;
580 readonly resolve?: MessageResolver;
581}): ReadonlyArray<ReviewSectionItem> {
582 const resolve = input.resolve ?? m;
583 const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
584 (checkpoint) => {
585 const id = getReviewSectionIdForCheckpoint(checkpoint);
586 const repositoryGroups = checkpointRepositoryGroups(checkpoint, input.rootName ?? "Project");
587 const unlistedRepositories = (checkpoint.repositories ?? []).flatMap((repository) =>
588 repository.baselineMissing ? [repository.name] : [],
589 );
590 return {
591 id,
592 kind: "turn",
593 title: checkpointTitle(checkpoint, resolve),
594 subtitle: checkpointSubtitle(checkpoint, resolve),
595 diff: input.turnDiffById[id] ?? null,
596 isLoading: false,
597 ...(repositoryGroups.length === 0 ? {} : { repositoryGroups }),
598 ...(unlistedRepositories.length === 0 ? {} : { unlistedRepositories }),
599 };
600 },
601 );
602
603 const gitItems = GIT_SECTION_KINDS.flatMap<ReviewSectionItem>((kind) => {
604 const section = input.gitSections.find(
605 (candidate): candidate is ReviewGitSource => candidate.kind === kind,
606 );
607 if (section) {
608 return [
609 {
610 id: `git:${kind}`,
611 kind,
612 title: section.title,
613 subtitle: gitSubtitle(section, resolve),
614 diff: section.diff,
615 source: section,
616 ...(section.files ? { files: section.files } : {}),
617 truncated: section.truncated,
618 isLoading: false,
619 },
620 ];
621 }
622 const state = input.gitSectionStates[kind];
623 return state === null
624 ? []
625 : [
626 {
627 id: `git:${kind}`,
628 kind,
629 title: resolve(GIT_PLACEHOLDER_TITLES[kind]),
630 subtitle: null,
631 diff: null,
632 isLoading: state === "loading",
633 },
634 ];
635 });
636
637 return [...turnItems, ...gitItems];
638}
639
640export function getDefaultReviewSectionId(
641 sections: ReadonlyArray<ReviewSectionItem>,
642): string | null {
643 return (sections.find((section) => section.id === CHANGES_SECTION_ID) ?? sections[0])?.id ?? null;
644}
645
646/**
647 * The store holds only the user's pick. While that section is missing (still loading, or the
648 * working tree went clean) the default shows, and the pick returns once the section does: the
649 * thread-feed entry relies on this, as it selects a section before the sections have loaded.
650 */
651export function resolveReviewSelectedSectionId(
652 sections: ReadonlyArray<ReviewSectionItem>,
653 storedSectionId: string | null,
654): string | null {
655 return storedSectionId !== null && sections.some((section) => section.id === storedSectionId)
656 ? storedSectionId
657 : getDefaultReviewSectionId(sections);
658}
659
660export function buildReviewParsedDiff(
661 diff: string | null | undefined,
662 cacheScope: string,
663 resolve: MessageResolver = m,
664): ReviewParsedDiff {
665 if (!diff?.trim()) {
666 return { kind: "empty" };
667 }
668
669 const { text, truncated } = splitTruncationMarker(diff);
670 if (text.length === 0) {
671 return { kind: "empty" };
672 }
673
674 const notice = truncated
675 ? resolve(msg("Diff output hit the server size cap. Showing the available excerpt."))
676 : null;
677
678 try {
679 const cacheKey = buildPatchCacheKey(text, cacheScope);
680 const patchId = getReviewPatchId(cacheKey);
681 const parsedPatches = runDiffParserSilently(() =>
682 parsePatchFiles(text, { cacheKeyPrefix: cacheKey }),
683 );
684 const rawFiles = new Map<string, string | null>();
685 if (!truncated) {
686 for (const rawFile of text.split(/(?=^diff --git )/m)) {
687 const header = rawFile.slice(0, rawFile.indexOf("\n"));
688 rawFiles.set(header, rawFiles.has(header) ? null : rawFile);
689 }
690 }
691 const files = pipe(
692 parsedPatches,
693 Arr.flatMap((patch) => patch.files),
694 Arr.map((file, index) =>
695 mapRenderableFile(
696 file,
697 `${patchId}:f${index.toString(36)}`,
698 rawFiles.get(
699 `diff --git ${quoteGitPatchPath(`a/${file.name}`)} ${quoteGitPatchPath(`b/${file.name}`)}`,
700 ),
701 ),
702 ),
703 );
704
705 if (files.length === 0) {
706 return {
707 kind: "raw",
708 text,
709 reason: truncated
710 ? resolve(
711 msg(
712 "Diff was truncated before it could be parsed completely. Showing the raw excerpt.",
713 ),
714 )
715 : resolve(msg("Unsupported diff format. Showing raw patch.")),
716 notice,
717 };
718 }
719
720 return {
721 kind: "files",
722 files,
723 fileCount: files.length,
724 additions: files.reduce((total, file) => total + file.additions, 0),
725 deletions: files.reduce((total, file) => total + file.deletions, 0),
726 notice,
727 };
728 } catch {
729 return {
730 kind: "raw",
731 text,
732 reason: truncated
733 ? resolve(
734 msg(
735 "Diff was truncated before it could be parsed completely. Showing the raw excerpt.",
736 ),
737 )
738 : resolve(msg("Failed to parse patch. Showing raw patch.")),
739 notice,
740 };
741 }
742}
743
744export function applyReviewDiffMetadata(
745 previewDiff: ReviewParsedDiff,
746 selectedSection: Pick<ReviewSectionItem, "files" | "truncated"> | null,
747 resolve: MessageResolver = m,
748): ReviewParsedDiff {
749 if (previewDiff.kind === "empty") return previewDiff;
750 const notice = selectedSection?.truncated
751 ? selectedSection.files
752 ? resolve(
753 msg(
754 "This preview exceeds the size limit. Changes shown are incomplete. Counts include all changes.",
755 ),
756 )
757 : resolve(msg("This preview exceeds the size limit. Changes shown are incomplete."))
758 : previewDiff.notice;
759 if (previewDiff.kind !== "files" || !selectedSection?.files) return { ...previewDiff, notice };
760 const totals = selectedSection.files.reduce(
761 (total, file) => ({
762 additions: total.additions + file.additions,
763 deletions: total.deletions + file.deletions,
764 }),
765 { additions: 0, deletions: 0 },
766 );
767 const stats = new Map(selectedSection.files.map((file) => [file.path, file]));
768 const files = previewDiff.files.map((file) => {
769 const stat = stats.get(file.path);
770 return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
771 });
772 return { ...previewDiff, ...totals, files, fileCount: selectedSection.files.length, notice };
773}
774
775/**
776 * The files of one folder of a turn's patch. A file belongs to the deepest folder holding it,
777 * and to the thread's own (the empty folder) when no repository does.
778 */
779export function filterReviewParsedDiffToFolder(
780 parsedDiff: ReviewParsedDiff,
781 folder: string,
782 folders: ReadonlyArray<string>,
783): ReviewParsedDiff {
784 if (parsedDiff.kind !== "files") return parsedDiff;
785 const files = parsedDiff.files.filter((file) => {
786 let owner = "";
787 for (const candidate of folders) {
788 if (candidate.length > owner.length && file.path.startsWith(`${candidate}/`)) {
789 owner = candidate;
790 }
791 }
792 return owner === folder;
793 });
794 return {
795 ...parsedDiff,
796 files,
797 fileCount: files.length,
798 additions: files.reduce((total, file) => total + file.additions, 0),
799 deletions: files.reduce((total, file) => total + file.deletions, 0),
800 };
801}