Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: centralize home worktree lookup with find_home() and home_path() (#409)
Maximilian Roosbac5eeab14e3
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 032bac183..44f775747 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -689,12 +689,11 @@ pub fn collect(let branches_without_worktrees = branches_without_worktrees?;let remote_branches = remote_branches?;- // Main worktree is the worktree on the default branch (if exists), else first worktree- let main_worktree = worktrees- .iter()- .find(|wt| wt.branch.as_deref() == Some(default_branch.as_str()))+ // Main worktree is the worktree on the default branch (if exists), else first worktree.+ // find_home returns None only if worktrees is empty, which shouldn't happen for wt list.+ let main_worktree = Worktree::find_home(&worktrees, &default_branch).cloned()- .unwrap_or_else(|| worktrees[0].clone());+ .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;// Defer previous_branch lookup until after skeleton - set is_previous later// (skeleton shows placeholder gutter, actual symbols appear when data loads)diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex be9038e61..03f89bd69 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -95,7 +95,6 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// Get target branch (default to default branch if not provided)let target_branch = repo.resolve_target_branch(target)?;- let worktrees = repo.list_worktrees()?;// Worktree for target is optional: if present we use it for safety checks and as destination.let target_worktree_path = repo.worktree_for_branch(&target_branch)?;@@ -192,10 +191,11 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {}),)?;- // Destination: prefer the target branch's worktree; fall back to main when absent- let destination_path = target_worktree_path- .clone()- .unwrap_or_else(|| worktrees[0].path.clone());+ // Destination: prefer the target branch's worktree; fall back to home path.+ let destination_path = match target_worktree_path {+ Some(path) => path,+ None => repo.home_path()?,+ };// Finish worktree unless --no-remove was specifiedif remove_effective {diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 58b5476ca..09ef9b915 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -72,7 +72,9 @@ impl RepositoryCliExt for Repository {) -> anyhow::Result<RemoveResult> {let current_path = self.worktree_root()?.to_path_buf();let worktrees = self.list_worktrees()?;- let main_worktree_path = worktrees[0].path.clone();+ // Home worktree: prefer default branch's worktree, fall back to first worktree,+ // then repo base for bare repos with no worktrees.+ let home_worktree_path = self.home_path()?;// Resolve target to worktree path and branchlet (worktree_path, branch_name, is_current) = match target {@@ -158,13 +160,14 @@ impl RepositoryCliExt for Repository {// Compute main_path and changed_directory based on whether we're removing currentlet (main_path, changed_directory) = if is_current {- (main_worktree_path, true)+ (home_worktree_path, true)} else {(current_path, false)};- // Resolve default branch for integration reason display+ // Resolve target branch for integration reason display// Skip if removing the default branch itself (avoids tautological "main (ancestor of main)")+ // Use .ok() to treat errors as unknown - safer than empty string for integration checkslet default_branch = self.default_branch().ok();let target_branch = match (&default_branch, &branch_name) {(Some(db), Some(bn)) if db == bn => None,diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 95967f20c..de9fa6bb5 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -11,7 +11,7 @@ use anyhow::{Context, Result};use std::env;use std::io::{self, Read};use std::path::Path;-use worktrunk::git::Repository;+use worktrunk::git::{Repository, Worktree};use super::list::{self, CollectOptions};@@ -233,15 +233,15 @@ fn get_git_status(repo: &Repository, cwd: &Path, include_links: bool) -> Result<// Effective target for integration checks: upstream if ahead of local, else local.let integration_target = repo.effective_integration_target(&default_branch);- // Determine if this is the main worktree- let main_worktree = worktrees- .iter()- .find(|w| w.branch.as_deref() == Some(default_branch.as_str()))- .unwrap_or(&worktrees[0]);- let is_main = wt.path == main_worktree.path;+ // Determine if this is the home worktree (default branch's worktree, or first if none)+ // Use the already-fetched worktrees to avoid a redundant git command+ // Note: called `is_home` here because bare repos have no git "main worktree" -+ // all worktrees are linked. The `is_main` param in build_worktree_item is for display.+ let home_worktree = Worktree::find_home(&worktrees, &default_branch);+ let is_home = home_worktree.is_some_and(|hw| wt.path == hw.path);// Build item with identity fields- let mut item = list::build_worktree_item(wt, is_main, true, false);+ let mut item = list::build_worktree_item(wt, is_home, true, false);// Populate computed fields (parallel git operations) and format status_line// Compute everything (same as --full) for complete status symbolsdiff --git a/src/git/mod.rs b/src/git/mod.rsindex 966bb642e..8c1de914a 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -326,6 +326,25 @@ impl Worktree {pub fn dir_name(&self) -> &str {path_dir_name(&self.path)}++ /// Find the "home" worktree - the default branch's worktree if it exists,+ /// otherwise the first worktree in the list.+ ///+ /// This is the preferred destination when we need to cd somewhere+ /// (e.g., after removing the current worktree, or after merge removes the worktree).+ ///+ /// For normal repos, `worktrees[0]` is usually the default branch's worktree,+ /// so the fallback rarely matters. For bare repos, there's no semantic "main"+ /// worktree, so preferring the default branch's worktree provides consistency.+ ///+ /// Returns `None` only if `worktrees` is empty. If `default_branch` is empty+ /// or doesn't match any worktree, returns the first worktree.+ pub fn find_home<'a>(worktrees: &'a [Worktree], default_branch: &str) -> Option<&'a Worktree> {+ worktrees+ .iter()+ .find(|wt| wt.branch.as_deref() == Some(default_branch))+ .or_else(|| worktrees.first())+ }}// Helper functions for worktree parsing@@ -476,4 +495,48 @@ mod tests {assert_eq!(format!("{hook}"), expected);}}++ #[test]+ fn test_find_home() {+ let make_wt = |branch: Option<&str>| Worktree {+ path: PathBuf::from(format!("/repo.{}", branch.unwrap_or("detached"))),+ head: "abc123".into(),+ branch: branch.map(String::from),+ bare: false,+ detached: branch.is_none(),+ locked: None,+ prunable: None,+ };++ // Empty list returns None+ assert!(Worktree::find_home(&[], "main").is_none());++ // Single worktree on default branch+ let wts = vec![make_wt(Some("main"))];+ assert_eq!(+ Worktree::find_home(&wts, "main").unwrap().path.to_str(),+ Some("/repo.main")+ );++ // Default branch not first - should still find it+ let wts = vec![make_wt(Some("feature")), make_wt(Some("main"))];+ assert_eq!(+ Worktree::find_home(&wts, "main").unwrap().path.to_str(),+ Some("/repo.main")+ );++ // No default branch match - returns first+ let wts = vec![make_wt(Some("feature")), make_wt(Some("bugfix"))];+ assert_eq!(+ Worktree::find_home(&wts, "main").unwrap().path.to_str(),+ Some("/repo.feature")+ );++ // Empty default branch - returns first+ let wts = vec![make_wt(Some("feature"))];+ assert_eq!(+ Worktree::find_home(&wts, "").unwrap().path.to_str(),+ Some("/repo.feature")+ );+ }}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 3fcdfcf6e..88eca49b2 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -595,6 +595,25 @@ impl Repository {.cloned()}+ /// Find the "home" path - where to cd when leaving a worktree.+ ///+ /// This is the preferred destination after removing the current worktree+ /// or after merge removes the worktree. Priority:+ /// 1. The default branch's worktree (if it exists)+ /// 2. The first worktree in the list+ /// 3. The repo base directory (for bare repos with no worktrees)+ pub fn home_path(&self) -> anyhow::Result<PathBuf> {+ let worktrees = self.list_worktrees()?;+ let default_branch = self.default_branch().unwrap_or_default();++ if let Some(home) = Worktree::find_home(&worktrees, &default_branch) {+ return Ok(home.path.clone());+ }++ // No worktrees - fall back to repo base (bare repo case)+ self.worktree_base()+ }+/// Check if this is a bare repository (no working tree).////// Bare repositories have no main worktree — all worktrees are linked