Fix git branch indicator in subdirectories

Walk up directory hierarchy to find .git/HEAD instead of only checking cwd.

fixes #156
This commit is contained in:
Mario Zechner 2025-12-10 22:52:19 +01:00
parent 1fe87bc50d
commit 79f5c6d22e
2 changed files with 30 additions and 4 deletions

View file

@ -12,6 +12,8 @@
- **In-memory branching for `--no-session` mode**: Branching now works correctly in `--no-session` mode without creating any session files. The conversation is truncated in memory.
- **Git branch indicator now works in subdirectories**: The footer's git branch detection now walks up the directory hierarchy to find the git root, so it works when running pi from a subdirectory of a repository. ([#156](https://github.com/badlogic/pi-mono/issues/156))
## [0.18.1] - 2025-12-10
### Added

View file

@ -2,10 +2,30 @@ import type { AgentState } from "@mariozechner/pi-agent-core";
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { type Component, visibleWidth } from "@mariozechner/pi-tui";
import { existsSync, type FSWatcher, readFileSync, watch } from "fs";
import { join } from "path";
import { dirname, join } from "path";
import { isModelUsingOAuth } from "../../../core/model-config.js";
import { theme } from "../theme/theme.js";
/**
* Find the git root directory by walking up from cwd.
* Returns the path to .git/HEAD 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 parent = dirname(dir);
if (parent === dir) {
// Reached filesystem root
return null;
}
dir = parent;
}
}
/**
* Footer component that shows pwd, token stats, and context usage
*/
@ -40,8 +60,8 @@ export class FooterComponent implements Component {
this.gitWatcher = null;
}
const gitHeadPath = join(process.cwd(), ".git", "HEAD");
if (!existsSync(gitHeadPath)) {
const gitHeadPath = findGitHeadPath();
if (!gitHeadPath) {
return;
}
@ -87,7 +107,11 @@ export class FooterComponent implements Component {
}
try {
const gitHeadPath = join(process.cwd(), ".git", "HEAD");
const gitHeadPath = findGitHeadPath();
if (!gitHeadPath) {
this.cachedBranch = null;
return null;
}
const content = readFileSync(gitHeadPath, "utf8").trim();
if (content.startsWith("ref: refs/heads/")) {