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

BitbucketPullRequestProvider.ts

368 lines12.7 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 "../client/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​
41/**
42 * Bitbucket lets the author of a pull request decline their own with no more than read access,
43 * and the permission response says nothing about who opened this one — so withholding the
44 * control from the one person entitled to it is the worse of the two mistakes.
45 */
46export function bitbucketViewerPermissions(input: {
47 readonly canWrite: boolean;
48}): PullRequestViewerPermissions {
49 return {
50 actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.canWrite),
51 comment: true,
52 resolve: true,
53 verdicts: CAPABILITIES.review.verdicts,
54 requestReviewers: true,
55 };
57​
58export function bitbucketProviderFailure(
59 error: BitbucketPullRequestApi.BitbucketPullRequestApiError,
60): PullRequestProviderFailure {
61 if (error._tag === "BitbucketResponseError" && error.status === 401) {
62 return { reason: "unauthenticated" };
63 }
64 if (error._tag === "SourceControlRateLimitPausedError") {
65 return { reason: "rate-limited", retryAt: error.retryAt };
66 }
67 if (
68 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
69 error.status === 429
70 ) {
71 return {
72 reason: "rate-limited",
73 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
74 };
75 }
76 if (
77 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
78 error.status === 404
79 ) {
80 return { reason: "not-found" };
81 }
82 return { reason: "failed" };
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.headSha ? { headSha: pullRequest.headSha } : {}),
93 ...(pullRequest.headRepositoryNameWithOwner
94 ? { headRepositoryNameWithOwner: pullRequest.headRepositoryNameWithOwner }
95 : {}),
96 baseBranch: pullRequest.baseBranch,
97 state: pullRequest.state,
98 isDraft: pullRequest.isDraft,
99 mergeability: pullRequest.mergeability,
100 additions: 0,
101 deletions: 0,
102 createdAt: pullRequest.createdAt,
103 updatedAt: pullRequest.updatedAt,
104 reviewRequestLogins: pullRequest.reviewRequestLogins,
105 labels: [],
106 };
108​
109export const make = Effect.gen(function* () {
110 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
111​
112 const fail =
113 (operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
114 new PullRequestProviderError({
115 provider: SourceControlProviderKind.make("bitbucket"),
116 operation,
117 ...bitbucketProviderFailure(error),
118 detail: error.detail,
119 cause: error,
120 });
121​
122 const recoverRead = <A>(
123 read: Effect.Effect<A, BitbucketPullRequestApi.BitbucketPullRequestApiError>,
124 fallback: A,
125 ) => {
126 const recover = () => Effect.succeed(fallback);
127 return Effect.catchTags(read, {
128 BitbucketResponseError: (error) => (error.status === 429 ? Effect.fail(error) : recover()),
129 BitbucketUntrustedUrlError: recover,
130 BitbucketRepositoryLocatorError: recover,
131 BitbucketRequestError: recover,
132 BitbucketResponseBodyReadError: (error) =>
133 error.status === 429 ? Effect.fail(error) : recover(),
134 BitbucketResponseDecodeError: recover,
135 BitbucketRepositoryVcsResolveError: recover,
136 BitbucketRepositoryRemotesListError: recover,
137 BitbucketRepositoryRemoteNotFoundError: recover,
138 BitbucketPullRequestBodyReadError: recover,
139 BitbucketCheckoutError: recover,
140 BitbucketPullRequestReadError: recover,
141 BitbucketViewerUnavailableError: recover,
142 BitbucketRepositoryUnsupportedError: recover,
143 BitbucketDiffCommitError: recover,
144 });
145 };
146​
147 const provider: PullRequestProviderApi = {
148 kind: SourceControlProviderKind.make("bitbucket"),
149 capabilities: CAPABILITIES,
150​
151 getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),
152​
153 listChangeRequests: (input) =>
154 api
155 .listPullRequests({
156 repository: input.repository,
157 state: input.state,
158 limit: input.limit,
159 query: input.query,
160 cursor: input.cursor,
161 author:
162 input.filters?.author === undefined
163 ? undefined
164 : resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
165 draft: input.filters?.draft === undefined ? undefined : input.filters.draft === "only",
166 })
167 .pipe(
168 Effect.mapError(fail("listChangeRequests")),
169 Effect.map((batch) => ({
170 items: batch.items.map(toChangeRequest),
171 truncated: batch.truncated,
172 continues: true,
173 })),
174 ),
175​
176 getChangeRequestChecks: (input) =>
177 Effect.all([api.getPullRequest(input), api.listChecks(input)], { concurrency: 2 }).pipe(
178 Effect.map(([pullRequest, checks]) => ({ state: pullRequest.state, checks })),
179 Effect.mapError(fail("getChangeRequestChecks")),
180 ),
181​
182 getChangeRequest: (input) => {
183 const target = { repository: input.repository, number: input.number };
184 return Effect.all(
185 [
186 api.getPullRequest(target),
187 api.getDiffStat(target),
188 recoverRead(api.getMergeability(target), "unknown" as const),
189 recoverRead(api.listChecks(target), []),
190 recoverRead(api.getRepositoryPermission(target), true),
191 ],
192 { concurrency: 5 },
193 ).pipe(
194 Effect.mapError(fail("getChangeRequest")),
195 Effect.map(
196 ([
197 pullRequest,
198 diffStat,
199 mergeability,
200 checks,
201 canWrite,
202 ]): ProviderChangeRequestDetail => ({
203 ...toChangeRequest(pullRequest),
204 mergeability,
205 additions: diffStat.additions,
206 deletions: diffStat.deletions,
207 changedFiles: diffStat.changedFiles,
208 body: pullRequest.body,
209 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
210 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
211 reviewers: pullRequest.reviewers,
212 checks,
213 // Bitbucket publishes no per-repository list of allowed strategies, so the ones it
214 // supports are all offered and a strategy the repository forbids fails on merge.
215 mergeCapabilities: { merge: true, squash: true, rebase: true },
216 viewerPermissions: bitbucketViewerPermissions({ canWrite }),
217 }),
218 ),
219 );
220 },
221​
222 getChangeRequestActivity: (input) => {
223 const target = { repository: input.repository, number: input.number };
224 return Effect.all(
225 [
226 api.getPullRequest(target),
227 recoverRead(api.listComments(target), { comments: [], threads: [], truncated: true }),
228 recoverRead(api.listCommits(target), []),
229 ],
230 { concurrency: 3 },
231 ).pipe(
232 Effect.mapError(fail("getChangeRequestActivity")),
233 Effect.map(([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
234 comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
235 left.createdAt.localeCompare(right.createdAt),
236 ),
237 commentCount: comments.comments.length + pullRequest.reviews.length,
238 commentsTruncated: comments.truncated,
239 reviewThreads: comments.threads,
240 commits,
241 })),
242 );
243 },
244​
245 getViewerPermissions: (input) =>
246 api.getRepositoryPermission({ repository: input.repository }).pipe(
247 Effect.mapError(fail("getViewerPermissions")),
248 Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
249 ),
250​
251 // `/diff` answers with the whole patch and pages nothing, so the first slice is the last.
252 getDiff: (input) =>
253 api
254 .getPullRequestDiff({
255 repository: input.repository,
256 number: input.number,
257 ...(input.commit === undefined ? {} : { commit: input.commit }),
258 })
259 .pipe(
260 Effect.mapError(fail("getDiff")),
261 Effect.map((diff) => ({ ...diff, nextCursor: null })),
262 ),
263​
264 getFileRevisions: (input) =>
265 api
266 .getFileRevisions({
267 repository: input.repository,
268 number: input.number,
269 paths: input.paths,
270 })
271 .pipe(Effect.mapError(fail("getFileRevisions"))),
272​
273 // Users only: Bitbucket requests a review of an account, and has no group that stands in for
274 // one on a pull request.
275 listReviewerCandidates: (input) =>
276 api
277 .listReviewerCandidates({ repository: input.repository, number: input.number })
278 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
279​
280 setReviewerRequest: (input) =>
281 api
282 .setReviewerRequest({
283 repository: input.repository,
284 number: input.number,
285 reviewers: input.reviewers,
286 requested: input.requested,
287 })
288 .pipe(Effect.mapError(fail("setReviewerRequest"))),
289​
290 runAction: (input) =>
291 api
292 .runAction({
293 repository: input.repository,
294 number: input.number,
295 action: input.action,
296 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
297 })
298 .pipe(Effect.mapError(fail("runAction"))),
299​
300 updateChangeRequest: (input) =>
301 api
302 .updateChangeRequest({
303 repository: input.repository,
304 number: input.number,
305 title: input.title,
306 body: input.body,
307 })
308 .pipe(Effect.mapError(fail("updateChangeRequest"))),
309​
310 comment: (input) =>
311 api
312 .comment({ repository: input.repository, number: input.number, body: input.body })
313 .pipe(Effect.mapError(fail("comment"))),
314​
315 updateComment: (input) =>
316 api
317 .updateComment({
318 repository: input.repository,
319 number: input.number,
320 commentId: input.commentId,
321 body: input.body,
322 })
323 .pipe(Effect.mapError(fail("updateComment"))),
324​
325 submitReview: (input) =>
326 api
327 .submitReview({
328 repository: input.repository,
329 number: input.number,
330 verdict: input.verdict,
331 body: input.body,
332 comments: input.comments,
333 })
334 .pipe(Effect.mapError(fail("submitReview"))),
335​
336 replyToThread: (input) =>
337 api
338 .replyToComment({
339 repository: input.repository,
340 number: input.number,
341 commentId: input.threadId,
342 body: input.body,
343 })
344 .pipe(Effect.mapError(fail("replyToThread"))),
345​
346 setReaction: () =>
347 Effect.fail(
348 new PullRequestProviderError({
349 provider: SourceControlProviderKind.make("bitbucket"),
350 operation: "setReaction",
351 reason: "failed",
352 detail: "Bitbucket does not support reactions.",
353 }),
354 ),
355​
356 setThreadResolution: (input) =>
357 api
358 .setCommentResolution({
359 repository: input.repository,
360 number: input.number,
361 commentId: input.threadId,
362 resolved: input.resolved,
363 })
364 .pipe(Effect.mapError(fail("setThreadResolution"))),
365 };
366​
367 return provider;
368});