Open History to see the last commit
1import fs 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 { expect } from "vitest";
8
9import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
10import { type GitManagerShape } from "../Services/GitManager.ts";
11import {
12 type GitHubCliShape,
13 type GitHubPullRequestSummary,
14 GitHubCli,
15} from "../Services/GitHubCli.ts";
16import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
17import { GitServiceLive } from "./GitService.ts";
18import { GitService } from "../Services/GitService.ts";
19import { GitCoreLive } from "./GitCore.ts";
20import { makeGitManager } from "./GitManager.ts";
21
22interface FakeGhScenario {
23 prListSequence?: string[];
24 createdPrUrl?: string;
25 defaultBranch?: string;
26 failWith?: GitHubCliError;
27}
28
29interface FakeGitTextGeneration {
30 generateCommitMessage: (input: {
31 cwd: string;
32 branch: string | null;
33 stagedSummary: string;
34 stagedPatch: string;
35 }) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
36 generatePrContent: (input: {
37 cwd: string;
38 baseBranch: string;
39 headBranch: string;
40 commitSummary: string;
41 diffSummary: string;
42 diffPatch: string;
43 }) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
44}
45
46function makeTempDir(
47 prefix: string,
48): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
49 return Effect.gen(function* () {
50 const fileSystem = yield* FileSystem.FileSystem;
51 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
52 });
53}
54
55function runGit(
56 cwd: string,
57 args: readonly string[],
58 allowNonZeroExit = false,
59): Effect.Effect<
60 { readonly code: number; readonly stdout: string; readonly stderr: string },
61 GitCommandError,
62 GitService
63> {
64 return Effect.gen(function* () {
65 const gitService = yield* GitService;
66 return yield* gitService.execute({
67 operation: "GitManager.test.runGit",
68 cwd,
69 args,
70 allowNonZeroExit,
71 });
72 });
73}
74
75function initRepo(
76 cwd: string,
77): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {
78 return Effect.gen(function* () {
79 const fs = yield* FileSystem.FileSystem;
80 yield* runGit(cwd, ["init", "--initial-branch=main"]);
81 yield* runGit(cwd, ["config", "user.email", "test@example.com"]);
82 yield* runGit(cwd, ["config", "user.name", "Test User"]);
83 yield* fs.writeFileString(path.join(cwd, "README.md"), "hello\n");
84 yield* runGit(cwd, ["add", "README.md"]);
85 yield* runGit(cwd, ["commit", "-m", "Initial commit"]);
86 });
87}
88
89function createBareRemote(): Effect.Effect<
90 string,
91 PlatformError.PlatformError | GitCommandError,
92 FileSystem.FileSystem | Scope.Scope | GitService
93> {
94 return Effect.gen(function* () {
95 const remoteDir = yield* makeTempDir("t3code-git-remote-");
96 yield* runGit(remoteDir, ["init", "--bare"]);
97 return remoteDir;
98 });
99}
100
101function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
102 const implementation: FakeGitTextGeneration = {
103 generateCommitMessage: () =>
104 Effect.succeed({
105 subject: "Implement stacked git actions",
106 body: "",
107 }),
108 generatePrContent: () =>
109 Effect.succeed({
110 title: "Add stacked git actions",
111 body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
112 }),
113 ...overrides,
114 };
115
116 return {
117 generateCommitMessage: (input) =>
118 implementation.generateCommitMessage(input).pipe(
119 Effect.mapError(
120 (cause) =>
121 new TextGenerationError({
122 operation: "generateCommitMessage",
123 detail: "fake text generation failed",
124 ...(cause !== undefined ? { cause } : {}),
125 }),
126 ),
127 ),
128 generatePrContent: (input) =>
129 implementation.generatePrContent(input).pipe(
130 Effect.mapError(
131 (cause) =>
132 new TextGenerationError({
133 operation: "generatePrContent",
134 detail: "fake text generation failed",
135 ...(cause !== undefined ? { cause } : {}),
136 }),
137 ),
138 ),
139 };
140}
141
142function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
143 service: GitHubCliShape;
144 ghCalls: string[];
145} {
146 const prListQueue = [...(scenario.prListSequence ?? [])];
147 const ghCalls: string[] = [];
148
149 const execute: GitHubCliShape["execute"] = (input) => {
150 const args = [...input.args];
151 ghCalls.push(args.join(" "));
152
153 if (scenario.failWith) {
154 return Effect.fail(scenario.failWith);
155 }
156
157 if (args[0] === "pr" && args[1] === "list") {
158 const stdout = (prListQueue.shift() ?? "[]") + "\n";
159 return Effect.succeed({
160 stdout,
161 stderr: "",
162 code: 0,
163 signal: null,
164 timedOut: false,
165 });
166 }
167
168 if (args[0] === "pr" && args[1] === "create") {
169 return Effect.succeed({
170 stdout:
171 (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
172 stderr: "",
173 code: 0,
174 signal: null,
175 timedOut: false,
176 });
177 }
178
179 if (args[0] === "pr" && args[1] === "view") {
180 return Effect.succeed({
181 stdout: "",
182 stderr: "",
183 code: 0,
184 signal: null,
185 timedOut: false,
186 });
187 }
188
189 if (args[0] === "repo" && args[1] === "view") {
190 return Effect.succeed({
191 stdout: `${scenario.defaultBranch ?? "main"}\n`,
192 stderr: "",
193 code: 0,
194 signal: null,
195 timedOut: false,
196 });
197 }
198
199 return Effect.fail(
200 new GitHubCliError({
201 operation: "execute",
202 detail: `Unexpected gh command: ${args.join(" ")}`,
203 }),
204 );
205 };
206
207 return {
208 service: {
209 execute,
210 listOpenPullRequests: (input) =>
211 execute({
212 cwd: input.cwd,
213 args: [
214 "pr",
215 "list",
216 "--head",
217 input.headBranch,
218 "--state",
219 "open",
220 "--limit",
221 String(input.limit ?? 1),
222 "--json",
223 "number,title,url,baseRefName,headRefName",
224 ],
225 }).pipe(
226 Effect.map(
227 (result) => JSON.parse(result.stdout) as ReadonlyArray<GitHubPullRequestSummary>,
228 ),
229 ),
230 createPullRequest: (input) =>
231 execute({
232 cwd: input.cwd,
233 args: [
234 "pr",
235 "create",
236 "--base",
237 input.baseBranch,
238 "--head",
239 input.headBranch,
240 "--title",
241 input.title,
242 "--body-file",
243 input.bodyFile,
244 ],
245 }).pipe(Effect.asVoid),
246 getDefaultBranch: (input) =>
247 execute({
248 cwd: input.cwd,
249 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
250 }).pipe(
251 Effect.map((result) => {
252 const value = result.stdout.trim();
253 return value.length > 0 ? value : null;
254 }),
255 ),
256 },
257 ghCalls,
258 };
259}
260
261function runStackedAction(
262 manager: GitManagerShape,
263 input: {
264 cwd: string;
265 action: "commit" | "commit_push" | "commit_push_pr";
266 commitMessage?: string;
267 },
268) {
269 return manager.runStackedAction(input);
270}
271
272function makeManager(input?: {
273 ghScenario?: FakeGhScenario;
274 textGeneration?: Partial<FakeGitTextGeneration>;
275}) {
276 const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
277 const textGeneration = createTextGeneration(input?.textGeneration);
278
279 const gitCoreLayer = GitCoreLive.pipe(
280 Layer.provideMerge(GitServiceLive),
281 Layer.provideMerge(NodeServices.layer),
282 );
283
284 const managerLayer = Layer.mergeAll(
285 Layer.succeed(GitHubCli, gitHubCli),
286 Layer.succeed(TextGeneration, textGeneration),
287 gitCoreLayer,
288 NodeServices.layer,
289 );
290
291 return makeGitManager.pipe(
292 Effect.provide(managerLayer),
293 Effect.map((manager) => ({ manager, ghCalls })),
294 );
295}
296
297const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
298
299it.layer(GitManagerTestLayer)("GitManager", (it) => {
300 it.effect("status includes open PR metadata when branch already has an open PR", () =>
301 Effect.gen(function* () {
302 const repoDir = yield* makeTempDir("t3code-git-manager-");
303 yield* initRepo(repoDir);
304 yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
305 const remoteDir = yield* createBareRemote();
306 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
307 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
308
309 const { manager } = yield* makeManager({
310 ghScenario: {
311 prListSequence: [
312 JSON.stringify([
313 {
314 number: 13,
315 title: "Existing PR",
316 url: "https://github.com/pingdotgg/codething-mvp/pull/13",
317 baseRefName: "main",
318 headRefName: "feature/status-open-pr",
319 },
320 ]),
321 ],
322 },
323 });
324
325 const status = yield* manager.status({ cwd: repoDir });
326 expect(status.branch).toBe("feature/status-open-pr");
327 expect(status.openPr).toEqual({
328 number: 13,
329 title: "Existing PR",
330 url: "https://github.com/pingdotgg/codething-mvp/pull/13",
331 baseBranch: "main",
332 headBranch: "feature/status-open-pr",
333 });
334 }),
335 );
336
337 it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
338 Effect.gen(function* () {
339 const repoDir = yield* makeTempDir("t3code-git-manager-");
340 yield* initRepo(repoDir);
341 yield* runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
342 const remoteDir = yield* createBareRemote();
343 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
344 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
345
346 const { manager } = yield* makeManager({
347 ghScenario: {
348 failWith: new GitHubCliError({
349 operation: "execute",
350 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
351 }),
352 },
353 });
354
355 const status = yield* manager.status({ cwd: repoDir });
356 expect(status.branch).toBe("feature/status-no-gh");
357 expect(status.openPr).toBeNull();
358 }),
359 );
360
361 it.effect("creates a commit when working tree is dirty", () =>
362 Effect.gen(function* () {
363 const repoDir = yield* makeTempDir("t3code-git-manager-");
364 yield* initRepo(repoDir);
365 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
366
367 const { manager } = yield* makeManager();
368 const result = yield* runStackedAction(manager, {
369 cwd: repoDir,
370 action: "commit",
371 });
372
373 expect(result.commit.status).toBe("created");
374 expect(result.push.status).toBe("skipped_not_requested");
375 expect(result.pr.status).toBe("skipped_not_requested");
376 expect(
377 yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
378 Effect.map((result) => result.stdout.trim()),
379 ),
380 ).toBe("Implement stacked git actions");
381 }),
382 );
383
384 it.effect("uses custom commit message when provided", () =>
385 Effect.gen(function* () {
386 const repoDir = yield* makeTempDir("t3code-git-manager-");
387 yield* initRepo(repoDir);
388 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
389 let generatedCount = 0;
390
391 const { manager } = yield* makeManager({
392 textGeneration: {
393 generateCommitMessage: () =>
394 Effect.sync(() => {
395 generatedCount += 1;
396 return {
397 subject: "this should not be used",
398 body: "",
399 };
400 }),
401 },
402 });
403 const result = yield* runStackedAction(manager, {
404 cwd: repoDir,
405 action: "commit",
406 commitMessage: "feat: custom summary line\n\n- details from user",
407 });
408
409 expect(result.commit.status).toBe("created");
410 expect(result.commit.subject).toBe("feat: custom summary line");
411 expect(generatedCount).toBe(0);
412 expect(
413 yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
414 Effect.map((result) => result.stdout.trim()),
415 ),
416 ).toBe("feat: custom summary line");
417 expect(
418 yield* runGit(repoDir, ["log", "-1", "--pretty=%b"]).pipe(
419 Effect.map((result) => result.stdout.trim()),
420 ),
421 ).toContain("- details from user");
422 }),
423 );
424
425 it.effect("skips commit when there are no uncommitted changes", () =>
426 Effect.gen(function* () {
427 const repoDir = yield* makeTempDir("t3code-git-manager-");
428 yield* initRepo(repoDir);
429
430 const { manager } = yield* makeManager();
431 const result = yield* runStackedAction(manager, {
432 cwd: repoDir,
433 action: "commit",
434 });
435
436 expect(result.commit.status).toBe("skipped_no_changes");
437 expect(result.push.status).toBe("skipped_not_requested");
438 expect(result.pr.status).toBe("skipped_not_requested");
439 }),
440 );
441
442 it.effect("commits and pushes with upstream auto-setup when needed", () =>
443 Effect.gen(function* () {
444 const repoDir = yield* makeTempDir("t3code-git-manager-");
445 yield* initRepo(repoDir);
446 yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
447 const remoteDir = yield* createBareRemote();
448 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
449 fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
450
451 const { manager } = yield* makeManager();
452 const result = yield* runStackedAction(manager, {
453 cwd: repoDir,
454 action: "commit_push",
455 });
456
457 expect(result.commit.status).toBe("created");
458 expect(result.push.status).toBe("pushed");
459 expect(result.push.setUpstream).toBe(true);
460 expect(
461 yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
462 Effect.map((result) => result.stdout.trim()),
463 ),
464 ).toBe("origin/feature/stacked-flow");
465 }),
466 );
467
468 it.effect("skips push when branch is already up to date", () =>
469 Effect.gen(function* () {
470 const repoDir = yield* makeTempDir("t3code-git-manager-");
471 yield* initRepo(repoDir);
472 yield* runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
473 const remoteDir = yield* createBareRemote();
474 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
475 yield* runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
476
477 const { manager } = yield* makeManager();
478 const result = yield* runStackedAction(manager, {
479 cwd: repoDir,
480 action: "commit_push",
481 });
482
483 expect(result.commit.status).toBe("skipped_no_changes");
484 expect(result.push.status).toBe("skipped_up_to_date");
485 }),
486 );
487
488 it.effect("returns existing PR metadata for commit/push/pr action", () =>
489 Effect.gen(function* () {
490 const repoDir = yield* makeTempDir("t3code-git-manager-");
491 yield* initRepo(repoDir);
492 yield* runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
493 const remoteDir = yield* createBareRemote();
494 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
495 yield* runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
496
497 const { manager, ghCalls } = yield* makeManager({
498 ghScenario: {
499 prListSequence: [
500 JSON.stringify([
501 {
502 number: 42,
503 title: "Existing PR",
504 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
505 baseRefName: "main",
506 headRefName: "feature/existing-pr",
507 },
508 ]),
509 ],
510 },
511 });
512 const result = yield* runStackedAction(manager, {
513 cwd: repoDir,
514 action: "commit_push_pr",
515 });
516
517 expect(result.pr.status).toBe("opened_existing");
518 expect(result.pr.number).toBe(42);
519 expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
520 }),
521 );
522
523 it.effect("creates PR when one does not already exist", () =>
524 Effect.gen(function* () {
525 const repoDir = yield* makeTempDir("t3code-git-manager-");
526 yield* initRepo(repoDir);
527 yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
528 const remoteDir = yield* createBareRemote();
529 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
530 fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
531 yield* runGit(repoDir, ["add", "changes.txt"]);
532 yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
533 yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
534 yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
535
536 const { manager, ghCalls } = yield* makeManager({
537 ghScenario: {
538 prListSequence: [
539 "[]",
540 JSON.stringify([
541 {
542 number: 88,
543 title: "Add stacked git actions",
544 url: "https://github.com/pingdotgg/codething-mvp/pull/88",
545 baseRefName: "main",
546 headRefName: "feature-create-pr",
547 },
548 ]),
549 ],
550 },
551 });
552 const result = yield* runStackedAction(manager, {
553 cwd: repoDir,
554 action: "commit_push_pr",
555 });
556
557 expect(result.pr.status).toBe("created");
558 expect(result.pr.number).toBe(88);
559 expect(
560 ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
561 ).toBe(true);
562 expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
563 }),
564 );
565
566 it.effect("rejects push/pr actions from detached HEAD", () =>
567 Effect.gen(function* () {
568 const repoDir = yield* makeTempDir("t3code-git-manager-");
569 yield* initRepo(repoDir);
570 yield* runGit(repoDir, ["checkout", "--detach", "HEAD"]);
571
572 const { manager } = yield* makeManager();
573 const errorMessage = yield* runStackedAction(manager, {
574 cwd: repoDir,
575 action: "commit_push",
576 }).pipe(
577 Effect.flip,
578 Effect.map((error) => error.message),
579 );
580 expect(errorMessage).toContain("detached HEAD");
581 }),
582 );
583
584 it.effect("surfaces missing gh binary errors", () =>
585 Effect.gen(function* () {
586 const repoDir = yield* makeTempDir("t3code-git-manager-");
587 yield* initRepo(repoDir);
588 yield* runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
589 const remoteDir = yield* createBareRemote();
590 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
591 yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
592
593 const { manager } = yield* makeManager({
594 ghScenario: {
595 failWith: new GitHubCliError({
596 operation: "execute",
597 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
598 }),
599 },
600 });
601
602 const errorMessage = yield* runStackedAction(manager, {
603 cwd: repoDir,
604 action: "commit_push_pr",
605 }).pipe(
606 Effect.flip,
607 Effect.map((error) => error.message),
608 );
609 expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
610 }),
611 );
612
613 it.effect("surfaces gh auth errors with guidance", () =>
614 Effect.gen(function* () {
615 const repoDir = yield* makeTempDir("t3code-git-manager-");
616 yield* initRepo(repoDir);
617 yield* runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
618 const remoteDir = yield* createBareRemote();
619 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
620 yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
621
622 const { manager } = yield* makeManager({
623 ghScenario: {
624 failWith: new GitHubCliError({
625 operation: "execute",
626 detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
627 }),
628 },
629 });
630
631 const errorMessage = yield* runStackedAction(manager, {
632 cwd: repoDir,
633 action: "commit_push_pr",
634 }).pipe(
635 Effect.flip,
636 Effect.map((error) => error.message),
637 );
638 expect(errorMessage).toContain("gh auth login");
639 }),
640 );
641});