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

pullRequestList.logic.ts

977 lines34.2 KB

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