Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: propagate repo_path() errors via Result instead of fallback (#1280)
worktrunk-bot79361c6e5280
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 53bce0597..11269744d 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -1,3 +1,4 @@+use anyhow::Result;use std::collections::HashMap;use std::path::Path;use worktrunk::HookType;@@ -67,8 +68,8 @@ impl<'a> CommandContext<'a> {pub fn build_hook_context(ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],-) -> HashMap<String, String> {- let repo_root = ctx.repo.repo_path();+) -> Result<HashMap<String, String>> {+ let repo_root = ctx.repo.repo_path()?;let repo_name = repo_root.file_name().and_then(|n| n.to_str())@@ -138,7 +139,7 @@ pub fn build_hook_context(map.insert((*k).into(), (*v).into());}- map+ Ok(map)}/// Expand commands from a CommandConfig without approval@@ -156,7 +157,7 @@ fn expand_commands(return Ok(Vec::new());}- let base_context = build_hook_context(ctx, extra_vars);+ let base_context = build_hook_context(ctx, extra_vars)?;// Convert to &str references for expand_templatelet vars: HashMap<&str, &str> = base_contextdiff --git a/src/commands/config/update.rs b/src/commands/config/update.rsindex 63f9f2512..e45a67190 100644--- a/src/commands/config/update.rs+++ b/src/commands/config/update.rs@@ -173,7 +173,7 @@ fn check_project_config() -> anyhow::Result<Option<UpdateCandidate>> {// Linked worktrees can't apply the update — suggest -C to main worktreeif is_linked {- let cmd = suggest_command_in_dir(repo.repo_path(), "config", &["update"], &[]);+ let cmd = suggest_command_in_dir(repo.repo_path()?, "config", &["update"], &[]);eprintln!("{}", hint_message("To update project config:"));eprintln!("{}", format_bash_with_gutter(&cmd));return Ok(None);diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 6680c1679..f15e72ba4 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -69,7 +69,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {// Build full hook context for this worktree// Pass wt.branch directly (not the display string) so detached HEAD maps to None -> "HEAD"let ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);- let context_map = build_hook_context(&ctx, &[]);+ let context_map = build_hook_context(&ctx, &[])?;// Convert to &str references for expand_templatelet vars: HashMap<&str, &str> = context_mapdiff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 3a32fe8eb..b4b12765d 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -240,7 +240,7 @@ pub fn handle_switch(//// When recovered from a deleted worktree, current_dir() and current_worktree().root()// both fail — fall back to repo_path() (the main worktree root).- let fallback_path = repo.repo_path().to_path_buf();+ let fallback_path = repo.repo_path()?.to_path_buf();let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());let source_root = repo.current_worktree().root().unwrap_or(fallback_path);let hooks_display_path =@@ -281,7 +281,7 @@ pub fn handle_switch(if let Some(cmd) = execute {// Build template context for expansion (includes base vars when creating)let ctx = CommandContext::new(&repo, config, Some(&branch_info.branch), result.path(), yes);- let template_vars = build_hook_context(&ctx, &extra_vars);+ let template_vars = build_hook_context(&ctx, &extra_vars)?;let vars: HashMap<&str, &str> = template_vars.iter().map(|(k, v)| (k.as_str(), v.as_str()))diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 8a93ced18..3af67a54f 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -592,7 +592,7 @@ fn render_hook_commands(// Show template or expanded commandlet command_text = if let Some(command_ctx) = ctx {// Expand template with current context- expand_command_template(&cmd.template, command_ctx, hook_type)+ expand_command_template(&cmd.template, command_ctx, hook_type)?} else {cmd.template.clone()};@@ -604,7 +604,11 @@ fn render_hook_commands(}/// Expand a command template with context variables-fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: HookType) -> String {+fn expand_command_template(+ template: &str,+ ctx: &CommandContext,+ hook_type: HookType,+) -> anyhow::Result<String> {// Build extra vars based on hook type (same logic as run_hook approval)let default_branch = ctx.repo.default_branch();let extra_vars: Vec<(&str, &str)> = match hook_type {@@ -622,7 +626,7 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook}_ => Vec::new(),};- let template_ctx = build_hook_context(ctx, &extra_vars);+ let template_ctx = build_hook_context(ctx, &extra_vars)?;let vars: HashMap<&str, &str> = template_ctx.iter().map(|(k, v)| (k.as_str(), v.as_str()))@@ -630,6 +634,8 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook// Use the standard template expansion (shell-escaped)// On any error, show both the template and error message- worktrunk::config::expand_template(template, &vars, true, ctx.repo, "hook preview")- .unwrap_or_else(|err| format!("# {}\n{}", err.message, template))+ Ok(+ worktrunk::config::expand_template(template, &vars, true, ctx.repo, "hook preview")+ .unwrap_or_else(|err| format!("# {}\n{}", err.message, template)),+ )}diff --git a/src/commands/select/log_formatter.rs b/src/commands/select/log_formatter.rsindex 7b21c65e9..c6e1a6542 100644--- a/src/commands/select/log_formatter.rs+++ b/src/commands/select/log_formatter.rs@@ -42,9 +42,12 @@ pub(super) fn batch_fetch_stats(// --root: include stats for root commits (no parent to diff against)// Each hash needs a trailing newline for git to process itlet stdin_data = hashes.iter().map(|h| format!("{h}\n")).collect::<String>();+ let Ok(repo_path) = repo.repo_path() else {+ return HashMap::new();+ };let Ok(output) = Cmd::new("git").args(["diff-tree", "--numstat", "-r", "--root", "--stdin"])- .current_dir(repo.repo_path())+ .current_dir(repo_path).stdin_bytes(stdin_data).run()else {diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rsindex cf8b12695..ce3f16287 100644--- a/src/commands/select/mod.rs+++ b/src/commands/select/mod.rs@@ -342,7 +342,7 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()// Show success message; emit cd directive if shell integration is active// Interactive picker always performs cd (change_dir: true)// When recovered from a deleted worktree, fall back to repo_path().- let fallback_path = repo.repo_path().to_path_buf();+ let fallback_path = repo.repo_path()?.to_path_buf();let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());let source_root = repo.current_worktree().root().unwrap_or(fallback_path);let hooks_display_path =diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex fa520926d..408cd0f7f 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -1706,7 +1706,7 @@ pub fn step_relocate("Cannot determine default branch; set with: wt config state default-branch set main");}- let repo_path = repo.repo_path().to_path_buf();+ let repo_path = repo.repo_path()?.to_path_buf();// Phase 1: Gather candidates (worktrees not at expected paths)let GatherResult {diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 42a1e41b0..05cd7a5c7 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -80,7 +80,7 @@ pub fn compute_worktree_path(branch: &str,config: &UserConfig,) -> anyhow::Result<PathBuf> {- let repo_root = repo.repo_path();+ let repo_root = repo.repo_path()?;let default_branch = repo.default_branch().unwrap_or_default();let is_bare = repo.is_bare()?;diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex f34714bac..a0ccb3ef3 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -75,7 +75,7 @@ fn resolve_remote_ref(progress_message(cformat!("Fetching {} {symbol}{number}...", ref_type.name())));- let repo_root = repo.repo_path();+ let repo_root = repo.repo_path()?;let info = provider.fetch_info(number, repo_root)?;// Display context with URL (as gutter under fetch progress)@@ -107,7 +107,7 @@ fn resolve_fork_ref(info: &RemoteRefInfo,) -> anyhow::Result<ResolvedTarget> {let ref_type = provider.ref_type();- let repo_root = repo.repo_path();+ let repo_root = repo.repo_path()?;let local_branch = remote_ref::local_branch_name(info);// Check if branch already exists and is tracking this refdiff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex 0988c463e..4284aa7e8 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -723,7 +723,8 @@ pub fn check_and_migrate(deprecations,label: label.to_string(),main_worktree_path: if !warn_and_migrate {- repo.map(|r| r.repo_path().to_path_buf())+ repo.and_then(|r| r.repo_path().ok())+ .map(|p| p.to_path_buf())} else {None},diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rsindex 8686e3136..1e586b4ac 100644--- a/src/config/user/accessors.rs+++ b/src/config/user/accessors.rs@@ -6,7 +6,7 @@use std::collections::HashMap;use crate::config::HooksConfig;-use crate::config::expansion::{TemplateExpandError, expand_template};+use crate::config::expansion::expand_template;use super::UserConfig;use super::merge::{Merge, merge_optional};@@ -207,19 +207,21 @@ impl UserConfig {branch: &str,repo: &crate::git::Repository,project: Option<&str>,- ) -> Result<String, TemplateExpandError> {+ ) -> anyhow::Result<String> {let template = match project {Some(p) => self.worktree_path_for_project(p),None => self.worktree_path(),};// Use native path format (not POSIX) since this is used for filesystem operations- let repo_path = repo.repo_path().to_string_lossy().to_string();+ let repo_path = repo.repo_path()?.to_string_lossy().to_string();let mut vars = HashMap::new();vars.insert("main_worktree", main_worktree);vars.insert("repo", main_worktree);vars.insert("branch", branch);vars.insert("repo_path", repo_path.as_str());- expand_template(&template, &vars, false, repo, "worktree-path")- .map(|p| shellexpand::tilde(&p).into_owned())+ Ok(+ expand_template(&template, &vars, false, repo, "worktree-path")+ .map(|p| shellexpand::tilde(&p).into_owned())?,+ )}}diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex ffbc77836..2eab5a9c7 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -361,7 +361,7 @@ fn test_worktrunk_config_format_path() {"Expected path containing parent navigation, got: {path}");// The path should start with the repo path (absolute)- let repo_path = test.repo.repo_path().to_string_lossy();+ let repo_path = test.repo.repo_path().unwrap().to_string_lossy();assert!(path.starts_with(repo_path.as_ref()),"Expected path starting with repo path '{repo_path}', got: {path}"@@ -404,7 +404,7 @@ fn test_worktrunk_config_format_path_repo_path_variable() {"Expected path containing 'worktrees' and 'feature-branch', got: {path}");// The path should start with the repo path- let repo_path = test.repo.repo_path().to_string_lossy();+ let repo_path = test.repo.repo_path().unwrap().to_string_lossy();assert!(path.starts_with(repo_path.as_ref()),"Expected path starting with repo path '{repo_path}', got: {path}"diff --git a/src/git/recover.rs b/src/git/recover.rsindex 47c837f23..b2e364d30 100644--- a/src/git/recover.rs+++ b/src/git/recover.rs@@ -327,7 +327,7 @@ mod tests {// Tests run inside a git repo in CI, so Repository::current() succeeds.let (repo, recovered) = current_or_recover().unwrap();assert!(!recovered);- assert!(repo.repo_path().exists());+ assert!(repo.repo_path().unwrap().exists());}#[test]@@ -421,7 +421,10 @@ mod tests {// Recovery should find beta's repo, not alpha'slet recovered = recover_from_path(&wt_b).unwrap();- assert_eq!(dunce::canonicalize(recovered.repo_path()).unwrap(), repo_b);+ assert_eq!(+ dunce::canonicalize(recovered.repo_path().unwrap()).unwrap(),+ repo_b+ );}#[test]diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 88151731e..df243d818 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -412,30 +412,40 @@ impl Repository {////// So we try `--show-toplevel` first (handles submodules), fall back to `parent()` (handles/// normal repos). This avoids fragile path-based detection of submodules.- pub fn repo_path(&self) -> &Path {- self.cache.repo_path.get_or_init(|| {- // Bare repos have no worktree — the git directory IS the repo- if self.is_bare().unwrap_or(false) {- return self.git_common_dir.clone();- }-- // Submodules: --show-toplevel succeeds (git has explicit core.worktree config)- if let Ok(out) = Cmd::new("git")- .args(["rev-parse", "--show-toplevel"])- .current_dir(&self.git_common_dir)- .context(path_to_logging_context(&self.git_common_dir))- .run()- && out.status.success()- {- return PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());- }+ ///+ /// # Errors+ ///+ /// Returns an error if `is_bare()` fails (e.g., git timeout). This surfaces+ /// the failure early rather than caching a potentially wrong path.+ pub fn repo_path(&self) -> anyhow::Result<&Path> {+ self.cache+ .repo_path+ .get_or_try_init(|| {+ // Submodules: --show-toplevel succeeds (git has explicit core.worktree config)+ if let Ok(out) = Cmd::new("git")+ .args(["rev-parse", "--show-toplevel"])+ .current_dir(&self.git_common_dir)+ .context(path_to_logging_context(&self.git_common_dir))+ .run()+ && out.status.success()+ {+ return Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()));+ }- // Normal repos: --show-toplevel fails from inside .git, use implicit relationship- self.git_common_dir- .parent()- .expect("Git directory has no parent")- .to_path_buf()- })+ // --show-toplevel failed:+ // 1. Bare repos (no working tree) → git_common_dir IS the repo+ // 2. Normal repos from inside .git → parent is the repo+ if self.is_bare()? {+ Ok(self.git_common_dir.clone())+ } else {+ Ok(self+ .git_common_dir+ .parent()+ .expect("Git directory has no parent")+ .to_path_buf())+ }+ })+ .map(|p| p.as_path())}/// Check if this is a bare repository (no working tree).diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 1aa61dcae..7079db6dc 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -178,7 +178,7 @@ impl Repository {// Fall back to full canonical path (use worktree base for consistency across all worktrees)// Full path avoids collisions across unrelated repos with the same directory name- let repo_root = self.repo_path();+ let repo_root = self.repo_path()?;let canonical =dunce::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf());let path_str = canonicaldiff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 392bf5201..2494103ab 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -400,6 +400,30 @@ fn test_default_branch_name_display() {}}+#[test]+fn repo_path_error_when_is_bare_fails() {+ use super::RepoCache;+ use std::sync::Arc;++ // Create a Repository with a non-existent git_common_dir.+ // This makes --show-toplevel fail (reaching the is_bare branch),+ // and then is_bare() also fails because git can't run in a missing dir.+ let repo = super::Repository {+ discovery_path: PathBuf::from("/nonexistent/repo"),+ git_common_dir: PathBuf::from("/nonexistent/.git"),+ cache: Arc::new(RepoCache::default()),+ };++ let err = repo.repo_path().unwrap_err();+ let msg = format!("{err:#}");+ // The OS error text is platform-specific (e.g., "No such file or directory" on Unix,+ // "The directory name is invalid." on Windows), so only assert the stable prefix.+ assert!(+ msg.starts_with("failed to check if repository is bare: "),+ "unexpected error message: {msg}"+ );+}+#[test]fn extract_failed_command_from_stream_error() {use super::StreamCommandError;diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex c34ddfd47..a5c32c206 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -46,7 +46,7 @@ impl Repository {if let Some(first) = worktrees.first_mut()&& canonicalize(&first.path).ok().as_deref() == Some(self.git_common_dir()){- first.path = self.repo_path().to_path_buf();+ first.path = self.repo_path()?.to_path_buf();}Ok(worktrees)@@ -94,7 +94,7 @@ impl Repository {};self.worktree_for_branch(&branch)} else {- Ok(Some(self.repo_path().to_path_buf()))+ Ok(Some(self.repo_path()?.to_path_buf()))}}@@ -287,8 +287,7 @@ impl Repository {/// - 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> {- Ok(self- .primary_worktree()?- .unwrap_or_else(|| self.repo_path().to_path_buf()))+ self.primary_worktree()?+ .map_or_else(|| self.repo_path().map(|p| p.to_path_buf()), Ok)}}diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 11a5a06da..3f890cd76 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -635,7 +635,7 @@ fn test_repo_path_in_submodule() {// The key assertion: repo_path() should return the submodule's working directory,// NOT something like parent/.git/modules/sub- let repo_path = repository.repo_path();+ let repo_path = repository.repo_path().unwrap();// Canonicalize both paths for comparison (handles symlinks like /var -> /private/var on macOS)let expected = dunce::canonicalize(&submodule_path).unwrap();