Open History to see the last commit
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 // Only positive lines anchor review threads; the API allows any integer.
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 // `/changes` and `/compare` omit hunks; 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 }));
296}
297β
298interface RepositoryOnHost {
299 readonly repository: string;
300 readonly host: string;
301}
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 };
316}
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 });
326}
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 });
342}
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];
350}
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 };
375}
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 );
385}
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 };
414}
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", "")];
440}
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 };
462}
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 };
549}
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 };
568}
569β
570function isEOFMarker(origin: string | undefined) {
571 return origin === "=" || origin === ">" || origin === "<";
572}
573β
574export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {
575 const chunks: Array<string> = [];
576 const omittedFileStats: Array<{ path: string; additions: number; deletions: number }> = [];
577 for (const file of diff.items) {
578 const oldPath = file.oldPath ?? file.path;
579 const a = quoteGitPatchPath(`a/${oldPath}`);
580 const b = quoteGitPatchPath(`b/${file.path}`);
581 const before = file.status === "added" ? "/dev/null" : a;
582 const after = file.status === "deleted" ? "/dev/null" : b;
583 const mode = file.isSubmodule ? "160000" : "100644";
584 const lines = [`diff --git ${a} ${b}`];
585 if (file.status === "added") lines.push(`new file mode ${mode}`);
586 if (file.status === "deleted") lines.push(`deleted file mode ${mode}`);
587 if (file.status === "renamed" || file.status === "copied") {
588 const action = file.status === "renamed" ? "rename" : "copy";
589 const hasChanges =
590 (file.hunks?.length ?? 0) > 0 ||
591 (file.additions ?? 0) > 0 ||
592 (file.deletions ?? 0) > 0 ||
593 file.binary ||
594 file.tooLarge ||
595 file.hunksOmitted;
596 // GitCafe has no similarity score; Pierre needs this header to retain rename metadata.
597 lines.push(
598 `similarity index ${hasChanges ? 0 : 100}%`,
599 `${action} from ${quoteGitPatchPath(oldPath)}`,
600 `${action} to ${quoteGitPatchPath(file.path)}`,
601 );
602 }
603 if (file.binary) {
604 lines.push(`Binary files ${before} and ${after} differ`);
605 } else if (file.tooLarge || file.hunksOmitted) {
606 omittedFileStats.push({
607 path: file.path,
608 additions: file.additions ?? 0,
609 deletions: file.deletions ?? 0,
610 });
611 } else if (file.isSubmodule) {
612 const hasOld = file.status !== "added" && file.oldOid !== undefined;
613 const hasNew = file.status !== "deleted" && file.newOid !== undefined;
614 lines.push(`--- ${before}`, `+++ ${after}`);
615 lines.push(`@@ -${hasOld ? "1" : "0,0"} +${hasNew ? "1" : "0,0"} @@`);
616 if (hasOld) lines.push(`-Subproject commit ${file.oldOid}`);
617 if (hasNew) lines.push(`+Subproject commit ${file.newOid}`);
618 } else {
619 const hunks = file.hunks ?? [];
620 if (hunks.length > 0) lines.push(`--- ${before}`, `+++ ${after}`);
621 for (const hunk of hunks) {
622 lines.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);
623 for (const [index, line] of hunk.lines.entries()) {
624 if (isEOFMarker(line.origin)) {
625 lines.push("\\ No newline at end of file");
626 } else {
627 lines.push(`${line.origin}${line.content.replace(/\n$/u, "")}`);
628 if (
629 ["+", "-", " "].includes(line.origin) &&
630 !line.content.endsWith("\n") &&
631 !isEOFMarker(hunk.lines[index + 1]?.origin)
632 ) {
633 lines.push("\\ No newline at end of file");
634 }
635 }
636 }
637 }
638 }
639 chunks.push(lines.join("\n"));
640 }
641 return {
642 patch: chunks.length === 0 ? "" : `${chunks.join("\n")}\n`,
643 truncated: diff.truncated === true || omittedFileStats.length > 0,
644 nextCursor: null,
645 ...(omittedFileStats.length === 0 ? {} : { omittedFileStats }),
646 };
647}
648β
649function checkStatus(check: (typeof GitCafeChecks.Type.items)[number]): PullRequestCheck["status"] {
650 if (check.status !== "completed") return "pending";
651 switch (check.conclusion) {
652 case "success":
653 return "success";
654 case "neutral":
655 return "neutral";
656 case "skipped":
657 return "skipped";
658 case "cancelled":
659 return "cancelled";
660 case "action_required":
661 return "action-required";
662 default:
663 return "failure";
664 }
665}
666β
667type GitCafeCheck = (typeof GitCafeChecks.Type.items)[number];
668β
669/** A check run's id, which grows with each run. Commit statuses (`status:β¦`) carry no such order. */
670function runOrder(check: GitCafeCheck): bigint | null {
671 return check.id != null && /^\d+$/u.test(check.id) ? BigInt(check.id) : null;
672}
673β
674/**
675 * GitCafe lists every run of a commit's checks, so a re-run arrives beside the run it replaced.
676 * The newest run is the check's state; an older failure is history, not a failing check. Runs whose
677 * order cannot be told apart are all kept, so no failure is hidden. Two reporters may share a check
678 * name, so a run only replaces runs from the same provider and GitHub app.
679 */
680export function toChecks(checks: typeof GitCafeChecks.Type): ReadonlyArray<PullRequestCheck> {
681 const kept: Array<GitCafeCheck> = [];
682 const newestByKey = new Map<string, { index: number; order: bigint }>();
683 for (const check of checks.items) {
684 const order = runOrder(check);
685 if (order === null) {
686 kept.push(check);
687 continue;
688 }
689 const key = JSON.stringify([check.provider ?? null, check.githubApp ?? null, check.name]);
690 const newest = newestByKey.get(key);
691 if (newest === undefined) {
692 newestByKey.set(key, { index: kept.length, order });
693 kept.push(check);
694 } else if (order > newest.order) {
695 kept[newest.index] = check;
696 newest.order = order;
697 }
698 }
699 return sortChecks(
700 kept.map((check) => ({
701 name: check.name,
702 status: checkStatus(check),
703 description: check.summary,
704 url: check.detailsUrl,
705 })),
706 );
707}
708β
709export function checksStateOf(
710 checks: ReadonlyArray<PullRequestCheck>,
711): PullRequestChecksState | null {
712 const statuses = new Set(checks.map((check) => check.status));
713 if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
714 if (statuses.has("pending") || statuses.has("action-required")) return "pending";
715 return statuses.has("success") ? "passing" : null;
716}