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

BitbucketApi.ts

762 lines26.0 KB

1import { Config, Context, Effect, FileSystem, Layer, Option, Schema } from "effect";
2import {
3 TrimmedNonEmptyString,
4 type SourceControlProviderAuth,
5 type SourceControlRepositoryCloneUrls,
6 type SourceControlRepositoryVisibility,
7} from "@t3tools/contracts";
8import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
9import { sanitizeBranchFragment } from "@t3tools/shared/git";
10import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
11​
12import * as BitbucketPullRequests from "./bitbucketPullRequests.ts";
13import * as SourceControlProvider from "./SourceControlProvider.ts";
14import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
15import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
16​
17const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
18​
19const BitbucketApiEnvConfig = Config.all({
20 baseUrl: Config.string("T3CODE_BITBUCKET_API_BASE_URL").pipe(
21 Config.withDefault(DEFAULT_API_BASE_URL),
22 ),
23 accessToken: Config.string("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
24 email: Config.string("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
25 apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
26});
27​
28export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
29 "BitbucketApiError",
30 {
31 operation: Schema.String,
32 detail: Schema.String,
33 status: Schema.optional(Schema.Number),
34 cause: Schema.optional(Schema.Defect),
35 },
36) {
37 override get message(): string {
38 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
39 }
41​
42const RawBitbucketRepositorySchema = Schema.Struct({
43 full_name: TrimmedNonEmptyString,
44 links: Schema.Struct({
45 html: Schema.optional(
46 Schema.Struct({
47 href: TrimmedNonEmptyString,
48 }),
49 ),
50 clone: Schema.optional(
51 Schema.Array(
52 Schema.Struct({
53 name: TrimmedNonEmptyString,
54 href: TrimmedNonEmptyString,
55 }),
56 ),
57 ),
58 }),
59 mainbranch: Schema.optional(
60 Schema.NullOr(
61 Schema.Struct({
62 name: TrimmedNonEmptyString,
63 }),
64 ),
65 ),
66});
67​
68const RawBitbucketBranchingModelSchema = Schema.Struct({
69 development: Schema.optional(
70 Schema.Struct({
71 branch: Schema.optional(
72 Schema.NullOr(
73 Schema.Struct({
74 name: Schema.optional(TrimmedNonEmptyString),
75 }),
76 ),
77 ),
78 is_valid: Schema.optional(Schema.Boolean),
79 name: Schema.optional(Schema.NullOr(Schema.String)),
80 use_mainbranch: Schema.optional(Schema.Boolean),
81 }),
82 ),
83});
84​
85const BitbucketUserSchema = Schema.Struct({
86 username: Schema.optional(TrimmedNonEmptyString),
87 display_name: Schema.optional(TrimmedNonEmptyString),
88 account_id: Schema.optional(TrimmedNonEmptyString),
89});
90​
91export interface BitbucketRepositoryLocator {
92 readonly workspace: string;
93 readonly repoSlug: string;
95​
96export interface BitbucketApiShape {
97 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
98 readonly listPullRequests: (input: {
99 readonly cwd: string;
100 readonly context?: SourceControlProvider.SourceControlProviderContext;
101 readonly headSelector: string;
102 readonly source?: SourceControlProvider.SourceControlRefSelector;
103 readonly state: "open" | "closed" | "merged" | "all";
104 readonly limit?: number;
105 }) => Effect.Effect<
106 ReadonlyArray<BitbucketPullRequests.NormalizedBitbucketPullRequestRecord>,
107 BitbucketApiError
108 >;
109 readonly getPullRequest: (input: {
110 readonly cwd: string;
111 readonly context?: SourceControlProvider.SourceControlProviderContext;
112 readonly reference: string;
113 }) => Effect.Effect<
114 BitbucketPullRequests.NormalizedBitbucketPullRequestRecord,
115 BitbucketApiError
116 >;
117 readonly getRepositoryCloneUrls: (input: {
118 readonly cwd: string;
119 readonly context?: SourceControlProvider.SourceControlProviderContext;
120 readonly repository: string;
121 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
122 readonly createRepository: (input: {
123 readonly cwd: string;
124 readonly repository: string;
125 readonly visibility: SourceControlRepositoryVisibility;
126 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
127 readonly createPullRequest: (input: {
128 readonly cwd: string;
129 readonly context?: SourceControlProvider.SourceControlProviderContext;
130 readonly baseBranch: string;
131 readonly headSelector: string;
132 readonly source?: SourceControlProvider.SourceControlRefSelector;
133 readonly target?: SourceControlProvider.SourceControlRefSelector;
134 readonly title: string;
135 readonly bodyFile: string;
136 }) => Effect.Effect<void, BitbucketApiError>;
137 readonly getDefaultBranch: (input: {
138 readonly cwd: string;
139 readonly context?: SourceControlProvider.SourceControlProviderContext;
140 }) => Effect.Effect<string | null, BitbucketApiError>;
141 readonly checkoutPullRequest: (input: {
142 readonly cwd: string;
143 readonly context?: SourceControlProvider.SourceControlProviderContext;
144 readonly reference: string;
145 readonly force?: boolean;
146 }) => Effect.Effect<void, BitbucketApiError>;
148​
149export class BitbucketApi extends Context.Service<BitbucketApi, BitbucketApiShape>()(
150 "t3/source-control/BitbucketApi",
151) {}
152​
153function nonEmpty(value: string | undefined): Option.Option<string> {
154 const trimmed = value?.trim();
155 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
157​
158function normalizeChangeRequestId(reference: string): string {
159 const trimmed = reference.trim().replace(/^#/, "");
160 const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
161 trimmed,
162 );
163 return urlMatch?.[1] ?? trimmed;
165​
166function sourceWorkspace(input: {
167 readonly headSelector: string;
168 readonly source?: SourceControlProvider.SourceControlRefSelector;
169}): string | undefined {
170 if (input.source?.owner) return input.source.owner;
171 return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
173​
174function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
175 switch (state) {
176 case "open":
177 return ["OPEN"];
178 case "closed":
179 return ["DECLINED", "SUPERSEDED"];
180 case "merged":
181 return ["MERGED"];
182 case "all":
183 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
184 }
186​
187function bitbucketQueryString(filters: ReadonlyArray<string>): string {
188 return filters.join(" AND ");
190​
191function bitbucketStateFilter(states: ReadonlyArray<string>): string {
192 return states.length === 1
193 ? `state = "${states[0]}"`
194 : `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
196​
197function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
198 const normalized = value.trim().replace(/\.git$/u, "");
199 const parts = normalized.split("/").filter((part) => part.length > 0);
200 if (parts.length < 2) return null;
201 const workspace = parts.at(-2);
202 const repoSlug = parts.at(-1);
203 return workspace && repoSlug ? { workspace, repoSlug } : null;
205​
206function requireRepositoryLocator(
207 operation: string,
208 repository: string,
209): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
210 const locator = parseBitbucketRepositorySlug(repository);
211 return locator
212 ? Effect.succeed(locator)
213 : Effect.fail(
214 new BitbucketApiError({
215 operation,
216 detail: "Bitbucket repositories must be specified as workspace/repository.",
217 }),
218 );
220​
221function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
222 const trimmed = remoteUrl.trim();
223 if (trimmed.startsWith("git@")) {
224 const pathStart = trimmed.indexOf(":");
225 return pathStart < 0 ? null : parseBitbucketRepositorySlug(trimmed.slice(pathStart + 1));
226 }
227​
228 try {
229 return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
230 } catch {
231 return null;
232 }
234​
235function normalizeRepositoryCloneUrls(
236 raw: typeof RawBitbucketRepositorySchema.Type,
237): SourceControlRepositoryCloneUrls {
238 const httpClone =
239 raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
240 raw.links.html?.href;
241 const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;
242​
243 return {
244 nameWithOwner: raw.full_name,
245 url: httpClone ?? raw.links.html?.href ?? raw.full_name,
246 sshUrl: sshClone ?? httpClone ?? raw.full_name,
247 };
249​
250function defaultChangeRequestTargetBranch(input: {
251 readonly repository: typeof RawBitbucketRepositorySchema.Type;
252 readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
253}): string | null {
254 const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
255 const development = input.branchingModel?.development;
256 if (!development || development.use_mainbranch === true || development.is_valid === false) {
257 return repositoryMainBranch;
258 }
259​
260 const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
261 if (developmentBranch.length === 0 || developmentBranch === "null") {
262 return repositoryMainBranch;
263 }
264​
265 return developmentBranch;
267​
268function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
269 const trimmed = originRemoteUrl?.trim() ?? "";
270 return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
272​
273function selectCloneUrl(input: {
274 readonly cloneUrls: SourceControlRepositoryCloneUrls;
275 readonly originRemoteUrl: string | null;
276}): string {
277 return shouldPreferSshRemote(input.originRemoteUrl)
278 ? input.cloneUrls.sshUrl
279 : input.cloneUrls.url;
281​
282function checkoutBranchName(input: {
283 readonly pullRequestId: number;
284 readonly headBranch: string;
285 readonly isCrossRepository: boolean;
286}): string {
287 if (!input.isCrossRepository) {
288 return input.headBranch;
289 }
290​
291 return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
293​
294function repositoryNameWithOwner(
295 repository: Schema.Schema.Type<
296 typeof BitbucketPullRequests.BitbucketPullRequestSchema
297 >["source"]["repository"],
298): string | null {
299 const fullName = repository?.full_name?.trim() ?? "";
300 return fullName.length > 0 ? fullName : null;
302​
303function repositoryOwnerName(repositoryName: string): string {
304 return repositoryName.split("/")[0]?.trim() || "bitbucket";
306​
307function authFromConfig(
308 config: Config.Success<typeof BitbucketApiEnvConfig>,
309): SourceControlProviderAuth {
310 if (Option.isSome(config.accessToken)) {
311 return {
312 status: "unknown",
313 account: Option.none(),
314 host: Option.some("bitbucket.org"),
315 detail: Option.some("Bitbucket access token is configured."),
316 };
317 }
318​
319 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
320 return {
321 status: "unknown",
322 account: config.email,
323 host: Option.some("bitbucket.org"),
324 detail: Option.some("Bitbucket API token is configured."),
325 };
326 }
327​
328 return {
329 status: "unauthenticated",
330 account: Option.none(),
331 host: Option.some("bitbucket.org"),
332 detail: Option.some(
333 "Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
334 ),
335 };
337​
338function requestError(operation: string, cause: unknown): BitbucketApiError {
339 return new BitbucketApiError({
340 operation,
341 detail: cause instanceof Error ? cause.message : String(cause),
342 cause,
343 });
345​
346function isBitbucketApiError(cause: unknown): cause is BitbucketApiError {
347 return Schema.is(BitbucketApiError)(cause);
349​
350function responseError(
351 operation: string,
352 response: HttpClientResponse.HttpClientResponse,
353): Effect.Effect<never, BitbucketApiError> {
354 return response.text.pipe(
355 Effect.catch(() => Effect.succeed("")),
356 Effect.flatMap((body) =>
357 Effect.fail(
358 new BitbucketApiError({
359 operation,
360 status: response.status,
361 detail:
362 body.trim().length > 0
363 ? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
364 : `Bitbucket returned HTTP ${response.status}.`,
365 }),
366 ),
367 ),
368 );
370​
371export const make = Effect.fn("makeBitbucketApi")(function* () {
372 const config = yield* BitbucketApiEnvConfig;
373 const httpClient = yield* HttpClient.HttpClient;
374 const fileSystem = yield* FileSystem.FileSystem;
375 const git = yield* GitVcsDriver.GitVcsDriver;
376 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
377​
378 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
379​
380 const withAuth = (request: HttpClientRequest.HttpClientRequest) => {
381 if (Option.isSome(config.accessToken)) {
382 return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));
383 }
384 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
385 return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));
386 }
387 return request;
388 };
389​
390 const decodeResponse = <S extends Schema.Top>(
391 operation: string,
392 schema: S,
393 response: HttpClientResponse.HttpClientResponse,
394 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
395 HttpClientResponse.matchStatus({
396 "2xx": (success) =>
397 HttpClientResponse.schemaBodyJson(schema)(success).pipe(
398 Effect.mapError(
399 (cause) =>
400 new BitbucketApiError({
401 operation,
402 detail: "Bitbucket returned invalid JSON for the requested resource.",
403 cause,
404 }),
405 ),
406 ),
407 orElse: (failed) => responseError(operation, failed),
408 })(response);
409​
410 const executeJson = <S extends Schema.Top>(
411 operation: string,
412 request: HttpClientRequest.HttpClientRequest,
413 schema: S,
414 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
415 httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
416 Effect.mapError((cause) => requestError(operation, cause)),
417 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
418 );
419​
420 const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
421 readonly cwd: string;
422 readonly context?: SourceControlProvider.SourceControlProviderContext;
423 readonly repository?: string;
424 }) {
425 const fromRepository =
426 input.repository !== undefined ? parseBitbucketRepositorySlug(input.repository) : null;
427 if (fromRepository) return fromRepository;
428​
429 const fromContext =
430 input.context?.provider.kind === "bitbucket"
431 ? parseBitbucketRemoteUrl(input.context.remoteUrl)
432 : null;
433 if (fromContext) return fromContext;
434​
435 const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
436 Effect.mapError(
437 (cause) =>
438 new BitbucketApiError({
439 operation: "resolveRepository",
440 detail: `Failed to resolve VCS repository for ${input.cwd}.`,
441 cause,
442 }),
443 ),
444 );
445 const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
446 Effect.mapError(
447 (cause) =>
448 new BitbucketApiError({
449 operation: "resolveRepository",
450 detail: `Failed to list remotes for ${input.cwd}.`,
451 cause,
452 }),
453 ),
454 );
455​
456 for (const remote of remotes.remotes) {
457 if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
458 const parsed = parseBitbucketRemoteUrl(remote.url);
459 if (parsed) return parsed;
460 }
461​
462 return yield* new BitbucketApiError({
463 operation: "resolveRepository",
464 detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
465 });
466 });
467​
468 const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
469 executeJson(
470 "getRepository",
471 HttpClientRequest.get(
472 apiUrl(
473 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
474 ),
475 ),
476 RawBitbucketRepositorySchema,
477 );
478​
479 const getRepository = (input: {
480 readonly cwd: string;
481 readonly context?: SourceControlProvider.SourceControlProviderContext;
482 readonly repository?: string;
483 }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
484​
485 const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
486 executeJson(
487 "getBranchingModel",
488 HttpClientRequest.get(
489 apiUrl(
490 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
491 ),
492 ),
493 RawBitbucketBranchingModelSchema,
494 );
495​
496 const getRawPullRequestFromRepository = (
497 repository: BitbucketRepositoryLocator,
498 reference: string,
499 ) =>
500 executeJson(
501 "getPullRequest",
502 HttpClientRequest.get(
503 apiUrl(
504 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
505 ),
506 ),
507 BitbucketPullRequests.BitbucketPullRequestSchema,
508 );
509​
510 const getRawPullRequest = (input: {
511 readonly cwd: string;
512 readonly context?: SourceControlProvider.SourceControlProviderContext;
513 readonly reference: string;
514 }) =>
515 resolveRepository(input).pipe(
516 Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
517 );
518​
519 const readConfigValueNullable = (cwd: string, key: string) =>
520 git.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
521​
522 const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
523 readonly cwd: string;
524 readonly context?: SourceControlProvider.SourceControlProviderContext;
525 readonly destinationRepository: BitbucketRepositoryLocator;
526 readonly sourceRepositoryName: string;
527 readonly isCrossRepository: boolean;
528 }) {
529 if (
530 input.context?.provider.kind === "bitbucket" &&
531 !input.isCrossRepository &&
532 parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
533 ) {
534 return input.context.remoteName;
535 }
536​
537 if (!input.isCrossRepository) {
538 const remoteName = yield* git
539 .resolvePrimaryRemoteName(input.cwd)
540 .pipe(Effect.catch(() => Effect.succeed(null)));
541 if (remoteName) return remoteName;
542 }
543​
544 const cloneUrls = yield* getRepository({
545 cwd: input.cwd,
546 repository: input.sourceRepositoryName,
547 ...(input.context ? { context: input.context } : {}),
548 }).pipe(Effect.map(normalizeRepositoryCloneUrls));
549 const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
550 return yield* git.ensureRemote({
551 cwd: input.cwd,
552 preferredName: input.isCrossRepository
553 ? repositoryOwnerName(input.sourceRepositoryName)
554 : input.destinationRepository.workspace,
555 url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
556 });
557 });
558​
559 return BitbucketApi.of({
560 probeAuth: executeJson(
561 "probeAuth",
562 HttpClientRequest.get(apiUrl("/user")),
563 BitbucketUserSchema,
564 ).pipe(
565 Effect.map((user) => ({
566 status: "authenticated" as const,
567 account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
568 host: Option.some("bitbucket.org"),
569 detail: Option.none<string>(),
570 })),
571 Effect.catch(() => Effect.succeed(authFromConfig(config))),
572 ),
573 listPullRequests: (input) =>
574 resolveRepository(input).pipe(
575 Effect.flatMap((repository) => {
576 const states = toBitbucketStates(input.state);
577 const query: Record<string, string | ReadonlyArray<string>> = {
578 pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
579 sort: "-updated_on",
580 q: bitbucketQueryString([
581 `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
582 bitbucketStateFilter(states),
583 ]),
584 state: states,
585 };
586​
587 return executeJson(
588 "listPullRequests",
589 HttpClientRequest.get(
590 apiUrl(
591 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
592 ),
593 { urlParams: query },
594 ),
595 BitbucketPullRequests.BitbucketPullRequestListSchema,
596 );
597 }),
598 Effect.map((list) =>
599 list.values.map(BitbucketPullRequests.normalizeBitbucketPullRequestRecord),
600 ),
601 ),
602 getPullRequest: (input) =>
603 getRawPullRequest(input).pipe(
604 Effect.map(BitbucketPullRequests.normalizeBitbucketPullRequestRecord),
605 ),
606 getRepositoryCloneUrls: (input) =>
607 getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
608 createRepository: (input) =>
609 requireRepositoryLocator("createRepository", input.repository).pipe(
610 Effect.flatMap((repository) =>
611 executeJson(
612 "createRepository",
613 HttpClientRequest.post(
614 apiUrl(
615 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
616 ),
617 ).pipe(
618 HttpClientRequest.bodyJsonUnsafe({
619 scm: "git",
620 is_private: input.visibility === "private",
621 }),
622 ),
623 RawBitbucketRepositorySchema,
624 ),
625 ),
626 Effect.map(normalizeRepositoryCloneUrls),
627 ),
628 createPullRequest: (input) =>
629 Effect.gen(function* () {
630 const repository = yield* resolveRepository(input);
631 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
632 Effect.mapError(
633 (cause) =>
634 new BitbucketApiError({
635 operation: "createPullRequest",
636 detail: `Failed to read pull request body file ${input.bodyFile}.`,
637 cause,
638 }),
639 ),
640 );
641 const sourceOwner = sourceWorkspace(input);
642 const body = {
643 title: input.title,
644 description,
645 source: {
646 branch: {
647 name: SourceControlProvider.sourceBranch(input),
648 },
649 ...(sourceOwner
650 ? {
651 repository: {
652 full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
653 },
654 }
655 : {}),
656 },
657 destination: {
658 branch: {
659 name: input.target?.refName ?? input.baseBranch,
660 },
661 },
662 };
663​
664 yield* executeJson(
665 "createPullRequest",
666 HttpClientRequest.post(
667 apiUrl(
668 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
669 ),
670 ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
671 BitbucketPullRequests.BitbucketPullRequestSchema,
672 );
673 }),
674 getDefaultBranch: (input) =>
675 resolveRepository(input).pipe(
676 Effect.flatMap((locator) =>
677 Effect.all(
678 {
679 repository: getRepositoryFromLocator(locator),
680 branchingModel: getBranchingModelFromLocator(locator).pipe(
681 Effect.catch(() =>
682 Effect.succeed<typeof RawBitbucketBranchingModelSchema.Type | null>(null),
683 ),
684 ),
685 },
686 { concurrency: "unbounded" },
687 ),
688 ),
689 Effect.map(defaultChangeRequestTargetBranch),
690 ),
691 // Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
692 // an official checkout CLI. This provider-local path uses GitVcsDriver as a
693 // narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
694 // as the source-control provider model: if we support non-Git-compatible
695 // hosting providers or native JJ/Sapling checkout flows, move this into a
696 // VCS-specific change-request checkout capability.
697 checkoutPullRequest: (input) =>
698 Effect.gen(function* () {
699 const destinationRepository = yield* resolveRepository(input);
700 const pullRequest = yield* getRawPullRequestFromRepository(
701 destinationRepository,
702 input.reference,
703 );
704 const destinationRepositoryName =
705 repositoryNameWithOwner(pullRequest.destination.repository) ??
706 `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
707 const sourceRepositoryName =
708 repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
709 const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
710 const remoteName = yield* resolveCheckoutRemote({
711 cwd: input.cwd,
712 destinationRepository,
713 sourceRepositoryName,
714 isCrossRepository,
715 ...(input.context ? { context: input.context } : {}),
716 });
717 const remoteBranch = pullRequest.source.branch.name;
718 const localBranch = checkoutBranchName({
719 pullRequestId: pullRequest.id,
720 headBranch: remoteBranch,
721 isCrossRepository,
722 });
723 const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
724 const localBranchExists = localBranchNames.includes(localBranch);
725​
726 if (input.force === true || !localBranchExists) {
727 yield* git.fetchRemoteBranch({
728 cwd: input.cwd,
729 remoteName,
730 remoteBranch,
731 localBranch,
732 });
733 } else {
734 yield* git.fetchRemoteTrackingBranch({
735 cwd: input.cwd,
736 remoteName,
737 remoteBranch,
738 });
739 }
740​
741 yield* git.setBranchUpstream({
742 cwd: input.cwd,
743 branch: localBranch,
744 remoteName,
745 remoteBranch,
746 });
747 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
748 }).pipe(
749 Effect.mapError((cause) =>
750 isBitbucketApiError(cause)
751 ? cause
752 : new BitbucketApiError({
753 operation: "checkoutPullRequest",
754 detail: cause instanceof Error ? cause.message : String(cause),
755 cause,
756 }),
757 ),
758 ),
759 });
760});
761​
762export const layer = Layer.effect(BitbucketApi, make());