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

pullRequestDiffPages.ts

223 lines7.6 KB

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