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

BitbucketPullRequestProvider.ts

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