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