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

GitVcsDriverCore.test.ts

810 lines31.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it, describe } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Path from "effect/Path";
7import * as PlatformError from "effect/PlatformError";
8import * as Scope from "effect/Scope";
9​
10import { GitCommandError } from "@t3tools/contracts";
11import { ServerConfig } from "../config.ts";
12import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
13import * as GitVcsDriver from "./GitVcsDriver.ts";
14​
15const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
16 prefix: "t3-git-vcs-driver-test-",
17});
18const TestLayer = GitVcsDriver.layer.pipe(
19 Layer.provide(ServerConfigLayer),
20 Layer.provideMerge(NodeServices.layer),
21);
22​
23const makeTmpDir = (
24 prefix = "git-vcs-driver-test-",
25): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
26 Effect.gen(function* () {
27 const fileSystem = yield* FileSystem.FileSystem;
28 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
29 });
30​
31const writeTextFile = (
32 cwd: string,
33 relativePath: string,
34 contents: string,
35): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> =>
36 Effect.gen(function* () {
37 const fileSystem = yield* FileSystem.FileSystem;
38 const pathService = yield* Path.Path;
39 const filePath = pathService.join(cwd, relativePath);
40 yield* fileSystem.makeDirectory(pathService.dirname(filePath), { recursive: true });
41 yield* fileSystem.writeFileString(filePath, contents);
42 });
43​
44const git = (
45 cwd: string,
46 args: ReadonlyArray<string>,
47 env?: NodeJS.ProcessEnv,
48): Effect.Effect<string, GitCommandError, GitVcsDriver.GitVcsDriver> =>
49 Effect.gen(function* () {
50 const driver = yield* GitVcsDriver.GitVcsDriver;
51 const result = yield* driver.execute({
52 operation: "GitVcsDriver.test.git",
53 cwd,
54 args,
55 ...(env ? { env } : {}),
56 timeoutMs: 10_000,
57 });
58 return result.stdout.trim();
59 });
60​
61const initRepoWithCommit = (
62 cwd: string,
63): Effect.Effect<
64 { readonly initialBranch: string },
65 GitCommandError | PlatformError.PlatformError,
66 GitVcsDriver.GitVcsDriver | FileSystem.FileSystem | Path.Path
67> =>
68 Effect.gen(function* () {
69 const driver = yield* GitVcsDriver.GitVcsDriver;
70 yield* driver.initRepo({ cwd });
71 yield* git(cwd, ["config", "user.email", "test@test.com"]);
72 yield* git(cwd, ["config", "user.name", "Test"]);
73 yield* writeTextFile(cwd, "README.md", "# test\n");
74 yield* git(cwd, ["add", "."]);
75 yield* git(cwd, ["commit", "-m", "initial commit"]);
76 const initialBranch = yield* git(cwd, ["branch", "--show-current"]);
77 return { initialBranch };
78 });
79​
80it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
81 describe("structured errors", () => {
82 it.effect("preserves structured spawn context and the platform cause", () =>
83 Effect.gen(function* () {
84 const parent = yield* makeTmpDir();
85 const pathService = yield* Path.Path;
86 const cwd = pathService.join(parent, "missing");
87 const driver = yield* GitVcsDriver.GitVcsDriver;
88​
89 const error = yield* driver
90 .execute({
91 operation: "GitVcsDriver.test.missingCwd",
92 cwd,
93 args: ["status", "--short"],
94 })
95 .pipe(Effect.flip);
96​
97 assert.deepInclude(error, {
98 _tag: "GitCommandError",
99 operation: "GitVcsDriver.test.missingCwd",
100 command: "git",
101 argumentCount: 2,
102 cwd,
103 detail: "Failed to spawn Git process.",
104 });
105 if (!(error.cause instanceof PlatformError.PlatformError)) {
106 return assert.fail("expected the original platform error cause");
107 }
108 assert.equal(error.cause.reason._tag, "NotFound");
109 assert.notInclude(error.detail, error.cause.message);
110 }),
111 );
112​
113 it.effect("does not retain git arguments or stderr in command failures", () =>
114 Effect.gen(function* () {
115 const cwd = yield* makeTmpDir();
116 const driver = yield* GitVcsDriver.GitVcsDriver;
117 yield* driver.initRepo({ cwd });
118​
119 const secret = "secret-token-value";
120 const error = yield* driver
121 .execute({
122 operation: "GitVcsDriver.test.redactedFailure",
123 cwd,
124 args: ["status", `--unknown-option=${secret}`],
125 })
126 .pipe(Effect.flip);
127​
128 assert.deepInclude(error, {
129 _tag: "GitCommandError",
130 operation: "GitVcsDriver.test.redactedFailure",
131 command: "git",
132 argumentCount: 2,
133 cwd,
134 });
135 assert.isNumber(error.exitCode);
136 assert.isAbove(error.stderrLength ?? 0, 0);
137 assert.notInclude(error.detail, secret);
138 assert.notInclude(error.message, secret);
139 assert.notProperty(error, "args");
140 assert.notProperty(error, "stderr");
141 }),
142 );
143​
144 it.effect("recovers a structurally identified missing cwd as a non-repository", () =>
145 Effect.gen(function* () {
146 const parent = yield* makeTmpDir();
147 const pathService = yield* Path.Path;
148 const cwd = pathService.join(parent, "missing");
149 const driver = yield* GitVcsDriver.GitVcsDriver;
150​
151 const [localStatus, remoteStatus, refs] = yield* Effect.all([
152 driver.statusDetails(cwd),
153 driver.statusDetailsRemote(cwd, { refreshUpstream: false }),
154 driver.listRefs({ cwd }),
155 ]);
156​
157 assert.equal(localStatus.isRepo, false);
158 assert.equal(remoteStatus.isRepo, false);
159 assert.equal(refs.isRepo, false);
160 assert.deepStrictEqual(refs.refs, []);
161 }),
162 );
163​
164 it.effect("does not wrap a remove-worktree command failure in a synthetic error", () =>
165 Effect.gen(function* () {
166 const cwd = yield* makeTmpDir();
167 const pathService = yield* Path.Path;
168 const missingWorktree = pathService.join(cwd, "missing-worktree");
169 const driver = yield* GitVcsDriver.GitVcsDriver;
170 yield* driver.initRepo({ cwd });
171​
172 const error = yield* driver
173 .removeWorktree({ cwd, path: missingWorktree })
174 .pipe(Effect.flip);
175​
176 assert.deepInclude(error, {
177 _tag: "GitCommandError",
178 operation: "GitVcsDriver.removeWorktree",
179 command: "git",
180 argumentCount: 3,
181 cwd,
182 });
183 assert.notProperty(error, "cause");
184 assert.notInclude(error.detail, "Git command failed in");
185 }),
186 );
187 });
188​
189 describe("review diff previews", () => {
190 it.effect("drops an unterminated path from truncated NUL-separated git output", () =>
191 Effect.sync(() => {
192 const paths = splitNullSeparatedGitStdoutPaths({
193 stdout: "complete.txt\0partial",
194 stdoutTruncated: true,
195 });
196​
197 assert.deepStrictEqual(paths, ["complete.txt"]);
198 }),
199 );
200​
201 it.effect("keeps the final path when NUL-separated git output is complete", () =>
202 Effect.sync(() => {
203 const paths = splitNullSeparatedGitStdoutPaths({
204 stdout: "complete.txt\0final.txt",
205 stdoutTruncated: false,
206 });
207​
208 assert.deepStrictEqual(paths, ["complete.txt", "final.txt"]);
209 }),
210 );
211​
212 it.effect("honors whitespace filtering for worktree and branch previews", () =>
213 Effect.gen(function* () {
214 const cwd = yield* makeTmpDir();
215 const { initialBranch } = yield* initRepoWithCommit(cwd);
216 const driver = yield* GitVcsDriver.GitVcsDriver;
217 yield* git(cwd, ["checkout", "-b", "feature/whitespace"]);
218 yield* writeTextFile(cwd, "README.md", "# test\n");
219 yield* git(cwd, ["add", "README.md"]);
220 yield* git(cwd, ["commit", "-m", "change whitespace"]);
221 yield* writeTextFile(cwd, "README.md", "# test\n");
222​
223 const included = yield* driver.getReviewDiffPreview({
224 cwd,
225 baseRef: initialBranch,
226 ignoreWhitespace: false,
227 });
228 const ignored = yield* driver.getReviewDiffPreview({
229 cwd,
230 baseRef: initialBranch,
231 ignoreWhitespace: true,
232 });
233​
234 assert.isNotEmpty(included.sources.find((source) => source.kind === "working-tree")?.diff);
235 assert.isNotEmpty(included.sources.find((source) => source.kind === "branch-range")?.diff);
236 assert.strictEqual(
237 ignored.sources.find((source) => source.kind === "working-tree")?.diff,
238 "",
239 );
240 assert.strictEqual(
241 ignored.sources.find((source) => source.kind === "branch-range")?.diff,
242 "",
243 );
244 }),
245 );
246 });
247​
248 describe("repository status", () => {
249 it.effect("reports non-repository directories without failing", () =>
250 Effect.gen(function* () {
251 const cwd = yield* makeTmpDir();
252 const driver = yield* GitVcsDriver.GitVcsDriver;
253​
254 const refs = yield* driver.listRefs({ cwd });
255 assert.equal(refs.isRepo, false);
256 assert.deepStrictEqual(refs.refs, []);
257 }),
258 );
259​
260 it.effect("reports refName and dirty state for a repository", () =>
261 Effect.gen(function* () {
262 const cwd = yield* makeTmpDir();
263 const { initialBranch } = yield* initRepoWithCommit(cwd);
264 yield* writeTextFile(cwd, "feature.ts", "export const value = 1;\n");
265​
266 const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
267​
268 assert.equal(status.isRepo, true);
269 assert.equal(status.branch, initialBranch);
270 assert.equal(status.hasWorkingTreeChanges, true);
271 assert.include(
272 status.workingTree.files.map((file) => file.path),
273 "feature.ts",
274 );
275 }),
276 );
277​
278 it.effect("reports default-branch delta separately from upstream delta", () =>
279 Effect.gen(function* () {
280 const cwd = yield* makeTmpDir();
281 const remote = yield* makeTmpDir("git-vcs-driver-remote-");
282 const { initialBranch } = yield* initRepoWithCommit(cwd);
283 yield* git(remote, ["init", "--bare"]);
284 yield* git(cwd, ["remote", "add", "origin", remote]);
285 yield* git(cwd, ["push", "-u", "origin", initialBranch]);
286 yield* git(cwd, ["checkout", "-b", "feature/synced"]);
287 yield* writeTextFile(cwd, "feature.txt", "feature\n");
288 yield* git(cwd, ["add", "feature.txt"]);
289 yield* git(cwd, ["commit", "-m", "feature commit"]);
290 yield* git(cwd, ["push", "-u", "origin", "feature/synced"]);
291​
292 const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
293​
294 assert.equal(status.hasUpstream, true);
295 assert.equal(status.aheadCount, 0);
296 assert.equal(status.behindCount, 0);
297 assert.equal(status.aheadOfDefaultCount, 1);
298 }),
299 );
300​
301 it.effect("reports remote divergence without reading working-tree details", () =>
302 Effect.gen(function* () {
303 const cwd = yield* makeTmpDir();
304 const remote = yield* makeTmpDir("git-vcs-driver-remote-");
305 const { initialBranch } = yield* initRepoWithCommit(cwd);
306 yield* git(remote, ["init", "--bare"]);
307 yield* git(cwd, ["remote", "add", "origin", remote]);
308 yield* git(cwd, ["push", "-u", "origin", initialBranch]);
309 yield* git(cwd, ["checkout", "-b", "feature/remote-status"]);
310 yield* writeTextFile(cwd, "feature.txt", "feature\n");
311 yield* git(cwd, ["add", "feature.txt"]);
312 yield* git(cwd, ["commit", "-m", "feature commit"]);
313 yield* git(cwd, ["push", "-u", "origin", "feature/remote-status"]);
314 yield* writeTextFile(cwd, "untracked.txt", "local-only\n");
315​
316 const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
317​
318 assert.equal(status.isRepo, true);
319 assert.equal(status.branch, "feature/remote-status");
320 assert.equal(status.hasUpstream, true);
321 assert.equal(status.aheadCount, 0);
322 assert.equal(status.behindCount, 0);
323 assert.equal(status.aheadOfDefaultCount, 1);
324 assert.notProperty(status, "workingTree");
325 assert.notProperty(status, "hasWorkingTreeChanges");
326 }),
327 );
328​
329 it.effect("can read cached remote divergence without fetching upstream", () =>
330 Effect.gen(function* () {
331 const cwd = yield* makeTmpDir();
332 const remote = yield* makeTmpDir("git-vcs-driver-remote-");
333 const updater = yield* makeTmpDir("git-vcs-driver-updater-");
334 const { initialBranch } = yield* initRepoWithCommit(cwd);
335 yield* git(remote, ["init", "--bare"]);
336 yield* git(cwd, ["remote", "add", "origin", remote]);
337 yield* git(cwd, ["push", "-u", "origin", initialBranch]);
338​
339 yield* git(updater, ["clone", remote, "."]);
340 yield* git(updater, ["config", "user.email", "test@test.com"]);
341 yield* git(updater, ["config", "user.name", "Test"]);
342 yield* writeTextFile(updater, "remote.txt", "remote\n");
343 yield* git(updater, ["add", "remote.txt"]);
344 yield* git(updater, ["commit", "-m", "remote commit"]);
345 yield* git(updater, ["push", "origin", initialBranch]);
346​
347 const driver = yield* GitVcsDriver.GitVcsDriver;
348 const cachedStatus = yield* driver.statusDetailsRemote(cwd, {
349 refreshUpstream: false,
350 });
351 const refreshedStatus = yield* driver.statusDetailsRemote(cwd);
352​
353 assert.equal(cachedStatus.behindCount, 0);
354 assert.equal(refreshedStatus.behindCount, 1);
355 }),
356 );
357​
358 it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () =>
359 Effect.gen(function* () {
360 const cwd = yield* makeTmpDir();
361 const origin = yield* makeTmpDir("git-vcs-driver-origin-");
362 const upstream = yield* makeTmpDir("git-vcs-driver-upstream-");
363 yield* initRepoWithCommit(cwd);
364 yield* git(origin, ["init", "--bare"]);
365 yield* git(upstream, ["init", "--bare"]);
366 yield* git(cwd, ["branch", "-M", "main"]);
367 yield* git(cwd, ["remote", "add", "origin", origin]);
368 yield* git(cwd, ["remote", "add", "upstream", upstream]);
369 yield* git(cwd, ["push", "origin", "main"]);
370 yield* git(cwd, ["push", "upstream", "main"]);
371 yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
372 yield* git(cwd, ["checkout", "-b", "release"]);
373 yield* writeTextFile(cwd, "release.txt", "release\n");
374 yield* git(cwd, ["add", "release.txt"]);
375 yield* git(cwd, ["commit", "-m", "release commit"]);
376 yield* git(cwd, ["push", "-u", "upstream", "release"]);
377 yield* git(cwd, [
378 "symbolic-ref",
379 "refs/remotes/upstream/HEAD",
380 "refs/remotes/upstream/release",
381 ]);
382​
383 const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
384​
385 assert.equal(status.branch, "release");
386 assert.equal(status.upstreamRef, "upstream/release");
387 assert.equal(status.isDefaultBranch, false);
388 }),
389 );
390​
391 it.effect("makes background upstream status fetches non-interactive", () =>
392 Effect.gen(function* () {
393 const cwd = yield* makeTmpDir();
394 const tempDir = yield* makeTmpDir("git-vcs-driver-ssh-env-");
395 const { initialBranch } = yield* initRepoWithCommit(cwd);
396 const fileSystem = yield* FileSystem.FileSystem;
397 const pathService = yield* Path.Path;
398 const sshLogPath = pathService.join(tempDir, "ssh-env.txt");
399 const sshWrapperPath = pathService.join(tempDir, "ssh-wrapper.sh");
400 const envKeys = [
401 "GCM_INTERACTIVE",
402 "GIT_ASKPASS",
403 "GIT_SSH",
404 "GIT_TERMINAL_PROMPT",
405 "SSH_ASKPASS",
406 "SSH_ASKPASS_REQUIRE",
407 "T3_TEST_SSH_ASKPASS_LOG",
408 ] as const;
409 const previousEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
410​
411 yield* fileSystem.writeFileString(
412 sshWrapperPath,
413 [
414 "#!/bin/sh",
415 'printf "GCM_INTERACTIVE=%s\\n" "${GCM_INTERACTIVE:-}" > "$T3_TEST_SSH_ASKPASS_LOG"',
416 'printf "GIT_ASKPASS=%s\\n" "${GIT_ASKPASS:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
417 'printf "GIT_TERMINAL_PROMPT=%s\\n" "${GIT_TERMINAL_PROMPT:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
418 'printf "SSH_ASKPASS=%s\\n" "${SSH_ASKPASS:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
419 'printf "SSH_ASKPASS_REQUIRE=%s\\n" "${SSH_ASKPASS_REQUIRE:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
420 "exit 1",
421 "",
422 ].join("\n"),
423 );
424 yield* fileSystem.chmod(sshWrapperPath, 0o755);
425 yield* git(cwd, ["remote", "add", "origin", "ssh://example.invalid/repo.git"]);
426 yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]);
427 yield* git(cwd, ["branch", "--set-upstream-to", `origin/${initialBranch}`]);
428​
429 yield* Effect.gen(function* () {
430 process.env.GIT_SSH = sshWrapperPath;
431 process.env.GCM_INTERACTIVE = "always";
432 process.env.GIT_ASKPASS = "git-askpass";
433 process.env.GIT_TERMINAL_PROMPT = "1";
434 process.env.SSH_ASKPASS = "ssh-askpass";
435 process.env.SSH_ASKPASS_REQUIRE = "force";
436 process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
437​
438 yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
439​
440 assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [
441 "GCM_INTERACTIVE=never",
442 "GIT_ASKPASS=",
443 "GIT_TERMINAL_PROMPT=0",
444 "SSH_ASKPASS=",
445 "SSH_ASKPASS_REQUIRE=never",
446 ]);
447 }).pipe(
448 Effect.ensuring(
449 Effect.sync(() => {
450 for (const key of envKeys) {
451 const previous = previousEnv.get(key);
452 if (previous === undefined) {
453 delete process.env[key];
454 } else {
455 process.env[key] = previous;
456 }
457 }
458 }),
459 ),
460 );
461 }),
462 );
463​
464 it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
465 Effect.gen(function* () {
466 const cwd = yield* makeTmpDir();
467 const remote = yield* makeTmpDir("git-vcs-driver-remote-");
468 const { initialBranch } = yield* initRepoWithCommit(cwd);
469 yield* git(remote, ["init", "--bare"]);
470 yield* git(cwd, ["remote", "add", "origin", remote]);
471 yield* git(cwd, ["push", "-u", "origin", initialBranch]);
472 yield* git(cwd, ["checkout", "-b", "feature/no-upstream"]);
473 yield* writeTextFile(cwd, "feature.txt", "feature\n");
474 yield* git(cwd, ["add", "feature.txt"]);
475 yield* git(cwd, ["commit", "-m", "feature commit"]);
476​
477 const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
478​
479 assert.equal(status.hasUpstream, false);
480 assert.equal(status.aheadCount, 1);
481 assert.equal(status.behindCount, 0);
482 assert.equal(status.aheadOfDefaultCount, 1);
483 }),
484 );
485 });
486​
487 describe("refName operations", () => {
488 it.effect("optionally includes remote refs that match local branches", () =>
489 Effect.gen(function* () {
490 const cwd = yield* makeTmpDir();
491 const remote = yield* makeTmpDir("git-vcs-driver-remote-");
492 const { initialBranch } = yield* initRepoWithCommit(cwd);
493 yield* git(remote, ["init", "--bare"]);
494 yield* git(cwd, ["remote", "add", "origin", remote]);
495 yield* git(cwd, ["push", "-u", "origin", initialBranch]);
496 const driver = yield* GitVcsDriver.GitVcsDriver;
497​
498 const deduplicated = yield* driver.listRefs({ cwd });
499 assert.equal(
500 deduplicated.refs.some((ref) => ref.name === `origin/${initialBranch}`),
501 false,
502 );
503​
504 const complete = yield* driver.listRefs({ cwd, includeMatchingRemoteRefs: true });
505 assert.equal(
506 complete.refs.some((ref) => ref.name === initialBranch),
507 true,
508 );
509 assert.equal(
510 complete.refs.some((ref) => ref.name === `origin/${initialBranch}`),
511 true,
512 );
513​
514 const remoteOnly = yield* driver.listRefs({
515 cwd,
516 includeMatchingRemoteRefs: true,
517 refKind: "remote",
518 limit: 1,
519 });
520 assert.equal(remoteOnly.refs.length, 1);
521 assert.equal(remoteOnly.refs[0]?.name, `origin/${initialBranch}`);
522 assert.equal(remoteOnly.refs[0]?.isRemote, true);
523 }),
524 );
525​
526 it.effect("creates, checks out, renames, and lists refs", () =>
527 Effect.gen(function* () {
528 const cwd = yield* makeTmpDir();
529 yield* initRepoWithCommit(cwd);
530 const driver = yield* GitVcsDriver.GitVcsDriver;
531​
532 yield* driver.createRef({ cwd, refName: "feature/original" });
533 const switchRef = yield* driver.switchRef({ cwd, refName: "feature/original" });
534 assert.equal(switchRef.refName, "feature/original");
535​
536 const renamed = yield* driver.renameBranch({
537 cwd,
538 oldBranch: "feature/original",
539 newBranch: "feature/renamed",
540 });
541 assert.equal(renamed.branch, "feature/renamed");
542 assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/renamed");
543​
544 const refs = yield* driver.listRefs({ cwd });
545 assert.equal(
546 refs.refs.find((refName) => refName.name === "feature/renamed")?.current,
547 true,
548 );
549 }),
550 );
551​
552 it.effect("returns the existing refName when rename source and target match", () =>
553 Effect.gen(function* () {
554 const cwd = yield* makeTmpDir();
555 yield* initRepoWithCommit(cwd);
556 const driver = yield* GitVcsDriver.GitVcsDriver;
557​
558 const current = yield* git(cwd, ["branch", "--show-current"]);
559 const result = yield* driver.renameBranch({
560 cwd,
561 oldBranch: current,
562 newBranch: current,
563 });
564​
565 assert.equal(result.branch, current);
566 }),
567 );
568 });
569​
570 describe("worktree operations", () => {
571 it.effect("creates and removes a worktree for a new refName", () =>
572 Effect.gen(function* () {
573 const cwd = yield* makeTmpDir();
574 const { initialBranch } = yield* initRepoWithCommit(cwd);
575 const pathService = yield* Path.Path;
576 const worktreePath = pathService.join(
577 yield* makeTmpDir("git-worktrees-"),
578 "feature-worktree",
579 );
580 const driver = yield* GitVcsDriver.GitVcsDriver;
581​
582 const created = yield* driver.createWorktree({
583 cwd,
584 path: worktreePath,
585 refName: initialBranch,
586 newRefName: "feature/worktree",
587 });
588​
589 assert.equal(created.worktree.path, worktreePath);
590 assert.equal(created.worktree.refName, "feature/worktree");
591 assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "feature/worktree");
592​
593 yield* driver.removeWorktree({ cwd, path: worktreePath });
594 const fileSystem = yield* FileSystem.FileSystem;
595 assert.equal(yield* fileSystem.exists(worktreePath), false);
596 }),
597 );
598 });
599​
600 describe("commit context", () => {
601 it.effect("stages selected files and commits only those files", () =>
602 Effect.gen(function* () {
603 const cwd = yield* makeTmpDir();
604 yield* initRepoWithCommit(cwd);
605 const driver = yield* GitVcsDriver.GitVcsDriver;
606​
607 yield* writeTextFile(cwd, "a.txt", "a\n");
608 yield* writeTextFile(cwd, "b.txt", "b\n");
609​
610 const context = yield* driver.prepareCommitContext(cwd, ["a.txt"]);
611 assert.include(context?.stagedSummary ?? "", "a.txt");
612 assert.notInclude(context?.stagedSummary ?? "", "b.txt");
613​
614 const commit = yield* driver.commit(cwd, "Add a", "");
615 assert.match(commit.commitSha, /^[a-f0-9]{40}$/);
616 assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "Add a");
617​
618 const status = yield* git(cwd, ["status", "--porcelain"]);
619 assert.include(status, "?? b.txt");
620 assert.notInclude(status, "a.txt");
621 }),
622 );
623 });
624​
625 describe("remote operations", () => {
626 it.effect("creates a worktree from the latest fetched remote commit", () =>
627 Effect.gen(function* () {
628 const cwd = yield* makeTmpDir();
629 const remote = yield* makeTmpDir("git-remote-");
630 const peer = yield* makeTmpDir("git-peer-");
631 const { initialBranch } = yield* initRepoWithCommit(cwd);
632 yield* git(remote, ["init", "--bare"]);
633 yield* git(cwd, ["remote", "add", "origin", remote]);
634 yield* git(cwd, ["push", "-u", "origin", initialBranch]);
635 yield* git(remote, ["symbolic-ref", "HEAD", `refs/heads/${initialBranch}`]);
636 const beforeFetch = yield* git(cwd, ["rev-parse", `refs/remotes/origin/${initialBranch}`]);
637​
638 yield* git(peer, ["clone", remote, "."]);
639 yield* git(peer, ["config", "user.email", "test@test.com"]);
640 yield* git(peer, ["config", "user.name", "Test"]);
641 yield* writeTextFile(peer, "remote-change.txt", "remote\n");
642 yield* git(peer, ["add", "remote-change.txt"]);
643 yield* git(peer, ["commit", "-m", "remote change"]);
644 yield* git(peer, ["push", "origin", initialBranch]);
645 const remoteHead = yield* git(peer, ["rev-parse", "HEAD"]);
646 assert.notEqual(beforeFetch, remoteHead);
647​
648 const driver = yield* GitVcsDriver.GitVcsDriver;
649 yield* driver.fetchRemote({ cwd, remoteName: "origin" });
650​
651 const resolvedBase = yield* driver.resolveRemoteTrackingCommit({
652 cwd,
653 refName: initialBranch,
654 fallbackRemoteName: "origin",
655 });
656 const explicitlyResolvedBase = yield* driver.resolveRemoteTrackingCommit({
657 cwd,
658 refName: `origin/${initialBranch}`,
659 fallbackRemoteName: "origin",
660 });
661​
662 assert.deepEqual(resolvedBase, {
663 commitSha: remoteHead,
664 remoteRefName: `origin/${initialBranch}`,
665 });
666 assert.deepEqual(explicitlyResolvedBase, resolvedBase);
667 assert.equal(yield* git(cwd, ["rev-parse", initialBranch]), beforeFetch);
668​
669 const pathService = yield* Path.Path;
670 const worktreePath = pathService.join(
671 yield* makeTmpDir("git-fetched-worktrees-"),
672 "fetched-origin",
673 );
674 yield* driver.createWorktree({
675 cwd,
676 path: worktreePath,
677 refName: resolvedBase.commitSha,
678 newRefName: "t3code/fetched-origin",
679 baseRefName: resolvedBase.remoteRefName,
680 });
681​
682 assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), remoteHead);
683 assert.equal(
684 yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.gh-merge-base"),
685 initialBranch,
686 );
687 assert.equal(
688 yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.remote"),
689 null,
690 );
691 const status = yield* driver.statusDetails(worktreePath);
692 assert.equal(status.aheadCount, 0);
693 assert.equal(status.aheadOfDefaultCount, 0);
694 }),
695 );
696​
697 it.effect("pushes with upstream setup and skips when already up to date", () =>
698 Effect.gen(function* () {
699 const cwd = yield* makeTmpDir();
700 const remote = yield* makeTmpDir("git-remote-");
701 yield* initRepoWithCommit(cwd);
702 yield* git(remote, ["init", "--bare"]);
703 yield* git(cwd, ["remote", "add", "origin", remote]);
704 yield* (yield* GitVcsDriver.GitVcsDriver).createRef({
705 cwd,
706 refName: "feature/push",
707 });
708 yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({
709 cwd,
710 refName: "feature/push",
711 });
712 yield* writeTextFile(cwd, "feature.txt", "feature\n");
713 yield* (yield* GitVcsDriver.GitVcsDriver).prepareCommitContext(cwd);
714 yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add feature", "");
715​
716 const pushed = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null);
717 assert.deepInclude(pushed, {
718 status: "pushed",
719 branch: "feature/push",
720 setUpstream: true,
721 });
722 assert.equal(
723 yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]),
724 "origin/feature/push",
725 );
726​
727 const skipped = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null);
728 assert.deepInclude(skipped, {
729 status: "skipped_up_to_date",
730 branch: "feature/push",
731 });
732 }),
733 );
734​
735 it.effect(
736 "pushes upstream branches to the remote branch name, not the upstream shorthand",
737 () =>
738 Effect.gen(function* () {
739 const cwd = yield* makeTmpDir();
740 const remote = yield* makeTmpDir("git-remote-");
741 yield* initRepoWithCommit(cwd);
742 const driver = yield* GitVcsDriver.GitVcsDriver;
743 yield* git(cwd, ["branch", "-M", "main"]);
744 yield* git(remote, ["init", "--bare"]);
745 yield* git(cwd, ["remote", "add", "origin", remote]);
746 yield* git(cwd, ["push", "-u", "origin", "main"]);
747 yield* writeTextFile(cwd, "upstream.txt", "upstream\n");
748 yield* driver.prepareCommitContext(cwd);
749 yield* driver.commit(cwd, "Add upstream update", "");
750​
751 const pushed = yield* driver.pushCurrentBranch(cwd, null);
752​
753 assert.deepInclude(pushed, {
754 status: "pushed",
755 branch: "main",
756 upstreamBranch: "origin/main",
757 setUpstream: false,
758 });
759 assert.equal(
760 yield* git(remote, ["log", "-1", "--pretty=%s", "main"]),
761 "Add upstream update",
762 );
763 const badBranch = yield* driver.execute({
764 operation: "GitVcsDriver.test.showBadRemoteBranch",
765 cwd: remote,
766 args: ["show-ref", "--verify", "--quiet", "refs/heads/origin/main"],
767 allowNonZeroExit: true,
768 timeoutMs: 10_000,
769 });
770 assert.notEqual(badBranch.exitCode, 0);
771 }),
772 );
773​
774 it.effect("pushes to the requested remote instead of the primary remote", () =>
775 Effect.gen(function* () {
776 const cwd = yield* makeTmpDir();
777 const originRemote = yield* makeTmpDir("git-origin-remote-");
778 const publishRemote = yield* makeTmpDir("git-publish-remote-");
779 yield* initRepoWithCommit(cwd);
780 const driver = yield* GitVcsDriver.GitVcsDriver;
781 yield* git(cwd, ["branch", "-M", "main"]);
782 yield* git(originRemote, ["init", "--bare"]);
783 yield* git(publishRemote, ["init", "--bare"]);
784 yield* git(cwd, ["remote", "add", "origin", originRemote]);
785 yield* git(cwd, ["remote", "add", "origin-1", publishRemote]);
786​
787 const pushed = yield* driver.pushCurrentBranch(cwd, null, { remoteName: "origin-1" });
788​
789 assert.deepInclude(pushed, {
790 status: "pushed",
791 branch: "main",
792 upstreamBranch: "origin-1/main",
793 setUpstream: true,
794 });
795 assert.equal(
796 yield* git(publishRemote, ["log", "-1", "--pretty=%s", "main"]),
797 "initial commit",
798 );
799 const originMain = yield* driver.execute({
800 operation: "GitVcsDriver.test.originMainMissing",
801 cwd: originRemote,
802 args: ["show-ref", "--verify", "--quiet", "refs/heads/main"],
803 allowNonZeroExit: true,
804 timeoutMs: 10_000,
805 });
806 assert.notEqual(originMain.exitCode, 0);
807 }),
808 );
809 });
810});