Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Improve switch mismatch detection and messaging (#195)

Maximilian Roos25eec0af6576
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 0213c33f6..f56861bb5 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -71,6 +71,12 @@ repos:
entry: '\\x1b\['
# format.rs strips ANSI codes injected by wrap_ansi crate
exclude: '^(tests/|.*_test\.rs$|src/styling/(line|mod|format)\.rs$|src/output/global\.rs$|src/cli\.rs$)'
+ - id: no-std-canonicalize-in-tests
+ name: no-std-canonicalize-in-tests
+ description: Use dunce::canonicalize in tests to avoid Windows \\?\ prefix issues
+ language: pygrep
+ entry: '\.canonicalize\(\)'
+ files: '^tests/'
ci:
# pre-commit.ci doesn't have Rust toolchain, so skip Rust-specific hooks.
diff --git a/Cargo.lock b/Cargo.lock
index b4bff6f94..763ddcd4a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1977,6 +1977,9 @@ dependencies = [
[[package]]
name = "setup-select-test"
version = "0.1.0"
+dependencies = [
+ "dunce",
+]
[[package]]
name = "sha2"
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index c5d98c18d..a1503633f 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -35,6 +35,7 @@ use worktrunk::styling::{
};
use crate::commands::command_executor::{CommandContext, build_hook_context};
+use crate::commands::worktree_display_name;
use crate::output;
/// Run a command in each worktree sequentially.
@@ -58,10 +59,8 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
let repo_root = repo.worktree_base()?;
for wt in &worktrees.worktrees {
- let branch = wt.branch.as_deref().unwrap_or("(detached)");
- output::print(progress_message(cformat!(
- "Running in <bold>{branch}</>..."
- )))?;
+ let display_name = worktree_display_name(wt, &repo, &config);
+ output::print(progress_message(format!("Running in {display_name}...")))?;
// Open repository at worktree path to get worktree-specific context (commit, etc.)
let wt_repo = Repository::at(&wt.path);
@@ -101,10 +100,10 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
Ok(()) => {}
Err(CommandError::SpawnFailed(err)) => {
output::print(error_message(cformat!(
- "Failed in <bold>{branch}</> (spawn failed)"
+ "Failed in <bold>{display_name}</> (spawn failed)"
)))?;
output::gutter(format_with_gutter(&err, "", None))?;
- failed.push(branch.to_string());
+ failed.push(display_name.to_string());
}
Err(CommandError::ExitCode(exit_code)) => {
// stderr already streamed to terminal; just show failure message
@@ -112,9 +111,9 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
.map(|code| format!(" (exit code {code})"))
.unwrap_or_default();
output::print(error_message(cformat!(
- "Failed in <bold>{branch}</>{exit_info}"
+ "Failed in <bold>{display_name}</>{exit_info}"
)))?;
- failed.push(branch.to_string());
+ failed.push(display_name.to_string());
}
}
}
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 971bcf79a..075e9ecaf 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -19,14 +19,14 @@
//! - Within worktrees: Git operations (ahead/behind, diffs, CI) run concurrently via scoped threads
//!
//! This ensures fast operations don't wait for slow ones (e.g., CI doesn't block ahead/behind counts)
-use std::path::Path;
-
use crossbeam_channel as chan;
use dunce::canonicalize;
use rayon::prelude::*;
use worktrunk::git::{LineDiff, Repository, Worktree};
use worktrunk::styling::{INFO_EMOJI, warning_message};
+use crate::commands::is_worktree_at_expected_path;
+
use super::ci_status::PrStatus;
use super::model::{
AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, GitOperationState, ItemKind,
@@ -515,13 +515,6 @@ pub fn collect(
current_worktree_path.as_ref(),
);
- // Get main worktree directory name for path template expansion
- let main_worktree_name = main_worktree
- .path
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("");
-
// Get branches early for layout calculation and skeleton creation (when --branches is used)
// Sort by timestamp (most recent first)
let branches_without_worktrees = if show_branches {
@@ -563,30 +556,8 @@ pub fn collect(
.as_deref()
.is_some_and(|prev| wt.branch.as_deref() == Some(prev));
- // Compute path mismatch: does the actual path match what the template would generate?
- // Main worktree on default branch is the reference point (no mismatch possible)
- // Main worktree on OTHER branch should show mismatch (it's "not at home")
- let paths_equal = |expected: &Path| -> bool {
- match (&wt_canonical, canonicalize(expected).ok()) {
- (Some(actual), Some(expected)) => actual == &expected,
- _ => wt.path == *expected,
- }
- };
- let path_mismatch = if is_main && wt.branch.as_deref() == Some(default_branch.as_str())
- {
- false
- } else if let Some(branch) = &wt.branch {
- config
- .format_path(main_worktree_name, branch)
- .map(|rel| !paths_equal(&main_worktree.path.join(&rel)))
- .unwrap_or_else(|e| {
- log::debug!("Template expansion failed for branch {}: {}", branch, e);
- false
- })
- } else {
- // Detached HEAD - not on any branch, so "not at home"
- true
- };
+ // Check if worktree is at its expected path based on config template
+ let path_mismatch = !is_worktree_at_expected_path(wt, repo, config);
let mut worktree_data =
WorktreeData::from_worktree(wt, is_main, is_current, is_previous);
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 785d1885e..1a0c89611 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -38,7 +38,7 @@ pub use standalone::{
};
pub use worktree::{
compute_worktree_path, handle_remove, handle_remove_by_path, handle_remove_current,
- handle_switch, resolve_worktree_arg,
+ handle_switch, is_worktree_at_expected_path, resolve_worktree_arg, worktree_display_name,
};
// Re-export Shell from the canonical location
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 046634899..cb982dd3f 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use color_print::cformat;
use skim::prelude::*;
use std::borrow::Cow;
use std::fs;
@@ -488,7 +489,7 @@ impl WorktreeSkimItem {
let path = wt_info.path.display().to_string();
self.render_diff_preview(
&["-C", &path, "diff", "HEAD"],
- &format!("{INFO_EMOJI} {branch} has no uncommitted changes"),
+ &cformat!("{INFO_EMOJI} <bold>{branch}</> has no uncommitted changes"),
width,
)
}
@@ -501,16 +502,18 @@ impl WorktreeSkimItem {
let branch = self.item.branch_name();
let repo = Repository::current();
let Ok(default_branch) = repo.default_branch() else {
- return format!("{INFO_EMOJI} {branch} has no commits ahead of main\n");
+ return cformat!("{INFO_EMOJI} <bold>{branch}</> has no commits ahead of main\n");
};
if self.item.counts().ahead == 0 {
- return format!("{INFO_EMOJI} {branch} has no commits ahead of {default_branch}\n");
+ return cformat!(
+ "{INFO_EMOJI} <bold>{branch}</> has no commits ahead of <bold>{default_branch}</>\n"
+ );
}
let merge_base = format!("{}...{}", default_branch, self.item.head());
self.render_diff_preview(
&["diff", &merge_base],
- &format!("{INFO_EMOJI} {branch} has no changes vs {default_branch}"),
+ &cformat!("{INFO_EMOJI} <bold>{branch}</> has no changes vs <bold>{default_branch}</>"),
width,
)
}
@@ -532,7 +535,7 @@ impl WorktreeSkimItem {
let head = self.item.head();
let branch = self.item.branch_name();
let Ok(default_branch) = repo.default_branch() else {
- output.push_str(&format!("{INFO_EMOJI} {branch} has no commits\n"));
+ output.push_str(&cformat!("{INFO_EMOJI} <bold>{branch}</> has no commits\n"));
return output;
};
@@ -547,7 +550,7 @@ impl WorktreeSkimItem {
// running git commands. This would provide better diagnostics but adds latency to
// every preview render. Trade-off: simplicity + speed vs. detailed error messages.
let Ok(merge_base_output) = repo.run_command(&["merge-base", &default_branch, head]) else {
- output.push_str(&format!("{INFO_EMOJI} {branch} has no commits\n"));
+ output.push_str(&cformat!("{INFO_EMOJI} <bold>{branch}</> has no commits\n"));
return output;
};
@@ -940,8 +943,7 @@ pub fn handle_select(is_directive_mode: bool) -> anyhow::Result<()> {
// Switch to the selected worktree
// handle_switch can handle both branch names and worktree paths
- let (result, resolved_branch) =
- handle_switch(&identifier, false, None, false, false, &config)?;
+ let (result, branch_info) = handle_switch(&identifier, false, None, false, false, &config)?;
// Clear the terminal screen after skim exits to prevent artifacts
// Use stderr for terminal control sequences - in directive mode, stdout goes to a FIFO
@@ -952,7 +954,7 @@ pub fn handle_select(is_directive_mode: bool) -> anyhow::Result<()> {
execute!(stderr(), crossterm::cursor::MoveTo(0, 0))?;
// Show success message; emit cd directive if in directive mode
- handle_switch_output(&result, &resolved_branch, false, is_directive_mode)?;
+ handle_switch_output(&result, &branch_info, false, is_directive_mode)?;
}
Ok(())
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 40f535b3a..13333b655 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -189,12 +189,22 @@ pub fn resolve_worktree_arg(
}
/// Compute the expected worktree path for a branch name.
+///
+/// For the default branch, returns the repo root (main worktree location).
+/// For other branches, applies the `worktree-path` template from config.
pub fn compute_worktree_path(
repo: &Repository,
branch: &str,
config: &WorktrunkConfig,
) -> anyhow::Result<PathBuf> {
let repo_root = repo.worktree_base()?;
+
+ // 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 !repo.is_bare()? && repo.default_branch().is_ok_and(|default| branch == default) {
+ return Ok(repo_root);
+ }
+
let repo_name = repo_root
.file_name()
.ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?
@@ -214,6 +224,61 @@ pub fn compute_worktree_path(
Ok(repo_root.join(relative_path).normalize())
}
+/// Check if a worktree is at its expected path based on config template.
+///
+/// Returns true if the worktree's actual path matches what `compute_worktree_path`
+/// would generate for its branch. Detached HEAD always returns false (no expected path).
+///
+/// Uses canonicalization to handle symlinks and relative paths correctly.
+pub fn is_worktree_at_expected_path(
+ wt: &worktrunk::git::Worktree,
+ repo: &Repository,
+ config: &WorktrunkConfig,
+) -> bool {
+ use dunce::canonicalize;
+
+ match &wt.branch {
+ Some(branch) => compute_worktree_path(repo, branch, config)
+ .map(|expected| {
+ // Use canonicalization to handle symlinks
+ match (canonicalize(&wt.path), canonicalize(&expected)) {
+ (Ok(actual), Ok(expected)) => actual == expected,
+ _ => wt.path == expected, // Fallback to direct comparison
+ }
+ })
+ .unwrap_or(false),
+ None => false, // Detached HEAD has no expected path
+ }
+}
+
+/// Compute a user-facing display name for a worktree.
+///
+/// Returns styled content with branch names bolded:
+/// - If branch is consistent with worktree location: just the branch name (bolded)
+/// - If branch differs from expected location: `dir_name (on **branch**)` (both bolded)
+/// - If detached HEAD: `dir_name (detached)` (dir_name bolded)
+///
+/// "Consistent" means the worktree path matches `compute_worktree_path(branch)`,
+/// which returns repo root for default branch and templated path for others.
+pub fn worktree_display_name(
+ wt: &worktrunk::git::Worktree,
+ repo: &Repository,
+ config: &WorktrunkConfig,
+) -> String {
+ let dir_name = wt.dir_name();
+
+ match &wt.branch {
+ Some(branch) => {
+ if is_worktree_at_expected_path(wt, repo, config) {
+ cformat!("<bold>{branch}</>")
+ } else {
+ cformat!("<bold>{dir_name}</> (on <bold>{branch}</>)")
+ }
+ }
+ None => cformat!("<bold>{dir_name}</> (detached)"),
+ }
+}
+
/// Flags indicating which merge operations occurred
#[derive(Debug, Clone, Copy)]
pub struct MergeOperations {
@@ -252,6 +317,29 @@ impl SwitchResult {
}
}
+/// Branch state for a switch operation, tracking expected vs current branch.
+#[derive(Debug, Clone)]
+pub struct SwitchBranchInfo {
+ /// The branch user expected to switch to (resolved from input)
+ pub expected: String,
+ /// The branch currently checked out (None = detached HEAD)
+ pub current: Option<String>,
+ /// Expected path when there's a path mismatch (None = path matches template)
+ pub expected_path: Option<PathBuf>,
+}
+
+impl SwitchBranchInfo {
+ /// Check if there's a mismatch between expected and current branch
+ pub fn is_branch_mismatch(&self) -> bool {
+ self.current.as_deref() != Some(self.expected.as_str())
+ }
+
+ /// The branch name (for no-mismatch case where expected == current)
+ pub fn branch(&self) -> &str {
+ self.current.as_deref().unwrap_or(&self.expected)
+ }
+}
+
/// Result of a worktree remove operation
pub enum RemoveResult {
/// Removed worktree and returned to main (if needed)
@@ -280,7 +368,7 @@ pub fn handle_switch(
force: bool,
no_verify: bool,
config: &WorktrunkConfig,
-) -> anyhow::Result<(SwitchResult, String)> {
+) -> anyhow::Result<(SwitchResult, SwitchBranchInfo)> {
let repo = Repository::current();
// Get the actual current branch BEFORE switching.
@@ -333,29 +421,48 @@ pub fn handle_switch(
let expected_path = compute_worktree_path(&repo, &resolved_branch, config)?;
// Helper to build switch result for an existing worktree
- let switch_to_existing = |path: PathBuf, branch: String| -> (SwitchResult, String) {
- let canonical_path = canonicalize(&path).unwrap_or(path);
- let current_dir = std::env::current_dir()
- .ok()
- .and_then(|p| canonicalize(&p).ok());
- let already_at_worktree = current_dir
- .as_ref()
- .map(|cur| cur == &canonical_path)
- .unwrap_or(false);
-
- let result = if already_at_worktree {
- SwitchResult::AlreadyAt(canonical_path)
- } else {
- SwitchResult::Existing(canonical_path)
+ // `actual_branch` is None for detached HEAD
+ let switch_to_existing =
+ |path: PathBuf, actual_branch: Option<String>| -> (SwitchResult, SwitchBranchInfo) {
+ let canonical_path = canonicalize(&path).unwrap_or(path.clone());
+ let current_dir = std::env::current_dir()
+ .ok()
+ .and_then(|p| canonicalize(&p).ok());
+ let already_at_worktree = current_dir
+ .as_ref()
+ .map(|cur| cur == &canonical_path)
+ .unwrap_or(false);
+
+ // Check if the actual path matches the expected path
+ let canonical_expected = canonicalize(&expected_path).unwrap_or(expected_path.clone());
+ let path_mismatch = if canonical_path != canonical_expected {
+ Some(expected_path.clone())
+ } else {
+ None
+ };
+
+ let result = if already_at_worktree {
+ SwitchResult::AlreadyAt(canonical_path)
+ } else {
+ SwitchResult::Existing(canonical_path)
+ };
+ let branch_info = SwitchBranchInfo {
+ expected: resolved_branch.clone(),
+ current: actual_branch,
+ expected_path: path_mismatch,
+ };
+ (result, branch_info)
};
- (result, branch)
- };
// Branch-first lookup: check if branch has a worktree anywhere
match repo.worktree_for_branch(&resolved_branch)? {
Some(existing_path) if existing_path.exists() => {
let _ = repo.record_switch_previous(new_previous.as_deref());
- return Ok(switch_to_existing(existing_path, resolved_branch));
+ // Branch matches (found by branch lookup), so actual = requested
+ return Ok(switch_to_existing(
+ existing_path,
+ Some(resolved_branch.clone()),
+ ));
}
Some(_) => {
return Err(GitError::WorktreeMissing {
@@ -496,7 +603,11 @@ pub fn handle_switch(
base_branch: base_for_creation,
from_remote,
},
- resolved_branch,
+ SwitchBranchInfo {
+ expected: resolved_branch.clone(),
+ current: Some(resolved_branch),
+ expected_path: None, // Created at expected path by definition
+ },
))
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 6c0b56730..7214014b6 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -225,22 +225,24 @@ impl std::fmt::Display for GitError {
occupant,
} => {
let path_display = format_path_for_display(path);
- let hint = if let Some(occupant_branch) = occupant {
- hint_message(cformat!(
- "Reuse the existing worktree at {path_display} (currently on <bold>{occupant_branch}</>) or remove the directory before retrying"
- ))
+ let error_suffix = if let Some(occupant_branch) = occupant {
+ cformat!("existing worktree, on <bold>{occupant_branch}</>")
} else {
- hint_message(format!(
- "Reuse the existing worktree at {path_display} or remove the directory before retrying"
- ))
+ "existing worktree, detached".to_string()
};
+ // Hint is self-contained (includes both path and branch)
+ let hint = hint_message(cformat!(
+ "Switch the worktree at <bright-black>{path_display}</> to <bright-black>{branch}</>"
+ ));
+ let command = format!("cd {path_display} && git switch {branch}");
write!(
f,
- "{}\n\n{}",
+ "{}\n\n{}\n{}",
error_message(cformat!(
- "Cannot create worktree for <bold>{branch}</>: target path already exists"
+ "Cannot create worktree for <bold>{branch}</> at <bold>{path_display}</>: {error_suffix}"
)),
- hint
+ hint,
+ format_with_gutter(&command, "", None)
)
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 3f28834ca..aa134af9d 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -212,6 +212,27 @@ pub struct Worktree {
pub prunable: Option<String>,
}
+/// Extract the directory name from a path for display purposes.
+///
+/// Returns the last component of the path as a string, or "(unknown)" if
+/// the path has no filename or contains invalid UTF-8.
+pub fn path_dir_name(path: &std::path::Path) -> &str {
+ path.file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("(unknown)")
+}
+
+impl Worktree {
+ /// Returns the worktree directory name.
+ ///
+ /// This is the filesystem directory name (e.g., "repo.feature" from "/path/to/repo.feature").
+ /// For user-facing display with context (branch consistency, detached state),
+ /// use `worktree_display_name()` from the commands module instead.
+ pub fn dir_name(&self) -> &str {
+ path_dir_name(&self.path)
+ }
+}
+
/// A list of worktrees with automatic bare worktree filtering.
///
/// This type ensures:
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 3cf9db6cc..00a993ea9 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -60,6 +60,8 @@ fn base_path() -> &'static PathBuf {
struct RepositoryLayout {
/// Base path for worktrees (repo root for normal repos, bare repo path for bare repos)
worktree_base: PathBuf,
+ /// Whether this is a bare repository
+ is_bare: bool,
}
/// Repository context for git operations.
@@ -132,7 +134,10 @@ impl Repository {
.to_path_buf()
};
- let layout = RepositoryLayout { worktree_base };
+ let layout = RepositoryLayout {
+ worktree_base,
+ is_bare,
+ };
// set() returns Err if already set, but we checked above, so ignore the result
let _ = self.layout.set(layout);
@@ -540,6 +545,14 @@ impl Repository {
Ok(self.layout()?.worktree_base.clone())
}
+ /// 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.
+ pub fn is_bare(&self) -> anyhow::Result<bool> {
+ Ok(self.layout()?.is_bare)
+ }
+
/// Check if the working tree has uncommitted changes.
pub fn is_dirty(&self) -> anyhow::Result<bool> {
let stdout = self.run_command(&["status", "--porcelain"])?;
diff --git a/src/main.rs b/src/main.rs
index c4a6fb0fe..66aaadc31 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1220,14 +1220,14 @@ fn main() {
}
// Execute switch operation (creates worktree, runs post-create hooks if approved)
- let (result, resolved_branch) =
+ let (result, branch_info) =
handle_switch(&branch, create, base.as_deref(), force, skip_hooks, &config)?;
// Show success message (temporal locality: immediately after worktree creation)
// Pass cli.internal to indicate whether shell integration is active
handle_switch_output(
&result,
- &resolved_branch,
+ &branch_info,
execute.is_some(),
cli.internal.is_some(),
)?;
@@ -1241,7 +1241,7 @@ fn main() {
let ctx = CommandContext::new(
&repo,
&config,
- Some(&resolved_branch),
+ Some(branch_info.branch()),
path,
&repo_root,
force,
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index ca33f611d..2c1259367 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -6,11 +6,12 @@ use std::path::Path;
use crate::commands::command_executor::CommandContext;
use crate::commands::execute_pre_remove_commands;
use crate::commands::process::spawn_detached;
-use crate::commands::worktree::{RemoveResult, SwitchResult};
+use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::GitError;
use worktrunk::git::IntegrationReason;
use worktrunk::git::Repository;
+use worktrunk::git::path_dir_name;
use worktrunk::path::format_path_for_display;
use worktrunk::shell::Shell;
use worktrunk::styling::{
@@ -346,50 +347,109 @@ fn shell_integration_hint() -> String {
/// When false, we show warnings for operations that can't complete without shell integration.
pub fn handle_switch_output(
result: &SwitchResult,
- branch: &str,
+ branch_info: &SwitchBranchInfo,
has_execute_command: bool,
is_directive_mode: bool,
) -> anyhow::Result<()> {
// Set target directory for command execution
super::change_directory(result.path())?;
- // Show message based on result type and mode
+ let path = result.path();
+ let path_display = format_path_for_display(path);
+ let expected_branch = &branch_info.expected;
+
+ // Handle branch mismatch cases (worktree checked out to wrong branch or detached)
+ if branch_info.is_branch_mismatch() {
+ let mismatch_info = match &branch_info.current {
+ Some(current) => {
+ cformat!("expecting <bold>{expected_branch}</>, got <bold>{current}</>")
+ }
+ None => cformat!("expecting <bold>{expected_branch}</>, got detached HEAD"),
+ };
+
+ match result {
+ SwitchResult::AlreadyAt(_) => {
+ super::print(warning_message(cformat!(
+ "Already at <bold>{path_display}</>. Branch doesn't match path: {mismatch_info}"
+ )))?;
+ }
+ SwitchResult::Existing(_) => {
+ if is_directive_mode || has_execute_command {
+ super::print(warning_message(cformat!(
+ "Switched to <bold>{path_display}</>. Branch doesn't match path: {mismatch_info}"
+ )))?;
+ } else if Shell::is_integration_configured().ok().flatten().is_some() {
+ super::print(warning_message(cformat!(
+ "Worktree at <bold>{path_display}</>. Branch doesn't match path: {mismatch_info} (cannot cd, binary invoked directly)"
+ )))?;
+ } else {
+ super::print(warning_message(cformat!(
+ "Worktree at <bold>{path_display}</>. Branch doesn't match path: {mismatch_info} (cannot cd, no shell integration)"
+ )))?;
+ super::shell_integration_hint(shell_integration_hint())?;
+ }
+ }
+ SwitchResult::Created { .. } => {
+ // Created case should never have mismatch - we just created it
+ unreachable!("Created worktree should not have branch mismatch");
+ }
+ }
+
+ super::flush()?;
+ return Ok(());
+ }
+
+ // Normal case - branch matches
+ let branch = branch_info.branch();
+
+ // Show path mismatch warning after the main message
+ let path_mismatch_warning = branch_info.expected_path.as_ref().map(|expected| {
+ let expected_display = format_path_for_display(expected);
+ warning_message(format!(
+ "Worktree path doesn't match naming template (expected {expected_display})"
+ ))
+ });
+
match result {
- SwitchResult::AlreadyAt(path) => {
- // Already at target - show info, no hint needed
+ SwitchResult::AlreadyAt(_) => {
super::print(info_message(cformat!(
- "Already on worktree for <bold>{branch}</> @ <bold>{}</>",
- format_path_for_display(path)
+ "Already on worktree for <bold>{branch}</> @ <bold>{path_display}</>"
)))?;
+ if let Some(warning) = path_mismatch_warning {
+ super::print(warning)?;
+ }
}
- SwitchResult::Existing(path) => {
- let path_display = format_path_for_display(path);
-
+ SwitchResult::Existing(_) => {
if is_directive_mode || has_execute_command {
- // Shell integration active or --execute provided - show success
super::print(success_message(format_switch_success_message(
branch, path, false, None, None,
)))?;
+ if let Some(warning) = path_mismatch_warning {
+ super::print(warning)?;
+ }
} else if Shell::is_integration_configured().ok().flatten().is_some() {
- // Shell configured but not active (ran binary directly, e.g. `command wt`)
super::print(warning_message(cformat!(
"Worktree for <bold>{branch}</> @ <bold>{path_display}</>; cannot cd (binary invoked directly)"
)))?;
+ if let Some(warning) = path_mismatch_warning {
+ super::print(warning)?;
+ }
} else {
- // Shell integration not configured - show warning and setup hint
super::print(warning_message(cformat!(
"Worktree for <bold>{branch}</> @ <bold>{path_display}</>; cannot cd (no shell integration)"
)))?;
+ if let Some(warning) = path_mismatch_warning {
+ super::print(warning)?;
+ }
super::shell_integration_hint(shell_integration_hint())?;
}
}
SwitchResult::Created {
- path,
created_branch,
base_branch,
from_remote,
+ ..
} => {
- // Creation succeeded - show success
super::print(success_message(format_switch_success_message(
branch,
path,
@@ -404,9 +464,7 @@ pub fn handle_switch_output(
}
}
- // Flush output (important for directive mode)
super::flush()?;
-
Ok(())
}
@@ -598,7 +656,7 @@ fn handle_removed_worktree_output(
let _ = target_repo.run_command(&["fsmonitor--daemon", "stop"]);
if let Err(err) = repo.remove_worktree(worktree_path) {
return Err(GitError::WorktreeRemovalFailed {
- branch: "(detached)".into(),
+ branch: path_dir_name(worktree_path).to_string(),
path: worktree_path.to_path_buf(),
error: err.to_string(),
}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index e0b47118b..48215e5f5 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -478,7 +478,7 @@ fn copy_fixture_template(dest: &Path) {
/// On Windows, `std::fs::canonicalize()` returns verbatim paths like `\\?\C:\...`
/// which git cannot handle. The `dunce` crate strips this prefix when safe.
/// On Unix, this is equivalent to `std::fs::canonicalize()`.
-fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
+pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
dunce::canonicalize(path)
}
@@ -1661,20 +1661,36 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {
"[REPO]$1",
);
- // Normalize temp directory paths in project identifiers (approval prompts)
- // Example: /private/var/folders/wf/.../T/.tmpABC123/origin -> [PROJECT_ID]
- settings.add_filter(
- r"/private/var/folders/[^/]+/[^/]+/T/\.[^/]+/[^)]+",
- "[PROJECT_ID]",
- );
-
// Normalize WORKTRUNK_CONFIG_PATH temp paths in stdout/stderr output
// (metadata is handled via redactions below)
+ // IMPORTANT: These specific filters must come BEFORE the generic [PROJECT_ID] filters
settings.add_filter(r".*/\.tmp[^/]+/test-config\.toml", "[TEST_CONFIG]");
// Normalize GIT_CONFIG_GLOBAL temp paths
settings.add_filter(r".*/\.tmp[^/]+/test-gitconfig", "[TEST_GIT_CONFIG]");
+ // Normalize temp directory paths in project identifiers (approval prompts)
+ // Example: /private/var/folders/wf/.../T/.tmpABC123/origin -> [PROJECT_ID]
+ // Note: [^)'\s\x1b]+ stops at ), ', whitespace, or ANSI escape to avoid matching too much
+ settings.add_filter(
+ r"/private/var/folders/[^/]+/[^/]+/T/\.[^/]+/[^)'\s\x1b]+",
+ "[PROJECT_ID]",
+ );
+ // Linux: /tmp/.tmpXXXXXX/path -> [PROJECT_ID]
+ settings.add_filter(r"/tmp/\.tmp[^/]+/[^)'\s\x1b]+", "[PROJECT_ID]");
+ // Windows: C:/Users/user/AppData/Local/Temp/.tmpXXXXXX/path -> [PROJECT_ID]
+ // Handles Windows temp paths with drive letters (after backslash normalization)
+ settings.add_filter(
+ r"[A-Z]:/Users/[^/]+/AppData/Local/Temp/\.tmp[^/]+/[^)'\s\x1b]+",
+ "[PROJECT_ID]",
+ );
+
+ // Generic tilde-prefixed paths that aren't repo or worktree paths.
+ // On CI, HOME is a temp directory, so paths under HOME become ~/something.
+ // This catches paths like ~/wrong-path that don't follow the repo naming convention.
+ // MUST come AFTER specific ~/repo patterns so they match first.
+ settings.add_filter(r"~/[a-zA-Z0-9_-]+", "[PROJECT_ID]");
+
// Normalize HOME temp directory in snapshots (stdout/stderr content)
// Matches any temp directory path (without trailing filename)
// Examples:
diff --git a/tests/helpers/setup-select-test/Cargo.toml b/tests/helpers/setup-select-test/Cargo.toml
index 4cb1e66d2..284e77d70 100644
--- a/tests/helpers/setup-select-test/Cargo.toml
+++ b/tests/helpers/setup-select-test/Cargo.toml
@@ -6,3 +6,6 @@ name = "setup-select-test"
version = "0.1.0"
edition = "2024"
publish = false
+
+[dependencies]
+dunce = "1.0"
diff --git a/tests/helpers/setup-select-test/src/main.rs b/tests/helpers/setup-select-test/src/main.rs
index 2982690e5..50c278214 100644
--- a/tests/helpers/setup-select-test/src/main.rs
+++ b/tests/helpers/setup-select-test/src/main.rs
@@ -11,9 +11,14 @@
use std::fs;
use std::io::{self, Write};
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::process::Command;
+/// Canonicalize path without Windows `\\?\` prefix.
+fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
+ dunce::canonicalize(path)
+}
+
fn main() {
println!("Setting up test environment for `wt select`...\n");
@@ -26,7 +31,7 @@ fn main() {
let root = temp_base.join("repo");
fs::create_dir(&root).unwrap();
- let root = root.canonicalize().unwrap();
+ let root = canonicalize(&root).unwrap();
// Initialize git repo
git(&root, &["init", "-b", "main"]);
@@ -108,7 +113,7 @@ fn main() {
}
// Add uncommitted changes to feature worktree
- let feature_wt = feature_wt.canonicalize().unwrap();
+ let feature_wt = canonicalize(&feature_wt).unwrap();
fs::write(feature_wt.join("uncommitted.txt"), "uncommitted changes").unwrap();
// Create some branches without worktrees
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
index a83b5ea6a..1e321d9d8 100644
--- a/tests/integration_tests/bare_repository.rs
+++ b/tests/integration_tests/bare_repository.rs
@@ -1,4 +1,6 @@
-use crate::common::{TestRepo, repo, setup_temp_snapshot_settings, wait_for_file, wt_command};
+use crate::common::{
+ TestRepo, canonicalize, repo, setup_temp_snapshot_settings, wait_for_file, wt_command,
+};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
@@ -16,7 +18,8 @@ struct BareRepoTest {
impl BareRepoTest {
fn new() -> Self {
let temp_dir = tempfile::TempDir::new().unwrap();
- let bare_repo_path = temp_dir.path().join("repo.git");
+ // Bare repo without .git suffix - worktrees go inside as subdirectories
+ let bare_repo_path = temp_dir.path().join("repo");
let test_config_path = temp_dir.path().join("test-config.toml");
let mut test = Self {
@@ -43,8 +46,12 @@ impl BareRepoTest {
);
}
- // Canonicalize path
- test.bare_repo_path = test.bare_repo_path.canonicalize().unwrap();
+ // Canonicalize path (using dunce to avoid \\?\ prefix on Windows)
+ test.bare_repo_path = canonicalize(&test.bare_repo_path).unwrap();
+
+ // Write config with template for worktrees inside bare repo
+ // Template {{ branch }} creates worktrees as subdirectories: repo/main, repo/feature
+ fs::write(&test.test_config_path, "worktree-path = \"{{ branch }}\"\n").unwrap();
test
}
@@ -62,8 +69,9 @@ impl BareRepoTest {
}
/// Create a worktree from the bare repository
+ /// Worktrees are created inside the bare repo directory: repo/main, repo/feature
fn create_worktree(&self, branch: &str, worktree_name: &str) -> PathBuf {
- let worktree_path = self.temp_dir.path().join(worktree_name);
+ let worktree_path = self.bare_repo_path.join(worktree_name);
let mut cmd = Command::new("git");
cmd.args([
@@ -90,7 +98,7 @@ impl BareRepoTest {
);
}
- worktree_path.canonicalize().unwrap()
+ canonicalize(&worktree_path).unwrap()
}
/// Create a commit in the specified worktree
@@ -160,11 +168,12 @@ impl BareRepoTest {
fn test_bare_repo_list_worktrees() {
let test = BareRepoTest::new();
- // Create two worktrees
- let main_worktree = test.create_worktree("main", "repo.main");
+ // Create worktrees inside bare repo matching template: {{ branch }}
+ // Worktrees are at repo/main and repo/feature
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit on main");
- let feature_worktree = test.create_worktree("feature", "repo.feature");
+ let feature_worktree = test.create_worktree("feature", "feature");
test.commit_in_worktree(&feature_worktree, "Work on feature");
let settings = setup_temp_snapshot_settings(test.temp_path());
@@ -183,7 +192,7 @@ fn test_bare_repo_list_shows_no_bare_entry() {
let test = BareRepoTest::new();
// Create one worktree
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit");
// Run wt list and verify bare repo is NOT shown
@@ -205,13 +214,11 @@ fn test_bare_repo_switch_creates_worktree() {
let test = BareRepoTest::new();
// Create initial worktree
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit");
- // Use default template (sibling worktrees): ../{{ main_worktree }}.{{ branch }}
- // No config needed - defaults will create worktrees as siblings with dot separator
-
// Run wt switch --create to create a new worktree
+ // Config uses {{ branch }} template, so worktrees are created inside bare repo
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
cmd.args(["switch", "--create", "feature", "--internal"])
@@ -227,32 +234,13 @@ fn test_bare_repo_switch_creates_worktree() {
);
}
- // Debug: check where worktrees actually are
- let list_output = Command::new("git")
- .args([
- "-C",
- test.bare_repo_path().to_str().unwrap(),
- "worktree",
- "list",
- ])
- .env("GIT_CONFIG_GLOBAL", "/dev/null")
- .output()
- .unwrap();
-
- eprintln!(
- "Git worktree list:\n{}",
- String::from_utf8_lossy(&list_output.stdout)
- );
-
- // Verify the new worktree was created as sibling with dot separator
- // Default template: ../{{ main_worktree }}.{{ branch }} -> repo.git.feature
- let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
- let expected_path = test.temp_path().join(format!("{}.feature", bare_name));
+ // Verify the new worktree was created inside the bare repo
+ // Template: {{ branch }} -> repo/feature
+ let expected_path = test.bare_repo_path().join("feature");
assert!(
expected_path.exists(),
- "Expected worktree at {:?} but it doesn't exist.\nGit worktree list:\n{}",
- expected_path,
- String::from_utf8_lossy(&list_output.stdout)
+ "Expected worktree at {:?}",
+ expected_path
);
// Verify git worktree list shows both worktrees (but not bare repo)
@@ -274,15 +262,14 @@ fn test_bare_repo_switch_creates_worktree() {
}
#[test]
-fn test_bare_repo_switch_with_default_naming() {
+fn test_bare_repo_switch_with_configured_naming() {
let test = BareRepoTest::new();
// Create initial worktree
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit");
- // Use default naming pattern (should still work with bare repos)
- // Default is "../{{ main_worktree }}.{{ branch }}" which becomes "repo.git.feature"
+ // Config uses "{{ branch }}" template, so worktrees are created inside bare repo
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
cmd.args(["switch", "--create", "feature", "--internal"])
@@ -298,9 +285,8 @@ fn test_bare_repo_switch_with_default_naming() {
);
}
- // Verify worktree was created as sibling to bare repo
- let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
- let expected_path = test.temp_path().join(format!("{}.feature", bare_name));
+ // Verify worktree was created inside bare repo
+ let expected_path = test.bare_repo_path().join("feature");
assert!(
expected_path.exists(),
"Expected worktree at {:?}",
@@ -313,10 +299,10 @@ fn test_bare_repo_remove_worktree() {
let test = BareRepoTest::new();
// Create two worktrees
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit");
- let feature_worktree = test.create_worktree("feature", "repo.feature");
+ let feature_worktree = test.create_worktree("feature", "feature");
test.commit_in_worktree(&feature_worktree, "Feature work");
// Remove feature worktree from main worktree
@@ -350,11 +336,11 @@ fn test_bare_repo_identifies_primary_correctly() {
let test = BareRepoTest::new();
// Create multiple worktrees
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Main commit");
- let _feature1 = test.create_worktree("feature1", "repo.feature1");
- let _feature2 = test.create_worktree("feature2", "repo.feature2");
+ let _feature1 = test.create_worktree("feature1", "feature1");
+ let _feature2 = test.create_worktree("feature2", "feature2");
// Run wt list to see which is marked as primary
let mut cmd = wt_command();
@@ -374,13 +360,11 @@ fn test_bare_repo_worktree_base_used_for_paths() {
let test = BareRepoTest::new();
// Create initial worktree
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit");
- // Use default template - creates sibling worktrees with dot separator
- // No config needed - defaults will create worktrees as siblings
-
- // Create new worktree - should be created relative to bare repo root
+ // Create new worktree - config uses {{ branch }} template
+ // Worktrees are created inside the bare repo directory
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
cmd.args(["switch", "--create", "dev", "--internal"])
@@ -388,21 +372,20 @@ fn test_bare_repo_worktree_base_used_for_paths() {
cmd.output().unwrap();
- // Verify path is created as sibling to bare repo (using worktree_base)
- // Default template: ../{{ main_worktree }}.{{ branch }} -> repo.git.dev
- let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
- let expected = test.temp_path().join(format!("{}.dev", bare_name));
+ // Verify path is created inside bare repo (using worktree_base)
+ // Template: {{ branch }} -> repo/dev
+ let expected = test.bare_repo_path().join("dev");
assert!(
expected.exists(),
"Worktree should be created using worktree_base: {:?}",
expected
);
- // Should NOT be relative to main worktree
- let wrong_path = main_worktree.join("dev");
+ // Should NOT be relative to main worktree's directory (as if it were a non-bare repo)
+ let wrong_path = main_worktree.parent().unwrap().join("main.dev");
assert!(
!wrong_path.exists(),
- "Worktree should not be relative to main worktree"
+ "Worktree should not use worktree directory as base"
);
}
@@ -413,7 +396,7 @@ fn test_bare_repo_equivalent_to_normal_repo(repo: TestRepo) {
// Set up bare repo
let bare_test = BareRepoTest::new();
- let bare_main = bare_test.create_worktree("main", "bare-repo.main");
+ let bare_main = bare_test.create_worktree("main", "main");
bare_test.commit_in_worktree(&bare_main, "Commit in bare repo");
// Set up normal repo (using fixture)
@@ -452,7 +435,7 @@ fn test_bare_repo_commands_from_bare_directory() {
let test = BareRepoTest::new();
// Create a worktree so the repo has some content
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit");
// Run wt list from the bare repo directory itself (not from a worktree)
@@ -487,22 +470,19 @@ fn test_bare_repo_merge_workflow() {
let test = BareRepoTest::new();
// Create main worktree
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit on main");
- // Use default template - creates sibling worktrees with dot separator
- // No config needed - defaults will create worktrees as siblings
-
- // Create feature branch worktree
+ // Create feature branch worktree using wt switch
+ // Config uses {{ branch }} template, so worktrees are inside bare repo
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
cmd.args(["switch", "--create", "feature", "--internal"])
.current_dir(&main_worktree);
cmd.output().unwrap();
- // Get feature worktree path (default template: ../{{ main_worktree }}.{{ branch }})
- let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
- let feature_worktree = test.temp_path().join(format!("{}.feature", bare_name));
+ // Get feature worktree path (template: {{ branch }} -> repo/feature)
+ let feature_worktree = test.bare_repo_path().join("feature");
assert!(feature_worktree.exists(), "Feature worktree should exist");
// Make a commit in feature worktree
@@ -566,12 +546,11 @@ fn test_bare_repo_background_logs_location() {
let test = BareRepoTest::new();
// Create main worktree
- let main_worktree = test.create_worktree("main", "repo.main");
+ let main_worktree = test.create_worktree("main", "main");
test.commit_in_worktree(&main_worktree, "Initial commit");
// Create feature worktree
- let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
- let feature_worktree = test.create_worktree("feature", &format!("{}.feature", bare_name));
+ let feature_worktree = test.create_worktree("feature", "feature");
test.commit_in_worktree(&feature_worktree, "Feature work");
// Run remove in background to test log file location
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index d8a459253..4fdeb0ea6 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1,6 +1,6 @@
use crate::common::{
- TestRepo, make_snapshot_cmd_with_global_flags, repo, repo_with_remote, setup_snapshot_settings,
- setup_temp_snapshot_settings, wt_command,
+ TestRepo, canonicalize, make_snapshot_cmd_with_global_flags, repo, repo_with_remote,
+ setup_snapshot_settings, setup_temp_snapshot_settings, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -561,7 +561,7 @@ fn test_remove_default_branch_no_tautology() {
.unwrap();
assert!(output.status.success(), "Failed to init bare repo");
- let bare_repo_path: PathBuf = bare_repo_path.canonicalize().unwrap();
+ let bare_repo_path: PathBuf = canonicalize(&bare_repo_path).unwrap();
// Create worktree for main branch
let main_worktree = temp_dir.path().join("repo.main");
@@ -583,7 +583,7 @@ fn test_remove_default_branch_no_tautology() {
.unwrap();
assert!(output.status.success(), "Failed to create main worktree");
- let main_worktree = main_worktree.canonicalize().unwrap();
+ let main_worktree = canonicalize(&main_worktree).unwrap();
// Create initial commit in main worktree
std::fs::write(main_worktree.join("file.txt"), "initial").unwrap();
@@ -630,7 +630,7 @@ fn test_remove_default_branch_no_tautology() {
.unwrap();
assert!(output.status.success(), "Failed to create feature worktree");
- let feature_worktree = feature_worktree.canonicalize().unwrap();
+ let feature_worktree = canonicalize(&feature_worktree).unwrap();
// Remove main worktree by name from feature worktree (foreground for snapshot)
// Should NOT show "(ancestor of main)" - that would be tautological
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index e8147ac09..24c6dbce1 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -36,6 +36,7 @@
#![cfg(all(unix, feature = "shell-integration-tests"))]
use crate::common::TestRepo;
+use crate::common::canonicalize;
use crate::common::shell::shell_available;
use insta::assert_snapshot;
use insta_cmd::get_cargo_bin;
@@ -1526,7 +1527,7 @@ approved-commands = ["echo 'fish background task'"]
// Get the worktrunk source directory (where this test is running from)
// This is the directory that contains Cargo.toml with the workspace
- let worktrunk_source = env::current_dir().unwrap().canonicalize().unwrap();
+ let worktrunk_source = canonicalize(&env::current_dir().unwrap()).unwrap();
// Build a shell script that runs from the worktrunk source directory
let wt_bin = get_cargo_bin("wt");
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_path_occupied.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_path_occupied.snap
index ba9fcac23..0044acdcc 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_path_occupied.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_path_occupied.snap
@@ -1,7 +1,8 @@
---
-source: tests/git_error_display.rs
+source: tests/integration_tests/git_error_display.rs
expression: err.to_string()
---
-❌ Cannot create worktree for feature-z: target path already exists
+❌ Cannot create worktree for feature-z at /tmp/repo.feature-z: existing worktree, on other-branch
-💡 Reuse the existing worktree at /tmp/repo.feature-z (currently on other-branch) or remove the directory before retrying
+💡 Switch the worktree at /tmp/repo.feature-z to feature-z
+  cd /tmp/repo.feature-z && git switch feature-z
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 8f1186f63..0c95ec734 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -439,13 +439,164 @@ fn test_create_with_base_main(repo: TestRepo) {
);
}
+/// Test that normal switch (branch matches) does NOT show warning
#[rstest]
-fn test_switch_default_branch_missing_worktree(repo: TestRepo) {
- // Move the primary worktree off the default branch so no worktree holds it
- repo.switch_primary_to("develop");
+fn test_switch_no_warning_when_branch_matches(mut repo: TestRepo) {
+ // Create a worktree for "feature" branch (normal case)
+ repo.add_worktree("feature");
+
+ // Switch to feature with shell integration - should NOT show any warning
+ snapshot_switch_with_global_flags(
+ "switch_no_warning_when_branch_matches",
+ &repo,
+ &["feature"],
+ &["--internal"],
+ );
+}
+
+/// Test switching to a worktree at an unexpected path shows a hint
+#[rstest]
+fn test_switch_path_mismatch_shows_hint(repo: TestRepo) {
+ use std::process::Command;
+
+ // Create a worktree at a non-standard path (sibling to repo, not following template)
+ let wrong_path = repo.root_path().parent().unwrap().join("wrong-path");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args([
+ "worktree",
+ "add",
+ wrong_path.to_str().unwrap(),
+ "-b",
+ "feature",
+ ])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Switch to feature - should show hint about path mismatch
+ snapshot_switch_with_global_flags(
+ "switch_path_mismatch_shows_hint",
+ &repo,
+ &["feature"],
+ &["--internal"],
+ );
+}
+
+/// Test that switching to a branch errors when path is occupied by worktree on different branch
+///
+/// With branch-first lookup, if a worktree was created for "feature" but then switched to
+/// "bugfix", `wt switch feature` can't find it (since it looks by branch name). When it
+/// tries to create a new worktree, it fails because the path exists. The hint shows what
+/// branch currently occupies the path.
+#[rstest]
+fn test_switch_error_path_occupied_different_branch(repo: TestRepo) {
+ use std::process::Command;
+
+ // Create a worktree for "feature" branch at expected path
+ let feature_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args([
+ "worktree",
+ "add",
+ feature_path.to_str().unwrap(),
+ "-b",
+ "feature",
+ ])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Switch that worktree to a different branch "bugfix"
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["switch", "-c", "bugfix"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ // Switch to feature - should error since path is occupied by bugfix worktree
+ snapshot_switch_with_global_flags(
+ "switch_error_path_occupied_different_branch",
+ &repo,
+ &["feature"],
+ &["--internal"],
+ );
+}
- snapshot_switch("switch_default_branch_missing_worktree", &repo, &["main"]);
+/// Test that switching to a branch errors when path is occupied by detached HEAD worktree
+#[rstest]
+fn test_switch_error_path_occupied_detached(repo: TestRepo) {
+ use std::process::Command;
+
+ // Create a worktree for "feature" branch at expected path
+ let feature_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args([
+ "worktree",
+ "add",
+ feature_path.to_str().unwrap(),
+ "-b",
+ "feature",
+ ])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Get the HEAD commit and detach
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ let output = cmd
+ .args(["rev-parse", "HEAD"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["checkout", "--detach", &commit])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ // Switch to feature - should error since path is occupied by detached worktree
+ snapshot_switch_with_global_flags(
+ "switch_error_path_occupied_detached",
+ &repo,
+ &["feature"],
+ &["--internal"],
+ );
}
+
+/// Test switching to default branch when main worktree is on a different branch
+///
+/// When the main worktree (repo root) has been switched to a feature branch via
+/// `git checkout feature`, `wt switch main` should show the path-occupied error
+/// with helpful commands to switch it back.
+#[rstest]
+fn test_switch_error_main_worktree_on_different_branch(repo: TestRepo) {
+ use std::process::Command;
+
+ // Switch the main worktree to a different branch
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["checkout", "-b", "feature"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Now try to switch to main - should error because main worktree is on feature
+ snapshot_switch_with_global_flags(
+ "switch_error_main_worktree_on_different_branch",
+ &repo,
+ &["main"],
+ &["--internal"],
+ );
+}
+
// Internal mode with execute tests
/// Test that --execute with exit code is emitted in directive mode shell script.
/// The shell wrapper will eval this script and propagate the exit code.
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
index 5ccb9d88a..a6de5e635 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
@@ -21,8 +21,8 @@ exit_code: 0
----- stdout -----
----- stderr -----
- Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-@ main ^ ./repo.main 6c3da842 1d Initial commit on main
-+ feature ⚑↑ ↑1 ./repo.feature 72413a3b 1d Work on feature
+ Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+@ main ^ ./main 6c3da842 1d Initial commit on main
++ feature ↑ ↑1 ./feature 72413a3b 1d Work on feature
⚪ Showing 2 worktrees, 1 ahead
diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails.snap
index d60cc9027..0c881bfbb 100644
--- a/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails.snap
+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails.snap
@@ -10,6 +10,7 @@ info:
- show
- nonexistent-ref
env:
+ APPDATA: "[TEST_CONFIG_HOME]"
CLICOLOR_FORCE: "1"
COLUMNS: "150"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -17,10 +18,14 @@ info:
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
+ PATH: "[PATH]"
SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: false
exit_code: 1
@@ -31,13 +36,13 @@ exit_code: 1
fatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
-❌ Failed in main (exit code 128)
+❌ Failed in main (exit code 128)
🔄 Running in feature...
fatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
-❌ Failed in feature (exit code 128)
+❌ Failed in feature (exit code 128)
🟡 2 of 2 worktrees failed
-  main
-  feature
+  main
+  feature
diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap
index bedfc8785..b7fde8539 100644
--- a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap
+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap
@@ -33,7 +33,7 @@ exit_code: 0
----- stderr -----
🔄 Running in main...
Branch: main
-🔄 Running in (detached)...
+🔄 Running in repo.detached-test (detached)...
Branch: HEAD
✅ Completed in 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached.snap
index d574a664a..0b57b8fae 100644
--- a/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached.snap
+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached.snap
@@ -33,6 +33,6 @@ exit_code: 0
----- stderr -----
🔄 Running in main...
-🔄 Running in (detached)...
+🔄 Running in repo.detached-test (detached)...
✅ Completed in 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_main_worktree_on_different_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_main_worktree_on_different_branch.snap
new file mode 100644
index 000000000..cd53ed6ee
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_main_worktree_on_different_branch.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - "--internal"
+ - switch
+ - main
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+❌ Cannot create worktree for main at [REPO]: existing worktree, on feature
+
+💡 Switch the worktree at [REPO] to main
+  cd [REPO] && git switch main
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
new file mode 100644
index 000000000..8987de94a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - "--internal"
+ - switch
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+❌ Cannot create worktree for feature at [REPO].feature: existing worktree, detached
+
+💡 Switch the worktree at [REPO].feature to feature
+  cd [REPO].feature && git switch feature
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
new file mode 100644
index 000000000..1eb61af83
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - "--internal"
+ - switch
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+❌ Cannot create worktree for feature at [REPO].feature: existing worktree, on bugfix
+
+💡 Switch the worktree at [REPO].feature to feature
+  cd [REPO].feature && git switch feature
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_default_branch_missing_worktree.snap b/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
similarity index 79%
rename from tests/snapshots/integration__integration_tests__switch__switch_default_branch_missing_worktree.snap
rename to tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
index 78af2b214..48510a50e 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_default_branch_missing_worktree.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
@@ -3,8 +3,9 @@ source: tests/integration_tests/switch.rs
info:
program: wt
args:
+ - "--internal"
- switch
- - main
+ - feature
env:
APPDATA: "[TEST_CONFIG_HOME]"
CLICOLOR_FORCE: "1"
@@ -26,7 +27,7 @@ info:
success: true
exit_code: 0
----- stdout -----
+cd '[REPO].feature'
----- stderr -----
-✅ Switched to worktree for main @ [REPO].main
-💡 Run wt config shell install to enable automatic cd
+✅ Switched to worktree for feature @ [REPO].feature
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_path_mismatch_shows_hint.snap b/tests/snapshots/integration__integration_tests__switch__switch_path_mismatch_shows_hint.snap
new file mode 100644
index 000000000..754e41757
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_path_mismatch_shows_hint.snap
@@ -0,0 +1,34 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - "--internal"
+ - switch
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+cd '[PROJECT_ID]'
+
+----- stderr -----
+✅ Switched to worktree for feature @ [PROJECT_ID]
+🟡 Worktree path doesn't match naming template (expected [REPO].feature)