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

GitHubPullRequestProvider.ts

637 lines23.2 KB

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