Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: consolidate Repository fields and make repo_path/is_bare infallible (#748)
Maximilian Roosf994551352ff
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex 01920e7c5..094885378 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -167,7 +167,7 @@ fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> any/// # Example////// ```ignore-/// let ctx = CommandContext::new(&repo, &config, &branch, &worktree_path, &repo_root, yes);+/// let ctx = CommandContext::new(&repo, &config, &branch, &worktree_path, yes);/// let approved = approve_hooks(&ctx, &[HookType::PostCreate, HookType::PostStart])?;/// ```pub fn approve_hooks(diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 61d942696..e4075ffae 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -21,7 +21,6 @@ pub struct CommandContext<'a> {/// Current branch name, if on a branch (None in detached HEAD state).pub branch: Option<&'a str>,pub worktree_path: &'a Path,- pub repo_root: &'a Path,pub yes: bool,}@@ -31,7 +30,6 @@ impl<'a> CommandContext<'a> {config: &'a UserConfig,branch: Option<&'a str>,worktree_path: &'a Path,- repo_root: &'a Path,yes: bool,) -> Self {Self {@@ -39,7 +37,6 @@ impl<'a> CommandContext<'a> {config,branch,worktree_path,- repo_root,yes,}}@@ -58,7 +55,7 @@ pub fn build_hook_context(ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],) -> HashMap<String, String> {- let repo_root = ctx.repo_root;+ let repo_root = ctx.repo.repo_path();let repo_name = repo_root.file_name().and_then(|n| n.to_str())diff --git a/src/commands/context.rs b/src/commands/context.rsindex 3524fc6a4..71e32046c 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -21,7 +21,6 @@ pub struct CommandEnv {pub branch: Option<String>,pub config: UserConfig,pub worktree_path: PathBuf,- pub repo_root: PathBuf,}impl CommandEnv {@@ -34,16 +33,12 @@ impl CommandEnv {let worktree_path = std::env::current_dir().context("Failed to get current directory")?;let branch = repo.require_current_branch(action)?;let config = UserConfig::load().context("Failed to load config")?;- let repo_root = repo- .repo_path()- .context("Failed to determine repository root")?;Ok(Self {repo,branch: Some(branch),config,worktree_path,- repo_root,})}@@ -60,16 +55,12 @@ impl CommandEnv {.branch().context("Failed to determine current branch")?;let config = UserConfig::load().context("Failed to load config")?;- let repo_root = repo- .repo_path()- .context("Failed to determine repository root")?;Ok(Self {repo,branch,config,worktree_path,- repo_root,})}@@ -80,7 +71,6 @@ impl CommandEnv {&self.config,self.branch.as_deref(),&self.worktree_path,- &self.repo_root,yes,)}diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 229e6886c..b54864671 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -60,23 +60,13 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {// Join args into a template string (will be expanded per-worktree)let command_template = args.join(" ");- // Get repo root for context- let repo_root = repo.repo_path()?;-for wt in &worktrees {let display_name = worktree_display_name(wt, &repo, &config);output::print(progress_message(format!("Running in {display_name}...")))?;// 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,- &repo_root,- false,- );+ let ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);let context_map = build_hook_context(&ctx, &[]);// Convert to &str references for expand_templatediff --git a/src/commands/merge.rs b/src/commands/merge.rsindex cf0f52638..7b1a1def1 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -83,8 +83,11 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// Merge requires being on a branch (can't merge from detached HEAD)let current_branch = env.require_branch("merge")?.to_string();+ // Cache current worktree for multiple queries+ let current_wt = repo.current_worktree();+// Validate --no-commit: requires clean working tree- if !commit && repo.current_worktree().is_dirty()? {+ if !commit && current_wt.is_dirty()? {return Err(worktrunk::git::GitError::UncommittedChanges {action: Some("merge with --no-commit".into()),branch: Some(current_branch.clone()),@@ -102,7 +105,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let target_worktree_path = repo.worktree_for_branch(&target_branch)?;// When current == target or we're in the main worktree, disable remove (can't remove it)- let in_main = !repo.current_worktree().is_linked().unwrap_or(false);+ let in_main = !current_wt.is_linked().unwrap_or(false);let on_target = current_branch == target_branch;let remove_effective = remove && !on_target && !in_main;@@ -123,7 +126,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {};// Handle uncommitted changes (skip if --no-commit) - track whether commit occurred- let committed = if commit && repo.current_worktree().is_dirty()? {+ let committed = if commit && current_wt.is_dirty()? {if squash_enabled {false // Squash path handles staging and committing} else {@@ -204,14 +207,10 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {if remove_effective {// STEP 1: Check for uncommitted changes before attempting cleanup// This prevents showing "Cleaning up worktree..." before failing- repo.current_worktree().ensure_clean(- "remove worktree after merge",- Some(¤t_branch),- false,- )?;+ current_wt.ensure_clean("remove worktree after merge", Some(¤t_branch), false)?;// STEP 2: Remove worktree via shared remove output handler so final message matches wt remove- let worktree_root = repo.current_worktree().root()?.to_path_buf();+ let worktree_root = current_wt.root()?.to_path_buf();// After a successful merge, get integration reasonlet (_, integration_reason) = repo.integration_reason(¤t_branch, &target_branch)?;// Compute expected_path for path mismatch detection@@ -248,14 +247,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {if verify {// Execute post-merge commands in the destination worktree// This runs after cleanup so the context is clear to the user- let ctx = CommandContext::new(- repo,- config,- Some(¤t_branch),- &destination_path,- &destination_path,- yes,- );+ let ctx = CommandContext::new(repo, config, Some(¤t_branch), &destination_path, yes);// Show path when user's shell won't be in the destination directory where hooks run.let display_path = if remove_effective && !in_main && !on_target {// Worktree removed, user will cd to destinationdiff --git a/src/commands/select/log_formatter.rs b/src/commands/select/log_formatter.rsindex 0301f74d3..d567c9e37 100644--- a/src/commands/select/log_formatter.rs+++ b/src/commands/select/log_formatter.rs@@ -38,7 +38,7 @@ pub(super) fn batch_fetch_stats(let stdin_data = hashes.iter().map(|h| format!("{h}\n")).collect::<String>();let Ok(output) = Cmd::new("git").args(["diff-tree", "--numstat", "-r", "--root", "--stdin"])- .current_dir(repo.repo_path().unwrap_or_else(|_| ".".into()))+ .current_dir(repo.repo_path()).stdin_bytes(stdin_data).run()else {diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 897251fda..d48e34622 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -238,7 +238,7 @@ pub fn handle_squash(generator.emit_hint_if_needed()?;// Get current branch and repo name for template variables- let repo_root = repo.current_worktree().root()?;+ let repo_root = wt.root()?;let repo_name = repo_root.file_name().and_then(|n| n.to_str())@@ -300,10 +300,8 @@ pub fn step_show_squash_prompt(let target_branch = repo.require_target_ref(target)?;// Get current branch- let current_branch = repo- .current_worktree()- .branch()?- .unwrap_or_else(|| "HEAD".to_string());+ let wt = repo.current_worktree();+ let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());// Get merge base with target branch (required for generating squash message)let merge_base = repo@@ -315,7 +313,7 @@ pub fn step_show_squash_prompt(let subjects = repo.commit_subjects(&range)?;// Get repo name from directory- let repo_root = repo.current_worktree().root()?;+ let repo_root = wt.root()?;let repo_name = repo_root.file_name().and_then(|n| n.to_str())diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 6d14d67d2..57847a085 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -78,14 +78,14 @@ 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()?;+ let is_bare = repo.is_bare();// Default branch lives at repo root (main worktree), not a templated path.// Exception: bare repos have no main worktree, so all branches use templated paths.if !is_bare && branch == default_branch {- return Ok(repo_root);+ return Ok(repo_root.to_path_buf());}let repo_name = repo_rootdiff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 340e77c9b..b72c8bf05 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -60,8 +60,8 @@ fn resolve_switch_target(// Fetch PR info (network call via gh CLI)crate::output::print(progress_message(cformat!("Fetching PR #{pr_number}...")))?;- let repo_root = repo.repo_path()?;- let pr_info = fetch_pr_info(pr_number, &repo_root)?;+ let repo_root = repo.repo_path();+ let pr_info = fetch_pr_info(pr_number, repo_root)?;if pr_info.is_cross_repository {// Fork PR: will need fetch + pushRemote config (see pr_ref module docs)@@ -70,7 +70,7 @@ fn resolve_switch_target(// Check if branch already exists and is tracking this PR// If so, we can reuse it without re-fetching or re-configuringif let Some(tracks_this_pr) =- worktrunk::git::pr_ref::branch_tracks_pr(&repo_root, &local_branch, pr_number)+ worktrunk::git::pr_ref::branch_tracks_pr(repo_root, &local_branch, pr_number){if tracks_this_pr {// Branch exists and tracks this PR - just create worktree@@ -166,8 +166,8 @@ fn resolve_switch_target(// Fetch MR info (network call via glab CLI)crate::output::print(progress_message(cformat!("Fetching MR !{mr_number}...")))?;- let repo_root = repo.repo_path()?;- let mr_info = mr_ref::fetch_mr_info(mr_number, &repo_root)?;+ let repo_root = repo.repo_path();+ let mr_info = mr_ref::fetch_mr_info(mr_number, repo_root)?;if mr_info.is_cross_project {// Fork MR: will need fetch + pushRemote config (see mr_ref module docs)@@ -176,7 +176,7 @@ fn resolve_switch_target(// Check if branch already exists and is tracking this MR// If so, we can reuse it without re-fetching or re-configuringif let Some(tracks_this_mr) =- mr_ref::branch_tracks_mr(&repo_root, &local_branch, mr_number)+ mr_ref::branch_tracks_mr(repo_root, &local_branch, mr_number){if tracks_this_mr {// Branch exists and tracks this MR - just create worktree@@ -761,15 +761,7 @@ pub fn execute_switch(// Execute post-create commandsif !no_verify {- let repo_root = repo.repo_path()?;- let ctx = CommandContext::new(- repo,- config,- Some(&branch),- &worktree_path,- &repo_root,- force,- );+ let ctx = CommandContext::new(repo, config, Some(&branch), &worktree_path, force);match &method {CreationMethod::Regular { base_branch, .. } => {diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex f8675cd2f..5ff3c24bd 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -283,7 +283,7 @@ impl Repository {// - 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()?;+ let is_bare = self.is_bare();let in_linked_worktree = self.current_worktree().is_linked()?;if ((is_bare && !in_linked_worktree) || branches.is_empty())&& let Ok(head_ref) = self.run_command(&["symbolic-ref", "HEAD"])diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex aba662e26..fcc0935a3 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -65,8 +65,6 @@ pub(super) use working_tree::path_to_logging_context;#[derive(Debug, Default)]pub(super) struct RepoCache {// ========== Repo-wide values (same for all worktrees) ==========- /// Whether this is a bare repository- pub(super) is_bare: OnceCell<bool>,/// Default branch (main, master, etc.)pub(super) default_branch: OnceCell<Option<String>>,/// Invalid default branch config (user configured a branch that doesn't exist).@@ -80,8 +78,6 @@ pub(super) struct RepoCache {pub(super) primary_remote_url: OnceCell<Option<String>>,/// Project identifier derived from remote URLpub(super) project_identifier: OnceCell<String>,- /// Repository root path (main worktree for normal repos, bare directory for bare repos)- pub(super) repo_path: OnceCell<PathBuf>,/// Project config (loaded from .config/wt.toml in main worktree)pub(super) project_config: OnceCell<Option<ProjectConfig>>,/// Merge-base cache: (commit1, commit2) -> merge_base_sha (None = no common ancestor)@@ -168,6 +164,11 @@ pub struct Repository {discovery_path: PathBuf,/// The shared .git directory, computed at construction time.git_common_dir: PathBuf,+ /// Whether this is a bare repository, computed at construction time.+ is_bare: bool,+ /// Repository root path, computed at construction time.+ /// For normal repos: parent of git_common_dir. For bare repos: git_common_dir itself.+ repo_path: PathBuf,/// Cached data for this repository. Shared across clones via Arc.pub(super) cache: Arc<RepoCache>,}@@ -198,10 +199,23 @@ impl Repository {/// use [`Repository::worktree_at()`] instead.pub fn at(path: impl Into<PathBuf>) -> anyhow::Result<Self> {let discovery_path = path.into();- let git_common_dir = Self::resolve_git_common_dir(&discovery_path)?;+ let (git_common_dir, is_bare) = Self::resolve_repo_info(&discovery_path)?;++ // Compute repo_path from git_common_dir and is_bare+ let repo_path = if is_bare {+ git_common_dir.clone()+ } else {+ git_common_dir+ .parent()+ .context("Git directory has no parent")?+ .to_path_buf()+ };+Ok(Self {discovery_path,git_common_dir,+ is_bare,+ repo_path,cache: Arc::new(RepoCache::default()),})}@@ -216,28 +230,48 @@ impl Repository {Arc::ptr_eq(&self.cache, &other.cache)}- /// Resolve the git common directory for a path.- fn resolve_git_common_dir(discovery_path: &Path) -> anyhow::Result<PathBuf> {+ /// Resolve git common directory and bare status.+ ///+ /// Note: We need two git calls because `--is-bare-repository` returns false when+ /// run from a worktree of a bare repo. We first get git_common_dir, then check+ /// is_bare from there.+ fn resolve_repo_info(discovery_path: &Path) -> anyhow::Result<(PathBuf, bool)> {+ // First, get the git common directorylet output = Cmd::new("git").args(["rev-parse", "--git-common-dir"]).current_dir(discovery_path).context(path_to_logging_context(discovery_path)).run()- .context("Failed to execute: git rev-parse --git-common-dir")?;+ .context("Failed to execute: git rev-parse")?;if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);bail!("{}", stderr.trim());}- let stdout = String::from_utf8_lossy(&output.stdout);- let path = PathBuf::from(stdout.trim());- if path.is_relative() {- canonicalize(discovery_path.join(&path))- .context("Failed to resolve git common directory")+ let git_common_dir_raw = String::from_utf8_lossy(&output.stdout);+ let git_common_dir_path = PathBuf::from(git_common_dir_raw.trim());+ let git_common_dir = if git_common_dir_path.is_relative() {+ canonicalize(discovery_path.join(&git_common_dir_path))+ .context("Failed to resolve git common directory")?} else {- Ok(path)- }+ git_common_dir_path+ };++ // Now check is_bare from the git_common_dir itself, not the discovery path.+ // This is important for worktrees of bare repos: running from the worktree+ // returns false, but running from the bare repo returns true.+ let output = Cmd::new("git")+ .args(["rev-parse", "--is-bare-repository"])+ .current_dir(&git_common_dir)+ .context(path_to_logging_context(&git_common_dir))+ .run()+ .context("Failed to check if repository is bare")?;++ let is_bare =+ output.status.success() && String::from_utf8_lossy(&output.stdout).trim() == "true";++ Ok((git_common_dir, is_bare))}/// Get the path this repository was discovered from.@@ -321,39 +355,19 @@ impl Repository {/// This is the base for template expansion (`{{ repo }}`, `{{ repo_path }}`)./// NOT necessarily where established files live — use `primary_worktree()` for that.///- /// Result is cached in the repository's shared cache (same for all clones).- pub fn repo_path(&self) -> anyhow::Result<PathBuf> {- self.cache- .repo_path- .get_or_try_init(|| {- let git_common_dir =- canonicalize(self.git_common_dir()).context("Failed to canonicalize path")?;-- if self.is_bare()? {- Ok(git_common_dir)- } else {- Ok(git_common_dir- .parent()- .context("Git directory has no parent")?- .to_path_buf())- }- })- .cloned()+ /// Computed at construction time from `git rev-parse --git-common-dir`.+ pub fn repo_path(&self) -> &Path {+ &self.repo_path}/// Check if this is a bare repository (no working tree).////// Bare repositories have no main worktree — all worktrees are linked/// worktrees at templated paths, including the default branch.- /// Result is cached in the repository's shared cache (same for all clones).- pub fn is_bare(&self) -> anyhow::Result<bool> {- self.cache- .is_bare- .get_or_try_init(|| {- let output = self.run_command(&["config", "--bool", "core.bare"])?;- Ok(output.trim() == "true")- })- .copied()+ ///+ /// Computed at construction time from `git rev-parse --is-bare-repository`.+ pub fn is_bare(&self) -> bool {+ self.is_bare}/// Check if git's builtin fsmonitor daemon is enabled.diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 258f84e86..6594931be 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -151,7 +151,7 @@ impl Repository {}// Fall back to repository name (use worktree base for consistency across all worktrees)- let repo_root = self.repo_path()?;+ let repo_root = self.repo_path();let repo_name = repo_root.file_name().and_then(|name| name.to_str())diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex bc06bd745..0c065075a 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -64,13 +64,13 @@ impl Repository {////// For template var `{{ primary_worktree_path }}`.pub fn primary_worktree(&self) -> anyhow::Result<Option<PathBuf>> {- if self.is_bare()? {+ if self.is_bare() {let Some(branch) = self.default_branch() else {return Ok(None);};self.worktree_for_branch(&branch)} else {- Ok(Some(self.repo_path()?))+ Ok(Some(self.repo_path().to_path_buf()))}}@@ -226,6 +226,6 @@ impl Repository {}// No worktrees - fall back to repo base (bare repo case)- self.repo_path()+ Ok(self.repo_path().to_path_buf())}}diff --git a/src/llm.rs b/src/llm.rsindex 6ff021d35..a395125b9 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -490,14 +490,10 @@ pub(crate) fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Re// Prepare diff (may filter if too large)let prepared = prepare_diff(diff_output, diff_stat);- // Get current branch- let current_branch = repo- .current_worktree()- .branch()?- .unwrap_or_else(|| "HEAD".to_string());-- // Get repo name from directory- let repo_root = repo.current_worktree().root()?;+ // Get current branch and repo root+ let wt = repo.current_worktree();+ let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());+ let repo_root = wt.root()?;let repo_name = repo_root.file_name().and_then(|n| n.to_str())diff --git a/src/main.rs b/src/main.rsindex 9282ddebc..51a859158 100644--- a/src/main.rs+++ b/src/main.rs@@ -727,13 +727,11 @@ fn main() {// This ensures approval happens once at the command entry point// If user declines, skip hooks but continue with worktree operationlet approved = if verify {- let repo_root = repo.repo_path().context("Failed to switch worktree")?;let ctx = CommandContext::new(&repo,&config,Some(plan.branch()),plan.worktree_path(),- &repo_root,yes,);// Approve different hooks based on whether we're creating or switching@@ -809,13 +807,11 @@ fn main() {// - post-start: runs only when creating a NEW worktreeif !skip_hooks {let repo = Repository::current()?;- let repo_root = repo.repo_path().context("Failed to switch worktree")?;let ctx = CommandContext::new(&repo,&config,Some(&branch_info.branch),result.path(),- &repo_root,yes,);@@ -833,13 +829,11 @@ fn main() {if let Some(cmd) = execute {// Build template context for expansion (includes base vars when creating)let repo = Repository::current()?;- let repo_root = repo.repo_path().context("Failed to get repo root")?;let ctx = CommandContext::new(&repo,&config,Some(&branch_info.branch),result.path(),- &repo_root,yes,);let template_vars = build_hook_context(&ctx, &extra_vars);diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex c17170219..d2e25abaf 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -559,13 +559,11 @@ fn spawn_post_switch_after_remove(// is removed (cwd may no longer exist).let repo = Repository::at(main_path)?;let dest_branch = repo.worktree_at(main_path).branch()?;- let repo_root = repo.repo_path()?;let ctx = CommandContext::new(&repo,&config,dest_branch.as_deref(),main_path,- &repo_root,false, // force=false for CommandContext);// No base context for remove-triggered switch (we're returning to main, not creating)@@ -787,7 +785,6 @@ fn handle_removed_worktree_output(&config,branch_name,worktree_path,- main_path,false, // force=false for CommandContext (not approval-related));// Show path when removing a different worktree (user is elsewhere)