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