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

pullRequestList.logic.ts

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