Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat: improve bare repo support with symbolic-ref HEAD heuristic (#417)

Maximilian Roosf87199d1b7b1
diff --git a/CLAUDE.md b/CLAUDE.md
index e06deac98..eb8c73bdc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -38,6 +38,23 @@ Example of escalating instead of suppressing:
fn parse_config() { ... }
```
+## Documentation
+
+**Behavior changes require documentation updates.** This is not optional.
+
+When changing:
+- Detection logic
+- CLI flags or their defaults
+- Error conditions or messages
+
+Ask: "Does `--help` still describe what the code does?" If not, update `src/cli.rs` first.
+
+After modifying `cli.rs`, sync the doc pages:
+
+```bash
+cargo test --test integration test_command_pages_are_in_sync
+```
+
## Data Safety
Never risk data loss without explicit user consent. Err on the side of failing safely.
diff --git a/docs/content/config.md b/docs/content/config.md
index 80c228390..e383f4d81 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -766,6 +766,7 @@ Once detected, the result is cached in `worktrunk.default-branch` for fast acces
The local inference fallback uses these heuristics in order:
- If only one local branch exists, uses it
+- For bare repos or empty repos, checks `symbolic-ref HEAD`
- Checks `git config init.defaultBranch`
- Looks for common names: main, master, develop, trunk
diff --git a/src/cli.rs b/src/cli.rs
index 1adb4010e..02cbaf4ca 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -456,6 +456,7 @@ Once detected, the result is cached in `worktrunk.default-branch` for fast acces
The local inference fallback uses these heuristics in order:
- If only one local branch exists, uses it
+- For bare repos or empty repos, checks `symbolic-ref HEAD`
- Checks `git config init.defaultBranch`
- Looks for common names: main, master, develop, trunk
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 44f775747..75918f192 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -685,6 +685,16 @@ pub fn collect(
}
}
);
+ // TODO: Make default_branch optional so wt list can gracefully degrade when detection fails.
+ // Currently, ambiguous repos (multiple non-standard branches, no remote) fail entirely.
+ // With symbolic-ref HEAD heuristic added, this is less common but still possible.
+ // Required changes:
+ // 1. Make default_branch Option<String> here
+ // 2. find_home() already handles empty default_branch (falls back to first)
+ // 3. Make main_worktree optional or use first worktree when default_branch is None
+ // 4. Update TaskContext.require_default_branch() callers to handle None gracefully
+ // (skip ahead/behind, integration status, etc. instead of failing)
+ // 5. Show warning when default_branch couldn't be determined
let default_branch = default_branch?;
let branches_without_worktrees = branches_without_worktrees?;
let remote_branches = remote_branches?;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index ec512d50d..3740d78a8 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -147,20 +147,9 @@ pub fn resolve_worktree_arg(
config: &WorktrunkConfig,
context: ResolutionContext,
) -> anyhow::Result<ResolvedWorktree> {
- // Special symbols
+ // Special symbols - delegate to Repository for consistent error handling
match name {
- "@" => {
- // Current worktree by path - works even in detached HEAD
- let path = repo.worktree_root()?.to_path_buf();
- let worktrees = repo.list_worktrees()?;
- let branch = worktrees
- .iter()
- .find(|wt| wt.path == path)
- .and_then(|wt| wt.branch.clone());
- return Ok(ResolvedWorktree::Worktree { path, branch });
- }
- "-" | "^" => {
- // These resolve to branch names, use standard branch-based lookup
+ "@" | "-" | "^" => {
return repo.resolve_worktree(name);
}
_ => {}
@@ -609,7 +598,14 @@ pub fn handle_switch(
let base_for_creation = if create {
match resolved_base {
Some(b) => Some(b),
- None => repo.resolve_target_branch(None).ok(),
+ None => {
+ // Try to use default branch as base, but only if it actually exists
+ // (has commits). For empty repos, the default branch is unborn and
+ // git will automatically create an orphan worktree.
+ repo.resolve_target_branch(None)
+ .ok()
+ .filter(|b| repo.local_branch_exists(b).unwrap_or(false))
+ }
}
} else {
None
diff --git a/src/git/error.rs b/src/git/error.rs
index bf5b82a0b..feb93c747 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -58,6 +58,10 @@ pub enum GitError {
},
// Worktree errors
+ NotInWorktree {
+ /// The action that requires being in a worktree
+ action: Option<String>,
+ },
WorktreeMissing {
branch: String,
},
@@ -207,6 +211,21 @@ impl std::fmt::Display for GitError {
)
}
+ GitError::NotInWorktree { action } => {
+ let message = match action {
+ Some(action) => format!("Cannot {action}: not in a worktree"),
+ None => "Not in a worktree".to_string(),
+ };
+ write!(
+ f,
+ "{}\n{}",
+ error_message(&message),
+ hint_message(cformat!(
+ "Run this command from inside a worktree, or specify a branch name"
+ ))
+ )
+ }
+
GitError::WorktreeMissing { branch } => {
write!(
f,
@@ -898,6 +917,23 @@ mod tests {
assert!(display.contains("--create"));
}
+ #[test]
+ fn test_git_error_not_in_worktree() {
+ // With action
+ let err = GitError::NotInWorktree {
+ action: Some("resolve '@'".into()),
+ };
+ let display = err.to_string();
+ assert!(display.contains("Cannot resolve '@'"));
+ assert!(display.contains("not in a worktree"));
+ assert!(display.contains("specify a branch name"));
+
+ // Without action
+ let err = GitError::NotInWorktree { action: None };
+ let display = err.to_string();
+ assert!(display.contains("Not in a worktree"));
+ }
+
#[test]
fn test_git_error_worktree_missing() {
let err = GitError::WorktreeMissing {
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 88eca49b2..b2c828a13 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -369,13 +369,19 @@ impl Repository {
match name {
"@" => {
// Current worktree by path - works even in detached HEAD
- let path = self.worktree_root()?.to_path_buf();
+ // If worktree_root fails (e.g., in bare repo directory), give a clear error
+ let path = self.worktree_root().map_err(|_| GitError::NotInWorktree {
+ action: Some("resolve '@'".into()),
+ })?;
let worktrees = self.list_worktrees()?;
let branch = worktrees
.iter()
.find(|wt| wt.path == path)
.and_then(|wt| wt.branch.clone());
- Ok(ResolvedWorktree::Worktree { path, branch })
+ Ok(ResolvedWorktree::Worktree {
+ path: path.to_path_buf(),
+ branch,
+ })
}
_ => {
// Resolve to branch name first, then find its worktree
@@ -471,9 +477,10 @@ impl Repository {
///
/// Uses local heuristics when no remote is available:
/// 1. If only one local branch exists, use it
- /// 2. Check user's git config init.defaultBranch
- /// 3. Look for common branch names (main, master, develop, trunk)
- /// 4. Fail if none of the above work
+ /// 2. Check symbolic-ref HEAD (authoritative for bare repos, works before first commit)
+ /// 3. Check user's git config init.defaultBranch (if branch exists)
+ /// 4. Look for common branch names (main, master, develop, trunk)
+ /// 5. Fail if none of the above work
fn infer_default_branch_locally(&self) -> anyhow::Result<String> {
// 1. If there's only one local branch, use it
let branches = self.local_branches()?;
@@ -481,7 +488,21 @@ impl Repository {
return Ok(branches[0].clone());
}
- // 2. Check git config init.defaultBranch
+ // 2. Check symbolic-ref HEAD - authoritative for bare repos and empty repos
+ // - Bare repo directory: HEAD always points to the default branch
+ // - Empty repos: No branches exist yet, but HEAD tells us the intended default
+ // - Linked worktrees: HEAD points to CURRENT branch, so skip this heuristic
+ // - Normal repos: HEAD points to CURRENT branch, so skip this heuristic
+ let is_bare = self.is_bare().unwrap_or(false);
+ let in_worktree = self.is_in_worktree().unwrap_or(false);
+ if ((is_bare && !in_worktree) || branches.is_empty())
+ && let Ok(head_ref) = self.run_command(&["symbolic-ref", "HEAD"])
+ && let Some(branch) = head_ref.trim().strip_prefix("refs/heads/")
+ {
+ return Ok(branch.to_string());
+ }
+
+ // 3. Check git config init.defaultBranch (if branch exists)
if let Ok(default) = self.run_command(&["config", "--get", "init.defaultBranch"]) {
let branch = default.trim().to_string();
if !branch.is_empty() && branches.contains(&branch) {
@@ -489,14 +510,14 @@ impl Repository {
}
}
- // 3. Look for common branch names
+ // 4. Look for common branch names
for name in ["main", "master", "develop", "trunk"] {
if branches.contains(&name.to_string()) {
return Ok(name.to_string());
}
}
- // 4. Give up — can't infer
+ // 5. Give up — can't infer
Err(GitError::Other {
message:
"Could not infer default branch. Please specify target branch explicitly or set up a remote."
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index 0b3d7142d..8709563b2 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -176,6 +176,8 @@ fn test_get_default_branch_no_remote_fails_when_no_match(repo: TestRepo) {
repo.git_command().args(["branch", "def"]).status().unwrap();
// Now we have: xyz, abc, def - no common names, no init.defaultBranch
+ // In normal repos (not bare), symbolic-ref HEAD isn't used because HEAD
+ // points to the current branch, not the default branch.
// Should fail with an error
let result = Repository::at(repo.root_path()).default_branch();
assert!(result.is_err());
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap
index da5e465ac..7dfccb049 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap
@@ -57,6 +57,7 @@ Once detected, the result is cached in worktrunk.default-branch for fast
The local inference fallback uses these heuristics in order:
- If only one local branch exists, uses it
+- For bare repos or empty repos, checks symbolic-ref HEAD
- Checks git config init.defaultBranch
- Looks for common names: main, master, develop, trunk