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

BitbucketApi.ts

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