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

BitbucketPullRequestProvider.ts

421 lines14.4 KB

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