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

gitCafePullRequestJson.ts

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