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

pullRequestList.logic.ts

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