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

gitCafePullRequestJson.ts

558 lines18.6 KB

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