Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(switch): defer compute_worktree_path for existing worktrees (#1030)
Maximilian Roos625b5cdd71d0
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex de140738e..67bf181bf 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -11,7 +11,9 @@ use worktrunk::styling::{eprintln, info_message};use super::command_approval::approve_hooks;use super::command_executor::{CommandContext, build_hook_context};-use super::worktree::{SwitchPlan, SwitchResult, execute_switch, plan_switch};+use super::worktree::{+ SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, get_path_mismatch, plan_switch,+};use crate::output::{execute_user_command, handle_switch_output, is_shell_integration_active,prompt_shell_integration,@@ -161,6 +163,18 @@ pub fn handle_switch(return Ok(());}+ // Compute path mismatch lazily (deferred from plan_switch for existing worktrees)+ let branch_info = match &result {+ SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {+ let expected_path = get_path_mismatch(&repo, &branch_info.branch, path, config);+ SwitchBranchInfo {+ expected_path,+ ..branch_info+ }+ }+ _ => branch_info,+ };+// Show success message (temporal locality: immediately after worktree operation)// Returns path to display in hooks when user's shell won't be in the worktree// Also shows worktree-path hint on first --create (before shell integration warning)diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rsindex f57dcb4a0..a9e76956f 100644--- a/src/commands/select/mod.rs+++ b/src/commands/select/mod.rs@@ -20,7 +20,9 @@ use super::handle_switch::{approve_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,};use super::list::collect;-use super::worktree::{execute_switch, plan_switch};+use super::worktree::{+ SwitchBranchInfo, SwitchResult, execute_switch, get_path_mismatch, plan_switch,+};use crate::output::handle_switch_output;use items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};@@ -278,6 +280,18 @@ pub fn handle_select(let skip_hooks = !approve_switch_hooks(&repo, &config, &plan, false, true)?;let (result, branch_info) = execute_switch(&repo, plan, &config, false, skip_hooks)?;+ // Compute path mismatch lazily (deferred from plan_switch for existing worktrees)+ let branch_info = match &result {+ SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {+ let expected_path = get_path_mismatch(&repo, &branch_info.branch, path, &config);+ SwitchBranchInfo {+ expected_path,+ ..branch_info+ }+ }+ _ => branch_info,+ };+// Show success message; emit cd directive if shell integration is active// Interactive picker always performs cd (change_dir: true)let cwd = std::env::current_dir().context("Failed to get current directory")?;diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 46ac83d3a..fd8e36e35 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -17,7 +17,7 @@ use worktrunk::styling::{warning_message,};-use super::resolve::{compute_clobber_backup, compute_worktree_path, paths_match};+use super::resolve::{compute_clobber_backup, compute_worktree_path};use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};use crate::commands::command_executor::CommandContext;@@ -445,32 +445,6 @@ fn resolve_switch_target(})}-/// Check if branch already has a worktree.-///-/// Returns `Some(Existing)` if worktree exists and is valid.-/// Returns error if worktree record exists but directory is missing.-/// Returns `None` if no worktree exists for this branch.-fn check_existing_worktree(- repo: &Repository,- branch: &str,- expected_path: &Path,- new_previous: Option<String>,-) -> anyhow::Result<Option<SwitchPlan>> {- match repo.worktree_for_branch(branch)? {- Some(existing_path) if existing_path.exists() => Ok(Some(SwitchPlan::Existing {- path: canonicalize(&existing_path).unwrap_or(existing_path),- branch: branch.to_string(),- expected_path: expected_path.to_path_buf(),- new_previous,- })),- Some(_) => Err(GitError::WorktreeMissing {- branch: branch.to_string(),- }- .into()),- None => Ok(None),- }-}-/// Validate that we can create a worktree at the given path.////// Checks:@@ -609,16 +583,28 @@ pub fn plan_switch(// Phase 1: Resolve target (handles pr:, validates --create/--base, may do network)let target = resolve_switch_target(repo, branch, create, base)?;- // Phase 2: Compute expected path- let expected_path = compute_worktree_path(repo, &target.branch, config)?;-- // Phase 3: Check if worktree already exists for this branch- if let Some(existing) =- check_existing_worktree(repo, &target.branch, &expected_path, new_previous.clone())?- {- return Ok(existing);+ // Phase 2: Check if worktree already exists for this branch (fast path)+ // This avoids computing the worktree path template (~7 git commands) for existing switches.+ match repo.worktree_for_branch(&target.branch)? {+ Some(existing_path) if existing_path.exists() => {+ return Ok(SwitchPlan::Existing {+ path: canonicalize(&existing_path).unwrap_or(existing_path),+ branch: target.branch,+ new_previous,+ });+ }+ Some(_) => {+ return Err(GitError::WorktreeMissing {+ branch: target.branch,+ }+ .into());+ }+ None => {}}+ // Phase 3: Compute expected path (only needed for create)+ let expected_path = compute_worktree_path(repo, &target.branch, config)?;+// Phase 4: Validate we can create at this pathlet clobber_backup = validate_worktree_creation(repo,@@ -654,7 +640,6 @@ pub fn execute_switch(SwitchPlan::Existing {path,branch,- expected_path,new_previous,} => {let current_dir = std::env::current_dir()@@ -672,23 +657,19 @@ pub fn execute_switch(let _ = repo.set_switch_previous(new_previous.as_deref());}- let mismatch_path = if !paths_match(&path, &expected_path) {- Some(expected_path)- } else {- None- };-let result = if already_at_worktree {SwitchResult::AlreadyAt(path)} else {SwitchResult::Existing { path }};+ // Path mismatch is computed lazily by callers after first output,+ // avoiding ~7 git commands on the hot path for existing switches.Ok((result,SwitchBranchInfo {branch,- expected_path: mismatch_path,+ expected_path: None,},))}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 5e9bf898a..140aaa84c 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -97,8 +97,6 @@ pub enum SwitchPlan {Existing {path: PathBuf,branch: String,- /// Expected path for mismatch detection- expected_path: PathBuf,/// Branch to record as "previous" for `wt switch -`new_previous: Option<String>,},