The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { SourceControlProviderKind } from "@t3tools/contracts"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as FileSystem from "effect/FileSystem"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import * as Result from "effect/Result"; |
| 6 | import * as Schema from "effect/Schema"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import { |
| 9 | PositiveInt, |
| 10 | SourceControlProviderError, |
| 11 | TrimmedNonEmptyString, |
| 12 | type ChangeRequest, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import { |
| 15 | probeSourceControlProvider, |
| 16 | providerAuth, |
| 17 | type SourceControlCliDiscoverySpec, |
| 18 | type SourceControlManagedCliDiscoverySpec, |
| 19 | } from "@t3tools/source-control-core/server/discovery"; |
| 20 | import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid"; |
| 21 | import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; |
| 22 | import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; |
| 23 | import { isSshRemoteUrl } from "@t3tools/shared/sourceControl"; |
| 24 | import { parsePullRequestUrl } from "../shared/definition.ts"; |
| 25 | |
| 26 | import * as GitCafeApi from "./GitCafeApi.ts"; |
| 27 | import * as GitCafeCredentials from "./GitCafeCredentials.ts"; |
| 28 | import * as GitCafeHosts from "./gitCafeHosts.ts"; |
| 29 | |
| 30 | const AUTH_HOST = "git.cafe"; |
| 31 | const ADMISSION_TIMEOUT = "30 seconds"; |
| 32 | const ADMISSION_POLL_INTERVAL = "500 millis"; |
| 33 | const cliArgs = (host: string) => [ |
| 34 | "--host", |
| 35 | `https://${host}/api`, |
| 36 | "--no-input", |
| 37 | "--no-update-check", |
| 38 | ]; |
| 39 | |
| 40 | const decodeAuth = Schema.decodeUnknownResult( |
| 41 | Schema.fromJsonString( |
| 42 | Schema.Struct({ |
| 43 | schemaVersion: Schema.Literal(1), |
| 44 | data: Schema.Struct({ host: Schema.String, username: TrimmedNonEmptyString }), |
| 45 | }), |
| 46 | ), |
| 47 | ); |
| 48 | const decodeFailure = Schema.decodeUnknownResult( |
| 49 | Schema.fromJsonString( |
| 50 | Schema.Struct({ |
| 51 | schemaVersion: Schema.Literal(1), |
| 52 | error: Schema.Struct({ |
| 53 | code: Schema.String, |
| 54 | message: Schema.String, |
| 55 | status: Schema.NullOr(Schema.Finite), |
| 56 | }), |
| 57 | }), |
| 58 | ), |
| 59 | ); |
| 60 | const cliFailure = (output: string) => |
| 61 | [output.trim(), ...output.split(/\r?\n/u).toReversed()] |
| 62 | .map((line) => decodeFailure(line.trim())) |
| 63 | .find(Result.isSuccess)?.success.error; |
| 64 | |
| 65 | const cliDiscovery = { |
| 66 | type: "cli", |
| 67 | kind: SourceControlProviderKind.make("gitcafe"), |
| 68 | label: "GitCafe", |
| 69 | executable: "cafe", |
| 70 | versionArgs: ["--version"], |
| 71 | authArgs: [...cliArgs(AUTH_HOST), "auth", "status", "--json"], |
| 72 | parseAuth: (input) => { |
| 73 | const signedIn = decodeAuth(input.stdout.trim()); |
| 74 | if (input.exitCode === 0 && Result.isSuccess(signedIn)) |
| 75 | return providerAuth({ |
| 76 | status: "authenticated", |
| 77 | host: AUTH_HOST, |
| 78 | account: signedIn.success.data.username, |
| 79 | }); |
| 80 | const failure = cliFailure(input.stderr) ?? cliFailure(input.stdout); |
| 81 | if (failure) |
| 82 | return providerAuth({ |
| 83 | // Forbidden/offline responses do not establish that a login is gone. |
| 84 | status: |
| 85 | failure.code === "AUTHENTICATION_REQUIRED" || failure.status === 401 |
| 86 | ? "unauthenticated" |
| 87 | : "unknown", |
| 88 | host: AUTH_HOST, |
| 89 | detail: failure.message, |
| 90 | }); |
| 91 | return providerAuth({ |
| 92 | status: "unknown", |
| 93 | host: AUTH_HOST, |
| 94 | detail: `GitCafe authentication status could not be read. Run \`cafe auth login --host https://${AUTH_HOST}/api\`.`, |
| 95 | }); |
| 96 | }, |
| 97 | installHint: `Install the GitCafe CLI with \`bun install -g @gitcafe/cli\`, then run \`cafe auth login --host https://${AUTH_HOST}/api\`, save a token in Settings, or set CAFE_TOKEN on the server.`, |
| 98 | } satisfies SourceControlCliDiscoverySpec; |
| 99 | |
| 100 | export const parseAuth = cliDiscovery.parseAuth; |
| 101 | |
| 102 | export const makeDiscovery = Effect.gen(function* () { |
| 103 | const { process } = yield* SourceControlHost.SourceControlHost; |
| 104 | const credentials = yield* GitCafeCredentials.GitCafeCredentials; |
| 105 | return { |
| 106 | type: "managed-cli", |
| 107 | kind: cliDiscovery.kind, |
| 108 | label: cliDiscovery.label, |
| 109 | installHint: cliDiscovery.installHint, |
| 110 | probe: (cwd: string) => |
| 111 | credentials.cliEnv(AUTH_HOST).pipe( |
| 112 | Effect.result, |
| 113 | Effect.flatMap((env) => |
| 114 | probeSourceControlProvider({ |
| 115 | cwd, |
| 116 | spec: cliDiscovery, |
| 117 | process: { |
| 118 | run: (input) => |
| 119 | process.run({ |
| 120 | ...input, |
| 121 | env: { ...input.env, ...(Result.isSuccess(env) ? env.success : {}) }, |
| 122 | }), |
| 123 | }, |
| 124 | }).pipe( |
| 125 | Effect.map((item) => |
| 126 | Result.isSuccess(env) |
| 127 | ? item |
| 128 | : { |
| 129 | ...item, |
| 130 | auth: providerAuth({ |
| 131 | status: "unauthenticated", |
| 132 | host: AUTH_HOST, |
| 133 | detail: env.failure.message, |
| 134 | }), |
| 135 | }, |
| 136 | ), |
| 137 | ), |
| 138 | ), |
| 139 | ), |
| 140 | refineUnknownRemote: () => Effect.succeed(null), |
| 141 | } satisfies SourceControlManagedCliDiscoverySpec; |
| 142 | }); |
| 143 | |
| 144 | const Repository = Schema.Struct({ |
| 145 | name: TrimmedNonEmptyString, |
| 146 | defaultBranch: Schema.NullOr(TrimmedNonEmptyString), |
| 147 | }); |
| 148 | const Pull = Schema.Struct({ |
| 149 | number: PositiveInt, |
| 150 | title: TrimmedNonEmptyString, |
| 151 | state: Schema.Literals(["open", "closed", "merged"]), |
| 152 | draft: Schema.Boolean, |
| 153 | sourceBranch: TrimmedNonEmptyString, |
| 154 | targetBranch: TrimmedNonEmptyString, |
| 155 | headOid: Schema.optional(Schema.NullOr(Schema.String)), |
| 156 | updatedAt: Schema.OptionFromNullOr(Schema.DateTimeUtcFromString), |
| 157 | }); |
| 158 | const PullDetail = Schema.Struct({ |
| 159 | ...Pull.fields, |
| 160 | sourceRepo: Schema.NullOr( |
| 161 | Schema.Struct({ owner: TrimmedNonEmptyString, name: TrimmedNonEmptyString }), |
| 162 | ), |
| 163 | closedAt: Schema.NullOr(Schema.String), |
| 164 | mergedAt: Schema.NullOr(Schema.String), |
| 165 | }); |
| 166 | const Pulls = Schema.Struct({ items: Schema.Array(Pull), next: Schema.NullOr(Schema.String) }); |
| 167 | const RepositoryAdmission = Schema.Struct({ |
| 168 | repoId: TrimmedNonEmptyString, |
| 169 | state: Schema.String, |
| 170 | owner: TrimmedNonEmptyString, |
| 171 | name: TrimmedNonEmptyString, |
| 172 | }); |
| 173 | const RepositoryId = Schema.Struct({ id: TrimmedNonEmptyString }); |
| 174 | const CreatedPull = Schema.Struct({ number: PositiveInt }); |
| 175 | const encodeBranches = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); |
| 176 | |
| 177 | interface Target { |
| 178 | readonly host: GitCafeHosts.GitCafeHost; |
| 179 | readonly repository: string; |
| 180 | } |
| 181 | |
| 182 | const cloneUrls = (target: Target) => ({ |
| 183 | nameWithOwner: target.repository, |
| 184 | url: `https://${target.host}/${target.repository}`, |
| 185 | sshUrl: `ssh@${target.host}:${target.repository}.git`, |
| 186 | }); |
| 187 | |
| 188 | const isSshRemote = (remoteUrl: string | undefined) => |
| 189 | remoteUrl !== undefined && isSshRemoteUrl(remoteUrl); |
| 190 | |
| 191 | export const make = Effect.gen(function* () { |
| 192 | const api = yield* GitCafeApi.GitCafeApi; |
| 193 | const host = yield* SourceControlHost.SourceControlHost; |
| 194 | const fileSystem = yield* FileSystem.FileSystem; |
| 195 | |
| 196 | const error = (operation: string, cwd: string, detail: string, cause?: unknown) => |
| 197 | new SourceControlProviderError({ |
| 198 | provider: SourceControlProviderKind.make("gitcafe"), |
| 199 | operation, |
| 200 | cwd, |
| 201 | detail, |
| 202 | ...(cause === undefined ? {} : { cause }), |
| 203 | }); |
| 204 | const read = <S extends Schema.Codec<unknown, unknown, never, never>>( |
| 205 | operation: string, |
| 206 | cwd: string, |
| 207 | request: Omit<GitCafeApi.GitCafeApiRequest, "operation">, |
| 208 | schema: S, |
| 209 | ) => |
| 210 | api.request({ ...request, operation }).pipe( |
| 211 | Effect.mapError((cause) => error(operation, cwd, cause.detail, cause)), |
| 212 | Effect.flatMap((raw) => |
| 213 | Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe( |
| 214 | Effect.mapError((cause) => |
| 215 | error(operation, cwd, "GitCafe returned an unreadable response.", cause), |
| 216 | ), |
| 217 | ), |
| 218 | ), |
| 219 | ); |
| 220 | const resolveTarget = Effect.fn("GitCafeSourceControlProvider.resolveTarget")(function* ( |
| 221 | operation: string, |
| 222 | input: { |
| 223 | readonly cwd: string; |
| 224 | readonly context?: SourceControlProvider.SourceControlProviderContext; |
| 225 | readonly repository?: string; |
| 226 | }, |
| 227 | ) { |
| 228 | const named = |
| 229 | input.repository === undefined ? null : GitCafeHosts.parseGitCafeRemote(input.repository); |
| 230 | if (named) return named; |
| 231 | const readRemote = host.git |
| 232 | .resolvePrimaryRemoteName(input.cwd) |
| 233 | .pipe( |
| 234 | Effect.flatMap((remote) => host.git.readConfigValue(input.cwd, `remote.${remote}.url`)), |
| 235 | ); |
| 236 | const remoteUrl = |
| 237 | input.context?.remoteUrl ?? |
| 238 | (input.repository === undefined |
| 239 | ? yield* readRemote.pipe( |
| 240 | Effect.mapError((cause) => |
| 241 | error(operation, input.cwd, "Could not read the GitCafe remote.", cause), |
| 242 | ), |
| 243 | ) |
| 244 | : yield* readRemote.pipe(Effect.orElseSucceed(() => null))); |
| 245 | const remote = remoteUrl ? GitCafeHosts.parseGitCafeRemote(remoteUrl) : null; |
| 246 | if (input.repository === undefined) { |
| 247 | if (remote) return remote; |
| 248 | return yield* error(operation, input.cwd, "No GitCafe repository remote was found."); |
| 249 | } |
| 250 | const repository = GitCafeHosts.gitCafeRepositoryPath(input.repository); |
| 251 | if (repository !== null) |
| 252 | return { host: remote?.host ?? AUTH_HOST, repository } satisfies Target; |
| 253 | return yield* error( |
| 254 | operation, |
| 255 | input.cwd, |
| 256 | "A GitCafe repository is named owner/name or by its git.cafe URL.", |
| 257 | ); |
| 258 | }); |
| 259 | |
| 260 | const getPull = Effect.fn("GitCafeSourceControlProvider.getPull")(function* (input: { |
| 261 | readonly cwd: string; |
| 262 | readonly context?: SourceControlProvider.SourceControlProviderContext; |
| 263 | readonly reference: string; |
| 264 | }) { |
| 265 | const match = parsePullRequestUrl(input.reference.trim()); |
| 266 | const urlHost = match === null ? null : GitCafeHosts.gitCafeHost(match.host); |
| 267 | const target: Target = |
| 268 | urlHost && match |
| 269 | ? { host: urlHost, repository: match.repository } |
| 270 | : yield* resolveTarget("getChangeRequest", input); |
| 271 | const number = match |
| 272 | ? urlHost |
| 273 | ? String(match.number) |
| 274 | : undefined |
| 275 | : /^#?([1-9]\d*)$/u.exec(input.reference.trim())?.[1]; |
| 276 | if (number === undefined) |
| 277 | return yield* error( |
| 278 | "getChangeRequest", |
| 279 | input.cwd, |
| 280 | "A GitCafe pull request is a number or a git.cafe pull request URL.", |
| 281 | ); |
| 282 | const pull = yield* read( |
| 283 | "getChangeRequest", |
| 284 | input.cwd, |
| 285 | { host: target.host, path: `/repos/${target.repository}/pulls/${number}` }, |
| 286 | PullDetail, |
| 287 | ); |
| 288 | const owner = target.repository.split("/")[0] ?? null; |
| 289 | return { |
| 290 | provider: SourceControlProviderKind.make("gitcafe"), |
| 291 | number: pull.number, |
| 292 | title: pull.title, |
| 293 | url: `https://${target.host}/${target.repository}/pulls/${pull.number}`, |
| 294 | baseRefName: pull.targetBranch, |
| 295 | headRefName: pull.sourceBranch, |
| 296 | ...(pull.headOid ? { headSha: pull.headOid } : {}), |
| 297 | state: pull.state, |
| 298 | ...(pull.draft ? { isDraft: true } : {}), |
| 299 | closedAt: pull.closedAt, |
| 300 | mergedAt: pull.mergedAt, |
| 301 | updatedAt: pull.updatedAt, |
| 302 | isCrossRepository: pull.sourceRepo !== null, |
| 303 | headRepositoryNameWithOwner: pull.sourceRepo |
| 304 | ? `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` |
| 305 | : target.repository, |
| 306 | headRepositoryOwnerLogin: pull.sourceRepo?.owner ?? owner, |
| 307 | } satisfies ChangeRequest; |
| 308 | }); |
| 309 | |
| 310 | return SourceControlProvider.SourceControlProvider.of({ |
| 311 | kind: SourceControlProviderKind.make("gitcafe"), |
| 312 | repositoryNameFromRemoteUrl: (url) => GitCafeHosts.parseGitCafeRemote(url)?.repository ?? null, |
| 313 | getChangeRequest: getPull, |
| 314 | listChangeRequests: Effect.fn("GitCafeSourceControlProvider.listChangeRequests")( |
| 315 | function* (input) { |
| 316 | const target = yield* resolveTarget("listChangeRequests", input); |
| 317 | const source = SourceControlProvider.sourceControlRefFromInput(input); |
| 318 | const branch = SourceControlProvider.sourceBranch(input); |
| 319 | const limit = input.limit ?? 20; |
| 320 | const items: Array<ChangeRequest> = []; |
| 321 | let after: string | null = null; |
| 322 | do { |
| 323 | const query = new URLSearchParams({ |
| 324 | sourceBranches: encodeBranches([branch]), |
| 325 | limit: String(Math.min(limit, 100)), |
| 326 | sort: "newest", |
| 327 | }); |
| 328 | if (input.state !== "all") query.set("state", input.state); |
| 329 | if (after !== null) query.set("after", after); |
| 330 | const page: typeof Pulls.Type = yield* read( |
| 331 | "listChangeRequests", |
| 332 | input.cwd, |
| 333 | { host: target.host, path: `/repos/${target.repository}/pulls?${query}` }, |
| 334 | Pulls, |
| 335 | ); |
| 336 | for (const pull of page.items) { |
| 337 | if (pull.sourceBranch !== branch || items.length >= limit) continue; |
| 338 | // List rows omit fork identity; read matching branches in full. |
| 339 | const detail = yield* getPull({ |
| 340 | cwd: input.cwd, |
| 341 | reference: `https://${target.host}/${target.repository}/pulls/${pull.number}`, |
| 342 | }); |
| 343 | if ( |
| 344 | (!source?.repository || detail.headRepositoryNameWithOwner === source.repository) && |
| 345 | (!source?.owner || detail.headRepositoryOwnerLogin === source.owner) |
| 346 | ) |
| 347 | items.push(detail); |
| 348 | } |
| 349 | after = page.items.length === 0 || page.next === after ? null : page.next; |
| 350 | } while (after !== null && items.length < limit); |
| 351 | return items; |
| 352 | }, |
| 353 | ), |
| 354 | createChangeRequest: Effect.fn("GitCafeSourceControlProvider.createChangeRequest")( |
| 355 | function* (input) { |
| 356 | const target = yield* resolveTarget("createChangeRequest", { |
| 357 | ...input, |
| 358 | ...(input.target?.repository ? { repository: input.target.repository } : {}), |
| 359 | }); |
| 360 | const source = SourceControlProvider.sourceControlRefFromInput(input); |
| 361 | const sourceRepository = |
| 362 | source?.repository ?? |
| 363 | (source?.owner |
| 364 | ? `${source.owner}/${target.repository.split("/")[1]}` |
| 365 | : target.repository); |
| 366 | const branch = SourceControlProvider.sourceBranch(input); |
| 367 | // GitCafe names the head by its repository's id, so the head repository is looked up first. |
| 368 | const head = yield* read( |
| 369 | "createChangeRequest", |
| 370 | input.cwd, |
| 371 | { host: target.host, path: `/repos/${sourceRepository}` }, |
| 372 | RepositoryId, |
| 373 | ); |
| 374 | const description = yield* fileSystem |
| 375 | .readFileString(input.bodyFile) |
| 376 | .pipe( |
| 377 | Effect.mapError((cause) => |
| 378 | error( |
| 379 | "createChangeRequest", |
| 380 | input.cwd, |
| 381 | "Could not read the pull request description.", |
| 382 | cause, |
| 383 | ), |
| 384 | ), |
| 385 | ); |
| 386 | yield* read( |
| 387 | "createChangeRequest", |
| 388 | input.cwd, |
| 389 | { |
| 390 | host: target.host, |
| 391 | method: "POST", |
| 392 | path: `/repos/${target.repository}/pulls`, |
| 393 | body: { |
| 394 | repo: head.id, |
| 395 | source: branch, |
| 396 | target: input.target?.refName ?? input.baseRefName, |
| 397 | title: input.title, |
| 398 | ...(description.trim().length === 0 ? {} : { description }), |
| 399 | }, |
| 400 | }, |
| 401 | CreatedPull, |
| 402 | ); |
| 403 | }, |
| 404 | ), |
| 405 | getRepositoryCloneUrls: Effect.fn("GitCafeSourceControlProvider.getRepositoryCloneUrls")( |
| 406 | function* (input) { |
| 407 | const target = yield* resolveTarget("getRepositoryCloneUrls", input); |
| 408 | yield* read( |
| 409 | "getRepositoryCloneUrls", |
| 410 | input.cwd, |
| 411 | { host: target.host, path: `/repos/${target.repository}` }, |
| 412 | Repository, |
| 413 | ); |
| 414 | return cloneUrls(target); |
| 415 | }, |
| 416 | ), |
| 417 | createRepository: Effect.fn("GitCafeSourceControlProvider.createRepository")(function* (input) { |
| 418 | const target = yield* resolveTarget("createRepository", input); |
| 419 | const [owner = "", name = ""] = target.repository.split("/"); |
| 420 | const pending = yield* read( |
| 421 | "createRepository", |
| 422 | input.cwd, |
| 423 | { |
| 424 | host: target.host, |
| 425 | method: "POST", |
| 426 | path: `/orgs/${owner}/repos`, |
| 427 | body: { |
| 428 | name, |
| 429 | requestKey: yield* randomUuidV4, |
| 430 | visibility: input.visibility, |
| 431 | defaultBranch: "main", |
| 432 | }, |
| 433 | }, |
| 434 | RepositoryAdmission, |
| 435 | ); |
| 436 | // GitCafe admits a repository asynchronously and answers while admission is still running, |
| 437 | // so wait for it to settle the way `cafe repo create --clone` does. |
| 438 | const settled = (state: string) => state === "complete" || state === "blocked"; |
| 439 | const resource = settled(pending.state) |
| 440 | ? pending |
| 441 | : yield* read( |
| 442 | "createRepository", |
| 443 | input.cwd, |
| 444 | { |
| 445 | host: target.host, |
| 446 | path: `/orgs/${pending.owner}/admissions/${pending.repoId}`, |
| 447 | }, |
| 448 | RepositoryAdmission, |
| 449 | ).pipe( |
| 450 | Effect.repeat({ |
| 451 | until: (admission) => settled(admission.state), |
| 452 | schedule: Schedule.spaced(ADMISSION_POLL_INTERVAL), |
| 453 | }), |
| 454 | Effect.timeoutOption(ADMISSION_TIMEOUT), |
| 455 | Effect.map(Option.getOrElse(() => pending)), |
| 456 | ); |
| 457 | if (resource.state !== "complete") |
| 458 | return yield* error( |
| 459 | "createRepository", |
| 460 | input.cwd, |
| 461 | `GitCafe repository ${target.repository} is ${resource.state}. Check it on GitCafe before retrying.`, |
| 462 | ); |
| 463 | return cloneUrls({ host: target.host, repository: `${resource.owner}/${resource.name}` }); |
| 464 | }), |
| 465 | getDefaultBranch: Effect.fn("GitCafeSourceControlProvider.getDefaultBranch")(function* (input) { |
| 466 | const target = yield* resolveTarget("getDefaultBranch", input); |
| 467 | const repository = yield* read( |
| 468 | "getDefaultBranch", |
| 469 | input.cwd, |
| 470 | { host: target.host, path: `/repos/${target.repository}` }, |
| 471 | Repository, |
| 472 | ); |
| 473 | return repository.defaultBranch; |
| 474 | }), |
| 475 | // `cafe` has no forced checkout. |
| 476 | checkoutChangeRequest: Effect.fn("GitCafeSourceControlProvider.checkoutChangeRequest")( |
| 477 | function* (input) { |
| 478 | const pull = yield* getPull(input); |
| 479 | const pullHost = new URL(pull.url).host; |
| 480 | const sourceRepository = pull.headRepositoryNameWithOwner; |
| 481 | if (!sourceRepository) |
| 482 | return yield* error( |
| 483 | "checkoutChangeRequest", |
| 484 | input.cwd, |
| 485 | "GitCafe did not name the pull request's source repository.", |
| 486 | ); |
| 487 | const contextRemote = input.context |
| 488 | ? GitCafeHosts.parseGitCafeRemote(input.context.remoteUrl) |
| 489 | : null; |
| 490 | const git = host.git; |
| 491 | yield* Effect.gen(function* () { |
| 492 | const remoteName = |
| 493 | input.context && |
| 494 | contextRemote?.repository === sourceRepository && |
| 495 | contextRemote.host === pullHost |
| 496 | ? input.context.remoteName |
| 497 | : yield* git.ensureRemote({ |
| 498 | cwd: input.cwd, |
| 499 | preferredName: "gitcafe", |
| 500 | url: isSshRemote(input.context?.remoteUrl) |
| 501 | ? `ssh@${pullHost}:${sourceRepository}.git` |
| 502 | : `https://${pullHost}/${sourceRepository}.git`, |
| 503 | }); |
| 504 | const localBranch = pull.isCrossRepository |
| 505 | ? `pr-${pull.number}/${pull.headRefName}` |
| 506 | : pull.headRefName; |
| 507 | const branches = yield* git.listLocalBranchNames(input.cwd); |
| 508 | const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: pull.headRefName }; |
| 509 | if (input.force !== true && !branches.includes(localBranch)) |
| 510 | yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); |
| 511 | else yield* git.fetchRemoteTrackingBranch(remoteBranch); |
| 512 | if (input.force === true) |
| 513 | yield* git.execute({ |
| 514 | operation: "GitCafeSourceControlProvider.checkoutChangeRequest", |
| 515 | cwd: input.cwd, |
| 516 | // The upstream is recorded next, through the host's serialized config write. |
| 517 | args: [ |
| 518 | "checkout", |
| 519 | "--no-track", |
| 520 | "-B", |
| 521 | localBranch, |
| 522 | `refs/remotes/${remoteName}/${pull.headRefName}`, |
| 523 | "--", |
| 524 | ], |
| 525 | }); |
| 526 | yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); |
| 527 | yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); |
| 528 | }).pipe( |
| 529 | Effect.mapError((cause) => |
| 530 | error( |
| 531 | "checkoutChangeRequest", |
| 532 | input.cwd, |
| 533 | "Could not check out the GitCafe pull request.", |
| 534 | cause, |
| 535 | ), |
| 536 | ), |
| 537 | ); |
| 538 | }, |
| 539 | ), |
| 540 | }); |
| 541 | }); |