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

SourceControlRepositoryService.test.ts

735 lines26.6 KB

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