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