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

GitHubPullRequestProvider.ts

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