Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import type {
7 PullRequestAction,
8 PullRequestCheck,
9 PullRequestComment,
10 PullRequestCommit,
11 PullRequestListState,
12 PullRequestMergeMethod,
13 PullRequestMergeability,
14 PullRequestReviewCommentDraft,
15 PullRequestReviewThread,
16 PullRequestReviewVerdict,
17 PullRequestReviewerCandidateList,
18} from "@t3tools/contracts";
19
20import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
21import {
22 buildReviewThreads,
23 decodeCommentsJson,
24 decodeCommitsJson,
25 decodeConflictsJson,
26 decodeDiffstatJson,
27 decodePullRequestJson,
28 decodePullRequestPageJson,
29 decodeRepositoryPermissionJson,
30 decodeStatusesJson,
31 decodeViewerJson,
32 decodeWorkspaceMembersJson,
33 type BitbucketDiffStat,
34 type BitbucketPullRequest,
35 type BitbucketRawComment,
36} from "./bitbucketPullRequestJson.ts";
37import type { ProviderListCursor } from "./PullRequestProvider.ts";
38
39/**
40 * Names the read that produced unusable output, so a failure reports the call it came from
41 * rather than borrowing another operation's message.
42 */
43export class BitbucketPullRequestReadError extends Schema.TaggedErrorClass<BitbucketPullRequestReadError>()(
44 "BitbucketPullRequestReadError",
45 {
46 operation: Schema.String,
47 cause: Schema.Defect(),
48 },
49) {
50 get detail(): string {
51 return `Bitbucket returned an unreadable ${this.operation} response.`;
52 }
53
54 override get message(): string {
55 return `Bitbucket failed in ${this.operation}: ${this.detail}`;
56 }
57}
58
59/** Not a decode failure: Bitbucket answered, the account it answered for just has no handle. */
60export class BitbucketViewerUnavailableError extends Schema.TaggedErrorClass<BitbucketViewerUnavailableError>()(
61 "BitbucketViewerUnavailableError",
62 {},
63) {
64 get detail(): string {
65 return "Bitbucket returned no account name for the configured credentials.";
66 }
67
68 override get message(): string {
69 return `Bitbucket failed in getViewer: ${this.detail}`;
70 }
71}
72
73/** A repository that is not `workspace/slug`, which is the only form Bitbucket addresses. */
74export class BitbucketRepositoryUnsupportedError extends Schema.TaggedErrorClass<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
89/** Not a decode failure: the reader named a commit that is not a sha this repository could hold. */
90export class BitbucketDiffCommitError extends Schema.TaggedErrorClass<BitbucketDiffCommitError>()(
91 "BitbucketDiffCommitError",
92 {},
93) {
94 get detail(): string {
95 return "The named commit was not a commit sha.";
96 }
97
98 override get message(): string {
99 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
100 }
101}
102
103export type BitbucketPullRequestApiError =
104 | BitbucketApi.BitbucketApiError
105 | BitbucketPullRequestReadError
106 | BitbucketViewerUnavailableError
107 | BitbucketRepositoryUnsupportedError
108 | BitbucketDiffCommitError;
109
110/**
111 * Bitbucket's own ceiling. Asking for more does not fail — it answers with an empty page and no
112 * error at all, so this is a number to respect rather than to push against.
113 */
114const MAX_PAGE_SIZE = 50;
115/** Pages to walk before a listing is reported as truncated. */
116const MAX_LIST_PAGES = 10;
117/** The page size for pull request conversations, commits, and checks. */
118const CONVERSATION_PAGE_SIZE = 50;
119/**
120 * Pages of the conversation to follow before it is reported as truncated. Bitbucket serves
121 * fifty comments a page, so this is five hundred — beyond any pull request a person is reading,
122 * and an end to a walk whose only other stop is Bitbucket running out.
123 */
124const CONVERSATION_PAGES = 10;
125/** The same ceiling the gh and glab diff reads use. */
126const DIFF_MAX_BYTES = 8 * 1024 * 1024;
127
128export interface BitbucketPullRequestBatch {
129 readonly items: ReadonlyArray<BitbucketPullRequest>;
130 readonly truncated: boolean;
131}
132
133export class BitbucketPullRequestApi extends Context.Service<
134 BitbucketPullRequestApi,
135 {
136 /** A function rather than a value, so the request is built per call and not at layer time. */
137 readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
138
139 readonly listPullRequests: (input: {
140 readonly repository: string;
141 readonly state: PullRequestListState;
142 readonly limit: number;
143 /** Free text, matched against a pull request's title and description. */
144 readonly query?: string | undefined;
145 /** Where to carry on from, as a predicate on `updated_on` beside any other. */
146 readonly cursor?: ProviderListCursor | undefined;
147 }) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
148
149 readonly getPullRequest: (input: {
150 readonly repository: string;
151 readonly number: number;
152 }) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
153
154 /** True where the credentials can write to the repository, which is what merging needs. */
155 readonly getRepositoryPermission: (input: {
156 readonly repository: string;
157 }) => Effect.Effect<boolean, BitbucketPullRequestApiError>;
158
159 readonly getPullRequestDiff: (input: {
160 readonly repository: string;
161 readonly number: number;
162 /** One commit's own changes, rather than everything the pull request carries. */
163 readonly commit?: string | undefined;
164 }) => Effect.Effect<
165 { readonly patch: string; readonly truncated: boolean },
166 BitbucketPullRequestApiError
167 >;
168
169 readonly getDiffStat: (input: {
170 readonly repository: string;
171 readonly number: number;
172 }) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;
173
174 readonly getMergeability: (input: {
175 readonly repository: string;
176 readonly number: number;
177 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
178
179 readonly listComments: (input: {
180 readonly repository: string;
181 readonly number: number;
182 }) => Effect.Effect<
183 {
184 readonly comments: ReadonlyArray<PullRequestComment>;
185 readonly threads: ReadonlyArray<PullRequestReviewThread>;
186 readonly truncated: boolean;
187 },
188 BitbucketPullRequestApiError
189 >;
190
191 readonly listCommits: (input: {
192 readonly repository: string;
193 readonly number: number;
194 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
195
196 readonly listChecks: (input: {
197 readonly repository: string;
198 readonly number: number;
199 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
200
201 /**
202 * Who this pull request may be sent to, and who it has already been sent to. Two reads at
203 * once, because Bitbucket keeps the people on the workspace and the reviewers on the pull
204 * request, and neither answers for the other.
205 */
206 readonly listReviewerCandidates: (input: {
207 readonly repository: string;
208 readonly number: number;
209 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
210
211 readonly setReviewerRequest: (input: {
212 readonly repository: string;
213 readonly number: number;
214 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
215 readonly requested: boolean;
216 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
217
218 readonly runAction: (input: {
219 readonly repository: string;
220 readonly number: number;
221 readonly action: PullRequestAction;
222 readonly mergeMethod?: PullRequestMergeMethod;
223 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
224
225 readonly updateChangeRequest: (input: {
226 readonly repository: string;
227 readonly number: number;
228 readonly title?: string | undefined;
229 readonly body?: string | undefined;
230 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
231
232 readonly comment: (input: {
233 readonly repository: string;
234 readonly number: number;
235 readonly body: string;
236 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
237
238 readonly updateComment: (input: {
239 readonly repository: string;
240 readonly number: number;
241 readonly commentId: string;
242 readonly body: string;
243 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
244
245 readonly submitReview: (input: {
246 readonly repository: string;
247 readonly number: number;
248 readonly verdict: PullRequestReviewVerdict;
249 readonly body: string;
250 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
251 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
252
253 readonly replyToComment: (input: {
254 readonly repository: string;
255 readonly number: number;
256 readonly commentId: string;
257 readonly body: string;
258 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
259
260 readonly setCommentResolution: (input: {
261 readonly repository: string;
262 readonly number: number;
263 readonly commentId: string;
264 readonly resolved: boolean;
265 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
266 }
267>()("t3/pullRequest/BitbucketPullRequestApi") {}
268
269/** `workspace/slug`; Bitbucket has no deeper nesting to address. */
270function repositorySegments(
271 repository: string,
272): Result.Result<
273 { readonly workspace: string; readonly slug: string },
274 BitbucketRepositoryUnsupportedError
275> {
276 const segments = repository
277 .split("/")
278 .map((segment) => segment.trim())
279 .filter((segment) => segment.length > 0);
280 const [workspace, slug] = segments;
281 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
282 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
283 }
284 return Result.succeed({ workspace, slug });
285}
286
287function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
288 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
289 segments.slug,
290 )}`;
291}
292
293/**
294 * A commit sha arrives from the reader and goes straight into a request path, so it is checked
295 * rather than trusted: hexadecimal only, from the shortest abbreviation a host prints up to a
296 * whole sha.
297 */
298function isCommitSha(value: string): boolean {
299 return /^[0-9a-f]{7,64}$/i.test(value);
300}
301
302/**
303 * Bitbucket unions repeated `state` parameters, so a tab that spans several of its states asks
304 * for each. It separates a declined pull request from one superseded by another, and both read
305 * as closed here.
306 */
307function stateParams(state: PullRequestListState): ReadonlyArray<string> {
308 switch (state) {
309 case "open":
310 return ["OPEN"];
311 case "merged":
312 return ["MERGED"];
313 case "closed":
314 return ["DECLINED", "SUPERSEDED"];
315 case "all":
316 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
317 }
318}
319
320/**
321 * Bitbucket has no search term, only a filter expression, so free text becomes one: a
322 * case-insensitive contains against the two fields a pull request carries words in. The
323 * parentheses matter, because the expression is ANDed with the state filter beside it and an
324 * unbracketed `OR` would swallow it.
325 *
326 * A string literal in that grammar is delimited by double quotes, so the reader's text is
327 * escaped before it goes inside one — a quote would otherwise end the literal and leave the
328 * rest of the text standing as filter syntax. The whole expression is then URL-encoded, so
329 * nothing in it reaches the query string as a parameter of its own.
330 */
331function searchFilter(query: string): string {
332 const literal = filterLiteral(query);
333 return `(title ~ "${literal}" OR description ~ "${literal}")`;
334}
335
336/**
337 * Text as a string literal of Bitbucket's filter grammar. The backslash is escaped first, or
338 * escaping the quote would only produce a literal backslash followed by a live quote.
339 */
340function filterLiteral(value: string): string {
341 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
342}
343
344/** Bitbucket's merge strategies, named differently from the three the contract carries. */
345function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
346 switch (method) {
347 case "squash":
348 return "squash";
349 case "rebase":
350 // The linear history GitHub calls "rebase and merge".
351 return "rebase_fast_forward";
352 default:
353 return "merge_commit";
354 }
355}
356
357export const make = Effect.gen(function* () {
358 const bitbucket = yield* BitbucketApi.BitbucketApi;
359
360 /**
361 * The repository's own path, and the workspace above it — which the people who may review are
362 * kept on rather than on the repository, so both are handed over at once.
363 */
364 const withRepository = <A>(
365 repository: string,
366 use: (path: string, workspace: string) => Effect.Effect<A, BitbucketPullRequestApiError>,
367 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
368 const segments = repositorySegments(repository);
369 return Result.isSuccess(segments)
370 ? use(repositoryPathOf(segments.success), segments.success.workspace)
371 : Effect.fail(segments.failure);
372 };
373
374 /**
375 * Bitbucket pages with a cursor rather than an offset, so the walk follows the `next` URL it
376 * sends. It stops once the caller's page is filled, when Bitbucket reports no next page, or at
377 * the page cap — and anything but running out of pages means there is more to be had.
378 */
379 const listPage = (input: {
380 readonly url: string;
381 readonly limit: number;
382 readonly page: number;
383 readonly collected: ReadonlyArray<BitbucketPullRequest>;
384 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
385 bitbucket.request({ method: "GET", url: input.url }).pipe(
386 Effect.flatMap((response) => {
387 const decoded = decodePullRequestPageJson(response.body);
388 if (!Result.isSuccess(decoded)) {
389 return Effect.fail(
390 new BitbucketPullRequestReadError({
391 operation: "listPullRequests",
392 cause: decoded.failure,
393 }),
394 );
395 }
396 const collected = [...input.collected, ...decoded.success.items];
397 const next = decoded.success.next;
398 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
399 return Effect.succeed({
400 items: collected.slice(0, input.limit),
401 // Bitbucket pages in fifties whatever was asked for, so a walk that stopped on the
402 // count rather than on the last page is holding rows it is about to drop. Those are
403 // more results just as surely as another page would be.
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 * The conversation, following the `next` Bitbucket sends until it sends none. Threads are
432 * assembled once at the end rather than per page, because a reply and the remark it answers
433 * can land either side of a page boundary.
434 */
435 const commentsPage = (input: {
436 readonly url: string;
437 readonly page: number;
438 readonly comments: ReadonlyArray<PullRequestComment>;
439 readonly entries: ReadonlyArray<BitbucketRawComment>;
440 }): Effect.Effect<
441 {
442 readonly comments: ReadonlyArray<PullRequestComment>;
443 readonly threads: ReadonlyArray<PullRequestReviewThread>;
444 readonly truncated: boolean;
445 },
446 BitbucketPullRequestApiError
447 > =>
448 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
449 Effect.flatMap((page) => {
450 const comments = [...input.comments, ...page.comments];
451 const entries = [...input.entries, ...page.entries];
452 if (page.next !== null && input.page < CONVERSATION_PAGES) {
453 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
454 }
455 return Effect.succeed({
456 comments,
457 threads: buildReviewThreads(entries),
458 truncated: page.next !== null,
459 });
460 }),
461 );
462
463 /** Walks a Bitbucket cursor to its end and combines every decoded item. */
464 const itemPages = <A>(input: {
465 readonly operation: string;
466 readonly url: string;
467 readonly decode: (
468 body: string,
469 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
470 readonly items: ReadonlyArray<A>;
471 /** Commit pages are individually oldest-first, so older pages are prepended. */
472 readonly prepend: boolean;
473 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
474 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
475 Effect.flatMap((page) => {
476 const items = input.prepend
477 ? [...page.items, ...input.items]
478 : [...input.items, ...page.items];
479 return page.next === null
480 ? Effect.succeed(items)
481 : itemPages({ ...input, url: page.next, items });
482 }),
483 );
484
485 /** Diffstat has one aggregate per page, so its totals are folded while following `next`. */
486 const diffStatPages = (input: {
487 readonly url: string;
488 readonly totals: BitbucketDiffStat;
489 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
490 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
491 Effect.flatMap((page) => {
492 const totals = {
493 additions: input.totals.additions + page.additions,
494 deletions: input.totals.deletions + page.deletions,
495 changedFiles: input.totals.changedFiles + page.changedFiles,
496 };
497 return page.next === null
498 ? Effect.succeed(totals)
499 : diffStatPages({ url: page.next, totals });
500 }),
501 );
502
503 return BitbucketPullRequestApi.of({
504 getViewer: () =>
505 bitbucket.request({ method: "GET", url: "/user" }).pipe(
506 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
507 const decoded = decodeViewerJson(response.body);
508 if (!Result.isSuccess(decoded)) {
509 return Effect.fail(
510 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
511 );
512 }
513 return decoded.success === null
514 ? Effect.fail(new BitbucketViewerUnavailableError())
515 : Effect.succeed(decoded.success);
516 }),
517 ),
518
519 listPullRequests: (input) =>
520 withRepository(input.repository, (path) => {
521 const search = input.query?.trim() ?? "";
522 // Both narrowings share the one `q` Bitbucket takes, so they are ANDed rather than one
523 // replacing the other. The boundary instant is read inclusively — the rows already sent
524 // at it come back and the caller drops them, which is what keeps their neighbours at the
525 // same instant from being skipped. A date is a bare literal in this grammar, and this one
526 // was checked against a timestamp's shape before it got here.
527 const predicates = [
528 ...(search.length === 0 ? [] : [searchFilter(search)]),
529 ...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
530 ];
531 return listPage({
532 // Reviewers are not on a listing by default, and `viewerReviewRequested` needs them.
533 url: `${path}/pullrequests?${stateParams(input.state)
534 .map((state) => `state=${state}`)
535 .join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
536 predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
537 }`,
538 limit: input.limit,
539 page: 1,
540 collected: [],
541 });
542 }),
543
544 getPullRequest: (input) =>
545 withRepository(input.repository, (path) =>
546 readPage({
547 operation: "getPullRequest",
548 url: `${path}/pullrequests/${input.number}`,
549 decode: decodePullRequestJson,
550 }),
551 ),
552
553 // Nothing on the repository, the pull request or the workspace states what the credentials
554 // may do, so this endpoint is the one request Bitbucket makes unavoidable. It is asked
555 // alongside the reads the detail was already making, so it costs no round trip of its own.
556 getRepositoryPermission: (input) =>
557 withRepository(input.repository, () =>
558 readPage({
559 operation: "getRepositoryPermission",
560 url: `/user/permissions/repositories?q=${encodeURIComponent(
561 `repository.full_name="${filterLiteral(input.repository.trim())}"`,
562 )}`,
563 decode: decodeRepositoryPermissionJson,
564 }),
565 ),
566
567 getPullRequestDiff: (input) =>
568 input.commit !== undefined && !isCommitSha(input.commit)
569 ? Effect.fail(new BitbucketDiffCommitError())
570 : withRepository(input.repository, (path) =>
571 // Already a unified patch, so it needs no decoding at all — only a bound, which a
572 // diff of any size would otherwise ignore. A commit's own patch sits beside the pull
573 // request's at `/diff/{sha}` and reads the same way.
574 bitbucket
575 .request({
576 method: "GET",
577 url:
578 input.commit === undefined
579 ? `${path}/pullrequests/${input.number}/diff`
580 : `${path}/diff/${input.commit}`,
581 maxBytes: DIFF_MAX_BYTES,
582 })
583 .pipe(
584 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
585 ),
586 ),
587
588 getDiffStat: (input) =>
589 withRepository(input.repository, (path) =>
590 diffStatPages({
591 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
592 totals: { additions: 0, deletions: 0, changedFiles: 0 },
593 }),
594 ),
595
596 getMergeability: (input) =>
597 withRepository(input.repository, (path) =>
598 readPage({
599 operation: "getMergeability",
600 url: `${path}/pullrequests/${input.number}/conflicts`,
601 decode: decodeConflictsJson,
602 }),
603 ),
604
605 listComments: (input) =>
606 withRepository(input.repository, (path) =>
607 commentsPage({
608 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
609 page: 1,
610 comments: [],
611 entries: [],
612 }),
613 ),
614
615 listCommits: (input) =>
616 withRepository(input.repository, (path) =>
617 itemPages({
618 operation: "listCommits",
619 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
620 decode: decodeCommitsJson,
621 items: [],
622 prepend: true,
623 }),
624 ),
625
626 listChecks: (input) =>
627 withRepository(input.repository, (path) =>
628 itemPages({
629 operation: "listChecks",
630 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
631 decode: decodeStatusesJson,
632 items: [],
633 prepend: false,
634 }),
635 ),
636
637 listReviewerCandidates: (input) =>
638 withRepository(input.repository, (path, workspace) =>
639 Effect.all(
640 [
641 readPage({
642 operation: "getPullRequest",
643 url: `${path}/pullrequests/${input.number}`,
644 decode: decodePullRequestJson,
645 }),
646 readPage({
647 operation: "listReviewerCandidates",
648 url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
649 decode: decodeWorkspaceMembersJson,
650 }),
651 ],
652 { concurrency: 2 },
653 ).pipe(
654 Effect.map(([pullRequest, members]) => {
655 const requested = new Set(pullRequest.reviewerIds);
656 const author = pullRequest.author?.login;
657 return {
658 // The author is dropped rather than shown unusable: Bitbucket refuses to make the
659 // person who opened a pull request its reviewer.
660 candidates: members.items.flatMap((candidate) =>
661 candidate.login === author
662 ? []
663 : [{ ...candidate, isRequested: requested.has(candidate.id) }],
664 ),
665 truncated: members.next !== null,
666 };
667 }),
668 ),
669 ),
670
671 setReviewerRequest: (input) =>
672 withRepository(input.repository, (path) => {
673 const pullRequest = `${path}/pullrequests/${input.number}`;
674 return readPage({
675 operation: "getPullRequest",
676 url: pullRequest,
677 decode: decodePullRequestJson,
678 }).pipe(
679 Effect.flatMap((current) => {
680 // Bitbucket has no endpoint that adds or removes one reviewer: the pull request's
681 // `reviewers` is written whole, so the set that is already there is read first and
682 // the change applied to it. Everything else about the pull request is left out of
683 // the body, which leaves it as it was.
684 const uuids = new Set(current.reviewerIds);
685 for (const reviewer of input.reviewers) {
686 if (input.requested) uuids.add(reviewer.id);
687 else uuids.delete(reviewer.id);
688 }
689 return bitbucket.request({
690 method: "PUT",
691 url: pullRequest,
692 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
693 });
694 }),
695 Effect.asVoid,
696 );
697 }),
698
699 runAction: (input) =>
700 withRepository(input.repository, (path) => {
701 const pullRequest = `${path}/pullrequests/${input.number}`;
702 // Only merge and close reach here: the provider declares the others unsupported, so the
703 // surface never offers them.
704 if (input.action === "merge") {
705 return bitbucket
706 .request({
707 method: "POST",
708 url: `${pullRequest}/merge`,
709 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
710 })
711 .pipe(Effect.asVoid);
712 }
713 return bitbucket
714 .request({ method: "POST", url: `${pullRequest}/decline` })
715 .pipe(Effect.asVoid);
716 }),
717
718 updateChangeRequest: (input) =>
719 withRepository(input.repository, (path) =>
720 // Only the words this call rewrites travel in the body: as `setReviewerRequest` above
721 // relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
722 // was — sending `reviewers` back here would overwrite a change another user made to it
723 // between this call being issued and the request landing.
724 bitbucket
725 .request({
726 method: "PUT",
727 url: `${path}/pullrequests/${input.number}`,
728 body: JSON.stringify({
729 ...(input.title === undefined ? {} : { title: input.title }),
730 ...(input.body === undefined ? {} : { description: input.body }),
731 }),
732 })
733 .pipe(Effect.asVoid),
734 ),
735
736 comment: (input) =>
737 withRepository(input.repository, (path) =>
738 bitbucket
739 .request({
740 method: "POST",
741 url: `${path}/pullrequests/${input.number}/comments`,
742 // A JSON document rather than a form field, so the body stays text whatever it says.
743 body: JSON.stringify({ content: { raw: input.body } }),
744 })
745 .pipe(Effect.asVoid),
746 ),
747
748 updateComment: (input) =>
749 withRepository(input.repository, (path) =>
750 bitbucket
751 .request({
752 // Bitbucket keeps a pull request's remarks and its line comments in the one
753 // collection, so this endpoint rewrites either kind.
754 method: "PUT",
755 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
756 input.commentId,
757 )}`,
758 body: JSON.stringify({ content: { raw: input.body } }),
759 })
760 .pipe(Effect.asVoid),
761 ),
762
763 submitReview: (input) =>
764 withRepository(input.repository, (path) =>
765 Effect.gen(function* () {
766 const pullRequest = `${path}/pullrequests/${input.number}`;
767 // Bitbucket has no pending review, so a review is replayed as the requests it is
768 // made of: the line comments, then the summary, then the verdict. The verdict goes
769 // last so a review that fails part-way is never left standing as an approval.
770 yield* Effect.forEach(
771 input.comments,
772 (comment) =>
773 bitbucket.request({
774 method: "POST",
775 url: `${pullRequest}/comments`,
776 body: JSON.stringify({
777 content: { raw: comment.body },
778 inline: {
779 path: comment.path,
780 ...(comment.side === "left" ? { from: comment.line } : { to: comment.line }),
781 },
782 }),
783 }),
784 { discard: true },
785 );
786 if (input.body.trim().length > 0) {
787 yield* bitbucket.request({
788 method: "POST",
789 url: `${pullRequest}/comments`,
790 // @effect-diagnostics-next-line preferSchemaOverJson:off
791 body: JSON.stringify({ content: { raw: input.body } }),
792 });
793 }
794 if (input.verdict === "approve") {
795 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
796 }
797 if (input.verdict === "request-changes") {
798 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
799 }
800 }),
801 ),
802
803 replyToComment: (input) =>
804 withRepository(input.repository, (path) =>
805 bitbucket
806 .request({
807 method: "POST",
808 url: `${path}/pullrequests/${input.number}/comments`,
809 body: JSON.stringify({
810 content: { raw: input.body },
811 parent: { id: Number(input.commentId) },
812 }),
813 })
814 .pipe(Effect.asVoid),
815 ),
816
817 setCommentResolution: (input) =>
818 withRepository(input.repository, (path) =>
819 bitbucket
820 .request({
821 // Resolving is a sub-resource that is created and deleted, rather than a field.
822 method: input.resolved ? "POST" : "DELETE",
823 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
824 input.commentId,
825 )}/resolve`,
826 })
827 .pipe(Effect.asVoid),
828 ),
829 });
830});
831
832export const layer = Layer.effect(BitbucketPullRequestApi, make);