Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions src/git/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,33 @@ export async function getStagedDiffWithSignal(
}
}

function isUnbornHead(): boolean {
let headRef: string;
try {
headRef = execFileSync(getGitExecutable(), ['symbolic-ref', '--quiet', 'HEAD'], {
encoding: 'utf-8',
stdio: 'pipe',
}).trim();
} catch {
// A detached or malformed HEAD is not the normal empty-repository state.
return false;
}

try {
const refs = execFileSync(getGitExecutable(), ['for-each-ref', '--format=%(refname)', headRef], {
encoding: 'utf-8',
stdio: 'pipe',
})
.split(/\r?\n/)
.filter(Boolean);

return headRef.length > 0 && !refs.includes(headRef);
} catch {
// If the ref database cannot be queried, keep the original fatal Git error.
return false;
}
}

export function hasCommits(): boolean {
try {
const count = execFileSync(getGitExecutable(), ['rev-list', '--count', 'HEAD'], {
Expand All @@ -178,8 +205,14 @@ export function hasCommits(): boolean {
}).trim();

return Number.parseInt(count, 10) > 0;
} catch {
return false;
} catch (err) {
if (isUnbornHead()) {
return false;
}

const nodeErr = err as NodeJS.ErrnoException & { stderr?: string };
const stderr = nodeErr.stderr?.trim();
throw new Error(stderr || nodeErr.message || 'Failed to inspect git history');
}
}

Expand Down
17 changes: 17 additions & 0 deletions tests/git-diff.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,23 @@ test("hasCommits returns true after the first commit", () => {
}
});

test("hasCommits propagates a fatal HEAD error", () => {
const repoDir = initRepo();

try {
git(["commit", "--allow-empty", "-m", "initial commit"], repoDir);
const headRef = git(["symbolic-ref", "--quiet", "HEAD"], repoDir).trim();
const headPath = join(repoDir, ".git", "refs", "heads", headRef.slice("refs/heads/".length));
writeFileSync(headPath, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n", "utf-8");

withCwd(repoDir, () => {
assert.throws(() => hasCommits(), /unknown revision|bad object|ambiguous argument/i);
});
} finally {
rmSync(repoDir, { recursive: true, force: true });
}
});

test("getStagedDiff returns diff when changes are staged", () => {
const repoDir = initRepo();

Expand Down
Loading