Open History to see the last commit
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 SourceControlRepositoryError,
11 type SourceControlCloneRepositoryInput,
12 type SourceControlCloneRepositoryResult,
13 type SourceControlCloneProtocol,
14 type SourceControlProviderKind,
15 type SourceControlPublishRepositoryInput,
16 type SourceControlPublishRepositoryResult,
17 type SourceControlRepositoryCloneUrls,
18 type SourceControlRepositoryInfo,
19 type SourceControlRepositoryLookupInput,
20} from "@t3tools/contracts";
21
22import { ServerConfig } from "../config.ts";
23import { expandHomePathWith } from "../pathExpansion.ts";
24import {
25 parseGitCloneProgressLine,
26 type GitCloneProgressLine,
27} from "../project/gitCloneProgress.ts";
28import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
29import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
30const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
31
32export class SourceControlRepositoryService extends Context.Service<
33 SourceControlRepositoryService,
34 {
35 readonly lookupRepository: (
36 input: SourceControlRepositoryLookupInput,
37 ) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
38 /**
39 * Everything `cloneRepository` checks before running git: the resolved
40 * remote, the normalized destination, and that the destination is empty.
41 * Lets a caller create the project first and clone afterwards.
42 */
43 readonly prepareClone: (
44 input: SourceControlCloneRepositoryInput,
45 ) => Effect.Effect<SourceControlPreparedClone, SourceControlRepositoryError>;
46 readonly cloneRepository: (
47 input: SourceControlCloneRepositoryInput,
48 options?: SourceControlCloneOptions,
49 ) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
50 /** Removes a partial or failed clone so the destination is empty again. */
51 readonly discardClone: (
52 destinationPath: string,
53 ) => Effect.Effect<void, SourceControlRepositoryError>;
54 readonly publishRepository: (
55 input: SourceControlPublishRepositoryInput,
56 ) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
57 }
58>()("t3/sourceControl/SourceControlRepositoryService") {}
59
60export interface SourceControlPreparedClone {
61 readonly destinationPath: string;
62 /** Credential-free; safe to show and to store in snapshots. */
63 readonly remoteUrl: string;
64 /** What git is given; may carry embedded credentials. */
65 readonly cloneUrl: string;
66 readonly repository: SourceControlRepositoryInfo | null;
67}
68
69export interface SourceControlCloneOptions {
70 readonly onProgress?: (line: GitCloneProgressLine) => Effect.Effect<void>;
71 /** Overrides the default clone budget; `null` disables the deadline. */
72 readonly timeoutMs?: number | null;
73}
74
75// The synchronous RPC (older clients, mobile) keeps a deadline: nothing else
76// tells the user a clone stalled. The tracked path passes null and relies on
77// progress and Cancel instead.
78const CLONE_TIMEOUT_MS = 120_000;
79const CLONE_ENV = {
80 // `--progress` forces the transfer counters through the pipe; the delay env
81 // makes the checkout counter start immediately. No tty means a credential
82 // prompt would hang forever, so tell git to fail instead.
83 GIT_PROGRESS_DELAY: "0",
84 GIT_TERMINAL_PROMPT: "0",
85 LC_ALL: "C",
86} satisfies NodeJS.ProcessEnv;
87
88function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
89 return Effect.mapError((cause: unknown) =>
90 isSourceControlRepositoryError(cause)
91 ? cause
92 : new SourceControlRepositoryError({
93 operation,
94 provider,
95 detail: "The source control operation could not be completed.",
96 cause,
97 }),
98 );
99}
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 };
111}
112
113/**
114 * The URL clients see. A pasted `https://user:token@host/…` must not travel
115 * back over `subscribeProjectClones` to every reader; git still gets the
116 * original.
117 */
118function redactRemoteUrl(remoteUrl: string): string {
119 try {
120 const url = new URL(remoteUrl);
121 // Clone URLs have no legitimate query; when one is present it is a token.
122 if (url.username.length === 0 && url.password.length === 0 && url.search.length === 0) {
123 return remoteUrl;
124 }
125 url.username = "";
126 url.password = "";
127 url.search = "";
128 return url.toString();
129 } catch {
130 return remoteUrl;
131 }
132}
133
134// Userinfo may itself contain `@`; everything up to the last one before the
135// host boundary goes.
136const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/]+@/gi;
137
138/** Drops `user:token@` from any URL embedded in free text. */
139function redactUrlCredentials(text: string): string {
140 return text.replace(URL_WITH_USERINFO, "$1");
141}
142
143function selectRemoteUrl(
144 urls: SourceControlRepositoryCloneUrls,
145 protocol: SourceControlCloneProtocol | undefined,
146): string {
147 switch (protocol ?? "auto") {
148 case "https":
149 return urls.url;
150 case "ssh":
151 case "auto":
152 return urls.sshUrl;
153 }
154}
155
156/** @public Service construction is part of the canonical Effect module API. */
157export const make = Effect.gen(function* () {
158 const config = yield* ServerConfig;
159 const fileSystem = yield* FileSystem.FileSystem;
160 const git = yield* GitVcsDriver.GitVcsDriver;
161 const path = yield* Path.Path;
162 const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
163
164 const ensureConcreteProvider = (input: {
165 readonly operation: string;
166 readonly provider: SourceControlProviderKind;
167 readonly host?: string | undefined;
168 }) => {
169 if (input.provider === "unknown") {
170 return Effect.fail(
171 new SourceControlRepositoryError({
172 operation: input.operation,
173 provider: input.provider,
174 detail: "Choose a source control provider before continuing.",
175 }),
176 );
177 }
178
179 if (input.provider === "github-enterprise" && !input.host?.trim()) {
180 return Effect.fail(
181 new SourceControlRepositoryError({
182 operation: input.operation,
183 provider: input.provider,
184 detail: "Choose a GitHub Enterprise host before continuing.",
185 }),
186 );
187 }
188
189 return Effect.succeed(input.provider);
190 };
191
192 const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
193 input: SourceControlRepositoryLookupInput,
194 ) {
195 const providerKind = yield* ensureConcreteProvider({
196 operation: "lookupRepository",
197 provider: input.provider,
198 host: input.host,
199 });
200 const provider = yield* providers.get(providerKind);
201 const urls = yield* provider.getRepositoryCloneUrls({
202 cwd: input.cwd ?? config.cwd,
203 repository: input.repository.trim(),
204 ...(input.host ? { host: input.host } : {}),
205 });
206 return toRepositoryInfo(providerKind, urls);
207 });
208
209 const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
210 function* (destinationPath: string) {
211 const trimmed = destinationPath.trim();
212 if (trimmed.length === 0) {
213 return yield* new SourceControlRepositoryError({
214 operation: "cloneRepository",
215 provider: "unknown",
216 detail: "Choose a destination path before cloning.",
217 });
218 }
219
220 return path.resolve(expandHomePathWith(trimmed, path));
221 },
222 );
223
224 const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
225 function* (destinationPath: string) {
226 const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
227 if (yield* fileSystem.exists(normalizedDestination)) {
228 const entries = yield* fileSystem
229 .readDirectory(normalizedDestination, { recursive: false })
230 .pipe(
231 Effect.mapError(
232 (cause) =>
233 new SourceControlRepositoryError({
234 operation: "cloneRepository",
235 provider: "unknown",
236 detail: "Destination path already exists and is not a directory.",
237 cause,
238 }),
239 ),
240 );
241 if (entries.length > 0) {
242 return yield* new SourceControlRepositoryError({
243 operation: "cloneRepository",
244 provider: "unknown",
245 detail: "Destination path already exists and is not empty.",
246 });
247 }
248 } else {
249 yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
250 }
251
252 return {
253 destinationPath: normalizedDestination,
254 parentPath: path.dirname(normalizedDestination),
255 directoryName: path.basename(normalizedDestination),
256 };
257 },
258 );
259
260 const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* (
261 input: SourceControlCloneRepositoryInput,
262 ) {
263 const preparedDestination = yield* prepareDestination(input.destinationPath);
264 let repository: SourceControlRepositoryInfo | null = null;
265 let remoteUrl = input.remoteUrl?.trim() ?? null;
266 let provider: SourceControlProviderKind = input.provider ?? "unknown";
267
268 if (input.provider && input.repository) {
269 repository = yield* lookupRepository({
270 provider: input.provider,
271 repository: input.repository,
272 cwd: preparedDestination.parentPath,
273 ...(input.host ? { host: input.host } : {}),
274 });
275 remoteUrl = selectRemoteUrl(repository, input.protocol);
276 provider = input.provider;
277 }
278
279 if (!remoteUrl) {
280 return yield* new SourceControlRepositoryError({
281 operation: "cloneRepository",
282 provider,
283 detail: "Enter a repository path or clone URL before cloning.",
284 });
285 }
286
287 return {
288 destinationPath: preparedDestination.destinationPath,
289 remoteUrl: redactRemoteUrl(remoteUrl),
290 cloneUrl: remoteUrl,
291 repository,
292 } satisfies SourceControlPreparedClone;
293 });
294
295 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
296 input: SourceControlCloneRepositoryInput,
297 options?: SourceControlCloneOptions,
298 ) {
299 const prepared = yield* prepareClone(input);
300 const onProgress = options?.onProgress;
301 // Git interleaves progress redraws with its real messages on stderr. The
302 // last non-progress lines are what explain a failure ("Repository not
303 // found", "Permission denied"), so keep them for the error detail.
304 const stderrTail: Array<string> = [];
305 const onStderrLine = (line: string) => {
306 const parsed = parseGitCloneProgressLine(line);
307 if (parsed) return onProgress ? onProgress(parsed) : Effect.void;
308 return Effect.sync(() => {
309 const trimmed = line.trim();
310 if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
311 // Git echoes the remote in some failures; the tail becomes user-facing text.
312 stderrTail.push(redactUrlCredentials(trimmed));
313 if (stderrTail.length > 4) stderrTail.shift();
314 });
315 };
316 yield* git
317 .execute({
318 operation: "SourceControlRepositoryService.cloneRepository",
319 cwd: path.dirname(prepared.destinationPath),
320 args: ["clone", "--progress", prepared.cloneUrl, path.basename(prepared.destinationPath)],
321 timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
322 // Progress redraws add up on a slow multi-GB clone. The buffered copy
323 // is never read (the tail is kept by hand above), so keep it small
324 // and let the line callbacks keep flowing past the cap.
325 maxOutputBytes: 256 * 1024,
326 appendTruncationMarker: true,
327 keepLineCallbacksAfterTruncation: true,
328 env: CLONE_ENV,
329 progress: { onStderrLine },
330 })
331 .pipe(
332 Effect.mapError(
333 (cause) =>
334 new SourceControlRepositoryError({
335 operation: "cloneRepository",
336 provider: input.provider ?? "unknown",
337 detail:
338 stderrTail.length > 0
339 ? stderrTail.join(" ")
340 : "The repository could not be cloned.",
341 cause,
342 }),
343 ),
344 );
345
346 return {
347 cwd: prepared.destinationPath,
348 remoteUrl: prepared.remoteUrl,
349 repository: prepared.repository,
350 };
351 });
352
353 const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
354 destinationPath: string,
355 ) {
356 const normalized = yield* normalizeDestinationPath(destinationPath);
357 // Only what git left behind may go. The destination was empty when the
358 // clone started, so anything without a `.git` inside was put there by
359 // someone else since; refuse rather than delete their files.
360 // A missing destination is already discarded; any other read failure
361 // (a file in its place, permissions) is not something to remove through.
362 const entries = yield* fileSystem.readDirectory(normalized).pipe(
363 Effect.catchIf(
364 (cause) => cause.reason._tag === "NotFound",
365 () => Effect.succeed<ReadonlyArray<string>>([]),
366 ),
367 Effect.mapError(
368 (cause) =>
369 new SourceControlRepositoryError({
370 operation: "discardClone",
371 provider: "unknown",
372 detail: "The clone destination could not be inspected.",
373 cause,
374 }),
375 ),
376 );
377 if (entries.length > 0 && !entries.includes(".git")) {
378 return yield* new SourceControlRepositoryError({
379 operation: "discardClone",
380 provider: "unknown",
381 detail: "Destination path contains files that are not from the clone.",
382 });
383 }
384 // The directory itself is the project's workspace root and must stay;
385 // only git's partial contents go. An interrupted git may still be closing
386 // files, so removal retries briefly.
387 yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
388 Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
389 Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
390 Effect.mapError(
391 (cause) =>
392 new SourceControlRepositoryError({
393 operation: "discardClone",
394 provider: "unknown",
395 detail: "The partial clone could not be removed.",
396 cause,
397 }),
398 ),
399 );
400 });
401
402 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
403 function* (input: SourceControlPublishRepositoryInput) {
404 const providerKind = yield* ensureConcreteProvider({
405 operation: "publishRepository",
406 provider: input.provider,
407 host: input.host,
408 });
409 const provider = yield* providers.get(providerKind);
410 const urls = yield* provider.createRepository({
411 cwd: input.cwd,
412 repository: input.repository.trim(),
413 visibility: input.visibility,
414 ...(input.host ? { host: input.host } : {}),
415 });
416 const remoteUrl = selectRemoteUrl(urls, input.protocol);
417 const remoteName = yield* git.ensureRemote({
418 cwd: input.cwd,
419 preferredName: input.remoteName?.trim() || "origin",
420 url: remoteUrl,
421 });
422
423 // An empty local repo (no commits) would make `git push HEAD:...` fail
424 // with an opaque "src refspec HEAD does not match any". Treat this as a
425 // partial success: the remote was created and wired up, but there is
426 // nothing to push yet.
427 const hasCommits = yield* git
428 .execute({
429 operation: "SourceControlRepositoryService.publishRepository.headCheck",
430 cwd: input.cwd,
431 args: ["rev-parse", "--verify", "HEAD"],
432 })
433 .pipe(
434 Effect.map(() => true),
435 Effect.orElseSucceed(() => false),
436 );
437 if (!hasCommits) {
438 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
439 return {
440 repository: toRepositoryInfo(providerKind, urls),
441 remoteName,
442 remoteUrl,
443 branch: details?.branch ?? "main",
444 status: "remote_added" as const,
445 };
446 }
447
448 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
449
450 return {
451 repository: toRepositoryInfo(providerKind, urls),
452 remoteName,
453 remoteUrl,
454 branch: pushResult.branch,
455 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
456 status: "pushed" as const,
457 };
458 },
459 );
460
461 return SourceControlRepositoryService.of({
462 lookupRepository: (input) =>
463 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
464 prepareClone: (input) =>
465 prepareClone(input).pipe(mapRepositoryError("cloneRepository", input.provider ?? "unknown")),
466 cloneRepository: (input, options) =>
467 cloneRepository(input, options).pipe(
468 mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
469 ),
470 discardClone: (destinationPath) =>
471 discardClone(destinationPath).pipe(mapRepositoryError("discardClone", "unknown")),
472 publishRepository: (input) =>
473 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
474 });
475});
476
477export const layer = Layer.effect(SourceControlRepositoryService, make);