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