Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: simplify home_path to use primary_worktree directly (#786)
Maximilian Roosb122a4a86458
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 889983bb0..b38ef266a 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -310,13 +310,17 @@ pub fn collect(crate::output::print(hint_message(hint))?;}- // Main worktree is the worktree on the default branch (if exists), else first non-prunable worktree.- // find_home returns None if all worktrees are prunable or the list is empty.+ // Main worktree is the primary worktree (for sorting and is_main display).+ // - Normal repos: the main worktree (repo root)+ // - Bare repos: the default branch's worktree// TODO: show ellipsis or indicator when default_branch is None and columns are empty- let main_worktree =- WorktreeInfo::find_home(&worktrees, default_branch.as_deref().unwrap_or(""))- .cloned()- .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;+ let primary_path = repo.primary_worktree()?;+ let main_worktree = primary_path+ .as_ref()+ .and_then(|p| worktrees.iter().find(|wt| wt.path == *p))+ .or_else(|| worktrees.iter().find(|wt| !wt.is_prunable()))+ .cloned()+ .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/statusline.rs b/src/commands/statusline.rsindex 334160411..1de177330 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, WorktreeInfo};+use worktrunk::git::Repository;use worktrunk::styling::{get_terminal_width, truncate_visible};use super::list::{self, CollectOptions, StatuslineSegment};@@ -264,24 +264,22 @@ fn get_git_status_segments(return Ok(vec![]);};- // Get default branch for comparisons- let default_branch = match repo.default_branch() {- Some(b) => b,- None => {- // Can't determine default branch - just show current branch- return Ok(vec![StatuslineSegment::from_column(- wt.branch.as_deref().unwrap_or("HEAD").to_string(),- ColumnKind::Branch,- )]);- }- };+ // If we can't determine the default branch, just show current branch+ if repo.default_branch().is_none() {+ return Ok(vec![StatuslineSegment::from_column(+ wt.branch.as_deref().unwrap_or("HEAD").to_string(),+ ColumnKind::Branch,+ )]);+ }- // 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 = WorktreeInfo::find_home(&worktrees, &default_branch);- let is_home = home_worktree.is_some_and(|hw| wt.path == hw.path);+ // Determine if this is the primary worktree+ // - Normal repos: the main worktree (repo root)+ // - Bare repos: the default branch's worktree+ let is_home = repo+ .primary_worktree()+ .ok()+ .flatten()+ .is_some_and(|p| wt.path == p);// Build item with identity fieldslet mut item = list::build_worktree_item(wt, is_home, true, false);diff --git a/src/git/mod.rs b/src/git/mod.rsindex ca6a2ef79..9cb580e85 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -439,35 +439,6 @@ impl WorktreeInfo {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 non-prunable 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).- ///- /// Prunable worktrees (directory deleted but git still tracks metadata) are- /// excluded since we can't cd to a directory that doesn't exist.- ///- /// 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` if all worktrees are prunable or `worktrees` is empty.- /// If `default_branch` doesn't match any non-prunable worktree, returns the- /// first non-prunable worktree.- pub fn find_home<'a>(- worktrees: &'a [WorktreeInfo],- default_branch: &str,- ) -> Option<&'a WorktreeInfo> {- // Filter out prunable worktrees (directory deleted but git still tracks metadata).- // Can't cd to a worktree that doesn't exist.- worktrees- .iter()- .filter(|wt| !wt.is_prunable())- .find(|wt| wt.branch.as_deref() == Some(default_branch))- .or_else(|| worktrees.iter().find(|wt| !wt.is_prunable()))- }}// Helper functions for worktree parsing@@ -645,50 +616,6 @@ mod tests {}}- #[test]- fn test_find_home() {- let make_wt = |branch: Option<&str>| WorktreeInfo {- 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!(WorktreeInfo::find_home(&[], "main").is_none());-- // Single worktree on default branch- let wts = vec![make_wt(Some("main"))];- assert_eq!(- WorktreeInfo::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!(- WorktreeInfo::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!(- WorktreeInfo::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!(- WorktreeInfo::find_home(&wts, "").unwrap().path.to_str(),- Some("/repo.feature")- );- }-#[test]fn test_branch_ref_from_worktree_info() {let wt = WorktreeInfo {diff --git a/src/git/parse.rs b/src/git/parse.rsindex 419485352..0f75afe2e 100644--- a/src/git/parse.rs+++ b/src/git/parse.rs@@ -297,68 +297,53 @@ mod tests {#[test]fn test_parse_porcelain_list_single_worktree() {let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);- assert!(result.is_ok());- let worktrees = result.unwrap();- assert_eq!(worktrees.len(), 1);- assert_eq!(worktrees[0].path.to_str().unwrap(), "/path/to/repo");- assert_eq!(worktrees[0].head, "abc123");- assert_eq!(worktrees[0].branch, Some("main".to_string()));+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert_eq!(wt.path.to_str().unwrap(), "/path/to/repo");+ assert_eq!(wt.head, "abc123");+ assert_eq!(wt.branch, Some("main".to_string()));}#[test]fn test_parse_porcelain_list_multiple_worktrees() {let output = "worktree /path/main\nHEAD aaa\nbranch refs/heads/main\n\nworktree /path/feature\nHEAD bbb\nbranch refs/heads/feature\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);- assert!(result.is_ok());- let worktrees = result.unwrap();- assert_eq!(worktrees.len(), 2);- assert_eq!(worktrees[0].branch, Some("main".to_string()));- assert_eq!(worktrees[1].branch, Some("feature".to_string()));+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();+ assert_eq!(main_wt.branch, Some("main".to_string()));+ assert_eq!(feature_wt.branch, Some("feature".to_string()));}#[test]fn test_parse_porcelain_list_bare_repo() {let output = "worktree /path/to/repo.git\nHEAD abc123\nbare\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);- assert!(result.is_ok());- let worktrees = result.unwrap();- assert_eq!(worktrees.len(), 1);- assert!(worktrees[0].bare);+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert!(wt.bare);}#[test]fn test_parse_porcelain_list_detached() {let output = "worktree /path/to/repo\nHEAD abc123\ndetached\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);- assert!(result.is_ok());- let worktrees = result.unwrap();- assert_eq!(worktrees.len(), 1);- assert!(worktrees[0].detached);- assert!(worktrees[0].branch.is_none());+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert!(wt.detached);+ assert!(wt.branch.is_none());}#[test]fn test_parse_porcelain_list_locked() {let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked reason for lock\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);- assert!(result.is_ok());- let worktrees = result.unwrap();- assert_eq!(worktrees.len(), 1);- assert_eq!(worktrees[0].locked, Some("reason for lock".to_string()));+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert_eq!(wt.locked, Some("reason for lock".to_string()));}#[test]fn test_parse_porcelain_list_prunable() {let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable gitdir file missing\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);- assert!(result.is_ok());- let worktrees = result.unwrap();- assert_eq!(worktrees.len(), 1);- assert_eq!(- worktrees[0].prunable,- Some("gitdir file missing".to_string())- );+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert_eq!(wt.prunable, Some("gitdir file missing".to_string()));}#[test]@@ -397,10 +382,9 @@ mod tests {fn test_parse_porcelain_list_branch_without_refs_prefix() {// This can happen in some edge caseslet output = "worktree /path/to/repo\nHEAD abc123\nbranch main\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);- assert!(result.is_ok());- let worktrees = result.unwrap();+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();// Should use the branch name as-is when no refs/heads/ prefix- assert_eq!(worktrees[0].branch, Some("main".to_string()));+ assert_eq!(wt.branch, Some("main".to_string()));}}diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex acb6ddbdf..77bbdafc5 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -15,17 +15,17 @@ branch refs/heads/feature";let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();- assert_eq!(worktrees.len(), 2);+ let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();- assert_eq!(worktrees[0].path, PathBuf::from("/path/to/main"));- assert_eq!(worktrees[0].head, "abcd1234");- assert_eq!(worktrees[0].branch, Some("main".to_string()));- assert!(!worktrees[0].bare);- assert!(!worktrees[0].detached);+ assert_eq!(main_wt.path, PathBuf::from("/path/to/main"));+ assert_eq!(main_wt.head, "abcd1234");+ assert_eq!(main_wt.branch, Some("main".to_string()));+ assert!(!main_wt.bare);+ assert!(!main_wt.detached);- assert_eq!(worktrees[1].path, PathBuf::from("/path/to/feature"));- assert_eq!(worktrees[1].head, "efgh5678");- assert_eq!(worktrees[1].branch, Some("feature".to_string()));+ assert_eq!(feature_wt.path, PathBuf::from("/path/to/feature"));+ assert_eq!(feature_wt.head, "efgh5678");+ assert_eq!(feature_wt.branch, Some("feature".to_string()));}#[test]@@ -37,9 +37,9 @@ detached";let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();- assert_eq!(worktrees.len(), 1);- assert!(worktrees[0].detached);- assert_eq!(worktrees[0].branch, None);+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert!(wt.detached);+ assert_eq!(wt.branch, None);}#[test]@@ -108,8 +108,8 @@ locked reason for lock";let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();- assert_eq!(worktrees.len(), 1);- assert_eq!(worktrees[0].locked, Some("reason for lock".to_string()));+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert_eq!(wt.locked, Some("reason for lock".to_string()));}#[test]@@ -121,8 +121,8 @@ bare";let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();- assert_eq!(worktrees.len(), 1);- assert!(worktrees[0].bare);+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert!(wt.bare);}#[test]@@ -332,9 +332,9 @@ locked";let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();- assert_eq!(worktrees.len(), 1);+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();// Empty lock reason should still be recorded- assert_eq!(worktrees[0].locked, Some(String::new()));+ assert_eq!(wt.locked, Some(String::new()));}#[test]@@ -347,15 +347,9 @@ prunable gitdir file points to non-existent location";let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();- assert_eq!(worktrees.len(), 1);- assert!(worktrees[0].prunable.is_some());- assert!(- worktrees[0]- .prunable- .as_ref()- .unwrap()- .contains("non-existent")- );+ let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();+ assert!(wt.prunable.is_some());+ assert!(wt.prunable.as_ref().unwrap().contains("non-existent"));}#[test]@@ -379,12 +373,13 @@ detached";let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();- assert_eq!(worktrees.len(), 4);- assert_eq!(worktrees[0].branch, Some("main".to_string()));- assert_eq!(worktrees[1].branch, Some("feature-a".to_string()));- assert_eq!(worktrees[2].branch, Some("feature-b".to_string()));- assert!(worktrees[3].detached);- assert_eq!(worktrees[3].branch, None);+ let [main_wt, feature_a, feature_b, detached_wt]: [WorktreeInfo; 4] =+ worktrees.try_into().unwrap();+ assert_eq!(main_wt.branch, Some("main".to_string()));+ assert_eq!(feature_a.branch, Some("feature-a".to_string()));+ assert_eq!(feature_b.branch, Some("feature-b".to_string()));+ assert!(detached_wt.detached);+ assert_eq!(detached_wt.branch, None);}#[test]diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex d99111edf..5e736bd59 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -222,20 +222,12 @@ impl Repository {/// 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)+ /// Returns the primary worktree if it exists, otherwise the repo root.+ /// - Normal repos: the main worktree (repo root)+ /// - Bare repos: the default branch's worktree, or the bare repo directorypub 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) = WorktreeInfo::find_home(&worktrees, &default_branch) {- return Ok(home.path.clone());- }-- // No worktrees - fall back to repo base (bare repo case)- Ok(self.repo_path().to_path_buf())+ Ok(self+ .primary_worktree()?+ .unwrap_or_else(|| self.repo_path().to_path_buf()))}}diff --git a/src/git/test.rs b/src/git/test.rsindex 84f69af9c..37017ef77 100644--- a/src/git/test.rs+++ b/src/git/test.rs@@ -36,17 +36,14 @@ fn test_parse_worktree_list_no_trailing_blank_line() {#[test]fn test_parse_worktree_list_multiple_worktrees() {let output = "worktree /path/to/main\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/feature\nHEAD def456\nbranch refs/heads/feature\ndetached\n\n";- let result = WorktreeInfo::parse_porcelain_list(output);-- assert!(result.is_ok());- let worktrees = result.unwrap();- assert_eq!(worktrees.len(), 2);+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();+ let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();- assert_eq!(worktrees[0].branch, Some("main".to_string()));- assert!(!worktrees[0].detached);+ assert_eq!(main_wt.branch, Some("main".to_string()));+ assert!(!main_wt.detached);- assert_eq!(worktrees[1].branch, Some("feature".to_string()));- assert!(worktrees[1].detached);+ assert_eq!(feature_wt.branch, Some("feature".to_string()));+ assert!(feature_wt.detached);}#[rstest]