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

SourceControlRepositoryService.ts

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