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

BitbucketPullRequestProvider.ts

360 lines12.3 KB

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