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 * as Schema from "effect/Schema";
11import { ChildProcessSpawner } from "effect/process";
12
13import { GitCommandError, SourceControlProviderError } from "@t3tools/contracts";
14
15import * as ServerConfig from "../config.ts";
16import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
17import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
18import * as BitbucketSourceControlProvider from "@t3tools/source-control-bitbucket/server/BitbucketSourceControlProvider";
19import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
20import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
21import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts";
22
23const isSourceControlProviderError = Schema.is(SourceControlProviderError);
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(NodeServices.layer));
103}
104
105it.effect("looks up repositories through the requested provider without search", () => {
106 const calls: Array<{ cwd: string; repository: string }> = [];
107 const provider = makeProvider({
108 getRepositoryCloneUrls: (input) =>
109 Effect.sync(() => {
110 calls.push({ cwd: input.cwd, repository: input.repository });
111 return CLONE_URLS;
112 }),
113 });
114
115 return Effect.gen(function* () {
116 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
117 const result = yield* service.lookupRepository({
118 provider: SourceControlProviderKind.make("github"),
119 repository: "octocat/t3code",
120 cwd: "/workspace",
121 });
122
123 assert.deepStrictEqual(result, {
124 provider: SourceControlProviderKind.make("github"),
125 ...CLONE_URLS,
126 });
127 assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
128 }).pipe(Effect.provide(layer({ provider })));
129});
130
131it.effect("preserves provider failures without deriving the repository message from them", () => {
132 const providerCause = new SourceControlProviderError({
133 provider: SourceControlProviderKind.make("github"),
134 operation: "getRepositoryCloneUrls",
135 cwd: "/workspace",
136 repository: "octocat/t3code",
137 detail: "credential token abc123 was rejected",
138 });
139 const provider = makeProvider({
140 getRepositoryCloneUrls: () => Effect.fail(providerCause),
141 });
142
143 return Effect.gen(function* () {
144 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
145 const error = yield* Effect.flip(
146 service.lookupRepository({
147 provider: SourceControlProviderKind.make("github"),
148 repository: "octocat/t3code",
149 cwd: "/workspace",
150 }),
151 );
152
153 assert.strictEqual(error.provider, "github");
154 assert.strictEqual(error.operation, "lookupRepository");
155 assert.strictEqual(error.detail, "The source control operation could not be completed.");
156 assert.strictEqual(
157 error.message,
158 "Source control repository operation lookupRepository failed for github: The source control operation could not be completed.",
159 );
160 assert.strictEqual(error.cause, providerCause);
161 }).pipe(Effect.provide(layer({ provider })));
162});
163
164it.effect(
165 "reports the safe Bitbucket locator detail through repository lookup and publishing",
166 () =>
167 Effect.gen(function* () {
168 const locatorCause = new BitbucketApi.BitbucketRepositoryLocatorError({
169 repository: "credential-token-abc123",
170 });
171 const provider = yield* BitbucketSourceControlProvider.make.pipe(
172 Effect.provide(
173 Layer.mock(BitbucketApi.BitbucketApi)({
174 getRepositoryCloneUrls: () => Effect.fail(locatorCause),
175 createRepository: () => Effect.fail(locatorCause),
176 }),
177 ),
178 );
179
180 yield* Effect.gen(function* () {
181 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
182 const input = {
183 provider: SourceControlProviderKind.make("bitbucket"),
184 repository: locatorCause.repository,
185 cwd: "/workspace",
186 };
187 for (const operation of [
188 service.lookupRepository(input).pipe(Effect.asVoid),
189 service.publishRepository({ ...input, visibility: "private" }).pipe(Effect.asVoid),
190 ]) {
191 const error = yield* Effect.flip(operation);
192
193 assert.strictEqual(error.provider, "bitbucket");
194 assert.strictEqual(
195 error.detail,
196 "Bitbucket repositories must be specified as workspace/repository.",
197 );
198 assert.notInclude(error.message, locatorCause.repository);
199 assert.instanceOf(error.cause, SourceControlProviderError);
200 assert.strictEqual(
201 isSourceControlProviderError(error.cause) ? error.cause.cause : null,
202 locatorCause,
203 );
204 }
205 }).pipe(Effect.provide(layer({ provider })));
206 }),
207);
208
209it.effect("keeps a plain Bitbucket locator lookalike out of the repository message", () => {
210 const provider = makeProvider({
211 kind: SourceControlProviderKind.make("bitbucket"),
212 getRepositoryCloneUrls: () =>
213 Effect.fail(
214 new SourceControlProviderError({
215 provider: SourceControlProviderKind.make("bitbucket"),
216 operation: "getRepositoryCloneUrls",
217 cwd: "/workspace",
218 detail: "credential token abc123 was rejected",
219 cause: {
220 _tag: "BitbucketRepositoryLocatorError",
221 repository: "t3code",
222 detail: "credential token abc123 was rejected",
223 },
224 }),
225 ),
226 });
227
228 return Effect.gen(function* () {
229 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
230 const error = yield* Effect.flip(
231 service.lookupRepository({
232 provider: SourceControlProviderKind.make("bitbucket"),
233 repository: "t3code",
234 }),
235 );
236
237 assert.strictEqual(error.detail, "The source control operation could not be completed.");
238 assert.notInclude(error.message, "abc123");
239 }).pipe(Effect.provide(layer({ provider })));
240});
241
242it.effect("keeps arbitrary Bitbucket request failures out of the repository message", () =>
243 Effect.gen(function* () {
244 const cause = new BitbucketApi.BitbucketRequestError({
245 operation: "getRepository",
246 cause: new Error("credential token abc123 was rejected"),
247 });
248 const provider = yield* BitbucketSourceControlProvider.make.pipe(
249 Effect.provide(
250 Layer.mock(BitbucketApi.BitbucketApi)({
251 getRepositoryCloneUrls: () => Effect.fail(cause),
252 }),
253 ),
254 );
255
256 yield* Effect.gen(function* () {
257 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
258 const error = yield* Effect.flip(
259 service.lookupRepository({
260 provider: SourceControlProviderKind.make("bitbucket"),
261 repository: "pingdotgg/t3code",
262 cwd: "/workspace",
263 }),
264 );
265
266 assert.strictEqual(error.detail, "The source control operation could not be completed.");
267 assert.notInclude(error.message, "abc123");
268 assert.notInclude(error.message, cause.detail);
269 }).pipe(Effect.provide(layer({ provider })));
270 }),
271);
272
273it.effect("clones a looked-up repository into the requested destination", () =>
274 Effect.gen(function* () {
275 const fs = yield* FileSystem.FileSystem;
276 const path = yield* Path.Path;
277 const parent = yield* fs.makeTempDirectoryScoped({
278 prefix: "t3-source-control-clone-parent-",
279 });
280 const destinationPath = path.join(parent, "t3code");
281 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
282
283 yield* Effect.gen(function* () {
284 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
285 const result = yield* service.cloneRepository({
286 provider: SourceControlProviderKind.make("github"),
287 repository: "octocat/t3code",
288 destinationPath,
289 protocol: "https",
290 });
291
292 assert.deepStrictEqual(result, {
293 cwd: destinationPath,
294 remoteUrl: CLONE_URLS.url,
295 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
296 });
297 assert.deepStrictEqual(cloneCalls, [
298 {
299 cwd: parent,
300 args: ["clone", "--progress", "--", CLONE_URLS.url, "t3code"],
301 },
302 ]);
303 }).pipe(
304 Effect.provide(
305 layer({
306 git: {
307 execute: (input) =>
308 Effect.sync(() => {
309 cloneCalls.push({ cwd: input.cwd, args: input.args });
310 return processOutput();
311 }),
312 },
313 }),
314 ),
315 );
316 }).pipe(Effect.provide(NodeServices.layer)),
317);
318
319it.effect.each(["--bare", "source.git"])(
320 "clones a local repository named %s as a working tree",
321 (repositoryName) =>
322 Effect.gen(function* () {
323 const fs = yield* FileSystem.FileSystem;
324 const path = yield* Path.Path;
325 const git = yield* GitVcsDriver.GitVcsDriver;
326 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-options-" });
327 yield* git.execute({
328 operation: "test.init",
329 cwd: parent,
330 args: ["init", "--bare", path.join(parent, repositoryName)],
331 });
332 const destinationPath = path.join(parent, "checkout");
333 yield* Effect.gen(function* () {
334 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
335 const result = yield* service.cloneRepository({
336 remoteUrl: repositoryName,
337 destinationPath,
338 });
339 assert.strictEqual(result.cwd, destinationPath);
340 assert.isTrue(yield* fs.exists(path.join(destinationPath, ".git")));
341 }).pipe(Effect.provide(layer({ git: { execute: git.execute } })));
342 }).pipe(
343 Effect.provide(
344 GitVcsDriver.layer.pipe(
345 Layer.provide(
346 ServerConfig.layerTest(process.cwd(), {
347 prefix: "t3-clone-options-config-",
348 }),
349 ),
350 Layer.provideMerge(NodeServices.layer),
351 ),
352 ),
353 ),
354);
355
356it.effect("reports clone progress from git's stderr and keeps its error text on failure", () =>
357 Effect.gen(function* () {
358 const fs = yield* FileSystem.FileSystem;
359 const path = yield* Path.Path;
360 const parent = yield* fs.makeTempDirectoryScoped({
361 prefix: "t3-source-control-clone-progress-",
362 });
363 const destinationPath = path.join(parent, "t3code");
364 const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
365
366 const stderrLines = [
367 "Cloning into 't3code'...",
368 "remote: Enumerating objects: 10, done.",
369 "Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
370 "Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
371 "fatal: early EOF",
372 "fatal: unable to access 'https://user:s3c@ret@github.com/octocat/t3code.git/': could not resolve host",
373 ];
374 const error = yield* Effect.gen(function* () {
375 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
376 return yield* Effect.flip(
377 service.cloneRepository(
378 { remoteUrl: CLONE_URLS.sshUrl, destinationPath },
379 { onProgress: (line) => Effect.sync(() => void progress.push(line)) },
380 ),
381 );
382 }).pipe(
383 Effect.provide(
384 layer({
385 git: {
386 execute: (input) =>
387 Effect.gen(function* () {
388 for (const line of stderrLines) {
389 yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
390 }
391 return yield* new GitCommandError({
392 operation: input.operation,
393 command: "git",
394 cwd: input.cwd,
395 detail: "Git command exited with a non-zero status.",
396 exitCode: 128,
397 });
398 }),
399 },
400 }),
401 ),
402 );
403
404 assert.deepStrictEqual(progress, [
405 { stage: "counting", percent: null, detail: null },
406 { stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
407 { stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
408 ]);
409 assert.strictEqual(
410 error.detail,
411 "fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
412 );
413 }).pipe(Effect.provide(NodeServices.layer)),
414);
415
416it.effect("strips embedded credentials from the remote URL it reports", () =>
417 Effect.gen(function* () {
418 const fs = yield* FileSystem.FileSystem;
419 const path = yield* Path.Path;
420 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
421 const destinationPath = path.join(parent, "t3code");
422 const cloneArgs: Array<ReadonlyArray<string>> = [];
423 const result = yield* Effect.gen(function* () {
424 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
425 return yield* service.prepareClone({
426 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
427 destinationPath,
428 });
429 }).pipe(
430 Effect.provide(
431 layer({
432 git: {
433 execute: (input) =>
434 Effect.sync(() => {
435 cloneArgs.push(input.args);
436 return processOutput();
437 }),
438 },
439 }),
440 ),
441 );
442 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
443 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
444 }).pipe(Effect.provide(NodeServices.layer)),
445);
446
447it.effect("discards only a directory git wrote to", () =>
448 Effect.gen(function* () {
449 const fs = yield* FileSystem.FileSystem;
450 const path = yield* Path.Path;
451 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
452 const partial = path.join(parent, "partial");
453 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
454 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
455 const foreign = path.join(parent, "foreign");
456 yield* fs.makeDirectory(foreign);
457 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
458
459 const replaced = path.join(parent, "replaced");
460 yield* fs.writeFileString(replaced, "not a directory");
461
462 yield* Effect.gen(function* () {
463 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
464 yield* service.discardClone(partial);
465 const error = yield* Effect.flip(service.discardClone(foreign));
466 assert.include(error.detail, "not from the clone");
467 const replacedError = yield* Effect.flip(service.discardClone(replaced));
468 assert.include(replacedError.detail, "could not be inspected");
469 yield* service.discardClone(path.join(parent, "missing"));
470 }).pipe(Effect.provide(layer({})));
471
472 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
473 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
474 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
475 }).pipe(Effect.provide(NodeServices.layer)),
476);
477
478it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
479 Effect.gen(function* () {
480 const fs = yield* FileSystem.FileSystem;
481 const path = yield* Path.Path;
482 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
483 yield* Effect.gen(function* () {
484 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
485 const query = yield* service.prepareClone({
486 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
487 destinationPath: path.join(parent, "a"),
488 });
489 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
490 const nested = yield* service.prepareClone({
491 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
492 destinationPath: path.join(parent, "b"),
493 });
494 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
495 }).pipe(Effect.provide(layer({})));
496 }).pipe(Effect.provide(NodeServices.layer)),
497);
498
499it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
500 const fileSystemCause = PlatformError.systemError({
501 _tag: "PermissionDenied",
502 module: "FileSystem",
503 method: "exists",
504 pathOrDescriptor: "/restricted/t3code",
505 });
506
507 return Effect.gen(function* () {
508 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
509 const error = yield* Effect.flip(
510 service.cloneRepository({
511 remoteUrl: CLONE_URLS.sshUrl,
512 destinationPath: "/restricted/t3code",
513 }),
514 );
515
516 assert.strictEqual(error.provider, "unknown");
517 assert.strictEqual(error.operation, "cloneRepository");
518 assert.strictEqual(error.cause, fileSystemCause);
519 }).pipe(
520 Effect.provide(
521 layer({
522 fileSystem: FileSystem.makeNoop({
523 exists: () => Effect.fail(fileSystemCause),
524 makeDirectory: () => Effect.void,
525 }),
526 }),
527 ),
528 );
529});
530
531it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
532 const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
533 const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
534 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
535 const provider = makeProvider({
536 createRepository: (input) =>
537 Effect.sync(() => {
538 createCalls.push({
539 cwd: input.cwd,
540 repository: input.repository,
541 visibility: input.visibility,
542 });
543 return CLONE_URLS;
544 }),
545 });
546
547 return Effect.gen(function* () {
548 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
549 const result = yield* service.publishRepository({
550 cwd: "/workspace",
551 provider: SourceControlProviderKind.make("github"),
552 repository: "octocat/t3code",
553 visibility: "private",
554 remoteName: "origin",
555 protocol: "ssh",
556 });
557
558 assert.deepStrictEqual(result, {
559 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
560 remoteName: "origin",
561 remoteUrl: CLONE_URLS.sshUrl,
562 branch: "feature/remote-v1",
563 upstreamBranch: "origin/feature/remote-v1",
564 status: "pushed",
565 });
566 assert.deepStrictEqual(createCalls, [
567 { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
568 ]);
569 assert.deepStrictEqual(remoteCalls, [
570 { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
571 ]);
572 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
573 }).pipe(
574 Effect.provide(
575 layer({
576 provider,
577 git: {
578 ensureRemote: (input) =>
579 Effect.sync(() => {
580 remoteCalls.push(input);
581 return "origin";
582 }),
583 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
584 Effect.sync(() => {
585 pushCalls.push({ cwd, remoteName: options?.remoteName });
586 return {
587 status: "pushed" as const,
588 branch: "feature/remote-v1",
589 upstreamBranch: "origin/feature/remote-v1",
590 setUpstream: true,
591 };
592 }),
593 },
594 }),
595 ),
596 );
597});
598
599it.effect("publishes to the remote name returned by ensureRemote", () => {
600 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
601
602 return Effect.gen(function* () {
603 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
604 const result = yield* service.publishRepository({
605 cwd: "/workspace",
606 provider: SourceControlProviderKind.make("github"),
607 repository: "octocat/t3code",
608 visibility: "private",
609 remoteName: "origin",
610 protocol: "ssh",
611 });
612
613 assert.equal(result.remoteName, "origin-1");
614 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
615 }).pipe(
616 Effect.provide(
617 layer({
618 git: {
619 ensureRemote: () => Effect.succeed("origin-1"),
620 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
621 Effect.sync(() => {
622 pushCalls.push({ cwd, remoteName: options?.remoteName });
623 return {
624 status: "pushed" as const,
625 branch: "feature/remote-v1",
626 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
627 setUpstream: true,
628 };
629 }),
630 },
631 }),
632 ),
633 );
634});
635
636function failingPush(reason?: GitCommandError["reason"]) {
637 return {
638 pushCurrentBranch: (cwd: string) =>
639 Effect.fail(
640 new GitCommandError({
641 operation: "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
642 command: "git",
643 cwd,
644 ...(reason === undefined ? {} : { reason }),
645 detail: "Git command exited with a non-zero status.",
646 }),
647 ),
648 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
649}
650
651it.effect("explains a rejected SSH push after creating the repository", () =>
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: "ssh",
661 }),
662 );
663
664 assert.strictEqual(error.operation, "publishRepository");
665 assert.strictEqual(
666 error.detail,
667 '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.',
668 );
669 assert.instanceOf(error.cause, GitCommandError);
670 }).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))),
671);
672
673it.effect("says the repository exists when an unclassified publish push fails", () =>
674 Effect.gen(function* () {
675 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
676 const error = yield* Effect.flip(
677 service.publishRepository({
678 cwd: "/workspace",
679 provider: SourceControlProviderKind.make("github"),
680 repository: "octocat/t3code",
681 visibility: "private",
682 protocol: "https",
683 }),
684 );
685
686 assert.strictEqual(
687 error.detail,
688 'Created octocat/t3code and added it as remote "origin", but the push failed. Fix the problem, then push again.',
689 );
690 }).pipe(Effect.provide(layer({ git: failingPush() }))),
691);
692
693it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
694 let pushCalls = 0;
695 return Effect.gen(function* () {
696 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
697 const result = yield* service.publishRepository({
698 cwd: "/workspace",
699 provider: SourceControlProviderKind.make("github"),
700 repository: "octocat/t3code",
701 visibility: "private",
702 remoteName: "origin",
703 protocol: "ssh",
704 });
705
706 assert.deepStrictEqual(result, {
707 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
708 remoteName: "origin",
709 remoteUrl: CLONE_URLS.sshUrl,
710 branch: "main",
711 status: "remote_added",
712 });
713 assert.strictEqual(pushCalls, 0);
714 }).pipe(
715 Effect.provide(
716 layer({
717 git: {
718 execute: (input) =>
719 input.args[0] === "rev-parse"
720 ? Effect.fail(
721 new GitCommandError({
722 operation: input.operation,
723 command: "git rev-parse --verify HEAD",
724 cwd: input.cwd,
725 detail: "fatal: Needed a single revision",
726 }),
727 )
728 : Effect.succeed(processOutput()),
729 statusDetails: () =>
730 Effect.succeed({
731 isRepo: true,
732 hasOriginRemote: true,
733 isDefaultBranch: true,
734 branch: "main",
735 upstreamRef: null,
736 hasWorkingTreeChanges: false,
737 workingTree: { files: [], insertions: 0, deletions: 0 },
738 hasUpstream: false,
739 aheadCount: 0,
740 behindCount: 0,
741 aheadOfDefaultCount: 0,
742 }),
743 pushCurrentBranch: () =>
744 Effect.sync(() => {
745 pushCalls += 1;
746 return {
747 status: "pushed" as const,
748 branch: "main",
749 upstreamBranch: "origin/main",
750 setUpstream: true,
751 };
752 }),
753 },
754 }),
755 ),
756 );
757});