Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import type {
10 PullRequestAction,
11 PullRequestCheck,
12 PullRequestComment,
13 PullRequestCommit,
14 PullRequestListState,
15 PullRequestMergeMethod,
16 PullRequestMergeability,
17 PullRequestReviewCommentDraft,
18 PullRequestReviewPosition,
19 PullRequestReviewThread,
20 PullRequestReviewVerdict,
21 PullRequestReviewerCandidateList,
22} from "@t3tools/contracts";
23
24import * as BitbucketApi from "./BitbucketApi.ts";
25import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
26import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
27import {
28 buildReviewThreads,
29 decodeCommentsJson,
30 decodeCommitsJson,
31 decodeConflictsJson,
32 decodeDiffstatJson,
33 decodePullRequestJson,
34 decodePullRequestPageJson,
35 decodeRepositoryPermissionJson,
36 decodeStatusesJson,
37 decodeViewerJson,
38 decodeWorkspaceMembersJson,
39 type BitbucketDiffStat,
40 type BitbucketPullRequest,
41 type BitbucketRawComment,
42} from "./bitbucketPullRequestJson.ts";
43import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
44
45export class BitbucketPullRequestReadError extends Schema.TaggedError<BitbucketPullRequestReadError>()(
46 "BitbucketPullRequestReadError",
47 {
48 operation: Schema.String,
49 cause: Schema.Defect(),
50 },
51) {
52 get detail(): string {
53 return `Bitbucket returned an unreadable ${this.operation} response.`;
54 }
55
56 override get message(): string {
57 return `Bitbucket failed in ${this.operation}: ${this.detail}`;
58 }
59}
60
61export class BitbucketViewerUnavailableError extends Schema.TaggedError<BitbucketViewerUnavailableError>()(
62 "BitbucketViewerUnavailableError",
63 {},
64) {
65 get detail(): string {
66 return "Bitbucket returned no account name for the configured credentials.";
67 }
68
69 override get message(): string {
70 return `Bitbucket failed in getViewer: ${this.detail}`;
71 }
72}
73
74export class BitbucketRepositoryUnsupportedError extends Schema.TaggedError<BitbucketRepositoryUnsupportedError>()(
75 "BitbucketRepositoryUnsupportedError",
76 {
77 repository: Schema.String,
78 },
79) {
80 get detail(): string {
81 return "A Bitbucket repository is addressed as workspace/repository.";
82 }
83
84 override get message(): string {
85 return `Bitbucket failed in resolveRepository: ${this.detail}`;
86 }
87}
88
89export class BitbucketDiffCommitError extends Schema.TaggedError<BitbucketDiffCommitError>()(
90 "BitbucketDiffCommitError",
91 {},
92) {
93 get detail(): string {
94 return "The named commit was not a commit sha.";
95 }
96
97 override get message(): string {
98 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
99 }
100}
101
102export type BitbucketPullRequestApiError =
103 | BitbucketApi.BitbucketApiError
104 | BitbucketPullRequestReadError
105 | BitbucketViewerUnavailableError
106 | BitbucketRepositoryUnsupportedError
107 | BitbucketDiffCommitError;
108
109function isRepositoryPermissionUnavailableError(
110 error: BitbucketPullRequestApiError,
111): error is BitbucketApi.BitbucketResponseError {
112 return (
113 error._tag === "BitbucketResponseError" &&
114 (error.status === 403 || error.status === 404 || error.status === 410)
115 );
116}
117
118/**
119 * Asking for more does not fail — it answers with an empty page and no error at
120 * all, so this is a number to respect rather than to push against.
121 */
122const MAX_PAGE_SIZE = 50;
123const MAX_LIST_PAGES = 10;
124const CONVERSATION_PAGE_SIZE = 50;
125const CONVERSATION_PAGES = 10;
126const DIFF_MAX_BYTES = 8 * 1024 * 1024;
127/**
128 * Deliberately far shorter than the window the caller holds versions for: a refresh drops what the
129 * caller holds precisely so the next read reaches Bitbucket, and this must not be what answers it
130 * instead.
131 */
132const REVISION_PATCH_TTL = Duration.seconds(5);
133const REVISION_PATCH_CAPACITY = 16;
134export interface BitbucketPullRequestBatch {
135 readonly items: ReadonlyArray<BitbucketPullRequest>;
136 readonly truncated: boolean;
137}
138
139export class BitbucketPullRequestApi extends Context.Service<
140 BitbucketPullRequestApi,
141 {
142 readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
143
144 readonly listPullRequests: (input: {
145 readonly repository: string;
146 readonly state: PullRequestListState;
147 readonly limit: number;
148 readonly query?: string | undefined;
149 readonly cursor?: ProviderListCursor | undefined;
150 }) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
151
152 readonly getPullRequest: (input: {
153 readonly repository: string;
154 readonly number: number;
155 }) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
156
157 readonly getRepositoryPermission: (input: {
158 readonly repository: string;
159 }) => Effect.Effect<boolean, BitbucketPullRequestApiError>;
160
161 readonly getPullRequestDiff: (input: {
162 readonly repository: string;
163 readonly number: number;
164 readonly commit?: string | undefined;
165 }) => Effect.Effect<
166 { readonly patch: string; readonly truncated: boolean },
167 BitbucketPullRequestApiError
168 >;
169
170 readonly getDiffStat: (input: {
171 readonly repository: string;
172 readonly number: number;
173 }) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;
174
175 /**
176 * Answers with every file the patch carries rather than only the paths asked about, since
177 * reading one file's version here means parsing all of them. `complete` is false for a patch
178 * cut short, which cannot speak for what came after the cut.
179 */
180 readonly getFileRevisions: (input: {
181 readonly repository: string;
182 readonly number: number;
183 readonly paths: ReadonlyArray<string>;
184 }) => Effect.Effect<
185 { readonly revisions: ReadonlyMap<string, string>; readonly complete: boolean },
186 BitbucketPullRequestApiError
187 >;
188
189 readonly getMergeability: (input: {
190 readonly repository: string;
191 readonly number: number;
192 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
193
194 readonly listComments: (input: {
195 readonly repository: string;
196 readonly number: number;
197 }) => Effect.Effect<
198 {
199 readonly comments: ReadonlyArray<PullRequestComment>;
200 readonly threads: ReadonlyArray<PullRequestReviewThread>;
201 readonly truncated: boolean;
202 },
203 BitbucketPullRequestApiError
204 >;
205
206 readonly listCommits: (input: {
207 readonly repository: string;
208 readonly number: number;
209 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
210
211 readonly listChecks: (input: {
212 readonly repository: string;
213 readonly number: number;
214 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
215
216 readonly listReviewerCandidates: (input: {
217 readonly repository: string;
218 readonly number: number;
219 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
220
221 readonly setReviewerRequest: (input: {
222 readonly repository: string;
223 readonly number: number;
224 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
225 readonly requested: boolean;
226 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
227
228 readonly runAction: (input: {
229 readonly repository: string;
230 readonly number: number;
231 readonly action: PullRequestAction;
232 readonly mergeMethod?: PullRequestMergeMethod;
233 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
234
235 readonly updateChangeRequest: (input: {
236 readonly repository: string;
237 readonly number: number;
238 readonly title?: string | undefined;
239 readonly body?: string | undefined;
240 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
241
242 readonly comment: (input: {
243 readonly repository: string;
244 readonly number: number;
245 readonly body: string;
246 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
247
248 readonly updateComment: (input: {
249 readonly repository: string;
250 readonly number: number;
251 readonly commentId: string;
252 readonly body: string;
253 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
254
255 readonly submitReview: (input: {
256 readonly repository: string;
257 readonly number: number;
258 readonly verdict: PullRequestReviewVerdict;
259 readonly body: string;
260 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
261 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
262
263 readonly replyToComment: (input: {
264 readonly repository: string;
265 readonly number: number;
266 readonly commentId: string;
267 readonly body: string;
268 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
269
270 readonly setCommentResolution: (input: {
271 readonly repository: string;
272 readonly number: number;
273 readonly commentId: string;
274 readonly resolved: boolean;
275 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
276 }
277>()("@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi") {}
278
279function repositorySegments(
280 repository: string,
281): Result.Result<
282 { readonly workspace: string; readonly slug: string },
283 BitbucketRepositoryUnsupportedError
284> {
285 const segments = repository
286 .split("/")
287 .map((segment) => segment.trim())
288 .filter((segment) => segment.length > 0);
289 const [workspace, slug] = segments;
290 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
291 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
292 }
293 return Result.succeed({ workspace, slug });
294}
295
296function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
297 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
298 segments.slug,
299 )}`;
300}
301
302function isCommitSha(value: string): boolean {
303 return /^[0-9a-f]{7,64}$/i.test(value);
304}
305
306/**
307 * Bitbucket unions repeated `state` parameters, so a tab that spans several of its states asks
308 * for each.
309 */
310function stateParams(state: PullRequestListState): ReadonlyArray<string> {
311 switch (state) {
312 case "open":
313 return ["OPEN"];
314 case "merged":
315 return ["MERGED"];
316 case "closed":
317 return ["DECLINED", "SUPERSEDED"];
318 case "all":
319 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
320 }
321}
322
323/**
324 * The parentheses matter, because the expression is ANDed with the state filter beside it and
325 * an unbracketed `OR` would swallow it.
326 */
327function searchFilter(query: string): string {
328 const literal = filterLiteral(query);
329 return `(title ~ "${literal}" OR description ~ "${literal}")`;
330}
331
332/**
333 * The backslash is escaped first, or escaping the quote would only produce a literal
334 * backslash followed by a live quote.
335 */
336function filterLiteral(value: string): string {
337 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
338}
339
340function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
341 switch (method) {
342 case "squash":
343 return "squash";
344 case "rebase":
345 return "rebase_fast_forward";
346 default:
347 return "merge_commit";
348 }
349}
350
351function bitbucketReviewPosition(
352 position: PullRequestReviewPosition,
353): { readonly from: number } | { readonly to: number } {
354 switch (position.kind) {
355 case "added":
356 return { to: position.newLine };
357 case "deleted":
358 return { from: position.oldLine };
359 case "context":
360 return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };
361 }
362}
363
364/** @public Service construction is part of the canonical Effect module API. */
365export const make = Effect.gen(function* () {
366 const bitbucket = yield* BitbucketApi.BitbucketApi;
367
368 const withRepository = <A>(
369 repository: string,
370 use: (
371 path: string,
372 workspace: string,
373 slug: string,
374 ) => Effect.Effect<A, BitbucketPullRequestApiError>,
375 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
376 const segments = repositorySegments(repository);
377 return Result.isSuccess(segments)
378 ? use(repositoryPathOf(segments.success), segments.success.workspace, segments.success.slug)
379 : Effect.fail(segments.failure);
380 };
381
382 const listPage = (input: {
383 readonly url: string;
384 readonly limit: number;
385 readonly page: number;
386 readonly collected: ReadonlyArray<BitbucketPullRequest>;
387 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
388 bitbucket.request({ method: "GET", url: input.url }).pipe(
389 Effect.flatMap((response) => {
390 const decoded = decodePullRequestPageJson(response.body);
391 if (!Result.isSuccess(decoded)) {
392 return Effect.fail(
393 new BitbucketPullRequestReadError({
394 operation: "listPullRequests",
395 cause: decoded.failure,
396 }),
397 );
398 }
399 const collected = [...input.collected, ...decoded.success.items];
400 const next = decoded.success.next;
401 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
402 return Effect.succeed({
403 items: collected.slice(0, input.limit),
404 truncated: next !== null || collected.length > input.limit,
405 });
406 }
407 return listPage({ ...input, url: next, page: input.page + 1, collected });
408 }),
409 );
410
411 const readPage = <A>(input: {
412 readonly operation: string;
413 readonly url: string;
414 readonly decode: (body: string) => Result.Result<A, unknown>;
415 }): Effect.Effect<A, BitbucketPullRequestApiError> =>
416 bitbucket.request({ method: "GET", url: input.url }).pipe(
417 Effect.flatMap((response) => {
418 const decoded = input.decode(response.body);
419 return Result.isSuccess(decoded)
420 ? Effect.succeed(decoded.success)
421 : Effect.fail(
422 new BitbucketPullRequestReadError({
423 operation: input.operation,
424 cause: decoded.failure,
425 }),
426 );
427 }),
428 );
429
430 /**
431 * Threads are assembled once at the end rather than per page, because a reply and the remark
432 * it answers can land either side of a page boundary.
433 */
434 const commentsPage = (input: {
435 readonly url: string;
436 readonly page: number;
437 readonly comments: ReadonlyArray<PullRequestComment>;
438 readonly entries: ReadonlyArray<BitbucketRawComment>;
439 }): Effect.Effect<
440 {
441 readonly comments: ReadonlyArray<PullRequestComment>;
442 readonly threads: ReadonlyArray<PullRequestReviewThread>;
443 readonly truncated: boolean;
444 },
445 BitbucketPullRequestApiError
446 > =>
447 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
448 Effect.flatMap((page) => {
449 const comments = [...input.comments, ...page.comments];
450 const entries = [...input.entries, ...page.entries];
451 if (page.next !== null && input.page < CONVERSATION_PAGES) {
452 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
453 }
454 return Effect.succeed({
455 comments,
456 threads: buildReviewThreads(entries),
457 truncated: page.next !== null,
458 });
459 }),
460 );
461
462 const itemPages = <A>(input: {
463 readonly operation: string;
464 readonly url: string;
465 readonly decode: (
466 body: string,
467 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
468 readonly items: ReadonlyArray<A>;
469 /** Commit pages are individually oldest-first, so older pages are prepended. */
470 readonly prepend: boolean;
471 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
472 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
473 Effect.flatMap((page) => {
474 const items = input.prepend
475 ? [...page.items, ...input.items]
476 : [...input.items, ...page.items];
477 return page.next === null
478 ? Effect.succeed(items)
479 : itemPages({ ...input, url: page.next, items });
480 }),
481 );
482
483 const diffStatPages = (input: {
484 readonly url: string;
485 readonly totals: BitbucketDiffStat;
486 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
487 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
488 Effect.flatMap((page) => {
489 const totals = {
490 additions: input.totals.additions + page.additions,
491 deletions: input.totals.deletions + page.deletions,
492 changedFiles: input.totals.changedFiles + page.changedFiles,
493 };
494 return page.next === null
495 ? Effect.succeed(totals)
496 : diffStatPages({ url: page.next, totals });
497 }),
498 );
499
500 const pullRequestDiff = (input: {
501 readonly repository: string;
502 readonly number: number;
503 readonly commit?: string | undefined;
504 }): Effect.Effect<
505 { readonly patch: string; readonly truncated: boolean },
506 BitbucketPullRequestApiError
507 > =>
508 input.commit !== undefined && !isCommitSha(input.commit)
509 ? Effect.fail(new BitbucketDiffCommitError())
510 : withRepository(input.repository, (path) =>
511 bitbucket
512 .request({
513 method: "GET",
514 url:
515 input.commit === undefined
516 ? `${path}/pullrequests/${input.number}/diff`
517 : `${path}/diff/${input.commit}`,
518 maxBytes: DIFF_MAX_BYTES,
519 })
520 .pipe(
521 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
522 ),
523 );
524
525 /**
526 * The parsed answer rather than the patch, which at this capacity would hold sixteen bodies
527 * of up to the byte ceiling each resident, and saves walking a patch of a hundred thousand
528 * lines again on every tick.
529 */
530 const revisionPatches = yield* Cache.makeWith(
531 (key: string) => {
532 const [repository, number] = JSON.parse(key) as [string, number];
533 return pullRequestDiff({ repository, number }).pipe(
534 Effect.map((diff) => ({
535 revisions: parseDiffFileRevisions(diff.patch),
536 truncated: diff.truncated,
537 })),
538 );
539 },
540 {
541 capacity: REVISION_PATCH_CAPACITY,
542 timeToLive: (exit) => (Exit.isSuccess(exit) ? REVISION_PATCH_TTL : Duration.zero),
543 },
544 );
545
546 return BitbucketPullRequestApi.of({
547 getViewer: () =>
548 bitbucket.request({ method: "GET", url: "/user" }).pipe(
549 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
550 const decoded = decodeViewerJson(response.body);
551 if (!Result.isSuccess(decoded)) {
552 return Effect.fail(
553 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
554 );
555 }
556 return decoded.success === null
557 ? Effect.fail(new BitbucketViewerUnavailableError())
558 : Effect.succeed(decoded.success);
559 }),
560 ),
561
562 listPullRequests: (input) =>
563 withRepository(input.repository, (path) => {
564 const search = input.query?.trim() ?? "";
565 // Exclude already-sent IDs at the inclusive timestamp before applying the page limit.
566 const predicates = [
567 ...(search.length === 0 ? [] : [searchFilter(search)]),
568 ...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
569 ...(input.cursor?.seenAt ?? []).map((number) => `id != ${number}`),
570 ];
571 return listPage({
572 // Reviewers are not on a listing by default, and `viewerReviewRequested` needs them.
573 url: `${path}/pullrequests?${stateParams(input.state)
574 .map((state) => `state=${state}`)
575 .join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
576 predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
577 }`,
578 limit: input.limit,
579 page: 1,
580 collected: [],
581 });
582 }),
583
584 getPullRequest: (input) =>
585 withRepository(input.repository, (path) =>
586 readPage({
587 operation: "getPullRequest",
588 // `closed_on` is left out of the default representation. It is the only merge or
589 // decline time Bitbucket states on the pull request itself, and settlement needs it.
590 url: `${path}/pullrequests/${input.number}?fields=%2Bclosed_on`,
591 decode: decodePullRequestJson,
592 }),
593 ),
594
595 // Bitbucket has retired permission endpoints before (CHANGE-2770), and some credentials may
596 // not reach `/user` endpoints at all. A 403, 404 or 410 here is read as a permission that
597 // could not be learned, the same as an empty page: it grants, and the write itself says why
598 // if the account may not do it. Other failures (a bad token, a network fault) still fail.
599 getRepositoryPermission: (input) =>
600 withRepository(input.repository, (_path, workspace, slug) =>
601 readPage({
602 operation: "getRepositoryPermission",
603 url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(
604 `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,
605 )}`,
606 decode: decodeRepositoryPermissionJson,
607 }),
608 ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true))),
609
610 getPullRequestDiff: pullRequestDiff,
611
612 getFileRevisions: (input) =>
613 input.paths.length === 0
614 ? Effect.succeed({ revisions: new Map(), complete: false })
615 : Cache.get(revisionPatches, JSON.stringify([input.repository, input.number])).pipe(
616 Effect.map((diff) => {
617 const revisions = new Map(diff.revisions);
618 // A patch cut short at the byte ceiling says nothing about the files past the cut,
619 // so those paths are left out rather than reported as removed.
620 if (!diff.truncated) {
621 for (const path of input.paths) {
622 if (!revisions.has(path)) revisions.set(path, "");
623 }
624 }
625 return { revisions, complete: !diff.truncated };
626 }),
627 ),
628
629 getDiffStat: (input) =>
630 withRepository(input.repository, (path) =>
631 diffStatPages({
632 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
633 totals: { additions: 0, deletions: 0, changedFiles: 0 },
634 }),
635 ),
636
637 getMergeability: (input) =>
638 withRepository(input.repository, (path) =>
639 readPage({
640 operation: "getMergeability",
641 url: `${path}/pullrequests/${input.number}/conflicts`,
642 decode: decodeConflictsJson,
643 }),
644 ),
645
646 listComments: (input) =>
647 withRepository(input.repository, (path) =>
648 commentsPage({
649 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
650 page: 1,
651 comments: [],
652 entries: [],
653 }),
654 ),
655
656 listCommits: (input) =>
657 withRepository(input.repository, (path) =>
658 itemPages({
659 operation: "listCommits",
660 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
661 decode: decodeCommitsJson,
662 items: [],
663 prepend: true,
664 }),
665 ),
666
667 listChecks: (input) =>
668 withRepository(input.repository, (path) =>
669 itemPages({
670 operation: "listChecks",
671 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
672 decode: decodeStatusesJson,
673 items: [],
674 prepend: false,
675 }).pipe(Effect.map(sortChecks)),
676 ),
677
678 listReviewerCandidates: (input) =>
679 withRepository(input.repository, (path, workspace) =>
680 Effect.all(
681 [
682 readPage({
683 operation: "getPullRequest",
684 url: `${path}/pullrequests/${input.number}`,
685 decode: decodePullRequestJson,
686 }),
687 readPage({
688 operation: "listReviewerCandidates",
689 url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
690 decode: decodeWorkspaceMembersJson,
691 }),
692 ],
693 { concurrency: 2 },
694 ).pipe(
695 Effect.map(([pullRequest, members]) => {
696 const requested = new Set(pullRequest.reviewerIds);
697 const author = pullRequest.author?.login;
698 return {
699 // The author is dropped rather than shown unusable: Bitbucket refuses to make the
700 // person who opened a pull request its reviewer.
701 candidates: members.items.flatMap((candidate) =>
702 candidate.login === author
703 ? []
704 : [{ ...candidate, isRequested: requested.has(candidate.id) }],
705 ),
706 truncated: members.next !== null,
707 };
708 }),
709 ),
710 ),
711
712 setReviewerRequest: (input) =>
713 withRepository(input.repository, (path) => {
714 const pullRequest = `${path}/pullrequests/${input.number}`;
715 return readPage({
716 operation: "getPullRequest",
717 url: pullRequest,
718 decode: decodePullRequestJson,
719 }).pipe(
720 Effect.flatMap((current) => {
721 // Bitbucket has no endpoint that adds or removes one reviewer: the pull request's
722 // `reviewers` is written whole, so the set that is already there is read first and
723 // the change applied to it.
724 const uuids = new Set(current.reviewerIds);
725 for (const reviewer of input.reviewers) {
726 if (input.requested) uuids.add(reviewer.id);
727 else uuids.delete(reviewer.id);
728 }
729 return bitbucket.request({
730 method: "PUT",
731 url: pullRequest,
732 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
733 });
734 }),
735 Effect.asVoid,
736 );
737 }),
738
739 runAction: (input) =>
740 withRepository(input.repository, (path) => {
741 const pullRequest = `${path}/pullrequests/${input.number}`;
742 if (input.action === "merge") {
743 return bitbucket
744 .request({
745 method: "POST",
746 url: `${pullRequest}/merge`,
747 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
748 })
749 .pipe(Effect.asVoid);
750 }
751 return bitbucket
752 .request({ method: "POST", url: `${pullRequest}/decline` })
753 .pipe(Effect.asVoid);
754 }),
755
756 updateChangeRequest: (input) =>
757 withRepository(input.repository, (path) =>
758 // Only the words this call rewrites travel in the body: as `setReviewerRequest` above
759 // relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
760 // was — sending `reviewers` back here would overwrite a change another user made to it
761 // between this call being issued and the request landing.
762 bitbucket
763 .request({
764 method: "PUT",
765 url: `${path}/pullrequests/${input.number}`,
766 body: JSON.stringify({
767 ...(input.title === undefined ? {} : { title: input.title }),
768 ...(input.body === undefined ? {} : { description: input.body }),
769 }),
770 })
771 .pipe(Effect.asVoid),
772 ),
773
774 comment: (input) =>
775 withRepository(input.repository, (path) =>
776 bitbucket
777 .request({
778 method: "POST",
779 url: `${path}/pullrequests/${input.number}/comments`,
780 body: JSON.stringify({ content: { raw: input.body } }),
781 })
782 .pipe(Effect.asVoid),
783 ),
784
785 updateComment: (input) =>
786 withRepository(input.repository, (path) =>
787 bitbucket
788 .request({
789 method: "PUT",
790 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
791 input.commentId,
792 )}`,
793 body: JSON.stringify({ content: { raw: input.body } }),
794 })
795 .pipe(Effect.asVoid),
796 ),
797
798 submitReview: (input) =>
799 withRepository(input.repository, (path) =>
800 Effect.gen(function* () {
801 const pullRequest = `${path}/pullrequests/${input.number}`;
802 // Bitbucket has no pending review, so a review is replayed as the requests it is
803 // made of: the line comments, then the summary, then the verdict. The verdict goes
804 // last so a review that fails part-way is never left standing as an approval.
805 yield* Effect.forEach(
806 input.comments,
807 (comment) =>
808 bitbucket.request({
809 method: "POST",
810 url: `${pullRequest}/comments`,
811 body: JSON.stringify({
812 content: { raw: comment.body },
813 inline: {
814 path: comment.path,
815 ...bitbucketReviewPosition(comment.position),
816 },
817 }),
818 }),
819 { discard: true },
820 );
821 if (input.body.trim().length > 0) {
822 yield* bitbucket.request({
823 method: "POST",
824 url: `${pullRequest}/comments`,
825 // @effect-diagnostics-next-line preferSchemaOverJson:off
826 body: JSON.stringify({ content: { raw: input.body } }),
827 });
828 }
829 if (input.verdict === "approve") {
830 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
831 }
832 if (input.verdict === "request-changes") {
833 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
834 }
835 }),
836 ),
837
838 replyToComment: (input) =>
839 withRepository(input.repository, (path) =>
840 bitbucket
841 .request({
842 method: "POST",
843 url: `${path}/pullrequests/${input.number}/comments`,
844 body: JSON.stringify({
845 content: { raw: input.body },
846 parent: { id: Number(input.commentId) },
847 }),
848 })
849 .pipe(Effect.asVoid),
850 ),
851
852 setCommentResolution: (input) =>
853 withRepository(input.repository, (path) =>
854 bitbucket
855 .request({
856 method: input.resolved ? "POST" : "DELETE",
857 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
858 input.commentId,
859 )}/resolve`,
860 })
861 .pipe(Effect.asVoid),
862 ),
863 });
864});
865
866export const layer = Layer.effect(BitbucketPullRequestApi, make);