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

GitHubPullRequestProvider.ts

644 lines24.5 KB

1import * as Effect from "effect/Effect";
2import type {
3 PullRequestActor,
4 PullRequestCapabilities,
5 PullRequestCheck,
6 PullRequestReaction,
7 PullRequestViewerPermissions,
8} from "@t3tools/contracts";
9​
10import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
11import {
12 PullRequestProviderError,
13 type PullRequestProviderFailure,
14 type ProviderChangeRequestActivity,
15 type ProviderChangeRequestDetail,
16 type PullRequestProviderApi,
17} from "./PullRequestProvider.ts";
18import type { GitHubViewerAccess, GitHubWorkflowRunApproval } from "./gitHubPullRequestJson.ts";
19​
20const CAPABILITIES: PullRequestCapabilities = {
21 diff: true,
22 comment: true,
23 actions: [
24 "merge",
25 "ready",
26 "draft",
27 "close",
28 "reopen",
29 "update-branch",
30 "enable-auto-merge",
31 "disable-auto-merge",
32 "revert",
33 "approve-workflows",
34 ],
35 mergeMethods: ["merge", "squash", "rebase"],
36 updateMethods: ["merge", "rebase"],
37 search: true,
38 reactions: true,
39 viewedFiles: "host",
40 review: {
41 inlineComment: true,
42 reply: true,
43 resolve: true,
44 verdicts: ["comment", "approve", "request-changes"],
45 },
46 reviewers: { request: true, listCandidates: true },
47 edit: { changeRequest: true, comment: true },
48 stacks: true,
49 stackActions: true,
50 labels: true,
51};
52​
53/**
54 * What the signed-in account may do here, from the three things GitHub says about it.
55 *
56 * Merging needs a role that can push, which is the one thing a stranger on an open-source
57 * repository never has. The other four actions go by `viewerCanUpdate`, because the author of a
58 * pull request may close it, reopen it and move it in and out of draft with no more than read
59 * access on the repository it was opened against.
60 *
61 * Commenting and reviewing are not gated at all: read access is enough to say something and
62 * enough to approve or ask for changes, which is what open-source review consists of. Resolving a
63 * conversation is the exception — GitHub allows it to whoever can write, and to the author of the
64 * pull request the conversation is on.
65 *
66 * Asking somebody else for a review needs write access, which is the one thing here an author
67 * cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
68 * and refuses the request behind it.
69 */
70export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
71 return {
72 ...(access.canWrite ? { stackRebase: true } : {}),
73 actions: [
74 // Arming a merge and taking the arming back are the merge, deferred: whoever may not
75 // merge here may not leave an instruction to merge later either.
76 ...(access.canWrite
77 ? ([
78 "merge",
79 "enable-auto-merge",
80 "disable-auto-merge",
81 "revert",
82 "approve-workflows",
83 ] as const)
84 : []),
85 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
86 // Whether this viewer may update the branch is GitHub's own answer, read with the
87 // comparison; without it the action is offered to nobody rather than to everybody.
88 ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
89 ],
90 comment: true,
91 resolve: access.canWrite || access.didAuthor,
92 // Anyone may review a pull request they can see, except their own: GitHub refuses an author's
93 // approval and their request for changes ("Can not approve your own pull request"), and
94 // leaves them commenting, which is what an author has to say about their own change anyway.
95 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
96 requestReviewers: access.canWrite,
97 ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
98 // Triage is the one role that labels without writing, which is what triage is for.
99 labels: access.canTriage,
100 };
102​
103/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
104export function gitHubProviderFailure(
105 error: GitHubPullRequestCli.GitHubPullRequestCliError,
106): PullRequestProviderFailure {
107 if (error._tag === "GitHubCliUnavailableError") return { reason: "missing-tool" };
108 if (error._tag === "GitHubCliAuthenticationError") return { reason: "unauthenticated" };
109 if (error._tag === "GitHubCliRateLimitError")
110 return {
111 reason: "rate-limited",
112 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
113 };
114 if (error._tag === "SourceControlRateLimitPausedError") {
115 return { reason: "rate-limited", retryAt: error.retryAt };
116 }
117 return { reason: "failed" };
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. An actor already carrying one keeps it.
123 *
124 * A login GitHub did not answer for falls back to the picture every GitHub install serves at
125 * `/<login>.png`. The lookup is one more request per repository and can be refused — a rate
126 * limit, a slow host — and a face that comes and goes between two loads of the same page reads
127 * as a bug in the page rather than as a request that failed quietly.
128 */
129function withAvatar(
130 actor: PullRequestActor | null,
131 avatarsByLogin: ReadonlyMap<string, string>,
132 host: string,
133 botLogins?: ReadonlySet<string>,
134): PullRequestActor | null {
135 if (actor === null) return actor;
136 if (botLogins?.has(actor.login)) actor = { ...actor, isBot: true };
137 if (actor.avatarUrl !== null) return actor;
138 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
139 return avatarUrl === null ? actor : { ...actor, avatarUrl };
141​
142function withWorkflowApprovals(
143 checks: ReadonlyArray<PullRequestCheck>,
144 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
145 unavailable: boolean,
146): ReadonlyArray<PullRequestCheck> {
147 const representedRunIds = new Set<number>();
148 for (const check of checks) {
149 if (check.status !== "action-required" || check.url === null) continue;
150 const id = check.url.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1];
151 if (id !== undefined) representedRunIds.add(Number(id));
152 }
153 const approvalChecks = runs
154 .filter((run) => !representedRunIds.has(run.id))
155 .map((run): PullRequestCheck => ({
156 name: run.name,
157 status: "action-required",
158 description: "A maintainer must approve this workflow before it can run.",
159 url: run.url,
160 }));
161 return [
162 ...checks,
163 ...approvalChecks,
164 ...(unavailable
165 ? [
166 {
167 name: "Workflow approval status",
168 status: "action-required" as const,
169 description: "GitHub could not determine whether workflows are awaiting approval.",
170 url: null,
171 },
172 ]
173 : []),
174 ];
176​
177/**
178 * Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
179 * names no page, and a guessed URL that 404s is worse than the initials it would replace.
180 */
181export function loginAvatarUrl(login: string, host: string): string | null {
182 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
184​
185/** True where markdown would render nothing: whitespace, or only HTML comments. */
186const rendersEmpty = (body: string): boolean =>
187 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
188​
189export const make = Effect.gen(function* () {
190 const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
191​
192 const fail = (operation: string) => (error: GitHubPullRequestCli.GitHubPullRequestCliError) =>
193 new PullRequestProviderError({
194 provider: "github",
195 operation,
196 ...gitHubProviderFailure(error),
197 detail: error.detail,
198 cause: error,
199 });
200​
201 const provider: PullRequestProviderApi = {
202 kind: "github",
203 capabilities: CAPABILITIES,
204 getRoutingIdentity: (input) =>
205 cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
206 withVerifiedCredential: (input, use) =>
207 cli
208 .withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
209 .pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
210​
211 getViewer: (input) =>
212 cli
213 .getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
214 .pipe(Effect.mapError(fail("getViewer"))),
215​
216 listChangeRequests: (input) =>
217 cli
218 .listPullRequests({
219 cwd: input.cwd,
220 repository: input.repository,
221 host: input.host,
222 state: input.state,
223 involvement: input.involvement,
224 viewer: input.viewer,
225 limit: input.limit,
226 query: input.query,
227 cursor: input.cursor,
228 filters: input.filters,
229 })
230 .pipe(
231 Effect.mapError(fail("listChangeRequests")),
232 Effect.flatMap((page) =>
233 cli
234 .listActorAvatars({
235 cwd: input.cwd,
236 repository: input.repository,
237 host: input.host,
238 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
239 })
240 // A listing without faces is still a listing, so a failed lookup falls back to
241 // the initials rather than taking the rows down with it.
242 .pipe(
243 Effect.orElseSucceed(() => new Map<string, string>()),
244 Effect.map((avatarsByLogin) => ({
245 ...page,
246 items: page.items.map((item) => ({
247 ...item,
248 author: withAvatar(item.author, avatarsByLogin, input.host),
249 })),
250 })),
251 ),
252 ),
253 ),
254​
255 /**
256 * The same listing for a whole host in one search. The avatar lookup the per-repository read
257 * needs is not here: a search reports an author's picture itself, so a face costs no request
258 * of its own — `withAvatar` still stands behind it for the login GitHub answered nothing for.
259 */
260 listChangeRequestsAcross: (input) =>
261 cli
262 .searchPullRequests({
263 cwd: input.cwd,
264 host: input.host,
265 repositories: input.repositories,
266 state: input.state,
267 involvement: input.involvement,
268 viewer: input.viewer,
269 limit: input.limit,
270 query: input.query,
271 cursor: input.cursor,
272 filters: input.filters,
273 })
274 .pipe(
275 Effect.mapError(fail("listChangeRequestsAcross")),
276 Effect.map((batch) => ({
277 truncated: batch.truncated,
278 items: batch.items.map((item) => ({
279 ...item,
280 author: withAvatar(item.author, new Map<string, string>(), input.host),
281 })),
282 })),
283 ),
284​
285 listChangeRequestStats: (input) =>
286 cli
287 .listPullRequestStats({
288 cwd: input.cwd,
289 host: input.host,
290 changeRequests: input.changeRequests,
291 })
292 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
293​
294 getChangeRequestSummary: (input) =>
295 cli.getPullRequestSummary(input).pipe(
296 // `gh pr view` names the author without an avatar; the login-shaped URL every user
297 // has stands in, without the second request the listing spends on it.
298 Effect.map((summary) => ({
299 ...summary,
300 ...(summary.author === undefined
301 ? {}
302 : { author: withAvatar(summary.author, new Map(), input.host) }),
303 })),
304 Effect.mapError(fail("getChangeRequestSummary")),
305 ),
306​
307 getChangeRequestStack: (input) =>
308 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
309​
310 getChangeRequestPreview: (input) =>
311 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
312​
313 getChangeRequest: (input) =>
314 cli.getPullRequestDetail(input).pipe(
315 Effect.flatMap((pullRequest) => {
316 // Fork workflows awaiting approval are absent from the normal check rollup.
317 const approvals =
318 pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
319 ? Effect.succeed({
320 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
321 unavailable: false,
322 })
323 : pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
324 ? Effect.succeed({
325 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
326 unavailable: true,
327 })
328 : cli
329 .listWorkflowRunsRequiringApproval({
330 ...input,
331 headSha: pullRequest.headSha,
332 headBranch: pullRequest.headBranch,
333 headRepositoryOwner: pullRequest.headRepositoryOwner,
334 isCrossRepository: true,
335 })
336 .pipe(
337 Effect.matchEffect({
338 onFailure: (error) =>
339 error._tag === "GitHubCliRateLimitError" ||
340 error._tag === "SourceControlRateLimitPausedError"
341 ? Effect.fail(error)
342 : Effect.succeed({
343 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
344 unavailable: true,
345 }),
346 onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
347 }),
348 );
349 return approvals.pipe(
350 Effect.map((workflowApprovals): ProviderChangeRequestDetail => ({
351 ...pullRequest,
352 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
353 checks: withWorkflowApprovals(
354 pullRequest.checks,
355 workflowApprovals.runs,
356 workflowApprovals.unavailable,
357 ),
358 ...(workflowApprovals.unavailable
359 ? {}
360 : { workflowApprovalsRequired: workflowApprovals.runs.length }),
361 reviewers: pullRequest.reviewRequestLogins.map((login) => ({
362 login,
363 name: null,
364 avatarUrl: null,
365 })),
366 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
367 viewerPermissions: gitHubViewerPermissions({
368 ...pullRequest.viewerAccess,
369 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
370 }),
371 baseComparison:
372 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
373 ? "unknown"
374 : pullRequest.comparison.behindBy > 0
375 ? "behind"
376 : "up-to-date",
377 ...(pullRequest.comparison?.behindBy == null
378 ? {}
379 : { behindBy: pullRequest.comparison.behindBy }),
380 })),
381 );
382 }),
383 Effect.mapError(fail("getChangeRequest")),
384 ),
385​
386 getChangeRequestActivity: (input) =>
387 Effect.all(
388 [
389 cli.getPullRequestActivity(input),
390 // Line comments live on review threads, which `gh pr view --json` cannot reach. A
391 // GraphQL hiccup degrades to a truncated conversation rather than blanking activity.
392 cli.listReviewThreadComments(input).pipe(
393 Effect.orElseSucceed(() => ({
394 comments: [],
395 dismissalsByReviewId: new Map<string, string>(),
396 reactions: [],
397 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
398 reviewThreads: [],
399 commentCount: 0,
400 truncated: true,
401 reviewers: [],
402 avatarsByLogin: new Map<string, string>(),
403 botLogins: new Set<string>(),
404 commitStats: new Map<
405 string,
406 { readonly additions: number; readonly deletions: number }
407 >(),
408 commits: [],
409 viewer: { canUpdate: true, didAuthor: false },
410 })),
411 ),
412 ],
413 { concurrency: 2 },
414 ).pipe(
415 Effect.mapError(fail("getChangeRequestActivity")),
416 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
417 author: withAvatar(
418 pullRequest.author,
419 reviewThreads.avatarsByLogin,
420 input.host,
421 reviewThreads.botLogins,
422 ),
423 reviewers: reviewThreads.reviewers,
424 reactions: reviewThreads.reactions,
425 commits: (reviewThreads.commits.length > 0
426 ? reviewThreads.commits
427 : pullRequest.commits
428 ).map((commit) => ({
429 ...commit,
430 ...reviewThreads.commitStats.get(commit.oid),
431 authors: commit.authors?.map(
432 (author) =>
433 withAvatar(
434 author,
435 reviewThreads.avatarsByLogin,
436 input.host,
437 reviewThreads.botLogins,
438 ) ?? author,
439 ),
440 })),
441 comments: [...pullRequest.comments, ...reviewThreads.comments]
442 .map((comment) => ({
443 ...comment,
444 // GitHub keeps the dismissal reason on the timeline event, not on the review,
445 // so a dismissed review with nothing visible of its own reads its words from
446 // there. "Visible" and not "empty": bot reviews often carry only an HTML
447 // marker comment, which markdown renders as nothing.
448 body:
449 comment.kind === "review" &&
450 comment.reviewState?.toUpperCase() === "DISMISSED" &&
451 rendersEmpty(comment.body)
452 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
453 : comment.body,
454 author: withAvatar(
455 comment.author,
456 reviewThreads.avatarsByLogin,
457 input.host,
458 reviewThreads.botLogins,
459 ),
460 // A comment out of `gh pr view --json` carries none of its own: that read
461 // reports no reaction at all, so they arrive from the GraphQL page by node id.
462 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
463 }))
464 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
465 // `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
466 // are always whole and only the thread walk can stop short of the host.
467 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
468 commentsTruncated: reviewThreads.truncated,
469 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
470 ...thread,
471 comments: thread.comments.map((comment) => ({
472 ...comment,
473 author: withAvatar(
474 comment.author,
475 reviewThreads.avatarsByLogin,
476 input.host,
477 reviewThreads.botLogins,
478 ),
479 })),
480 })),
481 })),
482 ),
483​
484 getReviewThreadComments: (input) =>
485 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
486​
487 getViewerPermissions: (input) =>
488 Effect.all(
489 [
490 cli.getViewerAccess({ ...input, allowReserve: true }),
491 // Whether this viewer may update the branch is only on the comparison, and the
492 // comparison only resolves through the head ref the detail carries. A failure here
493 // withholds that one action rather than the whole answer, the way the detail path
494 // leaves the banner unknown.
495 input.includeUpdateBranch === false
496 ? Effect.succeed(false)
497 : cli.getPullRequestDetail(input).pipe(
498 Effect.flatMap((pullRequest) =>
499 pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
500 ? Effect.succeed(false)
501 : cli
502 .getPullRequestBaseComparison({
503 ...input,
504 headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
505 allowReserve: true,
506 })
507 .pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),
508 ),
509 Effect.orElseSucceed(() => false),
510 ),
511 ],
512 { concurrency: 2 },
513 ).pipe(
514 Effect.mapError(fail("getViewerPermissions")),
515 Effect.map(([access, canUpdateBranch]) =>
516 gitHubViewerPermissions({ ...access, canUpdateBranch }),
517 ),
518 ),
519​
520 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
521​
522 getDiffFileContents: (input) =>
523 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
524​
525 getFilesViewed: (input) =>
526 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
527​
528 setFilesViewed: (input) =>
529 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
530​
531 listReviewerCandidates: (input) =>
532 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
533​
534 setReviewerRequest: (input) =>
535 cli
536 .setReviewerRequest({
537 cwd: input.cwd,
538 repository: input.repository,
539 host: input.host,
540 number: input.number,
541 reviewers: input.reviewers,
542 requested: input.requested,
543 })
544 .pipe(Effect.mapError(fail("setReviewerRequest"))),
545​
546 listLabelCandidates: (input) =>
547 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
548​
549 setLabels: (input) =>
550 cli
551 .setLabels({
552 cwd: input.cwd,
553 repository: input.repository,
554 host: input.host,
555 number: input.number,
556 labels: input.labels,
557 applied: input.applied,
558 })
559 .pipe(Effect.mapError(fail("setLabels"))),
560​
561 runAction: (input) =>
562 cli
563 .runPullRequestAction({
564 cwd: input.cwd,
565 repository: input.repository,
566 host: input.host,
567 number: input.number,
568 action: input.action,
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});