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