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

pullRequestList.logic.ts

1,007 lines35.0 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: string[] = [];
540 const providers = new Map<string, PullRequestListResult["providers"][number]>();
541 const entries: 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 entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
564 errors.push(...answer.errors.map((error) => ({ ...error, environmentId })));
565 truncated ||= answer.truncated;
566 if (answer.truncated) truncatedEnvironments.push(environmentId);
567 if (Object.keys(answer.nextCursors).length > 0) {
568 nextCursors[environmentId] = answer.nextCursors;
569 }
570 }
571 return {
572 viewers,
573 providers: [...providers.values()],
574 entries: entries.toSorted(comparePullRequestsByRecency),
575 errors,
576 truncated,
577 nextCursors,
578 truncatedEnvironments,
579 };
581​
582export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray<string>): string =>
583 [...environmentIds].sort((left, right) => left.localeCompare(right)).join(",");
584​
585export interface PullRequestPartitionsSnapshot {
586 readonly authored: ReadonlyArray<EnvironmentPullRequestEntry>;
587 readonly reviewing: ReadonlyArray<EnvironmentPullRequestEntry>;
589​
590/** Retain project scope during reconnect until projects arrive. */
591export function resolveProjectScope<Id extends string>(
592 projectId: Id | undefined,
593 projects: ReadonlyArray<{ readonly id: string }>,
594 projectsKnown: boolean,
595): Id | undefined {
596 if (projectId === undefined || !projectsKnown) return projectId;
597 return projects.some((project) => project.id === projectId) ? projectId : undefined;
599​
600export function findScopedProject<
601 Project extends { readonly id: string; readonly environmentId: string },
602>(
603 projects: ReadonlyArray<Project>,
604 environmentId: string | null | undefined,
605 projectId: string | undefined,
606): Project | undefined {
607 if (projectId === undefined) return undefined;
608 const matches = projects.filter((project) => project.id === projectId);
609 if (environmentId === null || environmentId === undefined) {
610 return matches.length === 1 ? matches[0] : undefined;
611 }
612 return matches.find((project) => project.environmentId === environmentId);
614​
615export function resolveQueryEnvironmentIds<Id extends string>(
616 environmentIds: ReadonlyArray<Id>,
617 projects: ReadonlyArray<{ readonly id: string; readonly environmentId: Id }>,
618 scopedProject: { readonly environmentId: Id } | undefined,
619 scopedProjectId: string | undefined,
620 projectsKnown: boolean,
621): ReadonlyArray<Id> {
622 if (scopedProject !== undefined) {
623 return environmentIds.filter((environmentId) => environmentId === scopedProject.environmentId);
624 }
625 if (scopedProjectId === undefined || !projectsKnown) return environmentIds;
626 const holders = new Set(
627 projects
628 .filter((project) => project.id === scopedProjectId)
629 .map((project) => project.environmentId),
630 );
631 return environmentIds.filter((environmentId) => holders.has(environmentId));
633​
634/** Retain connecting environments to avoid matching another server's project id. */
635export function resolveSelectedEnvironmentId<Id extends string>(
636 namedEnvironmentId: Id | undefined,
637 knownEnvironmentIds: ReadonlySet<Id>,
638 fallbackEnvironmentId: Id | null,
639): Id | null {
640 if (namedEnvironmentId === undefined) return fallbackEnvironmentId;
641 return knownEnvironmentIds.has(namedEnvironmentId) ? namedEnvironmentId : fallbackEnvironmentId;
643​
644/** Host search also matches bodies and commits absent from visible row fields. */
645export function scorePullRequestMatch(entry: PullRequestListEntry, query: string): number {
646 const needle = query.trim().toLowerCase();
647 if (needle.length === 0) return 0;
648 const number = needle.replace(/^#/u, "");
649 if (/^\d+$/u.test(number)) return String(entry.number) === number ? 100 : 0;
650​
651 const title = entry.title.toLowerCase();
652 const terms = needle.split(/\s+/u).filter((term) => term.length > 0);
653 if (title === needle) return 90;
654 if (title.includes(needle)) return 80;
655 if (terms.length > 1 && terms.every((term) => title.includes(term))) return 70;
656 if (entry.headBranch.toLowerCase().includes(needle)) return 60;
657 if ((entry.author?.login ?? "").toLowerCase().includes(needle)) return 50;
658 if (entry.repository.toLowerCase().includes(needle)) return 40;
659 if (terms.some((term) => title.includes(term))) return 30;
660 return 10;
662​
663export function rankPullRequestMatches<Entry extends PullRequestListEntry>(
664 entries: ReadonlyArray<Entry>,
665 query: string,
666): ReadonlyArray<Entry> {
667 if (query.trim().length === 0) return entries;
668 return entries.toSorted((left, right) => {
669 const byScore = scorePullRequestMatch(right, query) - scorePullRequestMatch(left, query);
670 return byScore !== 0 ? byScore : comparePullRequestsByRecency(left, right);
671 });
673​
674export function rankPullRequestsByMergeReadiness<Entry extends PullRequestListEntry>(
675 entries: ReadonlyArray<Entry>,
676 hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,
677): ReadonlyArray<Entry> {
678 const tier = (entry: Entry) => {
679 if (entry.mergeability === "conflicting") return 4;
680 if (entry.state !== "open") return 3;
681 if (entry.isDraft) return 2;
682 if (entry.checksState === "passing" && entry.reviewDecision === "approved") return 0;
683 if (entry.checksState === "passing") return 1;
684 return 2;
685 };
686 return entries.toSorted((left, right) => {
687 const byTier = tier(left) - tier(right);
688 if (byTier !== 0) return byTier;
689 const measured = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));
690 const sized = left.additions + left.deletions - (right.additions + right.deletions);
691 return measured || sized || comparePullRequestsByRecency(left, right);
692 });
694​
695export function comparePullRequestsByRecency(
696 left: PullRequestListEntry,
697 right: PullRequestListEntry,
698) {
699 const leftUpdated = toSortableTimestamp(left.updatedAt);
700 const rightUpdated = toSortableTimestamp(right.updatedAt);
701 const measured = Number(leftUpdated === null) - Number(rightUpdated === null);
702 if (measured !== 0) return measured;
703 if (leftUpdated === null || rightUpdated === null) return 0;
704 return rightUpdated - leftUpdated;
706​
707function rankByTierThenRecency<Entry extends PullRequestListEntry>(
708 entries: ReadonlyArray<Entry>,
709 tier: (entry: Entry) => number,
710): ReadonlyArray<Entry> {
711 return entries.toSorted((left, right) => {
712 const byTier = tier(left) - tier(right);
713 return byTier !== 0 ? byTier : comparePullRequestsByRecency(left, right);
714 });
716​
717export function rankPullRequestsBlockedOnAuthor<Entry extends PullRequestListEntry>(
718 entries: ReadonlyArray<Entry>,
719): ReadonlyArray<Entry> {
720 return rankByTierThenRecency(entries, (entry) => {
721 if (entry.state !== "open") return 6;
722 if (entry.mergeability === "conflicting") return 0;
723 if (entry.reviewDecision === "changes-requested") return 1;
724 if (entry.checksState === "failing") return 2;
725 if (entry.isDraft) return 3;
726 if (entry.checksState === "passing" && entry.reviewDecision === "approved") return 5;
727 return 4;
728 });
730​
731function rankPullRequestsBlockedOnReviewer<Entry extends PullRequestListEntry>(
732 entries: ReadonlyArray<Entry>,
733): ReadonlyArray<Entry> {
734 return rankByTierThenRecency(entries, (entry) => (entry.state === "open" ? 0 : 1));
736​
737export function sortPullRequestGroups<Entry extends PullRequestListEntry>(
738 groups: ReadonlyArray<PullRequestGroup<Entry>>,
739 sort: PullRequestListSort,
740 searchText: string,
741 hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,
742 involvement: PullRequestInvolvement = "all",
743): ReadonlyArray<PullRequestGroup<Entry>> {
744 const sortWithinGroups = (rank: (entries: ReadonlyArray<Entry>) => ReadonlyArray<Entry>) =>
745 groups.map((group) => ({ ...group, entries: rank(group.entries) }));
746​
747 if (sort === "ready") {
748 return searchText.trim().length === 0
749 ? sortWithinGroups((entries) => rankPullRequestsByMergeReadiness(entries, hasMeasuredSize))
750 : groups;
751 }
752 if (sort === "blocked") {
753 if (searchText.trim().length > 0) return groups;
754 const role = (key: PullRequestGroupKey) =>
755 key === "others" ? involvement : key === "authored" ? "authored" : "reviewing";
756 return groups.map((group) => {
757 const groupRole = role(group.key);
758 if (groupRole === "all") return group;
759 const rank =
760 groupRole === "authored"
761 ? rankPullRequestsBlockedOnAuthor
762 : rankPullRequestsBlockedOnReviewer;
763 return { ...group, entries: rank(group.entries) };
764 });
765 }
766 if (sort === "updated") return groups;
767​
768 const timestamp = (entry: Entry) =>
769 toSortableTimestamp(entry.updatedAt) ?? toSortableTimestamp(entry.createdAt) ?? 0;
770 return sortWithinGroups((entries) =>
771 entries.toSorted((left, right) => {
772 if (sort === "newest" || sort === "oldest") {
773 const leftCreated = toSortableTimestamp(left.createdAt);
774 const rightCreated = toSortableTimestamp(right.createdAt);
775 const measured = Number(rightCreated !== null) - Number(leftCreated !== null);
776 const dated = (leftCreated ?? 0) - (rightCreated ?? 0);
777 return (
778 measured || (sort === "newest" ? -dated : dated) || timestamp(right) - timestamp(left)
779 );
780 }
781 const measured = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));
782 const sized = left.additions + left.deletions - (right.additions + right.deletions);
783 return (
784 measured || (sort === "largest" ? -sized : sized) || timestamp(right) - timestamp(left)
785 );
786 }),
787 );
789​
790export function withDiffStat<
791 Entry extends PullRequestListEntry & { readonly environmentId: string },
792>(
793 entry: Entry,
794 statsByRow: ReadonlyMap<string, { readonly additions: number; readonly deletions: number }>,
795): Entry {
796 if (entry.additions !== 0 || entry.deletions !== 0) return entry;
797 const stat = statsByRow.get(pullRequestDiffStatKey(entry));
798 return stat === undefined ? entry : { ...entry, ...stat };
800​
801export interface PullRequestListOverride {
802 readonly state: PullRequestState;
803 readonly isDraft?: boolean;
804 readonly updatedAt: string;
805 readonly token: number;
806 readonly at: number;
807 /** Set when the host reported this state, so a newer row can outrank it. */
808 readonly fromReply?: true;
809 readonly observedAt?: number;
811​
812export function pullRequestOverrideAfterAction(
813 entry: Pick<PullRequestListEntry, "state" | "isDraft">,
814 action: PullRequestAction,
815 now: Date,
816 token: number,
817 reply?: PullRequestSummary,
818): PullRequestListOverride | null {
819 if (reply !== undefined) {
820 const { state, isDraft, updatedAt, observedAt } = reply;
821 return {
822 state,
823 ...(isDraft === undefined ? {} : { isDraft }),
824 updatedAt,
825 ...(observedAt === undefined ? {} : { observedAt }),
826 fromReply: true,
827 token,
828 at: now.getTime(),
829 };
830 }
831 const stamp = { updatedAt: now.toISOString(), token, at: now.getTime() };
832 switch (action) {
833 case "close":
834 return { state: "closed", ...stamp };
835 case "reopen":
836 return { state: "open", ...stamp };
837 case "merge":
838 return { state: "merged", ...stamp };
839 case "draft":
840 return { state: entry.state, isDraft: true, ...stamp };
841 case "ready":
842 return { state: entry.state, isDraft: false, ...stamp };
843 default:
844 return null;
845 }
847​
848export function applyPullRequestOverrides<Entry extends PullRequestListEntry>(
849 entries: ReadonlyArray<Entry>,
850 overrides: ReadonlyMap<string, PullRequestListOverride>,
851 keyOf: (entry: Entry) => string,
852 state: PullRequestListState,
853): ReadonlyArray<Entry> {
854 if (overrides.size === 0 && state === "all") return entries;
855 const out: Entry[] = [];
856 for (const entry of entries) {
857 const held = overrides.get(keyOf(entry));
858 const override =
859 held?.fromReply === true && isStalePullRequestReply(entry, held) ? undefined : held;
860 if (state !== "all" && (override?.state ?? entry.state) !== state) continue;
861 out.push(override === undefined ? entry : { ...entry, ...override });
862 }
863 return overrides.size === 0 && out.length === entries.length ? entries : out;
865​
866export function reusePullRequestEntries<Entry extends PullRequestListEntry>(
867 previous: ReadonlyArray<Entry>,
868 next: ReadonlyArray<Entry>,
869 keyOf: (entry: Entry) => string,
870): ReadonlyArray<Entry> {
871 if (previous.length === 0) return next;
872 const held = new Map(previous.map((entry) => [keyOf(entry), entry]));
873 let reused = 0;
874 const out = next.map((entry) => {
875 const before = held.get(keyOf(entry));
876 if (before !== undefined && JSON.stringify(before) === JSON.stringify(entry)) {
877 reused += 1;
878 return before;
879 }
880 return entry;
881 });
882 return reused === next.length &&
883 previous.length === next.length &&
884 previous.every((entry, index) => keyOf(entry) === keyOf(next[index]!))
885 ? previous
886 : out;
888​
889const PULL_REQUEST_OVERRIDE_TRUST_MS = 60_000;
890​
891/** Retire overrides only when returned rows agree; partial-feed absence proves nothing. */
892export function settlePullRequestOverrides<Entry extends PullRequestListEntry>(
893 overrides: ReadonlyMap<string, PullRequestListOverride>,
894 answered: ReadonlyArray<Entry>,
895 keyOf: (entry: Entry) => string,
896 now: number,
897): ReadonlyMap<string, PullRequestListOverride> {
898 if (overrides.size === 0) return overrides;
899 const byKey = new Map(answered.map((entry) => [keyOf(entry), entry]));
900 const kept = new Map<string, PullRequestListOverride>();
901 for (const [key, override] of overrides) {
902 const row = byKey.get(key);
903 if (row === undefined) {
904 kept.set(key, override);
905 continue;
906 }
907 const agrees =
908 row.state === override.state &&
909 (override.isDraft === undefined || row.isDraft === override.isDraft);
910 const outranked = now - override.at > PULL_REQUEST_OVERRIDE_TRUST_MS;
911 if (!agrees && !outranked) kept.set(key, override);
912 }
913 return kept.size === overrides.size ? overrides : kept;
915​
916export type PullRequestQuickAction = "close" | "merge" | "ready" | "reopen";
917​
918export function pullRequestHostActions(
919 providers: ReadonlyArray<PullRequestListResult["providers"][number]>,
920): (
921 entry: Pick<EnvironmentPullRequestEntry, "host" | "provider">,
922) => ReadonlySet<PullRequestAction> {
923 const byHost = new Map(
924 providers.flatMap((provider) =>
925 provider.actions === undefined
926 ? []
927 : [[provider.host.toLowerCase(), new Set(provider.actions)] as const],
928 ),
929 );
930 const none = new Set<PullRequestAction>();
931 return (entry) =>
932 byHost.get(entry.host.toLowerCase()) ??
933 sourceControlClients.find(entry.provider)?.changeRequestActionsWhenUnreported ??
934 none;
936​
937export function pullRequestQuickActions(
938 entry: Pick<EnvironmentPullRequestEntry, "state" | "isDraft">,
939 hostActions: ReadonlySet<PullRequestAction>,
940): ReadonlyArray<PullRequestQuickAction> {
941 const forState: ReadonlyArray<PullRequestQuickAction> =
942 entry.state === "merged"
943 ? []
944 : entry.state === "closed"
945 ? ["reopen"]
946 : entry.isDraft
947 ? ["close", "ready"]
948 : ["close", "merge"];
949 return forState.filter((action) => hostActions.has(action));
951​
952export function largestPullRequestReadCount(
953 entries: ReadonlyArray<EnvironmentPullRequestEntry>,
954): number {
955 const counts = new Map<string, number>();
956 for (const entry of entries) {
957 const read = `${entry.environmentId} ${entry.host.toLowerCase()} ${
958 sourceControlClients.find(entry.provider)?.changeRequestListScope === "host"
959 ? ""
960 : entry.repository.toLowerCase()
961 }`;
962 counts.set(read, (counts.get(read) ?? 0) + 1);
963 }
964 return Math.max(0, ...counts.values());
966​
967export function findProjectForRepository<
968 Project extends {
969 readonly id: string;
970 readonly environmentId: string;
971 readonly repositoryIdentity?: RepositoryIdentity | null | undefined;
972 },
973>(
974 projects: ReadonlyArray<Project>,
975 input: {
976 readonly repository: string;
977 readonly host?: string | undefined;
978 readonly selectedEnvironmentId?: string | null | undefined;
979 readonly scopedProjectId?: string | undefined;
980 readonly scopedEnvironmentId?: string | null | undefined;
981 },
982): Project | undefined {
983 const repository = input.repository.toLowerCase();
984 const host = input.host?.toLowerCase();
985 const candidates = projects.filter((project) => {
986 if (
987 input.selectedEnvironmentId != null &&
988 project.environmentId !== input.selectedEnvironmentId
989 ) {
990 return false;
991 }
992 const identity = project.repositoryIdentity;
993 if (
994 !identity ||
995 sourceControlClients.repositorySelector(identity)?.toLowerCase() !== repository
996 ) {
997 return false;
998 }
999 return (
1000 host === undefined ||
1001 sourceControlClients.changeRequestHost(identity, identity.provider) === host
1002 );
1003 });
1004 // Azure repository names can collide across projects on the same host.
1005 const scoped = findScopedProject(candidates, input.scopedEnvironmentId, input.scopedProjectId);
1006 return scoped ?? candidates[0];