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

BitbucketApi.ts

1,093 lines36.5 KB

1import * as Config from "effect/Config";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import {
9 NonNegativeInt,
10 TrimmedNonEmptyString,
11 type SourceControlProviderAuth,
12 type SourceControlRepositoryCloneUrls,
13 type SourceControlRepositoryVisibility,
14} from "@t3tools/contracts";
15import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
16import { sanitizeBranchFragment } from "@t3tools/shared/git";
17import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
18​
19import {
20 BitbucketPullRequestListSchema,
21 BitbucketPullRequestSchema,
22 normalizeBitbucketPullRequestRecord,
23 type NormalizedBitbucketPullRequestRecord,
24} from "./bitbucketPullRequests.ts";
25import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
26import * as SourceControlProvider from "./SourceControlProvider.ts";
27import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
28import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
29​
30const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
31/** A response body past this is cut short, so one huge diff cannot exhaust the server. */
32const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
33/** Bitbucket redirects a diff once; this leaves room without following a chain forever. */
34const MAX_REDIRECTS = 3;
35​
36const BitbucketApiEnvConfig = Config.all({
37 baseUrl: Config.string("T3CODE_BITBUCKET_API_BASE_URL").pipe(
38 Config.withDefault(DEFAULT_API_BASE_URL),
39 ),
40 accessToken: Config.string("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
41 email: Config.string("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
42 apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
43});
44​
45const BitbucketApiOperation = Schema.Literals([
46 "resolveRepository",
47 "getRepository",
48 "getBranchingModel",
49 "getPullRequest",
50 "listPullRequests",
51 "createRepository",
52 "createPullRequest",
53 "probeAuth",
54 "checkoutPullRequest",
55 // The raw escape hatch. Callers name their own operation in their own error, the way the
56 // pull request wrappers do on top of `gh` and `glab`.
57 "request",
58]);
59type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
60​
61export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
62 "BitbucketRepositoryLocatorError",
63 {
64 repository: Schema.String,
65 },
66) {
67 get detail(): string {
68 return "Bitbucket repositories must be specified as workspace/repository.";
69 }
70​
71 override get message(): string {
72 return `Bitbucket API failed in createRepository: ${this.detail}`;
73 }
75​
76export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
77 "BitbucketRequestError",
78 {
79 operation: BitbucketApiOperation,
80 cause: Schema.Defect(),
81 },
82) {
83 get detail(): string {
84 return "Failed to send the Bitbucket request.";
85 }
86​
87 override get message(): string {
88 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
89 }
91​
92export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
93 "BitbucketResponseError",
94 {
95 operation: BitbucketApiOperation,
96 status: Schema.Int,
97 responseBodyLength: NonNegativeInt,
98 },
99) {
100 get detail(): string {
101 return `Bitbucket returned HTTP ${this.status}.`;
102 }
103​
104 override get message(): string {
105 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
106 }
108​
109export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
110 "BitbucketResponseBodyReadError",
111 {
112 operation: BitbucketApiOperation,
113 status: Schema.Int,
114 cause: Schema.Defect(),
115 },
116) {
117 get detail(): string {
118 return `Bitbucket returned HTTP ${this.status}.`;
119 }
120​
121 override get message(): string {
122 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
123 }
125​
126export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
127 "BitbucketResponseDecodeError",
128 {
129 operation: BitbucketApiOperation,
130 status: Schema.Int,
131 cause: Schema.Defect(),
132 },
133) {
134 get detail(): string {
135 return "Bitbucket returned invalid JSON for the requested resource.";
136 }
137​
138 override get message(): string {
139 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
140 }
142​
143export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
144 "BitbucketRepositoryVcsResolveError",
145 {
146 cwd: Schema.String,
147 cause: Schema.Defect(),
148 },
149) {
150 get detail(): string {
151 return `Failed to resolve VCS repository for ${this.cwd}.`;
152 }
153​
154 override get message(): string {
155 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
156 }
158​
159export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
160 "BitbucketRepositoryRemotesListError",
161 {
162 cwd: Schema.String,
163 cause: Schema.Defect(),
164 },
165) {
166 get detail(): string {
167 return `Failed to list remotes for ${this.cwd}.`;
168 }
169​
170 override get message(): string {
171 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
172 }
174​
175export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
176 "BitbucketRepositoryRemoteNotFoundError",
177 {
178 cwd: Schema.String,
179 },
180) {
181 get detail(): string {
182 return `No Bitbucket repository remote was detected for ${this.cwd}.`;
183 }
184​
185 override get message(): string {
186 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
187 }
189​
190export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
191 "BitbucketPullRequestBodyReadError",
192 {
193 cwd: Schema.String,
194 bodyFile: Schema.String,
195 cause: Schema.Defect(),
196 },
197) {
198 get detail(): string {
199 return `Failed to read pull request body file ${this.bodyFile}.`;
200 }
201​
202 override get message(): string {
203 return `Bitbucket API failed in createPullRequest: ${this.detail}`;
204 }
206​
207export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
208 "BitbucketCheckoutError",
209 {
210 cwd: Schema.String,
211 reference: Schema.String,
212 cause: Schema.Defect(),
213 },
214) {
215 get detail(): string {
216 return "Failed to check out the Bitbucket pull request.";
217 }
218​
219 override get message(): string {
220 return `Bitbucket API failed in checkoutPullRequest: ${this.detail}`;
221 }
223​
224/**
225 * A url that does not belong to the configured Bitbucket. Refused rather than followed, because
226 * the request carries the account's credentials and a url that came back in a response — a
227 * pagination cursor, or the target of a redirect — is not this server's to trust.
228 */
229export class BitbucketUntrustedUrlError extends Schema.TaggedErrorClass<BitbucketUntrustedUrlError>()(
230 "BitbucketUntrustedUrlError",
231 {
232 /** The host only. A rejected hop is often a signed url, whose query carries a credential. */
233 host: Schema.String,
234 },
235) {
236 get detail(): string {
237 return `The response pointed at ${this.host}, outside the configured Bitbucket.`;
238 }
239​
240 override get message(): string {
241 return `Bitbucket API failed in request: ${this.detail}`;
242 }
244​
245export const BitbucketApiError = Schema.Union([
246 BitbucketUntrustedUrlError,
247 BitbucketRepositoryLocatorError,
248 BitbucketRequestError,
249 BitbucketResponseError,
250 BitbucketResponseBodyReadError,
251 BitbucketResponseDecodeError,
252 BitbucketRepositoryVcsResolveError,
253 BitbucketRepositoryRemotesListError,
254 BitbucketRepositoryRemoteNotFoundError,
255 BitbucketPullRequestBodyReadError,
256 BitbucketCheckoutError,
257]);
258export type BitbucketApiError = typeof BitbucketApiError.Type;
259export const isBitbucketApiError = Schema.is(BitbucketApiError);
260​
261const RawBitbucketRepositorySchema = Schema.Struct({
262 full_name: TrimmedNonEmptyString,
263 links: Schema.Struct({
264 html: Schema.optional(
265 Schema.Struct({
266 href: TrimmedNonEmptyString,
267 }),
268 ),
269 clone: Schema.optional(
270 Schema.Array(
271 Schema.Struct({
272 name: TrimmedNonEmptyString,
273 href: TrimmedNonEmptyString,
274 }),
275 ),
276 ),
277 }),
278 mainbranch: Schema.optional(
279 Schema.NullOr(
280 Schema.Struct({
281 name: TrimmedNonEmptyString,
282 }),
283 ),
284 ),
285});
286​
287const RawBitbucketBranchingModelSchema = Schema.Struct({
288 development: Schema.optional(
289 Schema.Struct({
290 branch: Schema.optional(
291 Schema.NullOr(
292 Schema.Struct({
293 name: Schema.optional(TrimmedNonEmptyString),
294 }),
295 ),
296 ),
297 is_valid: Schema.optional(Schema.Boolean),
298 name: Schema.optional(Schema.NullOr(Schema.String)),
299 use_mainbranch: Schema.optional(Schema.Boolean),
300 }),
301 ),
302});
303​
304const BitbucketUserSchema = Schema.Struct({
305 username: Schema.optional(TrimmedNonEmptyString),
306 display_name: Schema.optional(TrimmedNonEmptyString),
307 account_id: Schema.optional(TrimmedNonEmptyString),
308});
309​
310export interface BitbucketRepositoryLocator {
311 readonly workspace: string;
312 readonly repoSlug: string;
314​
315export class BitbucketApi extends Context.Service<
316 BitbucketApi,
317 {
318 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
319​
320 /**
321 * One authenticated request, returning the body verbatim. Bitbucket answers most endpoints
322 * with JSON and a few — a pull request diff, for one — with plain text, so the body is
323 * handed back undecoded for the caller to read as it sees fit.
324 */
325 readonly request: (input: {
326 readonly method: "GET" | "POST" | "PUT" | "DELETE";
327 /**
328 * A path below the API base, or a whole URL as a paged response reports its next page.
329 * A whole URL is refused unless it belongs to the configured Bitbucket.
330 */
331 readonly url: string;
332 /** A JSON document, for the endpoints that take one. */
333 readonly body?: string;
334 /** Response bytes to keep; past this the body comes back cut short and marked. */
335 readonly maxBytes?: number;
336 }) => Effect.Effect<{ readonly body: string; readonly truncated: boolean }, BitbucketApiError>;
337 readonly listPullRequests: (input: {
338 readonly cwd: string;
339 readonly context?: SourceControlProvider.SourceControlProviderContext;
340 readonly headSelector: string;
341 readonly source?: SourceControlProvider.SourceControlRefSelector;
342 readonly state: "open" | "closed" | "merged" | "all";
343 readonly limit?: number;
344 }) => Effect.Effect<ReadonlyArray<NormalizedBitbucketPullRequestRecord>, BitbucketApiError>;
345 readonly getPullRequest: (input: {
346 readonly cwd: string;
347 readonly context?: SourceControlProvider.SourceControlProviderContext;
348 readonly reference: string;
349 }) => Effect.Effect<NormalizedBitbucketPullRequestRecord, BitbucketApiError>;
350 readonly getRepositoryCloneUrls: (input: {
351 readonly cwd: string;
352 readonly context?: SourceControlProvider.SourceControlProviderContext;
353 readonly repository: string;
354 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
355 readonly createRepository: (input: {
356 readonly cwd: string;
357 readonly repository: string;
358 readonly visibility: SourceControlRepositoryVisibility;
359 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
360 readonly createPullRequest: (input: {
361 readonly cwd: string;
362 readonly context?: SourceControlProvider.SourceControlProviderContext;
363 readonly baseBranch: string;
364 readonly headSelector: string;
365 readonly source?: SourceControlProvider.SourceControlRefSelector;
366 readonly target?: SourceControlProvider.SourceControlRefSelector;
367 readonly title: string;
368 readonly bodyFile: string;
369 }) => Effect.Effect<void, BitbucketApiError>;
370 readonly getDefaultBranch: (input: {
371 readonly cwd: string;
372 readonly context?: SourceControlProvider.SourceControlProviderContext;
373 }) => Effect.Effect<string | null, BitbucketApiError>;
374 readonly checkoutPullRequest: (input: {
375 readonly cwd: string;
376 readonly context?: SourceControlProvider.SourceControlProviderContext;
377 readonly reference: string;
378 readonly force?: boolean;
379 }) => Effect.Effect<void, BitbucketApiError>;
380 }
381>()("t3/sourceControl/BitbucketApi") {}
382​
383function nonEmpty(value: string | undefined): Option.Option<string> {
384 const trimmed = value?.trim();
385 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
387​
388function normalizeChangeRequestId(reference: string): string {
389 const trimmed = reference.trim().replace(/^#/, "");
390 const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
391 trimmed,
392 );
393 return urlMatch?.[1] ?? trimmed;
395​
396function sourceWorkspace(input: {
397 readonly headSelector: string;
398 readonly source?: SourceControlProvider.SourceControlRefSelector;
399}): string | undefined {
400 if (input.source?.owner) return input.source.owner;
401 return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
403​
404function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
405 switch (state) {
406 case "open":
407 return ["OPEN"];
408 case "closed":
409 return ["DECLINED", "SUPERSEDED"];
410 case "merged":
411 return ["MERGED"];
412 case "all":
413 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
414 }
416​
417function bitbucketQueryString(filters: ReadonlyArray<string>): string {
418 return filters.join(" AND ");
420​
421function bitbucketStateFilter(states: ReadonlyArray<string>): string {
422 return states.length === 1
423 ? `state = "${states[0]}"`
424 : `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
426​
427function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
428 const normalized = value.trim().replace(/\.git$/u, "");
429 const parts = normalized.split("/").filter((part) => part.length > 0);
430 if (parts.length < 2) return null;
431 const workspace = parts.at(-2);
432 const repoSlug = parts.at(-1);
433 return workspace && repoSlug ? { workspace, repoSlug } : null;
435​
436function requireRepositoryLocator(
437 repository: string,
438): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
439 const locator = parseBitbucketRepositorySlug(repository);
440 return locator
441 ? Effect.succeed(locator)
442 : Effect.fail(
443 new BitbucketRepositoryLocatorError({
444 repository,
445 }),
446 );
448​
449function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
450 const trimmed = remoteUrl.trim();
451 if (trimmed.startsWith("git@")) {
452 const pathStart = trimmed.indexOf(":");
453 return pathStart < 0 ? null : parseBitbucketRepositorySlug(trimmed.slice(pathStart + 1));
454 }
455​
456 try {
457 return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
458 } catch {
459 return null;
460 }
462​
463function normalizeRepositoryCloneUrls(
464 raw: typeof RawBitbucketRepositorySchema.Type,
465): SourceControlRepositoryCloneUrls {
466 const httpClone =
467 raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
468 raw.links.html?.href;
469 const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;
470​
471 return {
472 nameWithOwner: raw.full_name,
473 url: httpClone ?? raw.links.html?.href ?? raw.full_name,
474 sshUrl: sshClone ?? httpClone ?? raw.full_name,
475 };
477​
478function defaultChangeRequestTargetBranch(input: {
479 readonly repository: typeof RawBitbucketRepositorySchema.Type;
480 readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
481}): string | null {
482 const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
483 const development = input.branchingModel?.development;
484 if (!development || development.use_mainbranch === true || development.is_valid === false) {
485 return repositoryMainBranch;
486 }
487​
488 const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
489 if (developmentBranch.length === 0 || developmentBranch === "null") {
490 return repositoryMainBranch;
491 }
492​
493 return developmentBranch;
495​
496function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
497 const trimmed = originRemoteUrl?.trim() ?? "";
498 return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
500​
501function selectCloneUrl(input: {
502 readonly cloneUrls: SourceControlRepositoryCloneUrls;
503 readonly originRemoteUrl: string | null;
504}): string {
505 return shouldPreferSshRemote(input.originRemoteUrl)
506 ? input.cloneUrls.sshUrl
507 : input.cloneUrls.url;
509​
510function checkoutBranchName(input: {
511 readonly pullRequestId: number;
512 readonly headBranch: string;
513 readonly isCrossRepository: boolean;
514}): string {
515 if (!input.isCrossRepository) {
516 return input.headBranch;
517 }
518​
519 return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
521​
522function repositoryNameWithOwner(
523 repository: Schema.Schema.Type<typeof BitbucketPullRequestSchema>["source"]["repository"],
524): string | null {
525 const fullName = repository?.full_name?.trim() ?? "";
526 return fullName.length > 0 ? fullName : null;
528​
529function repositoryOwnerName(repositoryName: string): string {
530 return repositoryName.split("/")[0]?.trim() || "bitbucket";
532​
533function authFromConfig(
534 config: Config.Success<typeof BitbucketApiEnvConfig>,
535): SourceControlProviderAuth {
536 if (Option.isSome(config.accessToken)) {
537 return {
538 status: "unknown",
539 account: Option.none(),
540 host: Option.some("bitbucket.org"),
541 detail: Option.some("Bitbucket access token is configured."),
542 };
543 }
544​
545 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
546 return {
547 status: "unknown",
548 account: config.email,
549 host: Option.some("bitbucket.org"),
550 detail: Option.some("Bitbucket API token is configured."),
551 };
552 }
553​
554 return {
555 status: "unauthenticated",
556 account: Option.none(),
557 host: Option.some("bitbucket.org"),
558 detail: Option.some(
559 "Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
560 ),
561 };
563​
564/** Null for anything that is not a url at all, which is never the configured Bitbucket. */
565function originOf(value: string): string | null {
566 try {
567 return new URL(value).origin;
568 } catch {
569 return null;
570 }
572​
573function responseError(
574 operation: BitbucketApiOperation,
575 response: HttpClientResponse.HttpClientResponse,
576): Effect.Effect<never, BitbucketApiError> {
577 // Bounded like any other body: an error response is no smaller than a successful one, and
578 // only its length is reported anyway.
579 return collectUint8StreamText({
580 stream: response.stream,
581 maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
582 }).pipe(
583 Effect.mapError(
584 (cause) =>
585 new BitbucketResponseBodyReadError({
586 operation,
587 status: response.status,
588 cause,
589 }),
590 ),
591 Effect.flatMap((collected) =>
592 Effect.fail(
593 new BitbucketResponseError({
594 operation,
595 status: response.status,
596 responseBodyLength: collected.text.length,
597 }),
598 ),
599 ),
600 );
602​
603export const make = Effect.gen(function* () {
604 const config = yield* BitbucketApiEnvConfig;
605 const httpClient = yield* HttpClient.HttpClient;
606 const fileSystem = yield* FileSystem.FileSystem;
607 const git = yield* GitVcsDriver.GitVcsDriver;
608 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
609​
610 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
611​
612 const withAuth = (request: HttpClientRequest.HttpClientRequest) => {
613 if (Option.isSome(config.accessToken)) {
614 return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));
615 }
616 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
617 return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));
618 }
619 return request;
620 };
621​
622 const decodeResponse = <S extends Schema.Top>(
623 operation: BitbucketApiOperation,
624 schema: S,
625 response: HttpClientResponse.HttpClientResponse,
626 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
627 HttpClientResponse.matchStatus({
628 "2xx": (success) =>
629 HttpClientResponse.schemaBodyJson(schema)(success).pipe(
630 Effect.mapError(
631 (cause) =>
632 new BitbucketResponseDecodeError({
633 operation,
634 status: success.status,
635 cause,
636 }),
637 ),
638 ),
639 orElse: (failed) => responseError(operation, failed),
640 })(response);
641​
642 const executeJson = <S extends Schema.Top>(
643 operation: BitbucketApiOperation,
644 request: HttpClientRequest.HttpClientRequest,
645 schema: S,
646 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
647 httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
648 Effect.mapError(
649 (cause) =>
650 new BitbucketRequestError({
651 operation,
652 cause,
653 }),
654 ),
655 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
656 );
657​
658 const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
659 readonly cwd: string;
660 readonly context?: SourceControlProvider.SourceControlProviderContext;
661 readonly repository?: string;
662 }) {
663 const fromRepository =
664 input.repository !== undefined ? parseBitbucketRepositorySlug(input.repository) : null;
665 if (fromRepository) return fromRepository;
666​
667 const fromContext =
668 input.context?.provider.kind === "bitbucket"
669 ? parseBitbucketRemoteUrl(input.context.remoteUrl)
670 : null;
671 if (fromContext) return fromContext;
672​
673 const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
674 Effect.mapError(
675 (cause) =>
676 new BitbucketRepositoryVcsResolveError({
677 cwd: input.cwd,
678 cause,
679 }),
680 ),
681 );
682 const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
683 Effect.mapError(
684 (cause) =>
685 new BitbucketRepositoryRemotesListError({
686 cwd: input.cwd,
687 cause,
688 }),
689 ),
690 );
691​
692 for (const remote of remotes.remotes) {
693 if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
694 const parsed = parseBitbucketRemoteUrl(remote.url);
695 if (parsed) return parsed;
696 }
697​
698 return yield* new BitbucketRepositoryRemoteNotFoundError({
699 cwd: input.cwd,
700 });
701 });
702​
703 const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
704 executeJson(
705 "getRepository",
706 HttpClientRequest.get(
707 apiUrl(
708 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
709 ),
710 ),
711 RawBitbucketRepositorySchema,
712 );
713​
714 const getRepository = (input: {
715 readonly cwd: string;
716 readonly context?: SourceControlProvider.SourceControlProviderContext;
717 readonly repository?: string;
718 }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
719​
720 const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
721 executeJson(
722 "getBranchingModel",
723 HttpClientRequest.get(
724 apiUrl(
725 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
726 ),
727 ),
728 RawBitbucketBranchingModelSchema,
729 );
730​
731 const getRawPullRequestFromRepository = (
732 repository: BitbucketRepositoryLocator,
733 reference: string,
734 ) =>
735 executeJson(
736 "getPullRequest",
737 HttpClientRequest.get(
738 apiUrl(
739 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
740 ),
741 ),
742 BitbucketPullRequestSchema,
743 );
744​
745 const getRawPullRequest = (input: {
746 readonly cwd: string;
747 readonly context?: SourceControlProvider.SourceControlProviderContext;
748 readonly reference: string;
749 }) =>
750 resolveRepository(input).pipe(
751 Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
752 );
753​
754 const readConfigValueNullable = (cwd: string, key: string) =>
755 git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
756​
757 const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
758 readonly cwd: string;
759 readonly context?: SourceControlProvider.SourceControlProviderContext;
760 readonly destinationRepository: BitbucketRepositoryLocator;
761 readonly sourceRepositoryName: string;
762 readonly isCrossRepository: boolean;
763 }) {
764 if (
765 input.context?.provider.kind === "bitbucket" &&
766 !input.isCrossRepository &&
767 parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
768 ) {
769 return input.context.remoteName;
770 }
771​
772 if (!input.isCrossRepository) {
773 const remoteName = yield* git
774 .resolvePrimaryRemoteName(input.cwd)
775 .pipe(Effect.orElseSucceed(() => null));
776 if (remoteName) return remoteName;
777 }
778​
779 const cloneUrls = yield* getRepository({
780 cwd: input.cwd,
781 repository: input.sourceRepositoryName,
782 ...(input.context ? { context: input.context } : {}),
783 }).pipe(Effect.map(normalizeRepositoryCloneUrls));
784 const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
785 return yield* git.ensureRemote({
786 cwd: input.cwd,
787 preferredName: input.isCrossRepository
788 ? repositoryOwnerName(input.sourceRepositoryName)
789 : input.destinationRepository.workspace,
790 url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
791 });
792 });
793​
794 // A pull request's diff, diffstat and conflicts are served as redirects to a commit-range
795 // URL, and the client does not follow redirects unless asked. The hop stays on the same host,
796 // so the credentials travel with it.
797 /**
798 * The one host these credentials may be sent to. A url that came back inside a response — a
799 * pagination cursor, or the target of a redirect — is data, not instruction, so it is checked
800 * against this before the account's token travels with it.
801 */
802 const apiOrigin = originOf(config.baseUrl);
803​
804 const trustedUrl = (value: string): string | null => {
805 if (!/^https?:\/\//u.test(value)) return apiUrl(value);
806 const origin = originOf(value);
807 return origin !== null && origin === apiOrigin ? value : null;
808 };
809​
810 /**
811 * Redirects are followed here rather than by the client, which forwards every header to
812 * whatever host it is sent to. A pull request diff, diffstat and conflicts are all served as
813 * redirects, so they have to be followed — but only back to the same Bitbucket.
814 */
815 const send = (input: {
816 readonly method: "GET" | "POST" | "PUT" | "DELETE";
817 readonly url: string;
818 readonly body?: string;
819 readonly redirects: number;
820 }): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
821 const url = trustedUrl(input.url);
822 if (url === null) {
823 return Effect.fail(
824 new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
825 );
826 }
827 const base =
828 input.method === "GET"
829 ? HttpClientRequest.get(url)
830 : input.method === "POST"
831 ? HttpClientRequest.post(url)
832 : input.method === "DELETE"
833 ? HttpClientRequest.make("DELETE")(url)
834 : HttpClientRequest.put(url);
835 // No `Accept: application/json`: the diff endpoints answer with a patch, not JSON.
836 const withBody =
837 input.body === undefined
838 ? base
839 : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
840 return httpClient.execute(withAuth(withBody)).pipe(
841 Effect.mapError(
842 (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
843 ),
844 Effect.flatMap((response) => {
845 const location = response.headers.location;
846 if (
847 response.status >= 300 &&
848 response.status < 400 &&
849 location !== undefined &&
850 input.redirects < MAX_REDIRECTS
851 ) {
852 return send({
853 ...input,
854 url: new URL(location, url).toString(),
855 redirects: input.redirects + 1,
856 });
857 }
858 return Effect.succeed(response);
859 }),
860 );
861 };
862​
863 const request: BitbucketApi["Service"]["request"] = (input) =>
864 send({ ...input, redirects: 0 }).pipe(
865 Effect.flatMap((response) =>
866 HttpClientResponse.matchStatus({
867 // Read through the body stream rather than `text`, so an oversized diff is stopped
868 // as it arrives instead of being materialized whole and then cut. The same collector
869 // the process runner bounds command output with.
870 "2xx": (success) =>
871 collectUint8StreamText({
872 stream: success.stream,
873 maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
874 }).pipe(
875 Effect.mapError(
876 (cause) =>
877 new BitbucketResponseBodyReadError({
878 operation: "request",
879 status: success.status,
880 cause,
881 }),
882 ),
883 Effect.map((collected) => ({
884 body: collected.text,
885 truncated: collected.truncated,
886 })),
887 ),
888 orElse: (failed) => responseError("request", failed),
889 })(response),
890 ),
891 );
892​
893 return BitbucketApi.of({
894 request,
895 probeAuth: executeJson(
896 "probeAuth",
897 HttpClientRequest.get(apiUrl("/user")),
898 BitbucketUserSchema,
899 ).pipe(
900 Effect.map((user) => ({
901 status: "authenticated" as const,
902 account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
903 host: Option.some("bitbucket.org"),
904 detail: Option.none<string>(),
905 })),
906 Effect.orElseSucceed(() => authFromConfig(config)),
907 ),
908 listPullRequests: (input) =>
909 resolveRepository(input).pipe(
910 Effect.flatMap((repository) => {
911 const states = toBitbucketStates(input.state);
912 const query: Record<string, string | ReadonlyArray<string>> = {
913 pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
914 sort: "-updated_on",
915 q: bitbucketQueryString([
916 `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
917 bitbucketStateFilter(states),
918 ]),
919 state: states,
920 };
921​
922 return executeJson(
923 "listPullRequests",
924 HttpClientRequest.get(
925 apiUrl(
926 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
927 ),
928 { urlParams: query },
929 ),
930 BitbucketPullRequestListSchema,
931 );
932 }),
933 Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
934 ),
935 getPullRequest: (input) =>
936 getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord)),
937 getRepositoryCloneUrls: (input) =>
938 getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
939 createRepository: (input) =>
940 requireRepositoryLocator(input.repository).pipe(
941 Effect.flatMap((repository) =>
942 executeJson(
943 "createRepository",
944 HttpClientRequest.post(
945 apiUrl(
946 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
947 ),
948 ).pipe(
949 HttpClientRequest.bodyJsonUnsafe({
950 scm: "git",
951 is_private: input.visibility === "private",
952 }),
953 ),
954 RawBitbucketRepositorySchema,
955 ),
956 ),
957 Effect.map(normalizeRepositoryCloneUrls),
958 ),
959 createPullRequest: (input) =>
960 Effect.gen(function* () {
961 const repository = yield* resolveRepository(input);
962 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
963 Effect.mapError(
964 (cause) =>
965 new BitbucketPullRequestBodyReadError({
966 cwd: input.cwd,
967 bodyFile: input.bodyFile,
968 cause,
969 }),
970 ),
971 );
972 const sourceOwner = sourceWorkspace(input);
973 const body = {
974 title: input.title,
975 description,
976 source: {
977 branch: {
978 name: SourceControlProvider.sourceBranch(input),
979 },
980 ...(sourceOwner
981 ? {
982 repository: {
983 full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
984 },
985 }
986 : {}),
987 },
988 destination: {
989 branch: {
990 name: input.target?.refName ?? input.baseBranch,
991 },
992 },
993 };
994​
995 yield* executeJson(
996 "createPullRequest",
997 HttpClientRequest.post(
998 apiUrl(
999 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1000 ),
1001 ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1002 BitbucketPullRequestSchema,
1003 );
1004 }),
1005 getDefaultBranch: (input) =>
1006 resolveRepository(input).pipe(
1007 Effect.flatMap((locator) =>
1008 Effect.all(
1010 repository: getRepositoryFromLocator(locator),
1011 branchingModel: getBranchingModelFromLocator(locator).pipe(
1012 Effect.orElseSucceed(
1013 (): typeof RawBitbucketBranchingModelSchema.Type | null => null,
1014 ),
1015 ),
1016 },
1017 { concurrency: "unbounded" },
1018 ),
1019 ),
1020 Effect.map(defaultChangeRequestTargetBranch),
1021 ),
1022 // Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
1023 // an official checkout CLI. This provider-local path uses GitVcsDriver as a
1024 // narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
1025 // as the source-control provider model: if we support non-Git-compatible
1026 // hosting providers or native JJ/Sapling checkout flows, move this into a
1027 // VCS-specific change-request checkout capability.
1028 checkoutPullRequest: (input) =>
1029 Effect.gen(function* () {
1030 const destinationRepository = yield* resolveRepository(input);
1031 const pullRequest = yield* getRawPullRequestFromRepository(
1032 destinationRepository,
1033 input.reference,
1034 );
1035 const destinationRepositoryName =
1036 repositoryNameWithOwner(pullRequest.destination.repository) ??
1037 `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
1038 const sourceRepositoryName =
1039 repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
1040 const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
1041 const remoteName = yield* resolveCheckoutRemote({
1042 cwd: input.cwd,
1043 destinationRepository,
1044 sourceRepositoryName,
1045 isCrossRepository,
1046 ...(input.context ? { context: input.context } : {}),
1047 });
1048 const remoteBranch = pullRequest.source.branch.name;
1049 const localBranch = checkoutBranchName({
1050 pullRequestId: pullRequest.id,
1051 headBranch: remoteBranch,
1052 isCrossRepository,
1053 });
1054 const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
1055 const localBranchExists = localBranchNames.includes(localBranch);
1056​
1057 if (input.force === true || !localBranchExists) {
1058 yield* git.fetchRemoteBranch({
1059 cwd: input.cwd,
1060 remoteName,
1061 remoteBranch,
1062 localBranch,
1063 });
1064 } else {
1065 yield* git.fetchRemoteTrackingBranch({
1066 cwd: input.cwd,
1067 remoteName,
1068 remoteBranch,
1069 });
1071​
1072 yield* git.setBranchUpstream({
1073 cwd: input.cwd,
1074 branch: localBranch,
1075 remoteName,
1076 remoteBranch,
1077 });
1078 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
1079 }).pipe(
1080 Effect.mapError((cause) =>
1081 isBitbucketApiError(cause)
1082 ? cause
1083 : new BitbucketCheckoutError({
1084 cwd: input.cwd,
1085 reference: input.reference,
1086 cause,
1087 }),
1088 ),
1089 ),
1090 });
1091});
1092​
1093export const layer = Layer.effect(BitbucketApi, make);