Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BitbucketPullRequestProvider.ts

373 lines13.5 KB

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