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

GitManager.test.ts

927 lines30.1 KB

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;
28​
29interface FakeGitTextGeneration {
30 generateCommitMessage: (input: {
31 cwd: string;
32 branch: string | null;
33 stagedSummary: string;
34 stagedPatch: string;
35 includeBranch?: boolean;
36 }) => Effect.Effect<
37 { subject: string; body: string; branch?: string | undefined },
38 TextGenerationError
39 >;
40 generatePrContent: (input: {
41 cwd: string;
42 baseBranch: string;
43 headBranch: string;
44 commitSummary: string;
45 diffSummary: string;
46 diffPatch: string;
47 }) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
48 generateBranchName: (input: {
49 cwd: string;
50 message: string;
51 }) => Effect.Effect<{ branch: string }, TextGenerationError>;
53​
54function makeTempDir(
55 prefix: string,
56): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
57 return Effect.gen(function* () {
58 const fileSystem = yield* FileSystem.FileSystem;
59 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
60 });
62​
63function runGit(
64 cwd: string,
65 args: readonly string[],
66 allowNonZeroExit = false,
67): Effect.Effect<
68 { readonly code: number; readonly stdout: string; readonly stderr: string },
69 GitCommandError,
70 GitService
71> {
72 return Effect.gen(function* () {
73 const gitService = yield* GitService;
74 return yield* gitService.execute({
75 operation: "GitManager.test.runGit",
76 cwd,
77 args,
78 allowNonZeroExit,
79 });
80 });
82​
83function initRepo(
84 cwd: string,
85): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {
86 return Effect.gen(function* () {
87 const fs = yield* FileSystem.FileSystem;
88 yield* runGit(cwd, ["init", "--initial-branch=main"]);
89 yield* runGit(cwd, ["config", "user.email", "test@example.com"]);
90 yield* runGit(cwd, ["config", "user.name", "Test User"]);
91 yield* fs.writeFileString(path.join(cwd, "README.md"), "hello\n");
92 yield* runGit(cwd, ["add", "README.md"]);
93 yield* runGit(cwd, ["commit", "-m", "Initial commit"]);
94 });
96​
97function createBareRemote(): Effect.Effect<
98 string,
99 PlatformError.PlatformError | GitCommandError,
100 FileSystem.FileSystem | Scope.Scope | GitService
101> {
102 return Effect.gen(function* () {
103 const remoteDir = yield* makeTempDir("t3code-git-remote-");
104 yield* runGit(remoteDir, ["init", "--bare"]);
105 return remoteDir;
106 });
108​
109function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
110 const implementation: FakeGitTextGeneration = {
111 generateCommitMessage: (input) =>
112 Effect.succeed({
113 subject: "Implement stacked git actions",
114 body: "",
115 ...(input.includeBranch
116 ? { branch: "feature/implement-stacked-git-actions" }
117 : {}),
118 }),
119 generatePrContent: () =>
120 Effect.succeed({
121 title: "Add stacked git actions",
122 body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
123 }),
124 generateBranchName: () =>
125 Effect.succeed({
126 branch: "update-workflow",
127 }),
128 ...overrides,
129 };
130​
131 return {
132 generateCommitMessage: (input) =>
133 implementation.generateCommitMessage(input).pipe(
134 Effect.mapError(
135 (cause) =>
136 new TextGenerationError({
137 operation: "generateCommitMessage",
138 detail: "fake text generation failed",
139 ...(cause !== undefined ? { cause } : {}),
140 }),
141 ),
142 ),
143 generatePrContent: (input) =>
144 implementation.generatePrContent(input).pipe(
145 Effect.mapError(
146 (cause) =>
147 new TextGenerationError({
148 operation: "generatePrContent",
149 detail: "fake text generation failed",
150 ...(cause !== undefined ? { cause } : {}),
151 }),
152 ),
153 ),
154 generateBranchName: (input) =>
155 implementation.generateBranchName(input).pipe(
156 Effect.mapError(
157 (cause) =>
158 new TextGenerationError({
159 operation: "generateBranchName",
160 detail: "fake text generation failed",
161 ...(cause !== undefined ? { cause } : {}),
162 }),
163 ),
164 ),
165 };
167​
168function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
169 service: GitHubCliShape;
170 ghCalls: string[];
171} {
172 const prListQueue = [...(scenario.prListSequence ?? [])];
173 const ghCalls: string[] = [];
174​
175 const execute: GitHubCliShape["execute"] = (input) => {
176 const args = [...input.args];
177 ghCalls.push(args.join(" "));
178​
179 if (scenario.failWith) {
180 return Effect.fail(scenario.failWith);
181 }
182​
183 if (args[0] === "pr" && args[1] === "list") {
184 const stdout = (prListQueue.shift() ?? "[]") + "\n";
185 return Effect.succeed({
186 stdout,
187 stderr: "",
188 code: 0,
189 signal: null,
190 timedOut: false,
191 });
192 }
193​
194 if (args[0] === "pr" && args[1] === "create") {
195 return Effect.succeed({
196 stdout:
197 (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
198 stderr: "",
199 code: 0,
200 signal: null,
201 timedOut: false,
202 });
203 }
204​
205 if (args[0] === "pr" && args[1] === "view") {
206 return Effect.succeed({
207 stdout: "",
208 stderr: "",
209 code: 0,
210 signal: null,
211 timedOut: false,
212 });
213 }
214​
215 if (args[0] === "repo" && args[1] === "view") {
216 return Effect.succeed({
217 stdout: `${scenario.defaultBranch ?? "main"}\n`,
218 stderr: "",
219 code: 0,
220 signal: null,
221 timedOut: false,
222 });
223 }
224​
225 return Effect.fail(
226 new GitHubCliError({
227 operation: "execute",
228 detail: `Unexpected gh command: ${args.join(" ")}`,
229 }),
230 );
231 };
232​
233 return {
234 service: {
235 execute,
236 listOpenPullRequests: (input) =>
237 execute({
238 cwd: input.cwd,
239 args: [
240 "pr",
241 "list",
242 "--head",
243 input.headBranch,
244 "--state",
245 "open",
246 "--limit",
247 String(input.limit ?? 1),
248 "--json",
249 "number,title,url,baseRefName,headRefName",
250 ],
251 }).pipe(
252 Effect.map(
253 (result) => JSON.parse(result.stdout) as ReadonlyArray<GitHubPullRequestSummary>,
254 ),
255 ),
256 createPullRequest: (input) =>
257 execute({
258 cwd: input.cwd,
259 args: [
260 "pr",
261 "create",
262 "--base",
263 input.baseBranch,
264 "--head",
265 input.headBranch,
266 "--title",
267 input.title,
268 "--body-file",
269 input.bodyFile,
270 ],
271 }).pipe(Effect.asVoid),
272 getDefaultBranch: (input) =>
273 execute({
274 cwd: input.cwd,
275 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
276 }).pipe(
277 Effect.map((result) => {
278 const value = result.stdout.trim();
279 return value.length > 0 ? value : null;
280 }),
281 ),
282 },
283 ghCalls,
284 };
286​
287function runStackedAction(
288 manager: GitManagerShape,
289 input: {
290 cwd: string;
291 action: "commit" | "commit_push" | "commit_push_pr";
292 commitMessage?: string;
293 featureBranch?: boolean;
294 },
295) {
296 return manager.runStackedAction(input);
298​
299function makeManager(input?: {
300 ghScenario?: FakeGhScenario;
301 textGeneration?: Partial<FakeGitTextGeneration>;
302}) {
303 const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
304 const textGeneration = createTextGeneration(input?.textGeneration);
305​
306 const gitCoreLayer = GitCoreLive.pipe(
307 Layer.provideMerge(GitServiceLive),
308 Layer.provideMerge(NodeServices.layer),
309 );
310​
311 const managerLayer = Layer.mergeAll(
312 Layer.succeed(GitHubCli, gitHubCli),
313 Layer.succeed(TextGeneration, textGeneration),
314 gitCoreLayer,
315 NodeServices.layer,
316 );
317​
318 return makeGitManager.pipe(
319 Effect.provide(managerLayer),
320 Effect.map((manager) => ({ manager, ghCalls })),
321 );
323​
324const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
325​
326it.layer(GitManagerTestLayer)("GitManager", (it) => {
327 it.effect("status includes PR metadata when branch already has an open PR", () =>
328 Effect.gen(function* () {
329 const repoDir = yield* makeTempDir("t3code-git-manager-");
330 yield* initRepo(repoDir);
331 yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
332 const remoteDir = yield* createBareRemote();
333 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
334 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
335​
336 const { manager } = yield* makeManager({
337 ghScenario: {
338 prListSequence: [
339 JSON.stringify([
340 {
341 number: 13,
342 title: "Existing PR",
343 url: "https://github.com/pingdotgg/codething-mvp/pull/13",
344 baseRefName: "main",
345 headRefName: "feature/status-open-pr",
346 },
347 ]),
348 ],
349 },
350 });
351​
352 const status = yield* manager.status({ cwd: repoDir });
353 expect(status.branch).toBe("feature/status-open-pr");
354 expect(status.pr).toEqual({
355 number: 13,
356 title: "Existing PR",
357 url: "https://github.com/pingdotgg/codething-mvp/pull/13",
358 baseBranch: "main",
359 headBranch: "feature/status-open-pr",
360 state: "open",
361 });
362 }),
363 );
364​
365 it.effect("status returns merged PR state when latest PR was merged", () =>
366 Effect.gen(function* () {
367 const repoDir = yield* makeTempDir("t3code-git-manager-");
368 yield* initRepo(repoDir);
369 yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
370​
371 const { manager } = yield* makeManager({
372 ghScenario: {
373 prListSequence: [
374 JSON.stringify([
375 {
376 number: 22,
377 title: "Merged PR",
378 url: "https://github.com/pingdotgg/codething-mvp/pull/22",
379 baseRefName: "main",
380 headRefName: "feature/status-merged-pr",
381 state: "MERGED",
382 mergedAt: "2026-01-30T10:00:00Z",
383 updatedAt: "2026-01-30T10:00:00Z",
384 },
385 ]),
386 ],
387 },
388 });
389​
390 const status = yield* manager.status({ cwd: repoDir });
391 expect(status.branch).toBe("feature/status-merged-pr");
392 expect(status.pr).toEqual({
393 number: 22,
394 title: "Merged PR",
395 url: "https://github.com/pingdotgg/codething-mvp/pull/22",
396 baseBranch: "main",
397 headBranch: "feature/status-merged-pr",
398 state: "merged",
399 });
400 }),
401 );
402​
403 it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
404 Effect.gen(function* () {
405 const repoDir = yield* makeTempDir("t3code-git-manager-");
406 yield* initRepo(repoDir);
407 yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
408​
409 const { manager } = yield* makeManager({
410 ghScenario: {
411 prListSequence: [
412 JSON.stringify([
413 {
414 number: 45,
415 title: "Merged PR",
416 url: "https://github.com/pingdotgg/codething-mvp/pull/45",
417 baseRefName: "main",
418 headRefName: "feature/status-open-over-merged",
419 state: "MERGED",
420 mergedAt: "2026-01-31T10:00:00Z",
421 updatedAt: "2026-02-01T10:00:00Z",
422 },
423 {
424 number: 46,
425 title: "Open PR",
426 url: "https://github.com/pingdotgg/codething-mvp/pull/46",
427 baseRefName: "main",
428 headRefName: "feature/status-open-over-merged",
429 state: "OPEN",
430 updatedAt: "2026-01-30T10:00:00Z",
431 },
432 ]),
433 ],
434 },
435 });
436​
437 const status = yield* manager.status({ cwd: repoDir });
438 expect(status.branch).toBe("feature/status-open-over-merged");
439 expect(status.pr).toEqual({
440 number: 46,
441 title: "Open PR",
442 url: "https://github.com/pingdotgg/codething-mvp/pull/46",
443 baseBranch: "main",
444 headBranch: "feature/status-open-over-merged",
445 state: "open",
446 });
447 }),
448 );
449​
450 it.effect("status is resilient to gh lookup failures and returns pr null", () =>
451 Effect.gen(function* () {
452 const repoDir = yield* makeTempDir("t3code-git-manager-");
453 yield* initRepo(repoDir);
454 yield* runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
455 const remoteDir = yield* createBareRemote();
456 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
457 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
458​
459 const { manager } = yield* makeManager({
460 ghScenario: {
461 failWith: new GitHubCliError({
462 operation: "execute",
463 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
464 }),
465 },
466 });
467​
468 const status = yield* manager.status({ cwd: repoDir });
469 expect(status.branch).toBe("feature/status-no-gh");
470 expect(status.pr).toBeNull();
471 }),
472 );
473​
474 it.effect("creates a commit when working tree is dirty", () =>
475 Effect.gen(function* () {
476 const repoDir = yield* makeTempDir("t3code-git-manager-");
477 yield* initRepo(repoDir);
478 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
479​
480 const { manager } = yield* makeManager();
481 const result = yield* runStackedAction(manager, {
482 cwd: repoDir,
483 action: "commit",
484 });
485​
486 expect(result.branch.status).toBe("skipped_not_requested");
487 expect(result.commit.status).toBe("created");
488 expect(result.push.status).toBe("skipped_not_requested");
489 expect(result.pr.status).toBe("skipped_not_requested");
490 expect(
491 yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
492 Effect.map((result) => result.stdout.trim()),
493 ),
494 ).toBe("Implement stacked git actions");
495 }),
496 );
497​
498 it.effect("uses custom commit message when provided", () =>
499 Effect.gen(function* () {
500 const repoDir = yield* makeTempDir("t3code-git-manager-");
501 yield* initRepo(repoDir);
502 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
503 let generatedCount = 0;
504​
505 const { manager } = yield* makeManager({
506 textGeneration: {
507 generateCommitMessage: (input) =>
508 Effect.sync(() => {
509 generatedCount += 1;
510 return {
511 subject: "this should not be used",
512 body: "",
513 ...(input.includeBranch ? { branch: "feature/unused" } : {}),
514 };
515 }),
516 },
517 });
518 const result = yield* runStackedAction(manager, {
519 cwd: repoDir,
520 action: "commit",
521 commitMessage: "feat: custom summary line\n\n- details from user",
522 });
523​
524 expect(result.branch.status).toBe("skipped_not_requested");
525 expect(result.commit.status).toBe("created");
526 expect(result.commit.subject).toBe("feat: custom summary line");
527 expect(generatedCount).toBe(0);
528 expect(
529 yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
530 Effect.map((result) => result.stdout.trim()),
531 ),
532 ).toBe("feat: custom summary line");
533 expect(
534 yield* runGit(repoDir, ["log", "-1", "--pretty=%b"]).pipe(
535 Effect.map((result) => result.stdout.trim()),
536 ),
537 ).toContain("- details from user");
538 }),
539 );
540​
541 it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
542 Effect.gen(function* () {
543 const repoDir = yield* makeTempDir("t3code-git-manager-");
544 yield* initRepo(repoDir);
545 const remoteDir = yield* createBareRemote();
546 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
547 yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
548 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
549 let generatedCount = 0;
550​
551 const { manager } = yield* makeManager({
552 textGeneration: {
553 generateCommitMessage: (input) =>
554 Effect.sync(() => {
555 generatedCount += 1;
556 return {
557 subject: "Implement stacked git actions",
558 body: "",
559 ...(input.includeBranch
560 ? { branch: "feature/implement-stacked-git-actions" }
561 : {}),
562 };
563 }),
564 },
565 });
566 const result = yield* runStackedAction(manager, {
567 cwd: repoDir,
568 action: "commit_push",
569 featureBranch: true,
570 });
571​
572 expect(result.branch.status).toBe("created");
573 expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
574 expect(result.commit.status).toBe("created");
575 expect(result.push.status).toBe("pushed");
576 expect(
577 yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
578 Effect.map((result) => result.stdout.trim()),
579 ),
580 ).toBe("feature/implement-stacked-git-actions");
581​
582 const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
583 Effect.map((r) => r.stdout.trim()),
584 );
585 const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
586 Effect.map((r) => r.stdout.trim()),
587 );
588 expect(mergeBase).toBe(mainSha);
589 expect(generatedCount).toBe(1);
590 }),
591 );
592​
593 it.effect("featureBranch uses custom commit message and derives branch name", () =>
594 Effect.gen(function* () {
595 const repoDir = yield* makeTempDir("t3code-git-manager-");
596 yield* initRepo(repoDir);
597 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
598 let generatedCount = 0;
599​
600 const { manager } = yield* makeManager({
601 textGeneration: {
602 generateCommitMessage: (input) =>
603 Effect.sync(() => {
604 generatedCount += 1;
605 return {
606 subject: "unused",
607 body: "",
608 ...(input.includeBranch ? { branch: "feature/unused" } : {}),
609 };
610 }),
611 },
612 });
613 const result = yield* runStackedAction(manager, {
614 cwd: repoDir,
615 action: "commit",
616 featureBranch: true,
617 commitMessage: "feat: custom summary line\n\n- details from user",
618 });
619​
620 expect(result.branch.status).toBe("created");
621 expect(result.branch.name).toBe("feature/feat-custom-summary-line");
622 expect(result.commit.status).toBe("created");
623 expect(result.commit.subject).toBe("feat: custom summary line");
624 expect(generatedCount).toBe(0);
625​
626 const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
627 Effect.map((r) => r.stdout.trim()),
628 );
629 const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
630 Effect.map((r) => r.stdout.trim()),
631 );
632 expect(mergeBase).toBe(mainSha);
633 }),
634 );
635​
636 it.effect("skips commit when there are no uncommitted changes", () =>
637 Effect.gen(function* () {
638 const repoDir = yield* makeTempDir("t3code-git-manager-");
639 yield* initRepo(repoDir);
640​
641 const { manager } = yield* makeManager();
642 const result = yield* runStackedAction(manager, {
643 cwd: repoDir,
644 action: "commit",
645 });
646​
647 expect(result.branch.status).toBe("skipped_not_requested");
648 expect(result.commit.status).toBe("skipped_no_changes");
649 expect(result.push.status).toBe("skipped_not_requested");
650 expect(result.pr.status).toBe("skipped_not_requested");
651 }),
652 );
653​
654 it.effect("featureBranch returns error when worktree is clean", () =>
655 Effect.gen(function* () {
656 const repoDir = yield* makeTempDir("t3code-git-manager-");
657 yield* initRepo(repoDir);
658​
659 const { manager } = yield* makeManager();
660 const errorMessage = yield* runStackedAction(manager, {
661 cwd: repoDir,
662 action: "commit",
663 featureBranch: true,
664 }).pipe(
665 Effect.flip,
666 Effect.map((error) => error.message),
667 );
668​
669 expect(errorMessage).toContain("no changes to commit");
670 }),
671 );
672​
673 it.effect("commits and pushes with upstream auto-setup when needed", () =>
674 Effect.gen(function* () {
675 const repoDir = yield* makeTempDir("t3code-git-manager-");
676 yield* initRepo(repoDir);
677 yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
678 const remoteDir = yield* createBareRemote();
679 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
680 fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
681​
682 const { manager } = yield* makeManager();
683 const result = yield* runStackedAction(manager, {
684 cwd: repoDir,
685 action: "commit_push",
686 });
687​
688 expect(result.branch.status).toBe("skipped_not_requested");
689 expect(result.commit.status).toBe("created");
690 expect(result.push.status).toBe("pushed");
691 expect(result.push.setUpstream).toBe(true);
692 expect(
693 yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
694 Effect.map((result) => result.stdout.trim()),
695 ),
696 ).toBe("origin/feature/stacked-flow");
697 }),
698 );
699​
700 it.effect(
701 "pushes and creates PR from a no-upstream branch when local commits are ahead of base",
702 () =>
703 Effect.gen(function* () {
704 const repoDir = yield* makeTempDir("t3code-git-manager-");
705 yield* initRepo(repoDir);
706 yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
707 const remoteDir = yield* createBareRemote();
708 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
709 fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
710​
711 const { manager, ghCalls } = yield* makeManager({
712 ghScenario: {
713 prListSequence: [
714 "[]",
715 JSON.stringify([
716 {
717 number: 77,
718 title: "Add no-upstream PR flow",
719 url: "https://github.com/pingdotgg/codething-mvp/pull/77",
720 baseRefName: "main",
721 headRefName: "feature/no-upstream-pr",
722 },
723 ]),
724 ],
725 },
726 });
727​
728 const result = yield* runStackedAction(manager, {
729 cwd: repoDir,
730 action: "commit_push_pr",
731 });
732​
733 expect(result.branch.status).toBe("skipped_not_requested");
734 expect(result.commit.status).toBe("created");
735 expect(result.push.status).toBe("pushed");
736 expect(result.push.setUpstream).toBe(true);
737 expect(result.pr.status).toBe("created");
738 expect(
739 yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
740 Effect.map((result) => result.stdout.trim()),
741 ),
742 ).toBe("origin/feature/no-upstream-pr");
743 expect(
744 ghCalls.some((call) =>
745 call.includes("pr create --base main --head feature/no-upstream-pr"),
746 ),
747 ).toBe(true);
748 }),
749 );
750​
751 it.effect("skips push when branch is already up to date", () =>
752 Effect.gen(function* () {
753 const repoDir = yield* makeTempDir("t3code-git-manager-");
754 yield* initRepo(repoDir);
755 yield* runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
756 const remoteDir = yield* createBareRemote();
757 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
758 yield* runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
759​
760 const { manager } = yield* makeManager();
761 const result = yield* runStackedAction(manager, {
762 cwd: repoDir,
763 action: "commit_push",
764 });
765​
766 expect(result.branch.status).toBe("skipped_not_requested");
767 expect(result.commit.status).toBe("skipped_no_changes");
768 expect(result.push.status).toBe("skipped_up_to_date");
769 }),
770 );
771​
772 it.effect("returns existing PR metadata for commit/push/pr action", () =>
773 Effect.gen(function* () {
774 const repoDir = yield* makeTempDir("t3code-git-manager-");
775 yield* initRepo(repoDir);
776 yield* runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
777 const remoteDir = yield* createBareRemote();
778 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
779 yield* runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
780​
781 const { manager, ghCalls } = yield* makeManager({
782 ghScenario: {
783 prListSequence: [
784 JSON.stringify([
785 {
786 number: 42,
787 title: "Existing PR",
788 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
789 baseRefName: "main",
790 headRefName: "feature/existing-pr",
791 },
792 ]),
793 ],
794 },
795 });
796 const result = yield* runStackedAction(manager, {
797 cwd: repoDir,
798 action: "commit_push_pr",
799 });
800​
801 expect(result.branch.status).toBe("skipped_not_requested");
802 expect(result.pr.status).toBe("opened_existing");
803 expect(result.pr.number).toBe(42);
804 expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
805 }),
806 );
807​
808 it.effect("creates PR when one does not already exist", () =>
809 Effect.gen(function* () {
810 const repoDir = yield* makeTempDir("t3code-git-manager-");
811 yield* initRepo(repoDir);
812 yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
813 const remoteDir = yield* createBareRemote();
814 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
815 fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
816 yield* runGit(repoDir, ["add", "changes.txt"]);
817 yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
818 yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
819 yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
820​
821 const { manager, ghCalls } = yield* makeManager({
822 ghScenario: {
823 prListSequence: [
824 "[]",
825 JSON.stringify([
826 {
827 number: 88,
828 title: "Add stacked git actions",
829 url: "https://github.com/pingdotgg/codething-mvp/pull/88",
830 baseRefName: "main",
831 headRefName: "feature-create-pr",
832 },
833 ]),
834 ],
835 },
836 });
837 const result = yield* runStackedAction(manager, {
838 cwd: repoDir,
839 action: "commit_push_pr",
840 });
841​
842 expect(result.branch.status).toBe("skipped_not_requested");
843 expect(result.pr.status).toBe("created");
844 expect(result.pr.number).toBe(88);
845 expect(
846 ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
847 ).toBe(true);
848 expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
849 }),
850 );
851​
852 it.effect("rejects push/pr actions from detached HEAD", () =>
853 Effect.gen(function* () {
854 const repoDir = yield* makeTempDir("t3code-git-manager-");
855 yield* initRepo(repoDir);
856 yield* runGit(repoDir, ["checkout", "--detach", "HEAD"]);
857​
858 const { manager } = yield* makeManager();
859 const errorMessage = yield* runStackedAction(manager, {
860 cwd: repoDir,
861 action: "commit_push",
862 }).pipe(
863 Effect.flip,
864 Effect.map((error) => error.message),
865 );
866 expect(errorMessage).toContain("detached HEAD");
867 }),
868 );
869​
870 it.effect("surfaces missing gh binary errors", () =>
871 Effect.gen(function* () {
872 const repoDir = yield* makeTempDir("t3code-git-manager-");
873 yield* initRepo(repoDir);
874 yield* runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
875 const remoteDir = yield* createBareRemote();
876 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
877 yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
878​
879 const { manager } = yield* makeManager({
880 ghScenario: {
881 failWith: new GitHubCliError({
882 operation: "execute",
883 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
884 }),
885 },
886 });
887​
888 const errorMessage = yield* runStackedAction(manager, {
889 cwd: repoDir,
890 action: "commit_push_pr",
891 }).pipe(
892 Effect.flip,
893 Effect.map((error) => error.message),
894 );
895 expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
896 }),
897 );
898​
899 it.effect("surfaces gh auth errors with guidance", () =>
900 Effect.gen(function* () {
901 const repoDir = yield* makeTempDir("t3code-git-manager-");
902 yield* initRepo(repoDir);
903 yield* runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
904 const remoteDir = yield* createBareRemote();
905 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
906 yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
907​
908 const { manager } = yield* makeManager({
909 ghScenario: {
910 failWith: new GitHubCliError({
911 operation: "execute",
912 detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
913 }),
914 },
915 });
916​
917 const errorMessage = yield* runStackedAction(manager, {
918 cwd: repoDir,
919 action: "commit_push_pr",
920 }).pipe(
921 Effect.flip,
922 Effect.map((error) => error.message),
923 );
924 expect(errorMessage).toContain("gh auth login");
925 }),
926 );
927});