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