Fix status bar git branch detection in worktrees and submodules

This commit is contained in:
Kevin 2026-01-05 21:20:56 -06:00 committed by Mario Zechner
parent 9063a71fe6
commit 6cb3135695
2 changed files with 33 additions and 7 deletions

View file

@ -1,7 +1,7 @@
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { type Component, truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
import { existsSync, type FSWatcher, readFileSync, watch } from "fs";
import { dirname, join } from "path";
import { existsSync, type FSWatcher, readFileSync, statSync, watch } from "fs";
import { dirname, join, resolve } from "path";
import type { AgentSession } from "../../../core/agent-session.js";
import { theme } from "../theme/theme.js";
@ -18,15 +18,37 @@ function sanitizeStatusText(text: string): string {
}
/**
* Find the git root directory by walking up from cwd.
* Returns the path to .git/HEAD if found, null otherwise.
* Find the git HEAD path by walking up from cwd.
* Handles both regular git repos (.git is a directory) and worktrees (.git is a file).
* Returns the path to the HEAD file if found, null otherwise.
*/
function findGitHeadPath(): string | null {
let dir = process.cwd();
while (true) {
const gitHeadPath = join(dir, ".git", "HEAD");
if (existsSync(gitHeadPath)) {
return gitHeadPath;
const gitPath = join(dir, ".git");
if (existsSync(gitPath)) {
try {
const stat = statSync(gitPath);
if (stat.isFile()) {
// Worktree: .git is a file containing "gitdir: <path>"
const content = readFileSync(gitPath, "utf8").trim();
if (content.startsWith("gitdir: ")) {
const gitDir = content.slice(8);
const headPath = resolve(dir, gitDir, "HEAD");
if (existsSync(headPath)) {
return headPath;
}
}
} else if (stat.isDirectory()) {
// Regular repo: .git is a directory
const headPath = join(gitPath, "HEAD");
if (existsSync(headPath)) {
return headPath;
}
}
} catch {
return null;
}
}
const parent = dirname(dir);
if (parent === dir) {