Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import type {
6 PullRequestActor,
7 PullRequestCapabilities,
8 PullRequestCheck,
9 PullRequestReaction,
10 PullRequestViewerPermissions,
11} from "@t3tools/contracts";
12
13import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
14import {
15 PullRequestProviderError,
16 type PullRequestProviderFailure,
17 type ProviderChangeRequestActivity,
18 type ProviderChangeRequestDetail,
19 type PullRequestProviderApi,
20} from "./PullRequestProvider.ts";
21import type { GitHubViewerAccess, GitHubWorkflowRunApproval } from "./gitHubPullRequestJson.ts";
22
23const CAPABILITIES: PullRequestCapabilities = {
24 diff: true,
25 comment: true,
26 actions: [
27 "merge",
28 "ready",
29 "draft",
30 "close",
31 "reopen",
32 "update-branch",
33 "enable-auto-merge",
34 "disable-auto-merge",
35 "revert",
36 "approve-workflows",
37 ],
38 mergeMethods: ["merge", "squash", "rebase"],
39 updateMethods: ["merge", "rebase"],
40 search: true,
41 reactions: true,
42 review: {
43 inlineComment: true,
44 reply: true,
45 resolve: true,
46 verdicts: ["comment", "approve", "request-changes"],
47 },
48 reviewers: { request: true, listCandidates: true },
49 edit: { changeRequest: true, comment: 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 actions: [
73 // Arming a merge and taking the arming back are the merge, deferred: whoever may not
74 // merge here may not leave an instruction to merge later either.
75 ...(access.canWrite
76 ? ([
77 "merge",
78 "enable-auto-merge",
79 "disable-auto-merge",
80 "revert",
81 "approve-workflows",
82 ] as const)
83 : []),
84 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
85 // Whether this viewer may update the branch is GitHub's own answer, read with the
86 // comparison; without it the action is offered to nobody rather than to everybody.
87 ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
88 ],
89 comment: true,
90 resolve: access.canWrite || access.didAuthor,
91 // Anyone may review a pull request they can see, except their own: GitHub refuses an author's
92 // approval and their request for changes ("Can not approve your own pull request"), and
93 // leaves them commenting, which is what an author has to say about their own change anyway.
94 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
95 requestReviewers: access.canWrite,
96 ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
97 // Triage is the one role that labels without writing, which is what triage is for.
98 labels: access.canTriage,
99 };
100}
101
102/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
103export function gitHubProviderFailure(
104 error: GitHubPullRequestCli.GitHubPullRequestCliError,
105): PullRequestProviderFailure {
106 if (error._tag === "GitHubCliUnavailableError") return { reason: "missing-tool" };
107 if (error._tag === "GitHubCliAuthenticationError") return { reason: "unauthenticated" };
108 if (error._tag === "GitHubCliRateLimitError") return { reason: "rate-limited" };
109 if (error._tag === "SourceControlRateLimitPausedError") {
110 return { reason: "rate-limited", retryAt: error.retryAt };
111 }
112 return { reason: "failed" };
113}
114
115/**
116 * `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
117 * applied here by login. An actor already carrying one keeps it.
118 *
119 * A login GitHub did not answer for falls back to the picture every GitHub install serves at
120 * `/<login>.png`. The lookup is one more request per repository and can be refused — a rate
121 * limit, a slow host — and a face that comes and goes between two loads of the same page reads
122 * as a bug in the page rather than as a request that failed quietly.
123 */
124function withAvatar(
125 actor: PullRequestActor | null,
126 avatarsByLogin: ReadonlyMap<string, string>,
127 host: string,
128): PullRequestActor | null {
129 if (actor === null || actor.avatarUrl !== null) return actor;
130 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
131 return avatarUrl === null ? actor : { ...actor, avatarUrl };
132}
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 ];
167}
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;
175}
176
177/** True where markdown would render nothing: whitespace, or only HTML comments. */
178const rendersEmpty = (body: string): boolean =>
179 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
180
181export const make = Effect.gen(function* () {
182 const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
183
184 const repositoryAccessCache = yield* Cache.makeWith(
185 (key: string) => {
186 const [cwd, repository, host] = JSON.parse(key) as [string, string, string];
187 return cli.getRepositoryAccess({ cwd, repository, host });
188 },
189 {
190 capacity: 128,
191 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
192 },
193 );
194 const getRepositoryAccess = (input: {
195 readonly cwd: string;
196 readonly repository: string;
197 readonly host: string;
198 }) => Cache.get(repositoryAccessCache, JSON.stringify([input.cwd, input.repository, input.host]));
199
200 const fail = (operation: string) => (error: GitHubPullRequestCli.GitHubPullRequestCliError) =>
201 new PullRequestProviderError({
202 provider: "github",
203 operation,
204 ...gitHubProviderFailure(error),
205 detail: error.detail,
206 cause: error,
207 });
208
209 const provider: PullRequestProviderApi = {
210 kind: "github",
211 capabilities: CAPABILITIES,
212
213 getViewer: (input) =>
214 cli.getViewerLogin({ cwd: input.cwd }).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(Effect.mapError(fail("getChangeRequestSummary"))),
296
297 getChangeRequest: (input) =>
298 Effect.all(
299 [
300 cli.getPullRequestDetail(input).pipe(
301 Effect.flatMap((pullRequest) =>
302 Effect.all({
303 // Only an open pull request can be behind anything worth saying so about, and
304 // only one whose head repository is known can be compared at all.
305 comparison:
306 pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
307 ? Effect.succeed(null)
308 : cli
309 .getPullRequestBaseComparison({
310 ...input,
311 headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
312 })
313 .pipe(Effect.orElseSucceed(() => null)),
314 // GitHub omits a fork workflow that has not been approved from the normal check
315 // rollup. Read the action-required runs by head revision so "all passed" cannot
316 // be shown while a whole workflow is still waiting to start.
317 workflowApprovals:
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 }).pipe(Effect.map((extra) => ({ pullRequest, ...extra }))),
350 ),
351 ),
352 getRepositoryAccess({
353 cwd: input.cwd,
354 repository: input.repository,
355 host: input.host,
356 }),
357 // A small permissions query replaces the deeply paginated review-thread walk on the
358 // core path. Writes ask again immediately before mutating, so this is presentation.
359 cli.getViewerAccess(input),
360 ],
361 { concurrency: 3 },
362 ).pipe(
363 Effect.mapError(fail("getChangeRequest")),
364 Effect.map(([detail, repository, viewerAccess]): ProviderChangeRequestDetail => ({
365 ...detail.pullRequest,
366 checks: withWorkflowApprovals(
367 detail.pullRequest.checks,
368 detail.workflowApprovals.runs,
369 detail.workflowApprovals.unavailable,
370 ),
371 ...(detail.workflowApprovals.unavailable
372 ? {}
373 : { workflowApprovalsRequired: detail.workflowApprovals.runs.length }),
374 reviewers: detail.pullRequest.reviewRequestLogins.map((login) => ({
375 login,
376 name: null,
377 avatarUrl: null,
378 })),
379 mergeCapabilities: repository.mergeCapabilities,
380 viewerPermissions: gitHubViewerPermissions({
381 ...viewerAccess,
382 canUpdateBranch: detail.comparison?.viewerCanUpdate === true,
383 }),
384 baseComparison:
385 detail.comparison === null || detail.comparison.behindBy === null
386 ? "unknown"
387 : detail.comparison.behindBy > 0
388 ? "behind"
389 : "up-to-date",
390 ...(detail.comparison?.behindBy == null ? {} : { behindBy: detail.comparison.behindBy }),
391 })),
392 ),
393
394 getChangeRequestActivity: (input) =>
395 Effect.all(
396 [
397 cli.getPullRequestActivity(input),
398 // Line comments live on review threads, which `gh pr view --json` cannot reach. A
399 // GraphQL hiccup degrades to a truncated conversation rather than blanking activity.
400 cli.listReviewThreadComments(input).pipe(
401 Effect.orElseSucceed(() => ({
402 comments: [],
403 dismissalsByReviewId: new Map<string, string>(),
404 reactions: [],
405 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
406 reviewThreads: [],
407 commentCount: 0,
408 truncated: true,
409 reviewers: [],
410 avatarsByLogin: new Map<string, 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(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
425 reviewers: reviewThreads.reviewers,
426 reactions: reviewThreads.reactions,
427 commits: (reviewThreads.commits.length > 0
428 ? reviewThreads.commits
429 : pullRequest.commits
430 ).map((commit) => ({
431 ...commit,
432 ...reviewThreads.commitStats.get(commit.oid),
433 authors: commit.authors?.map(
434 (author) => withAvatar(author, reviewThreads.avatarsByLogin, input.host) ?? author,
435 ),
436 })),
437 comments: [...pullRequest.comments, ...reviewThreads.comments]
438 .map((comment) => ({
439 ...comment,
440 // GitHub keeps the dismissal reason on the timeline event, not on the review,
441 // so a dismissed review with nothing visible of its own reads its words from
442 // there. "Visible" and not "empty": bot reviews often carry only an HTML
443 // marker comment, which markdown renders as nothing.
444 body:
445 comment.kind === "review" &&
446 comment.reviewState?.toUpperCase() === "DISMISSED" &&
447 rendersEmpty(comment.body)
448 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
449 : comment.body,
450 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
451 // A comment out of `gh pr view --json` carries none of its own: that read
452 // reports no reaction at all, so they arrive from the GraphQL page by node id.
453 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
454 }))
455 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
456 // `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
457 // are always whole and only the thread walk can stop short of the host.
458 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
459 commentsTruncated: reviewThreads.truncated,
460 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
461 ...thread,
462 comments: thread.comments.map((comment) => ({
463 ...comment,
464 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
465 })),
466 })),
467 })),
468 ),
469
470 getReviewThreadComments: (input) =>
471 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
472
473 getViewerPermissions: (input) =>
474 Effect.all(
475 [
476 cli.getViewerAccess({ ...input, allowReserve: true }),
477 // Whether this viewer may update the branch is only on the comparison, and the
478 // comparison only resolves through the head ref the detail carries. A failure here
479 // withholds that one action rather than the whole answer, the way the detail path
480 // leaves the banner unknown.
481 cli.getPullRequestDetail(input).pipe(
482 Effect.flatMap((pullRequest) =>
483 pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
484 ? Effect.succeed(false)
485 : cli
486 .getPullRequestBaseComparison({
487 ...input,
488 headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
489 allowReserve: true,
490 })
491 .pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),
492 ),
493 Effect.orElseSucceed(() => false),
494 ),
495 ],
496 { concurrency: 2 },
497 ).pipe(
498 Effect.mapError(fail("getViewerPermissions")),
499 Effect.map(([access, canUpdateBranch]) =>
500 gitHubViewerPermissions({ ...access, canUpdateBranch }),
501 ),
502 ),
503
504 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
505
506 getDiffFileContents: (input) =>
507 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
508
509 listReviewerCandidates: (input) =>
510 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
511
512 setReviewerRequest: (input) =>
513 cli
514 .setReviewerRequest({
515 cwd: input.cwd,
516 repository: input.repository,
517 host: input.host,
518 number: input.number,
519 reviewers: input.reviewers,
520 requested: input.requested,
521 })
522 .pipe(Effect.mapError(fail("setReviewerRequest"))),
523
524 listLabelCandidates: (input) =>
525 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
526
527 setLabels: (input) =>
528 cli
529 .setLabels({
530 cwd: input.cwd,
531 repository: input.repository,
532 host: input.host,
533 number: input.number,
534 labels: input.labels,
535 applied: input.applied,
536 })
537 .pipe(Effect.mapError(fail("setLabels"))),
538
539 runAction: (input) =>
540 cli
541 .runPullRequestAction({
542 cwd: input.cwd,
543 repository: input.repository,
544 host: input.host,
545 number: input.number,
546 action: input.action,
547 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
548 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
549 })
550 .pipe(Effect.mapError(fail("runAction"))),
551
552 updateChangeRequest: (input) =>
553 cli
554 .updatePullRequest({
555 cwd: input.cwd,
556 repository: input.repository,
557 host: input.host,
558 number: input.number,
559 ...(input.title === undefined ? {} : { title: input.title }),
560 ...(input.body === undefined ? {} : { body: input.body }),
561 })
562 .pipe(Effect.mapError(fail("updateChangeRequest"))),
563
564 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
565
566 updateComment: (input) =>
567 cli
568 .updateComment({
569 cwd: input.cwd,
570 repository: input.repository,
571 host: input.host,
572 number: input.number,
573 commentId: input.commentId,
574 kind: input.kind,
575 body: input.body,
576 })
577 .pipe(Effect.mapError(fail("updateComment"))),
578
579 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
580
581 replyToThread: (input) =>
582 cli
583 .replyToReviewThread({
584 cwd: input.cwd,
585 repository: input.repository,
586 host: input.host,
587 threadId: input.threadId,
588 body: input.body,
589 })
590 .pipe(Effect.mapError(fail("replyToThread"))),
591
592 setReaction: (input) =>
593 cli
594 .setReaction({
595 cwd: input.cwd,
596 repository: input.repository,
597 host: input.host,
598 number: input.number,
599 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
600 content: input.content,
601 reacted: input.reacted,
602 })
603 .pipe(Effect.mapError(fail("setReaction"))),
604
605 setThreadResolution: (input) =>
606 cli
607 .setReviewThreadResolution({
608 cwd: input.cwd,
609 repository: input.repository,
610 host: input.host,
611 threadId: input.threadId,
612 resolved: input.resolved,
613 })
614 .pipe(Effect.mapError(fail("setThreadResolution"))),
615 };
616
617 return provider;
618});