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 stacks: true,
51 stackActions: true,
52 labels: true,
53};
54
55/**
56 * What the signed-in account may do here, from the three things GitHub says about it.
57 *
58 * Merging needs a role that can push, which is the one thing a stranger on an open-source
59 * repository never has. The other four actions go by `viewerCanUpdate`, because the author of a
60 * pull request may close it, reopen it and move it in and out of draft with no more than read
61 * access on the repository it was opened against.
62 *
63 * Commenting and reviewing are not gated at all: read access is enough to say something and
64 * enough to approve or ask for changes, which is what open-source review consists of. Resolving a
65 * conversation is the exception — GitHub allows it to whoever can write, and to the author of the
66 * pull request the conversation is on.
67 *
68 * Asking somebody else for a review needs write access, which is the one thing here an author
69 * cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
70 * and refuses the request behind it.
71 */
72export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
73 return {
74 ...(access.canWrite ? { stackRebase: true } : {}),
75 actions: [
76 // Arming a merge and taking the arming back are the merge, deferred: whoever may not
77 // merge here may not leave an instruction to merge later either.
78 ...(access.canWrite
79 ? ([
80 "merge",
81 "enable-auto-merge",
82 "disable-auto-merge",
83 "revert",
84 "approve-workflows",
85 ] as const)
86 : []),
87 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
88 // Whether this viewer may update the branch is GitHub's own answer, read with the
89 // comparison; without it the action is offered to nobody rather than to everybody.
90 ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
91 ],
92 comment: true,
93 resolve: access.canWrite || access.didAuthor,
94 // Anyone may review a pull request they can see, except their own: GitHub refuses an author's
95 // approval and their request for changes ("Can not approve your own pull request"), and
96 // leaves them commenting, which is what an author has to say about their own change anyway.
97 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
98 requestReviewers: access.canWrite,
99 ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
100 // Triage is the one role that labels without writing, which is what triage is for.
101 labels: access.canTriage,
102 };
103}
104
105/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
106export function gitHubProviderFailure(
107 error: GitHubPullRequestCli.GitHubPullRequestCliError,
108): PullRequestProviderFailure {
109 if (error._tag === "GitHubCliUnavailableError") return { reason: "missing-tool" };
110 if (error._tag === "GitHubCliAuthenticationError") return { reason: "unauthenticated" };
111 if (error._tag === "GitHubCliRateLimitError") return { reason: "rate-limited" };
112 if (error._tag === "SourceControlRateLimitPausedError") {
113 return { reason: "rate-limited", retryAt: error.retryAt };
114 }
115 return { reason: "failed" };
116}
117
118/**
119 * `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
120 * applied here by login. An actor already carrying one keeps it.
121 *
122 * A login GitHub did not answer for falls back to the picture every GitHub install serves at
123 * `/<login>.png`. The lookup is one more request per repository and can be refused — a rate
124 * limit, a slow host — and a face that comes and goes between two loads of the same page reads
125 * as a bug in the page rather than as a request that failed quietly.
126 */
127function withAvatar(
128 actor: PullRequestActor | null,
129 avatarsByLogin: ReadonlyMap<string, string>,
130 host: string,
131): PullRequestActor | null {
132 if (actor === null || 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
180/** True where markdown would render nothing: whitespace, or only HTML comments. */
181const rendersEmpty = (body: string): boolean =>
182 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
183
184export const make = Effect.gen(function* () {
185 const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
186
187 const repositoryAccessCache = yield* Cache.makeWith(
188 (key: string) => {
189 const [cwd, repository, host] = JSON.parse(key) as [string, string, string];
190 return cli.getRepositoryAccess({ cwd, repository, host });
191 },
192 {
193 capacity: 128,
194 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
195 },
196 );
197 const getRepositoryAccess = (input: {
198 readonly cwd: string;
199 readonly repository: string;
200 readonly host: string;
201 }) => Cache.get(repositoryAccessCache, JSON.stringify([input.cwd, input.repository, input.host]));
202
203 const fail = (operation: string) => (error: GitHubPullRequestCli.GitHubPullRequestCliError) =>
204 new PullRequestProviderError({
205 provider: "github",
206 operation,
207 ...gitHubProviderFailure(error),
208 detail: error.detail,
209 cause: error,
210 });
211
212 const provider: PullRequestProviderApi = {
213 kind: "github",
214 capabilities: CAPABILITIES,
215
216 getViewer: (input) =>
217 cli.getViewerLogin({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
218
219 listChangeRequests: (input) =>
220 cli
221 .listPullRequests({
222 cwd: input.cwd,
223 repository: input.repository,
224 host: input.host,
225 state: input.state,
226 involvement: input.involvement,
227 viewer: input.viewer,
228 limit: input.limit,
229 query: input.query,
230 cursor: input.cursor,
231 filters: input.filters,
232 })
233 .pipe(
234 Effect.mapError(fail("listChangeRequests")),
235 Effect.flatMap((page) =>
236 cli
237 .listActorAvatars({
238 cwd: input.cwd,
239 repository: input.repository,
240 host: input.host,
241 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
242 })
243 // A listing without faces is still a listing, so a failed lookup falls back to
244 // the initials rather than taking the rows down with it.
245 .pipe(
246 Effect.orElseSucceed(() => new Map<string, string>()),
247 Effect.map((avatarsByLogin) => ({
248 ...page,
249 items: page.items.map((item) => ({
250 ...item,
251 author: withAvatar(item.author, avatarsByLogin, input.host),
252 })),
253 })),
254 ),
255 ),
256 ),
257
258 /**
259 * The same listing for a whole host in one search. The avatar lookup the per-repository read
260 * needs is not here: a search reports an author's picture itself, so a face costs no request
261 * of its own — `withAvatar` still stands behind it for the login GitHub answered nothing for.
262 */
263 listChangeRequestsAcross: (input) =>
264 cli
265 .searchPullRequests({
266 cwd: input.cwd,
267 host: input.host,
268 repositories: input.repositories,
269 state: input.state,
270 involvement: input.involvement,
271 viewer: input.viewer,
272 limit: input.limit,
273 query: input.query,
274 cursor: input.cursor,
275 filters: input.filters,
276 })
277 .pipe(
278 Effect.mapError(fail("listChangeRequestsAcross")),
279 Effect.map((batch) => ({
280 truncated: batch.truncated,
281 items: batch.items.map((item) => ({
282 ...item,
283 author: withAvatar(item.author, new Map<string, string>(), input.host),
284 })),
285 })),
286 ),
287
288 listChangeRequestStats: (input) =>
289 cli
290 .listPullRequestStats({
291 cwd: input.cwd,
292 host: input.host,
293 changeRequests: input.changeRequests,
294 })
295 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
296
297 getChangeRequestSummary: (input) =>
298 cli.getPullRequestSummary(input).pipe(
299 // `gh pr view` names the author without an avatar; the login-shaped URL every user
300 // has stands in, without the second request the listing spends on it.
301 Effect.map((summary) => ({
302 ...summary,
303 ...(summary.author === undefined
304 ? {}
305 : { author: withAvatar(summary.author, new Map(), input.host) }),
306 })),
307 Effect.mapError(fail("getChangeRequestSummary")),
308 ),
309
310 getChangeRequestStack: (input) =>
311 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
312
313 getChangeRequest: (input) =>
314 Effect.all(
315 [
316 cli.getPullRequestDetail(input).pipe(
317 Effect.flatMap((pullRequest) =>
318 Effect.all({
319 // Only an open pull request can be behind anything worth saying so about, and
320 // only one whose head repository is known can be compared at all.
321 comparison:
322 pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
323 ? Effect.succeed(null)
324 : cli
325 .getPullRequestBaseComparison({
326 ...input,
327 headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
328 })
329 .pipe(Effect.orElseSucceed(() => null)),
330 // GitHub omits a fork workflow that has not been approved from the normal check
331 // rollup. Read the action-required runs by head revision so "all passed" cannot
332 // be shown while a whole workflow is still waiting to start.
333 workflowApprovals:
334 pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
335 ? Effect.succeed({
336 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
337 unavailable: false,
338 })
339 : pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
340 ? Effect.succeed({
341 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
342 unavailable: true,
343 })
344 : cli
345 .listWorkflowRunsRequiringApproval({
346 ...input,
347 headSha: pullRequest.headSha,
348 headBranch: pullRequest.headBranch,
349 headRepositoryOwner: pullRequest.headRepositoryOwner,
350 isCrossRepository: true,
351 })
352 .pipe(
353 Effect.matchEffect({
354 onFailure: (error) =>
355 error._tag === "GitHubCliRateLimitError" ||
356 error._tag === "SourceControlRateLimitPausedError"
357 ? Effect.fail(error)
358 : Effect.succeed({
359 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
360 unavailable: true,
361 }),
362 onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
363 }),
364 ),
365 }).pipe(Effect.map((extra) => ({ pullRequest, ...extra }))),
366 ),
367 ),
368 getRepositoryAccess({
369 cwd: input.cwd,
370 repository: input.repository,
371 host: input.host,
372 }),
373 // A small permissions query replaces the deeply paginated review-thread walk on the
374 // core path. Writes ask again immediately before mutating, so this is presentation.
375 cli.getViewerAccess(input),
376 ],
377 { concurrency: 3 },
378 ).pipe(
379 Effect.mapError(fail("getChangeRequest")),
380 Effect.map(([detail, repository, viewerAccess]): ProviderChangeRequestDetail => ({
381 ...detail.pullRequest,
382 checks: withWorkflowApprovals(
383 detail.pullRequest.checks,
384 detail.workflowApprovals.runs,
385 detail.workflowApprovals.unavailable,
386 ),
387 ...(detail.workflowApprovals.unavailable
388 ? {}
389 : { workflowApprovalsRequired: detail.workflowApprovals.runs.length }),
390 reviewers: detail.pullRequest.reviewRequestLogins.map((login) => ({
391 login,
392 name: null,
393 avatarUrl: null,
394 })),
395 mergeCapabilities: repository.mergeCapabilities,
396 viewerPermissions: gitHubViewerPermissions({
397 ...viewerAccess,
398 canUpdateBranch: detail.comparison?.viewerCanUpdate === true,
399 }),
400 baseComparison:
401 detail.comparison === null || detail.comparison.behindBy === null
402 ? "unknown"
403 : detail.comparison.behindBy > 0
404 ? "behind"
405 : "up-to-date",
406 ...(detail.comparison?.behindBy == null ? {} : { behindBy: detail.comparison.behindBy }),
407 })),
408 ),
409
410 getChangeRequestActivity: (input) =>
411 Effect.all(
412 [
413 cli.getPullRequestActivity(input),
414 // Line comments live on review threads, which `gh pr view --json` cannot reach. A
415 // GraphQL hiccup degrades to a truncated conversation rather than blanking activity.
416 cli.listReviewThreadComments(input).pipe(
417 Effect.orElseSucceed(() => ({
418 comments: [],
419 dismissalsByReviewId: new Map<string, string>(),
420 reactions: [],
421 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
422 reviewThreads: [],
423 commentCount: 0,
424 truncated: true,
425 reviewers: [],
426 avatarsByLogin: new Map<string, string>(),
427 commitStats: new Map<
428 string,
429 { readonly additions: number; readonly deletions: number }
430 >(),
431 commits: [],
432 viewer: { canUpdate: true, didAuthor: false },
433 })),
434 ),
435 ],
436 { concurrency: 2 },
437 ).pipe(
438 Effect.mapError(fail("getChangeRequestActivity")),
439 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
440 author: withAvatar(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
441 reviewers: reviewThreads.reviewers,
442 reactions: reviewThreads.reactions,
443 commits: (reviewThreads.commits.length > 0
444 ? reviewThreads.commits
445 : pullRequest.commits
446 ).map((commit) => ({
447 ...commit,
448 ...reviewThreads.commitStats.get(commit.oid),
449 authors: commit.authors?.map(
450 (author) => withAvatar(author, reviewThreads.avatarsByLogin, input.host) ?? author,
451 ),
452 })),
453 comments: [...pullRequest.comments, ...reviewThreads.comments]
454 .map((comment) => ({
455 ...comment,
456 // GitHub keeps the dismissal reason on the timeline event, not on the review,
457 // so a dismissed review with nothing visible of its own reads its words from
458 // there. "Visible" and not "empty": bot reviews often carry only an HTML
459 // marker comment, which markdown renders as nothing.
460 body:
461 comment.kind === "review" &&
462 comment.reviewState?.toUpperCase() === "DISMISSED" &&
463 rendersEmpty(comment.body)
464 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
465 : comment.body,
466 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
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 }))
471 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
472 // `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
473 // are always whole and only the thread walk can stop short of the host.
474 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
475 commentsTruncated: reviewThreads.truncated,
476 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
477 ...thread,
478 comments: thread.comments.map((comment) => ({
479 ...comment,
480 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
481 })),
482 })),
483 })),
484 ),
485
486 getReviewThreadComments: (input) =>
487 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
488
489 getViewerPermissions: (input) =>
490 Effect.all(
491 [
492 cli.getViewerAccess({ ...input, allowReserve: true }),
493 // Whether this viewer may update the branch is only on the comparison, and the
494 // comparison only resolves through the head ref the detail carries. A failure here
495 // withholds that one action rather than the whole answer, the way the detail path
496 // leaves the banner unknown.
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 listReviewerCandidates: (input) =>
526 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
527
528 setReviewerRequest: (input) =>
529 cli
530 .setReviewerRequest({
531 cwd: input.cwd,
532 repository: input.repository,
533 host: input.host,
534 number: input.number,
535 reviewers: input.reviewers,
536 requested: input.requested,
537 })
538 .pipe(Effect.mapError(fail("setReviewerRequest"))),
539
540 listLabelCandidates: (input) =>
541 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
542
543 setLabels: (input) =>
544 cli
545 .setLabels({
546 cwd: input.cwd,
547 repository: input.repository,
548 host: input.host,
549 number: input.number,
550 labels: input.labels,
551 applied: input.applied,
552 })
553 .pipe(Effect.mapError(fail("setLabels"))),
554
555 runAction: (input) =>
556 cli
557 .runPullRequestAction({
558 cwd: input.cwd,
559 repository: input.repository,
560 host: input.host,
561 number: input.number,
562 action: input.action,
563 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
564 ...(input.expectedStackHeads === undefined
565 ? {}
566 : { expectedStackHeads: input.expectedStackHeads }),
567 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
568 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
569 })
570 .pipe(Effect.mapError(fail("runAction"))),
571
572 updateChangeRequest: (input) =>
573 cli
574 .updatePullRequest({
575 cwd: input.cwd,
576 repository: input.repository,
577 host: input.host,
578 number: input.number,
579 ...(input.title === undefined ? {} : { title: input.title }),
580 ...(input.body === undefined ? {} : { body: input.body }),
581 })
582 .pipe(Effect.mapError(fail("updateChangeRequest"))),
583
584 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
585
586 updateComment: (input) =>
587 cli
588 .updateComment({
589 cwd: input.cwd,
590 repository: input.repository,
591 host: input.host,
592 number: input.number,
593 commentId: input.commentId,
594 kind: input.kind,
595 body: input.body,
596 })
597 .pipe(Effect.mapError(fail("updateComment"))),
598
599 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
600
601 replyToThread: (input) =>
602 cli
603 .replyToReviewThread({
604 cwd: input.cwd,
605 repository: input.repository,
606 host: input.host,
607 threadId: input.threadId,
608 body: input.body,
609 })
610 .pipe(Effect.mapError(fail("replyToThread"))),
611
612 setReaction: (input) =>
613 cli
614 .setReaction({
615 cwd: input.cwd,
616 repository: input.repository,
617 host: input.host,
618 number: input.number,
619 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
620 content: input.content,
621 reacted: input.reacted,
622 })
623 .pipe(Effect.mapError(fail("setReaction"))),
624
625 setThreadResolution: (input) =>
626 cli
627 .setReviewThreadResolution({
628 cwd: input.cwd,
629 repository: input.repository,
630 host: input.host,
631 threadId: input.threadId,
632 resolved: input.resolved,
633 })
634 .pipe(Effect.mapError(fail("setThreadResolution"))),
635 };
636
637 return provider;
638});