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

pullRequestList.logic.ts

970 lines33.7 KB

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