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

BitbucketApi.ts

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