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

SourceControlRepositoryService.ts

522 lines19.3 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 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;
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;
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 );
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 };
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 }
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");
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 }
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 }
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 yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
266 }
267​
268 return {
269 destinationPath: normalizedDestination,
270 parentPath: path.dirname(normalizedDestination),
271 directoryName: path.basename(normalizedDestination),
272 };
273 },
274 );
275​
276 const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* (
277 input: SourceControlCloneRepositoryInput,
278 ) {
279 const preparedDestination = yield* prepareDestination(input.destinationPath);
280 let repository: SourceControlRepositoryInfo | null = null;
281 let remoteUrl = input.remoteUrl?.trim() ?? null;
282 let provider: SourceControlProviderKind =
283 input.provider ?? SourceControlProviderKind.make("unknown");
284​
285 if (input.provider && input.repository) {
286 repository = yield* lookupRepository({
287 provider: input.provider,
288 repository: input.repository,
289 cwd: preparedDestination.parentPath,
290 });
291 remoteUrl = selectRemoteUrl(repository, input.protocol);
292 provider = input.provider;
293 }
294​
295 if (!remoteUrl) {
296 return yield* new SourceControlRepositoryError({
297 operation: "cloneRepository",
298 provider,
299 detail: "Enter a repository path or clone URL before cloning.",
300 });
301 }
302​
303 return {
304 destinationPath: preparedDestination.destinationPath,
305 remoteUrl: redactRemoteUrl(remoteUrl),
306 cloneUrl: remoteUrl,
307 repository,
308 } satisfies SourceControlPreparedClone;
309 });
310​
311 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
312 input: SourceControlCloneRepositoryInput,
313 options?: SourceControlCloneOptions,
314 ) {
315 const prepared = yield* prepareClone(input);
316 const onProgress = options?.onProgress;
317 // Git interleaves progress redraws with its real messages on stderr. The
318 // last non-progress lines are what explain a failure ("Repository not
319 // found", "Permission denied"), so keep them for the error detail.
320 const stderrTail: Array<string> = [];
321 const onStderrLine = (line: string) => {
322 const parsed = parseGitCloneProgressLine(line);
323 if (parsed) return onProgress ? onProgress(parsed) : Effect.void;
324 return Effect.sync(() => {
325 const trimmed = line.trim();
326 if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
327 // Git echoes the remote in some failures; the tail becomes user-facing text.
328 stderrTail.push(redactUrlCredentials(trimmed));
329 if (stderrTail.length > 4) stderrTail.shift();
330 });
331 };
332 yield* git
333 .execute({
334 operation: "SourceControlRepositoryService.cloneRepository",
335 cwd: path.dirname(prepared.destinationPath),
336 args: [
337 "clone",
338 "--progress",
339 "--",
340 prepared.cloneUrl,
341 path.basename(prepared.destinationPath),
342 ],
343 timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
344 // Progress redraws add up on a slow multi-GB clone. The buffered copy
345 // is never read (the tail is kept by hand above), so keep it small
346 // and let the line callbacks keep flowing past the cap.
347 maxOutputBytes: 256 * 1024,
348 appendTruncationMarker: true,
349 keepLineCallbacksAfterTruncation: true,
350 env: CLONE_ENV,
351 progress: { onStderrLine },
352 })
353 .pipe(
354 Effect.mapError(
355 (cause) =>
356 new SourceControlRepositoryError({
357 operation: "cloneRepository",
358 provider: input.provider ?? SourceControlProviderKind.make("unknown"),
359 detail:
360 stderrTail.length > 0
361 ? stderrTail.join(" ")
362 : "The repository could not be cloned.",
363 cause,
364 }),
365 ),
366 );
367​
368 return {
369 cwd: prepared.destinationPath,
370 remoteUrl: prepared.remoteUrl,
371 repository: prepared.repository,
372 };
373 });
374​
375 const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
376 destinationPath: string,
377 ) {
378 const normalized = yield* normalizeDestinationPath(destinationPath);
379 // Only what git left behind may go. The destination was empty when the
380 // clone started, so anything without a `.git` inside was put there by
381 // someone else since; refuse rather than delete their files.
382 // A missing destination is already discarded; any other read failure
383 // (a file in its place, permissions) is not something to remove through.
384 const entries = yield* fileSystem.readDirectory(normalized).pipe(
385 Effect.catchIf(
386 (cause) => cause.reason._tag === "NotFound",
387 () => Effect.succeed<ReadonlyArray<string>>([]),
388 ),
389 Effect.mapError(
390 (cause) =>
391 new SourceControlRepositoryError({
392 operation: "discardClone",
393 provider: SourceControlProviderKind.make("unknown"),
394 detail: "The clone destination could not be inspected.",
395 cause,
396 }),
397 ),
398 );
399 if (entries.length > 0 && !entries.includes(".git")) {
400 return yield* new SourceControlRepositoryError({
401 operation: "discardClone",
402 provider: SourceControlProviderKind.make("unknown"),
403 detail: "Destination path contains files that are not from the clone.",
404 });
405 }
406 // The directory itself is the project's workspace root and must stay;
407 // only git's partial contents go. An interrupted git may still be closing
408 // files, so removal retries briefly.
409 yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
410 Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
411 Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
412 Effect.mapError(
413 (cause) =>
414 new SourceControlRepositoryError({
415 operation: "discardClone",
416 provider: SourceControlProviderKind.make("unknown"),
417 detail: "The partial clone could not be removed.",
418 cause,
419 }),
420 ),
421 );
422 });
423​
424 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
425 function* (input: SourceControlPublishRepositoryInput) {
426 const providerKind = yield* ensureConcreteProvider({
427 operation: "publishRepository",
428 provider: input.provider,
429 });
430 const provider = yield* providers.get(providerKind);
431 const urls = yield* provider.createRepository({
432 cwd: input.cwd,
433 repository: input.repository.trim(),
434 visibility: input.visibility,
435 });
436 const remoteUrl = selectRemoteUrl(urls, input.protocol);
437 const remoteName = yield* git.ensureRemote({
438 cwd: input.cwd,
439 preferredName: input.remoteName?.trim() || "origin",
440 url: remoteUrl,
441 });
442​
443 // An empty local repo (no commits) would make `git push HEAD:...` fail
444 // with an opaque "src refspec HEAD does not match any". Treat this as a
445 // partial success: the remote was created and wired up, but there is
446 // nothing to push yet.
447 const hasCommits = yield* git
448 .execute({
449 operation: "SourceControlRepositoryService.publishRepository.headCheck",
450 cwd: input.cwd,
451 args: ["rev-parse", "--verify", "HEAD"],
452 })
453 .pipe(
454 Effect.map(() => true),
455 Effect.orElseSucceed(() => false),
456 );
457 if (!hasCommits) {
458 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
459 return {
460 repository: toRepositoryInfo(providerKind, urls),
461 remoteName,
462 remoteUrl,
463 branch: details?.branch ?? "main",
464 status: "remote_added" as const,
465 };
466 }
467​
468 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName }).pipe(
469 Effect.mapError(
470 (cause) =>
471 new SourceControlRepositoryError({
472 operation: "publishRepository",
473 provider: providerKind,
474 detail: publishPushFailureDetail({
475 urls,
476 remoteName,
477 remoteUrl,
478 reason: cause.reason,
479 }),
480 cause,
481 }),
482 ),
483 );
484​
485 return {
486 repository: toRepositoryInfo(providerKind, urls),
487 remoteName,
488 remoteUrl,
489 branch: pushResult.branch,
490 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
491 status: "pushed" as const,
492 };
493 },
494 );
495​
496 return SourceControlRepositoryService.of({
497 lookupRepository: (input) =>
498 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
499 prepareClone: (input) =>
500 prepareClone(input).pipe(
501 mapRepositoryError(
502 "cloneRepository",
503 input.provider ?? SourceControlProviderKind.make("unknown"),
504 ),
505 ),
506 cloneRepository: (input, options) =>
507 cloneRepository(input, options).pipe(
508 mapRepositoryError(
509 "cloneRepository",
510 input.provider ?? SourceControlProviderKind.make("unknown"),
511 ),
512 ),
513 discardClone: (destinationPath) =>
514 discardClone(destinationPath).pipe(
515 mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")),
516 ),
517 publishRepository: (input) =>
518 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
519 });
520});
521​
522export const layer = Layer.effect(SourceControlRepositoryService, make);