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

SourceControlRepositoryService.ts

717 lines27.2 KB

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