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