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

pullRequestList.logic.ts

1,016 lines35.3 KB

1import * as Schema from "effect/Schema";
2​
3import {
4 EnvironmentId,
5 PullRequestListEntry,
6 PullRequestListProjectError,
7 PullRequestListResult,
8 pullRequestHostOf,
9 resolvePullRequestAuthorFilter,
10} from "@t3tools/contracts";
11import type {
12 ProjectId,
13 RepositoryIdentity,
14 SourceControlProviderKind,
15 PullRequestAction,
16 PullRequestActor,
17 PullRequestDiffStat,
18 PullRequestInvolvement,
19 PullRequestLabel,
20 PullRequestListCursors,
21 PullRequestListFilters,
22 PullRequestListState,
23 PullRequestState,
24} from "@t3tools/contracts";
25​
26import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
27​
28import { toSortableTimestamp } from "../../lib/threadSort";
29import type { PullRequestListSort } from "./pullRequestListPreferences";
30​
31export interface EnvironmentPullRequestEntry extends PullRequestListEntry {
32 readonly environmentId: EnvironmentId;
34​
35export interface EnvironmentPullRequestStat extends PullRequestDiffStat {
36 readonly environmentId: EnvironmentId;
38​
39export interface EnvironmentPullRequestError extends PullRequestListProjectError {
40 readonly environmentId: EnvironmentId;
42​
43export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
44​
45export interface PullRequestGroup<Entry extends PullRequestListEntry = PullRequestListEntry> {
46 readonly key: PullRequestGroupKey;
47 readonly label: string;
48 readonly entries: ReadonlyArray<Entry>;
50​
51export interface PullRequestAuthorFacet {
52 readonly actor: PullRequestActor;
53 readonly count: number;
54 readonly mergedCount: number;
56​
57export interface PullRequestLabelFacet extends PullRequestLabel {
58 readonly count: number;
60​
61export type PullRequestViewers = PullRequestListResult["viewers"];
62​
63type ScopedEntry = PullRequestListEntry & { readonly environmentId?: string };
64​
65const pullRequestViewerKey = (entry: ScopedEntry): string =>
66 `${entry.environmentId ?? ""} ${entry.host}`;
67​
68const GROUP_LABELS: Record<PullRequestGroupKey, string> = {
69 reviewRequested: "Review requested",
70 authored: "Authored",
71 others: "Others",
72};
73​
74function normalize(value: string | null | undefined): string | null {
75 const trimmed = value?.trim().toLowerCase() ?? "";
76 return trimmed.length > 0 ? trimmed : null;
78​
79export function pullRequestLabelColor(color: string | null): string | null {
80 const hex = color?.trim().replace(/^#/, "") ?? "";
81 return /^[0-9a-fA-F]{6}$/.test(hex) ? `#${hex}` : null;
83​
84export function collectPullRequestListFacets(
85 entries: ReadonlyArray<PullRequestListEntry>,
86 state: PullRequestListState,
87) {
88 const authors = new Map<string, PullRequestAuthorFacet>();
89 const labels = new Map<string, PullRequestLabelFacet>();
90 const uniqueEntries = new Map(entries.map((entry) => [pullRequestEntryKey(entry), entry]));
91 for (const entry of uniqueEntries.values()) {
92 const inState = state === "all" || entry.state === state;
93 if (entry.author !== null) {
94 const key = normalize(entry.author.login);
95 if (key !== null) {
96 const held = authors.get(key);
97 authors.set(key, {
98 actor: held?.actor ?? entry.author,
99 count: (held?.count ?? 0) + Number(inState),
100 mergedCount: (held?.mergedCount ?? 0) + Number(entry.state === "merged"),
101 });
102 }
103 }
104 if (!inState) continue;
105 for (const label of entry.labels) {
106 const key = normalize(label.name);
107 if (key === null) continue;
108 const held = labels.get(key);
109 labels.set(key, {
110 ...label,
111 name: held?.name ?? label.name,
112 color: held?.color ?? label.color,
113 count: (held?.count ?? 0) + 1,
114 });
115 }
116 }
117 return {
118 authors: [...authors.values()]
119 .filter((author) => author.count > 0)
120 .toSorted(
121 (left, right) =>
122 right.mergedCount - left.mergedCount ||
123 right.count - left.count ||
124 left.actor.login.localeCompare(right.actor.login),
125 ),
126 labels: [...labels.values()].toSorted(
127 (left, right) => right.count - left.count || left.name.localeCompare(right.name),
128 ),
129 };
131​
132export function pullRequestEntryViewer(
133 entry: ScopedEntry,
134 viewers: PullRequestViewers,
135): string | null {
136 // The environment's own answer first; a plain host key is what a single-environment listing
137 // still writes, and what the snapshot from one carries.
138 return normalize(entry.viewer ?? viewers[pullRequestViewerKey(entry)] ?? viewers[entry.host]);
140​
141function isAuthoredByViewer(entry: ScopedEntry, viewers: PullRequestViewers): boolean {
142 const viewer = pullRequestEntryViewer(entry, viewers);
143 return viewer !== null && normalize(entry.author?.login) === viewer;
145​
146export function matchesPullRequestQuery(entry: PullRequestListEntry, query: string): boolean {
147 const normalizedQuery = query.trim().toLowerCase();
148 if (normalizedQuery.length === 0) return true;
149 return `#${entry.number} ${entry.title} ${entry.repository} ${entry.headBranch} ${entry.author?.login ?? ""}`
150 .toLowerCase()
151 .includes(normalizedQuery);
153​
154export function filterPullRequestsByInvolvement<Entry extends ScopedEntry>(
155 entries: ReadonlyArray<Entry>,
156 viewers: PullRequestViewers,
157 involvement: PullRequestInvolvement,
158): ReadonlyArray<Entry> {
159 if (involvement === "reviewing") {
160 return entries.filter((entry) => entry.viewerReviewRequested);
161 }
162 if (involvement === "authored") {
163 return entries.filter((entry) => isAuthoredByViewer(entry, viewers));
164 }
165 return entries;
167​
168export function narrowPullRequestsToFilters<Entry extends PullRequestListEntry>(
169 entries: ReadonlyArray<Entry>,
170 filters: {
171 readonly state: PullRequestListState;
172 readonly projectId: string | undefined;
173 readonly host: string | undefined;
174 },
175): ReadonlyArray<Entry> {
176 return entries.filter(
177 (entry) =>
178 (filters.state === "all" || entry.state === filters.state) &&
179 (filters.projectId === undefined || entry.projectId === filters.projectId) &&
180 (filters.host === undefined || entry.host === filters.host),
181 );
183​
184export function matchesPullRequestFilters(
185 entry: PullRequestListEntry,
186 filters: PullRequestListFilters,
187 viewer?: string | null,
188): boolean {
189 const labels = entry.labels.map((label) => label.name.trim().toLowerCase());
190 const holds = (label: string) => labels.includes(label.trim().toLowerCase());
191 return (
192 (filters.draft === undefined || entry.isDraft === (filters.draft === "only")) &&
193 (filters.review === undefined ||
194 (filters.review === "none"
195 ? entry.reviewDecision === undefined
196 : entry.reviewDecision === filters.review)) &&
197 (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
198 (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
199 (filters.author === undefined ||
200 entry.author?.login.toLowerCase() ===
201 resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
202 );
204​
205export function groupPullRequestsByInvolvement<Entry extends ScopedEntry>(
206 entries: ReadonlyArray<Entry>,
207 viewers: PullRequestViewers,
208): ReadonlyArray<PullRequestGroup<Entry>> {
209 const buckets: Record<PullRequestGroupKey, Entry[]> = {
210 reviewRequested: [],
211 authored: [],
212 others: [],
213 };
214 for (const entry of entries) {
215 if (isAuthoredByViewer(entry, viewers)) {
216 buckets.authored.push(entry);
217 } else if (entry.viewerReviewRequested) {
218 buckets.reviewRequested.push(entry);
219 } else {
220 buckets.others.push(entry);
221 }
222 }
223 return (["authored", "reviewRequested", "others"] as const)
224 .filter((key) => buckets[key].length > 0)
225 .map((key) => ({ key, label: GROUP_LABELS[key], entries: buckets[key] }));
227​
228export function pullRequestEntryKey(entry: ScopedEntry): string {
229 const scope = entry.environmentId === undefined ? "" : `${entry.environmentId}:`;
230 return `${scope}${entry.host}:${entry.repository}#${entry.number}`;
232​
233export interface PullRequestStatsTarget {
234 readonly environmentId: EnvironmentId;
235 readonly input: {
236 readonly refs: ReadonlyArray<{
237 readonly projectId: ProjectId;
238 readonly repository: string;
239 readonly number: number;
240 }>;
241 };
243​
244export interface PullRequestStatsBatch extends PullRequestStatsTarget {
245 readonly keys: ReadonlySet<string>;
247​
248export type PullRequestStatsPolicy = "visible" | "eager";
249​
250export interface PullRequestStatsScope {
251 readonly key: string;
252 readonly policy: PullRequestStatsPolicy;
254​
255const MAX_PULL_REQUEST_STATS_REFS = 500;
256​
257export function pullRequestStatsKeysToRequest(
258 entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>,
259 enteredKeys: ReadonlySet<string>,
260 batches: ReadonlyArray<PullRequestStatsBatch>,
261 statsByRow: ReadonlyMap<string, unknown>,
262): ReadonlySet<string> {
263 const requested = new Set(batches.flatMap((batch) => [...batch.keys]));
264 return new Set(
265 [...enteredKeys].filter((key) => {
266 const entry = entriesByKey.get(key);
267 return (
268 entry !== undefined &&
269 entry.additions === 0 &&
270 entry.deletions === 0 &&
271 !requested.has(key) &&
272 !statsByRow.has(pullRequestDiffStatKey(entry))
273 );
274 }),
275 );
277​
278export function pullRequestStatsBatches(
279 entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>,
280 keys: ReadonlySet<string>,
281): ReadonlyArray<PullRequestStatsBatch> {
282 const byEnvironment = new Map<
283 EnvironmentId,
284 Array<{
285 readonly key: string;
286 readonly ref: PullRequestStatsTarget["input"]["refs"][number];
287 }>
288 >();
289 for (const key of keys) {
290 const entry = entriesByKey.get(key);
291 if (entry === undefined) continue;
292 const rows = byEnvironment.get(entry.environmentId) ?? [];
293 rows.push({
294 key,
295 ref: {
296 projectId: entry.projectId,
297 repository: entry.repository,
298 number: entry.number,
299 },
300 });
301 byEnvironment.set(entry.environmentId, rows);
302 }
303 return [...byEnvironment].flatMap(([environmentId, rows]) => {
304 const batches: PullRequestStatsBatch[] = [];
305 for (let index = 0; index < rows.length; index += MAX_PULL_REQUEST_STATS_REFS) {
306 const batch = rows.slice(index, index + MAX_PULL_REQUEST_STATS_REFS);
307 batches.push({
308 environmentId,
309 input: { refs: batch.map((row) => row.ref) },
310 keys: new Set(batch.map((row) => row.key)),
311 });
312 }
313 return batches;
314 });
316​
317/**
318 * Size sorting needs every loaded row, while the other modes only need rows
319 * near the viewport.
320 */
321export function pullRequestStatsRequestBatches({
322 entriesByKey,
323 candidateKeys,
324 policy,
325 activeBatches,
326 statsByRow,
327 refresh = false,
328}: {
329 readonly entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>;
330 readonly candidateKeys: ReadonlySet<string>;
331 readonly policy: PullRequestStatsPolicy;
332 readonly activeBatches: ReadonlyArray<PullRequestStatsBatch>;
333 readonly statsByRow: ReadonlyMap<string, unknown>;
334 readonly refresh?: boolean;
335}): ReadonlyArray<PullRequestStatsBatch> {
336 const requestedKeys = policy === "eager" ? new Set(entriesByKey.keys()) : candidateKeys;
337 const keys = refresh
338 ? requestedKeys
339 : pullRequestStatsKeysToRequest(entriesByKey, requestedKeys, activeBatches, statsByRow);
340 return pullRequestStatsBatches(entriesByKey, keys);
342​
343export function pullRequestStatsRefreshBatches({
344 requestedScope,
345 currentScope,
346 entriesByKey,
347 candidateKeys,
348 statsByRow,
349}: {
350 readonly requestedScope: PullRequestStatsScope;
351 readonly currentScope: PullRequestStatsScope;
352 readonly entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>;
353 readonly candidateKeys: ReadonlySet<string>;
354 readonly statsByRow: ReadonlyMap<string, unknown>;
355}): ReadonlyArray<PullRequestStatsBatch> | null {
356 if (requestedScope.key !== currentScope.key || requestedScope.policy !== currentScope.policy) {
357 return null;
358 }
359 return pullRequestStatsRequestBatches({
360 entriesByKey,
361 candidateKeys,
362 policy: requestedScope.policy,
363 activeBatches: [],
364 statsByRow,
365 refresh: true,
366 });
368​
369export function retainVisiblePullRequestStatsBatches(
370 batches: ReadonlyArray<PullRequestStatsBatch>,
371 visibleKeys: ReadonlySet<string>,
372): ReadonlyArray<PullRequestStatsBatch> {
373 return batches.filter((batch) => {
374 for (const key of batch.keys) {
375 if (visibleKeys.has(key)) return true;
376 }
377 return false;
378 });
380​
381/**
382 * The feed is sliced by recency, so an older authored or review-requested row can be
383 * missing from its first page and arrive with a later one; grouping the loaded pages would
384 * then move it above rows already read.
385 */
386export function partitionPullRequestsWithPriority<Entry extends PullRequestListEntry>(
387 entries: ReadonlyArray<Entry>,
388 authored: ReadonlyArray<Entry>,
389 reviewRequested: ReadonlyArray<Entry>,
390): ReadonlyArray<PullRequestGroup<Entry>> {
391 const authoredByKey = new Map(authored.map((entry) => [pullRequestEntryKey(entry), entry]));
392 const reviewByKey = new Map(
393 reviewRequested.flatMap((entry) => {
394 const key = pullRequestEntryKey(entry);
395 return authoredByKey.has(key) ? [] : [[key, entry] as const];
396 }),
397 );
398 const others: Entry[] = [];
399 for (const entry of entries) {
400 const key = pullRequestEntryKey(entry);
401 if (authoredByKey.has(key)) {
402 authoredByKey.set(key, entry);
403 } else if (reviewByKey.has(key)) {
404 reviewByKey.set(key, entry);
405 } else {
406 others.push(entry);
407 }
408 }
409 const byRecency = (left: Entry, right: Entry) => right.updatedAt.localeCompare(left.updatedAt);
410 return (
411 [
412 { key: "authored", entries: [...authoredByKey.values()].toSorted(byRecency) },
413 { key: "reviewRequested", entries: [...reviewByKey.values()].toSorted(byRecency) },
414 { key: "others", entries: others },
415 ] as const
416 )
417 .filter((group) => group.entries.length > 0)
418 .map((group) => ({ ...group, label: GROUP_LABELS[group.key] }));
420​
421export type PullRequestDiffStats = ReadonlyMap<
422 string,
423 { readonly additions: number; readonly deletions: number }
424>;
425​
426/**
427 * The stats read is keyed by the rows on screen, so adding or removing one row is a fresh
428 * query with nothing in it yet; replacing the map would blank every count already showing for
429 * the round trip.
430 */
431export function mergePullRequestDiffStats(
432 previous: PullRequestDiffStats,
433 stats: ReadonlyArray<{
434 readonly environmentId: string;
435 readonly projectId: string;
436 readonly number: number;
437 readonly additions: number;
438 readonly deletions: number;
439 }>,
440): PullRequestDiffStats {
441 if (stats.length === 0) return previous;
442 const next = new Map(previous);
443 for (const stat of stats) {
444 next.set(pullRequestDiffStatKey(stat), {
445 additions: stat.additions,
446 deletions: stat.deletions,
447 });
448 }
449 return next;
451​
452export const pullRequestDiffStatKey = (row: {
453 readonly environmentId: string;
454 readonly projectId: string;
455 readonly number: number;
456}) => `${row.environmentId} ${row.projectId} ${row.number}`;
457​
458export interface MergedPullRequestList {
459 readonly viewers: PullRequestViewers;
460 readonly providers: PullRequestListResult["providers"];
461 readonly entries: ReadonlyArray<EnvironmentPullRequestEntry>;
462 readonly errors: ReadonlyArray<EnvironmentPullRequestError>;
463 readonly truncated: boolean;
464 readonly nextCursors: Readonly<Record<string, PullRequestListCursors>>;
465 readonly truncatedEnvironments: ReadonlyArray<string>;
467​
468export function mergePullRequestLists(
469 answers: ReadonlyArray<readonly [EnvironmentId, PullRequestListResult]>,
470): MergedPullRequestList | null {
471 if (answers.length === 0) return null;
472 const viewers: Record<string, string> = {};
473 const truncatedEnvironments: string[] = [];
474 const providers = new Map<string, PullRequestListResult["providers"][number]>();
475 const entries: EnvironmentPullRequestEntry[] = [];
476 const errors: EnvironmentPullRequestError[] = [];
477 const nextCursors: Record<string, PullRequestListCursors> = {};
478 let truncated = false;
479 for (const [environmentId, answer] of answers) {
480 for (const [host, login] of Object.entries(answer.viewers)) {
481 viewers[`${environmentId} ${host}`] = login;
482 }
483 for (const provider of answer.providers) {
484 const held = providers.get(provider.host);
485 providers.set(
486 provider.host,
487 held === undefined
488 ? provider
489 : {
490 ...(held.configured ? held : provider),
491 projectCount: held.projectCount + provider.projectCount,
492 searchesOnHost: held.searchesOnHost && provider.searchesOnHost,
493 configured: held.configured || provider.configured,
494 },
495 );
496 }
497 entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
498 errors.push(...answer.errors.map((error) => ({ ...error, environmentId })));
499 truncated ||= answer.truncated;
500 if (answer.truncated) truncatedEnvironments.push(environmentId);
501 if (Object.keys(answer.nextCursors).length > 0) {
502 nextCursors[environmentId] = answer.nextCursors;
503 }
504 }
505 return {
506 viewers,
507 providers: [...providers.values()],
508 entries: entries.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
509 errors,
510 truncated,
511 nextCursors,
512 truncatedEnvironments,
513 };
515​
516const SNAPSHOT_MAX_ENTRIES = 99;
517​
518type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
519​
520export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray<string>): string =>
521 [...environmentIds].sort((left, right) => left.localeCompare(right)).join(",");
522​
523const snapshotStorageKey = (environmentSetKey: string) =>
524 `t3.pullRequests.list:${environmentSetKey}`;
525​
526export interface PullRequestPartitionsSnapshot {
527 readonly authored: ReadonlyArray<EnvironmentPullRequestEntry>;
528 readonly reviewing: ReadonlyArray<EnvironmentPullRequestEntry>;
530​
531export interface PullRequestListSnapshot {
532 readonly scope: string;
533 readonly data: MergedPullRequestList;
534 readonly partitions?: PullRequestPartitionsSnapshot | undefined;
536​
537const EnvironmentPullRequestEntrySchema = Schema.Struct({
538 ...PullRequestListEntry.fields,
539 environmentId: EnvironmentId,
540});
541​
542const EnvironmentPullRequestErrorSchema = Schema.Struct({
543 ...PullRequestListProjectError.fields,
544 environmentId: EnvironmentId,
545});
546​
547const decodeSnapshot = Schema.decodeUnknownOption(
548 Schema.Struct({
549 scope: Schema.String,
550 data: Schema.Struct({
551 ...PullRequestListResult.fields,
552 entries: Schema.Array(EnvironmentPullRequestEntrySchema),
553 errors: Schema.Array(EnvironmentPullRequestErrorSchema),
554 nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
555 truncatedEnvironments: Schema.Array(Schema.String),
556 }),
557 partitions: Schema.optional(
558 Schema.Struct({
559 authored: Schema.Array(EnvironmentPullRequestEntrySchema),
560 reviewing: Schema.Array(EnvironmentPullRequestEntrySchema),
561 }),
562 ),
563 }),
564);
565​
566export function readPullRequestListSnapshot(
567 storage: SnapshotStorage | undefined,
568 environmentSetKey: string,
569): PullRequestListSnapshot | null {
570 try {
571 const raw = storage?.getItem(snapshotStorageKey(environmentSetKey));
572 if (!raw) return null;
573 const decoded = decodeSnapshot(JSON.parse(raw));
574 return decoded._tag === "Some" ? decoded.value : null;
575 } catch {
576 return null;
577 }
579​
580export function writePullRequestListSnapshot(
581 storage: SnapshotStorage | undefined,
582 environmentSetKey: string,
583 snapshot: PullRequestListSnapshot,
584): void {
585 try {
586 storage?.setItem(
587 snapshotStorageKey(environmentSetKey),
588 JSON.stringify({
589 scope: snapshot.scope,
590 data: {
591 ...snapshot.data,
592 entries: snapshot.data.entries.slice(0, SNAPSHOT_MAX_ENTRIES),
593 errors: [],
594 nextCursors: {},
595 truncatedEnvironments: [],
596 },
597 ...(snapshot.partitions === undefined
598 ? {}
599 : {
600 partitions: {
601 authored: snapshot.partitions.authored.slice(0, SNAPSHOT_MAX_ENTRIES),
602 reviewing: snapshot.partitions.reviewing.slice(0, SNAPSHOT_MAX_ENTRIES),
603 },
604 }),
605 }),
606 );
607 } catch {}
609​
610/**
611 * Until `projectsKnown`, the id is kept rather than dropped: an environment that has not
612 * reported yet is not the same as one without the project, and dropping first would show every
613 * project's pull requests for a moment before narrowing back down.
614 */
615export function resolveProjectScope<Id extends string>(
616 projectId: Id | undefined,
617 projects: ReadonlyArray<{ readonly id: string }>,
618 projectsKnown: boolean,
619): Id | undefined {
620 if (projectId === undefined || !projectsKnown) return projectId;
621 return projects.some((project) => project.id === projectId) ? projectId : undefined;
623​
624export function findScopedProject<
625 Project extends { readonly id: string; readonly environmentId: string },
626>(
627 projects: ReadonlyArray<Project>,
628 environmentId: string | null | undefined,
629 projectId: string | undefined,
630): Project | undefined {
631 if (projectId === undefined) return undefined;
632 const matches = projects.filter((project) => project.id === projectId);
633 if (environmentId === null || environmentId === undefined) {
634 return matches.length === 1 ? matches[0] : undefined;
635 }
636 return matches.find((project) => project.environmentId === environmentId);
638​
639export function resolveQueryEnvironmentIds<Id extends string>(
640 environmentIds: ReadonlyArray<Id>,
641 projects: ReadonlyArray<{ readonly id: string; readonly environmentId: Id }>,
642 scopedProject: { readonly environmentId: Id } | undefined,
643 scopedProjectId: string | undefined,
644 projectsKnown: boolean,
645): ReadonlyArray<Id> {
646 if (scopedProject !== undefined) {
647 return environmentIds.filter((environmentId) => environmentId === scopedProject.environmentId);
648 }
649 if (scopedProjectId === undefined || !projectsKnown) return environmentIds;
650 const holders = new Set(
651 projects
652 .filter((project) => project.id === scopedProjectId)
653 .map((project) => project.environmentId),
654 );
655 return environmentIds.filter((environmentId) => holders.has(environmentId));
657​
658/**
659 * Still connecting is not the same as gone: a server the workspace already knows about is kept
660 * named here even while it has nothing to answer with yet, so the lookup that follows finds
661 * nothing under it rather than falling through to a different server's project of the same id.
662 */
663export function resolveSelectedEnvironmentId<Id extends string>(
664 namedEnvironmentId: Id | undefined,
665 knownEnvironmentIds: ReadonlySet<Id>,
666 fallbackEnvironmentId: Id | null,
667): Id | null {
668 if (namedEnvironmentId === undefined) return fallbackEnvironmentId;
669 return knownEnvironmentIds.has(namedEnvironmentId) ? namedEnvironmentId : fallbackEnvironmentId;
671​
672/**
673 * Every host searches more than a row shows — GitHub reads bodies and commit messages, GitLab
674 * and Bitbucket read descriptions — so a result can be a real match with nothing on the row to
675 * show for it.
676 */
677export function scorePullRequestMatch(entry: PullRequestListEntry, query: string): number {
678 const needle = query.trim().toLowerCase();
679 if (needle.length === 0) return 0;
680 const number = needle.replace(/^#/u, "");
681 if (/^\d+$/u.test(number)) return String(entry.number) === number ? 100 : 0;
682​
683 const title = entry.title.toLowerCase();
684 const terms = needle.split(/\s+/u).filter((term) => term.length > 0);
685 if (title === needle) return 90;
686 if (title.includes(needle)) return 80;
687 if (terms.length > 1 && terms.every((term) => title.includes(term))) return 70;
688 if (entry.headBranch.toLowerCase().includes(needle)) return 60;
689 if ((entry.author?.login ?? "").toLowerCase().includes(needle)) return 50;
690 if (entry.repository.toLowerCase().includes(needle)) return 40;
691 if (terms.some((term) => title.includes(term))) return 30;
692 return 10;
694​
695export function rankPullRequestMatches<Entry extends PullRequestListEntry>(
696 entries: ReadonlyArray<Entry>,
697 query: string,
698): ReadonlyArray<Entry> {
699 if (query.trim().length === 0) return entries;
700 return entries.toSorted((left, right) => {
701 const byScore = scorePullRequestMatch(right, query) - scorePullRequestMatch(left, query);
702 return byScore !== 0 ? byScore : right.updatedAt.localeCompare(left.updatedAt);
703 });
705​
706export function rankPullRequestsByMergeReadiness<Entry extends PullRequestListEntry>(
707 entries: ReadonlyArray<Entry>,
708 hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,
709): ReadonlyArray<Entry> {
710 const tier = (entry: Entry) => {
711 if (entry.mergeability === "conflicting") return 4;
712 if (entry.state !== "open") return 3;
713 if (entry.isDraft) return 2;
714 if (entry.checksState === "passing" && entry.reviewDecision === "approved") return 0;
715 if (entry.checksState === "passing") return 1;
716 return 2;
717 };
718 return entries.toSorted((left, right) => {
719 const byTier = tier(left) - tier(right);
720 if (byTier !== 0) return byTier;
721 const measured = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));
722 const sized = left.additions + left.deletions - (right.additions + right.deletions);
723 return measured || sized || right.updatedAt.localeCompare(left.updatedAt);
724 });
726​
727function rankByTierThenRecency<Entry extends PullRequestListEntry>(
728 entries: ReadonlyArray<Entry>,
729 tier: (entry: Entry) => number,
730): ReadonlyArray<Entry> {
731 const timestamp = (entry: Entry) => toSortableTimestamp(entry.updatedAt);
732 return entries.toSorted((left, right) => {
733 const byTier = tier(left) - tier(right);
734 if (byTier !== 0) return byTier;
735 const leftUpdated = timestamp(left);
736 const rightUpdated = timestamp(right);
737 const measured = Number(leftUpdated === null) - Number(rightUpdated === null);
738 if (measured !== 0) return measured;
739 if (leftUpdated === null || rightUpdated === null) return 0;
740 return rightUpdated - leftUpdated;
741 });
743​
744export function rankPullRequestsBlockedOnAuthor<Entry extends PullRequestListEntry>(
745 entries: ReadonlyArray<Entry>,
746): ReadonlyArray<Entry> {
747 return rankByTierThenRecency(entries, (entry) => {
748 if (entry.state !== "open") return 6;
749 if (entry.mergeability === "conflicting") return 0;
750 if (entry.reviewDecision === "changes-requested") return 1;
751 if (entry.checksState === "failing") return 2;
752 if (entry.isDraft) return 3;
753 if (entry.checksState === "passing" && entry.reviewDecision === "approved") return 5;
754 return 4;
755 });
757​
758function rankPullRequestsBlockedOnReviewer<Entry extends PullRequestListEntry>(
759 entries: ReadonlyArray<Entry>,
760): ReadonlyArray<Entry> {
761 return rankByTierThenRecency(entries, (entry) => (entry.state === "open" ? 0 : 1));
763​
764export function sortPullRequestGroups<Entry extends PullRequestListEntry>(
765 groups: ReadonlyArray<PullRequestGroup<Entry>>,
766 sort: PullRequestListSort,
767 searchText: string,
768 hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,
769 involvement: PullRequestInvolvement = "all",
770): ReadonlyArray<PullRequestGroup<Entry>> {
771 const sortWithinGroups = (rank: (entries: ReadonlyArray<Entry>) => ReadonlyArray<Entry>) =>
772 groups.map((group) => ({ ...group, entries: rank(group.entries) }));
773​
774 if (sort === "ready") {
775 return searchText.trim().length === 0
776 ? sortWithinGroups((entries) => rankPullRequestsByMergeReadiness(entries, hasMeasuredSize))
777 : groups;
778 }
779 if (sort === "blocked") {
780 if (searchText.trim().length > 0) return groups;
781 const role = (key: PullRequestGroupKey) =>
782 key === "others" ? involvement : key === "authored" ? "authored" : "reviewing";
783 return groups.map((group) => {
784 const groupRole = role(group.key);
785 if (groupRole === "all") return group;
786 const rank =
787 groupRole === "authored"
788 ? rankPullRequestsBlockedOnAuthor
789 : rankPullRequestsBlockedOnReviewer;
790 return { ...group, entries: rank(group.entries) };
791 });
792 }
793 if (sort === "updated") return groups;
794​
795 const timestamp = (entry: Entry) =>
796 toSortableTimestamp(entry.updatedAt) ?? toSortableTimestamp(entry.createdAt) ?? 0;
797 return sortWithinGroups((entries) =>
798 entries.toSorted((left, right) => {
799 if (sort === "newest" || sort === "oldest") {
800 const leftCreated = toSortableTimestamp(left.createdAt);
801 const rightCreated = toSortableTimestamp(right.createdAt);
802 const measured = Number(rightCreated !== null) - Number(leftCreated !== null);
803 const dated = (leftCreated ?? 0) - (rightCreated ?? 0);
804 return (
805 measured || (sort === "newest" ? -dated : dated) || timestamp(right) - timestamp(left)
806 );
807 }
808 const measured = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));
809 const sized = left.additions + left.deletions - (right.additions + right.deletions);
810 return (
811 measured || (sort === "largest" ? -sized : sized) || timestamp(right) - timestamp(left)
812 );
813 }),
814 );
816​
817export function withDiffStat<
818 Entry extends PullRequestListEntry & { readonly environmentId: string },
819>(
820 entry: Entry,
821 statsByRow: ReadonlyMap<string, { readonly additions: number; readonly deletions: number }>,
822): Entry {
823 if (entry.additions !== 0 || entry.deletions !== 0) return entry;
824 const stat = statsByRow.get(pullRequestDiffStatKey(entry));
825 return stat === undefined ? entry : { ...entry, ...stat };
827​
828export interface PullRequestListOverride {
829 readonly state: PullRequestState;
830 readonly isDraft?: boolean;
831 readonly updatedAt: string;
832 readonly token: number;
833 readonly at: number;
835​
836export function pullRequestOverrideAfterAction(
837 entry: Pick<PullRequestListEntry, "state" | "isDraft">,
838 action: PullRequestAction,
839 now: Date,
840 token: number,
841): PullRequestListOverride | null {
842 const stamp = { updatedAt: now.toISOString(), token, at: now.getTime() };
843 switch (action) {
844 case "close":
845 return { state: "closed", ...stamp };
846 case "reopen":
847 return { state: "open", ...stamp };
848 case "merge":
849 return { state: "merged", ...stamp };
850 case "draft":
851 return { state: entry.state, isDraft: true, ...stamp };
852 case "ready":
853 return { state: entry.state, isDraft: false, ...stamp };
854 default:
855 return null;
856 }
858​
859export function applyPullRequestOverrides<Entry extends PullRequestListEntry>(
860 entries: ReadonlyArray<Entry>,
861 overrides: ReadonlyMap<string, PullRequestListOverride>,
862 keyOf: (entry: Entry) => string,
863 state: PullRequestListState,
864): ReadonlyArray<Entry> {
865 if (overrides.size === 0 && state === "all") return entries;
866 const out: Entry[] = [];
867 for (const entry of entries) {
868 const override = overrides.get(keyOf(entry));
869 if (state !== "all" && (override?.state ?? entry.state) !== state) continue;
870 out.push(override === undefined ? entry : { ...entry, ...override });
871 }
872 return overrides.size === 0 && out.length === entries.length ? entries : out;
874​
875export function reusePullRequestEntries<Entry extends PullRequestListEntry>(
876 previous: ReadonlyArray<Entry>,
877 next: ReadonlyArray<Entry>,
878 keyOf: (entry: Entry) => string,
879): ReadonlyArray<Entry> {
880 if (previous.length === 0) return next;
881 const held = new Map(previous.map((entry) => [keyOf(entry), entry]));
882 let reused = 0;
883 const out = next.map((entry) => {
884 const before = held.get(keyOf(entry));
885 if (before !== undefined && JSON.stringify(before) === JSON.stringify(entry)) {
886 reused += 1;
887 return before;
888 }
889 return entry;
890 });
891 return reused === next.length &&
892 previous.length === next.length &&
893 previous.every((entry, index) => keyOf(entry) === keyOf(next[index]!))
894 ? previous
895 : out;
897​
898const PULL_REQUEST_OVERRIDE_TRUST_MS = 60_000;
899​
900/**
901 * A read that started before the action can land after it and still say the old thing, so an
902 * override is not cleared because an answer arrived but because the answer agrees: the row is
903 * there in the state the override said. A row that is absent says nothing — the authored and
904 * reviewing groups are read apart from the feed, and a page is only a page — so absence never
905 * confirms.
906 */
907export function settlePullRequestOverrides<Entry extends PullRequestListEntry>(
908 overrides: ReadonlyMap<string, PullRequestListOverride>,
909 answered: ReadonlyArray<Entry>,
910 keyOf: (entry: Entry) => string,
911 now: number,
912): ReadonlyMap<string, PullRequestListOverride> {
913 if (overrides.size === 0) return overrides;
914 const byKey = new Map(answered.map((entry) => [keyOf(entry), entry]));
915 const kept = new Map<string, PullRequestListOverride>();
916 for (const [key, override] of overrides) {
917 const row = byKey.get(key);
918 if (row === undefined) {
919 kept.set(key, override);
920 continue;
921 }
922 const agrees =
923 row.state === override.state &&
924 (override.isDraft === undefined || row.isDraft === override.isDraft);
925 const outranked = now - override.at > PULL_REQUEST_OVERRIDE_TRUST_MS;
926 if (!agrees && !outranked) kept.set(key, override);
927 }
928 return kept.size === overrides.size ? overrides : kept;
930​
931export type PullRequestQuickAction = "close" | "merge" | "ready" | "reopen";
932​
933export function pullRequestHostActions(
934 providers: ReadonlyArray<PullRequestListResult["providers"][number]>,
935): (
936 entry: Pick<EnvironmentPullRequestEntry, "host" | "provider">,
937) => ReadonlySet<PullRequestAction> {
938 const byHost = new Map(
939 providers.flatMap((provider) =>
940 provider.actions === undefined
941 ? []
942 : [[provider.host.toLowerCase(), new Set(provider.actions)] as const],
943 ),
944 );
945 const legacy = new Set<PullRequestAction>(["close", "merge", "ready", "reopen"]);
946 const none = new Set<PullRequestAction>();
947 return (entry) =>
948 byHost.get(entry.host.toLowerCase()) ?? (entry.provider === "github" ? legacy : none);
950​
951export function pullRequestQuickActions(
952 entry: Pick<EnvironmentPullRequestEntry, "state" | "isDraft">,
953 hostActions: ReadonlySet<PullRequestAction>,
954): ReadonlyArray<PullRequestQuickAction> {
955 const forState: ReadonlyArray<PullRequestQuickAction> =
956 entry.state === "merged"
957 ? []
958 : entry.state === "closed"
959 ? ["reopen"]
960 : entry.isDraft
961 ? ["close", "ready"]
962 : ["close", "merge"];
963 return forState.filter((action) => hostActions.has(action));
965​
966export function largestPullRequestReadCount(
967 entries: ReadonlyArray<EnvironmentPullRequestEntry>,
968): number {
969 const counts = new Map<string, number>();
970 for (const entry of entries) {
971 const read = `${entry.environmentId} ${entry.host.toLowerCase()} ${
972 entry.provider === "github" ? "" : entry.repository.toLowerCase()
973 }`;
974 counts.set(read, (counts.get(read) ?? 0) + 1);
975 }
976 return Math.max(0, ...counts.values());
978​
979export function findProjectForRepository<
980 Project extends {
981 readonly id: string;
982 readonly environmentId: string;
983 readonly repositoryIdentity?: RepositoryIdentity | null | undefined;
984 },
985>(
986 projects: ReadonlyArray<Project>,
987 input: {
988 readonly repository: string;
989 readonly host?: string | undefined;
990 readonly selectedEnvironmentId?: string | null | undefined;
991 readonly scopedProjectId?: string | undefined;
992 readonly scopedEnvironmentId?: string | null | undefined;
993 },
994): Project | undefined {
995 const repository = input.repository.toLowerCase();
996 const host = input.host?.toLowerCase();
997 const candidates = projects.filter((project) => {
998 if (
999 input.selectedEnvironmentId != null &&
1000 project.environmentId !== input.selectedEnvironmentId
1001 ) {
1002 return false;
1004 const identity = project.repositoryIdentity;
1005 if (!identity || sourceControlRepositorySelector(identity)?.toLowerCase() !== repository) {
1006 return false;
1008 return (
1009 host === undefined ||
1010 pullRequestHostOf(identity, identity.provider as SourceControlProviderKind) === host
1011 );
1012 });
1013 // Azure repository names can collide across projects on the same host.
1014 const scoped = findScopedProject(candidates, input.scopedEnvironmentId, input.scopedProjectId);
1015 return scoped ?? candidates[0];