-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathGitCore.test.ts
More file actions
1916 lines (1655 loc) · 74 KB
/
GitCore.test.ts
File metadata and controls
1916 lines (1655 loc) · 74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs, { existsSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect, vi } from "vitest";
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
import { GitCommandError } from "../Errors.ts";
import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
import { ServerConfig } from "../../config.ts";
// ── Helpers ──
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-core-test-" });
const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfigLayer),
Layer.provide(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer);
function makeTmpDir(
prefix = "git-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
}
function writeTextFile(
filePath: string,
contents: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(filePath, contents);
});
}
/** Run a raw git command for test setup (not under test). */
function git(
cwd: string,
args: ReadonlyArray<string>,
env?: NodeJS.ProcessEnv,
): Effect.Effect<string, GitCommandError, GitCore> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
operation: "GitCore.test.git",
cwd,
args,
...(env ? { env } : {}),
timeoutMs: 10_000,
});
return result.stdout.trim();
});
}
function runShellCommand(input: {
command: string;
cwd: string;
timeoutMs?: number;
maxOutputBytes?: number;
}): Effect.Effect<ProcessRunResult, Error> {
return Effect.promise(() => {
const shellPath =
process.platform === "win32"
? (process.env.ComSpec ?? "cmd.exe")
: (process.env.SHELL ?? "/bin/sh");
const args =
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
return runProcess(shellPath, args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? 30_000,
allowNonZeroExit: true,
maxBufferBytes: input.maxOutputBytes ?? 1_000_000,
outputMode: "truncate",
});
});
}
const makeIsolatedGitCore = (executeOverride: GitCoreShape["execute"]) =>
makeGitCore({ executeOverride }).pipe(
Effect.provide(Layer.provideMerge(ServerConfigLayer, NodeServices.layer)),
);
/** Create a repo with an initial commit so branches work. */
function initRepoWithCommit(
cwd: string,
): Effect.Effect<
{ initialBranch: string },
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
> {
return Effect.gen(function* () {
const core = yield* GitCore;
yield* core.initRepo({ cwd });
yield* git(cwd, ["config", "user.email", "test@test.com"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
const initialBranch = yield* git(cwd, ["branch", "--show-current"]);
return { initialBranch };
});
}
function initRepoWithCommitOnBranch(
cwd: string,
initialBranch: string,
): Effect.Effect<
void,
GitCommandError | PlatformError.PlatformError,
FileSystem.FileSystem | GitCore
> {
return Effect.gen(function* () {
yield* git(cwd, ["init", `--initial-branch=${initialBranch}`]);
yield* git(cwd, ["config", "user.email", "test@test.com"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
});
}
function commitWithDate(
cwd: string,
fileName: string,
fileContents: string,
dateIsoString: string,
message: string,
): Effect.Effect<
void,
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
> {
return Effect.gen(function* () {
yield* writeTextFile(path.join(cwd, fileName), fileContents);
yield* git(cwd, ["add", fileName]);
yield* git(cwd, ["commit", "-m", message], {
...process.env,
GIT_AUTHOR_DATE: dateIsoString,
GIT_COMMITTER_DATE: dateIsoString,
});
});
}
// ── Tests ──
it.layer(TestLayer)("git integration", (it) => {
describe("shell process execution", () => {
it.effect("caps captured output when maxOutputBytes is exceeded", () =>
Effect.gen(function* () {
const result = yield* runShellCommand({
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
cwd: process.cwd(),
timeoutMs: 10_000,
maxOutputBytes: 128,
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated || result.stderrTruncated).toBe(true);
}),
);
});
// ── initGitRepo ──
describe("initGitRepo", () => {
it.effect("creates a valid git repo", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* (yield* GitCore).initRepo({ cwd: tmp });
expect(existsSync(path.join(tmp, ".git"))).toBe(true);
}),
);
it.effect("listGitBranches reports isRepo: true after init + commit", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches.length).toBeGreaterThanOrEqual(1);
}),
);
});
// ── listGitBranches ──
describe("listGitBranches", () => {
it.effect("returns isRepo: false for non-git directory", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.isRepo).toBe(false);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches).toEqual([]);
}),
);
it.effect("returns the current branch with current: true", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
const current = result.branches.find((b) => b.current);
expect(current).toBeDefined();
expect(current!.current).toBe(true);
}),
);
it.effect(
"does not include detached HEAD pseudo-refs as branches",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
expect(result.branches.some((branch) => branch.current)).toBe(false);
}),
30_000,
);
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "older-branch" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" });
yield* commitWithDate(
tmp,
"older.txt",
"older branch change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"older branch change",
);
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: initialBranch });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" });
yield* commitWithDate(
tmp,
"newer.txt",
"newer branch change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer branch change",
);
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" });
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.branches[0]!.name).toBe("older-branch");
expect(result.branches[1]!.name).toBe("newer-branch");
}),
);
it.effect("keeps default branch right after current branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
yield* git(tmp, ["remote", "set-head", "origin", defaultBranch]);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "current-branch" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" });
yield* commitWithDate(
tmp,
"current.txt",
"current change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"current change",
);
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" });
yield* commitWithDate(
tmp,
"newer.txt",
"newer change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer change",
);
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" });
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.branches[0]!.name).toBe("current-branch");
expect(result.branches[1]!.name).toBe(defaultBranch);
expect(result.branches[2]!.name).toBe("newer-branch");
}),
);
it.effect("lists multiple branches after creating them", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
const names = result.branches.map((b) => b.name);
expect(names).toContain("feature-a");
expect(names).toContain("feature-b");
}),
);
it.effect("isDefault is false when no remote exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
}),
);
it.effect("lists local branches first and remote branches last", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/local-only" });
const remoteOnlyBranch = "feature/remote-only";
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch });
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(result.hasOriginRemote).toBe(true);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
);
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
true,
);
expect(
result.branches.some(
(branch) => branch.name === "feature/local-only" && !branch.isRemote,
),
).toBe(true);
expect(
result.branches.some(
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
),
).toBe(true);
}),
);
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
const remoteName = "my-org/upstream";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", remoteName, remote]);
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
const remoteOnlyBranch = "feature/remote-with-remote-name";
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
const remoteBranch = result.branches.find(
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
);
expect(remoteBranch).toBeDefined();
expect(remoteBranch?.isRemote).toBe(true);
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
});
// ── checkoutGitBranch ──
describe("checkoutGitBranch", () => {
it.effect("checks out an existing branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature" });
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
const current = result.branches.find((b) => b.current);
expect(current!.name).toBe("feature");
}),
);
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const clone = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
const featureBranch = "feature-behind";
yield* (yield* GitCore).createBranch({ cwd: source, branch: featureBranch });
yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch });
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature base"]);
yield* git(source, ["push", "-u", "origin", featureBranch]);
yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: defaultBranch });
yield* git(clone, ["clone", remote, "."]);
yield* git(clone, ["config", "user.email", "test@test.com"]);
yield* git(clone, ["config", "user.name", "Test"]);
yield* git(clone, ["checkout", "-b", featureBranch, "--track", `origin/${featureBranch}`]);
yield* writeTextFile(path.join(clone, "feature.txt"), "feature from remote\n");
yield* git(clone, ["add", "feature.txt"]);
yield* git(clone, ["commit", "-m", "remote feature update"]);
yield* git(clone, ["push", "origin", featureBranch]);
yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch });
const core = yield* GitCore;
yield* Effect.promise(() =>
vi.waitFor(async () => {
const details = await Effect.runPromise(core.statusDetails(source));
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
}),
);
}),
);
it.effect("keeps checkout successful when upstream refresh fails", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
const featureBranch = "feature-refresh-failure";
yield* git(source, ["branch", featureBranch]);
yield* git(source, ["checkout", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature base"]);
yield* git(source, ["push", "-u", "origin", featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let refreshFetchAttempts = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
refreshFetchAttempts += 1;
return Effect.fail(
new GitCommandError({
operation: "git.test.refreshFailure",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "simulated fetch timeout",
}),
);
}
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(refreshFetchAttempts).toBe(1);
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
}),
);
it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
const featureBranch = "feature/scoped-fetch";
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature base"]);
yield* git(source, ["push", "-u", "origin", featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
fetchArgs = [...input.args];
return Effect.succeed({ code: 0, stdout: "", stderr: "" });
}
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchArgs).not.toBeNull();
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
expect(fetchArgs).toEqual([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
]);
}),
);
it.effect("returns checkout result before background upstream refresh completes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
const featureBranch = "feature/background-refresh";
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature base"]);
yield* git(source, ["push", "-u", "origin", featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let fetchStarted = false;
let releaseFetch!: () => void;
const waitForReleasePromise = new Promise<void>((resolve) => {
releaseFetch = resolve;
});
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
fetchStarted = true;
return Effect.promise(() =>
waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
);
}
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchStarted).toBe(true);
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
releaseFetch();
}),
);
it.effect("throws when branch does not exist", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const result = yield* Effect.result(
(yield* GitCore).checkoutBranch({ cwd: tmp, branch: "nonexistent" }),
);
expect(result._tag).toBe("Failure");
}),
);
it.effect("does not silently checkout a local branch when a remote ref no longer exists", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* (yield* GitCore).createBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result(
(yield* GitCore).checkoutBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["push", "-u", remoteName, featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* (yield* GitCore).checkoutBranch({
cwd: source,
branch: `${remoteName}/${featureBranch}`,
});
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
}),
);
it.effect(
"falls back to detached checkout when --track would conflict with an existing local branch",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({
cwd: source,
})).branches.find((branch) => branch.current)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
// Keep local branch but remove tracking so `--track origin/<branch>`
// would attempt to create an already-existing local branch.
yield* git(source, ["branch", "--unset-upstream"]);
yield* (yield* GitCore).checkoutBranch({
cwd: source,
branch: `origin/${defaultBranch}`,
});
const core = yield* GitCore;
const status = yield* core.statusDetails(source);
expect(status.branch).toBeNull();
}),
);
it.effect("throws when checkout would overwrite uncommitted changes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "other" });
// Create a conflicting change: modify README on current branch
yield* writeTextFile(path.join(tmp, "README.md"), "modified\n");
yield* git(tmp, ["add", "README.md"]);
// First, checkout other branch cleanly
yield* git(tmp, ["stash"]);
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "other" });
yield* writeTextFile(path.join(tmp, "README.md"), "other content\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "-m", "other change"]);
// Go back to default branch
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(b) => !b.current,
)!.name;
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch });
// Make uncommitted changes to the same file
yield* writeTextFile(path.join(tmp, "README.md"), "conflicting local\n");
// Checkout should fail due to uncommitted changes
const result = yield* Effect.result(
(yield* GitCore).checkoutBranch({ cwd: tmp, branch: "other" }),
);
expect(result._tag).toBe("Failure");
}),
);
});
// ── createGitBranch ──
describe("createGitBranch", () => {
it.effect("creates a new branch visible in listGitBranches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "new-feature" });
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
}),
);
it.effect("throws when branch already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "dupe" });
const result = yield* Effect.result(
(yield* GitCore).createBranch({ cwd: tmp, branch: "dupe" }),
);
expect(result._tag).toBe("Failure");
}),
);
});
// ── renameGitBranch ──
describe("renameGitBranch", () => {
it.effect("renames the current branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/old-name" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/old-name" });
const renamed = yield* (yield* GitCore).renameBranch({
cwd: tmp,
oldBranch: "feature/old-name",
newBranch: "feature/new-name",
});
expect(renamed.branch).toBe("feature/new-name");
const branches = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(branches.branches.some((branch) => branch.name === "feature/old-name")).toBe(false);
const current = branches.branches.find((branch) => branch.current);
expect(current?.name).toBe("feature/new-name");
}),
);
it.effect("returns success without git invocation when old/new names match", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const current = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(b) => b.current,
)!;
const renamed = yield* (yield* GitCore).renameBranch({
cwd: tmp,
oldBranch: current.name,
newBranch: current.name,
});
expect(renamed.branch).toBe(current.name);
}),
);
it.effect("appends numeric suffix when target branch already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "okcode/feat/session" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "okcode/tmp-working" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "okcode/tmp-working" });
const renamed = yield* (yield* GitCore).renameBranch({
cwd: tmp,
oldBranch: "okcode/tmp-working",
newBranch: "okcode/feat/session",
});
expect(renamed.branch).toBe("okcode/feat/session-1");
const branches = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(branches.branches.some((branch) => branch.name === "okcode/feat/session")).toBe(
true,
);
expect(branches.branches.some((branch) => branch.name === "okcode/feat/session-1")).toBe(
true,
);
const current = branches.branches.find((branch) => branch.current);
expect(current?.name).toBe("okcode/feat/session-1");
}),
);
it.effect("increments suffix until it finds an available branch name", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "okcode/feat/session" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "okcode/feat/session-1" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "okcode/tmp-working" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "okcode/tmp-working" });
const renamed = yield* (yield* GitCore).renameBranch({
cwd: tmp,
oldBranch: "okcode/tmp-working",
newBranch: "okcode/feat/session",
});
expect(renamed.branch).toBe("okcode/feat/session-2");
}),
);
it.effect("uses '--' separator for branch rename arguments", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/old-name" });
yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/old-name" });
const realGitCore = yield* GitCore;
let renameArgs: ReadonlyArray<string> | null = null;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "branch" && input.args[1] === "-m") {
renameArgs = [...input.args];
}
return realGitCore.execute(input);
});
const renamed = yield* core.renameBranch({
cwd: tmp,
oldBranch: "feature/old-name",
newBranch: "feature/new-name",
});
expect(renamed.branch).toBe("feature/new-name");
expect(renameArgs).toEqual(["branch", "-m", "--", "feature/old-name", "feature/new-name"]);
}),
);
});
// ── createGitWorktree + removeGitWorktree ──
describe("createGitWorktree", () => {
it.effect("auto-detects the current branch when the requested base branch is missing", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommitOnBranch(tmp, "master");
const core = yield* GitCore;
const wtPath = path.join(tmp, "worktree-missing-base");
const result = yield* core.createWorktree({
cwd: tmp,
branch: "main",
newBranch: "wt-missing-base",
path: wtPath,
});
expect(result.worktree.path).toBe(wtPath);
expect(result.worktree.branch).toBe("wt-missing-base");
expect(result.worktree.baseBranch).toBe("master");
expect(existsSync(wtPath)).toBe(true);
expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
expect(yield* git(wtPath, ["branch", "--show-current"])).toBe("wt-missing-base");
yield* core.removeWorktree({ cwd: tmp, path: wtPath });
}),
);
it.effect("rejects an unborn base branch with a helpful solution", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const core = yield* GitCore;
yield* core.initRepo({ cwd: tmp });
const wtPath = path.join(tmp, "worktree-unborn-base");
const error = yield* Effect.flip(
core.createWorktree({
cwd: tmp,
branch: "main",
newBranch: "wt-unborn-base",
path: wtPath,
}),
);
expect(error).toBeInstanceOf(GitCommandError);
expect(error.message).toContain("Base branch 'main' does not resolve to a commit yet.");
expect(error.message).toContain(
"Create the first commit or switch to Local mode before starting a worktree thread.",
);
}),
);
it.effect("creates a worktree with a new branch from the base branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const wtPath = path.join(tmp, "worktree-out");
const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(b) => b.current,
)!.name;
const result = yield* (yield* GitCore).createWorktree({
cwd: tmp,
branch: currentBranch,
newBranch: "wt-branch",
path: wtPath,
});
expect(result.worktree.path).toBe(wtPath);
expect(result.worktree.branch).toBe("wt-branch");
expect(existsSync(wtPath)).toBe(true);
expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
// Clean up worktree before tmp dir disposal
yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath });
}),
);
it.effect("worktree has the new branch checked out", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const wtPath = path.join(tmp, "wt-check-dir");
const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(
(b) => b.current,
)!.name;
yield* (yield* GitCore).createWorktree({
cwd: tmp,
branch: currentBranch,
newBranch: "wt-check",
path: wtPath,
});
// Verify the worktree is on the new branch
const branchOutput = yield* git(wtPath, ["branch", "--show-current"]);
expect(branchOutput).toBe("wt-check");