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

SourceControlRepositoryService.test.ts

911 lines33.1 KB

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