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

GitCore.test.ts

1,375 lines50.9 KB

1import { existsSync } from "node:fs";
2import path from "node:path";
3​
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { it } from "@effect/vitest";
6import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
7import { describe, expect, vi } from "vitest";
8​
9import { GitServiceLive } from "./GitService.ts";
10import { GitService, type GitServiceShape } from "../Services/GitService.ts";
11import { GitCoreLive } from "./GitCore.ts";
12import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
13import { GitCommandError } from "../Errors.ts";
14import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
15​
16// ── Helpers ──
17​
18const GitServiceTestLayer = GitServiceLive.pipe(Layer.provide(NodeServices.layer));
19const GitCoreTestLayer = GitCoreLive.pipe(
20 Layer.provide(GitServiceTestLayer),
21 Layer.provide(NodeServices.layer),
22);
23const TestLayer = Layer.mergeAll(NodeServices.layer, GitServiceTestLayer, GitCoreTestLayer);
24​
25function makeTmpDir(
26 prefix = "git-test-",
27): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
28 return Effect.gen(function* () {
29 const fileSystem = yield* FileSystem.FileSystem;
30 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
31 });
33​
34function writeTextFile(
35 filePath: string,
36 contents: string,
37): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
38 return Effect.gen(function* () {
39 const fileSystem = yield* FileSystem.FileSystem;
40 yield* fileSystem.writeFileString(filePath, contents);
41 });
43​
44/** Run a raw git command for test setup (not under test). */
45function git(
46 cwd: string,
47 args: ReadonlyArray<string>,
48 env?: NodeJS.ProcessEnv,
49): Effect.Effect<string, GitCommandError, GitService> {
50 return Effect.gen(function* () {
51 const gitService = yield* GitService;
52 const result = yield* gitService.execute({
53 operation: "GitCore.test.git",
54 cwd,
55 args,
56 ...(env ? { env } : {}),
57 timeoutMs: 10_000,
58 });
59 return result.stdout.trim();
60 });
62​
63function runShellCommand(input: {
64 command: string;
65 cwd: string;
66 timeoutMs?: number;
67 maxOutputBytes?: number;
68}): Effect.Effect<ProcessRunResult, Error> {
69 return Effect.promise(() => {
70 const shellPath =
71 process.platform === "win32"
72 ? (process.env.ComSpec ?? "cmd.exe")
73 : (process.env.SHELL ?? "/bin/sh");
74​
75 const args =
76 process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
77​
78 return runProcess(shellPath, args, {
79 cwd: input.cwd,
80 timeoutMs: input.timeoutMs ?? 30_000,
81 allowNonZeroExit: true,
82 maxBufferBytes: input.maxOutputBytes ?? 1_000_000,
83 outputMode: "truncate",
84 });
85 });
87​
88const makeIsolatedGitCore = (gitService: GitServiceShape) =>
89 Effect.promise(async () => {
90 const gitServiceLayer = Layer.succeed(GitService, gitService);
91 const coreLayer = GitCoreLive.pipe(
92 Layer.provide(gitServiceLayer),
93 Layer.provide(NodeServices.layer),
94 );
95 const core = await Effect.runPromise(Effect.service(GitCore).pipe(Effect.provide(coreLayer)));
96​
97 return {
98 status: (input) => core.status(input),
99 statusDetails: (cwd) => core.statusDetails(cwd),
100 prepareCommitContext: (cwd) => core.prepareCommitContext(cwd),
101 commit: (cwd, subject, body) => core.commit(cwd, subject, body),
102 pushCurrentBranch: (cwd, fallbackBranch) => core.pushCurrentBranch(cwd, fallbackBranch),
103 pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd),
104 readRangeContext: (cwd, baseBranch) => core.readRangeContext(cwd, baseBranch),
105 readConfigValue: (cwd, key) => core.readConfigValue(cwd, key),
106 listBranches: (input) => core.listBranches(input),
107 createWorktree: (input) => core.createWorktree(input),
108 removeWorktree: (input) => core.removeWorktree(input),
109 createBranch: (input) => core.createBranch(input),
110 checkoutBranch: (input) => core.checkoutBranch(input),
111 initRepo: (input) => core.initRepo(input),
112 } satisfies GitCoreShape;
113 });
114​
115function listGitBranches(input: Parameters<GitCoreShape["listBranches"]>[0]) {
116 return Effect.gen(function* () {
117 const core = yield* GitCore;
118 return yield* core.listBranches(input);
119 });
121​
122function initGitRepo(input: Parameters<GitCoreShape["initRepo"]>[0]) {
123 return Effect.gen(function* () {
124 const core = yield* GitCore;
125 return yield* core.initRepo(input);
126 });
128​
129function createGitBranch(input: Parameters<GitCoreShape["createBranch"]>[0]) {
130 return Effect.gen(function* () {
131 const core = yield* GitCore;
132 return yield* core.createBranch(input);
133 });
135​
136function checkoutGitBranch(input: Parameters<GitCoreShape["checkoutBranch"]>[0]) {
137 return Effect.gen(function* () {
138 const core = yield* GitCore;
139 return yield* core.checkoutBranch(input);
140 });
142​
143function createGitWorktree(input: Parameters<GitCoreShape["createWorktree"]>[0]) {
144 return Effect.gen(function* () {
145 const core = yield* GitCore;
146 return yield* core.createWorktree(input);
147 });
149​
150function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0]) {
151 return Effect.gen(function* () {
152 const core = yield* GitCore;
153 return yield* core.removeWorktree(input);
154 });
156​
157function pullGitBranch({ cwd }: { cwd: string }) {
158 return Effect.gen(function* () {
159 const core = yield* GitCore;
160 return yield* core.pullCurrentBranch(cwd);
161 });
163​
164/** Create a repo with an initial commit so branches work. */
165function initRepoWithCommit(
166 cwd: string,
167): Effect.Effect<
168 void,
169 GitCommandError | PlatformError.PlatformError,
170 GitCore | GitService | FileSystem.FileSystem
171> {
172 return Effect.gen(function* () {
173 yield* initGitRepo({ cwd });
174 yield* git(cwd, ["config", "user.email", "test@test.com"]);
175 yield* git(cwd, ["config", "user.name", "Test"]);
176 yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
177 yield* git(cwd, ["add", "."]);
178 yield* git(cwd, ["commit", "-m", "initial commit"]);
179 });
181​
182function commitWithDate(
183 cwd: string,
184 fileName: string,
185 fileContents: string,
186 dateIsoString: string,
187 message: string,
188): Effect.Effect<
189 void,
190 GitCommandError | PlatformError.PlatformError,
191 GitService | FileSystem.FileSystem
192> {
193 return Effect.gen(function* () {
194 yield* writeTextFile(path.join(cwd, fileName), fileContents);
195 yield* git(cwd, ["add", fileName]);
196 yield* git(cwd, ["commit", "-m", message], {
197 ...process.env,
198 GIT_AUTHOR_DATE: dateIsoString,
199 GIT_COMMITTER_DATE: dateIsoString,
200 });
201 });
203​
204// ── Tests ──
205​
206it.layer(TestLayer)("git integration", (it) => {
207 describe("shell process execution", () => {
208 it.effect("caps captured output when maxOutputBytes is exceeded", () =>
209 Effect.gen(function* () {
210 const result = yield* runShellCommand({
211 command: `node -e "process.stdout.write('x'.repeat(2000))"`,
212 cwd: process.cwd(),
213 timeoutMs: 10_000,
214 maxOutputBytes: 128,
215 });
216​
217 expect(result.code).toBe(0);
218 expect(result.stdout.length).toBeLessThanOrEqual(128);
219 expect(result.stdoutTruncated || result.stderrTruncated).toBe(true);
220 }),
221 );
222 });
223​
224 // ── initGitRepo ──
225​
226 describe("initGitRepo", () => {
227 it.effect("creates a valid git repo", () =>
228 Effect.gen(function* () {
229 const tmp = yield* makeTmpDir();
230 yield* initGitRepo({ cwd: tmp });
231 expect(existsSync(path.join(tmp, ".git"))).toBe(true);
232 }),
233 );
234​
235 it.effect("listGitBranches reports isRepo: true after init + commit", () =>
236 Effect.gen(function* () {
237 const tmp = yield* makeTmpDir();
238 yield* initRepoWithCommit(tmp);
239 const result = yield* listGitBranches({ cwd: tmp });
240 expect(result.isRepo).toBe(true);
241 expect(result.branches.length).toBeGreaterThanOrEqual(1);
242 }),
243 );
244 });
245​
246 // ── listGitBranches ──
247​
248 describe("listGitBranches", () => {
249 it.effect("returns isRepo: false for non-git directory", () =>
250 Effect.gen(function* () {
251 const tmp = yield* makeTmpDir();
252 const result = yield* listGitBranches({ cwd: tmp });
253 expect(result.isRepo).toBe(false);
254 expect(result.branches).toEqual([]);
255 }),
256 );
257​
258 it.effect("returns the current branch with current: true", () =>
259 Effect.gen(function* () {
260 const tmp = yield* makeTmpDir();
261 yield* initRepoWithCommit(tmp);
262 const result = yield* listGitBranches({ cwd: tmp });
263 const current = result.branches.find((b) => b.current);
264 expect(current).toBeDefined();
265 expect(current!.current).toBe(true);
266 }),
267 );
268​
269 it.effect("does not include detached HEAD pseudo-refs as branches", () =>
270 Effect.gen(function* () {
271 const tmp = yield* makeTmpDir();
272 yield* initRepoWithCommit(tmp);
273 yield* git(tmp, ["checkout", "--detach", "HEAD"]);
274​
275 const result = yield* listGitBranches({ cwd: tmp });
276 expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
277 expect(result.branches.some((branch) => branch.current)).toBe(false);
278 }),
279 );
280​
281 it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
282 Effect.gen(function* () {
283 const tmp = yield* makeTmpDir();
284 yield* initRepoWithCommit(tmp);
285 const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
286 (branch) => branch.current,
287 )!.name;
288​
289 yield* createGitBranch({ cwd: tmp, branch: "older-branch" });
290 yield* checkoutGitBranch({ cwd: tmp, branch: "older-branch" });
291 yield* commitWithDate(
292 tmp,
293 "older.txt",
294 "older branch change\n",
295 "Thu, 1 Jan 2037 00:00:00 +0000",
296 "older branch change",
297 );
298​
299 yield* checkoutGitBranch({ cwd: tmp, branch: initialBranch });
300 yield* createGitBranch({ cwd: tmp, branch: "newer-branch" });
301 yield* checkoutGitBranch({ cwd: tmp, branch: "newer-branch" });
302 yield* commitWithDate(
303 tmp,
304 "newer.txt",
305 "newer branch change\n",
306 "Fri, 1 Jan 2038 00:00:00 +0000",
307 "newer branch change",
308 );
309​
310 // Switch away to show current branch is pinned, then remaining branches are recency-sorted.
311 yield* checkoutGitBranch({ cwd: tmp, branch: "older-branch" });
312​
313 const result = yield* listGitBranches({ cwd: tmp });
314 expect(result.branches[0]!.name).toBe("older-branch");
315 expect(result.branches[1]!.name).toBe("newer-branch");
316 }),
317 );
318​
319 it.effect("keeps default branch right after current branch", () =>
320 Effect.gen(function* () {
321 const tmp = yield* makeTmpDir();
322 const remote = yield* makeTmpDir();
323 yield* initRepoWithCommit(tmp);
324 const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
325 (branch) => branch.current,
326 )!.name;
327​
328 yield* git(remote, ["init", "--bare"]);
329 yield* git(tmp, ["remote", "add", "origin", remote]);
330 yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
331 yield* git(tmp, ["remote", "set-head", "origin", defaultBranch]);
332​
333 yield* createGitBranch({ cwd: tmp, branch: "current-branch" });
334 yield* checkoutGitBranch({ cwd: tmp, branch: "current-branch" });
335 yield* commitWithDate(
336 tmp,
337 "current.txt",
338 "current change\n",
339 "Thu, 1 Jan 2037 00:00:00 +0000",
340 "current change",
341 );
342​
343 yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
344 yield* createGitBranch({ cwd: tmp, branch: "newer-branch" });
345 yield* checkoutGitBranch({ cwd: tmp, branch: "newer-branch" });
346 yield* commitWithDate(
347 tmp,
348 "newer.txt",
349 "newer change\n",
350 "Fri, 1 Jan 2038 00:00:00 +0000",
351 "newer change",
352 );
353​
354 yield* checkoutGitBranch({ cwd: tmp, branch: "current-branch" });
355​
356 const result = yield* listGitBranches({ cwd: tmp });
357 expect(result.branches[0]!.name).toBe("current-branch");
358 expect(result.branches[1]!.name).toBe(defaultBranch);
359 expect(result.branches[2]!.name).toBe("newer-branch");
360 }),
361 );
362​
363 it.effect("lists multiple branches after creating them", () =>
364 Effect.gen(function* () {
365 const tmp = yield* makeTmpDir();
366 yield* initRepoWithCommit(tmp);
367 yield* createGitBranch({ cwd: tmp, branch: "feature-a" });
368 yield* createGitBranch({ cwd: tmp, branch: "feature-b" });
369​
370 const result = yield* listGitBranches({ cwd: tmp });
371 const names = result.branches.map((b) => b.name);
372 expect(names).toContain("feature-a");
373 expect(names).toContain("feature-b");
374 }),
375 );
376​
377 it.effect("isDefault is false when no remote exists", () =>
378 Effect.gen(function* () {
379 const tmp = yield* makeTmpDir();
380 yield* initRepoWithCommit(tmp);
381 const result = yield* listGitBranches({ cwd: tmp });
382 expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
383 }),
384 );
385​
386 it.effect("lists local branches first and remote branches last", () =>
387 Effect.gen(function* () {
388 const remote = yield* makeTmpDir();
389 const tmp = yield* makeTmpDir();
390​
391 yield* git(remote, ["init", "--bare"]);
392 yield* initRepoWithCommit(tmp);
393 const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
394 (branch) => branch.current,
395 )!.name;
396​
397 yield* git(tmp, ["remote", "add", "origin", remote]);
398 yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
399​
400 yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
401​
402 const remoteOnlyBranch = "feature/remote-only";
403 yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
404 yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
405 yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
406 yield* git(tmp, ["checkout", defaultBranch]);
407 yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
408​
409 const result = yield* listGitBranches({ cwd: tmp });
410 const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
411​
412 expect(firstRemoteIndex).toBeGreaterThan(0);
413 expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
414 true,
415 );
416 expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
417 true,
418 );
419 expect(
420 result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
421 ).toBe(true);
422 expect(
423 result.branches.some(
424 (branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
425 ),
426 ).toBe(true);
427 }),
428 );
429​
430 it.effect("includes remoteName metadata for remotes with slash in the name", () =>
431 Effect.gen(function* () {
432 const remote = yield* makeTmpDir();
433 const tmp = yield* makeTmpDir();
434 const remoteName = "my-org/upstream";
435​
436 yield* git(remote, ["init", "--bare"]);
437 yield* initRepoWithCommit(tmp);
438 const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
439 (branch) => branch.current,
440 )!.name;
441​
442 yield* git(tmp, ["remote", "add", remoteName, remote]);
443 yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
444​
445 const remoteOnlyBranch = "feature/remote-with-remote-name";
446 yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
447 yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
448 yield* git(tmp, ["checkout", defaultBranch]);
449 yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
450​
451 const result = yield* listGitBranches({ cwd: tmp });
452 const remoteBranch = result.branches.find(
453 (branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
454 );
455​
456 expect(remoteBranch).toBeDefined();
457 expect(remoteBranch?.isRemote).toBe(true);
458 expect(remoteBranch?.remoteName).toBe(remoteName);
459 }),
460 );
461 });
462​
463 // ── checkoutGitBranch ──
464​
465 describe("checkoutGitBranch", () => {
466 it.effect("checks out an existing branch", () =>
467 Effect.gen(function* () {
468 const tmp = yield* makeTmpDir();
469 yield* initRepoWithCommit(tmp);
470 yield* createGitBranch({ cwd: tmp, branch: "feature" });
471​
472 yield* checkoutGitBranch({ cwd: tmp, branch: "feature" });
473​
474 const result = yield* listGitBranches({ cwd: tmp });
475 const current = result.branches.find((b) => b.current);
476 expect(current!.name).toBe("feature");
477 }),
478 );
479​
480 it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
481 Effect.gen(function* () {
482 const remote = yield* makeTmpDir();
483 const source = yield* makeTmpDir();
484 const clone = yield* makeTmpDir();
485 yield* git(remote, ["init", "--bare"]);
486​
487 yield* initRepoWithCommit(source);
488 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
489 (branch) => branch.current,
490 )!.name;
491 yield* git(source, ["remote", "add", "origin", remote]);
492 yield* git(source, ["push", "-u", "origin", defaultBranch]);
493​
494 const featureBranch = "feature-behind";
495 yield* createGitBranch({ cwd: source, branch: featureBranch });
496 yield* checkoutGitBranch({ cwd: source, branch: featureBranch });
497 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
498 yield* git(source, ["add", "feature.txt"]);
499 yield* git(source, ["commit", "-m", "feature base"]);
500 yield* git(source, ["push", "-u", "origin", featureBranch]);
501 yield* checkoutGitBranch({ cwd: source, branch: defaultBranch });
502​
503 yield* git(clone, ["clone", remote, "."]);
504 yield* git(clone, ["config", "user.email", "test@test.com"]);
505 yield* git(clone, ["config", "user.name", "Test"]);
506 yield* git(clone, ["checkout", "-b", featureBranch, "--track", `origin/${featureBranch}`]);
507 yield* writeTextFile(path.join(clone, "feature.txt"), "feature from remote\n");
508 yield* git(clone, ["add", "feature.txt"]);
509 yield* git(clone, ["commit", "-m", "remote feature update"]);
510 yield* git(clone, ["push", "origin", featureBranch]);
511​
512 yield* checkoutGitBranch({ cwd: source, branch: featureBranch });
513 const core = yield* GitCore;
514 yield* Effect.promise(() =>
515 vi.waitFor(async () => {
516 const details = await Effect.runPromise(core.statusDetails(source));
517 expect(details.branch).toBe(featureBranch);
518 expect(details.aheadCount).toBe(0);
519 expect(details.behindCount).toBe(1);
520 }),
521 );
522 }),
523 );
524​
525 it.effect("keeps checkout successful when upstream refresh fails", () =>
526 Effect.gen(function* () {
527 const remote = yield* makeTmpDir();
528 const source = yield* makeTmpDir();
529 yield* git(remote, ["init", "--bare"]);
530​
531 yield* initRepoWithCommit(source);
532 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
533 (branch) => branch.current,
534 )!.name;
535 yield* git(source, ["remote", "add", "origin", remote]);
536 yield* git(source, ["push", "-u", "origin", defaultBranch]);
537​
538 const featureBranch = "feature-refresh-failure";
539 yield* git(source, ["branch", featureBranch]);
540 yield* git(source, ["checkout", featureBranch]);
541 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
542 yield* git(source, ["add", "feature.txt"]);
543 yield* git(source, ["commit", "-m", "feature base"]);
544 yield* git(source, ["push", "-u", "origin", featureBranch]);
545 yield* git(source, ["checkout", defaultBranch]);
546​
547 const realGitService = yield* GitService;
548 let refreshFetchAttempts = 0;
549 const core = yield* makeIsolatedGitCore({
550 execute: (input) => {
551 if (input.args[0] === "fetch") {
552 refreshFetchAttempts += 1;
553 return Effect.fail(
554 new GitCommandError({
555 operation: "git.test.refreshFailure",
556 command: `git ${input.args.join(" ")}`,
557 cwd: input.cwd,
558 detail: "simulated fetch timeout",
559 }),
560 );
561 }
562 return realGitService.execute(input);
563 },
564 });
565 yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
566 yield* Effect.promise(() =>
567 vi.waitFor(() => {
568 expect(refreshFetchAttempts).toBe(1);
569 }),
570 );
571 expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
572 }),
573 );
574​
575 it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
576 Effect.gen(function* () {
577 const remote = yield* makeTmpDir();
578 const source = yield* makeTmpDir();
579 yield* git(remote, ["init", "--bare"]);
580​
581 yield* initRepoWithCommit(source);
582 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
583 (branch) => branch.current,
584 )!.name;
585 yield* git(source, ["remote", "add", "origin", remote]);
586 yield* git(source, ["push", "-u", "origin", defaultBranch]);
587​
588 const featureBranch = "feature/scoped-fetch";
589 yield* git(source, ["checkout", "-b", featureBranch]);
590 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
591 yield* git(source, ["add", "feature.txt"]);
592 yield* git(source, ["commit", "-m", "feature base"]);
593 yield* git(source, ["push", "-u", "origin", featureBranch]);
594 yield* git(source, ["checkout", defaultBranch]);
595​
596 const realGitService = yield* GitService;
597 let fetchArgs: readonly string[] | null = null;
598 const core = yield* makeIsolatedGitCore({
599 execute: (input) => {
600 if (input.args[0] === "fetch") {
601 fetchArgs = [...input.args];
602 return Effect.succeed({ code: 0, stdout: "", stderr: "" });
603 }
604 return realGitService.execute(input);
605 },
606 });
607 yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
608 yield* Effect.promise(() =>
609 vi.waitFor(() => {
610 expect(fetchArgs).not.toBeNull();
611 }),
612 );
613​
614 expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
615 expect(fetchArgs).toEqual([
616 "fetch",
617 "--quiet",
618 "--no-tags",
619 "origin",
620 `+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
621 ]);
622 }),
623 );
624​
625 it.effect("returns checkout result before background upstream refresh completes", () =>
626 Effect.gen(function* () {
627 const remote = yield* makeTmpDir();
628 const source = yield* makeTmpDir();
629 yield* git(remote, ["init", "--bare"]);
630​
631 yield* initRepoWithCommit(source);
632 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
633 (branch) => branch.current,
634 )!.name;
635 yield* git(source, ["remote", "add", "origin", remote]);
636 yield* git(source, ["push", "-u", "origin", defaultBranch]);
637​
638 const featureBranch = "feature/background-refresh";
639 yield* git(source, ["checkout", "-b", featureBranch]);
640 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
641 yield* git(source, ["add", "feature.txt"]);
642 yield* git(source, ["commit", "-m", "feature base"]);
643 yield* git(source, ["push", "-u", "origin", featureBranch]);
644 yield* git(source, ["checkout", defaultBranch]);
645​
646 const realGitService = yield* GitService;
647 let fetchStarted = false;
648 let releaseFetch: () => void = () => undefined;
649 const waitForReleasePromise = new Promise<void>((resolve) => {
650 releaseFetch = resolve;
651 });
652 const core = yield* makeIsolatedGitCore({
653 execute: (input) => {
654 if (input.args[0] === "fetch") {
655 fetchStarted = true;
656 return Effect.promise(() =>
657 waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
658 );
659 }
660 return realGitService.execute(input);
661 },
662 });
663 yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
664 yield* Effect.promise(() =>
665 vi.waitFor(() => {
666 expect(fetchStarted).toBe(true);
667 }),
668 );
669 expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
670 releaseFetch();
671 }),
672 );
673​
674 it.effect("throws when branch does not exist", () =>
675 Effect.gen(function* () {
676 const tmp = yield* makeTmpDir();
677 yield* initRepoWithCommit(tmp);
678 const result = yield* Effect.result(checkoutGitBranch({ cwd: tmp, branch: "nonexistent" }));
679 expect(result._tag).toBe("Failure");
680 }),
681 );
682​
683 it.effect(
684 "does not silently checkout a local branch when a remote ref no longer exists",
685 () =>
686 Effect.gen(function* () {
687 const remote = yield* makeTmpDir();
688 const source = yield* makeTmpDir();
689 yield* git(remote, ["init", "--bare"]);
690​
691 yield* initRepoWithCommit(source);
692 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
693 (branch) => branch.current,
694 )!.name;
695 yield* git(source, ["remote", "add", "origin", remote]);
696 yield* git(source, ["push", "-u", "origin", defaultBranch]);
697​
698 yield* createGitBranch({ cwd: source, branch: "feature" });
699​
700 const checkoutResult = yield* Effect.result(
701 checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
702 );
703 expect(checkoutResult._tag).toBe("Failure");
704 expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
705 }),
706 );
707​
708 it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
709 Effect.gen(function* () {
710 const remote = yield* makeTmpDir();
711 const source = yield* makeTmpDir();
712 const remoteName = "my-org/upstream";
713 const featureBranch = "feature";
714 yield* git(remote, ["init", "--bare"]);
715​
716 yield* initRepoWithCommit(source);
717 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
718 (branch) => branch.current,
719 )!.name;
720 yield* git(source, ["remote", "add", remoteName, remote]);
721 yield* git(source, ["push", "-u", remoteName, defaultBranch]);
722​
723 yield* git(source, ["checkout", "-b", featureBranch]);
724 yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
725 yield* git(source, ["add", "feature.txt"]);
726 yield* git(source, ["commit", "-m", "feature commit"]);
727 yield* git(source, ["push", "-u", remoteName, featureBranch]);
728 yield* git(source, ["checkout", defaultBranch]);
729 yield* git(source, ["branch", "-D", featureBranch]);
730​
731 yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
732​
733 expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
734 }),
735 );
736​
737 it.effect(
738 "falls back to detached checkout when --track would conflict with an existing local branch",
739 () =>
740 Effect.gen(function* () {
741 const remote = yield* makeTmpDir();
742 const source = yield* makeTmpDir();
743 yield* git(remote, ["init", "--bare"]);
744​
745 yield* initRepoWithCommit(source);
746 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
747 (branch) => branch.current,
748 )!.name;
749 yield* git(source, ["remote", "add", "origin", remote]);
750 yield* git(source, ["push", "-u", "origin", defaultBranch]);
751​
752 // Keep local branch but remove tracking so `--track origin/<branch>`
753 // would attempt to create an already-existing local branch.
754 yield* git(source, ["branch", "--unset-upstream"]);
755​
756 yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
757​
758 const core = yield* GitCore;
759 const status = yield* core.statusDetails(source);
760 expect(status.branch).toBeNull();
761 }),
762 );
763​
764 it.effect("throws when checkout would overwrite uncommitted changes", () =>
765 Effect.gen(function* () {
766 const tmp = yield* makeTmpDir();
767 yield* initRepoWithCommit(tmp);
768 yield* createGitBranch({ cwd: tmp, branch: "other" });
769​
770 // Create a conflicting change: modify README on current branch
771 yield* writeTextFile(path.join(tmp, "README.md"), "modified\n");
772 yield* git(tmp, ["add", "README.md"]);
773​
774 // First, checkout other branch cleanly
775 yield* git(tmp, ["stash"]);
776 yield* checkoutGitBranch({ cwd: tmp, branch: "other" });
777 yield* writeTextFile(path.join(tmp, "README.md"), "other content\n");
778 yield* git(tmp, ["add", "."]);
779 yield* git(tmp, ["commit", "-m", "other change"]);
780​
781 // Go back to default branch
782 const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
783 (b) => !b.current,
784 )!.name;
785 yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
786​
787 // Make uncommitted changes to the same file
788 yield* writeTextFile(path.join(tmp, "README.md"), "conflicting local\n");
789​
790 // Checkout should fail due to uncommitted changes
791 const result = yield* Effect.result(checkoutGitBranch({ cwd: tmp, branch: "other" }));
792 expect(result._tag).toBe("Failure");
793 }),
794 );
795 });
796​
797 // ── createGitBranch ──
798​
799 describe("createGitBranch", () => {
800 it.effect("creates a new branch visible in listGitBranches", () =>
801 Effect.gen(function* () {
802 const tmp = yield* makeTmpDir();
803 yield* initRepoWithCommit(tmp);
804 yield* createGitBranch({ cwd: tmp, branch: "new-feature" });
805​
806 const result = yield* listGitBranches({ cwd: tmp });
807 expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
808 }),
809 );
810​
811 it.effect("throws when branch already exists", () =>
812 Effect.gen(function* () {
813 const tmp = yield* makeTmpDir();
814 yield* initRepoWithCommit(tmp);
815 yield* createGitBranch({ cwd: tmp, branch: "dupe" });
816 const result = yield* Effect.result(createGitBranch({ cwd: tmp, branch: "dupe" }));
817 expect(result._tag).toBe("Failure");
818 }),
819 );
820 });
821​
822 // ── createGitWorktree + removeGitWorktree ──
823​
824 describe("createGitWorktree", () => {
825 it.effect("creates a worktree with a new branch from the base branch", () =>
826 Effect.gen(function* () {
827 const tmp = yield* makeTmpDir();
828 yield* initRepoWithCommit(tmp);
829​
830 const wtPath = path.join(tmp, "worktree-out");
831 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
832 (b) => b.current,
833 )!.name;
834​
835 const result = yield* createGitWorktree({
836 cwd: tmp,
837 branch: currentBranch,
838 newBranch: "wt-branch",
839 path: wtPath,
840 });
841​
842 expect(result.worktree.path).toBe(wtPath);
843 expect(result.worktree.branch).toBe("wt-branch");
844 expect(existsSync(wtPath)).toBe(true);
845 expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
846​
847 // Clean up worktree before tmp dir disposal
848 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
849 }),
850 );
851​
852 it.effect("worktree has the new branch checked out", () =>
853 Effect.gen(function* () {
854 const tmp = yield* makeTmpDir();
855 yield* initRepoWithCommit(tmp);
856​
857 const wtPath = path.join(tmp, "wt-check-dir");
858 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
859 (b) => b.current,
860 )!.name;
861​
862 yield* createGitWorktree({
863 cwd: tmp,
864 branch: currentBranch,
865 newBranch: "wt-check",
866 path: wtPath,
867 });
868​
869 // Verify the worktree is on the new branch
870 const branchOutput = yield* git(wtPath, ["branch", "--show-current"]);
871 expect(branchOutput).toBe("wt-check");
872​
873 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
874 }),
875 );
876​
877 it.effect("throws when new branch name already exists", () =>
878 Effect.gen(function* () {
879 const tmp = yield* makeTmpDir();
880 yield* initRepoWithCommit(tmp);
881 yield* createGitBranch({ cwd: tmp, branch: "existing" });
882​
883 const wtPath = path.join(tmp, "wt-conflict");
884 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
885 (b) => b.current,
886 )!.name;
887​
888 const result = yield* Effect.result(
889 createGitWorktree({
890 cwd: tmp,
891 branch: currentBranch,
892 newBranch: "existing",
893 path: wtPath,
894 }),
895 );
896 expect(result._tag).toBe("Failure");
897 }),
898 );
899​
900 it.effect("listGitBranches from worktree cwd reports worktree branch as current", () =>
901 Effect.gen(function* () {
902 const tmp = yield* makeTmpDir();
903 yield* initRepoWithCommit(tmp);
904​
905 const wtPath = path.join(tmp, "wt-list-dir");
906 const mainBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
907 (b) => b.current,
908 )!.name;
909​
910 yield* createGitWorktree({
911 cwd: tmp,
912 branch: mainBranch,
913 newBranch: "wt-list",
914 path: wtPath,
915 });
916​
917 // listGitBranches from the worktree should show wt-list as current
918 const wtBranches = yield* listGitBranches({ cwd: wtPath });
919 expect(wtBranches.isRepo).toBe(true);
920 const wtCurrent = wtBranches.branches.find((b) => b.current);
921 expect(wtCurrent!.name).toBe("wt-list");
922​
923 // Main repo should still show the original branch as current
924 const mainBranches = yield* listGitBranches({ cwd: tmp });
925 const mainCurrent = mainBranches.branches.find((b) => b.current);
926 expect(mainCurrent!.name).toBe(mainBranch);
927​
928 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
929 }),
930 );
931​
932 it.effect("removeGitWorktree cleans up the worktree", () =>
933 Effect.gen(function* () {
934 const tmp = yield* makeTmpDir();
935 yield* initRepoWithCommit(tmp);
936​
937 const wtPath = path.join(tmp, "wt-remove-dir");
938 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
939 (b) => b.current,
940 )!.name;
941​
942 yield* createGitWorktree({
943 cwd: tmp,
944 branch: currentBranch,
945 newBranch: "wt-remove",
946 path: wtPath,
947 });
948 expect(existsSync(wtPath)).toBe(true);
949​
950 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
951 expect(existsSync(wtPath)).toBe(false);
952 }),
953 );
954​
955 it.effect("removeGitWorktree force removes a dirty worktree", () =>
956 Effect.gen(function* () {
957 const tmp = yield* makeTmpDir();
958 yield* initRepoWithCommit(tmp);
959​
960 const wtPath = path.join(tmp, "wt-dirty-dir");
961 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
962 (b) => b.current,
963 )!.name;
964​
965 yield* createGitWorktree({
966 cwd: tmp,
967 branch: currentBranch,
968 newBranch: "wt-dirty",
969 path: wtPath,
970 });
971 expect(existsSync(wtPath)).toBe(true);
972​
973 yield* writeTextFile(path.join(wtPath, "README.md"), "dirty change\n");
974​
975 const failedRemove = yield* Effect.result(removeGitWorktree({ cwd: tmp, path: wtPath }));
976 expect(failedRemove._tag).toBe("Failure");
977 expect(existsSync(wtPath)).toBe(true);
978​
979 yield* removeGitWorktree({ cwd: tmp, path: wtPath, force: true });
980 expect(existsSync(wtPath)).toBe(false);
981 }),
982 );
983 });
984​
985 // ── Full flow: local branch checkout ──
986​
987 describe("full flow: local branch checkout", () => {
988 it.effect("init → commit → create branch → checkout → verify current", () =>
989 Effect.gen(function* () {
990 const tmp = yield* makeTmpDir();
991 yield* initRepoWithCommit(tmp);
992 yield* createGitBranch({ cwd: tmp, branch: "feature-login" });
993 yield* checkoutGitBranch({ cwd: tmp, branch: "feature-login" });
994​
995 const result = yield* listGitBranches({ cwd: tmp });
996 const current = result.branches.find((b) => b.current);
997 expect(current!.name).toBe("feature-login");
998 }),
999 );
1000 });
1001​
1002 // ── Full flow: worktree creation from base branch ──
1003​
1004 describe("full flow: worktree creation", () => {
1005 it.effect("creates worktree with new branch from current branch", () =>
1006 Effect.gen(function* () {
1007 const tmp = yield* makeTmpDir();
1008 yield* initRepoWithCommit(tmp);
1009​
1010 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
1011 (b) => b.current,
1012 )!.name;
1013​
1014 const wtPath = path.join(tmp, "my-worktree");
1015 const result = yield* createGitWorktree({
1016 cwd: tmp,
1017 branch: currentBranch,
1018 newBranch: "feature-wt",
1019 path: wtPath,
1020 });
1021​
1022 // Worktree exists
1023 expect(existsSync(result.worktree.path)).toBe(true);
1024​
1025 // Main repo still on original branch
1026 const mainBranches = yield* listGitBranches({ cwd: tmp });
1027 const mainCurrent = mainBranches.branches.find((b) => b.current);
1028 expect(mainCurrent!.name).toBe(currentBranch);
1029​
1030 // Worktree is on the new branch
1031 const wtBranch = yield* git(wtPath, ["branch", "--show-current"]);
1032 expect(wtBranch).toBe("feature-wt");
1033​
1034 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
1035 }),
1036 );
1037 });
1038​
1039 // ── Full flow: thread switching simulation ──
1040​
1041 describe("full flow: thread switching (checkout toggling)", () => {
1042 it.effect("checkout a → checkout b → checkout a → current matches", () =>
1043 Effect.gen(function* () {
1044 const tmp = yield* makeTmpDir();
1045 yield* initRepoWithCommit(tmp);
1046 yield* createGitBranch({ cwd: tmp, branch: "branch-a" });
1047 yield* createGitBranch({ cwd: tmp, branch: "branch-b" });
1048​
1049 // Simulate switching to thread A's branch
1050 yield* checkoutGitBranch({ cwd: tmp, branch: "branch-a" });
1051 let branches = yield* listGitBranches({ cwd: tmp });
1052 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
1053​
1054 // Simulate switching to thread B's branch
1055 yield* checkoutGitBranch({ cwd: tmp, branch: "branch-b" });
1056 branches = yield* listGitBranches({ cwd: tmp });
1057 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b");
1058​
1059 // Switch back to thread A
1060 yield* checkoutGitBranch({ cwd: tmp, branch: "branch-a" });
1061 branches = yield* listGitBranches({ cwd: tmp });
1062 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
1063 }),
1064 );
1065 });
1066​
1067 // ── Full flow: checkout conflict ──
1068​
1069 describe("full flow: checkout conflict", () => {
1070 it.effect("uncommitted changes prevent checkout to a diverged branch", () =>
1071 Effect.gen(function* () {
1072 const tmp = yield* makeTmpDir();
1073 yield* initRepoWithCommit(tmp);
1074 yield* createGitBranch({ cwd: tmp, branch: "diverged" });
1075​
1076 // Make diverged branch have different file content
1077 yield* checkoutGitBranch({ cwd: tmp, branch: "diverged" });
1078 yield* writeTextFile(path.join(tmp, "README.md"), "diverged content\n");
1079 yield* git(tmp, ["add", "."]);
1080 yield* git(tmp, ["commit", "-m", "diverge"]);
1081​
1082 // Actually, let's just get back to the initial branch explicitly
1083 const allBranches = yield* listGitBranches({ cwd: tmp });
1084 const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name;
1085 yield* checkoutGitBranch({ cwd: tmp, branch: initialBranch });
1086​
1087 // Make local uncommitted changes to the same file
1088 yield* writeTextFile(path.join(tmp, "README.md"), "local uncommitted\n");
1089​
1090 // Attempt checkout should fail
1091 const failedCheckout = yield* Effect.result(
1092 checkoutGitBranch({ cwd: tmp, branch: "diverged" }),
1093 );
1094 expect(failedCheckout._tag).toBe("Failure");
1095​
1096 // Current branch should still be the initial one
1097 const result = yield* listGitBranches({ cwd: tmp });
1098 expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
1099 }),
1100 );
1101 });
1102​
1103 describe("GitCore", () => {
1104 it.effect("supports branch lifecycle operations through the service API", () =>
1105 Effect.gen(function* () {
1106 const tmp = yield* makeTmpDir();
1107 const core = yield* GitCore;
1108​
1109 yield* core.initRepo({ cwd: tmp });
1110 yield* git(tmp, ["config", "user.email", "test@test.com"]);
1111 yield* git(tmp, ["config", "user.name", "Test"]);
1112 yield* writeTextFile(path.join(tmp, "README.md"), "# test\n");
1113 yield* git(tmp, ["add", "."]);
1114 yield* git(tmp, ["commit", "-m", "initial commit"]);
1115​
1116 yield* core.createBranch({ cwd: tmp, branch: "feature/service-api" });
1117 yield* core.checkoutBranch({ cwd: tmp, branch: "feature/service-api" });
1118 const branches = yield* core.listBranches({ cwd: tmp });
1119​
1120 expect(branches.isRepo).toBe(true);
1121 expect(
1122 branches.branches.find((branch: { current: boolean; name: string }) => branch.current)
1123 ?.name,
1124 ).toBe("feature/service-api");
1125 }),
1126 );
1127​
1128 it.effect("reports status details and dirty state", () =>
1129 Effect.gen(function* () {
1130 const tmp = yield* makeTmpDir();
1131 yield* initRepoWithCommit(tmp);
1132 const core = yield* GitCore;
1133​
1134 const clean = yield* core.status({ cwd: tmp });
1135 expect(clean.hasWorkingTreeChanges).toBe(false);
1136 expect(clean.branch).toBeTruthy();
1137​
1138 yield* writeTextFile(path.join(tmp, "README.md"), "updated\n");
1139 const dirty = yield* core.statusDetails(tmp);
1140 expect(dirty.hasWorkingTreeChanges).toBe(true);
1141 }),
1142 );
1143​
1144 it.effect("includes command context when worktree removal fails", () =>
1145 Effect.gen(function* () {
1146 const tmp = yield* makeTmpDir();
1147 yield* initRepoWithCommit(tmp);
1148 const core = yield* GitCore;
1149 const missingWorktreePath = path.join(tmp, "missing-worktree");
1150​
1151 const removeResult = yield* Effect.result(
1152 core.removeWorktree({ cwd: tmp, path: missingWorktreePath }),
1153 );
1154 expect(removeResult._tag).toBe("Failure");
1155 if (removeResult._tag !== "Failure") {
1156 return;
1158 const message = removeResult.failure.message;
1159 expect(message).toContain("git worktree remove");
1160 expect(message).toContain(`cwd: ${tmp}`);
1161 expect(message).toContain(missingWorktreePath);
1162 }),
1163 );
1164​
1165 it.effect(
1166 "refreshes upstream before statusDetails so behind count reflects remote updates",
1167 () =>
1168 Effect.gen(function* () {
1169 const remote = yield* makeTmpDir();
1170 const source = yield* makeTmpDir();
1171 const clone = yield* makeTmpDir();
1172 yield* git(remote, ["init", "--bare"]);
1173​
1174 yield* initRepoWithCommit(source);
1175 const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
1176 (branch) => branch.current,
1177 )!.name;
1178 yield* git(source, ["remote", "add", "origin", remote]);
1179 yield* git(source, ["push", "-u", "origin", initialBranch]);
1180​
1181 yield* git(clone, ["clone", remote, "."]);
1182 yield* git(clone, ["config", "user.email", "test@test.com"]);
1183 yield* git(clone, ["config", "user.name", "Test"]);
1184 yield* git(clone, [
1185 "checkout",
1186 "-B",
1187 initialBranch,
1188 "--track",
1189 `origin/${initialBranch}`,
1190 ]);
1191 yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
1192 yield* git(clone, ["add", "CHANGELOG.md"]);
1193 yield* git(clone, ["commit", "-m", "remote update"]);
1194 yield* git(clone, ["push", "origin", initialBranch]);
1195​
1196 const core = yield* GitCore;
1197 const details = yield* core.statusDetails(source);
1198 expect(details.branch).toBe(initialBranch);
1199 expect(details.aheadCount).toBe(0);
1200 expect(details.behindCount).toBe(1);
1201 }),
1202 );
1203​
1204 it.effect("prepares commit context by auto-staging and creates commit", () =>
1205 Effect.gen(function* () {
1206 const tmp = yield* makeTmpDir();
1207 yield* initRepoWithCommit(tmp);
1208 const core = yield* GitCore;
1209​
1210 yield* writeTextFile(path.join(tmp, "README.md"), "new content\n");
1211 const context = yield* core.prepareCommitContext(tmp);
1212 expect(context).not.toBeNull();
1213 expect(context!.stagedSummary.length).toBeGreaterThan(0);
1214 expect(context!.stagedPatch.length).toBeGreaterThan(0);
1215​
1216 const created = yield* core.commit(tmp, "Add README update", "- include updated content");
1217 expect(created.commitSha.length).toBeGreaterThan(0);
1218 expect(yield* git(tmp, ["log", "-1", "--pretty=%s"])).toBe("Add README update");
1219 }),
1220 );
1221​
1222 it.effect("pushes with upstream setup and then skips when up to date", () =>
1223 Effect.gen(function* () {
1224 const tmp = yield* makeTmpDir();
1225 const remote = yield* makeTmpDir();
1226 yield* initRepoWithCommit(tmp);
1227 yield* git(remote, ["init", "--bare"]);
1228 yield* git(tmp, ["remote", "add", "origin", remote]);
1229 yield* createGitBranch({ cwd: tmp, branch: "feature/core-push" });
1230 yield* checkoutGitBranch({ cwd: tmp, branch: "feature/core-push" });
1231​
1232 yield* writeTextFile(path.join(tmp, "feature.txt"), "push me\n");
1233 const core = yield* GitCore;
1234 const context = yield* core.prepareCommitContext(tmp);
1235 expect(context).not.toBeNull();
1236 yield* core.commit(tmp, "Add feature file", "");
1237​
1238 const pushed = yield* core.pushCurrentBranch(tmp, null);
1239 expect(pushed.status).toBe("pushed");
1240 expect(pushed.setUpstream).toBe(true);
1241 expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
1242 "origin/feature/core-push",
1243 );
1244​
1245 const skipped = yield* core.pushCurrentBranch(tmp, null);
1246 expect(skipped.status).toBe("skipped_up_to_date");
1247 }),
1248 );
1249​
1250 it.effect("pulls behind branch and then reports up-to-date", () =>
1251 Effect.gen(function* () {
1252 const remote = yield* makeTmpDir();
1253 const source = yield* makeTmpDir();
1254 const clone = yield* makeTmpDir();
1255 yield* git(remote, ["init", "--bare"]);
1256​
1257 yield* initRepoWithCommit(source);
1258 const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
1259 (branch) => branch.current,
1260 )!.name;
1261 yield* git(source, ["remote", "add", "origin", remote]);
1262 yield* git(source, ["push", "-u", "origin", initialBranch]);
1263​
1264 yield* git(clone, ["clone", remote, "."]);
1265 yield* git(clone, ["config", "user.email", "test@test.com"]);
1266 yield* git(clone, ["config", "user.name", "Test"]);
1267 yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
1268 yield* git(clone, ["add", "CHANGELOG.md"]);
1269 yield* git(clone, ["commit", "-m", "remote update"]);
1270 yield* git(clone, ["push", "origin", initialBranch]);
1271​
1272 const core = yield* GitCore;
1273 const pulled = yield* core.pullCurrentBranch(source);
1274 expect(pulled.status).toBe("pulled");
1275 expect((yield* core.statusDetails(source)).behindCount).toBe(0);
1276​
1277 const skipped = yield* core.pullCurrentBranch(source);
1278 expect(skipped.status).toBe("skipped_up_to_date");
1279 }),
1280 );
1281​
1282 it.effect("top-level pullGitBranch rejects when no upstream exists", () =>
1283 Effect.gen(function* () {
1284 const tmp = yield* makeTmpDir();
1285 yield* initRepoWithCommit(tmp);
1286 const result = yield* Effect.result(pullGitBranch({ cwd: tmp }));
1287 expect(result._tag).toBe("Failure");
1288 if (result._tag === "Failure") {
1289 expect(result.failure.message.toLowerCase()).toContain("no upstream");
1291 }),
1292 );
1293​
1294 it.effect("lists branches when recency lookup fails", () =>
1295 Effect.gen(function* () {
1296 const tmp = yield* makeTmpDir();
1297 yield* initRepoWithCommit(tmp);
1298 const realGitService = yield* GitService;
1299 let didFailRecency = false;
1300 const core = yield* makeIsolatedGitCore({
1301 execute: (input) => {
1302 if (!didFailRecency && input.args[0] === "for-each-ref") {
1303 didFailRecency = true;
1304 return Effect.fail(
1305 new GitCommandError({
1306 operation: "git.test.listBranchesRecency",
1307 command: `git ${input.args.join(" ")}`,
1308 cwd: input.cwd,
1309 detail: "timeout",
1310 }),
1311 );
1313 return realGitService.execute(input);
1314 },
1315 });
1316​
1317 const result = yield* core.listBranches({ cwd: tmp });
1318​
1319 expect(result.isRepo).toBe(true);
1320 expect(result.branches.length).toBeGreaterThan(0);
1321 expect(result.branches[0]?.current).toBe(true);
1322 expect(didFailRecency).toBe(true);
1323 }),
1324 );
1325​
1326 it.effect("falls back to empty remote branch data when remote lookups fail", () =>
1327 Effect.gen(function* () {
1328 const tmp = yield* makeTmpDir();
1329 const remote = yield* makeTmpDir();
1330 yield* initRepoWithCommit(tmp);
1331 yield* git(remote, ["init", "--bare"]);
1332 yield* git(tmp, ["remote", "add", "origin", remote]);
1333​
1334 const realGitService = yield* GitService;
1335 let didFailRemoteBranches = false;
1336 let didFailRemoteNames = false;
1337 const core = yield* makeIsolatedGitCore({
1338 execute: (input) => {
1339 if (input.args.join(" ") === "branch --no-color --remotes") {
1340 didFailRemoteBranches = true;
1341 return Effect.fail(
1342 new GitCommandError({
1343 operation: "git.test.listBranchesRemoteBranches",
1344 command: `git ${input.args.join(" ")}`,
1345 cwd: input.cwd,
1346 detail: "remote unavailable",
1347 }),
1348 );
1350 if (input.args.join(" ") === "remote") {
1351 didFailRemoteNames = true;
1352 return Effect.fail(
1353 new GitCommandError({
1354 operation: "git.test.listBranchesRemoteNames",
1355 command: `git ${input.args.join(" ")}`,
1356 cwd: input.cwd,
1357 detail: "remote unavailable",
1358 }),
1359 );
1361 return realGitService.execute(input);
1362 },
1363 });
1364​
1365 const result = yield* core.listBranches({ cwd: tmp });
1366​
1367 expect(result.isRepo).toBe(true);
1368 expect(result.branches.length).toBeGreaterThan(0);
1369 expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
1370 expect(didFailRemoteBranches).toBe(true);
1371 expect(didFailRemoteNames).toBe(true);
1372 }),
1373 );
1374 });
1375});