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