Open History to see the last commit
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 };
50}
51
52function processOutput(): GitVcsDriver.ExecuteGitResult {
53 return {
54 exitCode: ChildProcessSpawner.ExitCode(0),
55 stdout: "",
56 stderr: "",
57 stdoutTruncated: false,
58 stderrTruncated: false,
59 };
60}
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));
102}
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"]>;
321}
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 ["the caller asked for SSH", "ssh", "authentication_failed"],
371 ["git failed for another reason", undefined, "remote_unreachable"],
372] as const)("does not retry over HTTPS when %s", ([, protocol, reason]) =>
373 Effect.gen(function* () {
374 const urls: Array<string> = [];
375 yield* Effect.flip(
376 cloneInTemporaryDirectory(rejectingSsh(urls, false, reason), {
377 remoteUrl: CLONE_URLS.sshUrl,
378 ...(protocol === undefined ? {} : { protocol }),
379 }),
380 );
381
382 assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl]);
383 }),
384);
385
386it.effect.each([
387 ["a plain token", "s3cret"],
388 ["a token with an apostrophe", "s3'cret"],
389 ["a token with a double quote", 's3"cret'],
390 ["a host-only token with an at sign", "abc@secret"],
391 ["an unquoted token with an apostrophe", "s3'cret", true],
392 ["an unquoted token with a double quote", 's3"cret', true],
393 ["an unquoted URL with an apostrophe in its path", "path-token", true],
394] as const)("keeps %s in the query out of a failed clone's error text", ([, token, unquoted]) =>
395 Effect.gen(function* () {
396 const remote =
397 token === "abc@secret"
398 ? "https://github.com"
399 : token === "path-token"
400 ? "https://github.com/octocat/t3code's.git"
401 : "https://github.com/octocat/t3code.git";
402 const error = yield* Effect.flip(
403 cloneInTemporaryDirectory(
404 {
405 execute: (input) =>
406 Effect.gen(function* () {
407 const cloneUrl = input.args.at(-2)!;
408 // Git treats @ in a pathless URL's query as userinfo, losing the query delimiter.
409 const diagnosticUrl =
410 cloneUrl === "https://github.com?access_token=abc@secret"
411 ? "https://secret"
412 : cloneUrl;
413 yield* (
414 input.progress?.onStderrLine?.(
415 unquoted
416 ? `fatal: ${diagnosticUrl}/info/refs not valid: is this a git repository?`
417 : `fatal: unable to access '${diagnosticUrl}/': Could not resolve host: github.com`,
418 ) ?? Effect.void
419 );
420 return yield* new GitCommandError({
421 operation: input.operation,
422 command: "git",
423 cwd: input.cwd,
424 detail: "Git command exited with a non-zero status.",
425 exitCode: 128,
426 });
427 }),
428 },
429 { remoteUrl: `${remote}?access_token=${token}` },
430 ),
431 );
432
433 assert.strictEqual(
434 error.detail,
435 unquoted
436 ? `fatal: ${remote} not valid: is this a git repository?`
437 : `fatal: unable to access '${remote}${token === "abc@secret" ? "/" : ""}': Could not resolve host: github.com`,
438 );
439 }),
440);
441
442it.effect("strips embedded credentials from the remote URL it reports", () =>
443 Effect.gen(function* () {
444 const fs = yield* FileSystem.FileSystem;
445 const path = yield* Path.Path;
446 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
447 const destinationPath = path.join(parent, "t3code");
448 const cloneArgs: Array<ReadonlyArray<string>> = [];
449 const result = yield* Effect.gen(function* () {
450 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
451 return yield* service.prepareClone({
452 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
453 destinationPath,
454 });
455 }).pipe(
456 Effect.provide(
457 layer({
458 git: {
459 execute: (input) =>
460 Effect.sync(() => {
461 cloneArgs.push(input.args);
462 return processOutput();
463 }),
464 },
465 }),
466 ),
467 );
468 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
469 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
470 }).pipe(Effect.provide(NodeServices.layer)),
471);
472
473it.effect("discards only a directory git wrote to", () =>
474 Effect.gen(function* () {
475 const fs = yield* FileSystem.FileSystem;
476 const path = yield* Path.Path;
477 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
478 const partial = path.join(parent, "partial");
479 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
480 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
481 const foreign = path.join(parent, "foreign");
482 yield* fs.makeDirectory(foreign);
483 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
484
485 const replaced = path.join(parent, "replaced");
486 yield* fs.writeFileString(replaced, "not a directory");
487
488 yield* Effect.gen(function* () {
489 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
490 yield* service.discardClone(partial);
491 const error = yield* Effect.flip(service.discardClone(foreign));
492 assert.include(error.detail, "not from the clone");
493 const replacedError = yield* Effect.flip(service.discardClone(replaced));
494 assert.include(replacedError.detail, "could not be inspected");
495 yield* service.discardClone(path.join(parent, "missing"));
496 }).pipe(Effect.provide(layer({})));
497
498 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
499 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
500 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
501 }).pipe(Effect.provide(NodeServices.layer)),
502);
503
504it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
505 Effect.gen(function* () {
506 const fs = yield* FileSystem.FileSystem;
507 const path = yield* Path.Path;
508 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
509 yield* Effect.gen(function* () {
510 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
511 const query = yield* service.prepareClone({
512 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
513 destinationPath: path.join(parent, "a"),
514 });
515 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
516 const nested = yield* service.prepareClone({
517 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
518 destinationPath: path.join(parent, "b"),
519 });
520 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
521 }).pipe(Effect.provide(layer({})));
522 }).pipe(Effect.provide(NodeServices.layer)),
523);
524
525it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
526 const fileSystemCause = PlatformError.systemError({
527 _tag: "PermissionDenied",
528 module: "FileSystem",
529 method: "exists",
530 pathOrDescriptor: "/restricted/t3code",
531 });
532
533 return Effect.gen(function* () {
534 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
535 const error = yield* Effect.flip(
536 service.cloneRepository({
537 remoteUrl: CLONE_URLS.sshUrl,
538 destinationPath: "/restricted/t3code",
539 }),
540 );
541
542 assert.strictEqual(error.provider, "unknown");
543 assert.strictEqual(error.operation, "cloneRepository");
544 assert.strictEqual(error.cause, fileSystemCause);
545 }).pipe(
546 Effect.provide(
547 layer({
548 fileSystem: FileSystem.makeNoop({
549 exists: () => Effect.fail(fileSystemCause),
550 makeDirectory: () => Effect.void,
551 }),
552 }),
553 ),
554 );
555});
556
557it.effect("publishes to the remote name returned by ensureRemote", () => {
558 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
559
560 return Effect.gen(function* () {
561 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
562 const result = yield* service.publishRepository({
563 cwd: "/workspace",
564 provider: SourceControlProviderKind.make("github"),
565 repository: "octocat/t3code",
566 visibility: "private",
567 remoteName: "origin",
568 protocol: "ssh",
569 });
570
571 assert.equal(result.remoteName, "origin-1");
572 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
573 }).pipe(
574 Effect.provide(
575 layer({
576 git: {
577 ensureRemote: () => Effect.succeed("origin-1"),
578 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
579 Effect.sync(() => {
580 pushCalls.push({ cwd, remoteName: options?.remoteName });
581 return {
582 status: "pushed" as const,
583 branch: "feature/remote-v1",
584 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
585 setUpstream: true,
586 };
587 }),
588 },
589 }),
590 ),
591 );
592});
593
594function failingPush(reason?: GitCommandError["reason"]) {
595 return {
596 pushCurrentBranch: (cwd: string) =>
597 Effect.fail(
598 new GitCommandError({
599 operation: "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
600 command: "git",
601 cwd,
602 ...(reason === undefined ? {} : { reason }),
603 detail: "Git command exited with a non-zero status.",
604 }),
605 ),
606 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
607}
608
609it.effect("explains a rejected SSH push after creating the repository", () =>
610 Effect.gen(function* () {
611 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
612 const error = yield* Effect.flip(
613 service.publishRepository({
614 cwd: "/workspace",
615 provider: SourceControlProviderKind.make("github"),
616 repository: "octocat/t3code",
617 visibility: "private",
618 protocol: "ssh",
619 }),
620 );
621
622 assert.strictEqual(error.operation, "publishRepository");
623 assert.strictEqual(
624 error.detail,
625 '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.',
626 );
627 assert.instanceOf(error.cause, GitCommandError);
628 }).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))),
629);
630
631// regression: #19219 publishing did not explain why the first push failed
632it.effect("says the repository exists when an unclassified publish push fails", () =>
633 Effect.gen(function* () {
634 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
635 const error = yield* Effect.flip(
636 service.publishRepository({
637 cwd: "/workspace",
638 provider: SourceControlProviderKind.make("github"),
639 repository: "octocat/t3code",
640 visibility: "private",
641 protocol: "https",
642 }),
643 );
644
645 assert.strictEqual(
646 error.detail,
647 'Created octocat/t3code and added it as remote "origin", but the push failed. Fix the problem, then push again.',
648 );
649 }).pipe(Effect.provide(layer({ git: failingPush() }))),
650);
651
652it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
653 let pushCalls = 0;
654 return Effect.gen(function* () {
655 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
656 const result = yield* service.publishRepository({
657 cwd: "/workspace",
658 provider: SourceControlProviderKind.make("github"),
659 repository: "octocat/t3code",
660 visibility: "private",
661 remoteName: "origin",
662 protocol: "ssh",
663 });
664
665 assert.deepStrictEqual(result, {
666 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
667 remoteName: "origin",
668 remoteUrl: CLONE_URLS.sshUrl,
669 branch: "main",
670 status: "remote_added",
671 });
672 assert.strictEqual(pushCalls, 0);
673 }).pipe(
674 Effect.provide(
675 layer({
676 git: {
677 execute: (input) =>
678 input.args[0] === "rev-parse"
679 ? Effect.fail(
680 new GitCommandError({
681 operation: input.operation,
682 command: "git rev-parse --verify HEAD",
683 cwd: input.cwd,
684 detail: "fatal: Needed a single revision",
685 }),
686 )
687 : Effect.succeed(processOutput()),
688 statusDetails: () =>
689 Effect.succeed({
690 isRepo: true,
691 hasOriginRemote: true,
692 isDefaultBranch: true,
693 branch: "main",
694 upstreamRef: null,
695 hasWorkingTreeChanges: false,
696 workingTree: { files: [], insertions: 0, deletions: 0 },
697 hasUpstream: false,
698 aheadCount: 0,
699 behindCount: 0,
700 aheadOfDefaultCount: 0,
701 }),
702 pushCurrentBranch: () =>
703 Effect.sync(() => {
704 pushCalls += 1;
705 return {
706 status: "pushed" as const,
707 branch: "main",
708 upstreamBranch: "origin/main",
709 setUpstream: true,
710 };
711 }),
712 },
713 }),
714 ),
715 );
716});