Open History to see the last commit
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 };
65}
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 return { reason: "failed" };
86}
87
88function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeRequest {
89 return {
90 number: pullRequest.number,
91 title: pullRequest.title,
92 url: pullRequest.url,
93 author: pullRequest.author,
94 headBranch: pullRequest.headBranch,
95 ...(pullRequest.headRepositoryNameWithOwner
96 ? { headRepositoryNameWithOwner: pullRequest.headRepositoryNameWithOwner }
97 : {}),
98 baseBranch: pullRequest.baseBranch,
99 state: pullRequest.state,
100 isDraft: pullRequest.isDraft,
101 mergeability: pullRequest.mergeability,
102 // Line counts are a separate read, which only the detail is worth spending on.
103 additions: 0,
104 deletions: 0,
105 createdAt: pullRequest.createdAt,
106 updatedAt: pullRequest.updatedAt,
107 reviewRequestLogins: pullRequest.reviewRequestLogins,
108 // Bitbucket has no labels on a pull request.
109 labels: [],
110 };
111}
112
113export const make = Effect.gen(function* () {
114 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
115
116 const fail =
117 (operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
118 new PullRequestProviderError({
119 provider: "bitbucket",
120 operation,
121 ...bitbucketProviderFailure(error),
122 // Every Bitbucket failure states its own fact; this names the operation around it, so
123 // the two do not stack into "failed in x: failed in y: ...".
124 detail: error.detail,
125 cause: error,
126 });
127
128 const recoverRead = <A>(
129 read: Effect.Effect<A, BitbucketPullRequestApi.BitbucketPullRequestApiError>,
130 fallback: A,
131 ) => {
132 const recover = () => Effect.succeed(fallback);
133 return Effect.catchTags(read, {
134 BitbucketResponseError: (error) => (error.status === 429 ? Effect.fail(error) : recover()),
135 BitbucketUntrustedUrlError: recover,
136 BitbucketRepositoryLocatorError: recover,
137 BitbucketRequestError: recover,
138 BitbucketResponseBodyReadError: (error) =>
139 error.status === 429 ? Effect.fail(error) : recover(),
140 BitbucketResponseDecodeError: recover,
141 BitbucketRepositoryVcsResolveError: recover,
142 BitbucketRepositoryRemotesListError: recover,
143 BitbucketRepositoryRemoteNotFoundError: recover,
144 BitbucketPullRequestBodyReadError: recover,
145 BitbucketCheckoutError: recover,
146 BitbucketPullRequestReadError: recover,
147 BitbucketViewerUnavailableError: recover,
148 BitbucketRepositoryUnsupportedError: recover,
149 BitbucketDiffCommitError: recover,
150 });
151 };
152
153 const provider: PullRequestProviderApi = {
154 kind: "bitbucket",
155 capabilities: CAPABILITIES,
156
157 // Bitbucket credentials come from the server's environment rather than a checkout, so the
158 // account is the same whichever workspace asks.
159 getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),
160
161 listChangeRequests: (input) =>
162 api
163 .listPullRequests({
164 repository: input.repository,
165 state: input.state,
166 limit: input.limit,
167 query: input.query,
168 cursor: input.cursor,
169 })
170 .pipe(
171 Effect.mapError(fail("listChangeRequests")),
172 Effect.map((batch) => ({
173 items: batch.items.map(toChangeRequest),
174 truncated: batch.truncated,
175 // Bitbucket is asked for `-updated_on` whether or not it is being carried on from,
176 // so every page it answers is one a cursor can continue.
177 continues: true,
178 })),
179 ),
180
181 getChangeRequestChecks: (input) =>
182 Effect.all([api.getPullRequest(input), api.listChecks(input)], { concurrency: 2 }).pipe(
183 Effect.map(([pullRequest, checks]) => ({ state: pullRequest.state, checks })),
184 Effect.mapError(fail("getChangeRequestChecks")),
185 ),
186
187 getChangeRequest: (input) => {
188 const target = { repository: input.repository, number: input.number };
189 return Effect.all(
190 [
191 api.getPullRequest(target),
192 api.getDiffStat(target),
193 recoverRead(api.getMergeability(target), "unknown" as const),
194 recoverRead(api.listChecks(target), []),
195 // A permission that could not be read is an unknown one, which is granted: a hidden
196 // Merge leaves someone entitled to it with no way through, and one Bitbucket refuses
197 // at least says why.
198 recoverRead(api.getRepositoryPermission(target), true),
199 ],
200 { concurrency: 5 },
201 ).pipe(
202 Effect.mapError(fail("getChangeRequest")),
203 Effect.map(
204 ([
205 pullRequest,
206 diffStat,
207 mergeability,
208 checks,
209 canWrite,
210 ]): ProviderChangeRequestDetail => ({
211 ...toChangeRequest(pullRequest),
212 mergeability,
213 additions: diffStat.additions,
214 deletions: diffStat.deletions,
215 changedFiles: diffStat.changedFiles,
216 body: pullRequest.body,
217 mergedAt: null,
218 closedAt: null,
219 reviewers: pullRequest.reviewers,
220 checks,
221 // Bitbucket publishes no per-repository list of allowed strategies, so the ones it
222 // supports are all offered and a strategy the repository forbids fails on merge.
223 mergeCapabilities: { merge: true, squash: true, rebase: true },
224 viewerPermissions: bitbucketViewerPermissions({ canWrite }),
225 }),
226 ),
227 );
228 },
229
230 getChangeRequestActivity: (input) => {
231 const target = { repository: input.repository, number: input.number };
232 return Effect.all(
233 [
234 // Reviews ride on the pull request itself, so this inexpensive core read is repeated
235 // here rather than making the core response wait for the conversation endpoints.
236 api.getPullRequest(target),
237 recoverRead(api.listComments(target), { comments: [], threads: [], truncated: true }),
238 recoverRead(api.listCommits(target), []),
239 ],
240 { concurrency: 3 },
241 ).pipe(
242 Effect.mapError(fail("getChangeRequestActivity")),
243 Effect.map(([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
244 comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
245 left.createdAt.localeCompare(right.createdAt),
246 ),
247 commentCount: comments.comments.length + pullRequest.reviews.length,
248 commentsTruncated: comments.truncated,
249 reviewThreads: comments.threads,
250 commits,
251 })),
252 );
253 },
254
255 getViewerPermissions: (input) =>
256 api.getRepositoryPermission({ repository: input.repository }).pipe(
257 Effect.mapError(fail("getViewerPermissions")),
258 Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
259 ),
260
261 // `/diff` answers with the whole patch and pages nothing, so the first slice is the last.
262 getDiff: (input) =>
263 api
264 .getPullRequestDiff({
265 repository: input.repository,
266 number: input.number,
267 ...(input.commit === undefined ? {} : { commit: input.commit }),
268 })
269 .pipe(
270 Effect.mapError(fail("getDiff")),
271 Effect.map((diff) => ({ ...diff, nextCursor: null })),
272 ),
273
274 getFileRevisions: (input) =>
275 api
276 .getFileRevisions({
277 repository: input.repository,
278 number: input.number,
279 paths: input.paths,
280 })
281 .pipe(Effect.mapError(fail("getFileRevisions"))),
282
283 // Users only: Bitbucket requests a review of an account, and has no group that stands in for
284 // one on a pull request.
285 listReviewerCandidates: (input) =>
286 api
287 .listReviewerCandidates({ repository: input.repository, number: input.number })
288 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
289
290 setReviewerRequest: (input) =>
291 api
292 .setReviewerRequest({
293 repository: input.repository,
294 number: input.number,
295 reviewers: input.reviewers,
296 requested: input.requested,
297 })
298 .pipe(Effect.mapError(fail("setReviewerRequest"))),
299
300 runAction: (input) =>
301 api
302 .runAction({
303 repository: input.repository,
304 number: input.number,
305 action: input.action,
306 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
307 })
308 .pipe(Effect.mapError(fail("runAction"))),
309
310 updateChangeRequest: (input) =>
311 api
312 .updateChangeRequest({
313 repository: input.repository,
314 number: input.number,
315 title: input.title,
316 body: input.body,
317 })
318 .pipe(Effect.mapError(fail("updateChangeRequest"))),
319
320 comment: (input) =>
321 api
322 .comment({ repository: input.repository, number: input.number, body: input.body })
323 .pipe(Effect.mapError(fail("comment"))),
324
325 updateComment: (input) =>
326 api
327 .updateComment({
328 repository: input.repository,
329 number: input.number,
330 commentId: input.commentId,
331 body: input.body,
332 })
333 .pipe(Effect.mapError(fail("updateComment"))),
334
335 submitReview: (input) =>
336 api
337 .submitReview({
338 repository: input.repository,
339 number: input.number,
340 verdict: input.verdict,
341 body: input.body,
342 comments: input.comments,
343 })
344 .pipe(Effect.mapError(fail("submitReview"))),
345
346 replyToThread: (input) =>
347 api
348 .replyToComment({
349 repository: input.repository,
350 number: input.number,
351 commentId: input.threadId,
352 body: input.body,
353 })
354 .pipe(Effect.mapError(fail("replyToThread"))),
355
356 // Never called: `capabilities.reactions` is false, and the service refuses without it.
357 setReaction: () =>
358 Effect.fail(
359 new PullRequestProviderError({
360 provider: "bitbucket",
361 operation: "setReaction",
362 reason: "failed",
363 detail: "Bitbucket does not support reactions.",
364 }),
365 ),
366
367 setThreadResolution: (input) =>
368 api
369 .setCommentResolution({
370 repository: input.repository,
371 number: input.number,
372 commentId: input.threadId,
373 resolved: input.resolved,
374 })
375 .pipe(Effect.mapError(fail("setThreadResolution"))),
376 };
377
378 return provider;
379});