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