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

bitbucketPullRequestJson.ts

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