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