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