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

BitbucketPullRequestProvider.ts

369 lines12.5 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 getChangeRequest: (input) => {
186 const target = { repository: input.repository, number: input.number };
187 return Effect.all(
188 [
189 api.getPullRequest(target),
190 api.getDiffStat(target),
191 recoverRead(api.getMergeability(target), "unknown" as const),
192 recoverRead(api.listChecks(target), []),
193 recoverRead(api.getRepositoryPermission(target), true),
194 ],
195 { concurrency: 5 },
196 ).pipe(
197 Effect.mapError(fail("getChangeRequest")),
198 Effect.map(
199 ([
200 pullRequest,
201 diffStat,
202 mergeability,
203 checks,
204 canWrite,
205 ]): ProviderChangeRequestDetail => ({
206 ...toChangeRequest(pullRequest),
207 mergeability,
208 additions: diffStat.additions,
209 deletions: diffStat.deletions,
210 changedFiles: diffStat.changedFiles,
211 body: pullRequest.body,
212 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
213 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
214 reviewers: pullRequest.reviewers,
215 checks,
216 // Bitbucket exposes no strategy permissions; unsupported strategies fail at 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 api.getPullRequest(target),
229 recoverRead(api.listComments(target), { comments: [], threads: [], truncated: true }),
230 recoverRead(api.listCommits(target), []),
231 ],
232 { concurrency: 3 },
233 ).pipe(
234 Effect.mapError(fail("getChangeRequestActivity")),
235 Effect.map(([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
236 comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
237 left.createdAt.localeCompare(right.createdAt),
238 ),
239 commentCount: comments.comments.length + pullRequest.reviews.length,
240 commentsTruncated: comments.truncated,
241 reviewThreads: comments.threads,
242 commits,
243 })),
244 );
245 },
246​
247 getViewerPermissions: (input) =>
248 api.getRepositoryPermission({ repository: input.repository }).pipe(
249 Effect.mapError(fail("getViewerPermissions")),
250 Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
251 ),
252​
253 // `/diff` returns the whole patch without pagination.
254 getDiff: (input) =>
255 api
256 .getPullRequestDiff({
257 repository: input.repository,
258 number: input.number,
259 ...(input.commit === undefined ? {} : { commit: input.commit }),
260 })
261 .pipe(
262 Effect.mapError(fail("getDiff")),
263 Effect.map((diff) => ({ ...diff, nextCursor: null })),
264 ),
265​
266 getFileRevisions: (input) =>
267 api
268 .getFileRevisions({
269 repository: input.repository,
270 number: input.number,
271 paths: input.paths,
272 })
273 .pipe(Effect.mapError(fail("getFileRevisions"))),
274​
275 // Bitbucket supports user reviewers only.
276 listReviewerCandidates: (input) =>
277 api
278 .listReviewerCandidates({ repository: input.repository, number: input.number })
279 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
280​
281 setReviewerRequest: (input) =>
282 api
283 .setReviewerRequest({
284 repository: input.repository,
285 number: input.number,
286 reviewers: input.reviewers,
287 requested: input.requested,
288 })
289 .pipe(Effect.mapError(fail("setReviewerRequest"))),
290​
291 runAction: (input) =>
292 api
293 .runAction({
294 repository: input.repository,
295 number: input.number,
296 action: input.action,
297 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
298 })
299 .pipe(Effect.mapError(fail("runAction"))),
300​
301 updateChangeRequest: (input) =>
302 api
303 .updateChangeRequest({
304 repository: input.repository,
305 number: input.number,
306 title: input.title,
307 body: input.body,
308 })
309 .pipe(Effect.mapError(fail("updateChangeRequest"))),
310​
311 comment: (input) =>
312 api
313 .comment({ repository: input.repository, number: input.number, body: input.body })
314 .pipe(Effect.mapError(fail("comment"))),
315​
316 updateComment: (input) =>
317 api
318 .updateComment({
319 repository: input.repository,
320 number: input.number,
321 commentId: input.commentId,
322 body: input.body,
323 })
324 .pipe(Effect.mapError(fail("updateComment"))),
325​
326 submitReview: (input) =>
327 api
328 .submitReview({
329 repository: input.repository,
330 number: input.number,
331 verdict: input.verdict,
332 body: input.body,
333 comments: input.comments,
334 })
335 .pipe(Effect.mapError(fail("submitReview"))),
336​
337 replyToThread: (input) =>
338 api
339 .replyToComment({
340 repository: input.repository,
341 number: input.number,
342 commentId: input.threadId,
343 body: input.body,
344 })
345 .pipe(Effect.mapError(fail("replyToThread"))),
346​
347 setReaction: () =>
348 Effect.fail(
349 new PullRequestProviderError({
350 provider: SourceControlProviderKind.make("bitbucket"),
351 operation: "setReaction",
352 reason: "failed",
353 detail: "Bitbucket does not support reactions.",
354 }),
355 ),
356​
357 setThreadResolution: (input) =>
358 api
359 .setCommentResolution({
360 repository: input.repository,
361 number: input.number,
362 commentId: input.threadId,
363 resolved: input.resolved,
364 })
365 .pipe(Effect.mapError(fail("setThreadResolution"))),
366 };
367​
368 return provider;
369});