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