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.
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
48const RawBranchSchema = Schema.Struct({
49 branch: Schema.Struct({ name: TrimmedNonEmptyString }),
50 commit: Schema.optional(
51 Schema.NullOr(Schema.Struct({ hash: Schema.optional(Schema.NullOr(Schema.String)) })),
52 ),
53 repository: Schema.optional(Schema.NullOr(Schema.Struct({ full_name: TrimmedNonEmptyString }))),
54});
55
56const RawLinkSchema = Schema.Struct({ href: Schema.optional(Schema.String) });
57
58const RawPullRequestSchema = Schema.Struct({
59 id: Schema.Int,
60 title: Schema.String,
61 description: Schema.optional(Schema.NullOr(Schema.String)),
62 state: Schema.optional(Schema.NullOr(Schema.String)),
63 draft: Schema.optional(Schema.Boolean),
64 author: Schema.optional(Schema.NullOr(RawUserSchema)),
65 source: RawBranchSchema,
66 destination: RawBranchSchema,
67 created_on: Schema.String,
68 updated_on: Schema.String,
69 /** Only sent when asked for with `fields=+closed_on`; null while the request is open. */
70 closed_on: Schema.optional(Schema.NullOr(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 size: Schema.optional(Schema.NullOr(Schema.Int)),
91 next: Schema.optional(Schema.NullOr(Schema.String)),
92});
93
94const RawCommentSchema = Schema.Struct({
95 id: Schema.Int,
96 content: Schema.optional(Schema.NullOr(Schema.Struct({ raw: Schema.optional(Schema.String) }))),
97 user: Schema.optional(Schema.NullOr(RawUserSchema)),
98 created_on: Schema.String,
99 deleted: Schema.optional(Schema.Boolean),
100 pending: Schema.optional(Schema.Boolean),
101 parent: Schema.optional(Schema.NullOr(Schema.Struct({ id: Schema.Int }))),
102 inline: Schema.optional(
103 Schema.NullOr(
104 Schema.Struct({
105 path: Schema.optional(Schema.NullOr(Schema.String)),
106 from: Schema.optional(Schema.NullOr(Schema.Int)),
107 to: Schema.optional(Schema.NullOr(Schema.Int)),
108 outdated: Schema.optional(Schema.NullOr(Schema.Boolean)),
109 }),
110 ),
111 ),
112 resolution: Schema.optional(Schema.NullOr(Schema.Unknown)),
113 links: Schema.optional(
114 Schema.NullOr(Schema.Struct({ html: Schema.optional(Schema.NullOr(RawLinkSchema)) })),
115 ),
116});
117
118const RawCommitSchema = Schema.Struct({
119 hash: TrimmedNonEmptyString,
120 message: Schema.optional(Schema.NullOr(Schema.String)),
121 date: Schema.optional(Schema.NullOr(Schema.String)),
122 author: Schema.optional(
123 Schema.NullOr(
124 Schema.Struct({
125 raw: Schema.optional(Schema.NullOr(Schema.String)),
126 user: Schema.optional(Schema.NullOr(RawUserSchema)),
127 }),
128 ),
129 ),
130});
131
132const RawStatusSchema = Schema.Struct({
133 key: Schema.optional(Schema.NullOr(Schema.String)),
134 name: Schema.optional(Schema.NullOr(Schema.String)),
135 state: Schema.optional(Schema.NullOr(Schema.String)),
136 description: Schema.optional(Schema.NullOr(Schema.String)),
137 url: Schema.optional(Schema.NullOr(Schema.String)),
138});
139
140const RawDiffstatSchema = Schema.Struct({
141 lines_added: Schema.optional(Schema.NullOr(Schema.Int)),
142 lines_removed: Schema.optional(Schema.NullOr(Schema.Int)),
143});
144
145const RawMemberSchema = Schema.Struct({
146 user: Schema.optional(Schema.NullOr(RawUserSchema)),
147});
148
149const RawViewerSchema = Schema.Struct({
150 nickname: Schema.optional(Schema.NullOr(Schema.String)),
151 display_name: Schema.optional(Schema.NullOr(Schema.String)),
152});
153
154const RawRepositoryPermissionsSchema = Schema.Struct({
155 values: Schema.optional(
156 Schema.NullOr(
157 Schema.Array(Schema.Struct({ permission: Schema.optional(Schema.NullOr(Schema.String)) })),
158 ),
159 ),
160});
161
162export interface BitbucketPullRequest {
163 readonly number: number;
164 readonly title: string;
165 readonly url: string;
166 readonly author: PullRequestActor | null;
167 readonly headBranch: string;
168 readonly headSha: string | null;
169 readonly headRepositoryNameWithOwner: string | null;
170 readonly baseBranch: string;
171 readonly state: PullRequestState;
172 readonly isDraft: boolean;
173 /**
174 * Bitbucket reports no conflict state on a pull request, so the list leaves it unknown. The
175 * detail read asks the conflicts endpoint, which does answer.
176 */
177 readonly mergeability: PullRequestMergeability;
178 readonly createdAt: string;
179 readonly updatedAt: string;
180 /** When the request was merged or declined, unlike `updatedAt`, which later comments move. */
181 readonly closedAt: string | null;
182 readonly body: string;
183 readonly reviewRequestLogins: ReadonlyArray<string>;
184 readonly reviewers: ReadonlyArray<PullRequestActor>;
185 readonly reviewerIds: ReadonlyArray<string>;
186 readonly reviews: ReadonlyArray<PullRequestComment>;
187}
188
189function trimmed(value: string | null | undefined): string | null {
190 const text = value?.trim() ?? "";
191 return text.length > 0 ? text : null;
192}
193
194/**
195 * Bitbucket stamps times as `+00:00` with microseconds. The page sorts change requests from
196 * every host against each other as plain strings, so they are normalized to the same `Z` form
197 * the other hosts already use.
198 */
199function toIsoUtc(value: string): string {
200 return Option.match(DateTime.make(value), {
201 onNone: () => value,
202 onSome: DateTime.formatIso,
203 });
204}
205
206function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
207 const login = trimmed(raw?.nickname) ?? trimmed(raw?.display_name);
208 return login === null
209 ? null
210 : {
211 login,
212 name: trimmed(raw?.display_name),
213 avatarUrl: trimmed(raw?.links?.avatar?.href),
214 };
215}
216
217function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
218 switch (raw.state?.trim().toUpperCase()) {
219 case "MERGED":
220 return "merged";
221 case "DECLINED":
222 case "SUPERSEDED":
223 return "closed";
224 default:
225 return "open";
226 }
227}
228
229function toBuildStatus(value: string | null | undefined): PullRequestCheckStatus {
230 switch (value?.trim().toUpperCase()) {
231 case "SUCCESSFUL":
232 return "success";
233 case "FAILED":
234 return "failure";
235 case "STOPPED":
236 return "cancelled";
237 case "INPROGRESS":
238 return "pending";
239 default:
240 return "neutral";
241 }
242}
243
244function toReviews(
245 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
246): ReadonlyArray<PullRequestComment> {
247 return (raw.participants ?? []).flatMap((participant): ReadonlyArray<PullRequestComment> => {
248 const author = toActor(participant.user);
249 const votedAt = trimmed(participant.participated_on);
250 const reviewState =
251 trimmed(participant.state) ?? (participant.approved === true ? "approved" : null);
252 if (author === null || votedAt === null || reviewState === null) return [];
253 return [
254 {
255 id: `${raw.id}:${author.login}`,
256 kind: "review",
257 author,
258 body: "",
259 createdAt: toIsoUtc(votedAt),
260 url: null,
261 path: null,
262 reviewState,
263 },
264 ];
265 });
266}
267
268function toPullRequest(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): BitbucketPullRequest {
269 const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
270 const actor = toActor(reviewer);
271 return actor === null ? [] : [actor];
272 });
273 return {
274 number: raw.id,
275 title: raw.title,
276 url: raw.links.html.href,
277 author: toActor(raw.author),
278 headBranch: raw.source.branch.name,
279 headSha: trimmed(raw.source.commit?.hash),
280 headRepositoryNameWithOwner: raw.source.repository?.full_name ?? null,
281 baseBranch: raw.destination.branch.name,
282 state: toState(raw),
283 isDraft: raw.draft ?? false,
284 mergeability: "unknown",
285 createdAt: toIsoUtc(raw.created_on),
286 updatedAt: toIsoUtc(raw.updated_on),
287 closedAt: raw.closed_on == null ? null : toIsoUtc(raw.closed_on),
288 body: raw.description ?? "",
289 reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
290 reviewers,
291 reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) => trimmed(reviewer.uuid) ?? []),
292 reviews: toReviews(raw),
293 };
294}
295
296const decodePage = decodeJsonResult(RawPageSchema);
297const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
298const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
299const decodeCommentEntry = Schema.decodeUnknownExit(RawCommentSchema);
300const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
301const decodeStatusEntry = Schema.decodeUnknownExit(RawStatusSchema);
302const decodeDiffstatEntry = Schema.decodeUnknownExit(RawDiffstatSchema);
303const decodeMemberEntry = Schema.decodeUnknownExit(RawMemberSchema);
304const decodeViewer = decodeJsonResult(RawViewerSchema);
305const decodeConflicts = decodeJsonResult(RawPageSchema);
306const decodeRepositoryPermissions = decodeJsonResult(RawRepositoryPermissionsSchema);
307
308type DecodeFailure = Cause.Cause<Schema.SchemaError>;
309
310export interface BitbucketPage<A> {
311 readonly items: ReadonlyArray<A>;
312 readonly next: string | null;
313}
314
315export function decodePullRequestPageJson(
316 raw: string,
317): Result.Result<BitbucketPage<BitbucketPullRequest>, DecodeFailure> {
318 const decoded = decodePage(raw);
319 if (!Result.isSuccess(decoded)) {
320 return Result.fail(decoded.failure);
321 }
322 const items: BitbucketPullRequest[] = [];
323 for (const entry of decoded.success.values) {
324 const item = decodePullRequestEntry(entry);
325 if (Exit.isSuccess(item)) {
326 items.push(toPullRequest(item.value));
327 }
328 }
329 return Result.succeed({ items, next: trimmed(decoded.success.next) });
330}
331
332export function decodePullRequestJson(
333 raw: string,
334): Result.Result<BitbucketPullRequest, DecodeFailure> {
335 const decoded = decodePullRequest(raw);
336 return Result.isSuccess(decoded)
337 ? Result.succeed(toPullRequest(decoded.success))
338 : Result.fail(decoded.failure);
339}
340
341export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
342 const decoded = decodeViewer(raw);
343 return Result.isSuccess(decoded)
344 ? Result.succeed(trimmed(decoded.success.nickname) ?? trimmed(decoded.success.display_name))
345 : Result.fail(decoded.failure);
346}
347
348export function decodeRepositoryPermissionJson(raw: string): Result.Result<boolean, DecodeFailure> {
349 const decoded = decodeRepositoryPermissions(raw);
350 if (!Result.isSuccess(decoded)) {
351 return Result.fail(decoded.failure);
352 }
353 const permission = trimmed(decoded.success.values?.[0]?.permission)?.toLowerCase() ?? null;
354 return Result.succeed(permission === null || permission === "admin" || permission === "write");
355}
356
357/**
358 * Nothing on a repository lists the people with access to it — `permissions-config/users` is for
359 * administrators only — and a pull request can be sent to anyone in the workspace, so this is the
360 * list Bitbucket's own reviewer field is filled from too.
361 */
362export function decodeWorkspaceMembersJson(
363 raw: string,
364): Result.Result<BitbucketPage<PullRequestReviewerCandidate>, DecodeFailure> {
365 const decoded = decodePage(raw);
366 if (!Result.isSuccess(decoded)) {
367 return Result.fail(decoded.failure);
368 }
369 const items: PullRequestReviewerCandidate[] = [];
370 for (const entry of decoded.success.values) {
371 const member = decodeMemberEntry(entry);
372 if (Exit.isFailure(member)) continue;
373 const uuid = trimmed(member.value.user?.uuid);
374 const actor = toActor(member.value.user);
375 if (uuid === null || actor === null) continue;
376 items.push({ ...actor, id: uuid, kind: "user", isRequested: false });
377 }
378 return Result.succeed({ items, next: trimmed(decoded.success.next) });
379}
380
381export type BitbucketRawComment = Schema.Schema.Type<typeof RawCommentSchema>;
382
383export interface BitbucketComments {
384 readonly comments: ReadonlyArray<PullRequestComment>;
385 /**
386 * The same comments unread, for `buildReviewThreads`. A reply and the remark it answers can
387 * land on different pages, and only the caller holding every page can put them together.
388 */
389 readonly entries: ReadonlyArray<BitbucketRawComment>;
390 readonly next: string | null;
391}
392
393export function buildReviewThreads(
394 comments: ReadonlyArray<BitbucketRawComment>,
395): ReadonlyArray<PullRequestReviewThread> {
396 const byId = new Map(comments.map((comment) => [comment.id, comment]));
397 const rootOf = (comment: Schema.Schema.Type<typeof RawCommentSchema>) => {
398 let current = comment;
399 for (let step = 0; step < byId.size; step += 1) {
400 const parent = current.parent === null ? undefined : byId.get(current.parent?.id ?? -1);
401 if (parent === undefined) return current;
402 current = parent;
403 }
404 return current;
405 };
406
407 const threads = new Map<number, PullRequestReviewThread>();
408 const replies = new Map<number, Array<Schema.Schema.Type<typeof RawCommentSchema>>>();
409 for (const comment of comments) {
410 const root = rootOf(comment);
411 const inline = root.inline;
412 const path = trimmed(inline?.path);
413 if (path === null) continue;
414 if (root.id === comment.id) {
415 const side = inline?.to === null || inline?.to === undefined ? "left" : "right";
416 const line = side === "left" ? inline?.from : inline?.to;
417 threads.set(root.id, {
418 id: String(root.id),
419 path,
420 line: typeof line === "number" && line > 0 ? line : null,
421 side,
422 isResolved: root.resolution !== null && root.resolution !== undefined,
423 isOutdated: inline?.outdated === true,
424 comments: [],
425 });
426 }
427 const bucket = replies.get(root.id);
428 if (bucket === undefined) replies.set(root.id, [comment]);
429 else bucket.push(comment);
430 }
431
432 return [...threads.values()].flatMap((thread) => {
433 const entries = (replies.get(Number(thread.id)) ?? [])
434 .toSorted((left, right) => left.created_on.localeCompare(right.created_on))
435 .map((comment) => ({
436 id: String(comment.id),
437 author: toActor(comment.user),
438 body: comment.content?.raw ?? "",
439 createdAt: toIsoUtc(comment.created_on),
440 url: trimmed(comment.links?.html?.href),
441 }));
442 return entries.length === 0 ? [] : [{ ...thread, comments: entries }];
443 });
444}
445
446export function decodeCommentsJson(raw: string): Result.Result<BitbucketComments, DecodeFailure> {
447 const decoded = decodePage(raw);
448 if (!Result.isSuccess(decoded)) {
449 return Result.fail(decoded.failure);
450 }
451 const comments: PullRequestComment[] = [];
452 const kept: Array<BitbucketRawComment> = [];
453 for (const entry of decoded.success.values) {
454 const decodedComment = decodeCommentEntry(entry);
455 if (Exit.isFailure(decodedComment)) continue;
456 const comment = decodedComment.value;
457 if (comment.deleted === true || comment.pending === true) continue;
458 const body = comment.content?.raw ?? "";
459 if (body.trim().length === 0) continue;
460 kept.push(comment);
461 const path = trimmed(comment.inline?.path);
462 comments.push({
463 id: String(comment.id),
464 kind: path === null ? "issue-comment" : "review-comment",
465 author: toActor(comment.user),
466 body,
467 createdAt: toIsoUtc(comment.created_on),
468 url: trimmed(comment.links?.html?.href),
469 path,
470 reviewState: null,
471 });
472 }
473 return Result.succeed({ comments, entries: kept, next: trimmed(decoded.success.next) });
474}
475
476export function decodeCommitsJson(
477 raw: string,
478): Result.Result<BitbucketPage<PullRequestCommit>, DecodeFailure> {
479 const decoded = decodePage(raw);
480 if (!Result.isSuccess(decoded)) {
481 return Result.fail(decoded.failure);
482 }
483 const commits: PullRequestCommit[] = [];
484 for (const entry of decoded.success.values) {
485 const decodedCommit = decodeCommitEntry(entry);
486 if (Exit.isFailure(decodedCommit)) continue;
487 const commit = decodedCommit.value;
488 const committedDate = trimmed(commit.date);
489 if (committedDate === null) continue;
490 const linkedAuthor = toActor(commit.author?.user);
491 const rawAuthor = trimmed(commit.author?.raw);
492 commits.push({
493 oid: commit.hash,
494 messageHeadline: (commit.message ?? "").split("\n")[0] ?? "",
495 committedDate: toIsoUtc(committedDate),
496 authors:
497 linkedAuthor !== null
498 ? [linkedAuthor]
499 : rawAuthor === null
500 ? []
501 : [{ login: rawAuthor, name: rawAuthor, avatarUrl: null }],
502 });
503 }
504 // Bitbucket lists a pull request's commits newest first; the timeline reads oldest first.
505 return Result.succeed({ items: commits.toReversed(), next: trimmed(decoded.success.next) });
506}
507
508export function decodeStatusesJson(
509 raw: string,
510): Result.Result<BitbucketPage<PullRequestCheck>, DecodeFailure> {
511 const decoded = decodePage(raw);
512 if (!Result.isSuccess(decoded)) {
513 return Result.fail(decoded.failure);
514 }
515 const checks: Array<{
516 readonly check: PullRequestCheck;
517 readonly workflowName: string | null;
518 readonly at: string | null;
519 }> = [];
520 for (const entry of decoded.success.values) {
521 const decodedStatus = decodeStatusEntry(entry);
522 if (Exit.isFailure(decodedStatus)) continue;
523 const status = decodedStatus.value;
524 const name = trimmed(status.name) ?? trimmed(status.key);
525 if (name === null) continue;
526 // Bitbucket re-uses a status key when a pipeline is run again, so the same check can appear
527 // twice on one page. Nothing decoded here says which copy is newer, so the later one wins,
528 // which is the order Bitbucket writes an update in. The key is kept as the workflow name so
529 // two different pipelines that display the same name are not folded into one.
530 checks.push({
531 check: {
532 name,
533 status: toBuildStatus(status.state),
534 description: trimmed(status.description),
535 url: trimmed(status.url),
536 },
537 workflowName: trimmed(status.key),
538 at: null,
539 });
540 }
541 return Result.succeed({ items: dedupeChecks(checks), next: trimmed(decoded.success.next) });
542}
543
544export interface BitbucketDiffStat {
545 readonly additions: number;
546 readonly deletions: number;
547 readonly changedFiles: number;
548}
549
550export interface BitbucketDiffStatPage extends BitbucketDiffStat {
551 readonly next: string | null;
552}
553
554export function decodeDiffstatJson(
555 raw: string,
556): Result.Result<BitbucketDiffStatPage, DecodeFailure> {
557 const decoded = decodePage(raw);
558 if (!Result.isSuccess(decoded)) {
559 return Result.fail(decoded.failure);
560 }
561 let additions = 0;
562 let deletions = 0;
563 let changedFiles = 0;
564 for (const entry of decoded.success.values) {
565 const decodedStat = decodeDiffstatEntry(entry);
566 if (Exit.isFailure(decodedStat)) continue;
567 additions += decodedStat.value.lines_added ?? 0;
568 deletions += decodedStat.value.lines_removed ?? 0;
569 changedFiles += 1;
570 }
571 return Result.succeed({
572 additions,
573 deletions,
574 changedFiles,
575 next: trimmed(decoded.success.next),
576 });
577}
578
579export function decodeConflictsJson(
580 raw: string,
581): Result.Result<PullRequestMergeability, DecodeFailure> {
582 const decoded = decodeConflicts(raw);
583 return Result.isSuccess(decoded)
584 ? Result.succeed(decoded.success.values.length === 0 ? "mergeable" : "conflicting")
585 : Result.fail(decoded.failure);
586}