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

BitbucketPullRequestApi.ts

932 lines33.3 KB

1import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils";
2import * as Cache from "effect/Cache";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Result from "effect/Result";
11import * as Schema from "effect/Schema";
12import type {
13 PullRequestAction,
14 PullRequestCheck,
15 PullRequestComment,
16 PullRequestCommit,
17 PullRequestListState,
18 PullRequestMergeMethod,
19 PullRequestMergeability,
20 PullRequestReviewCommentDraft,
21 PullRequestReviewPosition,
22 PullRequestReviewThread,
23 PullRequestReviewVerdict,
24 PullRequestReviewerCandidateList,
25} from "@t3tools/contracts";
26​
27import * as BitbucketApi from "./BitbucketApi.ts";
28import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
29import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
30import {
31 buildReviewThreads,
32 decodeCommentsJson,
33 decodeCommitsJson,
34 decodeConflictsJson,
35 decodeDiffstatJson,
36 decodePullRequestJson,
37 decodePullRequestPageJson,
38 decodeRepositoryPermissionJson,
39 decodeStatusesJson,
40 decodeViewerAccountJson,
41 decodeViewerJson,
42 decodeWorkspaceMembersJson,
43 type BitbucketDiffStat,
44 type BitbucketPullRequest,
45 type BitbucketRawComment,
46} from "./bitbucketPullRequestJson.ts";
47import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
48​
49export class BitbucketPullRequestReadError extends Schema.TaggedError<BitbucketPullRequestReadError>()(
50 "BitbucketPullRequestReadError",
51 {
52 operation: Schema.String,
53 cause: Schema.Defect(),
54 },
55) {
56 get detail(): string {
57 return `Bitbucket returned an unreadable ${this.operation} response.`;
58 }
59​
60 override get message(): string {
61 return `Bitbucket failed in ${this.operation}: ${this.detail}`;
62 }
64​
65export class BitbucketViewerUnavailableError extends Schema.TaggedError<BitbucketViewerUnavailableError>()(
66 "BitbucketViewerUnavailableError",
67 {},
68) {
69 get detail(): string {
70 return "Bitbucket returned no account name for the configured credentials.";
71 }
72​
73 override get message(): string {
74 return `Bitbucket failed in getViewer: ${this.detail}`;
75 }
77​
78export class BitbucketRepositoryUnsupportedError extends Schema.TaggedError<BitbucketRepositoryUnsupportedError>()(
79 "BitbucketRepositoryUnsupportedError",
80 {
81 repository: Schema.String,
82 },
83) {
84 get detail(): string {
85 return "A Bitbucket repository is addressed as workspace/repository.";
86 }
87​
88 override get message(): string {
89 return `Bitbucket failed in resolveRepository: ${this.detail}`;
90 }
92​
93export class BitbucketDiffCommitError extends Schema.TaggedError<BitbucketDiffCommitError>()(
94 "BitbucketDiffCommitError",
95 {},
96) {
97 get detail(): string {
98 return "The named commit was not a commit sha.";
99 }
100​
101 override get message(): string {
102 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
103 }
105​
106export type BitbucketPullRequestApiError =
107 | BitbucketApi.BitbucketApiError
108 | BitbucketPullRequestReadError
109 | BitbucketViewerUnavailableError
110 | BitbucketRepositoryUnsupportedError
111 | BitbucketDiffCommitError;
112​
113function isRepositoryPermissionUnavailableError(
114 error: BitbucketPullRequestApiError,
115): error is BitbucketApi.BitbucketResponseError {
116 return (
117 error._tag === "BitbucketResponseError" &&
118 (error.status === 403 || error.status === 404 || error.status === 410)
119 );
121​
122/** Requests above this size return an empty page without an error. */
123const MAX_PAGE_SIZE = 50;
124const MAX_LIST_PAGES = 10;
125const CONVERSATION_PAGE_SIZE = 50;
126const CONVERSATION_PAGES = 10;
127const DIFF_MAX_BYTES = 8 * 1024 * 1024;
128/** Must expire before the caller's version cache so refreshes reach Bitbucket. */
129const REVISION_PATCH_TTL = Duration.seconds(5);
130const REVISION_PATCH_CAPACITY = 16;
131/** The members endpoint has no search, so a reviewer query reuses one walk of every page. */
132const WORKSPACE_MEMBERS_TTL = Duration.minutes(1);
133const WORKSPACE_MEMBERS_CAPACITY = 4;
134const encodeMembersKey = Schema.encodeSync(
135 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),
136);
137const encodeRevisionKey = Schema.encodeSync(
138 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Number])),
139);
140export interface BitbucketPullRequestBatch {
141 readonly items: ReadonlyArray<BitbucketPullRequest>;
142 readonly truncated: boolean;
144​
145export class BitbucketPullRequestApi extends Context.Service<
146 BitbucketPullRequestApi,
147 {
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 readonly query?: string | undefined;
155 readonly cursor?: ProviderListCursor | undefined;
156 /** Matched against the login a row shows, which is the nickname or else the display name. */
157 readonly author?: string | undefined;
158 readonly draft?: boolean | undefined;
159 }) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
160​
161 readonly getPullRequest: (input: {
162 readonly repository: string;
163 readonly number: number;
164 }) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
165​
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 readonly commit?: string | undefined;
174 }) => Effect.Effect<
175 { readonly patch: string; readonly truncated: boolean },
176 BitbucketPullRequestApiError
177 >;
178​
179 readonly getDiffStat: (input: {
180 readonly repository: string;
181 readonly number: number;
182 }) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;
183​
184 /** Truncated patches cannot identify absent paths as deleted. */
185 readonly getFileRevisions: (input: {
186 readonly repository: string;
187 readonly number: number;
188 readonly paths: ReadonlyArray<string>;
189 }) => Effect.Effect<
190 { readonly revisions: ReadonlyMap<string, string>; readonly complete: boolean },
191 BitbucketPullRequestApiError
192 >;
193​
194 readonly getMergeability: (input: {
195 readonly repository: string;
196 readonly number: number;
197 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
198​
199 readonly listComments: (input: {
200 readonly repository: string;
201 readonly number: number;
202 }) => Effect.Effect<
203 {
204 readonly comments: ReadonlyArray<PullRequestComment>;
205 readonly threads: ReadonlyArray<PullRequestReviewThread>;
206 readonly truncated: boolean;
207 },
208 BitbucketPullRequestApiError
209 >;
210​
211 readonly listCommits: (input: {
212 readonly repository: string;
213 readonly number: number;
214 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
215​
216 readonly listChecks: (input: {
217 readonly repository: string;
218 readonly number: number;
219 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
220​
221 readonly listReviewerCandidates: (input: {
222 readonly repository: string;
223 readonly number: number;
224 readonly query?: string | undefined;
225 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
226​
227 readonly setReviewerRequest: (input: {
228 readonly repository: string;
229 readonly number: number;
230 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
231 readonly requested: boolean;
232 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
233​
234 readonly runAction: (input: {
235 readonly repository: string;
236 readonly number: number;
237 readonly action: PullRequestAction;
238 readonly mergeMethod?: PullRequestMergeMethod;
239 }) => Effect.Effect<BitbucketPullRequest | void, BitbucketPullRequestApiError>;
240​
241 readonly updateChangeRequest: (input: {
242 readonly repository: string;
243 readonly number: number;
244 readonly title?: string | undefined;
245 readonly body?: string | undefined;
246 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
247​
248 readonly comment: (input: {
249 readonly repository: string;
250 readonly number: number;
251 readonly body: string;
252 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
253​
254 readonly updateComment: (input: {
255 readonly repository: string;
256 readonly number: number;
257 readonly commentId: string;
258 readonly body: string;
259 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
260​
261 readonly submitReview: (input: {
262 readonly repository: string;
263 readonly number: number;
264 readonly verdict: PullRequestReviewVerdict;
265 readonly body: string;
266 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
267 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
268​
269 readonly replyToComment: (input: {
270 readonly repository: string;
271 readonly number: number;
272 readonly commentId: string;
273 readonly body: string;
274 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
275​
276 readonly setCommentResolution: (input: {
277 readonly repository: string;
278 readonly number: number;
279 readonly commentId: string;
280 readonly resolved: boolean;
281 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
282 }
283>()("@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi") {}
284​
285function repositorySegments(
286 repository: string,
287): Result.Result<
288 { readonly workspace: string; readonly slug: string },
289 BitbucketRepositoryUnsupportedError
290> {
291 const segments = repository
292 .split("/")
293 .map((segment) => segment.trim())
294 .filter((segment) => segment.length > 0);
295 const [workspace, slug] = segments;
296 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
297 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
298 }
299 return Result.succeed({ workspace, slug });
301​
302function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
303 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
304 segments.slug,
305 )}`;
307​
308function stateParams(state: PullRequestListState): ReadonlyArray<string> {
309 switch (state) {
310 case "open":
311 return ["OPEN"];
312 case "merged":
313 return ["MERGED"];
314 case "closed":
315 return ["DECLINED", "SUPERSEDED"];
316 case "all":
317 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
318 }
320​
321function searchFilter(query: string): string {
322 const literal = filterLiteral(query);
323 return `(title ~ "${literal}" OR description ~ "${literal}")`;
325​
326function authorFilter(login: string): string {
327 const literal = filterLiteral(login);
328 return `(author.nickname = "${literal}" OR author.display_name = "${literal}")`;
330​
331/**
332 * The backslash is escaped first, or escaping the quote would only produce a literal
333 * backslash followed by a live quote.
334 */
335function filterLiteral(value: string): string {
336 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
338​
339// Bitbucket keeps microseconds; include the cursor's whole millisecond before excluding seen IDs.
340function updatedBeforeFilter(updatedBefore: string): string {
341 return Option.match(DateTime.make(updatedBefore), {
342 onNone: () => `updated_on <= ${updatedBefore}`,
343 onSome: (instant) =>
344 `updated_on < ${DateTime.formatIso(DateTime.add(instant, { milliseconds: 1 }))}`,
345 });
347​
348function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
349 switch (method) {
350 case "squash":
351 return "squash";
352 case "rebase":
353 return "rebase_fast_forward";
354 default:
355 return "merge_commit";
356 }
358​
359function bitbucketReviewPosition(
360 position: PullRequestReviewPosition,
361): { readonly from: number } | { readonly to: number } {
362 switch (position.kind) {
363 case "added":
364 return { to: position.newLine };
365 case "deleted":
366 return { from: position.oldLine };
367 case "context":
368 return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };
369 }
371​
372/** @public */
373export const make = Effect.gen(function* () {
374 const bitbucket = yield* BitbucketApi.BitbucketApi;
375​
376 const withRepository = <A>(
377 repository: string,
378 use: (
379 path: string,
380 workspace: string,
381 slug: string,
382 ) => Effect.Effect<A, BitbucketPullRequestApiError>,
383 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
384 const segments = repositorySegments(repository);
385 return Result.isSuccess(segments)
386 ? use(repositoryPathOf(segments.success), segments.success.workspace, segments.success.slug)
387 : Effect.fail(segments.failure);
388 };
389​
390 const listPage = (input: {
391 readonly url: string;
392 readonly limit: number;
393 readonly page: number;
394 readonly collected: ReadonlyArray<BitbucketPullRequest>;
395 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
396 bitbucket.request({ method: "GET", url: input.url }).pipe(
397 Effect.flatMap((response) => {
398 const decoded = decodePullRequestPageJson(response.body);
399 if (!Result.isSuccess(decoded)) {
400 return Effect.fail(
401 new BitbucketPullRequestReadError({
402 operation: "listPullRequests",
403 cause: decoded.failure,
404 }),
405 );
406 }
407 const collected = [...input.collected, ...decoded.success.items];
408 const next = decoded.success.next;
409 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
410 return Effect.succeed({
411 items: collected.slice(0, input.limit),
412 truncated: next !== null || collected.length > input.limit,
413 });
414 }
415 return listPage({ ...input, url: next, page: input.page + 1, collected });
416 }),
417 );
418​
419 const readPage = <A>(input: {
420 readonly operation: string;
421 readonly url: string;
422 readonly decode: (body: string) => Result.Result<A, unknown>;
423 }): Effect.Effect<A, BitbucketPullRequestApiError> =>
424 bitbucket.request({ method: "GET", url: input.url }).pipe(
425 Effect.flatMap((response) => {
426 const decoded = input.decode(response.body);
427 return Result.isSuccess(decoded)
428 ? Effect.succeed(decoded.success)
429 : Effect.fail(
430 new BitbucketPullRequestReadError({
431 operation: input.operation,
432 cause: decoded.failure,
433 }),
434 );
435 }),
436 );
437​
438 /** Replies and parents can span pages; assemble threads after pagination. */
439 const commentsPage = (input: {
440 readonly url: string;
441 readonly page: number;
442 readonly comments: ReadonlyArray<PullRequestComment>;
443 readonly entries: ReadonlyArray<BitbucketRawComment>;
444 }): Effect.Effect<
445 {
446 readonly comments: ReadonlyArray<PullRequestComment>;
447 readonly threads: ReadonlyArray<PullRequestReviewThread>;
448 readonly truncated: boolean;
449 },
450 BitbucketPullRequestApiError
451 > =>
452 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
453 Effect.flatMap((page) => {
454 const comments = [...input.comments, ...page.comments];
455 const entries = [...input.entries, ...page.entries];
456 if (page.next !== null && input.page < CONVERSATION_PAGES) {
457 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
458 }
459 return Effect.succeed({
460 comments,
461 threads: buildReviewThreads(entries),
462 truncated: page.next !== null,
463 });
464 }),
465 );
466​
467 const itemPages = <A>(input: {
468 readonly operation: string;
469 readonly url: string;
470 readonly decode: (
471 body: string,
472 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
473 readonly items: ReadonlyArray<A>;
474 /** Each commit page is oldest-first. */
475 readonly prepend: boolean;
476 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
477 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
478 Effect.flatMap((page) => {
479 const items = input.prepend
480 ? [...page.items, ...input.items]
481 : [...input.items, ...page.items];
482 return page.next === null
483 ? Effect.succeed(items)
484 : itemPages({ ...input, url: page.next, items });
485 }),
486 );
487​
488 const diffStatPages = (input: {
489 readonly url: string;
490 readonly totals: BitbucketDiffStat;
491 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
492 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
493 Effect.flatMap((page) => {
494 const totals = {
495 additions: input.totals.additions + page.additions,
496 deletions: input.totals.deletions + page.deletions,
497 changedFiles: input.totals.changedFiles + page.changedFiles,
498 };
499 return page.next === null
500 ? Effect.succeed(totals)
501 : diffStatPages({ url: page.next, totals });
502 }),
503 );
504​
505 const pullRequestDiff = (input: {
506 readonly repository: string;
507 readonly number: number;
508 readonly commit?: string | undefined;
509 }): Effect.Effect<
510 { readonly patch: string; readonly truncated: boolean },
511 BitbucketPullRequestApiError
512 > =>
513 input.commit !== undefined && !isCommitSha(input.commit)
514 ? Effect.fail(new BitbucketDiffCommitError())
515 : withRepository(input.repository, (path) =>
516 bitbucket
517 .request({
518 method: "GET",
519 url:
520 input.commit === undefined
521 ? `${path}/pullrequests/${input.number}/diff`
522 : `${path}/diff/${input.commit}`,
523 maxBytes: DIFF_MAX_BYTES,
524 })
525 .pipe(
526 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
527 ),
528 );
529​
530 // Cache revisions, not large patch bodies that need reparsing.
531 const revisionPatches = yield* Cache.makeWith(
532 (key: string) => {
533 const [repository, number] = JSON.parse(key) as [string, number];
534 return pullRequestDiff({ repository, number }).pipe(
535 Effect.map((diff) => ({
536 revisions: parseDiffFileRevisions(diff.patch),
537 truncated: diff.truncated,
538 })),
539 );
540 },
541 {
542 capacity: REVISION_PATCH_CAPACITY,
543 timeToLive: (exit) => (Exit.isSuccess(exit) ? REVISION_PATCH_TTL : Duration.zero),
544 },
545 );
546​
547 const membersUrl = (workspace: string) =>
548 `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`;
549​
550 const readViewer = (decode: typeof decodeViewerJson) =>
551 Effect.suspend(() => bitbucket.request({ method: "GET", url: "/user" })).pipe(
552 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
553 const decoded = decode(response.body);
554 if (!Result.isSuccess(decoded)) {
555 return Effect.fail(
556 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
557 );
558 }
559 return decoded.success === null
560 ? Effect.fail(new BitbucketViewerUnavailableError())
561 : Effect.succeed(decoded.success);
562 }),
563 );
564 const viewer = readViewer(decodeViewerJson);
565 const viewerAccount = readViewer(decodeViewerAccountJson);
566​
567 const allMembers = (workspace: string) =>
568 itemPages({
569 operation: "listReviewerCandidates",
570 url: membersUrl(workspace),
571 decode: decodeWorkspaceMembersJson,
572 items: [],
573 prepend: false,
574 });
575​
576 // Keyed by account too: credentials can change while the server runs.
577 const workspaceMembers = yield* Cache.makeWith(
578 (key: string) => allMembers((JSON.parse(key) as [string, string])[1]),
579 {
580 capacity: WORKSPACE_MEMBERS_CAPACITY,
581 timeToLive: (exit) => (Exit.isSuccess(exit) ? WORKSPACE_MEMBERS_TTL : Duration.zero),
582 },
583 );
584​
585 return BitbucketPullRequestApi.of({
586 getViewer: Effect.fn("BitbucketPullRequestApi.getViewer")(function () {
587 return viewer;
588 }),
589​
590 listPullRequests: Effect.fn("BitbucketPullRequestApi.listPullRequests")(function (input) {
591 return withRepository(input.repository, (path) => {
592 const search = input.query?.trim() ?? "";
593 // Exclude already-sent IDs in the boundary millisecond before applying the page limit.
594 const predicates = [
595 ...(search.length === 0 ? [] : [searchFilter(search)]),
596 ...(input.author === undefined ? [] : [authorFilter(input.author)]),
597 ...(input.draft === undefined ? [] : [`draft = ${input.draft}`]),
598 ...(input.cursor === undefined ? [] : [updatedBeforeFilter(input.cursor.updatedBefore)]),
599 ...(input.cursor?.seenAt ?? []).map((number) => `id != ${number}`),
600 ];
601 return listPage({
602 // Listings omit reviewers needed by `viewerReviewRequested`.
603 url: `${path}/pullrequests?${stateParams(input.state)
604 .map((state) => `state=${state}`)
605 .join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
606 predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
607 }`,
608 limit: input.limit,
609 page: 1,
610 collected: [],
611 });
612 });
613 }),
614​
615 getPullRequest: Effect.fn("BitbucketPullRequestApi.getPullRequest")(function (input) {
616 return withRepository(input.repository, (path) =>
617 readPage({
618 operation: "getPullRequest",
619 // Settlement needs `closed_on`, omitted by default.
620 url: `${path}/pullrequests/${input.number}?fields=%2Bclosed_on`,
621 decode: decodePullRequestJson,
622 }),
623 );
624 }),
625​
626 // Permission endpoints may return 403/404/410 (CHANGE-2770); let writes enforce access.
627 getRepositoryPermission: Effect.fn("BitbucketPullRequestApi.getRepositoryPermission")(
628 function (input) {
629 return withRepository(input.repository, (_path, workspace, slug) =>
630 readPage({
631 operation: "getRepositoryPermission",
632 url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(
633 `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,
634 )}`,
635 decode: decodeRepositoryPermissionJson,
636 }),
637 ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true)));
638 },
639 ),
640​
641 getPullRequestDiff: pullRequestDiff,
642​
643 getFileRevisions: Effect.fn("BitbucketPullRequestApi.getFileRevisions")(function* (input) {
644 if (input.paths.length === 0)
645 return { revisions: new Map<string, string>(), complete: false };
646 return yield* Cache.get(
647 revisionPatches,
648 encodeRevisionKey([input.repository, input.number]),
649 ).pipe(
650 Effect.map((diff) => {
651 const revisions = new Map(diff.revisions);
652 // A truncated patch cannot identify absent paths as deleted.
653 if (!diff.truncated) {
654 for (const path of input.paths) {
655 if (!revisions.has(path)) revisions.set(path, "");
656 }
657 }
658 return { revisions, complete: !diff.truncated };
659 }),
660 );
661 }),
662​
663 getDiffStat: Effect.fn("BitbucketPullRequestApi.getDiffStat")(function (input) {
664 return withRepository(input.repository, (path) =>
665 diffStatPages({
666 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
667 totals: { additions: 0, deletions: 0, changedFiles: 0 },
668 }),
669 );
670 }),
671​
672 getMergeability: Effect.fn("BitbucketPullRequestApi.getMergeability")(function (input) {
673 return withRepository(input.repository, (path) =>
674 readPage({
675 operation: "getMergeability",
676 url: `${path}/pullrequests/${input.number}/conflicts`,
677 decode: decodeConflictsJson,
678 }),
679 );
680 }),
681​
682 listComments: Effect.fn("BitbucketPullRequestApi.listComments")(function (input) {
683 return withRepository(input.repository, (path) =>
684 commentsPage({
685 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
686 page: 1,
687 comments: [],
688 entries: [],
689 }),
690 );
691 }),
692​
693 listCommits: Effect.fn("BitbucketPullRequestApi.listCommits")(function (input) {
694 return withRepository(input.repository, (path) =>
695 itemPages({
696 operation: "listCommits",
697 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
698 decode: decodeCommitsJson,
699 items: [],
700 prepend: true,
701 }),
702 );
703 }),
704​
705 listChecks: Effect.fn("BitbucketPullRequestApi.listChecks")(function (input) {
706 return withRepository(input.repository, (path) =>
707 itemPages({
708 operation: "listChecks",
709 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
710 decode: decodeStatusesJson,
711 items: [],
712 prepend: false,
713 }).pipe(Effect.map(sortChecks)),
714 );
715 }),
716​
717 listReviewerCandidates: Effect.fn("BitbucketPullRequestApi.listReviewerCandidates")(
718 function (input) {
719 const query = input.query?.trim().toLowerCase() ?? "";
720 return withRepository(input.repository, (path, workspace) =>
721 Effect.all(
722 [
723 readPage({
724 operation: "getPullRequest",
725 url: `${path}/pullrequests/${input.number}`,
726 decode: decodePullRequestJson,
727 }),
728 query.length === 0
729 ? readPage({
730 operation: "listReviewerCandidates",
731 url: membersUrl(workspace),
732 decode: decodeWorkspaceMembersJson,
733 })
734 : viewerAccount.pipe(
735 Effect.matchEffect({
736 // Without an account to key the cache by, walk uncached.
737 onFailure: () => allMembers(workspace),
738 onSuccess: (account) =>
739 Cache.get(workspaceMembers, encodeMembersKey([account, workspace])),
740 }),
741 Effect.map((items) => ({ items, next: null })),
742 ),
743 ],
744 { concurrency: 2 },
745 ).pipe(
746 Effect.map(([pullRequest, members]) => {
747 const requested = new Set(pullRequest.reviewerIds);
748 const author = pullRequest.author?.login;
749 return {
750 // Bitbucket forbids requesting a review from the PR author.
751 candidates: members.items.flatMap(({ accountId, ...candidate }) => {
752 if (candidate.login === author) return [];
753 const isRequested = requested.has(candidate.id);
754 // Shown as the login so callers that match logins accept it; writes keep the UUID.
755 if (accountId !== null && accountId.toLowerCase() === query)
756 return [{ ...candidate, login: accountId, isRequested }];
757 return query.length > 0 &&
758 !candidate.login.toLowerCase().includes(query) &&
759 !candidate.name?.toLowerCase().includes(query) &&
760 candidate.id.toLowerCase() !== query
761 ? []
762 : [{ ...candidate, isRequested }];
763 }),
764 truncated: members.next !== null,
765 };
766 }),
767 ),
768 );
769 },
770 ),
771​
772 setReviewerRequest: Effect.fn("BitbucketPullRequestApi.setReviewerRequest")(function (input) {
773 return withRepository(input.repository, (path) => {
774 const pullRequest = `${path}/pullrequests/${input.number}`;
775 return readPage({
776 operation: "getPullRequest",
777 url: pullRequest,
778 decode: decodePullRequestJson,
779 }).pipe(
780 Effect.flatMap((current) => {
781 // Bitbucket replaces the entire reviewer list.
782 const uuids = new Set(current.reviewerIds);
783 for (const reviewer of input.reviewers) {
784 if (input.requested) uuids.add(reviewer.id);
785 else uuids.delete(reviewer.id);
786 }
787 return bitbucket.request({
788 method: "PUT",
789 url: pullRequest,
790 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
791 });
792 }),
793 Effect.asVoid,
794 );
795 });
796 }),
797​
798 runAction: Effect.fn("BitbucketPullRequestApi.runAction")(function (input) {
799 return withRepository(input.repository, (path) => {
800 const pullRequest = `${path}/pullrequests/${input.number}`;
801 // Both reply with the pull request; a merge that runs long replies with a task instead.
802 const reply = Effect.map((response: { readonly body: string }) => {
803 const decoded = decodePullRequestJson(response.body);
804 return Result.isSuccess(decoded) ? decoded.success : undefined;
805 });
806 if (input.action === "merge") {
807 return bitbucket
808 .request({
809 method: "POST",
810 url: `${pullRequest}/merge`,
811 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
812 })
813 .pipe(reply);
814 }
815 return bitbucket.request({ method: "POST", url: `${pullRequest}/decline` }).pipe(reply);
816 });
817 }),
818​
819 updateChangeRequest: Effect.fn("BitbucketPullRequestApi.updateChangeRequest")(function (input) {
820 return withRepository(input.repository, (path) =>
821 // Partial PUTs preserve concurrent edits to unchanged fields.
822 bitbucket
823 .request({
824 method: "PUT",
825 url: `${path}/pullrequests/${input.number}`,
826 body: JSON.stringify({
827 ...(input.title === undefined ? {} : { title: input.title }),
828 ...(input.body === undefined ? {} : { description: input.body }),
829 }),
830 })
831 .pipe(Effect.asVoid),
832 );
833 }),
834​
835 comment: Effect.fn("BitbucketPullRequestApi.comment")(function (input) {
836 return withRepository(input.repository, (path) =>
837 bitbucket
838 .request({
839 method: "POST",
840 url: `${path}/pullrequests/${input.number}/comments`,
841 body: JSON.stringify({ content: { raw: input.body } }),
842 })
843 .pipe(Effect.asVoid),
844 );
845 }),
846​
847 updateComment: Effect.fn("BitbucketPullRequestApi.updateComment")(function (input) {
848 return withRepository(input.repository, (path) =>
849 bitbucket
850 .request({
851 method: "PUT",
852 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
853 input.commentId,
854 )}`,
855 body: JSON.stringify({ content: { raw: input.body } }),
856 })
857 .pipe(Effect.asVoid),
858 );
859 }),
860​
861 submitReview: Effect.fn("BitbucketPullRequestApi.submitReview")(function (input) {
862 return withRepository(input.repository, (path) =>
863 Effect.gen(function* () {
864 const pullRequest = `${path}/pullrequests/${input.number}`;
865 // A partially failed review must not leave an approval.
866 yield* Effect.forEach(
867 input.comments,
868 (comment) =>
869 bitbucket.request({
870 method: "POST",
871 url: `${pullRequest}/comments`,
872 body: JSON.stringify({
873 content: { raw: comment.body },
874 inline: {
875 path: comment.path,
876 ...bitbucketReviewPosition(comment.position),
877 },
878 }),
879 }),
880 { discard: true },
881 );
882 if (input.body.trim().length > 0) {
883 yield* bitbucket.request({
884 method: "POST",
885 url: `${pullRequest}/comments`,
886 // @effect-diagnostics-next-line globalJsonInEffect:off
887 body: JSON.stringify({ content: { raw: input.body } }),
888 });
889 }
890 if (input.verdict === "approve") {
891 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
892 }
893 if (input.verdict === "request-changes") {
894 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
895 }
896 }),
897 );
898 }),
899​
900 replyToComment: Effect.fn("BitbucketPullRequestApi.replyToComment")(function (input) {
901 return withRepository(input.repository, (path) =>
902 bitbucket
903 .request({
904 method: "POST",
905 url: `${path}/pullrequests/${input.number}/comments`,
906 body: JSON.stringify({
907 content: { raw: input.body },
908 parent: { id: Number(input.commentId) },
909 }),
910 })
911 .pipe(Effect.asVoid),
912 );
913 }),
914​
915 setCommentResolution: Effect.fn("BitbucketPullRequestApi.setCommentResolution")(
916 function (input) {
917 return withRepository(input.repository, (path) =>
918 bitbucket
919 .request({
920 method: input.resolved ? "POST" : "DELETE",
921 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
922 input.commentId,
923 )}/resolve`,
924 })
925 .pipe(Effect.asVoid),
926 );
927 },
928 ),
929 });
930});
931​
932export const layer = Layer.effect(BitbucketPullRequestApi, make);