Open History to see the last commit
1import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
2import type { PullRequestDiffResult } from "@t3tools/contracts";
3import {
4 buildReviewParsedDiff,
5 type ReviewParsedDiff,
6 type ReviewRenderableFile,
7} from "../review/reviewModel";
8
9export interface PullRequestDiffPage {
10 readonly cursor: string | null;
11 readonly result: PullRequestDiffResult;
12}
13
14interface CachedPullRequestDiffPages {
15 readonly pages: readonly PullRequestDiffPage[];
16 readonly cache: WeakMap<PullRequestDiffResult, ReviewParsedDiff>;
17 readonly parsed: ReviewParsedDiff;
18}
19
20// Keep only the latest combination per scoped first page; query results own its lifetime.
21const parsedSnapshots = new WeakMap<
22 PullRequestDiffResult,
23 Map<string, CachedPullRequestDiffPages>
24>();
25
26export function getCachedPullRequestDiffPages(
27 pages: readonly PullRequestDiffPage[],
28 scope: string,
29 terminology: ChangeRequestTerminology,
30): ReviewParsedDiff {
31 const first = pages[0];
32 if (!first) return { kind: "empty" };
33 const key = JSON.stringify([scope, terminology.singular, first.cursor]);
34 let snapshots = parsedSnapshots.get(first.result);
35 if (!snapshots) {
36 snapshots = new Map();
37 parsedSnapshots.set(first.result, snapshots);
38 }
39 const previous = snapshots.get(key);
40 if (
41 previous?.pages.length === pages.length &&
42 pages.every((page, index) => {
43 const cached = previous.pages[index];
44 return cached?.cursor === page.cursor && cached.result === page.result;
45 })
46 )
47 return previous.parsed;
48 const cache = previous?.cache ?? new WeakMap<PullRequestDiffResult, ReviewParsedDiff>();
49 const parsed = combinePullRequestDiffPages(pages, cache, scope, terminology);
50 snapshots.set(key, { pages, cache, parsed });
51 return parsed;
52}
53
54/** A changed page invalidates later cursors, which belong to the previous patch. */
55export function retainPullRequestDiffPage(
56 pages: readonly PullRequestDiffPage[],
57 cursor: string | null,
58 result: PullRequestDiffResult,
59): readonly PullRequestDiffPage[] {
60 const index = pages.findIndex((page) => page.cursor === cursor);
61 if (index === -1) return [...pages, { cursor, result }];
62 const previous = pages[index]?.result;
63 if (
64 previous === result ||
65 (previous?.patch === result.patch &&
66 previous.truncated === result.truncated &&
67 previous.nextCursor === result.nextCursor &&
68 previous.withheldFilesReadable === result.withheldFilesReadable &&
69 JSON.stringify(previous.omittedFileStats ?? []) ===
70 JSON.stringify(result.omittedFileStats ?? []))
71 )
72 return pages;
73 return [...pages.slice(0, index), { cursor, result }];
74}
75
76export function combinePullRequestDiffPages(
77 pages: readonly PullRequestDiffPage[],
78 cache: WeakMap<PullRequestDiffResult, ReviewParsedDiff>,
79 scope: string,
80 terminology: ChangeRequestTerminology,
81): ReviewParsedDiff {
82 const parsed = pages.map((page) => {
83 const cached = cache.get(page.result);
84 if (cached) return cached;
85 let value = buildReviewParsedDiff(page.result.patch, `${scope}:${page.cursor ?? "first"}`);
86 if (value.kind === "files" && page.result.omittedFileStats?.length) {
87 const omittedFileStats = new Map(
88 page.result.omittedFileStats.map((stat) => [stat.path, stat]),
89 );
90 const files = value.files.map((file) => {
91 const stat = omittedFileStats.get(file.path);
92 if (!stat) return file;
93 return {
94 ...file,
95 additions: stat.additions,
96 deletions: stat.deletions,
97 ...(file.rows.length === 0 ? { withheld: true } : {}),
98 };
99 });
100 value = {
101 ...value,
102 files,
103 additions: files.reduce((total, file) => total + file.additions, 0),
104 deletions: files.reduce((total, file) => total + file.deletions, 0),
105 };
106 }
107 cache.set(page.result, value);
108 return value;
109 });
110 const files = parsed.flatMap((page) => (page.kind === "files" ? page.files : []));
111 if (files.length === 0) return parsed[0] ?? { kind: "empty" };
112 return {
113 kind: "files",
114 files,
115 fileCount: files.length,
116 additions: files.reduce((total, file) => total + file.additions, 0),
117 deletions: files.reduce((total, file) => total + file.deletions, 0),
118 notice:
119 pages.some((page) => page.result.truncated) ||
120 parsed.some((page) => page.kind === "raw" || (page.kind === "files" && page.notice !== null))
121 ? `Some file contents are unavailable. Open the ${terminology.singular} on its provider to see the full changes.`
122 : null,
123 };
124}
125
126export type WithheldFileLoad =
127 | { readonly status: "loading" | "error" }
128 | { readonly status: "loaded"; readonly result: PullRequestDiffResult };
129
130const withheldFileParses = new WeakMap<PullRequestDiffResult, ReviewRenderableFile | null>();
131
132function parseWithheldFile(result: PullRequestDiffResult, scope: string) {
133 if (withheldFileParses.has(result)) return withheldFileParses.get(result) ?? null;
134 const parsed = buildReviewParsedDiff(result.patch, scope);
135 const file =
136 parsed.kind === "files" ? (parsed.files.find((entry) => entry.rows.length > 0) ?? null) : null;
137 withheldFileParses.set(result, file);
138 return file;
139}
140
141function withheldFileNotice(load: WithheldFileLoad | undefined, canLoad: boolean): string {
142 if (load === undefined) {
143 return canLoad
144 ? "Diff too large to display. Tap to load it."
145 : "Diff too large to display here.";
146 }
147 if (load.status === "loading") return "Loading diff…";
148 if (load.status === "error") return "Couldn't load this diff. Tap to try again.";
149 return "No text diff for this file.";
150}
151
152/**
153 * Puts each loaded withheld file in place of its empty one, under the same id so folds and
154 * targets hold, and gives the rest a notice saying what a tap does.
155 */
156export function withWithheldFiles(
157 parsed: ReviewParsedDiff,
158 loads: ReadonlyMap<string, WithheldFileLoad>,
159 canLoad: boolean,
160 scope: string,
161): ReviewParsedDiff {
162 if (parsed.kind !== "files" || !parsed.files.some((file) => file.withheld)) return parsed;
163 const files = parsed.files.map((file): ReviewRenderableFile => {
164 if (!file.withheld) return file;
165 const load = loads.get(file.path);
166 const loaded =
167 load?.status === "loaded"
168 ? parseWithheldFile(load.result, `${scope}:withheld:${file.path}`)
169 : null;
170 if (loaded !== null) return { ...loaded, id: file.id };
171 return {
172 ...file,
173 notice: withheldFileNotice(load, canLoad),
174 noticeTone: "warning",
175 noticeActionable: canLoad && (load === undefined || load.status === "error"),
176 };
177 });
178 return {
179 ...parsed,
180 files,
181 additions: files.reduce((total, file) => total + file.additions, 0),
182 deletions: files.reduce((total, file) => total + file.deletions, 0),
183 };
184}