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

pullRequestDiffPages.ts

215 lines7.4 KB

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