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

SourceControlRepositoryService.ts

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