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

BitbucketPullRequestProvider.ts

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