Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as NodePath from "@effect/platform-node/NodePath";
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { assert, it } from "@effect/vitest";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Path from "effect/Path";
11import * as Layer from "effect/Layer";
12import * as PlatformError from "effect/PlatformError";
13import * as Queue from "effect/Queue";
14import { ChildProcessSpawner } from "effect/process";
15import * as TestClock from "effect/testing/TestClock";
16
17import {
18 GitCommandError,
19 SourceControlProviderError,
20 type SourceControlCloneRepositoryInput,
21} from "@t3tools/contracts";
22
23import * as ServerConfig from "../config.ts";
24import type { GitCloneProgressLine } from "../project/gitCloneProgress.ts";
25import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
26import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
27import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
28import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts";
29
30const CLONE_URLS = {
31 nameWithOwner: "octocat/t3code",
32 url: "https://github.com/octocat/t3code",
33 sshUrl: "git@github.com:octocat/t3code.git",
34};
35
36function makeProvider(
37 overrides: Partial<SourceControlProvider.SourceControlProvider["Service"]> = {},
38): SourceControlProvider.SourceControlProvider["Service"] {
39 const unsupported = (operation: string) =>
40 Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
41 never,
42 SourceControlProviderError
43 >;
44
45 return {
46 kind: SourceControlProviderKind.make("github"),
47 listChangeRequests: () => unsupported("listChangeRequests"),
48 getChangeRequest: () => unsupported("getChangeRequest"),
49 createChangeRequest: () => unsupported("createChangeRequest"),
50 getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
51 createRepository: () => Effect.succeed(CLONE_URLS),
52 getDefaultBranch: () => Effect.succeed(null),
53 checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
54 ...overrides,
55 };
56}
57
58function processOutput(): GitVcsDriver.ExecuteGitResult {
59 return {
60 exitCode: ChildProcessSpawner.ExitCode(0),
61 stdout: "",
62 stderr: "",
63 stdoutTruncated: false,
64 stderrTruncated: false,
65 };
66}
67
68function layer(input: {
69 readonly provider?: SourceControlProvider.SourceControlProvider["Service"];
70 readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
71 readonly fileSystem?: FileSystem.FileSystem;
72}) {
73 const layerService = SourceControlRepositoryService.layer.pipe(
74 Layer.provide(
75 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
76 resolveLink: () => undefined,
77 get: () => Effect.succeed(input.provider ?? makeProvider()),
78 }),
79 ),
80 Layer.provide(
81 Layer.mock(GitVcsDriver.GitVcsDriver)({
82 execute: () => Effect.succeed(processOutput()),
83 invalidateRefs: () => Effect.void,
84 ensureRemote: () => Effect.succeed("origin"),
85 pushCurrentBranch: () =>
86 Effect.succeed({
87 status: "pushed" as const,
88 branch: "feature/remote-v1",
89 upstreamBranch: "origin/feature/remote-v1",
90 setUpstream: true,
91 }),
92 ...input.git,
93 }),
94 ),
95 Layer.provide(
96 ServerConfig.layerTest(
97 process.cwd(),
98 input.fileSystem ? "/tmp/t3-source-control-repos" : { prefix: "t3-source-control-repos-" },
99 ),
100 ),
101 );
102
103 return input.fileSystem
104 ? layerService.pipe(
105 Layer.provide(Layer.succeed(FileSystem.FileSystem, input.fileSystem)),
106 Layer.provideMerge(NodePath.layer),
107 )
108 : layerService.pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
109}
110
111const lookupFailingWith = (cause: unknown, detail: string) =>
112 Effect.gen(function* () {
113 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
114 return yield* service
115 .lookupRepository({ provider: SourceControlProviderKind.make("bitbucket"), repository: "x" })
116 .pipe(Effect.flip);
117 }).pipe(
118 Effect.provide(
119 layer({
120 provider: makeProvider({
121 getRepositoryCloneUrls: (input) =>
122 Effect.fail(
123 new SourceControlProviderError({
124 provider: SourceControlProviderKind.make("bitbucket"),
125 operation: "getRepositoryCloneUrls",
126 cwd: input.cwd,
127 detail,
128 cause,
129 }),
130 ),
131 }),
132 }),
133 ),
134 );
135
136it.effect("tells the user a host's fixed explanation of a failed repository lookup", () =>
137 Effect.gen(function* () {
138 const error = yield* lookupFailingWith(
139 { userFacingDetail: "Repositories are named workspace/repository." },
140 "Repositories are named workspace/repository.",
141 );
142 assert.strictEqual(error.detail, "Repositories are named workspace/repository.");
143 }),
144);
145
146it.effect("keeps a host's raw response text out of a failed repository lookup", () =>
147 Effect.gen(function* () {
148 const error = yield* lookupFailingWith(
149 new Error("upstream"),
150 "<html>internal token=abc</html>",
151 );
152 assert.strictEqual(error.detail, "The source control operation could not be completed.");
153 }),
154);
155
156it.effect("clones a looked-up repository after creating missing parent directories", () =>
157 Effect.gen(function* () {
158 const fs = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
161 prefix: "t3-source-control-clone-parent-",
162 });
163 const parent = path.join(temporaryDirectory, "missing", "nested");
164 const destinationPath = path.join(parent, "t3code");
165 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
166
167 yield* Effect.gen(function* () {
168 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
169 const result = yield* service.cloneRepository({
170 provider: SourceControlProviderKind.make("github"),
171 repository: "octocat/t3code",
172 destinationPath,
173 protocol: "https",
174 });
175
176 assert.deepStrictEqual(result, {
177 cwd: destinationPath,
178 remoteUrl: CLONE_URLS.url,
179 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
180 });
181 assert.deepStrictEqual(cloneCalls, [
182 {
183 cwd: parent,
184 args: ["clone", "--progress", "--", CLONE_URLS.url, "t3code"],
185 },
186 ]);
187 }).pipe(
188 Effect.provide(
189 layer({
190 git: {
191 execute: (input) =>
192 Effect.gen(function* () {
193 assert.isTrue(yield* fs.exists(parent).pipe(Effect.orDie));
194 cloneCalls.push({ cwd: input.cwd, args: input.args });
195 return processOutput();
196 }),
197 },
198 }),
199 ),
200 );
201 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
202);
203
204it.effect.each(["--bare", "source.git"])(
205 "clones a local repository named %s as a working tree",
206 (repositoryName) =>
207 Effect.gen(function* () {
208 const fs = yield* FileSystem.FileSystem;
209 const path = yield* Path.Path;
210 const git = yield* GitVcsDriver.GitVcsDriver;
211 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-options-" });
212 yield* git.execute({
213 operation: "test.init",
214 cwd: parent,
215 args: ["init", "--bare", path.join(parent, repositoryName)],
216 });
217 const destinationPath = path.join(parent, "checkout");
218 yield* Effect.gen(function* () {
219 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
220 const result = yield* service.cloneRepository({
221 remoteUrl: repositoryName,
222 destinationPath,
223 });
224 assert.strictEqual(result.cwd, destinationPath);
225 assert.isTrue(yield* fs.exists(path.join(destinationPath, ".git")));
226 }).pipe(Effect.provide(layer({ git })));
227 }).pipe(
228 Effect.provide(
229 GitVcsDriver.layer.pipe(
230 Layer.provide(
231 ServerConfig.layerTest(process.cwd(), {
232 prefix: "t3-clone-options-config-",
233 }),
234 ),
235 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
236 ),
237 ),
238 ),
239);
240
241it.effect.each([
242 { readsWhen: "before git creates the repository", readBeforeInit: true },
243 { readsWhen: "while HEAD is unborn", readBeforeInit: false },
244])("lists the cloned branches after a ref list was read $readsWhen", ({ readBeforeInit }) =>
245 Effect.gen(function* () {
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const git = yield* GitVcsDriver.GitVcsDriver;
249 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-refs-" });
250 const source = path.join(parent, "source");
251 const destinationPath = path.join(parent, "checkout");
252 const run = (cwd: string, args: ReadonlyArray<string>) =>
253 git.execute({ operation: "test.git", cwd, args });
254 yield* run(parent, ["init", "--initial-branch=staging", source]);
255 yield* run(source, [
256 "-c",
257 "user.name=Test",
258 "-c",
259 "user.email=test@example.com",
260 "commit",
261 "--allow-empty",
262 "-m",
263 "init",
264 ]);
265 const refNames = git
266 .listRefs({ cwd: destinationPath })
267 .pipe(Effect.map((result) => result.refs.map((ref) => ref.name)));
268 let duringClone: ReadonlyArray<string> | null = null;
269 // Stands in for git clone so the read lands at a chosen point inside it.
270 const cloneInTwoSteps = Effect.gen(function* () {
271 yield* fs.makeDirectory(destinationPath).pipe(Effect.orDie);
272 if (readBeforeInit) duringClone = yield* refNames;
273 yield* run(parent, ["init", "--initial-branch=staging", destinationPath]);
274 if (!readBeforeInit) duringClone = yield* refNames;
275 return yield* run(destinationPath, ["pull", source, "staging"]);
276 });
277 yield* Effect.gen(function* () {
278 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
279 yield* service.cloneRepository({ remoteUrl: source, destinationPath });
280 }).pipe(
281 Effect.provide(
282 layer({
283 git: {
284 ...git,
285 execute: (input) => (input.args[0] === "clone" ? cloneInTwoSteps : git.execute(input)),
286 },
287 }),
288 ),
289 );
290
291 assert.deepStrictEqual(duringClone, []);
292 assert.deepStrictEqual(yield* refNames, ["staging"]);
293 }).pipe(
294 Effect.provide(
295 GitVcsDriver.layer.pipe(
296 Layer.provide(
297 ServerConfig.layerTest(process.cwd(), {
298 prefix: "t3-clone-refs-config-",
299 }),
300 ),
301 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
302 ),
303 ),
304 ),
305);
306
307it.effect("reports clone progress from git's stderr and keeps its error text on failure", () =>
308 Effect.gen(function* () {
309 const fs = yield* FileSystem.FileSystem;
310 const path = yield* Path.Path;
311 const parent = yield* fs.makeTempDirectoryScoped({
312 prefix: "t3-source-control-clone-progress-",
313 });
314 const destinationPath = path.join(parent, "t3code");
315 const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
316
317 const stderrLines = [
318 "Cloning into 't3code'...",
319 "remote: Enumerating objects: 10, done.",
320 "Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
321 "Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
322 "fatal: early EOF",
323 "fatal: unable to access 'https://user:s3c@ret@github.com/octocat/t3code.git/': could not resolve host",
324 ];
325 const error = yield* Effect.gen(function* () {
326 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
327 return yield* Effect.flip(
328 service.cloneRepository(
329 { remoteUrl: CLONE_URLS.sshUrl, destinationPath },
330 { onProgress: (line) => Effect.sync(() => void progress.push(line)) },
331 ),
332 );
333 }).pipe(
334 Effect.provide(
335 layer({
336 git: {
337 execute: (input) =>
338 Effect.gen(function* () {
339 for (const line of stderrLines) {
340 yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
341 }
342 return yield* new GitCommandError({
343 operation: input.operation,
344 command: "git",
345 cwd: input.cwd,
346 detail: "Git command exited with a non-zero status.",
347 exitCode: 128,
348 });
349 }),
350 },
351 }),
352 ),
353 );
354
355 assert.deepStrictEqual(progress, [
356 { stage: "counting", percent: null, detail: null },
357 { stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
358 { stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
359 ]);
360 assert.strictEqual(
361 error.detail,
362 "fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
363 );
364 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
365);
366
367it.effect("reports a Git LFS download as progress only while its partial files change", () =>
368 Effect.gen(function* () {
369 const fs = yield* FileSystem.FileSystem;
370 const path = yield* Path.Path;
371 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-clone-lfs-" });
372 const destinationPath = path.join(parent, "t3code");
373 const incomplete = path.join(destinationPath, ".git", "lfs", "incomplete");
374 const progress = yield* Queue.unbounded<GitCloneProgressLine>();
375 const firstDownloading = yield* Deferred.make<void>();
376 const firstLanded = yield* Deferred.make<void>();
377 const secondDownloading = yield* Deferred.make<void>();
378 const secondLanded = yield* Deferred.make<void>();
379 const filtering = "Filtering content: 50% (1/2), 1.50 MiB | 1.00 MiB/s";
380
381 const clone = yield* Effect.gen(function* () {
382 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
383 return yield* service.cloneRepository(
384 { remoteUrl: CLONE_URLS.url, destinationPath },
385 { onProgress: (line) => Queue.offer(progress, line), timeoutMs: null },
386 );
387 }).pipe(
388 Effect.provide(
389 layer({
390 git: {
391 execute: (input) =>
392 Effect.gen(function* () {
393 yield* (
394 input.progress?.onStderrLine?.("Updating files: 100% (3/3), done.") ?? Effect.void
395 );
396 yield* fs.makeDirectory(incomplete, { recursive: true });
397 yield* fs.writeFile(path.join(incomplete, "a.part"), new Uint8Array(1536 * 1024));
398 yield* Deferred.succeed(firstDownloading, undefined);
399 yield* Deferred.await(firstLanded);
400 yield* fs.remove(path.join(incomplete, "a.part"));
401 yield* fs.writeFile(path.join(incomplete, "b.part"), new Uint8Array(512 * 1024));
402 yield* input.progress?.onStderrLine?.(filtering) ?? Effect.void;
403 yield* Deferred.succeed(secondDownloading, undefined);
404 yield* Deferred.await(secondLanded);
405 yield* fs.remove(path.join(incomplete, "b.part"));
406 return processOutput();
407 }).pipe(Effect.orDie),
408 },
409 }),
410 ),
411 Effect.forkChild,
412 );
413
414 yield* Deferred.await(firstDownloading);
415 yield* TestClock.adjust("2 seconds");
416 assert.deepStrictEqual(yield* Queue.takeN(progress, 2), [
417 { stage: "checkout", percent: 100, detail: null },
418 {
419 stage: "checkout",
420 percent: null,
421 detail: "Downloading Git LFS objects: 1.5 MiB in progress",
422 },
423 ]);
424
425 yield* Deferred.succeed(firstLanded, undefined);
426 yield* Deferred.await(secondDownloading);
427 yield* TestClock.adjust("2 seconds");
428 assert.deepStrictEqual(yield* Queue.takeN(progress, 2), [
429 { stage: "checkout", percent: 50, detail: "1.50 MiB | 1.00 MiB/s" },
430 {
431 stage: "checkout",
432 percent: 50,
433 detail: "Downloading Git LFS objects: 0.5 MiB in progress",
434 },
435 ]);
436
437 // The second object stops growing: a transfer that really stalled must stay silent.
438 yield* TestClock.adjust("2 seconds");
439 yield* Deferred.succeed(secondLanded, undefined);
440 yield* Fiber.join(clone);
441 assert.strictEqual(yield* Queue.size(progress), 0);
442 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
443);
444
445it.effect("says a clone that ran out of time timed out, not git's last remote line", () =>
446 Effect.gen(function* () {
447 const fs = yield* FileSystem.FileSystem;
448 const path = yield* Path.Path;
449 const parent = yield* fs.makeTempDirectoryScoped({
450 prefix: "t3-source-control-clone-timeout-",
451 });
452 const started = yield* Deferred.make<void>();
453 const clone = yield* Effect.gen(function* () {
454 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
455 return yield* Effect.flip(
456 service.cloneRepository({
457 remoteUrl: CLONE_URLS.url,
458 destinationPath: path.join(parent, "t3code"),
459 }),
460 );
461 }).pipe(
462 Effect.provide(
463 layer({
464 git: {
465 // Like the real driver: the transfer outlives its deadline and git's last line is
466 // a remote summary.
467 execute: (input) =>
468 Effect.gen(function* () {
469 yield* (
470 input.progress?.onStderrLine?.(
471 "remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0",
472 ) ?? Effect.void
473 );
474 yield* Deferred.succeed(started, undefined);
475 return yield* Effect.never;
476 }).pipe(
477 Effect.timeoutOrElse({
478 duration: input.timeoutMs ?? Infinity,
479 orElse: () =>
480 Effect.fail(
481 new GitCommandError({
482 operation: input.operation,
483 command: "git",
484 cwd: input.cwd,
485 detail: "Git command timed out.",
486 }),
487 ),
488 }),
489 ),
490 },
491 }),
492 ),
493 Effect.forkChild,
494 );
495
496 yield* Deferred.await(started);
497 yield* TestClock.adjust("2 minutes");
498 const error = yield* Fiber.join(clone);
499
500 assert.match(error.detail, /timed out/i);
501 }).pipe(Effect.provide(NodeServices.layer)),
502);
503
504function rejectingSsh(
505 urls: Array<string>,
506 httpsFails: boolean,
507 reason: GitCommandError["reason"] = "authentication_failed",
508) {
509 return {
510 execute: (input: GitVcsDriver.ExecuteGitInput) =>
511 Effect.gen(function* () {
512 const url = input.args.at(-2)!;
513 urls.push(url);
514 if (url.startsWith("https://") && !httpsFails) return processOutput();
515 yield* (
516 input.progress?.onStderrLine?.(
517 url.startsWith("https://")
518 ? "fatal: could not read Username for 'https://github.com': terminal prompts disabled"
519 : "git@github.com: Permission denied (publickey).",
520 ) ?? Effect.void
521 );
522 return yield* new GitCommandError({
523 operation: input.operation,
524 command: "git",
525 cwd: input.cwd,
526 reason,
527 detail: "Git command exited with a non-zero status.",
528 });
529 }),
530 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
531}
532
533const cloneInTemporaryDirectory = (
534 git: Partial<GitVcsDriver.GitVcsDriver["Service"]>,
535 input: Omit<SourceControlCloneRepositoryInput, "destinationPath">,
536) =>
537 Effect.gen(function* () {
538 const fs = yield* FileSystem.FileSystem;
539 const path = yield* Path.Path;
540 const parent = yield* fs
541 .makeTempDirectoryScoped({ prefix: "t3-clone-fallback-" })
542 .pipe(Effect.orDie);
543 return yield* Effect.gen(function* () {
544 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
545 return yield* service.cloneRepository({
546 ...input,
547 destinationPath: path.join(parent, "t3code"),
548 });
549 }).pipe(Effect.provide(layer({ git }).pipe(Layer.orDie)));
550 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
551
552it.effect("retries a clone over HTTPS when the SSH login is refused", () =>
553 Effect.gen(function* () {
554 const urls: Array<string> = [];
555 const result = yield* cloneInTemporaryDirectory(rejectingSsh(urls, false), {
556 remoteUrl: CLONE_URLS.sshUrl,
557 });
558
559 assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl, "https://github.com/octocat/t3code.git"]);
560 assert.strictEqual(result.remoteUrl, "https://github.com/octocat/t3code.git");
561 }),
562);
563
564it.effect("reports both failures when the HTTPS retry fails too", () =>
565 Effect.gen(function* () {
566 const urls: Array<string> = [];
567 const error = yield* Effect.flip(
568 cloneInTemporaryDirectory(rejectingSsh(urls, true), { remoteUrl: CLONE_URLS.sshUrl }),
569 );
570
571 assert.strictEqual(urls.length, 2);
572 assert.strictEqual(
573 error.detail,
574 "git@github.com: Permission denied (publickey). Cloning over HTTPS instead also failed: fatal: could not read Username for 'https://github.com': terminal prompts disabled",
575 );
576 }),
577);
578
579it.effect.each([
580 "git@ssh.dev.azure.com:v3/Fabrikam/Project1/fab_repo",
581 "ssh://user:pa@rt@ssh.dev.azure.com/v3/Fabrikam/Project1/fab_repo",
582 "ssh://us%40er:pa%40ss@ssh.dev.azure.com/v3/Fabrikam/Project1/fab_repo",
583])("retries Azure SSH URL %s using its HTTPS host and repository path", (remoteUrl) =>
584 Effect.gen(function* () {
585 const urls: Array<string> = [];
586 const result = yield* cloneInTemporaryDirectory(rejectingSsh(urls, false), {
587 remoteUrl,
588 });
589
590 assert.deepStrictEqual(urls, [
591 remoteUrl,
592 "https://dev.azure.com/Fabrikam/Project1/_git/fab_repo",
593 ]);
594 assert.strictEqual(result.remoteUrl, "https://dev.azure.com/Fabrikam/Project1/_git/fab_repo");
595 }),
596);
597
598it.effect.each([
599 ["the caller asked for SSH", "ssh", "authentication_failed"],
600 ["git failed for another reason", undefined, "remote_unreachable"],
601] as const)("does not retry over HTTPS when %s", ([, protocol, reason]) =>
602 Effect.gen(function* () {
603 const urls: Array<string> = [];
604 yield* Effect.flip(
605 cloneInTemporaryDirectory(rejectingSsh(urls, false, reason), {
606 remoteUrl: CLONE_URLS.sshUrl,
607 ...(protocol === undefined ? {} : { protocol }),
608 }),
609 );
610
611 assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl]);
612 }),
613);
614
615function rejectingHttps(
616 calls: Array<{ readonly url: string; readonly env: NodeJS.ProcessEnv | undefined }>,
617 sshFails: boolean,
618 reason: GitCommandError["reason"] = "authentication_failed",
619) {
620 return {
621 execute: (input: GitVcsDriver.ExecuteGitInput) =>
622 Effect.gen(function* () {
623 const url = input.args.at(-2)!;
624 calls.push({ url, env: input.env });
625 if (!url.startsWith("http") && !sshFails) return processOutput();
626 yield* (
627 input.progress?.onStderrLine?.(
628 url.startsWith("http")
629 ? "fatal: could not read Username for 'https://github.com': terminal prompts disabled"
630 : "git@github.com: Permission denied (publickey).",
631 ) ?? Effect.void
632 );
633 return yield* new GitCommandError({
634 operation: input.operation,
635 command: "git",
636 cwd: input.cwd,
637 reason,
638 detail: "Git command exited with a non-zero status.",
639 });
640 }),
641 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
642}
643
644it.effect("retries a GitHub HTTPS clone over SSH when HTTPS authentication is refused", () =>
645 Effect.gen(function* () {
646 const calls: Array<{ readonly url: string; readonly env: NodeJS.ProcessEnv | undefined }> = [];
647 const result = yield* cloneInTemporaryDirectory(rejectingHttps(calls, false), {
648 remoteUrl: "https://github.com/octocat/t3code.git",
649 });
650
651 assert.deepStrictEqual(
652 calls.map((call) => call.url),
653 ["https://github.com/octocat/t3code.git", "git@github.com:octocat/t3code.git"],
654 );
655 assert.strictEqual(calls[1]?.env?.SSH_ASKPASS, "");
656 assert.strictEqual(calls[1]?.env?.SSH_ASKPASS_REQUIRE, "never");
657 assert.strictEqual(result.remoteUrl, "git@github.com:octocat/t3code.git");
658 }),
659);
660
661it.effect("reports both failures and setup guidance when the GitHub SSH retry fails too", () =>
662 Effect.gen(function* () {
663 const calls: Array<{ readonly url: string; readonly env: NodeJS.ProcessEnv | undefined }> = [];
664 const error = yield* Effect.flip(
665 cloneInTemporaryDirectory(rejectingHttps(calls, true), {
666 remoteUrl: "https://github.com/octocat/t3code.git",
667 }),
668 );
669
670 assert.strictEqual(calls.length, 2);
671 assert.strictEqual(
672 error.detail,
673 "fatal: could not read Username for 'https://github.com': terminal prompts disabled. Cloning over SSH instead also failed: git@github.com: Permission denied (publickey). Run `gh auth setup-git` on the server or add an SSH key to your GitHub account, then retry.",
674 );
675 }),
676);
677
678it.effect.each([
679 [
680 "the caller asked for HTTPS",
681 "https://github.com/octocat/t3code.git",
682 undefined,
683 "https",
684 "authentication_failed",
685 ],
686 [
687 "git failed for another reason",
688 "https://github.com/octocat/t3code.git",
689 undefined,
690 undefined,
691 "remote_unreachable",
692 ],
693 [
694 "the remote is not GitHub",
695 "https://gitlab.com/octocat/t3code.git",
696 SourceControlProviderKind.make("github"),
697 undefined,
698 "authentication_failed",
699 ],
700 [
701 "the URL carries embedded credentials",
702 "https://token@github.com/octocat/t3code.git",
703 undefined,
704 undefined,
705 "authentication_failed",
706 ],
707 [
708 "the URL uses plain HTTP",
709 "http://github.com/octocat/t3code.git",
710 undefined,
711 undefined,
712 "authentication_failed",
713 ],
714] as const)("does not retry over SSH when %s", ([, remoteUrl, provider, protocol, reason]) =>
715 Effect.gen(function* () {
716 const calls: Array<{ readonly url: string; readonly env: NodeJS.ProcessEnv | undefined }> = [];
717 yield* Effect.flip(
718 cloneInTemporaryDirectory(rejectingHttps(calls, false, reason), {
719 remoteUrl,
720 ...(provider === undefined ? {} : { provider }),
721 ...(protocol === undefined ? {} : { protocol }),
722 }),
723 );
724
725 assert.deepStrictEqual(
726 calls.map((call) => call.url),
727 [remoteUrl],
728 );
729 }),
730);
731
732it.effect.each([
733 ["a plain token", "s3cret"],
734 ["a token with an apostrophe", "s3'cret"],
735 ["a token with a double quote", 's3"cret'],
736 ["a host-only token with an at sign", "abc@secret"],
737 ["an unquoted token with an apostrophe", "s3'cret", true],
738 ["an unquoted token with a double quote", 's3"cret', true],
739 ["an unquoted URL with an apostrophe in its path", "path-token", true],
740] as const)("keeps %s in the query out of a failed clone's error text", ([, token, unquoted]) =>
741 Effect.gen(function* () {
742 const remote =
743 token === "abc@secret"
744 ? "https://github.com"
745 : token === "path-token"
746 ? "https://github.com/octocat/t3code's.git"
747 : "https://github.com/octocat/t3code.git";
748 const error = yield* Effect.flip(
749 cloneInTemporaryDirectory(
750 {
751 execute: (input) =>
752 Effect.gen(function* () {
753 const cloneUrl = input.args.at(-2)!;
754 // Git treats @ in a pathless URL's query as userinfo, losing the query delimiter.
755 const diagnosticUrl =
756 cloneUrl === "https://github.com?access_token=abc@secret"
757 ? "https://secret"
758 : cloneUrl;
759 yield* (
760 input.progress?.onStderrLine?.(
761 unquoted
762 ? `fatal: ${diagnosticUrl}/info/refs not valid: is this a git repository?`
763 : `fatal: unable to access '${diagnosticUrl}/': Could not resolve host: github.com`,
764 ) ?? Effect.void
765 );
766 return yield* new GitCommandError({
767 operation: input.operation,
768 command: "git",
769 cwd: input.cwd,
770 detail: "Git command exited with a non-zero status.",
771 exitCode: 128,
772 });
773 }),
774 },
775 { remoteUrl: `${remote}?access_token=${token}` },
776 ),
777 );
778
779 assert.strictEqual(
780 error.detail,
781 unquoted
782 ? `fatal: ${remote} not valid: is this a git repository?`
783 : `fatal: unable to access '${remote}${token === "abc@secret" ? "/" : ""}': Could not resolve host: github.com`,
784 );
785 }),
786);
787
788it.effect("strips embedded credentials from the remote URL it reports", () =>
789 Effect.gen(function* () {
790 const fs = yield* FileSystem.FileSystem;
791 const path = yield* Path.Path;
792 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
793 const destinationPath = path.join(parent, "t3code");
794 const cloneArgs: Array<ReadonlyArray<string>> = [];
795 const result = yield* Effect.gen(function* () {
796 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
797 return yield* service.prepareClone({
798 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
799 destinationPath,
800 });
801 }).pipe(
802 Effect.provide(
803 layer({
804 git: {
805 execute: (input) =>
806 Effect.sync(() => {
807 cloneArgs.push(input.args);
808 return processOutput();
809 }),
810 },
811 }),
812 ),
813 );
814 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
815 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
816 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
817);
818
819it.effect("discards only a directory git wrote to", () =>
820 Effect.gen(function* () {
821 const fs = yield* FileSystem.FileSystem;
822 const path = yield* Path.Path;
823 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
824 const partial = path.join(parent, "partial");
825 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
826 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
827 const foreign = path.join(parent, "foreign");
828 yield* fs.makeDirectory(foreign);
829 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
830
831 const replaced = path.join(parent, "replaced");
832 yield* fs.writeFileString(replaced, "not a directory");
833
834 yield* Effect.gen(function* () {
835 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
836 yield* service.discardClone(partial);
837 const error = yield* Effect.flip(service.discardClone(foreign));
838 assert.include(error.detail, "not from the clone");
839 const replacedError = yield* Effect.flip(service.discardClone(replaced));
840 assert.include(replacedError.detail, "could not be inspected");
841 yield* service.discardClone(path.join(parent, "missing"));
842 }).pipe(Effect.provide(layer({})));
843
844 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
845 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
846 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
847 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
848);
849
850it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
851 Effect.gen(function* () {
852 const fs = yield* FileSystem.FileSystem;
853 const path = yield* Path.Path;
854 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
855 yield* Effect.gen(function* () {
856 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
857 const query = yield* service.prepareClone({
858 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
859 destinationPath: path.join(parent, "a"),
860 });
861 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
862 const nested = yield* service.prepareClone({
863 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
864 destinationPath: path.join(parent, "b"),
865 });
866 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
867 }).pipe(Effect.provide(layer({})));
868 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
869);
870
871it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
872 const fileSystemCause = PlatformError.systemError({
873 _tag: "PermissionDenied",
874 module: "FileSystem",
875 method: "exists",
876 pathOrDescriptor: "/restricted/t3code",
877 });
878
879 return Effect.gen(function* () {
880 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
881 const error = yield* Effect.flip(
882 service.cloneRepository({
883 remoteUrl: CLONE_URLS.sshUrl,
884 destinationPath: "/restricted/t3code",
885 }),
886 );
887
888 assert.strictEqual(error.provider, "unknown");
889 assert.strictEqual(error.operation, "cloneRepository");
890 assert.strictEqual(error.cause, fileSystemCause);
891 }).pipe(
892 Effect.provide(
893 layer({
894 fileSystem: FileSystem.makeNoop({
895 exists: () => Effect.fail(fileSystemCause),
896 makeDirectory: () => Effect.void,
897 }),
898 }),
899 ),
900 );
901});
902
903it.effect("publishes to the remote name returned by ensureRemote", () => {
904 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
905
906 return Effect.gen(function* () {
907 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
908 const result = yield* service.publishRepository({
909 cwd: "/workspace",
910 provider: SourceControlProviderKind.make("github"),
911 repository: "octocat/t3code",
912 visibility: "private",
913 remoteName: "origin",
914 protocol: "ssh",
915 });
916
917 assert.equal(result.remoteName, "origin-1");
918 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
919 }).pipe(
920 Effect.provide(
921 layer({
922 git: {
923 ensureRemote: () => Effect.succeed("origin-1"),
924 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
925 Effect.sync(() => {
926 pushCalls.push({ cwd, remoteName: options?.remoteName });
927 return {
928 status: "pushed" as const,
929 branch: "feature/remote-v1",
930 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
931 setUpstream: true,
932 };
933 }),
934 },
935 }),
936 ),
937 );
938});
939
940function failingPush(reason?: GitCommandError["reason"]) {
941 return {
942 pushCurrentBranch: (cwd: string) =>
943 Effect.fail(
944 new GitCommandError({
945 operation: "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
946 command: "git",
947 cwd,
948 ...(reason === undefined ? {} : { reason }),
949 detail: "Git command exited with a non-zero status.",
950 }),
951 ),
952 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
953}
954
955it.effect("explains a rejected SSH push after creating the repository", () =>
956 Effect.gen(function* () {
957 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
958 const error = yield* Effect.flip(
959 service.publishRepository({
960 cwd: "/workspace",
961 provider: SourceControlProviderKind.make("github"),
962 repository: "octocat/t3code",
963 visibility: "private",
964 protocol: "ssh",
965 }),
966 );
967
968 assert.strictEqual(error.operation, "publishRepository");
969 assert.strictEqual(
970 error.detail,
971 'Created octocat/t3code and added it as remote "origin", but the push failed because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "git remote set-url origin https://github.com/octocat/t3code", then push again.',
972 );
973 assert.instanceOf(error.cause, GitCommandError);
974 }).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))),
975);
976
977// regression: an auto-selected SSH remote kept failing every later fetch after a refused push
978it.effect("switches an auto-selected remote to HTTPS when the SSH push is refused", () => {
979 const gitArgs: Array<ReadonlyArray<string>> = [];
980 let pushAttempts = 0;
981 return Effect.gen(function* () {
982 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
983 const result = yield* service.publishRepository({
984 cwd: "/workspace",
985 provider: SourceControlProviderKind.make("github"),
986 repository: "octocat/t3code",
987 visibility: "private",
988 });
989
990 assert.strictEqual(result.status, "pushed");
991 assert.strictEqual(result.remoteUrl, CLONE_URLS.url);
992 assert.strictEqual(pushAttempts, 2);
993 assert.deepStrictEqual(gitArgs, [
994 ["rev-parse", "--verify", "HEAD"],
995 ["remote", "set-url", "origin", CLONE_URLS.url],
996 ]);
997 }).pipe(
998 Effect.provide(
999 layer({
1000 git: {
1001 execute: (input) =>
1002 Effect.sync(() => {
1003 gitArgs.push(input.args);
1004 return processOutput();
1005 }),
1006 pushCurrentBranch: (cwd) => {
1007 pushAttempts += 1;
1008 return pushAttempts === 1
1009 ? failingPush("authentication_failed").pushCurrentBranch(cwd)
1010 : Effect.succeed({
1011 status: "pushed" as const,
1012 branch: "main",
1013 upstreamBranch: "origin/main",
1014 setUpstream: true,
1015 });
1016 },
1017 },
1018 }),
1019 ),
1020 );
1021});
1022
1023// regression: #19219 publishing did not explain why the first push failed
1024it.effect("says the repository exists when an unclassified publish push fails", () =>
1025 Effect.gen(function* () {
1026 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
1027 const error = yield* Effect.flip(
1028 service.publishRepository({
1029 cwd: "/workspace",
1030 provider: SourceControlProviderKind.make("github"),
1031 repository: "octocat/t3code",
1032 visibility: "private",
1033 protocol: "https",
1034 }),
1035 );
1036
1037 assert.strictEqual(
1038 error.detail,
1039 'Created octocat/t3code and added it as remote "origin", but the push failed. Fix the problem, then push again.',
1040 );
1041 }).pipe(Effect.provide(layer({ git: failingPush() }))),
1042);
1043
1044it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
1045 let pushCalls = 0;
1046 return Effect.gen(function* () {
1047 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
1048 const result = yield* service.publishRepository({
1049 cwd: "/workspace",
1050 provider: SourceControlProviderKind.make("github"),
1051 repository: "octocat/t3code",
1052 visibility: "private",
1053 remoteName: "origin",
1054 protocol: "ssh",
1055 });
1056
1057 assert.deepStrictEqual(result, {
1058 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
1059 remoteName: "origin",
1060 remoteUrl: CLONE_URLS.sshUrl,
1061 branch: "main",
1062 status: "remote_added",
1063 });
1064 assert.strictEqual(pushCalls, 0);
1065 }).pipe(
1066 Effect.provide(
1067 layer({
1068 git: {
1069 execute: (input) =>
1070 input.args[0] === "rev-parse"
1071 ? Effect.fail(
1072 new GitCommandError({
1073 operation: input.operation,
1074 command: "git rev-parse --verify HEAD",
1075 cwd: input.cwd,
1076 detail: "fatal: Needed a single revision",
1077 }),
1078 )
1079 : Effect.succeed(processOutput()),
1080 statusDetails: () =>
1081 Effect.succeed({
1082 isRepo: true,
1083 hasOriginRemote: true,
1084 isDefaultBranch: true,
1085 branch: "main",
1086 upstreamRef: null,
1087 hasWorkingTreeChanges: false,
1088 workingTree: { files: [], insertions: 0, deletions: 0 },
1089 hasUpstream: false,
1090 aheadCount: 0,
1091 behindCount: 0,
1092 aheadOfDefaultCount: 0,
1093 }),
1094 pushCurrentBranch: () =>
1095 Effect.sync(() => {
1096 pushCalls += 1;
1097 return {
1098 status: "pushed" as const,
1099 branch: "main",
1100 upstreamBranch: "origin/main",
1101 setUpstream: true,
1102 };
1103 }),
1104 },
1105 }),
1106 ),
1107 );
1108});