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

SourceControlRepositoryService.ts

461 lines16.8 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 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 * as 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;
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;
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 );
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/**
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 }
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");
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 }
155​
156/** @public Service construction is part of the canonical Effect module API. */
157export const make = Effect.gen(function* () {
158 const config = yield* ServerConfig.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 }) => {
168 if (input.provider !== "unknown") {
169 return Effect.succeed(input.provider);
170 }
171​
172 return Effect.fail(
173 new SourceControlRepositoryError({
174 operation: input.operation,
175 provider: input.provider,
176 detail: "Choose a source control provider before continuing.",
177 }),
178 );
179 };
180​
181 const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
182 input: SourceControlRepositoryLookupInput,
183 ) {
184 const providerKind = yield* ensureConcreteProvider({
185 operation: "lookupRepository",
186 provider: input.provider,
187 });
188 const provider = yield* providers.get(providerKind);
189 const urls = yield* provider.getRepositoryCloneUrls({
190 cwd: input.cwd ?? config.cwd,
191 repository: input.repository.trim(),
192 });
193 return toRepositoryInfo(providerKind, urls);
194 });
195​
196 const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
197 function* (destinationPath: string) {
198 const trimmed = destinationPath.trim();
199 if (trimmed.length === 0) {
200 return yield* new SourceControlRepositoryError({
201 operation: "cloneRepository",
202 provider: "unknown",
203 detail: "Choose a destination path before cloning.",
204 });
205 }
206​
207 return path.resolve(expandHomePathWith(trimmed, path));
208 },
209 );
210​
211 const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
212 function* (destinationPath: string) {
213 const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
214 if (yield* fileSystem.exists(normalizedDestination)) {
215 const entries = yield* fileSystem
216 .readDirectory(normalizedDestination, { recursive: false })
217 .pipe(
218 Effect.mapError(
219 (cause) =>
220 new SourceControlRepositoryError({
221 operation: "cloneRepository",
222 provider: "unknown",
223 detail: "Destination path already exists and is not a directory.",
224 cause,
225 }),
226 ),
227 );
228 if (entries.length > 0) {
229 return yield* new SourceControlRepositoryError({
230 operation: "cloneRepository",
231 provider: "unknown",
232 detail: "Destination path already exists and is not empty.",
233 });
234 }
235 } else {
236 yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
237 }
238​
239 return {
240 destinationPath: normalizedDestination,
241 parentPath: path.dirname(normalizedDestination),
242 directoryName: path.basename(normalizedDestination),
243 };
244 },
245 );
246​
247 const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* (
248 input: SourceControlCloneRepositoryInput,
249 ) {
250 const preparedDestination = yield* prepareDestination(input.destinationPath);
251 let repository: SourceControlRepositoryInfo | null = null;
252 let remoteUrl = input.remoteUrl?.trim() ?? null;
253 let provider: SourceControlProviderKind = input.provider ?? "unknown";
254​
255 if (input.provider && input.repository) {
256 repository = yield* lookupRepository({
257 provider: input.provider,
258 repository: input.repository,
259 cwd: preparedDestination.parentPath,
260 });
261 remoteUrl = selectRemoteUrl(repository, input.protocol);
262 provider = input.provider;
263 }
264​
265 if (!remoteUrl) {
266 return yield* new SourceControlRepositoryError({
267 operation: "cloneRepository",
268 provider,
269 detail: "Enter a repository path or clone URL before cloning.",
270 });
271 }
272​
273 return {
274 destinationPath: preparedDestination.destinationPath,
275 remoteUrl: redactRemoteUrl(remoteUrl),
276 cloneUrl: remoteUrl,
277 repository,
278 } satisfies SourceControlPreparedClone;
279 });
280​
281 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
282 input: SourceControlCloneRepositoryInput,
283 options?: SourceControlCloneOptions,
284 ) {
285 const prepared = yield* prepareClone(input);
286 const onProgress = options?.onProgress;
287 // Git interleaves progress redraws with its real messages on stderr. The
288 // last non-progress lines are what explain a failure ("Repository not
289 // found", "Permission denied"), so keep them for the error detail.
290 const stderrTail: Array<string> = [];
291 const onStderrLine = (line: string) => {
292 const parsed = parseGitCloneProgressLine(line);
293 if (parsed) return onProgress ? onProgress(parsed) : Effect.void;
294 return Effect.sync(() => {
295 const trimmed = line.trim();
296 if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
297 // Git echoes the remote in some failures; the tail becomes user-facing text.
298 stderrTail.push(redactUrlCredentials(trimmed));
299 if (stderrTail.length > 4) stderrTail.shift();
300 });
301 };
302 yield* git
303 .execute({
304 operation: "SourceControlRepositoryService.cloneRepository",
305 cwd: path.dirname(prepared.destinationPath),
306 args: ["clone", "--progress", prepared.cloneUrl, path.basename(prepared.destinationPath)],
307 timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
308 // Progress redraws add up on a slow multi-GB clone. The buffered copy
309 // is never read (the tail is kept by hand above), so keep it small
310 // and let the line callbacks keep flowing past the cap.
311 maxOutputBytes: 256 * 1024,
312 appendTruncationMarker: true,
313 keepLineCallbacksAfterTruncation: true,
314 env: CLONE_ENV,
315 progress: { onStderrLine },
316 })
317 .pipe(
318 Effect.mapError(
319 (cause) =>
320 new SourceControlRepositoryError({
321 operation: "cloneRepository",
322 provider: input.provider ?? "unknown",
323 detail:
324 stderrTail.length > 0
325 ? stderrTail.join(" ")
326 : "The repository could not be cloned.",
327 cause,
328 }),
329 ),
330 );
331​
332 return {
333 cwd: prepared.destinationPath,
334 remoteUrl: prepared.remoteUrl,
335 repository: prepared.repository,
336 };
337 });
338​
339 const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
340 destinationPath: string,
341 ) {
342 const normalized = yield* normalizeDestinationPath(destinationPath);
343 // Only what git left behind may go. The destination was empty when the
344 // clone started, so anything without a `.git` inside was put there by
345 // someone else since; refuse rather than delete their files.
346 // A missing destination is already discarded; any other read failure
347 // (a file in its place, permissions) is not something to remove through.
348 const entries = yield* fileSystem.readDirectory(normalized).pipe(
349 Effect.catchIf(
350 (cause) => cause.reason._tag === "NotFound",
351 () => Effect.succeed<ReadonlyArray<string>>([]),
352 ),
353 Effect.mapError(
354 (cause) =>
355 new SourceControlRepositoryError({
356 operation: "discardClone",
357 provider: "unknown",
358 detail: "The clone destination could not be inspected.",
359 cause,
360 }),
361 ),
362 );
363 if (entries.length > 0 && !entries.includes(".git")) {
364 return yield* new SourceControlRepositoryError({
365 operation: "discardClone",
366 provider: "unknown",
367 detail: "Destination path contains files that are not from the clone.",
368 });
369 }
370 // The directory itself is the project's workspace root and must stay;
371 // only git's partial contents go. An interrupted git may still be closing
372 // files, so removal retries briefly.
373 yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
374 Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
375 Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
376 Effect.mapError(
377 (cause) =>
378 new SourceControlRepositoryError({
379 operation: "discardClone",
380 provider: "unknown",
381 detail: "The partial clone could not be removed.",
382 cause,
383 }),
384 ),
385 );
386 });
387​
388 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
389 function* (input: SourceControlPublishRepositoryInput) {
390 const providerKind = yield* ensureConcreteProvider({
391 operation: "publishRepository",
392 provider: input.provider,
393 });
394 const provider = yield* providers.get(providerKind);
395 const urls = yield* provider.createRepository({
396 cwd: input.cwd,
397 repository: input.repository.trim(),
398 visibility: input.visibility,
399 });
400 const remoteUrl = selectRemoteUrl(urls, input.protocol);
401 const remoteName = yield* git.ensureRemote({
402 cwd: input.cwd,
403 preferredName: input.remoteName?.trim() || "origin",
404 url: remoteUrl,
405 });
406​
407 // An empty local repo (no commits) would make `git push HEAD:...` fail
408 // with an opaque "src refspec HEAD does not match any". Treat this as a
409 // partial success: the remote was created and wired up, but there is
410 // nothing to push yet.
411 const hasCommits = yield* git
412 .execute({
413 operation: "SourceControlRepositoryService.publishRepository.headCheck",
414 cwd: input.cwd,
415 args: ["rev-parse", "--verify", "HEAD"],
416 })
417 .pipe(
418 Effect.map(() => true),
419 Effect.orElseSucceed(() => false),
420 );
421 if (!hasCommits) {
422 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
423 return {
424 repository: toRepositoryInfo(providerKind, urls),
425 remoteName,
426 remoteUrl,
427 branch: details?.branch ?? "main",
428 status: "remote_added" as const,
429 };
430 }
431​
432 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
433​
434 return {
435 repository: toRepositoryInfo(providerKind, urls),
436 remoteName,
437 remoteUrl,
438 branch: pushResult.branch,
439 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
440 status: "pushed" as const,
441 };
442 },
443 );
444​
445 return SourceControlRepositoryService.of({
446 lookupRepository: (input) =>
447 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
448 prepareClone: (input) =>
449 prepareClone(input).pipe(mapRepositoryError("cloneRepository", input.provider ?? "unknown")),
450 cloneRepository: (input, options) =>
451 cloneRepository(input, options).pipe(
452 mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
453 ),
454 discardClone: (destinationPath) =>
455 discardClone(destinationPath).pipe(mapRepositoryError("discardClone", "unknown")),
456 publishRepository: (input) =>
457 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
458 });
459});
460​
461export const layer = Layer.effect(SourceControlRepositoryService, make);