@@ -1,173 +1,179 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import {
3- mkdirSync,
4- mkdtempSync,
5- rmSync,
6- symlinkSync,
7- writeFileSync,
8-} from "node:fs";
9-import { tmpdir } from "node:os";
10-import { join } from "node:path";
11-import { getGitState } from "./git.ts";
12-import { canonicalizePath } from "./paths.ts";
13-
14-// ---------------------------------------------------------------------------
15-// Helpers
16-// ---------------------------------------------------------------------------
17-
18-let tmp: string;
19-
20-beforeEach(() => {
21- tmp = mkdtempSync(join(tmpdir(), "mc-git-"));
22-});
23-
24-afterEach(() => {
25- rmSync(tmp, { recursive: true, force: true });
26-});
27-
28-function expectGitState(
29- state: Awaited<ReturnType<typeof getGitState>>,
30-): NonNullable<Awaited<ReturnType<typeof getGitState>>> {
31- if (!state) {
32- throw new Error("Expected a git state snapshot");
33- }
34- return state;
35-}
36-
37-/** Run a git command in the temp directory. */
38-async function git(args: string, cwd = tmp): Promise<string> {
39- const proc = Bun.spawn(["git", ...args.split(" ")], {
40- cwd,
41- stdout: "pipe",
42- stderr: "pipe",
43- env: {
44- ...process.env,
45- GIT_AUTHOR_NAME: "Test",
46- GIT_AUTHOR_EMAIL: "test@test.com",
47- GIT_COMMITTER_NAME: "Test",
48- GIT_COMMITTER_EMAIL: "test@test.com",
49- },
1+import { describe, expect, test } from "bun:test";
2+import { getGitState, parseGitAheadBehind, parseGitStatus } from "./git.ts";
3+
4+describe("parseGitStatus", () => {
5+ test("returns zero counts for empty output", () => {
6+ expect(parseGitStatus("")).toEqual({
7+ staged: 0,
8+ modified: 0,
9+ untracked: 0,
10+ });
5011 });
51- const out = await new Response(proc.stdout as ReadableStream).text();
52- await proc.exited;
53- return out.trim();
54-}
5512
56-/** Initialize a git repo with one commit so HEAD exists. */
57-async function initRepo(cwd = tmp): Promise<void> {
58- await git("init", cwd);
59- writeFileSync(join(cwd, "README.md"), "# init\n");
60- await git("add .", cwd);
61- await git("commit -m init", cwd);
62-}
63-
64-// ---------------------------------------------------------------------------
65-// Tests
66-// ---------------------------------------------------------------------------
67-
68-describe("getGitState", () => {
69- test("returns null outside a git repo", async () => {
70- const state = await getGitState(tmp);
71- expect(state).toBeNull();
13+ test("counts mixed porcelain states", () => {
14+ expect(
15+ parseGitStatus(
16+ [
17+ "M staged-only.txt",
18+ " M modified-only.txt",
19+ "MM staged-and-modified.txt",
20+ "?? new-file.txt",
21+ ].join("\n"),
22+ ),
23+ ).toEqual({
24+ staged: 2,
25+ modified: 2,
26+ untracked: 1,
27+ });
7228 });
7329
74- test("detects repo root", async () => {
75- await initRepo();
76- const state = expectGitState(await getGitState(tmp));
77- expect(state.root).toBe(canonicalizePath(tmp));
30+ test("treats rename and delete statuses as tracked changes", () => {
31+ expect(
32+ parseGitStatus(
33+ [
34+ "R renamed.txt -> renamed-again.txt",
35+ " D deleted.txt",
36+ "A added.txt",
37+ ].join("\n"),
38+ ),
39+ ).toEqual({
40+ staged: 2,
41+ modified: 1,
42+ untracked: 0,
43+ });
7844 });
45+});
7946
80- test("gets current branch name", async () => {
81- await initRepo();
82- const state = expectGitState(await getGitState(tmp));
83- expect(state.branch).toBeOneOf(["main", "master"]);
84- });
85-
86- test("counts untracked files", async () => {
87- await initRepo();
88- writeFileSync(join(tmp, "new.txt"), "untracked");
89- const state = expectGitState(await getGitState(tmp));
90- expect(state.untracked).toBe(1);
91- });
92-
93- test("counts modified files", async () => {
94- await initRepo();
95- writeFileSync(join(tmp, "README.md"), "modified\n");
96- const state = expectGitState(await getGitState(tmp));
97- expect(state.modified).toBe(1);
98- });
99-
100- test("counts staged files", async () => {
101- await initRepo();
102- writeFileSync(join(tmp, "README.md"), "staged\n");
103- await git("add README.md");
104- const state = expectGitState(await getGitState(tmp));
105- expect(state.staged).toBe(1);
106- });
107-
108- test("counts mixed states correctly", async () => {
109- await initRepo();
110- // Stage a change
111- writeFileSync(join(tmp, "README.md"), "staged\n");
112- await git("add README.md");
113- // Add an untracked file
114- writeFileSync(join(tmp, "new.txt"), "untracked");
115- // Add a modified (but not staged) file — modify README again after staging
116- writeFileSync(join(tmp, "README.md"), "staged then modified\n");
117-
118- const state = expectGitState(await getGitState(tmp));
119- expect(state.staged).toBe(1);
120- expect(state.modified).toBe(1);
121- expect(state.untracked).toBe(1);
47+describe("parseGitAheadBehind", () => {
48+ test("parses ahead and behind counts from rev-list output", () => {
49+ expect(parseGitAheadBehind("3\t2")).toEqual({ ahead: 3, behind: 2 });
12250 });
12351
124- test("returns zero ahead/behind when no upstream", async () => {
125- await initRepo();
126- const state = expectGitState(await getGitState(tmp));
127- expect(state.upstream).toBeNull();
128- expect(state.ahead).toBe(0);
129- expect(state.behind).toBe(0);
52+ test("defaults missing or invalid values to zero", () => {
53+ expect(parseGitAheadBehind("")).toEqual({ ahead: 0, behind: 0 });
54+ expect(parseGitAheadBehind("nope nope")).toEqual({ ahead: 0, behind: 0 });
55+ expect(parseGitAheadBehind("5")).toEqual({ ahead: 5, behind: 0 });
13056 });
57+});
13158
132- test("detects ahead count relative to upstream", async () => {
133- // Create a bare "remote" repo
134- const bare = join(tmp, "remote.git");
135- await git(`init --bare ${bare}`);
136-
137- // Init a working repo and push
138- const work = join(tmp, "work");
139- await git(`clone ${bare} ${work}`);
140- writeFileSync(join(work, "file.txt"), "initial\n");
141- await git("add .", work);
142- await git("commit -m first", work);
143- await git("push origin HEAD", work);
144-
145- // Make a local commit (ahead by 1)
146- writeFileSync(join(work, "file.txt"), "updated\n");
147- await git("add .", work);
148- await git("commit -m second", work);
59+describe("getGitState", () => {
60+ test("returns null when git reports the cwd is not in a repo", async () => {
61+ const state = await getGitState("/tmp/not-a-repo", {
62+ run: async (args) => {
63+ expect(args).toEqual(["rev-parse", "--show-toplevel"]);
64+ return null;
65+ },
66+ });
14967
150- const state = expectGitState(await getGitState(work));
151- expect(state.upstream).toBeOneOf(["origin/main", "origin/master"]);
152- expect(state.ahead).toBe(1);
153- expect(state.behind).toBe(0);
68+ expect(state).toBeNull();
15469 });
15570
156- test("works from a subdirectory", async () => {
157- await initRepo();
158- const sub = join(tmp, "src", "deep");
159- mkdirSync(sub, { recursive: true });
160-
161- const state = expectGitState(await getGitState(sub));
162- expect(state.root).toBe(canonicalizePath(tmp));
71+ test("builds git state by parsing command output", async () => {
72+ const calls: Array<{ args: string[]; cwd: string; trim: boolean }> = [];
73+ const responses = new Map<string, string | null>([
74+ ["rev-parse --show-toplevel", "/repo"],
75+ ["branch --show-current", "main"],
76+ [
77+ "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
78+ "origin/main",
79+ ],
80+ [
81+ "status --porcelain",
82+ [
83+ "M staged-only.txt",
84+ " M modified-only.txt",
85+ "MM staged-and-modified.txt",
86+ "?? new-file.txt",
87+ ].join("\n"),
88+ ],
89+ ["rev-list --left-right --count HEAD...@{upstream}", "4\t1"],
90+ ]);
91+
92+ const state = await getGitState("/repo/subdir", {
93+ run: async (args, cwd, trim = true) => {
94+ calls.push({ args, cwd, trim });
95+ const key = args.join(" ");
96+ if (!responses.has(key)) {
97+ throw new Error(`Unexpected git command: ${key}`);
98+ }
99+ return responses.get(key) ?? null;
100+ },
101+ });
102+
103+ expect(state).toEqual({
104+ root: "/repo",
105+ branch: "main",
106+ upstream: "origin/main",
107+ staged: 2,
108+ modified: 2,
109+ untracked: 1,
110+ ahead: 4,
111+ behind: 1,
112+ });
113+ expect(calls).toEqual([
114+ {
115+ args: ["rev-parse", "--show-toplevel"],
116+ cwd: "/repo/subdir",
117+ trim: true,
118+ },
119+ {
120+ args: ["branch", "--show-current"],
121+ cwd: "/repo/subdir",
122+ trim: true,
123+ },
124+ {
125+ args: [
126+ "rev-parse",
127+ "--abbrev-ref",
128+ "--symbolic-full-name",
129+ "@{upstream}",
130+ ],
131+ cwd: "/repo/subdir",
132+ trim: true,
133+ },
134+ {
135+ args: ["status", "--porcelain"],
136+ cwd: "/repo/subdir",
137+ trim: false,
138+ },
139+ {
140+ args: ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"],
141+ cwd: "/repo/subdir",
142+ trim: true,
143+ },
144+ ]);
163145 });
164146
165- test("returns the canonical repo root when accessed through a symlink", async () => {
166- await initRepo();
167- mkdirSync(join(tmp, "src"), { recursive: true });
168- symlinkSync(tmp, join(tmp, "alias"));
169-
170- const state = expectGitState(await getGitState(join(tmp, "alias", "src")));
171- expect(state.root).toBe(canonicalizePath(tmp));
147+ test("falls back to empty branch, null upstream, and zero counts when optional commands fail", async () => {
148+ const state = await getGitState("/repo", {
149+ run: async (args) => {
150+ const key = args.join(" ");
151+ switch (key) {
152+ case "rev-parse --show-toplevel":
153+ return "/repo";
154+ case "branch --show-current":
155+ return null;
156+ case "rev-parse --abbrev-ref --symbolic-full-name @{upstream}":
157+ return null;
158+ case "status --porcelain":
159+ return null;
160+ case "rev-list --left-right --count HEAD...@{upstream}":
161+ return null;
162+ default:
163+ throw new Error(`Unexpected git command: ${key}`);
164+ }
165+ },
166+ });
167+
168+ expect(state).toEqual({
169+ root: "/repo",
170+ branch: "",
171+ upstream: null,
172+ staged: 0,
173+ modified: 0,
174+ untracked: 0,
175+ ahead: 0,
176+ behind: 0,
177+ });
172178 });
173179 });