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

gitManager.test.ts

482 lines14.9 KB

1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4​
5import { afterEach, describe, expect, it } from "vitest";
6​
7import { GitManager } from "./gitManager";
8import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
9​
10interface FakeGhScenario {
11 prListSequence?: string[];
12 createdPrUrl?: string;
13 defaultBranch?: string;
14 failWith?: Error;
16​
17interface FakeGitTextGenerator {
18 generateCommitMessage: (input: {
19 cwd: string;
20 branch: string | null;
21 stagedSummary: string;
22 stagedPatch: string;
23 }) => Promise<{ subject: string; body: string }>;
24 generatePrContent: (input: {
25 cwd: string;
26 baseBranch: string;
27 headBranch: string;
28 commitSummary: string;
29 diffSummary: string;
30 diffPatch: string;
31 }) => Promise<{ title: string; body: string }>;
33​
34const tempDirs: string[] = [];
35​
36function makeTempDir(prefix: string): string {
37 const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
38 tempDirs.push(dir);
39 return dir;
41​
42async function runGit(
43 cwd: string,
44 args: readonly string[],
45 allowNonZeroExit = false,
46): Promise<ProcessRunResult> {
47 return runProcess("git", args, { cwd, allowNonZeroExit });
49​
50async function runGitStdout(cwd: string, args: readonly string[]): Promise<string> {
51 const result = await runGit(cwd, args);
52 return result.stdout.trim();
54​
55async function initRepo(cwd: string): Promise<void> {
56 await runGit(cwd, ["init", "--initial-branch=main"]);
57 await runGit(cwd, ["config", "user.email", "test@example.com"]);
58 await runGit(cwd, ["config", "user.name", "Test User"]);
59 fs.writeFileSync(path.join(cwd, "README.md"), "hello\n");
60 await runGit(cwd, ["add", "README.md"]);
61 await runGit(cwd, ["commit", "-m", "Initial commit"]);
63​
64async function createBareRemote(): Promise<string> {
65 const remoteDir = makeTempDir("t3code-git-remote-");
66 await runProcess("git", ["init", "--bare"], { cwd: remoteDir });
67 return remoteDir;
69​
70function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
71 return {
72 generateCommitMessage: async () => ({
73 subject: "Implement stacked git actions",
74 body: "",
75 }),
76 generatePrContent: async () => ({
77 title: "Add stacked git actions",
78 body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
79 }),
80 ...overrides,
81 };
83​
84function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
85 runner: (
86 command: string,
87 args: readonly string[],
88 options?: ProcessRunOptions,
89 ) => Promise<ProcessRunResult>;
90 ghCalls: string[];
91} {
92 const prListQueue = [...(scenario.prListSequence ?? [])];
93 const ghCalls: string[] = [];
94​
95 const runner = async (
96 command: string,
97 args: readonly string[],
98 options?: ProcessRunOptions,
99 ): Promise<ProcessRunResult> => {
100 if (command !== "gh") {
101 return runProcess(command, args, options);
102 }
103​
104 ghCalls.push(args.join(" "));
105 if (scenario.failWith) {
106 throw scenario.failWith;
107 }
108​
109 if (args[0] === "pr" && args[1] === "list") {
110 const stdout = (prListQueue.shift() ?? "[]") + "\n";
111 return {
112 stdout,
113 stderr: "",
114 code: 0,
115 signal: null,
116 timedOut: false,
117 };
118 }
119​
120 if (args[0] === "pr" && args[1] === "create") {
121 return {
122 stdout:
123 (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
124 stderr: "",
125 code: 0,
126 signal: null,
127 timedOut: false,
128 };
129 }
130​
131 if (args[0] === "pr" && args[1] === "view") {
132 return {
133 stdout: "",
134 stderr: "",
135 code: 0,
136 signal: null,
137 timedOut: false,
138 };
139 }
140​
141 if (args[0] === "repo" && args[1] === "view") {
142 return {
143 stdout: `${scenario.defaultBranch ?? "main"}\n`,
144 stderr: "",
145 code: 0,
146 signal: null,
147 timedOut: false,
148 };
149 }
150​
151 throw new Error(`Unexpected gh command: ${args.join(" ")}`);
152 };
153​
154 return { runner, ghCalls };
156​
157afterEach(() => {
158 for (const dir of tempDirs.splice(0, tempDirs.length)) {
159 fs.rmSync(dir, { recursive: true, force: true });
160 }
161});
162​
163describe("GitManager", () => {
164 it("status includes open PR metadata when branch already has an open PR", async () => {
165 const repoDir = makeTempDir("t3code-git-manager-");
166 await initRepo(repoDir);
167 await runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
168 const remoteDir = await createBareRemote();
169 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
170 await runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
171​
172 const { runner } = createRunnerWithFakeGh({
173 prListSequence: [
174 JSON.stringify([
175 {
176 number: 13,
177 title: "Existing PR",
178 url: "https://github.com/pingdotgg/codething-mvp/pull/13",
179 baseRefName: "main",
180 headRefName: "feature/status-open-pr",
181 },
182 ]),
183 ],
184 });
185​
186 const manager = new GitManager({
187 runProcess: runner,
188 textGenerator: createTextGenerator(),
189 });
190​
191 const status = await manager.status({ cwd: repoDir });
192 expect(status.branch).toBe("feature/status-open-pr");
193 expect(status.openPr).toEqual({
194 number: 13,
195 title: "Existing PR",
196 url: "https://github.com/pingdotgg/codething-mvp/pull/13",
197 baseBranch: "main",
198 headBranch: "feature/status-open-pr",
199 });
200 });
201​
202 it("status is resilient to gh lookup failures and returns openPr null", async () => {
203 const repoDir = makeTempDir("t3code-git-manager-");
204 await initRepo(repoDir);
205 await runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
206 const remoteDir = await createBareRemote();
207 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
208 await runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
209​
210 const { runner } = createRunnerWithFakeGh({
211 failWith: new Error("Command not found: gh"),
212 });
213 const manager = new GitManager({
214 runProcess: runner,
215 textGenerator: createTextGenerator(),
216 });
217​
218 const status = await manager.status({ cwd: repoDir });
219 expect(status.branch).toBe("feature/status-no-gh");
220 expect(status.openPr).toBeNull();
221 });
222​
223 it("creates a commit when working tree is dirty", async () => {
224 const repoDir = makeTempDir("t3code-git-manager-");
225 await initRepo(repoDir);
226 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
227​
228 const manager = new GitManager({
229 textGenerator: createTextGenerator(),
230 });
231 const result = await manager.runStackedAction({
232 cwd: repoDir,
233 action: "commit",
234 });
235​
236 expect(result.commit.status).toBe("created");
237 expect(result.push.status).toBe("skipped_not_requested");
238 expect(result.pr.status).toBe("skipped_not_requested");
239 expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
240 "Implement stacked git actions",
241 );
242 });
243​
244 it("uses custom commit message when provided", async () => {
245 const repoDir = makeTempDir("t3code-git-manager-");
246 await initRepo(repoDir);
247 fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
248 let generatedCount = 0;
249​
250 const manager = new GitManager({
251 textGenerator: createTextGenerator({
252 generateCommitMessage: async () => {
253 generatedCount += 1;
254 return {
255 subject: "this should not be used",
256 body: "",
257 };
258 },
259 }),
260 });
261 const result = await manager.runStackedAction({
262 cwd: repoDir,
263 action: "commit",
264 commitMessage: "feat: custom summary line\n\n- details from user",
265 });
266​
267 expect(result.commit.status).toBe("created");
268 expect(result.commit.subject).toBe("feat: custom summary line");
269 expect(generatedCount).toBe(0);
270 expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
271 "feat: custom summary line",
272 );
273 expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%b"])).toContain(
274 "- details from user",
275 );
276 });
277​
278 it("skips commit when there are no uncommitted changes", async () => {
279 const repoDir = makeTempDir("t3code-git-manager-");
280 await initRepo(repoDir);
281​
282 const manager = new GitManager({
283 textGenerator: createTextGenerator(),
284 });
285 const result = await manager.runStackedAction({
286 cwd: repoDir,
287 action: "commit",
288 });
289​
290 expect(result.commit.status).toBe("skipped_no_changes");
291 expect(result.push.status).toBe("skipped_not_requested");
292 expect(result.pr.status).toBe("skipped_not_requested");
293 });
294​
295 it("commits and pushes with upstream auto-setup when needed", async () => {
296 const repoDir = makeTempDir("t3code-git-manager-");
297 await initRepo(repoDir);
298 await runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
299 const remoteDir = await createBareRemote();
300 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
301 fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
302​
303 const manager = new GitManager({
304 textGenerator: createTextGenerator(),
305 });
306 const result = await manager.runStackedAction({
307 cwd: repoDir,
308 action: "commit_push",
309 });
310​
311 expect(result.commit.status).toBe("created");
312 expect(result.push.status).toBe("pushed");
313 expect(result.push.setUpstream).toBe(true);
314 expect(await runGitStdout(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
315 "origin/feature/stacked-flow",
316 );
317 });
318​
319 it("skips push when branch is already up to date", async () => {
320 const repoDir = makeTempDir("t3code-git-manager-");
321 await initRepo(repoDir);
322 await runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
323 const remoteDir = await createBareRemote();
324 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
325 await runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
326​
327 const manager = new GitManager({
328 textGenerator: createTextGenerator(),
329 });
330 const result = await manager.runStackedAction({
331 cwd: repoDir,
332 action: "commit_push",
333 });
334​
335 expect(result.commit.status).toBe("skipped_no_changes");
336 expect(result.push.status).toBe("skipped_up_to_date");
337 });
338​
339 it("returns existing PR metadata for commit/push/pr action", async () => {
340 const repoDir = makeTempDir("t3code-git-manager-");
341 await initRepo(repoDir);
342 await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
343 const remoteDir = await createBareRemote();
344 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
345 await runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
346​
347 const { runner, ghCalls } = createRunnerWithFakeGh({
348 prListSequence: [
349 JSON.stringify([
350 {
351 number: 42,
352 title: "Existing PR",
353 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
354 baseRefName: "main",
355 headRefName: "feature/existing-pr",
356 },
357 ]),
358 ],
359 });
360​
361 const manager = new GitManager({
362 runProcess: runner,
363 textGenerator: createTextGenerator(),
364 });
365 const result = await manager.runStackedAction({
366 cwd: repoDir,
367 action: "commit_push_pr",
368 });
369​
370 expect(result.pr.status).toBe("opened_existing");
371 expect(result.pr.number).toBe(42);
372 expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
373 });
374​
375 it("creates PR when one does not already exist", async () => {
376 const repoDir = makeTempDir("t3code-git-manager-");
377 await initRepo(repoDir);
378 await runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
379 const remoteDir = await createBareRemote();
380 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
381 fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
382 await runGit(repoDir, ["add", "changes.txt"]);
383 await runGit(repoDir, ["commit", "-m", "Feature commit"]);
384 await runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
385 await runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
386​
387 const { runner, ghCalls } = createRunnerWithFakeGh({
388 prListSequence: [
389 "[]",
390 JSON.stringify([
391 {
392 number: 88,
393 title: "Add stacked git actions",
394 url: "https://github.com/pingdotgg/codething-mvp/pull/88",
395 baseRefName: "main",
396 headRefName: "feature-create-pr",
397 },
398 ]),
399 ],
400 });
401​
402 const manager = new GitManager({
403 runProcess: runner,
404 textGenerator: createTextGenerator(),
405 });
406 const result = await manager.runStackedAction({
407 cwd: repoDir,
408 action: "commit_push_pr",
409 });
410​
411 expect(result.pr.status).toBe("created");
412 expect(result.pr.number).toBe(88);
413 expect(
414 ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
415 ).toBe(true);
416 expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
417 });
418​
419 it("rejects push/pr actions from detached HEAD", async () => {
420 const repoDir = makeTempDir("t3code-git-manager-");
421 await initRepo(repoDir);
422 await runGit(repoDir, ["checkout", "--detach", "HEAD"]);
423​
424 const manager = new GitManager({
425 textGenerator: createTextGenerator(),
426 });
427 await expect(
428 manager.runStackedAction({
429 cwd: repoDir,
430 action: "commit_push",
431 }),
432 ).rejects.toThrow("detached HEAD");
433 });
434​
435 it("surfaces missing gh binary errors", async () => {
436 const repoDir = makeTempDir("t3code-git-manager-");
437 await initRepo(repoDir);
438 await runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
439 const remoteDir = await createBareRemote();
440 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
441 await runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
442​
443 const { runner } = createRunnerWithFakeGh({
444 failWith: new Error("Command not found: gh"),
445 });
446 const manager = new GitManager({
447 runProcess: runner,
448 textGenerator: createTextGenerator(),
449 });
450​
451 await expect(
452 manager.runStackedAction({
453 cwd: repoDir,
454 action: "commit_push_pr",
455 }),
456 ).rejects.toThrow("GitHub CLI (`gh`) is required");
457 });
458​
459 it("surfaces gh auth errors with guidance", async () => {
460 const repoDir = makeTempDir("t3code-git-manager-");
461 await initRepo(repoDir);
462 await runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
463 const remoteDir = await createBareRemote();
464 await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
465 await runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
466​
467 const { runner } = createRunnerWithFakeGh({
468 failWith: new Error("authentication failed"),
469 });
470 const manager = new GitManager({
471 runProcess: runner,
472 textGenerator: createTextGenerator(),
473 });
474​
475 await expect(
476 manager.runStackedAction({
477 cwd: repoDir,
478 action: "commit_push_pr",
479 }),
480 ).rejects.toThrow("gh auth login");
481 });
482});