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

SourceControlRepositoryService.test.ts

798 lines28.9 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 * 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 };
52​
53function processOutput(): GitVcsDriver.ExecuteGitResult {
54 return {
55 exitCode: ChildProcessSpawner.ExitCode(0),
56 stdout: "",
57 stderr: "",
58 stdoutTruncated: false,
59 stderrTruncated: false,
60 };
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));
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 after creating missing parent directories", () =>
274 Effect.gen(function* () {
275 const fs = yield* FileSystem.FileSystem;
276 const path = yield* Path.Path;
277 const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
278 prefix: "t3-source-control-clone-parent-",
279 });
280 const parent = path.join(temporaryDirectory, "missing", "nested");
281 const destinationPath = path.join(parent, "t3code");
282 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
283​
284 yield* Effect.gen(function* () {
285 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
286 const result = yield* service.cloneRepository({
287 provider: SourceControlProviderKind.make("github"),
288 repository: "octocat/t3code",
289 destinationPath,
290 protocol: "https",
291 });
292​
293 assert.deepStrictEqual(result, {
294 cwd: destinationPath,
295 remoteUrl: CLONE_URLS.url,
296 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
297 });
298 assert.deepStrictEqual(cloneCalls, [
299 {
300 cwd: parent,
301 args: ["clone", "--progress", "--", CLONE_URLS.url, "t3code"],
302 },
303 ]);
304 }).pipe(
305 Effect.provide(
306 layer({
307 git: {
308 execute: (input) =>
309 Effect.gen(function* () {
310 assert.isTrue(yield* fs.exists(parent).pipe(Effect.orDie));
311 cloneCalls.push({ cwd: input.cwd, args: input.args });
312 return processOutput();
313 }),
314 },
315 }),
316 ),
317 );
318 }).pipe(Effect.provide(NodeServices.layer)),
319);
320​
321it.effect.each(["--bare", "source.git"])(
322 "clones a local repository named %s as a working tree",
323 (repositoryName) =>
324 Effect.gen(function* () {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const git = yield* GitVcsDriver.GitVcsDriver;
328 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-options-" });
329 yield* git.execute({
330 operation: "test.init",
331 cwd: parent,
332 args: ["init", "--bare", path.join(parent, repositoryName)],
333 });
334 const destinationPath = path.join(parent, "checkout");
335 yield* Effect.gen(function* () {
336 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
337 const result = yield* service.cloneRepository({
338 remoteUrl: repositoryName,
339 destinationPath,
340 });
341 assert.strictEqual(result.cwd, destinationPath);
342 assert.isTrue(yield* fs.exists(path.join(destinationPath, ".git")));
343 }).pipe(Effect.provide(layer({ git: { execute: git.execute } })));
344 }).pipe(
345 Effect.provide(
346 GitVcsDriver.layer.pipe(
347 Layer.provide(
348 ServerConfig.layerTest(process.cwd(), {
349 prefix: "t3-clone-options-config-",
350 }),
351 ),
352 Layer.provideMerge(NodeServices.layer),
353 ),
354 ),
355 ),
356);
357​
358it.effect("reports clone progress from git's stderr and keeps its error text on failure", () =>
359 Effect.gen(function* () {
360 const fs = yield* FileSystem.FileSystem;
361 const path = yield* Path.Path;
362 const parent = yield* fs.makeTempDirectoryScoped({
363 prefix: "t3-source-control-clone-progress-",
364 });
365 const destinationPath = path.join(parent, "t3code");
366 const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
367​
368 const stderrLines = [
369 "Cloning into 't3code'...",
370 "remote: Enumerating objects: 10, done.",
371 "Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
372 "Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
373 "fatal: early EOF",
374 "fatal: unable to access 'https://user:s3c@ret@github.com/octocat/t3code.git/': could not resolve host",
375 ];
376 const error = yield* Effect.gen(function* () {
377 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
378 return yield* Effect.flip(
379 service.cloneRepository(
380 { remoteUrl: CLONE_URLS.sshUrl, destinationPath },
381 { onProgress: (line) => Effect.sync(() => void progress.push(line)) },
382 ),
383 );
384 }).pipe(
385 Effect.provide(
386 layer({
387 git: {
388 execute: (input) =>
389 Effect.gen(function* () {
390 for (const line of stderrLines) {
391 yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
392 }
393 return yield* new GitCommandError({
394 operation: input.operation,
395 command: "git",
396 cwd: input.cwd,
397 detail: "Git command exited with a non-zero status.",
398 exitCode: 128,
399 });
400 }),
401 },
402 }),
403 ),
404 );
405​
406 assert.deepStrictEqual(progress, [
407 { stage: "counting", percent: null, detail: null },
408 { stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
409 { stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
410 ]);
411 assert.strictEqual(
412 error.detail,
413 "fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
414 );
415 }).pipe(Effect.provide(NodeServices.layer)),
416);
417​
418it.effect("strips embedded credentials from the remote URL it reports", () =>
419 Effect.gen(function* () {
420 const fs = yield* FileSystem.FileSystem;
421 const path = yield* Path.Path;
422 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
423 const destinationPath = path.join(parent, "t3code");
424 const cloneArgs: Array<ReadonlyArray<string>> = [];
425 const result = yield* Effect.gen(function* () {
426 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
427 return yield* service.prepareClone({
428 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
429 destinationPath,
430 });
431 }).pipe(
432 Effect.provide(
433 layer({
434 git: {
435 execute: (input) =>
436 Effect.sync(() => {
437 cloneArgs.push(input.args);
438 return processOutput();
439 }),
440 },
441 }),
442 ),
443 );
444 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
445 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
446 }).pipe(Effect.provide(NodeServices.layer)),
447);
448​
449it.effect("discards only a directory git wrote to", () =>
450 Effect.gen(function* () {
451 const fs = yield* FileSystem.FileSystem;
452 const path = yield* Path.Path;
453 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
454 const partial = path.join(parent, "partial");
455 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
456 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
457 const foreign = path.join(parent, "foreign");
458 yield* fs.makeDirectory(foreign);
459 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
460​
461 const replaced = path.join(parent, "replaced");
462 yield* fs.writeFileString(replaced, "not a directory");
463​
464 yield* Effect.gen(function* () {
465 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
466 yield* service.discardClone(partial);
467 const error = yield* Effect.flip(service.discardClone(foreign));
468 assert.include(error.detail, "not from the clone");
469 const replacedError = yield* Effect.flip(service.discardClone(replaced));
470 assert.include(replacedError.detail, "could not be inspected");
471 yield* service.discardClone(path.join(parent, "missing"));
472 }).pipe(Effect.provide(layer({})));
473​
474 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
475 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
476 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
477 }).pipe(Effect.provide(NodeServices.layer)),
478);
479​
480it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
481 Effect.gen(function* () {
482 const fs = yield* FileSystem.FileSystem;
483 const path = yield* Path.Path;
484 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
485 yield* Effect.gen(function* () {
486 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
487 const query = yield* service.prepareClone({
488 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
489 destinationPath: path.join(parent, "a"),
490 });
491 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
492 const nested = yield* service.prepareClone({
493 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
494 destinationPath: path.join(parent, "b"),
495 });
496 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
497 }).pipe(Effect.provide(layer({})));
498 }).pipe(Effect.provide(NodeServices.layer)),
499);
500​
501it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
502 const fileSystemCause = PlatformError.systemError({
503 _tag: "PermissionDenied",
504 module: "FileSystem",
505 method: "exists",
506 pathOrDescriptor: "/restricted/t3code",
507 });
508​
509 return Effect.gen(function* () {
510 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
511 const error = yield* Effect.flip(
512 service.cloneRepository({
513 remoteUrl: CLONE_URLS.sshUrl,
514 destinationPath: "/restricted/t3code",
515 }),
516 );
517​
518 assert.strictEqual(error.provider, "unknown");
519 assert.strictEqual(error.operation, "cloneRepository");
520 assert.strictEqual(error.cause, fileSystemCause);
521 }).pipe(
522 Effect.provide(
523 layer({
524 fileSystem: FileSystem.makeNoop({
525 exists: () => Effect.fail(fileSystemCause),
526 makeDirectory: () => Effect.void,
527 }),
528 }),
529 ),
530 );
531});
532​
533it.effect("clones directly under an existing filesystem root without recreating it", () =>
534 Effect.gen(function* () {
535 const path = yield* Path.Path;
536 const root = path.parse(path.resolve(".")).root;
537 const cloneCalls: Array<string> = [];
538​
539 yield* Effect.gen(function* () {
540 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
541 yield* service.cloneRepository({
542 provider: SourceControlProviderKind.make("github"),
543 repository: "octocat/t3code",
544 destinationPath: path.join(root, "t3code"),
545 protocol: "https",
546 });
547​
548 assert.deepStrictEqual(cloneCalls, [root]);
549 }).pipe(
550 Effect.provide(
551 layer({
552 fileSystem: FileSystem.makeNoop({
553 exists: (target) => Effect.succeed(target === root),
554 makeDirectory: (target) =>
555 Effect.sync(() => {
556 assert.notStrictEqual(target, root, "must not try to create the existing root");
557 }),
558 }),
559 git: {
560 execute: (input) =>
561 Effect.sync(() => {
562 cloneCalls.push(input.cwd);
563 return processOutput();
564 }),
565 },
566 }),
567 ),
568 );
569 }).pipe(Effect.provide(NodePath.layer)),
570);
571​
572it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
573 const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
574 const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
575 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
576 const provider = makeProvider({
577 createRepository: (input) =>
578 Effect.sync(() => {
579 createCalls.push({
580 cwd: input.cwd,
581 repository: input.repository,
582 visibility: input.visibility,
583 });
584 return CLONE_URLS;
585 }),
586 });
587​
588 return Effect.gen(function* () {
589 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
590 const result = yield* service.publishRepository({
591 cwd: "/workspace",
592 provider: SourceControlProviderKind.make("github"),
593 repository: "octocat/t3code",
594 visibility: "private",
595 remoteName: "origin",
596 protocol: "ssh",
597 });
598​
599 assert.deepStrictEqual(result, {
600 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
601 remoteName: "origin",
602 remoteUrl: CLONE_URLS.sshUrl,
603 branch: "feature/remote-v1",
604 upstreamBranch: "origin/feature/remote-v1",
605 status: "pushed",
606 });
607 assert.deepStrictEqual(createCalls, [
608 { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
609 ]);
610 assert.deepStrictEqual(remoteCalls, [
611 { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
612 ]);
613 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
614 }).pipe(
615 Effect.provide(
616 layer({
617 provider,
618 git: {
619 ensureRemote: (input) =>
620 Effect.sync(() => {
621 remoteCalls.push(input);
622 return "origin";
623 }),
624 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
625 Effect.sync(() => {
626 pushCalls.push({ cwd, remoteName: options?.remoteName });
627 return {
628 status: "pushed" as const,
629 branch: "feature/remote-v1",
630 upstreamBranch: "origin/feature/remote-v1",
631 setUpstream: true,
632 };
633 }),
634 },
635 }),
636 ),
637 );
638});
639​
640it.effect("publishes to the remote name returned by ensureRemote", () => {
641 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
642​
643 return Effect.gen(function* () {
644 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
645 const result = yield* service.publishRepository({
646 cwd: "/workspace",
647 provider: SourceControlProviderKind.make("github"),
648 repository: "octocat/t3code",
649 visibility: "private",
650 remoteName: "origin",
651 protocol: "ssh",
652 });
653​
654 assert.equal(result.remoteName, "origin-1");
655 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
656 }).pipe(
657 Effect.provide(
658 layer({
659 git: {
660 ensureRemote: () => Effect.succeed("origin-1"),
661 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
662 Effect.sync(() => {
663 pushCalls.push({ cwd, remoteName: options?.remoteName });
664 return {
665 status: "pushed" as const,
666 branch: "feature/remote-v1",
667 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
668 setUpstream: true,
669 };
670 }),
671 },
672 }),
673 ),
674 );
675});
676​
677function failingPush(reason?: GitCommandError["reason"]) {
678 return {
679 pushCurrentBranch: (cwd: string) =>
680 Effect.fail(
681 new GitCommandError({
682 operation: "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
683 command: "git",
684 cwd,
685 ...(reason === undefined ? {} : { reason }),
686 detail: "Git command exited with a non-zero status.",
687 }),
688 ),
689 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
691​
692it.effect("explains a rejected SSH push after creating the repository", () =>
693 Effect.gen(function* () {
694 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
695 const error = yield* Effect.flip(
696 service.publishRepository({
697 cwd: "/workspace",
698 provider: SourceControlProviderKind.make("github"),
699 repository: "octocat/t3code",
700 visibility: "private",
701 protocol: "ssh",
702 }),
703 );
704​
705 assert.strictEqual(error.operation, "publishRepository");
706 assert.strictEqual(
707 error.detail,
708 '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.',
709 );
710 assert.instanceOf(error.cause, GitCommandError);
711 }).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))),
712);
713​
714it.effect("says the repository exists when an unclassified publish push fails", () =>
715 Effect.gen(function* () {
716 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
717 const error = yield* Effect.flip(
718 service.publishRepository({
719 cwd: "/workspace",
720 provider: SourceControlProviderKind.make("github"),
721 repository: "octocat/t3code",
722 visibility: "private",
723 protocol: "https",
724 }),
725 );
726​
727 assert.strictEqual(
728 error.detail,
729 'Created octocat/t3code and added it as remote "origin", but the push failed. Fix the problem, then push again.',
730 );
731 }).pipe(Effect.provide(layer({ git: failingPush() }))),
732);
733​
734it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
735 let pushCalls = 0;
736 return Effect.gen(function* () {
737 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
738 const result = yield* service.publishRepository({
739 cwd: "/workspace",
740 provider: SourceControlProviderKind.make("github"),
741 repository: "octocat/t3code",
742 visibility: "private",
743 remoteName: "origin",
744 protocol: "ssh",
745 });
746​
747 assert.deepStrictEqual(result, {
748 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
749 remoteName: "origin",
750 remoteUrl: CLONE_URLS.sshUrl,
751 branch: "main",
752 status: "remote_added",
753 });
754 assert.strictEqual(pushCalls, 0);
755 }).pipe(
756 Effect.provide(
757 layer({
758 git: {
759 execute: (input) =>
760 input.args[0] === "rev-parse"
761 ? Effect.fail(
762 new GitCommandError({
763 operation: input.operation,
764 command: "git rev-parse --verify HEAD",
765 cwd: input.cwd,
766 detail: "fatal: Needed a single revision",
767 }),
768 )
769 : Effect.succeed(processOutput()),
770 statusDetails: () =>
771 Effect.succeed({
772 isRepo: true,
773 hasOriginRemote: true,
774 isDefaultBranch: true,
775 branch: "main",
776 upstreamRef: null,
777 hasWorkingTreeChanges: false,
778 workingTree: { files: [], insertions: 0, deletions: 0 },
779 hasUpstream: false,
780 aheadCount: 0,
781 behindCount: 0,
782 aheadOfDefaultCount: 0,
783 }),
784 pushCurrentBranch: () =>
785 Effect.sync(() => {
786 pushCalls += 1;
787 return {
788 status: "pushed" as const,
789 branch: "main",
790 upstreamBranch: "origin/main",
791 setUpstream: true,
792 };
793 }),
794 },
795 }),
796 ),
797 );
798});