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

BitbucketPullRequestProvider.ts

376 lines13.1 KB

1import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
4​
5import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
6import {
7 PullRequestProviderError,
8 type PullRequestProviderFailure,
9 type ProviderChangeRequest,
10 type ProviderChangeRequestActivity,
11 type ProviderChangeRequestDetail,
12 type PullRequestProviderApi,
13} from "@t3tools/source-control-core/server/PullRequestProvider";
14import type { BitbucketPullRequest } from "./bitbucketPullRequestJson.ts";
15import { definition } from "../shared/definition.ts";
16​
17const CAPABILITIES: PullRequestCapabilities = {
18 diff: true,
19 comment: true,
20 actions: [...definition.changeRequestActions],
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​
41const UNAVAILABLE_REQUIREMENT = {
42 missing: "Bitbucket needs API credentials on the server. Add them in Settings → Source Control.",
43 unauthenticated:
44 "Bitbucket rejected the configured credentials. Check them in Settings → Source Control.",
45};
46​
47/**
48 * Bitbucket lets the author of a pull request decline their own with no more than read access,
49 * and the permission response says nothing about who opened this one — so withholding the
50 * control from the one person entitled to it is the worse of the two mistakes.
51 */
52export function bitbucketViewerPermissions(input: {
53 readonly canWrite: boolean;
54}): PullRequestViewerPermissions {
55 return {
56 actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.canWrite),
57 comment: true,
58 resolve: true,
59 verdicts: CAPABILITIES.review.verdicts,
60 requestReviewers: true,
61 };
63​
64export function bitbucketProviderFailure(
65 error: BitbucketPullRequestApi.BitbucketPullRequestApiError,
66): PullRequestProviderFailure {
67 if (error._tag === "BitbucketResponseError" && error.status === 401) {
68 return { reason: "unauthenticated" };
69 }
70 if (error._tag === "SourceControlRateLimitPausedError") {
71 return { reason: "rate-limited", retryAt: error.retryAt };
72 }
73 if (
74 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
75 error.status === 429
76 ) {
77 return {
78 reason: "rate-limited",
79 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
80 };
81 }
82 if (
83 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
84 error.status === 404
85 ) {
86 return { reason: "not-found" };
87 }
88 return { reason: "failed" };
90​
91function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeRequest {
92 return {
93 number: pullRequest.number,
94 title: pullRequest.title,
95 url: pullRequest.url,
96 author: pullRequest.author,
97 headBranch: pullRequest.headBranch,
98 ...(pullRequest.headSha ? { headSha: pullRequest.headSha } : {}),
99 ...(pullRequest.headRepositoryNameWithOwner
100 ? { headRepositoryNameWithOwner: pullRequest.headRepositoryNameWithOwner }
101 : {}),
102 baseBranch: pullRequest.baseBranch,
103 state: pullRequest.state,
104 isDraft: pullRequest.isDraft,
105 mergeability: pullRequest.mergeability,
106 additions: 0,
107 deletions: 0,
108 createdAt: pullRequest.createdAt,
109 updatedAt: pullRequest.updatedAt,
110 reviewRequestLogins: pullRequest.reviewRequestLogins,
111 labels: [],
112 };
114​
115export const make = Effect.gen(function* () {
116 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
117​
118 const fail =
119 (operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
120 new PullRequestProviderError({
121 provider: SourceControlProviderKind.make("bitbucket"),
122 operation,
123 ...bitbucketProviderFailure(error),
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: SourceControlProviderKind.make("bitbucket"),
155 capabilities: CAPABILITIES,
156 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
157 readsPublicHostWithoutCheckout: true,
158​
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 author:
170 input.filters?.author === undefined
171 ? undefined
172 : resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
173 draft: input.filters?.draft === undefined ? undefined : input.filters.draft === "only",
174 })
175 .pipe(
176 Effect.mapError(fail("listChangeRequests")),
177 Effect.map((batch) => ({
178 items: batch.items.map(toChangeRequest),
179 truncated: batch.truncated,
180 continues: true,
181 })),
182 ),
183​
184 getChangeRequestChecks: (input) =>
185 Effect.all([api.getPullRequest(input), api.listChecks(input)], { concurrency: 2 }).pipe(
186 Effect.map(([pullRequest, checks]) => ({ state: pullRequest.state, checks })),
187 Effect.mapError(fail("getChangeRequestChecks")),
188 ),
189​
190 getChangeRequest: (input) => {
191 const target = { repository: input.repository, number: input.number };
192 return Effect.all(
193 [
194 api.getPullRequest(target),
195 api.getDiffStat(target),
196 recoverRead(api.getMergeability(target), "unknown" as const),
197 recoverRead(api.listChecks(target), []),
198 recoverRead(api.getRepositoryPermission(target), true),
199 ],
200 { concurrency: 5 },
201 ).pipe(
202 Effect.mapError(fail("getChangeRequest")),
203 Effect.map(
204 ([
205 pullRequest,
206 diffStat,
207 mergeability,
208 checks,
209 canWrite,
210 ]): ProviderChangeRequestDetail => ({
211 ...toChangeRequest(pullRequest),
212 mergeability,
213 additions: diffStat.additions,
214 deletions: diffStat.deletions,
215 changedFiles: diffStat.changedFiles,
216 body: pullRequest.body,
217 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
218 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
219 reviewers: pullRequest.reviewers,
220 checks,
221 // Bitbucket publishes no per-repository list of allowed strategies, so the ones it
222 // supports are all offered and a strategy the repository forbids fails on merge.
223 mergeCapabilities: { merge: true, squash: true, rebase: true },
224 viewerPermissions: bitbucketViewerPermissions({ canWrite }),
225 }),
226 ),
227 );
228 },
229​
230 getChangeRequestActivity: (input) => {
231 const target = { repository: input.repository, number: input.number };
232 return Effect.all(
233 [
234 api.getPullRequest(target),
235 recoverRead(api.listComments(target), { comments: [], threads: [], truncated: true }),
236 recoverRead(api.listCommits(target), []),
237 ],
238 { concurrency: 3 },
239 ).pipe(
240 Effect.mapError(fail("getChangeRequestActivity")),
241 Effect.map(([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
242 comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
243 left.createdAt.localeCompare(right.createdAt),
244 ),
245 commentCount: comments.comments.length + pullRequest.reviews.length,
246 commentsTruncated: comments.truncated,
247 reviewThreads: comments.threads,
248 commits,
249 })),
250 );
251 },
252​
253 getViewerPermissions: (input) =>
254 api.getRepositoryPermission({ repository: input.repository }).pipe(
255 Effect.mapError(fail("getViewerPermissions")),
256 Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
257 ),
258​
259 // `/diff` answers with the whole patch and pages nothing, so the first slice is the last.
260 getDiff: (input) =>
261 api
262 .getPullRequestDiff({
263 repository: input.repository,
264 number: input.number,
265 ...(input.commit === undefined ? {} : { commit: input.commit }),
266 })
267 .pipe(
268 Effect.mapError(fail("getDiff")),
269 Effect.map((diff) => ({ ...diff, nextCursor: null })),
270 ),
271​
272 getFileRevisions: (input) =>
273 api
274 .getFileRevisions({
275 repository: input.repository,
276 number: input.number,
277 paths: input.paths,
278 })
279 .pipe(Effect.mapError(fail("getFileRevisions"))),
280​
281 // Users only: Bitbucket requests a review of an account, and has no group that stands in for
282 // one on a pull request.
283 listReviewerCandidates: (input) =>
284 api
285 .listReviewerCandidates({ repository: input.repository, number: input.number })
286 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
287​
288 setReviewerRequest: (input) =>
289 api
290 .setReviewerRequest({
291 repository: input.repository,
292 number: input.number,
293 reviewers: input.reviewers,
294 requested: input.requested,
295 })
296 .pipe(Effect.mapError(fail("setReviewerRequest"))),
297​
298 runAction: (input) =>
299 api
300 .runAction({
301 repository: input.repository,
302 number: input.number,
303 action: input.action,
304 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
305 })
306 .pipe(Effect.mapError(fail("runAction"))),
307​
308 updateChangeRequest: (input) =>
309 api
310 .updateChangeRequest({
311 repository: input.repository,
312 number: input.number,
313 title: input.title,
314 body: input.body,
315 })
316 .pipe(Effect.mapError(fail("updateChangeRequest"))),
317​
318 comment: (input) =>
319 api
320 .comment({ repository: input.repository, number: input.number, body: input.body })
321 .pipe(Effect.mapError(fail("comment"))),
322​
323 updateComment: (input) =>
324 api
325 .updateComment({
326 repository: input.repository,
327 number: input.number,
328 commentId: input.commentId,
329 body: input.body,
330 })
331 .pipe(Effect.mapError(fail("updateComment"))),
332​
333 submitReview: (input) =>
334 api
335 .submitReview({
336 repository: input.repository,
337 number: input.number,
338 verdict: input.verdict,
339 body: input.body,
340 comments: input.comments,
341 })
342 .pipe(Effect.mapError(fail("submitReview"))),
343​
344 replyToThread: (input) =>
345 api
346 .replyToComment({
347 repository: input.repository,
348 number: input.number,
349 commentId: input.threadId,
350 body: input.body,
351 })
352 .pipe(Effect.mapError(fail("replyToThread"))),
353​
354 setReaction: () =>
355 Effect.fail(
356 new PullRequestProviderError({
357 provider: SourceControlProviderKind.make("bitbucket"),
358 operation: "setReaction",
359 reason: "failed",
360 detail: "Bitbucket does not support reactions.",
361 }),
362 ),
363​
364 setThreadResolution: (input) =>
365 api
366 .setCommentResolution({
367 repository: input.repository,
368 number: input.number,
369 commentId: input.threadId,
370 resolved: input.resolved,
371 })
372 .pipe(Effect.mapError(fail("setThreadResolution"))),
373 };
374​
375 return provider;
376});