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