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