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

SourceControlRepositoryService.ts

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