The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Context from "effect/Context"; |
| 2 | import * as Duration from "effect/Duration"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as FileSystem from "effect/FileSystem"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import * as Path from "effect/Path"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | |
| 10 | import { |
| 11 | GitCommandError, |
| 12 | SourceControlProviderError, |
| 13 | SourceControlRepositoryError, |
| 14 | type GitCommandFailureReason, |
| 15 | type SourceControlCloneRepositoryInput, |
| 16 | type SourceControlCloneRepositoryResult, |
| 17 | type SourceControlCloneProtocol, |
| 18 | SourceControlProviderKind, |
| 19 | type SourceControlPublishRepositoryInput, |
| 20 | type SourceControlPublishRepositoryResult, |
| 21 | type SourceControlRepositoryCloneUrls, |
| 22 | type SourceControlRepositoryInfo, |
| 23 | type SourceControlRepositoryLookupInput, |
| 24 | } from "@t3tools/contracts"; |
| 25 | |
| 26 | import * as ServerConfig from "../config.ts"; |
| 27 | import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; |
| 28 | import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; |
| 29 | import { |
| 30 | gitLfsDownloadProgressLine, |
| 31 | isGitFilterProgressLine, |
| 32 | parseGitCloneProgressLine, |
| 33 | type GitCloneProgressLine, |
| 34 | } from "../project/gitCloneProgress.ts"; |
| 35 | import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; |
| 36 | import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; |
| 37 | import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts"; |
| 38 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 39 | import { cloneUrlForProtocol, cloneUrlProtocol } from "@t3tools/shared/cloneUrl"; |
| 40 | const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError); |
| 41 | const isSourceControlProviderError = Schema.is(SourceControlProviderError); |
| 42 | const isGitCommandError = Schema.is(GitCommandError); |
| 43 | |
| 44 | export class SourceControlRepositoryService extends Context.Service< |
| 45 | SourceControlRepositoryService, |
| 46 | { |
| 47 | readonly lookupRepository: ( |
| 48 | input: SourceControlRepositoryLookupInput, |
| 49 | ) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>; |
| 50 | readonly prepareClone: ( |
| 51 | input: SourceControlCloneRepositoryInput, |
| 52 | ) => Effect.Effect<SourceControlPreparedClone, SourceControlRepositoryError>; |
| 53 | readonly cloneRepository: ( |
| 54 | input: SourceControlCloneRepositoryInput, |
| 55 | options?: SourceControlCloneOptions, |
| 56 | ) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>; |
| 57 | readonly discardClone: ( |
| 58 | destinationPath: string, |
| 59 | ) => Effect.Effect<void, SourceControlRepositoryError>; |
| 60 | readonly publishRepository: ( |
| 61 | input: SourceControlPublishRepositoryInput, |
| 62 | ) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>; |
| 63 | } |
| 64 | >()("t3/sourceControl/SourceControlRepositoryService") {} |
| 65 | |
| 66 | export interface SourceControlPreparedClone { |
| 67 | readonly destinationPath: string; |
| 68 | readonly remoteUrl: string; |
| 69 | readonly cloneUrl: string; |
| 70 | readonly repository: SourceControlRepositoryInfo | null; |
| 71 | } |
| 72 | |
| 73 | export interface SourceControlCloneOptions { |
| 74 | readonly onProgress?: (line: GitCloneProgressLine) => Effect.Effect<void>; |
| 75 | /** Overrides the default clone budget; `null` disables the deadline. */ |
| 76 | readonly timeoutMs?: number | null; |
| 77 | } |
| 78 | |
| 79 | // Older/mobile synchronous RPCs need deadlines; tracked clones use progress and Cancel instead. |
| 80 | const CLONE_TIMEOUT_MS = 120_000; |
| 81 | const CLONE_ENV = { |
| 82 | // Force piped progress immediately; refuse credential prompts that would hang without a tty. |
| 83 | GIT_PROGRESS_DELAY: "0", |
| 84 | GIT_TERMINAL_PROMPT: "0", |
| 85 | // English progress without overriding LC_CTYPE, which a global post-checkout hook inherits. |
| 86 | LANGUAGE: "C", |
| 87 | } satisfies NodeJS.ProcessEnv; |
| 88 | // Well inside the tracker's stall window, at about the pace git itself reports. |
| 89 | const LFS_DOWNLOAD_POLL_INTERVAL = Duration.seconds(2); |
| 90 | |
| 91 | function mapRepositoryError(operation: string, provider: SourceControlProviderKind) { |
| 92 | return Effect.mapError((cause: unknown) => |
| 93 | isSourceControlRepositoryError(cause) |
| 94 | ? cause |
| 95 | : new SourceControlRepositoryError({ |
| 96 | operation, |
| 97 | provider, |
| 98 | detail: |
| 99 | (isSourceControlProviderError(cause) |
| 100 | ? SourceControlProvider.userFacingSourceControlDetail(cause.cause) |
| 101 | : undefined) ?? "The source control operation could not be completed.", |
| 102 | cause, |
| 103 | }), |
| 104 | ); |
| 105 | } |
| 106 | |
| 107 | function toRepositoryInfo( |
| 108 | provider: SourceControlProviderKind, |
| 109 | urls: SourceControlRepositoryCloneUrls, |
| 110 | ): SourceControlRepositoryInfo { |
| 111 | return { |
| 112 | provider, |
| 113 | nameWithOwner: urls.nameWithOwner, |
| 114 | url: urls.url, |
| 115 | sshUrl: urls.sshUrl, |
| 116 | }; |
| 117 | } |
| 118 | |
| 119 | // Redact credentials from client clone snapshots; git still receives the credentials. |
| 120 | function redactRemoteUrl(remoteUrl: string): string { |
| 121 | try { |
| 122 | const url = new URL(remoteUrl); |
| 123 | // Clone URLs have no legitimate query; when one is present it is a token. |
| 124 | if (url.username.length === 0 && url.password.length === 0 && url.search.length === 0) { |
| 125 | return remoteUrl; |
| 126 | } |
| 127 | url.username = ""; |
| 128 | url.password = ""; |
| 129 | url.search = ""; |
| 130 | return url.toString(); |
| 131 | } catch { |
| 132 | return remoteUrl; |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // Userinfo can contain @; remove through the last one before the host boundary. |
| 137 | const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]+@/gi; |
| 138 | // Git leaves quotes inside query tokens unescaped; consume through the closing quote. |
| 139 | const QUOTED_URL_QUERY = /(['"])([a-z][a-z0-9+.-]*:\/\/[^\s?]*)\?.*\1(?=[\s:]|$)/gi; |
| 140 | const URL_QUERY = /\b([a-z][a-z0-9+.-]*:\/\/[^\s?]*)\?[^\s]*/gi; |
| 141 | |
| 142 | function redactUrlCredentials(text: string): string { |
| 143 | return text |
| 144 | .replace(QUOTED_URL_QUERY, "$1$2$1") |
| 145 | .replace(URL_QUERY, "$1") |
| 146 | .replace(URL_WITH_USERINFO, "$1"); |
| 147 | } |
| 148 | |
| 149 | // The remote already exists after push failure; advise fixing access and pushing. |
| 150 | // Use fixed text and provider URLs because git stderr can expose credentials. |
| 151 | function publishPushFailureDetail(input: { |
| 152 | readonly urls: SourceControlRepositoryCloneUrls; |
| 153 | readonly remoteName: string; |
| 154 | readonly remoteUrl: string; |
| 155 | readonly reason: GitCommandFailureReason | undefined; |
| 156 | }): string { |
| 157 | const created = `Created ${input.urls.nameWithOwner} and added it as remote "${input.remoteName}", but the push failed`; |
| 158 | const switchToHttps = `git remote set-url ${input.remoteName} ${input.urls.url}`; |
| 159 | const usesSsh = input.remoteUrl === input.urls.sshUrl; |
| 160 | switch (input.reason) { |
| 161 | case "authentication_failed": |
| 162 | return usesSsh |
| 163 | ? `${created} because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "${switchToHttps}", then push again.` |
| 164 | : `${created} because Git could not authenticate. Check your Git credentials, then push again.`; |
| 165 | case "host_key_unverified": |
| 166 | return `${created} because the host's SSH key is not trusted yet. Verify it by connecting once with ssh, or switch the remote to HTTPS with "${switchToHttps}", then push again.`; |
| 167 | default: |
| 168 | return `${created}. Fix the problem, then push again.`; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /** |
| 173 | * SSH rejection can be retried over HTTPS when the host's credential helper is available. |
| 174 | * Explicit SSH requests must not fall back; unknown URL shapes must not be guessed. |
| 175 | */ |
| 176 | function httpsFallbackUrl( |
| 177 | input: SourceControlCloneRepositoryInput, |
| 178 | prepared: SourceControlPreparedClone, |
| 179 | ): string | null { |
| 180 | if (input.protocol === "ssh" || cloneUrlProtocol(prepared.cloneUrl) !== "ssh") return null; |
| 181 | if (prepared.repository?.sshUrl === prepared.cloneUrl) return prepared.repository.url; |
| 182 | return cloneUrlForProtocol(prepared.cloneUrl, "https"); |
| 183 | } |
| 184 | |
| 185 | const isSshRejection = (error: SourceControlRepositoryError) => |
| 186 | isGitCommandError(error.cause) && |
| 187 | (error.cause.reason === "authentication_failed" || error.cause.reason === "host_key_unverified"); |
| 188 | |
| 189 | function selectRemoteUrl( |
| 190 | urls: SourceControlRepositoryCloneUrls, |
| 191 | protocol: SourceControlCloneProtocol | undefined, |
| 192 | ): string { |
| 193 | switch (protocol ?? "auto") { |
| 194 | case "https": |
| 195 | return urls.url; |
| 196 | case "ssh": |
| 197 | case "auto": |
| 198 | return urls.sshUrl; |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | /** @public */ |
| 203 | export const make = Effect.gen(function* () { |
| 204 | const config = yield* ServerConfig.ServerConfig; |
| 205 | const fileSystem = yield* FileSystem.FileSystem; |
| 206 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 207 | const path = yield* Path.Path; |
| 208 | const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; |
| 209 | |
| 210 | const ensureConcreteProvider = (input: { |
| 211 | readonly operation: string; |
| 212 | readonly provider: SourceControlProviderKind; |
| 213 | }) => { |
| 214 | if (input.provider !== "unknown") { |
| 215 | return Effect.succeed(input.provider); |
| 216 | } |
| 217 | |
| 218 | return Effect.fail( |
| 219 | new SourceControlRepositoryError({ |
| 220 | operation: input.operation, |
| 221 | provider: input.provider, |
| 222 | detail: "Choose a source control provider before continuing.", |
| 223 | }), |
| 224 | ); |
| 225 | }; |
| 226 | |
| 227 | const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")( |
| 228 | function* (input: SourceControlRepositoryLookupInput) { |
| 229 | const providerKind = yield* ensureConcreteProvider({ |
| 230 | operation: "lookupRepository", |
| 231 | provider: input.provider, |
| 232 | }); |
| 233 | const provider = yield* providers.get(providerKind); |
| 234 | const urls = yield* provider.getRepositoryCloneUrls({ |
| 235 | cwd: input.cwd ?? config.cwd, |
| 236 | repository: input.repository.trim(), |
| 237 | }); |
| 238 | return toRepositoryInfo(providerKind, urls); |
| 239 | }, |
| 240 | // Someone adding or cloning a repository is waiting, so a background rate-limit pause must not |
| 241 | // refuse the lookup. |
| 242 | Effect.provideService(SourceControlRateLimit.Interactive, true), |
| 243 | ); |
| 244 | |
| 245 | const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")( |
| 246 | function* (destinationPath: string) { |
| 247 | const trimmed = destinationPath.trim(); |
| 248 | if (trimmed.length === 0) { |
| 249 | return yield* new SourceControlRepositoryError({ |
| 250 | operation: "cloneRepository", |
| 251 | provider: SourceControlProviderKind.make("unknown"), |
| 252 | detail: "Choose a destination path before cloning.", |
| 253 | }); |
| 254 | } |
| 255 | |
| 256 | return path.resolve(expandHomePath(trimmed, yield* HostProcess.HomeDirectory)); |
| 257 | }, |
| 258 | ); |
| 259 | |
| 260 | const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")( |
| 261 | function* (destinationPath: string) { |
| 262 | const normalizedDestination = yield* normalizeDestinationPath(destinationPath); |
| 263 | if (yield* fileSystem.exists(normalizedDestination)) { |
| 264 | const entries = yield* fileSystem |
| 265 | .readDirectory(normalizedDestination, { recursive: false }) |
| 266 | .pipe( |
| 267 | Effect.mapError( |
| 268 | (cause) => |
| 269 | new SourceControlRepositoryError({ |
| 270 | operation: "cloneRepository", |
| 271 | provider: SourceControlProviderKind.make("unknown"), |
| 272 | detail: "Destination path already exists and is not a directory.", |
| 273 | cause, |
| 274 | }), |
| 275 | ), |
| 276 | ); |
| 277 | if (entries.length > 0) { |
| 278 | return yield* new SourceControlRepositoryError({ |
| 279 | operation: "cloneRepository", |
| 280 | provider: SourceControlProviderKind.make("unknown"), |
| 281 | detail: "Destination path already exists and is not empty.", |
| 282 | }); |
| 283 | } |
| 284 | } else { |
| 285 | // Skip existing parents: recursive mkdir on a Windows drive root fails with EPERM. |
| 286 | const parentPath = path.dirname(normalizedDestination); |
| 287 | if (!(yield* fileSystem.exists(parentPath))) { |
| 288 | yield* fileSystem.makeDirectory(parentPath, { recursive: true }); |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | return { |
| 293 | destinationPath: normalizedDestination, |
| 294 | parentPath: path.dirname(normalizedDestination), |
| 295 | directoryName: path.basename(normalizedDestination), |
| 296 | }; |
| 297 | }, |
| 298 | ); |
| 299 | |
| 300 | const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* ( |
| 301 | input: SourceControlCloneRepositoryInput, |
| 302 | ) { |
| 303 | const preparedDestination = yield* prepareDestination(input.destinationPath); |
| 304 | let repository: SourceControlRepositoryInfo | null = null; |
| 305 | let remoteUrl = input.remoteUrl?.trim() ?? null; |
| 306 | let provider: SourceControlProviderKind = |
| 307 | input.provider ?? SourceControlProviderKind.make("unknown"); |
| 308 | |
| 309 | if (input.provider && input.repository) { |
| 310 | repository = yield* lookupRepository({ |
| 311 | provider: input.provider, |
| 312 | repository: input.repository, |
| 313 | cwd: preparedDestination.parentPath, |
| 314 | }); |
| 315 | remoteUrl = selectRemoteUrl(repository, input.protocol); |
| 316 | provider = input.provider; |
| 317 | } |
| 318 | |
| 319 | if (!remoteUrl) { |
| 320 | return yield* new SourceControlRepositoryError({ |
| 321 | operation: "cloneRepository", |
| 322 | provider, |
| 323 | detail: "Enter a repository path or clone URL before cloning.", |
| 324 | }); |
| 325 | } |
| 326 | |
| 327 | return { |
| 328 | destinationPath: preparedDestination.destinationPath, |
| 329 | remoteUrl: redactRemoteUrl(remoteUrl), |
| 330 | cloneUrl: remoteUrl, |
| 331 | repository, |
| 332 | } satisfies SourceControlPreparedClone; |
| 333 | }); |
| 334 | |
| 335 | // Git and git-lfs print nothing while one object downloads, so a healthy transfer reads as a |
| 336 | // stall. Its partial files growing are the only sign of life a plain clone gives. |
| 337 | const watchLfsDownload = ( |
| 338 | destinationPath: string, |
| 339 | onChange: (partialBytes: number) => Effect.Effect<void>, |
| 340 | ) => { |
| 341 | const incomplete = path.join(destinationPath, ".git", "lfs", "incomplete"); |
| 342 | const partialBytes = fileSystem.readDirectory(incomplete).pipe( |
| 343 | Effect.flatMap( |
| 344 | Effect.forEach((name) => |
| 345 | fileSystem |
| 346 | .stat(path.join(incomplete, name)) |
| 347 | .pipe(Effect.map((info) => Number(info.size))), |
| 348 | ), |
| 349 | ), |
| 350 | Effect.map((sizes) => sizes.reduce((total, size) => total + size, 0)), |
| 351 | // No directory means no LFS download; a part that landed mid-read counts on the next poll. |
| 352 | Effect.orElseSucceed(() => 0), |
| 353 | ); |
| 354 | return Effect.gen(function* () { |
| 355 | let previous = 0; |
| 356 | while (true) { |
| 357 | yield* Effect.sleep(LFS_DOWNLOAD_POLL_INTERVAL); |
| 358 | const current = yield* partialBytes; |
| 359 | if (current > 0 && current !== previous) yield* onChange(current); |
| 360 | previous = current; |
| 361 | } |
| 362 | }); |
| 363 | }; |
| 364 | |
| 365 | const runClone = Effect.fn("SourceControlRepositoryService.runClone")(function* ( |
| 366 | input: SourceControlCloneRepositoryInput, |
| 367 | destinationPath: string, |
| 368 | cloneUrl: string, |
| 369 | options?: SourceControlCloneOptions, |
| 370 | ) { |
| 371 | const onProgress = options?.onProgress; |
| 372 | // Git mixes progress and diagnostics on stderr; retain non-progress tail lines for failure details. |
| 373 | const stderrTail: Array<string> = []; |
| 374 | let filterPercent: number | null = null; |
| 375 | const onStderrLine = (line: string) => { |
| 376 | const parsed = parseGitCloneProgressLine(line); |
| 377 | if (parsed && isGitFilterProgressLine(line)) filterPercent = parsed.percent; |
| 378 | if (parsed) return onProgress ? onProgress(parsed) : Effect.void; |
| 379 | return Effect.sync(() => { |
| 380 | const trimmed = line.trim(); |
| 381 | if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return; |
| 382 | // Git echoes the remote in some failures; the tail becomes user-facing text. |
| 383 | stderrTail.push(redactUrlCredentials(trimmed)); |
| 384 | if (stderrTail.length > 4) stderrTail.shift(); |
| 385 | }); |
| 386 | }; |
| 387 | // Git misreads @ in a pathless URL's query as userinfo and echoes its suffix as the host. |
| 388 | const normalizedCloneUrl = cloneUrl.replace(/^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)\?/i, "$1/?"); |
| 389 | const provider = input.provider ?? SourceControlProviderKind.make("unknown"); |
| 390 | const timeoutMs = options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs; |
| 391 | const clone = git |
| 392 | .execute({ |
| 393 | operation: "SourceControlRepositoryService.cloneRepository", |
| 394 | cwd: path.dirname(destinationPath), |
| 395 | args: ["clone", "--progress", "--", normalizedCloneUrl, path.basename(destinationPath)], |
| 396 | // The deadline is applied below so a timeout is reported as one, not as git's last line. |
| 397 | timeoutMs: null, |
| 398 | // Buffered output is unused and progress can be huge; cap it while retaining line callbacks. |
| 399 | maxOutputBytes: 256 * 1024, |
| 400 | appendTruncationMarker: true, |
| 401 | keepLineCallbacksAfterTruncation: true, |
| 402 | env: CLONE_ENV, |
| 403 | progress: { onStderrLine }, |
| 404 | }) |
| 405 | .pipe( |
| 406 | Effect.mapError( |
| 407 | (cause) => |
| 408 | new SourceControlRepositoryError({ |
| 409 | operation: "cloneRepository", |
| 410 | provider, |
| 411 | detail: |
| 412 | stderrTail.length > 0 |
| 413 | ? stderrTail.join(" ") |
| 414 | : "The repository could not be cloned.", |
| 415 | cause, |
| 416 | }), |
| 417 | ), |
| 418 | ); |
| 419 | const watchedClone = onProgress |
| 420 | ? clone.pipe( |
| 421 | Effect.raceFirst( |
| 422 | watchLfsDownload(destinationPath, (partialBytes) => |
| 423 | onProgress(gitLfsDownloadProgressLine(partialBytes, filterPercent)), |
| 424 | ), |
| 425 | ), |
| 426 | ) |
| 427 | : clone; |
| 428 | if (timeoutMs === null) return yield* watchedClone; |
| 429 | // Interrupting the clone closes the scope that owns git, which kills it. |
| 430 | return yield* watchedClone.pipe( |
| 431 | Effect.timeoutOrElse({ |
| 432 | duration: timeoutMs, |
| 433 | orElse: () => |
| 434 | Effect.fail( |
| 435 | new SourceControlRepositoryError({ |
| 436 | operation: "cloneRepository", |
| 437 | provider, |
| 438 | detail: `The clone timed out after ${Duration.format(Duration.millis(timeoutMs))}.`, |
| 439 | }), |
| 440 | ), |
| 441 | }), |
| 442 | ); |
| 443 | }); |
| 444 | |
| 445 | const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* ( |
| 446 | input: SourceControlCloneRepositoryInput, |
| 447 | options?: SourceControlCloneOptions, |
| 448 | ) { |
| 449 | const prepared = yield* prepareClone(input); |
| 450 | const httpsUrl = httpsFallbackUrl(input, prepared); |
| 451 | const remoteUrl = yield* runClone( |
| 452 | input, |
| 453 | prepared.destinationPath, |
| 454 | prepared.cloneUrl, |
| 455 | options, |
| 456 | ).pipe( |
| 457 | Effect.as(prepared.remoteUrl), |
| 458 | // @effect-diagnostics-next-line catchConditionalRefailToCatchIf:off - The condition also narrows httpsUrl for the fallback closure. |
| 459 | Effect.catch((sshError) => |
| 460 | httpsUrl === null || !isSshRejection(sshError) |
| 461 | ? Effect.fail(sshError) |
| 462 | : runClone(input, prepared.destinationPath, httpsUrl, options).pipe( |
| 463 | Effect.as(redactRemoteUrl(httpsUrl)), |
| 464 | Effect.mapError( |
| 465 | (httpsError) => |
| 466 | new SourceControlRepositoryError({ |
| 467 | operation: "cloneRepository", |
| 468 | provider: sshError.provider, |
| 469 | detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`, |
| 470 | cause: httpsError.cause, |
| 471 | }), |
| 472 | ), |
| 473 | ), |
| 474 | ), |
| 475 | ); |
| 476 | |
| 477 | // A ref list read while the clone ran saw an unborn HEAD and no refs. |
| 478 | yield* git.invalidateRefs(prepared.destinationPath); |
| 479 | return { |
| 480 | cwd: prepared.destinationPath, |
| 481 | remoteUrl, |
| 482 | repository: prepared.repository, |
| 483 | }; |
| 484 | }); |
| 485 | |
| 486 | const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* ( |
| 487 | destinationPath: string, |
| 488 | ) { |
| 489 | const normalized = yield* normalizeDestinationPath(destinationPath); |
| 490 | // Only .git-bearing partial clones may be deleted; other files arrived after the empty-directory check. |
| 491 | // Missing destinations are already discarded; other read failures must refuse removal. |
| 492 | const entries = yield* fileSystem.readDirectory(normalized).pipe( |
| 493 | Effect.catchIf( |
| 494 | (cause) => cause.reason._tag === "NotFound", |
| 495 | () => Effect.succeed<ReadonlyArray<string>>([]), |
| 496 | ), |
| 497 | Effect.mapError( |
| 498 | (cause) => |
| 499 | new SourceControlRepositoryError({ |
| 500 | operation: "discardClone", |
| 501 | provider: SourceControlProviderKind.make("unknown"), |
| 502 | detail: "The clone destination could not be inspected.", |
| 503 | cause, |
| 504 | }), |
| 505 | ), |
| 506 | ); |
| 507 | if (entries.length > 0 && !entries.includes(".git")) { |
| 508 | return yield* new SourceControlRepositoryError({ |
| 509 | operation: "discardClone", |
| 510 | provider: SourceControlProviderKind.make("unknown"), |
| 511 | detail: "Destination path contains files that are not from the clone.", |
| 512 | }); |
| 513 | } |
| 514 | // Preserve the workspace directory after removing partial contents; retry while interrupted git closes files. |
| 515 | yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe( |
| 516 | Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })), |
| 517 | Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }), |
| 518 | Effect.mapError( |
| 519 | (cause) => |
| 520 | new SourceControlRepositoryError({ |
| 521 | operation: "discardClone", |
| 522 | provider: SourceControlProviderKind.make("unknown"), |
| 523 | detail: "The partial clone could not be removed.", |
| 524 | cause, |
| 525 | }), |
| 526 | ), |
| 527 | ); |
| 528 | }); |
| 529 | |
| 530 | const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")( |
| 531 | function* (input: SourceControlPublishRepositoryInput) { |
| 532 | const providerKind = yield* ensureConcreteProvider({ |
| 533 | operation: "publishRepository", |
| 534 | provider: input.provider, |
| 535 | }); |
| 536 | const provider = yield* providers.get(providerKind); |
| 537 | const urls = yield* provider.createRepository({ |
| 538 | cwd: input.cwd, |
| 539 | repository: input.repository.trim(), |
| 540 | visibility: input.visibility, |
| 541 | }); |
| 542 | const remoteUrl = selectRemoteUrl(urls, input.protocol); |
| 543 | const remoteName = yield* git.ensureRemote({ |
| 544 | cwd: input.cwd, |
| 545 | preferredName: input.remoteName?.trim() || "origin", |
| 546 | url: remoteUrl, |
| 547 | }); |
| 548 | |
| 549 | // Empty repos cannot push HEAD; report partial success because the remote already exists. |
| 550 | const hasCommits = yield* git |
| 551 | .execute({ |
| 552 | operation: "SourceControlRepositoryService.publishRepository.headCheck", |
| 553 | cwd: input.cwd, |
| 554 | args: ["rev-parse", "--verify", "HEAD"], |
| 555 | }) |
| 556 | .pipe( |
| 557 | Effect.as(true), |
| 558 | Effect.orElseSucceed(() => false), |
| 559 | ); |
| 560 | if (!hasCommits) { |
| 561 | const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null)); |
| 562 | return { |
| 563 | repository: toRepositoryInfo(providerKind, urls), |
| 564 | remoteName, |
| 565 | remoteUrl, |
| 566 | branch: details?.branch ?? "main", |
| 567 | status: "remote_added" as const, |
| 568 | }; |
| 569 | } |
| 570 | |
| 571 | const push = (pushUrl: string) => |
| 572 | git.pushCurrentBranch(input.cwd, null, { remoteName }).pipe( |
| 573 | Effect.map((result) => ({ branch: result.branch, remoteUrl: pushUrl })), |
| 574 | Effect.mapError( |
| 575 | (cause) => |
| 576 | new SourceControlRepositoryError({ |
| 577 | operation: "publishRepository", |
| 578 | provider: providerKind, |
| 579 | detail: publishPushFailureDetail({ |
| 580 | urls, |
| 581 | remoteName, |
| 582 | remoteUrl: pushUrl, |
| 583 | reason: cause.reason, |
| 584 | }), |
| 585 | cause, |
| 586 | }), |
| 587 | ), |
| 588 | ); |
| 589 | |
| 590 | // Like clone, an auto-selected SSH remote switches to HTTPS when SSH is refused; |
| 591 | // otherwise the remote keeps failing every later fetch and push. |
| 592 | const canSwitchToHttps = input.protocol !== "ssh" && remoteUrl === urls.sshUrl; |
| 593 | const pushed = yield* push(remoteUrl).pipe( |
| 594 | Effect.catchIf( |
| 595 | (error) => canSwitchToHttps && isSshRejection(error), |
| 596 | (sshError) => |
| 597 | git |
| 598 | .execute({ |
| 599 | operation: "SourceControlRepositoryService.publishRepository.switchToHttps", |
| 600 | cwd: input.cwd, |
| 601 | args: ["remote", "set-url", remoteName, urls.url], |
| 602 | }) |
| 603 | .pipe( |
| 604 | Effect.mapError(() => sshError), |
| 605 | Effect.andThen(push(urls.url)), |
| 606 | ), |
| 607 | ), |
| 608 | ); |
| 609 | |
| 610 | return { |
| 611 | repository: toRepositoryInfo(providerKind, urls), |
| 612 | remoteName, |
| 613 | remoteUrl: pushed.remoteUrl, |
| 614 | branch: pushed.branch, |
| 615 | status: "pushed" as const, |
| 616 | }; |
| 617 | }, |
| 618 | ); |
| 619 | |
| 620 | // Forwarders retain the underlying operation spans. |
| 621 | return SourceControlRepositoryService.of({ |
| 622 | lookupRepository: Effect.fnUntraced(function* (input) { |
| 623 | return yield* lookupRepository(input).pipe( |
| 624 | mapRepositoryError("lookupRepository", input.provider), |
| 625 | ); |
| 626 | }), |
| 627 | prepareClone: Effect.fnUntraced(function* (input) { |
| 628 | return yield* prepareClone(input).pipe( |
| 629 | mapRepositoryError( |
| 630 | "cloneRepository", |
| 631 | input.provider ?? SourceControlProviderKind.make("unknown"), |
| 632 | ), |
| 633 | ); |
| 634 | }), |
| 635 | cloneRepository: Effect.fnUntraced(function* (input, options) { |
| 636 | return yield* cloneRepository(input, options).pipe( |
| 637 | mapRepositoryError( |
| 638 | "cloneRepository", |
| 639 | input.provider ?? SourceControlProviderKind.make("unknown"), |
| 640 | ), |
| 641 | ); |
| 642 | }), |
| 643 | discardClone: Effect.fnUntraced(function* (destinationPath) { |
| 644 | return yield* discardClone(destinationPath).pipe( |
| 645 | mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")), |
| 646 | ); |
| 647 | }), |
| 648 | publishRepository: Effect.fnUntraced(function* (input) { |
| 649 | return yield* publishRepository(input).pipe( |
| 650 | mapRepositoryError("publishRepository", input.provider), |
| 651 | ); |
| 652 | }), |
| 653 | }); |
| 654 | }); |
| 655 | |
| 656 | export const layer = Layer.effect(SourceControlRepositoryService, make); |