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

SourceControlRepositoryService.ts

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