Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as DateTime from "effect/DateTime";
3import * as Exit from "effect/Exit";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7import type {
8 PullRequestActor,
9 PullRequestCheck,
10 PullRequestCheckStatus,
11 PullRequestComment,
12 PullRequestCommit,
13 PullRequestMergeability,
14 PullRequestReviewThread,
15 PullRequestReviewerCandidate,
16 PullRequestState,
17} from "@t3tools/contracts";
18import { TrimmedNonEmptyString } from "@t3tools/contracts";
19import { decodeJsonResult } from "@t3tools/shared/schemaJson";
20
21import { dedupeChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
22
23/**
24 * Bitbucket's enums are decoded as plain strings and normalized here, in the same tolerant
25 * style as the GitHub and GitLab decoders: a new pull request state or build status must not
26 * fail a whole payload.
27 */
28const RawUserSchema = Schema.Struct({
29 /**
30 * How Bitbucket addresses an account when a reviewer set is written; the handles it shows are
31 * not accepted there. Braced, and sent back exactly as it arrived.
32 */
33 uuid: Schema.optional(Schema.NullOr(Schema.String)),
34 /** Absent on an app account, which is why `display_name` has to stand in for it. */
35 nickname: Schema.optional(Schema.NullOr(Schema.String)),
36 display_name: Schema.optional(Schema.NullOr(Schema.String)),
37 links: Schema.optional(
38 Schema.NullOr(
39 Schema.Struct({
40 avatar: Schema.optional(
41 Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
42 ),
43 }),
44 ),
45 ),
46});
47
48/**
49 * Required, and required to be non-empty: the wire contract will not carry a change request
50 * without a branch or a link, so a row missing one is skipped rather than breaking the response
51 * it travels in.
52 */
53const RawBranchSchema = Schema.Struct({
54 branch: Schema.Struct({ name: TrimmedNonEmptyString }),
55 commit: Schema.optional(
56 Schema.NullOr(Schema.Struct({ hash: Schema.optional(Schema.NullOr(Schema.String)) })),
57 ),
58 repository: Schema.optional(Schema.NullOr(Schema.Struct({ full_name: TrimmedNonEmptyString }))),
59});
60
61const RawLinkSchema = Schema.Struct({ href: Schema.optional(Schema.String) });
62
63const RawPullRequestSchema = Schema.Struct({
64 id: Schema.Int,
65 title: Schema.String,
66 description: Schema.optional(Schema.NullOr(Schema.String)),
67 state: Schema.optional(Schema.NullOr(Schema.String)),
68 draft: Schema.optional(Schema.Boolean),
69 author: Schema.optional(Schema.NullOr(RawUserSchema)),
70 source: RawBranchSchema,
71 destination: RawBranchSchema,
72 created_on: Schema.String,
73 updated_on: Schema.String,
74 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
75 participants: Schema.optional(
76 Schema.NullOr(
77 Schema.Array(
78 Schema.Struct({
79 user: Schema.optional(Schema.NullOr(RawUserSchema)),
80 role: Schema.optional(Schema.NullOr(Schema.String)),
81 approved: Schema.optional(Schema.Boolean),
82 state: Schema.optional(Schema.NullOr(Schema.String)),
83 participated_on: Schema.optional(Schema.NullOr(Schema.String)),
84 }),
85 ),
86 ),
87 ),
88 links: Schema.Struct({ html: Schema.Struct({ href: TrimmedNonEmptyString }) }),
89});
90
91const RawPageSchema = Schema.Struct({
92 values: Schema.Array(Schema.Unknown),
93 /** A total count, which Bitbucket omits on some endpoints. */
94 size: Schema.optional(Schema.NullOr(Schema.Int)),
95 /** Present only while a further page exists. */
96 next: Schema.optional(Schema.NullOr(Schema.String)),
97});
98
99const RawCommentSchema = Schema.Struct({
100 id: Schema.Int,
101 content: Schema.optional(Schema.NullOr(Schema.Struct({ raw: Schema.optional(Schema.String) }))),
102 user: Schema.optional(Schema.NullOr(RawUserSchema)),
103 created_on: Schema.String,
104 deleted: Schema.optional(Schema.Boolean),
105 /** A comment still being drafted by its author. */
106 pending: Schema.optional(Schema.Boolean),
107 /** Set on a reply, to the comment it answers — which may itself be a reply. */
108 parent: Schema.optional(Schema.NullOr(Schema.Struct({ id: Schema.Int }))),
109 inline: Schema.optional(
110 Schema.NullOr(
111 Schema.Struct({
112 path: Schema.optional(Schema.NullOr(Schema.String)),
113 /** The line in the file as it was; set instead of `to` on a removed line. */
114 from: Schema.optional(Schema.NullOr(Schema.Int)),
115 /** The line in the file as it is now. */
116 to: Schema.optional(Schema.NullOr(Schema.Int)),
117 outdated: Schema.optional(Schema.NullOr(Schema.Boolean)),
118 }),
119 ),
120 ),
121 /** Non-null once someone has marked the thread resolved. */
122 resolution: Schema.optional(Schema.NullOr(Schema.Unknown)),
123 links: Schema.optional(
124 Schema.NullOr(Schema.Struct({ html: Schema.optional(Schema.NullOr(RawLinkSchema)) })),
125 ),
126});
127
128const RawCommitSchema = Schema.Struct({
129 hash: TrimmedNonEmptyString,
130 message: Schema.optional(Schema.NullOr(Schema.String)),
131 date: Schema.optional(Schema.NullOr(Schema.String)),
132 author: Schema.optional(
133 Schema.NullOr(
134 Schema.Struct({
135 raw: Schema.optional(Schema.NullOr(Schema.String)),
136 user: Schema.optional(Schema.NullOr(RawUserSchema)),
137 }),
138 ),
139 ),
140});
141
142const RawStatusSchema = Schema.Struct({
143 key: Schema.optional(Schema.NullOr(Schema.String)),
144 name: Schema.optional(Schema.NullOr(Schema.String)),
145 state: Schema.optional(Schema.NullOr(Schema.String)),
146 description: Schema.optional(Schema.NullOr(Schema.String)),
147 url: Schema.optional(Schema.NullOr(Schema.String)),
148});
149
150const RawDiffstatSchema = Schema.Struct({
151 lines_added: Schema.optional(Schema.NullOr(Schema.Int)),
152 lines_removed: Schema.optional(Schema.NullOr(Schema.Int)),
153});
154
155/** One row of `/workspaces/{workspace}/members`, which wraps the account it is about. */
156const RawMemberSchema = Schema.Struct({
157 user: Schema.optional(Schema.NullOr(RawUserSchema)),
158});
159
160const RawViewerSchema = Schema.Struct({
161 nickname: Schema.optional(Schema.NullOr(Schema.String)),
162 display_name: Schema.optional(Schema.NullOr(Schema.String)),
163});
164
165/**
166 * `/user/permissions/repositories` filtered to one repository, which is the only place Bitbucket
167 * states what the credentials may do with it: nothing on the repository, the pull request or the
168 * workspace carries it. One row, or none where Bitbucket names no permission for this account.
169 */
170const RawRepositoryPermissionsSchema = Schema.Struct({
171 values: Schema.optional(
172 Schema.NullOr(
173 Schema.Array(Schema.Struct({ permission: Schema.optional(Schema.NullOr(Schema.String)) })),
174 ),
175 ),
176});
177
178export interface BitbucketPullRequest {
179 readonly number: number;
180 readonly title: string;
181 readonly url: string;
182 readonly author: PullRequestActor | null;
183 readonly headBranch: string;
184 readonly headSha: string | null;
185 readonly headRepositoryNameWithOwner: string | null;
186 readonly baseBranch: string;
187 readonly state: PullRequestState;
188 readonly isDraft: boolean;
189 /**
190 * Bitbucket reports no conflict state on a pull request, so the list leaves it unknown. The
191 * detail read asks the conflicts endpoint, which does answer.
192 */
193 readonly mergeability: PullRequestMergeability;
194 readonly createdAt: string;
195 readonly updatedAt: string;
196 readonly body: string;
197 readonly reviewRequestLogins: ReadonlyArray<string>;
198 readonly reviewers: ReadonlyArray<PullRequestActor>;
199 /** The reviewers as Bitbucket addresses them, which is what writing the set back takes. */
200 readonly reviewerIds: ReadonlyArray<string>;
201 /** Approvals and change requests, which Bitbucket keeps on its participants. */
202 readonly reviews: ReadonlyArray<PullRequestComment>;
203}
204
205function trimmed(value: string | null | undefined): string | null {
206 const text = value?.trim() ?? "";
207 return text.length > 0 ? text : null;
208}
209
210/**
211 * Bitbucket stamps times as `+00:00` with microseconds. The page sorts change requests from
212 * every host against each other as plain strings, so they are normalized to the same `Z` form
213 * the other hosts already use.
214 */
215function toIsoUtc(value: string): string {
216 return Option.match(DateTime.make(value), {
217 onNone: () => value,
218 onSome: DateTime.formatIso,
219 });
220}
221
222/** An app account has no nickname, so the display name is the only handle it has. */
223function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
224 const login = trimmed(raw?.nickname) ?? trimmed(raw?.display_name);
225 return login === null
226 ? null
227 : {
228 login,
229 name: trimmed(raw?.display_name),
230 avatarUrl: trimmed(raw?.links?.avatar?.href),
231 };
232}
233
234function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
235 switch (raw.state?.trim().toUpperCase()) {
236 case "MERGED":
237 return "merged";
238 case "DECLINED":
239 case "SUPERSEDED":
240 return "closed";
241 default:
242 return "open";
243 }
244}
245
246function toBuildStatus(value: string | null | undefined): PullRequestCheckStatus {
247 switch (value?.trim().toUpperCase()) {
248 case "SUCCESSFUL":
249 return "success";
250 case "FAILED":
251 return "failure";
252 case "STOPPED":
253 return "cancelled";
254 case "INPROGRESS":
255 return "pending";
256 default:
257 return "neutral";
258 }
259}
260
261/**
262 * A participant who has voted is the closest Bitbucket has to a review, so it reads as one in
263 * the conversation. Participants who have only been added carry no verdict and are skipped.
264 */
265function toReviews(
266 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
267): ReadonlyArray<PullRequestComment> {
268 return (raw.participants ?? []).flatMap((participant): ReadonlyArray<PullRequestComment> => {
269 const author = toActor(participant.user);
270 const votedAt = trimmed(participant.participated_on);
271 const reviewState =
272 trimmed(participant.state) ?? (participant.approved === true ? "approved" : null);
273 if (author === null || votedAt === null || reviewState === null) return [];
274 return [
275 {
276 id: `${raw.id}:${author.login}`,
277 kind: "review",
278 author,
279 body: "",
280 createdAt: toIsoUtc(votedAt),
281 url: null,
282 path: null,
283 reviewState,
284 },
285 ];
286 });
287}
288
289function toPullRequest(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): BitbucketPullRequest {
290 const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
291 const actor = toActor(reviewer);
292 return actor === null ? [] : [actor];
293 });
294 return {
295 number: raw.id,
296 title: raw.title,
297 url: raw.links.html.href,
298 author: toActor(raw.author),
299 headBranch: raw.source.branch.name,
300 headSha: trimmed(raw.source.commit?.hash),
301 headRepositoryNameWithOwner: raw.source.repository?.full_name ?? null,
302 baseBranch: raw.destination.branch.name,
303 state: toState(raw),
304 isDraft: raw.draft ?? false,
305 mergeability: "unknown",
306 createdAt: toIsoUtc(raw.created_on),
307 updatedAt: toIsoUtc(raw.updated_on),
308 body: raw.description ?? "",
309 reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
310 reviewers,
311 reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) => trimmed(reviewer.uuid) ?? []),
312 reviews: toReviews(raw),
313 };
314}
315
316const decodePage = decodeJsonResult(RawPageSchema);
317const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
318const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
319const decodeCommentEntry = Schema.decodeUnknownExit(RawCommentSchema);
320const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
321const decodeStatusEntry = Schema.decodeUnknownExit(RawStatusSchema);
322const decodeDiffstatEntry = Schema.decodeUnknownExit(RawDiffstatSchema);
323const decodeMemberEntry = Schema.decodeUnknownExit(RawMemberSchema);
324const decodeViewer = decodeJsonResult(RawViewerSchema);
325const decodeConflicts = decodeJsonResult(RawPageSchema);
326const decodeRepositoryPermissions = decodeJsonResult(RawRepositoryPermissionsSchema);
327
328type DecodeFailure = Cause.Cause<Schema.SchemaError>;
329
330export interface BitbucketPage<A> {
331 readonly items: ReadonlyArray<A>;
332 /** The whole URL of the next page, which Bitbucket sends rather than an offset. */
333 readonly next: string | null;
334}
335
336/** Malformed entries are skipped rather than failing the page, as on the other hosts. */
337export function decodePullRequestPageJson(
338 raw: string,
339): Result.Result<BitbucketPage<BitbucketPullRequest>, DecodeFailure> {
340 const decoded = decodePage(raw);
341 if (!Result.isSuccess(decoded)) {
342 return Result.fail(decoded.failure);
343 }
344 const items: BitbucketPullRequest[] = [];
345 for (const entry of decoded.success.values) {
346 const item = decodePullRequestEntry(entry);
347 if (Exit.isSuccess(item)) {
348 items.push(toPullRequest(item.value));
349 }
350 }
351 return Result.succeed({ items, next: trimmed(decoded.success.next) });
352}
353
354export function decodePullRequestJson(
355 raw: string,
356): Result.Result<BitbucketPullRequest, DecodeFailure> {
357 const decoded = decodePullRequest(raw);
358 return Result.isSuccess(decoded)
359 ? Result.succeed(toPullRequest(decoded.success))
360 : Result.fail(decoded.failure);
361}
362
363export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
364 const decoded = decodeViewer(raw);
365 return Result.isSuccess(decoded)
366 ? Result.succeed(trimmed(decoded.success.nickname) ?? trimmed(decoded.success.display_name))
367 : Result.fail(decoded.failure);
368}
369
370/**
371 * Whether the configured credentials can write to the repository, which is what merging needs.
372 * Bitbucket answers `admin`, `write` or `read`, and an empty page means it named no permission at
373 * all for this account — an unknown standing, which is granted rather than guessed away.
374 */
375export function decodeRepositoryPermissionJson(raw: string): Result.Result<boolean, DecodeFailure> {
376 const decoded = decodeRepositoryPermissions(raw);
377 if (!Result.isSuccess(decoded)) {
378 return Result.fail(decoded.failure);
379 }
380 const permission = trimmed(decoded.success.values?.[0]?.permission)?.toLowerCase() ?? null;
381 return Result.succeed(permission === null || permission === "admin" || permission === "write");
382}
383
384/**
385 * The workspace's members, which is the nearest thing Bitbucket has to "who may review this".
386 * Nothing on a repository lists the people with access to it — `permissions-config/users` is for
387 * administrators only — and a pull request can be sent to anyone in the workspace, so this is the
388 * list Bitbucket's own reviewer field is filled from too.
389 *
390 * Nobody is marked requested here: who has been asked lives on the pull request, and only the
391 * caller holds both.
392 */
393export function decodeWorkspaceMembersJson(
394 raw: string,
395): Result.Result<BitbucketPage<PullRequestReviewerCandidate>, DecodeFailure> {
396 const decoded = decodePage(raw);
397 if (!Result.isSuccess(decoded)) {
398 return Result.fail(decoded.failure);
399 }
400 const items: PullRequestReviewerCandidate[] = [];
401 for (const entry of decoded.success.values) {
402 const member = decodeMemberEntry(entry);
403 if (Exit.isFailure(member)) continue;
404 const uuid = trimmed(member.value.user?.uuid);
405 const actor = toActor(member.value.user);
406 if (uuid === null || actor === null) continue;
407 items.push({ ...actor, id: uuid, kind: "user", isRequested: false });
408 }
409 return Result.succeed({ items, next: trimmed(decoded.success.next) });
410}
411
412/** One comment as Bitbucket sent it, kept so threads can be assembled across pages. */
413export type BitbucketRawComment = Schema.Schema.Type<typeof RawCommentSchema>;
414
415export interface BitbucketComments {
416 readonly comments: ReadonlyArray<PullRequestComment>;
417 /**
418 * The same comments unread, for `buildReviewThreads`. A reply and the remark it answers can
419 * land on different pages, and only the caller holding every page can put them together.
420 */
421 readonly entries: ReadonlyArray<BitbucketRawComment>;
422 readonly next: string | null;
423}
424
425/**
426 * Bitbucket returns one flat list, so a thread is reassembled from it: a comment pinned to a
427 * line opens a thread, and every reply that leads back to it belongs in it. A reply whose
428 * parent is on a page that was not read has nowhere to go, and is left out rather than shown
429 * as a thread of its own — it still stands in the flat conversation, which needs no parent.
430 */
431export function buildReviewThreads(
432 comments: ReadonlyArray<BitbucketRawComment>,
433): ReadonlyArray<PullRequestReviewThread> {
434 const byId = new Map(comments.map((comment) => [comment.id, comment]));
435 const rootOf = (comment: Schema.Schema.Type<typeof RawCommentSchema>) => {
436 // Bounded by the number of comments read, so a parent cycle cannot spin here.
437 let current = comment;
438 for (let step = 0; step < byId.size; step += 1) {
439 const parent = current.parent === null ? undefined : byId.get(current.parent?.id ?? -1);
440 if (parent === undefined) return current;
441 current = parent;
442 }
443 return current;
444 };
445
446 const threads = new Map<number, PullRequestReviewThread>();
447 const replies = new Map<number, Array<Schema.Schema.Type<typeof RawCommentSchema>>>();
448 for (const comment of comments) {
449 const root = rootOf(comment);
450 const inline = root.inline;
451 const path = trimmed(inline?.path);
452 if (path === null) continue;
453 if (root.id === comment.id) {
454 // `to` is the line as the file stands now, `from` the line it replaced; a comment that
455 // carries only `from` was written against the removed side.
456 const side = inline?.to === null || inline?.to === undefined ? "left" : "right";
457 const line = side === "left" ? inline?.from : inline?.to;
458 threads.set(root.id, {
459 id: String(root.id),
460 path,
461 line: typeof line === "number" && line > 0 ? line : null,
462 side,
463 isResolved: root.resolution !== null && root.resolution !== undefined,
464 isOutdated: inline?.outdated === true,
465 comments: [],
466 });
467 }
468 const bucket = replies.get(root.id);
469 if (bucket === undefined) replies.set(root.id, [comment]);
470 else bucket.push(comment);
471 }
472
473 return [...threads.values()].flatMap((thread) => {
474 const entries = (replies.get(Number(thread.id)) ?? [])
475 .toSorted((left, right) => left.created_on.localeCompare(right.created_on))
476 .map((comment) => ({
477 id: String(comment.id),
478 author: toActor(comment.user),
479 body: comment.content?.raw ?? "",
480 createdAt: toIsoUtc(comment.created_on),
481 url: trimmed(comment.links?.html?.href),
482 }));
483 return entries.length === 0 ? [] : [{ ...thread, comments: entries }];
484 });
485}
486
487/**
488 * Deleted comments and ones their author has not posted yet carry nothing to show. A comment
489 * pinned to a file is a line-level review comment, which is what that kind means.
490 */
491export function decodeCommentsJson(raw: string): Result.Result<BitbucketComments, DecodeFailure> {
492 const decoded = decodePage(raw);
493 if (!Result.isSuccess(decoded)) {
494 return Result.fail(decoded.failure);
495 }
496 const comments: PullRequestComment[] = [];
497 const kept: Array<BitbucketRawComment> = [];
498 for (const entry of decoded.success.values) {
499 const decodedComment = decodeCommentEntry(entry);
500 if (Exit.isFailure(decodedComment)) continue;
501 const comment = decodedComment.value;
502 if (comment.deleted === true || comment.pending === true) continue;
503 const body = comment.content?.raw ?? "";
504 if (body.trim().length === 0) continue;
505 kept.push(comment);
506 const path = trimmed(comment.inline?.path);
507 comments.push({
508 id: String(comment.id),
509 kind: path === null ? "issue-comment" : "review-comment",
510 author: toActor(comment.user),
511 body,
512 createdAt: toIsoUtc(comment.created_on),
513 url: trimmed(comment.links?.html?.href),
514 path,
515 reviewState: null,
516 });
517 }
518 return Result.succeed({ comments, entries: kept, next: trimmed(decoded.success.next) });
519}
520
521export function decodeCommitsJson(
522 raw: string,
523): Result.Result<BitbucketPage<PullRequestCommit>, DecodeFailure> {
524 const decoded = decodePage(raw);
525 if (!Result.isSuccess(decoded)) {
526 return Result.fail(decoded.failure);
527 }
528 const commits: PullRequestCommit[] = [];
529 for (const entry of decoded.success.values) {
530 const decodedCommit = decodeCommitEntry(entry);
531 if (Exit.isFailure(decodedCommit)) continue;
532 const commit = decodedCommit.value;
533 const committedDate = trimmed(commit.date);
534 if (committedDate === null) continue;
535 const linkedAuthor = toActor(commit.author?.user);
536 const rawAuthor = trimmed(commit.author?.raw);
537 commits.push({
538 oid: commit.hash,
539 messageHeadline: (commit.message ?? "").split("\n")[0] ?? "",
540 committedDate: toIsoUtc(committedDate),
541 authors:
542 linkedAuthor !== null
543 ? [linkedAuthor]
544 : rawAuthor === null
545 ? []
546 : [{ login: rawAuthor, name: rawAuthor, avatarUrl: null }],
547 });
548 }
549 // Bitbucket lists a pull request's commits newest first; the timeline reads oldest first.
550 return Result.succeed({ items: commits.toReversed(), next: trimmed(decoded.success.next) });
551}
552
553export function decodeStatusesJson(
554 raw: string,
555): Result.Result<BitbucketPage<PullRequestCheck>, DecodeFailure> {
556 const decoded = decodePage(raw);
557 if (!Result.isSuccess(decoded)) {
558 return Result.fail(decoded.failure);
559 }
560 const checks: Array<{
561 readonly check: PullRequestCheck;
562 readonly workflowName: string | null;
563 readonly at: string | null;
564 }> = [];
565 for (const entry of decoded.success.values) {
566 const decodedStatus = decodeStatusEntry(entry);
567 if (Exit.isFailure(decodedStatus)) continue;
568 const status = decodedStatus.value;
569 const name = trimmed(status.name) ?? trimmed(status.key);
570 if (name === null) continue;
571 // Bitbucket re-uses a status key when a pipeline is run again, so the same check can appear
572 // twice on one page. Nothing decoded here says which copy is newer, so the later one wins,
573 // which is the order Bitbucket writes an update in. The key is kept as the workflow name so
574 // two different pipelines that display the same name are not folded into one.
575 checks.push({
576 check: {
577 name,
578 status: toBuildStatus(status.state),
579 description: trimmed(status.description),
580 url: trimmed(status.url),
581 },
582 workflowName: trimmed(status.key),
583 at: null,
584 });
585 }
586 return Result.succeed({ items: dedupeChecks(checks), next: trimmed(decoded.success.next) });
587}
588
589export interface BitbucketDiffStat {
590 readonly additions: number;
591 readonly deletions: number;
592 readonly changedFiles: number;
593}
594
595export interface BitbucketDiffStatPage extends BitbucketDiffStat {
596 readonly next: string | null;
597}
598
599/** One entry per changed file, each carrying that file's line counts. */
600export function decodeDiffstatJson(
601 raw: string,
602): Result.Result<BitbucketDiffStatPage, DecodeFailure> {
603 const decoded = decodePage(raw);
604 if (!Result.isSuccess(decoded)) {
605 return Result.fail(decoded.failure);
606 }
607 let additions = 0;
608 let deletions = 0;
609 let changedFiles = 0;
610 for (const entry of decoded.success.values) {
611 const decodedStat = decodeDiffstatEntry(entry);
612 if (Exit.isFailure(decodedStat)) continue;
613 additions += decodedStat.value.lines_added ?? 0;
614 deletions += decodedStat.value.lines_removed ?? 0;
615 changedFiles += 1;
616 }
617 return Result.succeed({
618 additions,
619 deletions,
620 changedFiles,
621 next: trimmed(decoded.success.next),
622 });
623}
624
625/**
626 * The conflicts endpoint answers with one entry per conflicting path, so an empty page is the
627 * only statement Bitbucket makes that a pull request merges cleanly.
628 */
629export function decodeConflictsJson(
630 raw: string,
631): Result.Result<PullRequestMergeability, DecodeFailure> {
632 const decoded = decodeConflicts(raw);
633 return Result.isSuccess(decoded)
634 ? Result.succeed(decoded.success.values.length === 0 ? "mergeable" : "conflicting")
635 : Result.fail(decoded.failure);
636}