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

SourceControlRepositoryService.ts

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