Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
3import * as Effect from "effect/Effect";
4import type {
5 PullRequestActor,
6 PullRequestCapabilities,
7 PullRequestCheck,
8 PullRequestReaction,
9 PullRequestViewerPermissions,
10} from "@t3tools/contracts";
11
12import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
13import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
14import {
15 PullRequestProviderError,
16 type PullRequestProviderFailure,
17 type ProviderChangeRequestActivity,
18 type ProviderChangeRequestDetail,
19 type PullRequestProviderApi,
20 type ProviderRepositoryRef,
21} from "@t3tools/source-control-core/server/PullRequestProvider";
22import type {
23 GitHubRepositoryAccess,
24 GitHubViewerAccess,
25 GitHubWorkflowRunApproval,
26} from "./gitHubPullRequestJson.ts";
27import { definition } from "../client/definition.ts";
28
29const CAPABILITIES: PullRequestCapabilities = {
30 diff: true,
31 comment: true,
32 actions: [...definition.changeRequestActions],
33 mergeMethods: ["merge", "squash", "rebase"],
34 deleteBranch: true,
35 updateMethods: ["merge", "rebase"],
36 search: true,
37 reactions: true,
38 viewedFiles: "host",
39 review: {
40 inlineComment: true,
41 reply: true,
42 resolve: true,
43 verdicts: ["comment", "approve", "request-changes"],
44 },
45 reviewers: { request: true, listCandidates: true },
46 edit: { changeRequest: true, comment: true },
47 stacks: true,
48 stackActions: true,
49 labels: true,
50 assignees: true,
51};
52
53/**
54 * Asking somebody else for a review needs write access, which is the one thing here an author
55 * cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
56 * and refuses the request behind it.
57 */
58export function gitHubViewerPermissions(
59 access: GitHubViewerAccess & Pick<GitHubRepositoryAccess, "autoMergeAllowed">,
60): PullRequestViewerPermissions {
61 return {
62 ...(access.canWrite ? { stackRebase: true } : {}),
63 actions: [
64 ...(access.canDeleteBranch === true ? (["delete-branch"] as const) : []),
65 // Keep disabling available if the repository has since turned auto-merge off.
66 ...(access.canWrite
67 ? ([
68 "merge",
69 ...(access.autoMergeAllowed && access.canMergeNow !== true
70 ? (["enable-auto-merge"] as const)
71 : []),
72 "disable-auto-merge",
73 "revert",
74 "approve-workflows",
75 ] as const)
76 : []),
77 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
78 // Whether this viewer may update the branch is GitHub's own answer, read with the
79 // comparison; without it the action is offered to nobody rather than to everybody.
80 ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
81 ],
82 comment: true,
83 resolve: access.canWrite || access.didAuthor,
84 // Anyone may review a pull request they can see, except their own: GitHub refuses an author's
85 // approval and their request for changes ("Can not approve your own pull request"), and
86 // leaves them commenting, which is what an author has to say about their own change anyway.
87 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
88 requestReviewers: access.canWrite,
89 ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
90 labels: access.canTriage,
91 // Assigning, like labelling, takes triage.
92 assignees: access.canTriage,
93 };
94}
95
96export function gitHubProviderFailure(
97 error: GitHubPullRequestApi.GitHubPullRequestApiError,
98): PullRequestProviderFailure {
99 switch (error._tag) {
100 case "GitHubCliMissingError":
101 return { reason: "missing-tool" };
102 case "GitHubNotSignedInError":
103 case "GitHubHostDisabledError":
104 case "GitHubApiAuthenticationError":
105 return { reason: "unauthenticated" };
106 case "GitHubApiRateLimitError":
107 return {
108 reason: "rate-limited",
109 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
110 };
111 case "SourceControlRateLimitPausedError":
112 return { reason: "rate-limited", retryAt: error.retryAt };
113 case "GitHubApiNotFoundError":
114 return { reason: "not-found" };
115 default:
116 return { reason: "failed" };
117 }
118}
119
120/**
121 * `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
122 * applied here by login.
123 */
124function withAvatar(
125 actor: PullRequestActor | null,
126 avatarsByLogin: ReadonlyMap<string, string>,
127 host: string,
128 botLogins?: ReadonlySet<string>,
129): PullRequestActor | null {
130 if (actor === null) return actor;
131 if (botLogins?.has(actor.login)) actor = { ...actor, isBot: true };
132 if (actor.avatarUrl !== null) return actor;
133 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
134 return avatarUrl === null ? actor : { ...actor, avatarUrl };
135}
136
137function withWorkflowApprovals(
138 checks: ReadonlyArray<PullRequestCheck>,
139 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
140 unavailable: boolean,
141): ReadonlyArray<PullRequestCheck> {
142 const representedRunIds = new Set<number>();
143 for (const check of checks) {
144 if (check.status !== "action-required" || check.url === null) continue;
145 const id = check.url.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1];
146 if (id !== undefined) representedRunIds.add(Number(id));
147 }
148 const approvalChecks = runs
149 .filter((run) => !representedRunIds.has(run.id))
150 .map((run): PullRequestCheck => ({
151 name: run.name,
152 status: "action-required",
153 description: "A maintainer must approve this workflow before it can run.",
154 url: run.url,
155 }));
156 return [
157 ...checks,
158 ...approvalChecks,
159 ...(unavailable
160 ? [
161 {
162 name: "Workflow approval status",
163 status: "action-required" as const,
164 description: "GitHub could not determine whether workflows are awaiting approval.",
165 url: null,
166 },
167 ]
168 : []),
169 ];
170}
171
172/**
173 * Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
174 * names no page, and a guessed URL that 404s is worse than the initials it would replace.
175 */
176export function loginAvatarUrl(login: string, host: string): string | null {
177 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
178}
179
180const rendersEmpty = (body: string): boolean =>
181 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
182
183export const make = Effect.gen(function* () {
184 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
185
186 const fail = (operation: string) => (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
187 new PullRequestProviderError({
188 provider: SourceControlProviderKind.make("github"),
189 operation,
190 ...gitHubProviderFailure(error),
191 detail: error.message,
192 cause: error,
193 });
194
195 const readChecks = (input: ProviderRepositoryRef & { readonly number: number }) =>
196 cli.getPullRequestDetail(input).pipe(
197 Effect.flatMap((pullRequest) =>
198 (pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
199 ? Effect.succeed({
200 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
201 unavailable: false,
202 })
203 : pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
204 ? Effect.succeed({
205 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
206 unavailable: true,
207 })
208 : cli
209 .listWorkflowRunsRequiringApproval({
210 ...input,
211 headSha: pullRequest.headSha,
212 headBranch: pullRequest.headBranch,
213 headRepositoryOwner: pullRequest.headRepositoryOwner,
214 isCrossRepository: true,
215 })
216 .pipe(
217 Effect.matchEffect({
218 onFailure: (error) =>
219 error._tag === "GitHubApiRateLimitError" ||
220 error._tag === "SourceControlRateLimitPausedError"
221 ? Effect.fail(error)
222 : Effect.succeed({
223 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
224 unavailable: true,
225 }),
226 onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
227 }),
228 )
229 ).pipe(
230 Effect.map((workflowApprovals) => ({
231 ...pullRequest,
232 author: withAvatar(pullRequest.author, new Map(), input.host),
233 checks: withWorkflowApprovals(
234 pullRequest.checks,
235 workflowApprovals.runs,
236 workflowApprovals.unavailable,
237 ),
238 ...(workflowApprovals.unavailable
239 ? {}
240 : { workflowApprovalsRequired: workflowApprovals.runs.length }),
241 })),
242 ),
243 ),
244 );
245
246 const provider: PullRequestProviderApi = {
247 kind: SourceControlProviderKind.make("github"),
248 capabilities: CAPABILITIES,
249 mergeMessageRewrite: removeAgentCredits,
250 getRoutingIdentity: (input) =>
251 cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
252 withVerifiedCredential: (input, use) =>
253 cli
254 .withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
255 .pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
256
257 getViewer: (input) =>
258 cli
259 .getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
260 .pipe(Effect.mapError(fail("getViewer"))),
261
262 listChangeRequests: (input) =>
263 cli
264 .listPullRequests({
265 cwd: input.cwd,
266 repository: input.repository,
267 host: input.host,
268 state: input.state,
269 involvement: input.involvement,
270 viewer: input.viewer,
271 limit: input.limit,
272 query: input.query,
273 cursor: input.cursor,
274 filters: input.filters,
275 })
276 .pipe(
277 Effect.mapError(fail("listChangeRequests")),
278 Effect.flatMap((page) =>
279 cli
280 .listActorAvatars({
281 cwd: input.cwd,
282 repository: input.repository,
283 host: input.host,
284 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
285 })
286 .pipe(
287 Effect.orElseSucceed(() => new Map<string, string>()),
288 Effect.map((avatarsByLogin) => ({
289 ...page,
290 items: page.items.map((item) => ({
291 ...item,
292 author: withAvatar(item.author, avatarsByLogin, input.host),
293 })),
294 })),
295 ),
296 ),
297 ),
298
299 listChangeRequestsAcross: (input) =>
300 cli
301 .searchPullRequests({
302 cwd: input.cwd,
303 host: input.host,
304 repositories: input.repositories,
305 state: input.state,
306 involvement: input.involvement,
307 viewer: input.viewer,
308 limit: input.limit,
309 query: input.query,
310 cursor: input.cursor,
311 filters: input.filters,
312 })
313 .pipe(
314 Effect.mapError(fail("listChangeRequestsAcross")),
315 Effect.map((batch) => ({
316 truncated: batch.truncated,
317 items: batch.items.map((item) => ({
318 ...item,
319 author: withAvatar(item.author, new Map<string, string>(), input.host),
320 })),
321 })),
322 ),
323
324 listChangeRequestStats: (input) =>
325 cli
326 .listPullRequestStats({
327 cwd: input.cwd,
328 host: input.host,
329 changeRequests: input.changeRequests,
330 })
331 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
332
333 getChangeRequestSummary: (input) =>
334 cli.getPullRequestSummary(input).pipe(
335 Effect.map((summary) => ({
336 ...summary,
337 ...(summary.author === undefined
338 ? {}
339 : { author: withAvatar(summary.author, new Map(), input.host) }),
340 })),
341 Effect.mapError(fail("getChangeRequestSummary")),
342 ),
343
344 getChangeRequestStack: (input) =>
345 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
346
347 getChangeRequestWatchFingerprint: (input) =>
348 cli
349 .getPullRequestWatchFingerprint(input)
350 .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
351
352 getChangeRequestPreview: (input) =>
353 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
354
355 getChangeRequestChecks: (input) =>
356 cli.revalidateChecks(input, readChecks(input)).pipe(
357 Effect.map(({ state, checks }) => ({ state, checks })),
358 Effect.mapError(fail("getChangeRequestChecks")),
359 ),
360
361 getChangeRequest: (input) =>
362 readChecks(input).pipe(
363 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
364 ...pullRequest,
365 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
366 reviewers: [
367 ...pullRequest.reviewRequestLogins.map((login) => ({
368 login,
369 name: null,
370 avatarUrl: null,
371 })),
372 ...pullRequest.reviewRequestTeams,
373 ],
374 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
375 viewerPermissions: gitHubViewerPermissions({
376 ...pullRequest.viewerAccess,
377 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
378 }),
379 baseComparison:
380 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
381 ? "unknown"
382 : pullRequest.comparison.behindBy > 0
383 ? "behind"
384 : "up-to-date",
385 ...(pullRequest.comparison?.behindBy == null
386 ? {}
387 : { behindBy: pullRequest.comparison.behindBy }),
388 })),
389 Effect.mapError(fail("getChangeRequest")),
390 ),
391
392 getChangeRequestActivity: (input) =>
393 Effect.all(
394 [
395 cli.getPullRequestActivity(input),
396 // Line comments live on review threads, which `gh pr view --json` cannot reach.
397 cli.listReviewThreadComments(input).pipe(
398 Effect.orElseSucceed(() => ({
399 comments: [],
400 dismissalsByReviewId: new Map<string, string>(),
401 reactions: [],
402 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
403 editedAtById: new Map<string, string>(),
404 reviewThreads: [],
405 commentCount: 0,
406 truncated: true,
407 reviewThreadsTruncated: true,
408 reviewers: [],
409 avatarsByLogin: new Map<string, string>(),
410 botLogins: new Set<string>(),
411 commitStats: new Map<
412 string,
413 { readonly additions: number; readonly deletions: number }
414 >(),
415 commits: [],
416 viewer: { canUpdate: true, didAuthor: false },
417 })),
418 ),
419 ],
420 { concurrency: 2 },
421 ).pipe(
422 Effect.mapError(fail("getChangeRequestActivity")),
423 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
424 author: withAvatar(
425 pullRequest.author,
426 reviewThreads.avatarsByLogin,
427 input.host,
428 reviewThreads.botLogins,
429 ),
430 reviewers: reviewThreads.reviewers,
431 reactions: reviewThreads.reactions,
432 commits: (reviewThreads.commits.length > 0
433 ? reviewThreads.commits
434 : pullRequest.commits
435 ).map((commit) => ({
436 ...commit,
437 ...reviewThreads.commitStats.get(commit.oid),
438 authors: commit.authors?.map(
439 (author) =>
440 withAvatar(
441 author,
442 reviewThreads.avatarsByLogin,
443 input.host,
444 reviewThreads.botLogins,
445 ) ?? author,
446 ),
447 })),
448 comments: [...pullRequest.comments, ...reviewThreads.comments]
449 .map((comment) => ({
450 ...comment,
451 // GitHub keeps the dismissal reason on the timeline event, not on the review,
452 // so a dismissed review with nothing visible of its own reads its words from
453 // there. "Visible" and not "empty": bot reviews often carry only an HTML
454 // marker comment, which markdown renders as nothing.
455 body:
456 comment.kind === "review" &&
457 comment.reviewState?.toUpperCase() === "DISMISSED" &&
458 rendersEmpty(comment.body)
459 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
460 : comment.body,
461 author: withAvatar(
462 comment.author,
463 reviewThreads.avatarsByLogin,
464 input.host,
465 reviewThreads.botLogins,
466 ),
467 // A comment out of `gh pr view --json` carries none of its own: that read
468 // reports no reaction at all, so they arrive from the GraphQL page by node id.
469 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
470 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
471 }))
472 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
473 // `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
474 // are always whole and only the thread walk can stop short of the host.
475 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
476 commentsTruncated: reviewThreads.truncated,
477 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
478 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
479 ...thread,
480 comments: thread.comments.map((comment) => ({
481 ...comment,
482 author: withAvatar(
483 comment.author,
484 reviewThreads.avatarsByLogin,
485 input.host,
486 reviewThreads.botLogins,
487 ),
488 })),
489 })),
490 })),
491 ),
492
493 getReviewThreadComments: (input) =>
494 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
495
496 getViewerPermissions: (input) => {
497 const lightAccess = cli
498 .getViewerAccess({ ...input, allowReserve: true })
499 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
500 if (input.includeUpdateBranch === false) {
501 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
502 }
503 return cli.getPullRequestDetail(input).pipe(
504 Effect.provideService(SourceControlRateLimit.Interactive, true),
505 Effect.map((pullRequest) =>
506 gitHubViewerPermissions({
507 ...pullRequest.viewerAccess,
508 canUpdateBranch:
509 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
510 }),
511 ),
512 Effect.catchIf(
513 (error) =>
514 error._tag !== "GitHubApiRateLimitError" &&
515 error._tag !== "SourceControlRateLimitPausedError",
516 () => lightAccess,
517 ),
518 Effect.mapError(fail("getViewerPermissions")),
519 );
520 },
521
522 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
523
524 getDiffFileContents: (input) =>
525 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
526
527 getFilesViewed: (input) =>
528 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
529
530 getFileStats: (input) =>
531 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
532 setFilesViewed: (input) =>
533 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
534
535 listReviewerCandidates: (input) =>
536 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
537
538 setReviewerRequest: (input) =>
539 cli
540 .setReviewerRequest({
541 cwd: input.cwd,
542 repository: input.repository,
543 host: input.host,
544 number: input.number,
545 reviewers: input.reviewers,
546 requested: input.requested,
547 })
548 .pipe(Effect.mapError(fail("setReviewerRequest"))),
549
550 listLabelCandidates: (input) =>
551 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
552
553 setLabels: (input) =>
554 cli
555 .setLabels({
556 cwd: input.cwd,
557 repository: input.repository,
558 host: input.host,
559 number: input.number,
560 labels: input.labels,
561 applied: input.applied,
562 })
563 .pipe(Effect.mapError(fail("setLabels"))),
564
565 listAssigneeCandidates: (input) =>
566 cli.listAssigneeCandidates(input).pipe(Effect.mapError(fail("listAssigneeCandidates"))),
567
568 setAssignees: (input) =>
569 cli
570 .setAssignees({
571 cwd: input.cwd,
572 repository: input.repository,
573 host: input.host,
574 number: input.number,
575 assignees: input.assignees,
576 assigned: input.assigned,
577 })
578 .pipe(Effect.mapError(fail("setAssignees"))),
579
580 runAction: (input) =>
581 cli
582 .runPullRequestAction({
583 cwd: input.cwd,
584 repository: input.repository,
585 host: input.host,
586 number: input.number,
587 action: input.action,
588 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
589 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
590 ...(input.expectedStackHeads === undefined
591 ? {}
592 : { expectedStackHeads: input.expectedStackHeads }),
593 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
594 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
595 })
596 .pipe(Effect.mapError(fail("runAction"))),
597
598 updateChangeRequest: (input) =>
599 cli
600 .updatePullRequest({
601 cwd: input.cwd,
602 repository: input.repository,
603 host: input.host,
604 number: input.number,
605 ...(input.title === undefined ? {} : { title: input.title }),
606 ...(input.body === undefined ? {} : { body: input.body }),
607 })
608 .pipe(Effect.mapError(fail("updateChangeRequest"))),
609
610 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
611
612 updateComment: (input) =>
613 cli
614 .updateComment({
615 cwd: input.cwd,
616 repository: input.repository,
617 host: input.host,
618 number: input.number,
619 commentId: input.commentId,
620 kind: input.kind,
621 body: input.body,
622 })
623 .pipe(Effect.mapError(fail("updateComment"))),
624
625 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
626
627 replyToThread: (input) =>
628 cli
629 .replyToReviewThread({
630 cwd: input.cwd,
631 repository: input.repository,
632 host: input.host,
633 threadId: input.threadId,
634 body: input.body,
635 })
636 .pipe(Effect.mapError(fail("replyToThread"))),
637
638 setReaction: (input) =>
639 cli
640 .setReaction({
641 cwd: input.cwd,
642 repository: input.repository,
643 host: input.host,
644 number: input.number,
645 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
646 content: input.content,
647 reacted: input.reacted,
648 })
649 .pipe(Effect.mapError(fail("setReaction"))),
650
651 setThreadResolution: (input) =>
652 cli
653 .setReviewThreadResolution({
654 cwd: input.cwd,
655 repository: input.repository,
656 host: input.host,
657 threadId: input.threadId,
658 resolved: input.resolved,
659 })
660 .pipe(Effect.mapError(fail("setThreadResolution"))),
661 };
662
663 return provider;
664});