Repository navigation
Expand file tree
/
Copy pathSourceControlRepositoryService.ts
More file actions
590 lines (552 loc) · 22.3 KB
/
Copy pathSourceControlRepositoryService.ts
File metadata and controls
590 lines (552 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import {
GitCommandError,
SourceControlProviderError,
SourceControlRepositoryError,
type GitCommandFailureReason,
type SourceControlCloneRepositoryInput,
type SourceControlCloneRepositoryResult,
type SourceControlCloneProtocol,
SourceControlProviderKind,
type SourceControlPublishRepositoryInput,
type SourceControlPublishRepositoryResult,
type SourceControlRepositoryCloneUrls,
type SourceControlRepositoryInfo,
type SourceControlRepositoryLookupInput,
} from "@t3tools/contracts";
import * as ServerConfig from "../config.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import {
parseGitCloneProgressLine,
type GitCloneProgressLine,
} from "../project/gitCloneProgress.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { cloneUrlForProtocol, cloneUrlProtocol } from "@t3tools/shared/cloneUrl";
const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
const isGitCommandError = Schema.is(GitCommandError);
export class SourceControlRepositoryService extends Context.Service<
SourceControlRepositoryService,
{
readonly lookupRepository: (
input: SourceControlRepositoryLookupInput,
) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
readonly prepareClone: (
input: SourceControlCloneRepositoryInput,
) => Effect.Effect<SourceControlPreparedClone, SourceControlRepositoryError>;
readonly cloneRepository: (
input: SourceControlCloneRepositoryInput,
options?: SourceControlCloneOptions,
) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
readonly discardClone: (
destinationPath: string,
) => Effect.Effect<void, SourceControlRepositoryError>;
readonly publishRepository: (
input: SourceControlPublishRepositoryInput,
) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
}
>()("t3/sourceControl/SourceControlRepositoryService") {}
export interface SourceControlPreparedClone {
readonly destinationPath: string;
readonly remoteUrl: string;
readonly cloneUrl: string;
readonly repository: SourceControlRepositoryInfo | null;
}
export interface SourceControlCloneOptions {
readonly onProgress?: (line: GitCloneProgressLine) => Effect.Effect<void>;
/** Overrides the default clone budget; `null` disables the deadline. */
readonly timeoutMs?: number | null;
}
// Older/mobile synchronous RPCs need deadlines; tracked clones use progress and Cancel instead.
const CLONE_TIMEOUT_MS = 120_000;
const CLONE_ENV = {
// Force piped progress immediately; refuse credential prompts that would hang without a tty.
GIT_PROGRESS_DELAY: "0",
GIT_TERMINAL_PROMPT: "0",
// English progress without overriding LC_CTYPE, which a global post-checkout hook inherits.
LANGUAGE: "C",
} satisfies NodeJS.ProcessEnv;
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
return Effect.mapError((cause: unknown) =>
isSourceControlRepositoryError(cause)
? cause
: new SourceControlRepositoryError({
operation,
provider,
detail:
(isSourceControlProviderError(cause)
? SourceControlProvider.userFacingSourceControlDetail(cause.cause)
: undefined) ?? "The source control operation could not be completed.",
cause,
}),
);
}
function toRepositoryInfo(
provider: SourceControlProviderKind,
urls: SourceControlRepositoryCloneUrls,
): SourceControlRepositoryInfo {
return {
provider,
nameWithOwner: urls.nameWithOwner,
url: urls.url,
sshUrl: urls.sshUrl,
};
}
// Redact credentials from client clone snapshots; git still receives the credentials.
function redactRemoteUrl(remoteUrl: string): string {
try {
const url = new URL(remoteUrl);
// Clone URLs have no legitimate query; when one is present it is a token.
if (url.username.length === 0 && url.password.length === 0 && url.search.length === 0) {
return remoteUrl;
}
url.username = "";
url.password = "";
url.search = "";
return url.toString();
} catch {
return remoteUrl;
}
}
// Userinfo can contain @; remove through the last one before the host boundary.
const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]+@/gi;
// Git leaves quotes inside query tokens unescaped; consume through the closing quote.
const QUOTED_URL_QUERY = /(['"])([a-z][a-z0-9+.-]*:\/\/[^\s?]*)\?.*\1(?=[\s:]|$)/gi;
const URL_QUERY = /\b([a-z][a-z0-9+.-]*:\/\/[^\s?]*)\?[^\s]*/gi;
function redactUrlCredentials(text: string): string {
return text
.replace(QUOTED_URL_QUERY, "$1$2$1")
.replace(URL_QUERY, "$1")
.replace(URL_WITH_USERINFO, "$1");
}
// The remote already exists after push failure; advise fixing access and pushing.
// Use fixed text and provider URLs because git stderr can expose credentials.
function publishPushFailureDetail(input: {
readonly urls: SourceControlRepositoryCloneUrls;
readonly remoteName: string;
readonly remoteUrl: string;
readonly reason: GitCommandFailureReason | undefined;
}): string {
const created = `Created ${input.urls.nameWithOwner} and added it as remote "${input.remoteName}", but the push failed`;
const switchToHttps = `git remote set-url ${input.remoteName} ${input.urls.url}`;
const usesSsh = input.remoteUrl === input.urls.sshUrl;
switch (input.reason) {
case "authentication_failed":
return usesSsh
? `${created} because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "${switchToHttps}", then push again.`
: `${created} because Git could not authenticate. Check your Git credentials, then push again.`;
case "host_key_unverified":
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.`;
default:
return `${created}. Fix the problem, then push again.`;
}
}
/**
* SSH rejection can be retried over HTTPS when the host's credential helper is available.
* Explicit SSH requests must not fall back; unknown URL shapes must not be guessed.
*/
function httpsFallbackUrl(
input: SourceControlCloneRepositoryInput,
prepared: SourceControlPreparedClone,
): string | null {
if (input.protocol === "ssh" || cloneUrlProtocol(prepared.cloneUrl) !== "ssh") return null;
if (prepared.repository?.sshUrl === prepared.cloneUrl) return prepared.repository.url;
return cloneUrlForProtocol(prepared.cloneUrl, "https");
}
const isSshRejection = (error: SourceControlRepositoryError) =>
isGitCommandError(error.cause) &&
(error.cause.reason === "authentication_failed" || error.cause.reason === "host_key_unverified");
function selectRemoteUrl(
urls: SourceControlRepositoryCloneUrls,
protocol: SourceControlCloneProtocol | undefined,
): string {
switch (protocol ?? "auto") {
case "https":
return urls.url;
case "ssh":
case "auto":
return urls.sshUrl;
}
}
/** @public */
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const git = yield* GitVcsDriver.GitVcsDriver;
const path = yield* Path.Path;
const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const ensureConcreteProvider = (input: {
readonly operation: string;
readonly provider: SourceControlProviderKind;
}) => {
if (input.provider !== "unknown") {
return Effect.succeed(input.provider);
}
return Effect.fail(
new SourceControlRepositoryError({
operation: input.operation,
provider: input.provider,
detail: "Choose a source control provider before continuing.",
}),
);
};
const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(
function* (input: SourceControlRepositoryLookupInput) {
const providerKind = yield* ensureConcreteProvider({
operation: "lookupRepository",
provider: input.provider,
});
const provider = yield* providers.get(providerKind);
const urls = yield* provider.getRepositoryCloneUrls({
cwd: input.cwd ?? config.cwd,
repository: input.repository.trim(),
});
return toRepositoryInfo(providerKind, urls);
},
// Someone adding or cloning a repository is waiting, so a background rate-limit pause must not
// refuse the lookup.
Effect.provideService(SourceControlRateLimit.Interactive, true),
);
const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
function* (destinationPath: string) {
const trimmed = destinationPath.trim();
if (trimmed.length === 0) {
return yield* new SourceControlRepositoryError({
operation: "cloneRepository",
provider: SourceControlProviderKind.make("unknown"),
detail: "Choose a destination path before cloning.",
});
}
return path.resolve(expandHomePath(trimmed, yield* HostProcess.HomeDirectory));
},
);
const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
function* (destinationPath: string) {
const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
if (yield* fileSystem.exists(normalizedDestination)) {
const entries = yield* fileSystem
.readDirectory(normalizedDestination, { recursive: false })
.pipe(
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "cloneRepository",
provider: SourceControlProviderKind.make("unknown"),
detail: "Destination path already exists and is not a directory.",
cause,
}),
),
);
if (entries.length > 0) {
return yield* new SourceControlRepositoryError({
operation: "cloneRepository",
provider: SourceControlProviderKind.make("unknown"),
detail: "Destination path already exists and is not empty.",
});
}
} else {
// Skip existing parents: recursive mkdir on a Windows drive root fails with EPERM.
const parentPath = path.dirname(normalizedDestination);
if (!(yield* fileSystem.exists(parentPath))) {
yield* fileSystem.makeDirectory(parentPath, { recursive: true });
}
}
return {
destinationPath: normalizedDestination,
parentPath: path.dirname(normalizedDestination),
directoryName: path.basename(normalizedDestination),
};
},
);
const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* (
input: SourceControlCloneRepositoryInput,
) {
const preparedDestination = yield* prepareDestination(input.destinationPath);
let repository: SourceControlRepositoryInfo | null = null;
let remoteUrl = input.remoteUrl?.trim() ?? null;
let provider: SourceControlProviderKind =
input.provider ?? SourceControlProviderKind.make("unknown");
if (input.provider && input.repository) {
repository = yield* lookupRepository({
provider: input.provider,
repository: input.repository,
cwd: preparedDestination.parentPath,
});
remoteUrl = selectRemoteUrl(repository, input.protocol);
provider = input.provider;
}
if (!remoteUrl) {
return yield* new SourceControlRepositoryError({
operation: "cloneRepository",
provider,
detail: "Enter a repository path or clone URL before cloning.",
});
}
return {
destinationPath: preparedDestination.destinationPath,
remoteUrl: redactRemoteUrl(remoteUrl),
cloneUrl: remoteUrl,
repository,
} satisfies SourceControlPreparedClone;
});
const runClone = Effect.fn("SourceControlRepositoryService.runClone")(function* (
input: SourceControlCloneRepositoryInput,
destinationPath: string,
cloneUrl: string,
options?: SourceControlCloneOptions,
) {
const onProgress = options?.onProgress;
// Git mixes progress and diagnostics on stderr; retain non-progress tail lines for failure details.
const stderrTail: Array<string> = [];
const onStderrLine = (line: string) => {
const parsed = parseGitCloneProgressLine(line);
if (parsed) return onProgress ? onProgress(parsed) : Effect.void;
return Effect.sync(() => {
const trimmed = line.trim();
if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
// Git echoes the remote in some failures; the tail becomes user-facing text.
stderrTail.push(redactUrlCredentials(trimmed));
if (stderrTail.length > 4) stderrTail.shift();
});
};
// Git misreads @ in a pathless URL's query as userinfo and echoes its suffix as the host.
const normalizedCloneUrl = cloneUrl.replace(/^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)\?/i, "$1/?");
yield* git
.execute({
operation: "SourceControlRepositoryService.cloneRepository",
cwd: path.dirname(destinationPath),
args: ["clone", "--progress", "--", normalizedCloneUrl, path.basename(destinationPath)],
timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
// Buffered output is unused and progress can be huge; cap it while retaining line callbacks.
maxOutputBytes: 256 * 1024,
appendTruncationMarker: true,
keepLineCallbacksAfterTruncation: true,
env: CLONE_ENV,
progress: { onStderrLine },
})
.pipe(
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "cloneRepository",
provider: input.provider ?? SourceControlProviderKind.make("unknown"),
detail:
stderrTail.length > 0
? stderrTail.join(" ")
: "The repository could not be cloned.",
cause,
}),
),
);
});
const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
input: SourceControlCloneRepositoryInput,
options?: SourceControlCloneOptions,
) {
const prepared = yield* prepareClone(input);
const httpsUrl = httpsFallbackUrl(input, prepared);
const remoteUrl = yield* runClone(
input,
prepared.destinationPath,
prepared.cloneUrl,
options,
).pipe(
Effect.as(prepared.remoteUrl),
// @effect-diagnostics-next-line catchConditionalRefailToCatchIf:off - The condition also narrows httpsUrl for the fallback closure.
Effect.catch((sshError) =>
httpsUrl === null || !isSshRejection(sshError)
? Effect.fail(sshError)
: runClone(input, prepared.destinationPath, httpsUrl, options).pipe(
Effect.as(redactRemoteUrl(httpsUrl)),
Effect.mapError(
(httpsError) =>
new SourceControlRepositoryError({
operation: "cloneRepository",
provider: sshError.provider,
detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`,
cause: httpsError.cause,
}),
),
),
),
);
return {
cwd: prepared.destinationPath,
remoteUrl,
repository: prepared.repository,
};
});
const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
destinationPath: string,
) {
const normalized = yield* normalizeDestinationPath(destinationPath);
// Only .git-bearing partial clones may be deleted; other files arrived after the empty-directory check.
// Missing destinations are already discarded; other read failures must refuse removal.
const entries = yield* fileSystem.readDirectory(normalized).pipe(
Effect.catchIf(
(cause) => cause.reason._tag === "NotFound",
() => Effect.succeed<ReadonlyArray<string>>([]),
),
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "discardClone",
provider: SourceControlProviderKind.make("unknown"),
detail: "The clone destination could not be inspected.",
cause,
}),
),
);
if (entries.length > 0 && !entries.includes(".git")) {
return yield* new SourceControlRepositoryError({
operation: "discardClone",
provider: SourceControlProviderKind.make("unknown"),
detail: "Destination path contains files that are not from the clone.",
});
}
// Preserve the workspace directory after removing partial contents; retry while interrupted git closes files.
yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "discardClone",
provider: SourceControlProviderKind.make("unknown"),
detail: "The partial clone could not be removed.",
cause,
}),
),
);
});
const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
function* (input: SourceControlPublishRepositoryInput) {
const providerKind = yield* ensureConcreteProvider({
operation: "publishRepository",
provider: input.provider,
});
const provider = yield* providers.get(providerKind);
const urls = yield* provider.createRepository({
cwd: input.cwd,
repository: input.repository.trim(),
visibility: input.visibility,
});
const remoteUrl = selectRemoteUrl(urls, input.protocol);
const remoteName = yield* git.ensureRemote({
cwd: input.cwd,
preferredName: input.remoteName?.trim() || "origin",
url: remoteUrl,
});
// Empty repos cannot push HEAD; report partial success because the remote already exists.
const hasCommits = yield* git
.execute({
operation: "SourceControlRepositoryService.publishRepository.headCheck",
cwd: input.cwd,
args: ["rev-parse", "--verify", "HEAD"],
})
.pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
);
if (!hasCommits) {
const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
return {
repository: toRepositoryInfo(providerKind, urls),
remoteName,
remoteUrl,
branch: details?.branch ?? "main",
status: "remote_added" as const,
};
}
const push = (pushUrl: string) =>
git.pushCurrentBranch(input.cwd, null, { remoteName }).pipe(
Effect.map((result) => ({ branch: result.branch, remoteUrl: pushUrl })),
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "publishRepository",
provider: providerKind,
detail: publishPushFailureDetail({
urls,
remoteName,
remoteUrl: pushUrl,
reason: cause.reason,
}),
cause,
}),
),
);
// Like clone, an auto-selected SSH remote switches to HTTPS when SSH is refused;
// otherwise the remote keeps failing every later fetch and push.
const canSwitchToHttps = input.protocol !== "ssh" && remoteUrl === urls.sshUrl;
const pushed = yield* push(remoteUrl).pipe(
Effect.catchIf(
(error) => canSwitchToHttps && isSshRejection(error),
(sshError) =>
git
.execute({
operation: "SourceControlRepositoryService.publishRepository.switchToHttps",
cwd: input.cwd,
args: ["remote", "set-url", remoteName, urls.url],
})
.pipe(
Effect.mapError(() => sshError),
Effect.andThen(push(urls.url)),
),
),
);
return {
repository: toRepositoryInfo(providerKind, urls),
remoteName,
remoteUrl: pushed.remoteUrl,
branch: pushed.branch,
status: "pushed" as const,
};
},
);
// Forwarders retain the underlying operation spans.
return SourceControlRepositoryService.of({
lookupRepository: Effect.fnUntraced(function* (input) {
return yield* lookupRepository(input).pipe(
mapRepositoryError("lookupRepository", input.provider),
);
}),
prepareClone: Effect.fnUntraced(function* (input) {
return yield* prepareClone(input).pipe(
mapRepositoryError(
"cloneRepository",
input.provider ?? SourceControlProviderKind.make("unknown"),
),
);
}),
cloneRepository: Effect.fnUntraced(function* (input, options) {
return yield* cloneRepository(input, options).pipe(
mapRepositoryError(
"cloneRepository",
input.provider ?? SourceControlProviderKind.make("unknown"),
),
);
}),
discardClone: Effect.fnUntraced(function* (destinationPath) {
return yield* discardClone(destinationPath).pipe(
mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")),
);
}),
publishRepository: Effect.fnUntraced(function* (input) {
return yield* publishRepository(input).pipe(
mapRepositoryError("publishRepository", input.provider),
);
}),
});
});
export const layer = Layer.effect(SourceControlRepositoryService, make);