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

gitCafePullRequestJson.ts

694 lines23.6 KB

1import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
2import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
3import * as DateTime from "effect/DateTime";
4import * as Schema from "effect/Schema";
5import {
6 IsoDateTime,
7 NonNegativeInt,
8 PositiveInt,
9 TrimmedNonEmptyString,
10 type PullRequestActor,
11 type PullRequestCheck,
12 type PullRequestChecksState,
13 type PullRequestComment,
14 type PullRequestReaction,
15 type PullRequestReactionContent,
16 type PullRequestReviewerCandidate,
17 type PullRequestReviewThread,
18 type PullRequestViewerPermissions,
19} from "@t3tools/contracts";
20import type {
21 ProviderChangeRequest,
22 ProviderChangeRequestActivity,
23 ProviderChangeRequestStack,
24 ProviderDiffSlice,
25} from "@t3tools/source-control-core/server/PullRequestProvider";
26​
27const Actor = Schema.Union([
28 Schema.Struct({
29 kind: Schema.Literal("local"),
30 actorId: Schema.String,
31 handle: TrimmedNonEmptyString,
32 displayName: Schema.NullOr(Schema.String),
33 avatarUrl: Schema.NullOr(Schema.String),
34 bot: Schema.optional(Schema.Boolean),
35 }),
36 Schema.Struct({
37 kind: Schema.Literal("github"),
38 actorId: Schema.String,
39 login: TrimmedNonEmptyString,
40 avatarUrl: Schema.NullOr(Schema.String),
41 accountType: Schema.optional(Schema.NullOr(Schema.String)),
42 linkedProfile: Schema.optional(
43 Schema.NullOr(
44 Schema.Struct({ handle: TrimmedNonEmptyString, actorId: Schema.optional(Schema.String) }),
45 ),
46 ),
47 }),
48 Schema.Struct({ kind: Schema.Literal("unavailable"), actorId: Schema.String }),
49]);
50type Actor = typeof Actor.Type;
51​
52const PullState = Schema.Literals(["open", "closed", "merged"]);
53​
54export const GitCafePull = Schema.Struct({
55 id: TrimmedNonEmptyString,
56 number: PositiveInt,
57 title: TrimmedNonEmptyString,
58 state: PullState,
59 draft: Schema.Boolean,
60 sourceBranch: Schema.String,
61 targetBranch: Schema.String,
62 headOid: Schema.NullOr(Schema.String),
63 author: Actor,
64 createdAt: IsoDateTime,
65 updatedAt: IsoDateTime,
66 version: NonNegativeInt,
67 reviewers: Schema.optional(Schema.Array(Schema.Struct({ actor: Actor }))),
68 labels: Schema.optional(
69 Schema.Array(
70 Schema.Struct({ name: TrimmedNonEmptyString, color: Schema.NullOr(Schema.String) }),
71 ),
72 ),
73});
74export type GitCafePull = typeof GitCafePull.Type;
75​
76export const GitCafePulls = Schema.Struct({
77 items: Schema.Array(GitCafePull),
78 next: Schema.NullOr(Schema.String),
79});
80​
81export const GitCafePullDetail = Schema.Struct({
82 ...GitCafePull.fields,
83 description: Schema.NullOr(Schema.String),
84 closedAt: Schema.NullOr(IsoDateTime),
85 mergedAt: Schema.NullOr(IsoDateTime),
86 sourceRepo: Schema.NullOr(Schema.Struct({ owner: Schema.String, name: Schema.String })),
87 observedBaseOid: Schema.optional(Schema.NullOr(Schema.String)),
88 mergeRoute: Schema.optional(Schema.Literals(["native", "provider", "unsupported"])),
89 lockedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
90 viewerActorId: Schema.optional(Schema.NullOr(Schema.String)),
91 // Set once GitHub has merged a pull request GitCafe routed there, which can be before the
92 // sync brings the merged state back.
93 providerMerge: Schema.optional(Schema.NullOr(Schema.Struct({ mergedAt: IsoDateTime }))),
94 capabilities: Schema.Struct({
95 comment: Schema.Boolean,
96 review: Schema.Boolean,
97 merge: Schema.Boolean,
98 edit: Schema.Boolean,
99 moderate: Schema.Boolean,
100 }),
101});
102export type GitCafePullDetail = typeof GitCafePullDetail.Type;
103​
104const CommentCapabilities = Schema.Struct({
105 edit: Schema.Boolean,
106 hide: Schema.Boolean,
107 unhide: Schema.Boolean,
108 delete: Schema.Boolean,
109 resolve: Schema.Boolean,
110 unresolve: Schema.Boolean,
111});
112​
113const GitCafeComment = Schema.Struct({
114 id: TrimmedNonEmptyString,
115 threadId: TrimmedNonEmptyString,
116 version: Schema.optional(NonNegativeInt),
117 author: Actor,
118 body: Schema.NullOr(Schema.String),
119 createdAt: IsoDateTime,
120 path: Schema.NullOr(Schema.String),
121 // The API allows any integer here; only a positive line anchors a review thread.
122 line: Schema.NullOr(Schema.Int),
123 side: Schema.NullOr(Schema.Literals(["left", "right"])),
124 commitOid: Schema.NullOr(Schema.String),
125 resolvedAt: Schema.NullOr(IsoDateTime),
126 capabilities: Schema.optional(CommentCapabilities),
127});
128type GitCafeComment = typeof GitCafeComment.Type;
129​
130export const GitCafeComments = Schema.Struct({
131 items: Schema.Array(GitCafeComment),
132 next: Schema.NullOr(Schema.String),
133});
134​
135export const GitCafeReviews = Schema.Struct({
136 items: Schema.Array(
137 Schema.Struct({
138 id: TrimmedNonEmptyString,
139 author: Actor,
140 body: Schema.NullOr(Schema.String),
141 verdict: Schema.Literals(["approve", "request_changes", "comment"]),
142 dismissedAt: Schema.NullOr(IsoDateTime),
143 createdAt: IsoDateTime,
144 }),
145 ),
146 next: Schema.NullOr(Schema.String),
147});
148​
149export const GitCafeCommits = Schema.Struct({
150 items: Schema.Array(
151 Schema.Struct({ oid: TrimmedNonEmptyString, summary: Schema.String, time: Schema.Finite }),
152 ),
153 truncated: Schema.Boolean,
154 next: Schema.NullOr(Schema.String),
155 headOid: Schema.String,
156});
157​
158export const GitCafeLabels = Schema.Struct({
159 items: Schema.Array(
160 Schema.Struct({
161 id: TrimmedNonEmptyString,
162 name: TrimmedNonEmptyString,
163 color: Schema.NullOr(Schema.String),
164 description: Schema.optional(Schema.NullOr(Schema.String)),
165 }),
166 ),
167 next: Schema.NullOr(Schema.String),
168});
169​
170/** A pull request's reviewers and its reviewer candidates, each actor under its id. */
171export const GitCafeActorEntries = Schema.Struct({
172 items: Schema.Array(Schema.Struct({ id: TrimmedNonEmptyString, actor: Actor })),
173 next: Schema.NullOr(Schema.String),
174});
175​
176export const GitCafeReactions = Schema.Struct({
177 items: Schema.Array(
178 Schema.Struct({
179 subject: Schema.Struct({
180 kind: Schema.Literals(["issue", "issue_comment", "pull_request", "pull_request_comment"]),
181 id: TrimmedNonEmptyString,
182 }),
183 emoji: Schema.Union([
184 Schema.Struct({ kind: Schema.Literal("unicode"), value: TrimmedNonEmptyString }),
185 Schema.Struct({ kind: Schema.Literal("custom"), id: TrimmedNonEmptyString }),
186 ]),
187 count: PositiveInt,
188 viewerReactionId: Schema.NullOr(Schema.String),
189 reactors: Schema.Array(Actor),
190 }),
191 ),
192 next: Schema.NullOr(Schema.String),
193});
194​
195const GitCafeStack = Schema.Struct({
196 id: TrimmedNonEmptyString,
197 number: PositiveInt,
198 revision: PositiveInt,
199 landingBase: Schema.String,
200 members: Schema.Array(
201 Schema.Struct({
202 pullRequestNumber: PositiveInt,
203 title: Schema.String,
204 state: PullState,
205 draft: Schema.Boolean,
206 sourceBranch: Schema.String,
207 headOid: Schema.optional(Schema.String),
208 position: PositiveInt,
209 }),
210 ),
211});
212export type GitCafeStack = typeof GitCafeStack.Type;
213​
214export const GitCafeStackEnvelope = Schema.Struct({ stack: Schema.NullOr(GitCafeStack) });
215​
216const GitCafeDiffFile = Schema.Struct({
217 path: TrimmedNonEmptyString,
218 oldPath: Schema.optional(Schema.NullOr(Schema.String)),
219 status: Schema.optional(
220 Schema.Literals([
221 "added",
222 "deleted",
223 "modified",
224 "typeChanged",
225 "conflicted",
226 "renamed",
227 "copied",
228 ]),
229 ),
230 additions: Schema.optional(NonNegativeInt),
231 deletions: Schema.optional(NonNegativeInt),
232 binary: Schema.optional(Schema.Boolean),
233 tooLarge: Schema.optional(Schema.Boolean),
234 hunksOmitted: Schema.optional(Schema.Boolean),
235 isSubmodule: Schema.optional(Schema.Boolean),
236 oldOid: Schema.optional(Schema.String),
237 newOid: Schema.optional(Schema.String),
238 // Structural pages (`/changes`, `/compare`) list files without hunks; the batched reads fill them.
239 hunks: Schema.optional(
240 Schema.Array(
241 Schema.Struct({
242 oldStart: NonNegativeInt,
243 oldLines: NonNegativeInt,
244 newStart: NonNegativeInt,
245 newLines: NonNegativeInt,
246 lines: Schema.Array(Schema.Struct({ origin: Schema.String, content: Schema.String })),
247 }),
248 ),
249 ),
250});
251export type GitCafeDiffFile = typeof GitCafeDiffFile.Type;
252export const GitCafeDiffFiles = Schema.Array(GitCafeDiffFile);
253​
254export const GitCafeDiff = Schema.Struct({
255 items: GitCafeDiffFiles,
256 truncated: Schema.optional(Schema.Boolean),
257});
258​
259export const GitCafeChecks = Schema.Struct({
260 items: Schema.Array(
261 Schema.Struct({
262 id: Schema.optional(Schema.NullOr(Schema.String)),
263 provider: Schema.optional(Schema.NullOr(Schema.String)),
264 githubApp: Schema.optional(Schema.NullOr(Schema.String)),
265 name: TrimmedNonEmptyString,
266 status: Schema.Literals(["queued", "in_progress", "completed"]),
267 conclusion: Schema.NullOr(Schema.String),
268 summary: Schema.NullOr(Schema.String),
269 detailsUrl: Schema.NullOr(Schema.String),
270 }),
271 ),
272 next: Schema.NullOr(Schema.String),
273});
274​
275/** A user search answer and a collaborator page carry the same fields a picker shows. */
276export const GitCafePeople = Schema.Struct({
277 items: Schema.Array(
278 Schema.Struct({
279 handle: TrimmedNonEmptyString,
280 displayName: Schema.optional(Schema.NullOr(Schema.String)),
281 avatarUrl: Schema.optional(Schema.NullOr(Schema.String)),
282 }),
283 ),
284 next: Schema.NullOr(Schema.String),
285});
286​
287export function toPeople(
288 people: typeof GitCafePeople.Type,
289 host: string,
290): ReadonlyArray<PullRequestActor> {
291 return people.items.map((person) => ({
292 login: person.handle,
293 name: person.displayName ?? null,
294 avatarUrl: person.avatarUrl == null ? null : new URL(person.avatarUrl, `https://${host}`).href,
295 }));
297​
298interface RepositoryOnHost {
299 readonly repository: string;
300 readonly host: string;
302​
303function toActor(actor: Actor, host: string): PullRequestActor | null {
304 if (actor.kind === "unavailable") return null;
305 return {
306 login: actor.kind === "local" ? actor.handle : actor.login,
307 name: actor.kind === "local" ? actor.displayName : null,
308 // A mirrored GitHub account says it is a bot by its account type, not its login.
309 ...((actor.kind === "local" && actor.bot === true) ||
310 (actor.kind === "github" && actor.accountType === "bot")
311 ? { isBot: true }
312 : {}),
313 // GitCafe serves its own avatars by path, so a relative one is read against the host.
314 avatarUrl: actor.avatarUrl === null ? null : new URL(actor.avatarUrl, `https://${host}`).href,
315 };
317​
318export function toReviewers(
319 pull: Pick<GitCafePull, "reviewers">,
320 host: string,
321): ReadonlyArray<PullRequestActor> {
322 return (pull.reviewers ?? []).flatMap(({ actor }) => {
323 const reviewer = toActor(actor, host);
324 return reviewer === null ? [] : [reviewer];
325 });
327​
328export function toReviewerCandidates(
329 candidates: typeof GitCafeActorEntries.Type,
330 input: {
331 readonly requested: ReadonlySet<string>;
332 readonly authorActorId: string;
333 readonly host: string;
334 },
335): ReadonlyArray<PullRequestReviewerCandidate> {
336 return candidates.items.flatMap(({ id, actor }) => {
337 const reviewer = id === input.authorActorId ? null : toActor(actor, input.host);
338 return reviewer === null
339 ? []
340 : [{ ...reviewer, id, kind: "user" as const, isRequested: input.requested.has(id) }];
341 });
343​
344function reviewerLogins(actor: Actor, host: string): ReadonlyArray<string> {
345 const reviewer = toActor(actor, host);
346 if (reviewer === null) return [];
347 return actor.kind === "github" && actor.linkedProfile
348 ? [reviewer.login, actor.linkedProfile.handle]
349 : [reviewer.login];
351​
352export function toChangeRequest(
353 pull: GitCafePull,
354 target: RepositoryOnHost,
355): ProviderChangeRequest {
356 return {
357 number: pull.number,
358 title: pull.title,
359 url: `https://${target.host}/${target.repository}/pulls/${pull.number}`,
360 author: toActor(pull.author, target.host),
361 headBranch: pull.sourceBranch,
362 baseBranch: pull.targetBranch,
363 state: pull.state,
364 isDraft: pull.draft,
365 mergeability: "unknown",
366 additions: 0,
367 deletions: 0,
368 createdAt: pull.createdAt,
369 updatedAt: pull.updatedAt,
370 reviewRequestLogins: (pull.reviewers ?? []).flatMap(({ actor }) =>
371 reviewerLogins(actor, target.host),
372 ),
373 labels: (pull.labels ?? []).map(({ name, color }) => ({ name, color })),
374 };
376​
377function isViewerAuthor(detail: GitCafePullDetail): boolean {
378 const viewer = detail.viewerActorId;
379 if (viewer == null) return false;
380 const { author } = detail;
381 return (
382 author.actorId === viewer ||
383 (author.kind === "github" && author.linkedProfile?.actorId === viewer)
384 );
386​
387export function toViewerPermissions(detail: GitCafePullDetail): PullRequestViewerPermissions {
388 const { comment, edit, review, merge, moderate } = detail.capabilities;
389 const open = comment && (detail.lockedAt == null || moderate);
390 return {
391 actions: [
392 ...(edit && detail.state === "open"
393 ? ([detail.draft ? "ready" : "draft", "close"] as const)
394 : edit && detail.state === "closed"
395 ? (["reopen"] as const)
396 : []),
397 ...(merge && detail.state === "open" && !detail.draft ? (["merge"] as const) : []),
398 ],
399 stackRebase: merge,
400 comment: open,
401 resolve: open,
402 // GitCafe refuses an author's approval and request for changes, as GitHub does.
403 verdicts: !review
404 ? []
405 : isViewerAuthor(detail)
406 ? ["comment"]
407 : ["approve", "request-changes", "comment"],
408 requestReviewers: edit && detail.state === "open",
409 labels: edit && detail.state === "open",
410 editChangeRequest: edit,
411 // GitCafe's only branch update moves a whole stack.
412 updateMethods: [],
413 };
415​
416const REACTIONS: Readonly<Record<string, PullRequestReactionContent>> = {
417 "πŸ‘": "thumbs-up",
418 "πŸ‘Ž": "thumbs-down",
419 "πŸ˜„": "laugh",
420 "πŸŽ‰": "hooray",
421 "πŸ˜•": "confused",
422 "❀": "heart",
423 "πŸš€": "rocket",
424 "πŸ‘€": "eyes",
425};
426​
427export const REACTION_EMOJI: Readonly<Record<PullRequestReactionContent, string>> = {
428 "thumbs-up": "πŸ‘",
429 "thumbs-down": "πŸ‘Ž",
430 laugh: "πŸ˜„",
431 hooray: "πŸŽ‰",
432 confused: "πŸ˜•",
433 heart: "❀️",
434 rocket: "πŸš€",
435 eyes: "πŸ‘€",
436};
437​
438export function reactionContent(emoji: string): PullRequestReactionContent | undefined {
439 return REACTIONS[emoji.replaceAll("\uFE0F", "")];
441​
442function toReactions(data: typeof GitCafeReactions.Type, host: string) {
443 const reactions: Array<PullRequestReaction> = [];
444 const byComment = new Map<string, Array<PullRequestReaction>>();
445 for (const item of data.items) {
446 const content = item.emoji.kind === "unicode" ? reactionContent(item.emoji.value) : undefined;
447 if (content === undefined) continue;
448 const reaction: PullRequestReaction = {
449 content,
450 count: item.count,
451 actors: item.reactors.flatMap((actor) => {
452 const reactor = toActor(actor, host);
453 return reactor === null ? [] : [reactor.login];
454 }),
455 viewerHasReacted: item.viewerReactionId !== null,
456 };
457 if (item.subject.kind === "pull_request") reactions.push(reaction);
458 else if (item.subject.kind === "pull_request_comment")
459 byComment.set(item.subject.id, [...(byComment.get(item.subject.id) ?? []), reaction]);
460 }
461 return { reactions, byComment };
463​
464const REVIEW_STATES = {
465 approve: "approved",
466 request_changes: "changes_requested",
467 comment: "commented",
468} as const;
469​
470export function toActivity(input: {
471 readonly comments: typeof GitCafeComments.Type;
472 readonly reviews: typeof GitCafeReviews.Type;
473 readonly commits: typeof GitCafeCommits.Type;
474 readonly reactions?: typeof GitCafeReactions.Type;
475 readonly headOid?: string;
476 readonly host: string;
477}): ProviderChangeRequestActivity {
478 const { host } = input;
479 const reactions = input.reactions === undefined ? undefined : toReactions(input.reactions, host);
480 const remark = (comment: GitCafeComment) => ({
481 id: comment.id,
482 author: toActor(comment.author, host),
483 body: comment.body ?? "",
484 createdAt: comment.createdAt,
485 url: null,
486 ...(comment.capabilities === undefined ? {} : { canEdit: comment.capabilities.edit }),
487 ...(reactions === undefined ? {} : { reactions: reactions.byComment.get(comment.id) ?? [] }),
488 });
489 const ordered = input.comments.items.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
490 const groups = new Map<string, Array<GitCafeComment>>();
491 for (const comment of ordered) {
492 if (!comment.path || comment.line === null || comment.line < 1 || comment.side === null)
493 continue;
494 groups.set(comment.threadId, [...(groups.get(comment.threadId) ?? []), comment]);
495 }
496 const reviewThreads = [...groups.values()].map((group): PullRequestReviewThread => {
497 const first = group[0]!;
498 const latest = group.at(-1)!;
499 const root = group.find((comment) => comment.id === comment.threadId);
500 return {
501 id: first.threadId,
502 path: first.path!,
503 line: first.line,
504 side: first.side!,
505 isResolved: root?.resolvedAt != null,
506 isOutdated:
507 input.headOid !== undefined &&
508 latest.commitOid !== null &&
509 latest.commitOid !== input.headOid,
510 comments: group.map(remark),
511 ...(root?.capabilities === undefined
512 ? {}
513 : {
514 canResolve:
515 root.resolvedAt === null ? root.capabilities.resolve : root.capabilities.unresolve,
516 }),
517 };
518 });
519 const comments: Array<PullRequestComment> = [
520 ...ordered.map((comment) => ({
521 ...remark(comment),
522 kind: comment.path === null ? ("issue-comment" as const) : ("review-comment" as const),
523 path: comment.path,
524 reviewState: null,
525 })),
526 ...input.reviews.items.map((review) => ({
527 id: review.id,
528 kind: "review" as const,
529 author: toActor(review.author, host),
530 body: review.body ?? "",
531 createdAt: review.createdAt,
532 url: null,
533 path: null,
534 reviewState: review.dismissedAt !== null ? "dismissed" : REVIEW_STATES[review.verdict],
535 })),
536 ];
537 return {
538 comments: comments.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt)),
539 commentCount: input.comments.items.length + input.reviews.items.length,
540 commentsTruncated: input.comments.next !== null || input.reviews.next !== null,
541 reviewThreads,
542 commits: input.commits.items.map((commit) => ({
543 oid: commit.oid,
544 messageHeadline: commit.summary,
545 committedDate: DateTime.formatIso(DateTime.makeUnsafe(commit.time * 1_000)),
546 })),
547 ...(reactions === undefined ? {} : { reactions: reactions.reactions }),
548 };
550​
551export function toStack(stack: GitCafeStack, target: RepositoryOnHost): ProviderChangeRequestStack {
552 return {
553 id: stack.id,
554 number: stack.number,
555 url: `https://${target.host}/${target.repository}/stacks/${stack.number}`,
556 base: stack.landingBase,
557 layers: stack.members
558 .toSorted((a, b) => a.position - b.position)
559 .map((member) => ({
560 number: member.pullRequestNumber,
561 title: member.title,
562 headBranch: member.sourceBranch,
563 state: member.state,
564 isDraft: member.draft,
565 ...(member.headOid === undefined ? {} : { headSha: member.headOid }),
566 })),
567 };
569​
570export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {
571 const chunks: Array<string> = [];
572 const omittedFileStats: Array<{ path: string; additions: number; deletions: number }> = [];
573 for (const file of diff.items) {
574 const oldPath = file.oldPath ?? file.path;
575 const a = quoteGitPatchPath(`a/${oldPath}`);
576 const b = quoteGitPatchPath(`b/${file.path}`);
577 const before = file.status === "added" ? "/dev/null" : a;
578 const after = file.status === "deleted" ? "/dev/null" : b;
579 const mode = file.isSubmodule ? "160000" : "100644";
580 const lines = [`diff --git ${a} ${b}`];
581 if (file.status === "added") lines.push(`new file mode ${mode}`);
582 if (file.status === "deleted") lines.push(`deleted file mode ${mode}`);
583 if (file.status === "renamed" || file.status === "copied") {
584 const action = file.status === "renamed" ? "rename" : "copy";
585 lines.push(
586 `${action} from ${quoteGitPatchPath(oldPath)}`,
587 `${action} to ${quoteGitPatchPath(file.path)}`,
588 );
589 }
590 if (file.binary) {
591 lines.push(`Binary files ${before} and ${after} differ`);
592 } else if (file.tooLarge || file.hunksOmitted) {
593 omittedFileStats.push({
594 path: file.path,
595 additions: file.additions ?? 0,
596 deletions: file.deletions ?? 0,
597 });
598 } else if (file.isSubmodule) {
599 const hasOld = file.status !== "added" && file.oldOid !== undefined;
600 const hasNew = file.status !== "deleted" && file.newOid !== undefined;
601 lines.push(`--- ${before}`, `+++ ${after}`);
602 lines.push(`@@ -${hasOld ? "1" : "0,0"} +${hasNew ? "1" : "0,0"} @@`);
603 if (hasOld) lines.push(`-Subproject commit ${file.oldOid}`);
604 if (hasNew) lines.push(`+Subproject commit ${file.newOid}`);
605 } else {
606 const hunks = file.hunks ?? [];
607 if (hunks.length > 0) lines.push(`--- ${before}`, `+++ ${after}`);
608 for (const hunk of hunks) {
609 lines.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);
610 for (const line of hunk.lines) {
611 // GitCafe marks a missing final newline with libgit2's own origins.
612 if (["=", ">", "<"].includes(line.origin)) lines.push("\\ No newline at end of file");
613 else lines.push(`${line.origin}${line.content.replace(/\n$/u, "")}`);
614 }
615 }
616 }
617 chunks.push(lines.join("\n"));
618 }
619 return {
620 patch: chunks.length === 0 ? "" : `${chunks.join("\n")}\n`,
621 truncated: diff.truncated === true || omittedFileStats.length > 0,
622 nextCursor: null,
623 ...(omittedFileStats.length === 0 ? {} : { omittedFileStats }),
624 };
626​
627function checkStatus(check: (typeof GitCafeChecks.Type.items)[number]): PullRequestCheck["status"] {
628 if (check.status !== "completed") return "pending";
629 switch (check.conclusion) {
630 case "success":
631 return "success";
632 case "neutral":
633 return "neutral";
634 case "skipped":
635 return "skipped";
636 case "cancelled":
637 return "cancelled";
638 case "action_required":
639 return "action-required";
640 default:
641 return "failure";
642 }
644​
645type GitCafeCheck = (typeof GitCafeChecks.Type.items)[number];
646​
647/** A check run's id, which grows with each run. Commit statuses (`status:…`) carry no such order. */
648function runOrder(check: GitCafeCheck): bigint | null {
649 return check.id != null && /^\d+$/u.test(check.id) ? BigInt(check.id) : null;
651​
652/**
653 * GitCafe lists every run of a commit's checks, so a re-run arrives beside the run it replaced.
654 * The newest run is the check's state; an older failure is history, not a failing check. Runs whose
655 * order cannot be told apart are all kept, so no failure is hidden. Two reporters may share a check
656 * name, so a run only replaces runs from the same provider and GitHub app.
657 */
658export function toChecks(checks: typeof GitCafeChecks.Type): ReadonlyArray<PullRequestCheck> {
659 const kept: Array<GitCafeCheck> = [];
660 const newestByKey = new Map<string, { index: number; order: bigint }>();
661 for (const check of checks.items) {
662 const order = runOrder(check);
663 if (order === null) {
664 kept.push(check);
665 continue;
666 }
667 const key = JSON.stringify([check.provider ?? null, check.githubApp ?? null, check.name]);
668 const newest = newestByKey.get(key);
669 if (newest === undefined) {
670 newestByKey.set(key, { index: kept.length, order });
671 kept.push(check);
672 } else if (order > newest.order) {
673 kept[newest.index] = check;
674 newest.order = order;
675 }
676 }
677 return sortChecks(
678 kept.map((check) => ({
679 name: check.name,
680 status: checkStatus(check),
681 description: check.summary,
682 url: check.detailsUrl,
683 })),
684 );
686​
687export function checksStateOf(
688 checks: ReadonlyArray<PullRequestCheck>,
689): PullRequestChecksState | null {
690 const statuses = new Set(checks.map((check) => check.status));
691 if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
692 if (statuses.has("pending") || statuses.has("action-required")) return "pending";
693 return statuses.has("success") ? "passing" : null;