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};
35
36/**
37 * What the configured account may do here, from the one thing Bitbucket states per viewer: the
38 * repository permission. Merging needs `write` or `admin`, so that is what narrows.
39 *
40 * Declining stays offered whatever the permission. Bitbucket lets the author of a pull request
41 * decline their own with no more than read access, and the permission response says nothing about
42 * who opened this one — so withholding the control from the one person entitled to it is the
43 * worse of the two mistakes. Commenting and reviewing are not narrowed either: read access is
44 * enough to say something, to approve and to ask for changes.
45 *
46 * Asking for a review is left open for the same reason: Bitbucket takes a reviewer set from the
47 * author of a pull request as well as from whoever can write, and says nothing here about which
48 * of the two this account is.
49 */
50export function bitbucketViewerPermissions(input: {
51 readonly canWrite: boolean;
52}): PullRequestViewerPermissions {
53 return {
54 actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.canWrite),
55 comment: true,
56 resolve: true,
57 verdicts: CAPABILITIES.review.verdicts,
58 requestReviewers: true,
59 };
60}
61
62/** The failures that mean the credentials are the problem, rather than one request. */
63export function bitbucketProviderFailure(
64 error: BitbucketPullRequestApi.BitbucketPullRequestApiError,
65): PullRequestProviderFailure {
66 // Bitbucket is read over HTTP with credentials from the environment, so there is no tool to be
67 // missing: unusable always means the credentials are absent or refused.
68 if (error._tag === "BitbucketResponseError" && error.status === 401) {
69 return { reason: "unauthenticated" };
70 }
71 if (error._tag === "BitbucketResponseError" && error.status === 429) {
72 return {
73 reason: "rate-limited",
74 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
75 };
76 }
77 return { reason: "failed" };
78}
79
80function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeRequest {
81 return {
82 number: pullRequest.number,
83 title: pullRequest.title,
84 url: pullRequest.url,
85 author: pullRequest.author,
86 headBranch: pullRequest.headBranch,
87 baseBranch: pullRequest.baseBranch,
88 state: pullRequest.state,
89 isDraft: pullRequest.isDraft,
90 mergeability: pullRequest.mergeability,
91 // Line counts are a separate read, which only the detail is worth spending on.
92 additions: 0,
93 deletions: 0,
94 createdAt: pullRequest.createdAt,
95 updatedAt: pullRequest.updatedAt,
96 reviewRequestLogins: pullRequest.reviewRequestLogins,
97 // Bitbucket has no labels on a pull request.
98 labels: [],
99 };
100}
101
102export const make = Effect.gen(function* () {
103 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
104
105 const fail =
106 (operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
107 new PullRequestProviderError({
108 provider: "bitbucket",
109 operation,
110 ...bitbucketProviderFailure(error),
111 // Every Bitbucket failure states its own fact; this names the operation around it, so
112 // the two do not stack into "failed in x: failed in y: ...".
113 detail: error.detail,
114 cause: error,
115 });
116
117 const provider: PullRequestProviderApi = {
118 kind: "bitbucket",
119 capabilities: CAPABILITIES,
120
121 // Bitbucket credentials come from the server's environment rather than a checkout, so the
122 // account is the same whichever workspace asks.
123 getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),
124
125 listChangeRequests: (input) =>
126 api
127 .listPullRequests({
128 repository: input.repository,
129 state: input.state,
130 limit: input.limit,
131 query: input.query,
132 cursor: input.cursor,
133 })
134 .pipe(
135 Effect.mapError(fail("listChangeRequests")),
136 Effect.map((batch) => ({
137 items: batch.items.map(toChangeRequest),
138 truncated: batch.truncated,
139 // Bitbucket is asked for `-updated_on` whether or not it is being carried on from,
140 // so every page it answers is one a cursor can continue.
141 continues: true,
142 })),
143 ),
144
145 getChangeRequest: (input) => {
146 const target = { repository: input.repository, number: input.number };
147 return Effect.all(
148 [
149 api.getPullRequest(target),
150 api.getDiffStat(target),
151 api.getMergeability(target).pipe(Effect.orElseSucceed(() => "unknown" as const)),
152 api.listChecks(target).pipe(Effect.orElseSucceed(() => [])),
153 // A permission that could not be read is an unknown one, which is granted: a hidden
154 // Merge leaves someone entitled to it with no way through, and one Bitbucket refuses
155 // at least says why.
156 api.getRepositoryPermission(target).pipe(Effect.orElseSucceed(() => true)),
157 ],
158 { concurrency: 5 },
159 ).pipe(
160 Effect.mapError(fail("getChangeRequest")),
161 Effect.map(
162 ([
163 pullRequest,
164 diffStat,
165 mergeability,
166 checks,
167 canWrite,
168 ]): ProviderChangeRequestDetail => ({
169 ...toChangeRequest(pullRequest),
170 mergeability,
171 additions: diffStat.additions,
172 deletions: diffStat.deletions,
173 changedFiles: diffStat.changedFiles,
174 body: pullRequest.body,
175 mergedAt: pullRequest.state === "merged" ? pullRequest.updatedAt : null,
176 closedAt: pullRequest.state === "closed" ? pullRequest.updatedAt : null,
177 reviewers: pullRequest.reviewers,
178 checks,
179 // Bitbucket publishes no per-repository list of allowed strategies, so the ones it
180 // supports are all offered and a strategy the repository forbids fails on merge.
181 mergeCapabilities: { merge: true, squash: true, rebase: true },
182 viewerPermissions: bitbucketViewerPermissions({ canWrite }),
183 }),
184 ),
185 );
186 },
187
188 getChangeRequestActivity: (input) => {
189 const target = { repository: input.repository, number: input.number };
190 return Effect.all(
191 [
192 // Reviews ride on the pull request itself, so this inexpensive core read is repeated
193 // here rather than making the core response wait for the conversation endpoints.
194 api.getPullRequest(target),
195 api
196 .listComments(target)
197 .pipe(Effect.orElseSucceed(() => ({ comments: [], threads: [], truncated: true }))),
198 api.listCommits(target).pipe(Effect.orElseSucceed(() => [])),
199 ],
200 { concurrency: 3 },
201 ).pipe(
202 Effect.mapError(fail("getChangeRequestActivity")),
203 Effect.map(
204 ([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
205 comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
206 left.createdAt.localeCompare(right.createdAt),
207 ),
208 commentCount: comments.comments.length + pullRequest.reviews.length,
209 commentsTruncated: comments.truncated,
210 reviewThreads: comments.threads,
211 commits,
212 }),
213 ),
214 );
215 },
216
217 getViewerPermissions: (input) =>
218 api.getRepositoryPermission({ repository: input.repository }).pipe(
219 Effect.mapError(fail("getViewerPermissions")),
220 Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
221 ),
222
223 // `/diff` answers with the whole patch and pages nothing, so the first slice is the last.
224 getDiff: (input) =>
225 api
226 .getPullRequestDiff({
227 repository: input.repository,
228 number: input.number,
229 ...(input.commit === undefined ? {} : { commit: input.commit }),
230 })
231 .pipe(
232 Effect.mapError(fail("getDiff")),
233 Effect.map((diff) => ({ ...diff, nextCursor: null })),
234 ),
235
236 // Users only: Bitbucket requests a review of an account, and has no group that stands in for
237 // one on a pull request.
238 listReviewerCandidates: (input) =>
239 api
240 .listReviewerCandidates({ repository: input.repository, number: input.number })
241 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
242
243 setReviewerRequest: (input) =>
244 api
245 .setReviewerRequest({
246 repository: input.repository,
247 number: input.number,
248 reviewers: input.reviewers,
249 requested: input.requested,
250 })
251 .pipe(Effect.mapError(fail("setReviewerRequest"))),
252
253 runAction: (input) =>
254 api
255 .runAction({
256 repository: input.repository,
257 number: input.number,
258 action: input.action,
259 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
260 })
261 .pipe(Effect.mapError(fail("runAction"))),
262
263 updateChangeRequest: (input) =>
264 api
265 .updateChangeRequest({
266 repository: input.repository,
267 number: input.number,
268 title: input.title,
269 body: input.body,
270 })
271 .pipe(Effect.mapError(fail("updateChangeRequest"))),
272
273 comment: (input) =>
274 api
275 .comment({ repository: input.repository, number: input.number, body: input.body })
276 .pipe(Effect.mapError(fail("comment"))),
277
278 updateComment: (input) =>
279 api
280 .updateComment({
281 repository: input.repository,
282 number: input.number,
283 commentId: input.commentId,
284 body: input.body,
285 })
286 .pipe(Effect.mapError(fail("updateComment"))),
287
288 submitReview: (input) =>
289 api
290 .submitReview({
291 repository: input.repository,
292 number: input.number,
293 verdict: input.verdict,
294 body: input.body,
295 comments: input.comments,
296 })
297 .pipe(Effect.mapError(fail("submitReview"))),
298
299 replyToThread: (input) =>
300 api
301 .replyToComment({
302 repository: input.repository,
303 number: input.number,
304 commentId: input.threadId,
305 body: input.body,
306 })
307 .pipe(Effect.mapError(fail("replyToThread"))),
308
309 // Never called: `capabilities.reactions` is false, and the service refuses without it.
310 setReaction: () =>
311 Effect.fail(
312 new PullRequestProviderError({
313 provider: "bitbucket",
314 operation: "setReaction",
315 reason: "failed",
316 detail: "Bitbucket does not support reactions.",
317 }),
318 ),
319
320 setThreadResolution: (input) =>
321 api
322 .setCommentResolution({
323 repository: input.repository,
324 number: input.number,
325 commentId: input.threadId,
326 resolved: input.resolved,
327 })
328 .pipe(Effect.mapError(fail("setThreadResolution"))),
329 };
330
331 return provider;
332});