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