Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BitbucketPullRequestProvider.ts

385 lines14.0 KB

1import * as Effect from "effect/Effect";
2import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
3​
4import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
5import {
6 PullRequestProviderError,
7 type PullRequestProviderFailure,
8 type ProviderChangeRequest,
9 type ProviderChangeRequestActivity,
10 type ProviderChangeRequestDetail,
11 type PullRequestProviderApi,
12} from "./PullRequestProvider.ts";
13import type { BitbucketPullRequest } from "./bitbucketPullRequestJson.ts";
14​
15const CAPABILITIES: PullRequestCapabilities = {
16 diff: true,
17 comment: true,
18 // Bitbucket has no endpoint that reopens a declined pull request, and nothing documented that
19 // moves one in or out of draft, so neither is offered rather than failing when pressed.
20 actions: ["merge", "close"],
21 mergeMethods: ["merge", "squash", "rebase"],
22 search: true,
23 // Bitbucket Cloud's API exposes no reaction on a pull request or on a comment, so none is
24 // read and none is offered.
25 reactions: false,
26 review: {
27 inlineComment: true,
28 reply: true,
29 resolve: true,
30 verdicts: ["comment", "approve", "request-changes"],
31 },
32 reviewers: { request: true, listCandidates: true },
33 edit: { changeRequest: true, comment: true },
34 // Bitbucket Cloud states nothing about what a reviewer has already read: no endpoint carries a
35 // viewed file, and the per-pull-request properties it does offer are one value shared by
36 // everyone rather than one per reader. So the marks are kept here, and the client says whose
37 // they are rather than implying bitbucket.org will show them.
38 viewedFiles: "environment",
39};
40​
41/**
42 * What the configured account may do here, from the one thing Bitbucket states per viewer: the
43 * repository permission. Merging needs `write` or `admin`, so that is what narrows.
44 *
45 * Declining stays offered whatever the permission. Bitbucket lets the author of a pull request
46 * decline their own with no more than read access, and the permission response says nothing about
47 * who opened this one — so withholding the control from the one person entitled to it is the
48 * worse of the two mistakes. Commenting and reviewing are not narrowed either: read access is
49 * enough to say something, to approve and to ask for changes.
50 *
51 * Asking for a review is left open for the same reason: Bitbucket takes a reviewer set from the
52 * author of a pull request as well as from whoever can write, and says nothing here about which
53 * of the two this account is.
54 */
55export function bitbucketViewerPermissions(input: {
56 readonly canWrite: boolean;
57}): PullRequestViewerPermissions {
58 return {
59 actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.canWrite),
60 comment: true,
61 resolve: true,
62 verdicts: CAPABILITIES.review.verdicts,
63 requestReviewers: true,
64 };
66​
67/** The failures that mean the credentials are the problem, rather than one request. */
68export function bitbucketProviderFailure(
69 error: BitbucketPullRequestApi.BitbucketPullRequestApiError,
70): PullRequestProviderFailure {
71 // Bitbucket is read over HTTP with credentials from the environment, so there is no tool to be
72 // missing: unusable always means the credentials are absent or refused.
73 if (error._tag === "BitbucketResponseError" && error.status === 401) {
74 return { reason: "unauthenticated" };
75 }
76 if (
77 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
78 error.status === 429
79 ) {
80 return {
81 reason: "rate-limited",
82 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
83 };
84 }
85 if (
86 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
87 error.status === 404
88 ) {
89 return { reason: "not-found" };
90 }
91 return { reason: "failed" };
93​
94function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeRequest {
95 return {
96 number: pullRequest.number,
97 title: pullRequest.title,
98 url: pullRequest.url,
99 author: pullRequest.author,
100 headBranch: pullRequest.headBranch,
101 ...(pullRequest.headRepositoryNameWithOwner
102 ? { headRepositoryNameWithOwner: pullRequest.headRepositoryNameWithOwner }
103 : {}),
104 baseBranch: pullRequest.baseBranch,
105 state: pullRequest.state,
106 isDraft: pullRequest.isDraft,
107 mergeability: pullRequest.mergeability,
108 // Line counts are a separate read, which only the detail is worth spending on.
109 additions: 0,
110 deletions: 0,
111 createdAt: pullRequest.createdAt,
112 updatedAt: pullRequest.updatedAt,
113 reviewRequestLogins: pullRequest.reviewRequestLogins,
114 // Bitbucket has no labels on a pull request.
115 labels: [],
116 };
118​
119export const make = Effect.gen(function* () {
120 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
121​
122 const fail =
123 (operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
124 new PullRequestProviderError({
125 provider: "bitbucket",
126 operation,
127 ...bitbucketProviderFailure(error),
128 // Every Bitbucket failure states its own fact; this names the operation around it, so
129 // the two do not stack into "failed in x: failed in y: ...".
130 detail: error.detail,
131 cause: error,
132 });
133​
134 const recoverRead = <A>(
135 read: Effect.Effect<A, BitbucketPullRequestApi.BitbucketPullRequestApiError>,
136 fallback: A,
137 ) => {
138 const recover = () => Effect.succeed(fallback);
139 return Effect.catchTags(read, {
140 BitbucketResponseError: (error) => (error.status === 429 ? Effect.fail(error) : recover()),
141 BitbucketUntrustedUrlError: recover,
142 BitbucketRepositoryLocatorError: recover,
143 BitbucketRequestError: recover,
144 BitbucketResponseBodyReadError: (error) =>
145 error.status === 429 ? Effect.fail(error) : recover(),
146 BitbucketResponseDecodeError: recover,
147 BitbucketRepositoryVcsResolveError: recover,
148 BitbucketRepositoryRemotesListError: recover,
149 BitbucketRepositoryRemoteNotFoundError: recover,
150 BitbucketPullRequestBodyReadError: recover,
151 BitbucketCheckoutError: recover,
152 BitbucketPullRequestReadError: recover,
153 BitbucketViewerUnavailableError: recover,
154 BitbucketRepositoryUnsupportedError: recover,
155 BitbucketDiffCommitError: recover,
156 });
157 };
158​
159 const provider: PullRequestProviderApi = {
160 kind: "bitbucket",
161 capabilities: CAPABILITIES,
162​
163 // Bitbucket credentials come from the server's environment rather than a checkout, so the
164 // account is the same whichever workspace asks.
165 getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),
166​
167 listChangeRequests: (input) =>
168 api
169 .listPullRequests({
170 repository: input.repository,
171 state: input.state,
172 limit: input.limit,
173 query: input.query,
174 cursor: input.cursor,
175 })
176 .pipe(
177 Effect.mapError(fail("listChangeRequests")),
178 Effect.map((batch) => ({
179 items: batch.items.map(toChangeRequest),
180 truncated: batch.truncated,
181 // Bitbucket is asked for `-updated_on` whether or not it is being carried on from,
182 // so every page it answers is one a cursor can continue.
183 continues: true,
184 })),
185 ),
186​
187 getChangeRequestChecks: (input) =>
188 Effect.all([api.getPullRequest(input), api.listChecks(input)], { concurrency: 2 }).pipe(
189 Effect.map(([pullRequest, checks]) => ({ state: pullRequest.state, checks })),
190 Effect.mapError(fail("getChangeRequestChecks")),
191 ),
192​
193 getChangeRequest: (input) => {
194 const target = { repository: input.repository, number: input.number };
195 return Effect.all(
196 [
197 api.getPullRequest(target),
198 api.getDiffStat(target),
199 recoverRead(api.getMergeability(target), "unknown" as const),
200 recoverRead(api.listChecks(target), []),
201 // A permission that could not be read is an unknown one, which is granted: a hidden
202 // Merge leaves someone entitled to it with no way through, and one Bitbucket refuses
203 // at least says why.
204 recoverRead(api.getRepositoryPermission(target), true),
205 ],
206 { concurrency: 5 },
207 ).pipe(
208 Effect.mapError(fail("getChangeRequest")),
209 Effect.map(
210 ([
211 pullRequest,
212 diffStat,
213 mergeability,
214 checks,
215 canWrite,
216 ]): ProviderChangeRequestDetail => ({
217 ...toChangeRequest(pullRequest),
218 mergeability,
219 additions: diffStat.additions,
220 deletions: diffStat.deletions,
221 changedFiles: diffStat.changedFiles,
222 body: pullRequest.body,
223 mergedAt: null,
224 closedAt: null,
225 reviewers: pullRequest.reviewers,
226 checks,
227 // Bitbucket publishes no per-repository list of allowed strategies, so the ones it
228 // supports are all offered and a strategy the repository forbids fails on merge.
229 mergeCapabilities: { merge: true, squash: true, rebase: true },
230 viewerPermissions: bitbucketViewerPermissions({ canWrite }),
231 }),
232 ),
233 );
234 },
235​
236 getChangeRequestActivity: (input) => {
237 const target = { repository: input.repository, number: input.number };
238 return Effect.all(
239 [
240 // Reviews ride on the pull request itself, so this inexpensive core read is repeated
241 // here rather than making the core response wait for the conversation endpoints.
242 api.getPullRequest(target),
243 recoverRead(api.listComments(target), { comments: [], threads: [], truncated: true }),
244 recoverRead(api.listCommits(target), []),
245 ],
246 { concurrency: 3 },
247 ).pipe(
248 Effect.mapError(fail("getChangeRequestActivity")),
249 Effect.map(([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
250 comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
251 left.createdAt.localeCompare(right.createdAt),
252 ),
253 commentCount: comments.comments.length + pullRequest.reviews.length,
254 commentsTruncated: comments.truncated,
255 reviewThreads: comments.threads,
256 commits,
257 })),
258 );
259 },
260​
261 getViewerPermissions: (input) =>
262 api.getRepositoryPermission({ repository: input.repository }).pipe(
263 Effect.mapError(fail("getViewerPermissions")),
264 Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
265 ),
266​
267 // `/diff` answers with the whole patch and pages nothing, so the first slice is the last.
268 getDiff: (input) =>
269 api
270 .getPullRequestDiff({
271 repository: input.repository,
272 number: input.number,
273 ...(input.commit === undefined ? {} : { commit: input.commit }),
274 })
275 .pipe(
276 Effect.mapError(fail("getDiff")),
277 Effect.map((diff) => ({ ...diff, nextCursor: null })),
278 ),
279​
280 getFileRevisions: (input) =>
281 api
282 .getFileRevisions({
283 repository: input.repository,
284 number: input.number,
285 paths: input.paths,
286 })
287 .pipe(Effect.mapError(fail("getFileRevisions"))),
288​
289 // Users only: Bitbucket requests a review of an account, and has no group that stands in for
290 // one on a pull request.
291 listReviewerCandidates: (input) =>
292 api
293 .listReviewerCandidates({ repository: input.repository, number: input.number })
294 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
295​
296 setReviewerRequest: (input) =>
297 api
298 .setReviewerRequest({
299 repository: input.repository,
300 number: input.number,
301 reviewers: input.reviewers,
302 requested: input.requested,
303 })
304 .pipe(Effect.mapError(fail("setReviewerRequest"))),
305​
306 runAction: (input) =>
307 api
308 .runAction({
309 repository: input.repository,
310 number: input.number,
311 action: input.action,
312 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
313 })
314 .pipe(Effect.mapError(fail("runAction"))),
315​
316 updateChangeRequest: (input) =>
317 api
318 .updateChangeRequest({
319 repository: input.repository,
320 number: input.number,
321 title: input.title,
322 body: input.body,
323 })
324 .pipe(Effect.mapError(fail("updateChangeRequest"))),
325​
326 comment: (input) =>
327 api
328 .comment({ repository: input.repository, number: input.number, body: input.body })
329 .pipe(Effect.mapError(fail("comment"))),
330​
331 updateComment: (input) =>
332 api
333 .updateComment({
334 repository: input.repository,
335 number: input.number,
336 commentId: input.commentId,
337 body: input.body,
338 })
339 .pipe(Effect.mapError(fail("updateComment"))),
340​
341 submitReview: (input) =>
342 api
343 .submitReview({
344 repository: input.repository,
345 number: input.number,
346 verdict: input.verdict,
347 body: input.body,
348 comments: input.comments,
349 })
350 .pipe(Effect.mapError(fail("submitReview"))),
351​
352 replyToThread: (input) =>
353 api
354 .replyToComment({
355 repository: input.repository,
356 number: input.number,
357 commentId: input.threadId,
358 body: input.body,
359 })
360 .pipe(Effect.mapError(fail("replyToThread"))),
361​
362 // Never called: `capabilities.reactions` is false, and the service refuses without it.
363 setReaction: () =>
364 Effect.fail(
365 new PullRequestProviderError({
366 provider: "bitbucket",
367 operation: "setReaction",
368 reason: "failed",
369 detail: "Bitbucket does not support reactions.",
370 }),
371 ),
372​
373 setThreadResolution: (input) =>
374 api
375 .setCommentResolution({
376 repository: input.repository,
377 number: input.number,
378 commentId: input.threadId,
379 resolved: input.resolved,
380 })
381 .pipe(Effect.mapError(fail("setThreadResolution"))),
382 };
383​
384 return provider;
385});