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

bitbucketPullRequestJson.ts

631 lines23.2 KB

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