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