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

SourceControlRepositoryService.ts

549 lines20.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 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.catch((sshError) =>
386 httpsUrl === null || !isSshRejection(sshError)
387 ? Effect.fail(sshError)
388 : runClone(input, prepared.destinationPath, httpsUrl, options).pipe(
389 Effect.as(redactRemoteUrl(httpsUrl)),
390 Effect.mapError(
391 (httpsError) =>
392 new SourceControlRepositoryError({
393 operation: "cloneRepository",
394 provider: sshError.provider,
395 detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`,
396 cause: httpsError.cause,
397 }),
398 ),
399 ),
400 ),
401 );
402​
403 return {
404 cwd: prepared.destinationPath,
405 remoteUrl,
406 repository: prepared.repository,
407 };
408 });
409​
410 const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
411 destinationPath: string,
412 ) {
413 const normalized = yield* normalizeDestinationPath(destinationPath);
414 // Only .git-bearing partial clones may be deleted; other files arrived after the empty-directory check.
415 // Missing destinations are already discarded; other read failures must refuse removal.
416 const entries = yield* fileSystem.readDirectory(normalized).pipe(
417 Effect.catchIf(
418 (cause) => cause.reason._tag === "NotFound",
419 () => Effect.succeed<ReadonlyArray<string>>([]),
420 ),
421 Effect.mapError(
422 (cause) =>
423 new SourceControlRepositoryError({
424 operation: "discardClone",
425 provider: SourceControlProviderKind.make("unknown"),
426 detail: "The clone destination could not be inspected.",
427 cause,
428 }),
429 ),
430 );
431 if (entries.length > 0 && !entries.includes(".git")) {
432 return yield* new SourceControlRepositoryError({
433 operation: "discardClone",
434 provider: SourceControlProviderKind.make("unknown"),
435 detail: "Destination path contains files that are not from the clone.",
436 });
437 }
438 // Preserve the workspace directory after removing partial contents; retry while interrupted git closes files.
439 yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
440 Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
441 Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
442 Effect.mapError(
443 (cause) =>
444 new SourceControlRepositoryError({
445 operation: "discardClone",
446 provider: SourceControlProviderKind.make("unknown"),
447 detail: "The partial clone could not be removed.",
448 cause,
449 }),
450 ),
451 );
452 });
453​
454 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
455 function* (input: SourceControlPublishRepositoryInput) {
456 const providerKind = yield* ensureConcreteProvider({
457 operation: "publishRepository",
458 provider: input.provider,
459 });
460 const provider = yield* providers.get(providerKind);
461 const urls = yield* provider.createRepository({
462 cwd: input.cwd,
463 repository: input.repository.trim(),
464 visibility: input.visibility,
465 });
466 const remoteUrl = selectRemoteUrl(urls, input.protocol);
467 const remoteName = yield* git.ensureRemote({
468 cwd: input.cwd,
469 preferredName: input.remoteName?.trim() || "origin",
470 url: remoteUrl,
471 });
472​
473 // Empty repos cannot push HEAD; report partial success because the remote already exists.
474 const hasCommits = yield* git
475 .execute({
476 operation: "SourceControlRepositoryService.publishRepository.headCheck",
477 cwd: input.cwd,
478 args: ["rev-parse", "--verify", "HEAD"],
479 })
480 .pipe(
481 Effect.map(() => true),
482 Effect.orElseSucceed(() => false),
483 );
484 if (!hasCommits) {
485 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
486 return {
487 repository: toRepositoryInfo(providerKind, urls),
488 remoteName,
489 remoteUrl,
490 branch: details?.branch ?? "main",
491 status: "remote_added" as const,
492 };
493 }
494​
495 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName }).pipe(
496 Effect.mapError(
497 (cause) =>
498 new SourceControlRepositoryError({
499 operation: "publishRepository",
500 provider: providerKind,
501 detail: publishPushFailureDetail({
502 urls,
503 remoteName,
504 remoteUrl,
505 reason: cause.reason,
506 }),
507 cause,
508 }),
509 ),
510 );
511​
512 return {
513 repository: toRepositoryInfo(providerKind, urls),
514 remoteName,
515 remoteUrl,
516 branch: pushResult.branch,
517 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
518 status: "pushed" as const,
519 };
520 },
521 );
522​
523 return SourceControlRepositoryService.of({
524 lookupRepository: (input) =>
525 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
526 prepareClone: (input) =>
527 prepareClone(input).pipe(
528 mapRepositoryError(
529 "cloneRepository",
530 input.provider ?? SourceControlProviderKind.make("unknown"),
531 ),
532 ),
533 cloneRepository: (input, options) =>
534 cloneRepository(input, options).pipe(
535 mapRepositoryError(
536 "cloneRepository",
537 input.provider ?? SourceControlProviderKind.make("unknown"),
538 ),
539 ),
540 discardClone: (destinationPath) =>
541 discardClone(destinationPath).pipe(
542 mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")),
543 ),
544 publishRepository: (input) =>
545 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
546 });
547});
548​
549export const layer = Layer.effect(SourceControlRepositoryService, make);