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