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

SourceControlRepositoryService.ts

581 lines22.0 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 BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
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);
40const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
41​
42export class SourceControlRepositoryService extends Context.Service<
43 SourceControlRepositoryService,
44 {
45 readonly lookupRepository: (
46 input: SourceControlRepositoryLookupInput,
47 ) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
48 readonly prepareClone: (
49 input: SourceControlCloneRepositoryInput,
50 ) => Effect.Effect<SourceControlPreparedClone, SourceControlRepositoryError>;
51 readonly cloneRepository: (
52 input: SourceControlCloneRepositoryInput,
53 options?: SourceControlCloneOptions,
54 ) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
55 readonly discardClone: (
56 destinationPath: string,
57 ) => Effect.Effect<void, SourceControlRepositoryError>;
58 readonly publishRepository: (
59 input: SourceControlPublishRepositoryInput,
60 ) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
61 }
62>()("t3/sourceControl/SourceControlRepositoryService") {}
63​
64export interface SourceControlPreparedClone {
65 readonly destinationPath: string;
66 readonly remoteUrl: string;
67 readonly cloneUrl: string;
68 readonly repository: SourceControlRepositoryInfo | null;
70​
71export interface SourceControlCloneOptions {
72 readonly onProgress?: (line: GitCloneProgressLine) => Effect.Effect<void>;
73 /** Overrides the default clone budget; `null` disables the deadline. */
74 readonly timeoutMs?: number | null;
76​
77// The synchronous RPC (older clients, mobile) keeps a deadline: nothing else
78// tells the user a clone stalled. The tracked path passes null and relies on
79// progress and Cancel instead.
80const CLONE_TIMEOUT_MS = 120_000;
81const CLONE_ENV = {
82 // `--progress` forces the transfer counters through the pipe; the delay env
83 // makes the checkout counter start immediately. No tty means a credential
84 // prompt would hang forever, so tell git to fail instead.
85 GIT_PROGRESS_DELAY: "0",
86 GIT_TERMINAL_PROMPT: "0",
87 LC_ALL: "C",
88} satisfies NodeJS.ProcessEnv;
89​
90function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
91 return Effect.mapError((cause: unknown) =>
92 isSourceControlRepositoryError(cause)
93 ? cause
94 : new SourceControlRepositoryError({
95 operation,
96 provider,
97 detail:
98 isSourceControlProviderError(cause) &&
99 cause.provider === "bitbucket" &&
100 isBitbucketRepositoryLocatorError(cause.cause)
101 ? BitbucketApi.BitbucketRepositoryLocatorError.detail
102 : "The source control operation could not be completed.",
103 cause,
104 }),
105 );
107​
108function toRepositoryInfo(
109 provider: SourceControlProviderKind,
110 urls: SourceControlRepositoryCloneUrls,
111): SourceControlRepositoryInfo {
112 return {
113 provider,
114 nameWithOwner: urls.nameWithOwner,
115 url: urls.url,
116 sshUrl: urls.sshUrl,
117 };
119​
120/**
121 * The URL clients see. A pasted `https://user:token@host/…` must not travel
122 * back over `subscribeProjectClones` to every reader; git still gets the
123 * original.
124 */
125function redactRemoteUrl(remoteUrl: string): string {
126 try {
127 const url = new URL(remoteUrl);
128 // Clone URLs have no legitimate query; when one is present it is a token.
129 if (url.username.length === 0 && url.password.length === 0 && url.search.length === 0) {
130 return remoteUrl;
131 }
132 url.username = "";
133 url.password = "";
134 url.search = "";
135 return url.toString();
136 } catch {
137 return remoteUrl;
138 }
140​
141// Userinfo may itself contain `@`; everything up to the last one before the
142// host boundary goes.
143const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/]+@/gi;
144​
145function redactUrlCredentials(text: string): string {
146 return text.replace(URL_WITH_USERINFO, "$1");
148​
149/**
150 * Explains a failed first push of a published repository. The repository
151 * already exists by then, so publishing again cannot help; the user has to
152 * fix access and push. Built from fixed text and the provider's URLs only,
153 * since git's stderr can carry credentials.
154 */
155function publishPushFailureDetail(input: {
156 readonly urls: SourceControlRepositoryCloneUrls;
157 readonly remoteName: string;
158 readonly remoteUrl: string;
159 readonly reason: GitCommandFailureReason | undefined;
160}): string {
161 const created = `Created ${input.urls.nameWithOwner} and added it as remote "${input.remoteName}", but the push failed`;
162 const switchToHttps = `git remote set-url ${input.remoteName} ${input.urls.url}`;
163 const usesSsh = input.remoteUrl === input.urls.sshUrl;
164 switch (input.reason) {
165 case "authentication_failed":
166 return usesSsh
167 ? `${created} because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "${switchToHttps}", then push again.`
168 : `${created} because Git could not authenticate. Check your Git credentials, then push again.`;
169 case "host_key_unverified":
170 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.`;
171 default:
172 return `${created}. Fix the problem, then push again.`;
173 }
175​
176/**
177 * Adding a project clones over SSH for most hosts, and a machine with no SSH
178 * key there would fail every time, while the host's HTTPS credential helper
179 * may be set up. A clone whose SSH login was refused is retried once over
180 * HTTPS, unless the caller asked for SSH. A looked-up repository has the
181 * provider's own HTTPS URL; any other URL is rewritten, which is refused
182 * where it would have to guess.
183 */
184function httpsFallbackUrl(
185 input: SourceControlCloneRepositoryInput,
186 prepared: SourceControlPreparedClone,
187): string | null {
188 if (input.protocol === "ssh" || cloneUrlProtocol(prepared.cloneUrl) !== "ssh") return null;
189 if (prepared.repository?.sshUrl === prepared.cloneUrl) return prepared.repository.url;
190 return cloneUrlForProtocol(prepared.cloneUrl, "https");
192​
193const isSshRejection = (error: SourceControlRepositoryError) =>
194 isGitCommandError(error.cause) &&
195 (error.cause.reason === "authentication_failed" || error.cause.reason === "host_key_unverified");
196​
197function selectRemoteUrl(
198 urls: SourceControlRepositoryCloneUrls,
199 protocol: SourceControlCloneProtocol | undefined,
200): string {
201 switch (protocol ?? "auto") {
202 case "https":
203 return urls.url;
204 case "ssh":
205 case "auto":
206 return urls.sshUrl;
207 }
209​
210/** @public Service construction is part of the canonical Effect module API. */
211export const make = Effect.gen(function* () {
212 const config = yield* ServerConfig.ServerConfig;
213 const fileSystem = yield* FileSystem.FileSystem;
214 const git = yield* GitVcsDriver.GitVcsDriver;
215 const path = yield* Path.Path;
216 const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
217​
218 const ensureConcreteProvider = (input: {
219 readonly operation: string;
220 readonly provider: SourceControlProviderKind;
221 }) => {
222 if (input.provider !== "unknown") {
223 return Effect.succeed(input.provider);
224 }
225​
226 return Effect.fail(
227 new SourceControlRepositoryError({
228 operation: input.operation,
229 provider: input.provider,
230 detail: "Choose a source control provider before continuing.",
231 }),
232 );
233 };
234​
235 const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(
236 function* (input: SourceControlRepositoryLookupInput) {
237 const providerKind = yield* ensureConcreteProvider({
238 operation: "lookupRepository",
239 provider: input.provider,
240 });
241 const provider = yield* providers.get(providerKind);
242 const urls = yield* provider.getRepositoryCloneUrls({
243 cwd: input.cwd ?? config.cwd,
244 repository: input.repository.trim(),
245 });
246 return toRepositoryInfo(providerKind, urls);
247 },
248 // Someone adding or cloning a repository is waiting, so a background rate-limit pause must not
249 // refuse the lookup.
250 Effect.provideService(SourceControlRateLimit.Interactive, true),
251 );
252​
253 const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
254 function* (destinationPath: string) {
255 const trimmed = destinationPath.trim();
256 if (trimmed.length === 0) {
257 return yield* new SourceControlRepositoryError({
258 operation: "cloneRepository",
259 provider: SourceControlProviderKind.make("unknown"),
260 detail: "Choose a destination path before cloning.",
261 });
262 }
263​
264 return path.resolve(expandHomePath(trimmed, yield* HostProcess.HomeDirectory));
265 },
266 );
267​
268 const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
269 function* (destinationPath: string) {
270 const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
271 if (yield* fileSystem.exists(normalizedDestination)) {
272 const entries = yield* fileSystem
273 .readDirectory(normalizedDestination, { recursive: false })
274 .pipe(
275 Effect.mapError(
276 (cause) =>
277 new SourceControlRepositoryError({
278 operation: "cloneRepository",
279 provider: SourceControlProviderKind.make("unknown"),
280 detail: "Destination path already exists and is not a directory.",
281 cause,
282 }),
283 ),
284 );
285 if (entries.length > 0) {
286 return yield* new SourceControlRepositoryError({
287 operation: "cloneRepository",
288 provider: SourceControlProviderKind.make("unknown"),
289 detail: "Destination path already exists and is not empty.",
290 });
291 }
292 } else {
293 // Skip existing parents: recursive mkdir on a Windows drive root fails with EPERM.
294 const parentPath = path.dirname(normalizedDestination);
295 if (!(yield* fileSystem.exists(parentPath))) {
296 yield* fileSystem.makeDirectory(parentPath, { recursive: true });
297 }
298 }
299​
300 return {
301 destinationPath: normalizedDestination,
302 parentPath: path.dirname(normalizedDestination),
303 directoryName: path.basename(normalizedDestination),
304 };
305 },
306 );
307​
308 const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* (
309 input: SourceControlCloneRepositoryInput,
310 ) {
311 const preparedDestination = yield* prepareDestination(input.destinationPath);
312 let repository: SourceControlRepositoryInfo | null = null;
313 let remoteUrl = input.remoteUrl?.trim() ?? null;
314 let provider: SourceControlProviderKind =
315 input.provider ?? SourceControlProviderKind.make("unknown");
316​
317 if (input.provider && input.repository) {
318 repository = yield* lookupRepository({
319 provider: input.provider,
320 repository: input.repository,
321 cwd: preparedDestination.parentPath,
322 });
323 remoteUrl = selectRemoteUrl(repository, input.protocol);
324 provider = input.provider;
325 }
326​
327 if (!remoteUrl) {
328 return yield* new SourceControlRepositoryError({
329 operation: "cloneRepository",
330 provider,
331 detail: "Enter a repository path or clone URL before cloning.",
332 });
333 }
334​
335 return {
336 destinationPath: preparedDestination.destinationPath,
337 remoteUrl: redactRemoteUrl(remoteUrl),
338 cloneUrl: remoteUrl,
339 repository,
340 } satisfies SourceControlPreparedClone;
341 });
342​
343 const runClone = Effect.fn("SourceControlRepositoryService.runClone")(function* (
344 input: SourceControlCloneRepositoryInput,
345 destinationPath: string,
346 cloneUrl: string,
347 options?: SourceControlCloneOptions,
348 ) {
349 const onProgress = options?.onProgress;
350 // Git interleaves progress redraws with its real messages on stderr. The
351 // last non-progress lines are what explain a failure ("Repository not
352 // found", "Permission denied"), so keep them for the error detail.
353 const stderrTail: Array<string> = [];
354 const onStderrLine = (line: string) => {
355 const parsed = parseGitCloneProgressLine(line);
356 if (parsed) return onProgress ? onProgress(parsed) : Effect.void;
357 return Effect.sync(() => {
358 const trimmed = line.trim();
359 if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
360 // Git echoes the remote in some failures; the tail becomes user-facing text.
361 stderrTail.push(redactUrlCredentials(trimmed));
362 if (stderrTail.length > 4) stderrTail.shift();
363 });
364 };
365 yield* git
366 .execute({
367 operation: "SourceControlRepositoryService.cloneRepository",
368 cwd: path.dirname(destinationPath),
369 args: ["clone", "--progress", "--", cloneUrl, path.basename(destinationPath)],
370 timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
371 // Progress redraws add up on a slow multi-GB clone. The buffered copy
372 // is never read (the tail is kept by hand above), so keep it small
373 // and let the line callbacks keep flowing past the cap.
374 maxOutputBytes: 256 * 1024,
375 appendTruncationMarker: true,
376 keepLineCallbacksAfterTruncation: true,
377 env: CLONE_ENV,
378 progress: { onStderrLine },
379 })
380 .pipe(
381 Effect.mapError(
382 (cause) =>
383 new SourceControlRepositoryError({
384 operation: "cloneRepository",
385 provider: input.provider ?? SourceControlProviderKind.make("unknown"),
386 detail:
387 stderrTail.length > 0
388 ? stderrTail.join(" ")
389 : "The repository could not be cloned.",
390 cause,
391 }),
392 ),
393 );
394 });
395​
396 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
397 input: SourceControlCloneRepositoryInput,
398 options?: SourceControlCloneOptions,
399 ) {
400 const prepared = yield* prepareClone(input);
401 const httpsUrl = httpsFallbackUrl(input, prepared);
402 const remoteUrl = yield* runClone(
403 input,
404 prepared.destinationPath,
405 prepared.cloneUrl,
406 options,
407 ).pipe(
408 Effect.as(prepared.remoteUrl),
409 Effect.catch((sshError) =>
410 httpsUrl === null || !isSshRejection(sshError)
411 ? Effect.fail(sshError)
412 : runClone(input, prepared.destinationPath, httpsUrl, options).pipe(
413 Effect.as(redactRemoteUrl(httpsUrl)),
414 Effect.mapError(
415 (httpsError) =>
416 new SourceControlRepositoryError({
417 operation: "cloneRepository",
418 provider: sshError.provider,
419 detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`,
420 cause: httpsError.cause,
421 }),
422 ),
423 ),
424 ),
425 );
426​
427 return {
428 cwd: prepared.destinationPath,
429 remoteUrl,
430 repository: prepared.repository,
431 };
432 });
433​
434 const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
435 destinationPath: string,
436 ) {
437 const normalized = yield* normalizeDestinationPath(destinationPath);
438 // Only what git left behind may go. The destination was empty when the
439 // clone started, so anything without a `.git` inside was put there by
440 // someone else since; refuse rather than delete their files.
441 // A missing destination is already discarded; any other read failure
442 // (a file in its place, permissions) is not something to remove through.
443 const entries = yield* fileSystem.readDirectory(normalized).pipe(
444 Effect.catchIf(
445 (cause) => cause.reason._tag === "NotFound",
446 () => Effect.succeed<ReadonlyArray<string>>([]),
447 ),
448 Effect.mapError(
449 (cause) =>
450 new SourceControlRepositoryError({
451 operation: "discardClone",
452 provider: SourceControlProviderKind.make("unknown"),
453 detail: "The clone destination could not be inspected.",
454 cause,
455 }),
456 ),
457 );
458 if (entries.length > 0 && !entries.includes(".git")) {
459 return yield* new SourceControlRepositoryError({
460 operation: "discardClone",
461 provider: SourceControlProviderKind.make("unknown"),
462 detail: "Destination path contains files that are not from the clone.",
463 });
464 }
465 // The directory itself is the project's workspace root and must stay;
466 // only git's partial contents go. An interrupted git may still be closing
467 // files, so removal retries briefly.
468 yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
469 Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
470 Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
471 Effect.mapError(
472 (cause) =>
473 new SourceControlRepositoryError({
474 operation: "discardClone",
475 provider: SourceControlProviderKind.make("unknown"),
476 detail: "The partial clone could not be removed.",
477 cause,
478 }),
479 ),
480 );
481 });
482​
483 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
484 function* (input: SourceControlPublishRepositoryInput) {
485 const providerKind = yield* ensureConcreteProvider({
486 operation: "publishRepository",
487 provider: input.provider,
488 });
489 const provider = yield* providers.get(providerKind);
490 const urls = yield* provider.createRepository({
491 cwd: input.cwd,
492 repository: input.repository.trim(),
493 visibility: input.visibility,
494 });
495 const remoteUrl = selectRemoteUrl(urls, input.protocol);
496 const remoteName = yield* git.ensureRemote({
497 cwd: input.cwd,
498 preferredName: input.remoteName?.trim() || "origin",
499 url: remoteUrl,
500 });
501​
502 // An empty local repo (no commits) would make `git push HEAD:...` fail
503 // with an opaque "src refspec HEAD does not match any". Treat this as a
504 // partial success: the remote was created and wired up, but there is
505 // nothing to push yet.
506 const hasCommits = yield* git
507 .execute({
508 operation: "SourceControlRepositoryService.publishRepository.headCheck",
509 cwd: input.cwd,
510 args: ["rev-parse", "--verify", "HEAD"],
511 })
512 .pipe(
513 Effect.map(() => true),
514 Effect.orElseSucceed(() => false),
515 );
516 if (!hasCommits) {
517 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
518 return {
519 repository: toRepositoryInfo(providerKind, urls),
520 remoteName,
521 remoteUrl,
522 branch: details?.branch ?? "main",
523 status: "remote_added" as const,
524 };
525 }
526​
527 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName }).pipe(
528 Effect.mapError(
529 (cause) =>
530 new SourceControlRepositoryError({
531 operation: "publishRepository",
532 provider: providerKind,
533 detail: publishPushFailureDetail({
534 urls,
535 remoteName,
536 remoteUrl,
537 reason: cause.reason,
538 }),
539 cause,
540 }),
541 ),
542 );
543​
544 return {
545 repository: toRepositoryInfo(providerKind, urls),
546 remoteName,
547 remoteUrl,
548 branch: pushResult.branch,
549 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
550 status: "pushed" as const,
551 };
552 },
553 );
554​
555 return SourceControlRepositoryService.of({
556 lookupRepository: (input) =>
557 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
558 prepareClone: (input) =>
559 prepareClone(input).pipe(
560 mapRepositoryError(
561 "cloneRepository",
562 input.provider ?? SourceControlProviderKind.make("unknown"),
563 ),
564 ),
565 cloneRepository: (input, options) =>
566 cloneRepository(input, options).pipe(
567 mapRepositoryError(
568 "cloneRepository",
569 input.provider ?? SourceControlProviderKind.make("unknown"),
570 ),
571 ),
572 discardClone: (destinationPath) =>
573 discardClone(destinationPath).pipe(
574 mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")),
575 ),
576 publishRepository: (input) =>
577 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
578 });
579});
580​
581export const layer = Layer.effect(SourceControlRepositoryService, make);