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

SourceControlRepositoryService.ts

590 lines22.4 KB

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