Skip to content

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

feat: show path mismatch warning when removing worktrees at unexpected paths (#428)

Maximilian Roos361fc2013016
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 73a4d5d43..e47dcfd57 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -12,7 +12,9 @@ use super::context::CommandEnv;
use super::hooks::{HookFailureStrategy, run_hook_with_filter};
use super::project_config::{HookCommand, collect_commands_for_hooks};
use super::repository_ext::RepositoryCliExt;
-use super::worktree::{BranchDeletionMode, MergeOperations, RemoveResult, handle_push};
+use super::worktree::{
+ BranchDeletionMode, MergeOperations, RemoveResult, get_path_mismatch, handle_push,
+};
/// Options for the merge command
pub struct MergeOptions<'a> {
@@ -211,6 +213,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let mut provider =
worktrunk::git::LazyGitIntegration::new(&main_repo, &current_branch, &effective_target);
let integration_reason = worktrunk::git::check_integration(&mut provider);
+ // Compute expected_path for path mismatch detection
+ let expected_path = get_path_mismatch(repo, &current_branch, &worktree_root, config);
let remove_result = RemoveResult::RemovedWorktree {
main_path: destination_path.clone(),
worktree_path: worktree_root,
@@ -222,6 +226,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// Don't force removal - if worktree has untracked files added after
// commit, removal will fail and user can run `wt remove --force`
force_worktree: false,
+ expected_path,
};
// Run hooks during merge removal (pass through verify flag)
// Approval was handled at the gate (collect_merge_commands)
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index e4894f43e..e4c57e4db 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -2,9 +2,10 @@ use std::path::{Path, PathBuf};
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
-use super::worktree::{BranchDeletionMode, RemoveResult};
+use super::worktree::{BranchDeletionMode, RemoveResult, get_path_mismatch};
use anyhow::Context;
use color_print::cformat;
+use worktrunk::config::WorktrunkConfig;
use worktrunk::git::{
GitError, IntegrationReason, Repository, parse_porcelain_z, parse_untracked_files,
};
@@ -30,11 +31,15 @@ pub trait RepositoryCliExt {
///
/// Returns a `RemoveResult` describing what will be removed. The actual
/// removal is performed by the output handler.
+ ///
+ /// The `config` parameter is used to compute the expected worktree path
+ /// for path mismatch detection.
fn prepare_worktree_removal(
&self,
target: RemoveTarget,
deletion_mode: BranchDeletionMode,
force_worktree: bool,
+ config: &WorktrunkConfig,
) -> anyhow::Result<RemoveResult>;
/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.
@@ -69,6 +74,7 @@ impl RepositoryCliExt for Repository {
target: RemoveTarget,
deletion_mode: BranchDeletionMode,
force_worktree: bool,
+ config: &WorktrunkConfig,
) -> anyhow::Result<RemoveResult> {
let current_path = self.worktree_root()?.to_path_buf();
let worktrees = self.list_worktrees()?;
@@ -185,6 +191,12 @@ impl RepositoryCliExt for Repository {
deletion_mode,
);
+ // Compute expected_path for path mismatch detection
+ // Only set if actual path differs from expected (path mismatch)
+ let expected_path = branch_name
+ .as_ref()
+ .and_then(|branch| get_path_mismatch(self, branch, &worktree_path, config));
+
Ok(RemoveResult::RemovedWorktree {
main_path,
worktree_path,
@@ -194,6 +206,7 @@ impl RepositoryCliExt for Repository {
target_branch,
integration_reason,
force_worktree,
+ expected_path,
})
}
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index fb57fe9ae..f40a01d3e 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -218,6 +218,16 @@ fn is_worktree_at_expected_path(
is_worktree_at_expected_path_with(wt, repo, config, &default_branch, is_bare)
}
+/// Compare two paths for equality, canonicalizing to handle symlinks and relative paths.
+///
+/// Returns `true` if the paths resolve to the same location.
+fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {
+ use dunce::canonicalize;
+ let a_canonical = canonicalize(a).unwrap_or_else(|_| a.to_path_buf());
+ let b_canonical = canonicalize(b).unwrap_or_else(|_| b.to_path_buf());
+ a_canonical == b_canonical
+}
+
/// Check if a worktree is at its expected path, with pre-computed values.
///
/// Use this when `default_branch` and `is_bare` are already known (e.g., in list command)
@@ -229,21 +239,29 @@ pub fn is_worktree_at_expected_path_with(
default_branch: &str,
is_bare: bool,
) -> bool {
- use dunce::canonicalize;
-
match &wt.branch {
Some(branch) => compute_worktree_path_with(repo, branch, config, default_branch, is_bare)
- .map(
- |expected| match (canonicalize(&wt.path), canonicalize(&expected)) {
- (Ok(actual), Ok(expected)) => actual == expected,
- _ => wt.path == expected,
- },
- )
+ .map(|expected| paths_match(&wt.path, &expected))
.unwrap_or(false),
None => false,
}
}
+/// Returns the expected path if `actual_path` differs from the template-computed path.
+///
+/// Returns `Some(expected_path)` when there's a mismatch, `None` when paths match.
+/// Used to show path mismatch warnings in `wt remove` and `wt merge`.
+pub fn get_path_mismatch(
+ repo: &Repository,
+ branch: &str,
+ actual_path: &std::path::Path,
+ config: &WorktrunkConfig,
+) -> Option<PathBuf> {
+ compute_worktree_path(repo, branch, config)
+ .ok()
+ .filter(|expected| !paths_match(actual_path, expected))
+}
+
/// Optimized variant of `compute_worktree_path` that accepts pre-computed values.
///
/// Use this when `default_branch` and `is_bare` are already known to avoid
@@ -413,6 +431,9 @@ pub enum RemoveResult {
integration_reason: Option<worktrunk::git::IntegrationReason>,
/// Force git worktree removal even with untracked files.
force_worktree: bool,
+ /// Expected path based on config template. `Some` when actual path differs
+ /// from expected (path mismatch), `None` when path matches template.
+ expected_path: Option<PathBuf>,
},
/// Branch exists but has no worktree - attempt branch deletion only
BranchOnly {
@@ -496,8 +517,7 @@ pub fn handle_switch(
.unwrap_or(false);
// Check if the actual path matches the expected path (branch-worktree mismatch detection).
- let canonical_expected = canonicalize(&expected_path).unwrap_or(expected_path.clone());
- let mismatch_path = if canonical_path != canonical_expected {
+ let mismatch_path = if !paths_match(&path, &expected_path) {
Some(expected_path.clone())
} else {
None
@@ -714,6 +734,7 @@ pub fn handle_remove(
force_delete: bool,
force_worktree: bool,
background: bool,
+ config: &WorktrunkConfig,
) -> anyhow::Result<RemoveResult> {
let repo = Repository::current();
@@ -728,6 +749,7 @@ pub fn handle_remove(
RemoveTarget::Branch(worktree_name),
BranchDeletionMode::from_flags(no_delete_branch, force_delete),
force_worktree,
+ config,
)
}
@@ -740,6 +762,7 @@ pub fn handle_remove_current(
force_delete: bool,
force_worktree: bool,
background: bool,
+ config: &WorktrunkConfig,
) -> anyhow::Result<RemoveResult> {
let repo = Repository::current();
@@ -752,6 +775,7 @@ pub fn handle_remove_current(
RemoveTarget::Current,
BranchDeletionMode::from_flags(no_delete_branch, force_delete),
force_worktree,
+ config,
)
}
@@ -1125,6 +1149,7 @@ mod tests {
target_branch: Some("main".to_string()),
integration_reason: Some(worktrunk::git::IntegrationReason::SameCommit),
force_worktree: false,
+ expected_path: None,
};
match result {
RemoveResult::RemovedWorktree {
@@ -1136,6 +1161,7 @@ mod tests {
target_branch,
integration_reason,
force_worktree,
+ expected_path,
} => {
assert_eq!(main_path.to_str().unwrap(), "/main");
assert_eq!(worktree_path.to_str().unwrap(), "/worktree");
@@ -1146,6 +1172,7 @@ mod tests {
assert_eq!(target_branch.as_deref(), Some("main"));
assert!(integration_reason.is_some());
assert!(!force_worktree);
+ assert!(expected_path.is_none());
}
_ => panic!("Expected RemovedWorktree variant"),
}
@@ -1181,6 +1208,7 @@ mod tests {
target_branch: None,
integration_reason: None, // Force delete skips integration check
force_worktree: true,
+ expected_path: None,
};
match result {
RemoveResult::RemovedWorktree {
diff --git a/src/main.rs b/src/main.rs
index a275f54e7..ac8136745 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1373,9 +1373,14 @@ fn main() {
if branches.is_empty() {
// No branches specified, remove current worktree
// Uses path-based removal to handle detached HEAD state
- let result =
- handle_remove_current(!delete_branch, force_delete, force, background)
- .context("Failed to remove worktree")?;
+ let result = handle_remove_current(
+ !delete_branch,
+ force_delete,
+ force,
+ background,
+ &config,
+ )
+ .context("Failed to remove worktree")?;
// Approval was handled at the gate
// Post-switch hooks are spawned internally by handle_remove_output
handle_remove_output(&result, background, verify)
@@ -1430,6 +1435,7 @@ fn main() {
force_delete,
force,
background,
+ &config,
) {
Ok(result) => {
handle_remove_output(&result, background, verify)?;
@@ -1443,8 +1449,14 @@ fn main() {
// Handle branch-only cases (no worktree)
for branch in &branch_only {
- match handle_remove(branch, !delete_branch, force_delete, force, background)
- {
+ match handle_remove(
+ branch,
+ !delete_branch,
+ force_delete,
+ force,
+ background,
+ &config,
+ ) {
Ok(result) => {
handle_remove_output(&result, background, verify)?;
}
@@ -1458,8 +1470,13 @@ fn main() {
// Remove current worktree last (if it was in the list)
// Post-switch hooks are spawned internally by handle_remove_output
if let Some((_path, _branch)) = current {
- match handle_remove_current(!delete_branch, force_delete, force, background)
- {
+ match handle_remove_current(
+ !delete_branch,
+ force_delete,
+ force,
+ background,
+ &config,
+ ) {
Ok(result) => {
handle_remove_output(&result, background, verify)?;
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 6b1be9a04..ca20b7e37 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1,7 +1,7 @@
//! Output handlers for worktree operations using the global output context
use color_print::cformat;
-use std::path::Path;
+use std::path::{Path, PathBuf};
use crate::commands::branch_deletion::{
BranchDeletionOutcome, BranchDeletionResult, delete_branch_if_safe,
@@ -62,6 +62,16 @@ fn format_switch_message(
}
}
+/// Format a branch-worktree mismatch warning message.
+///
+/// Shows when a worktree is at a path that doesn't match the config template.
+fn format_path_mismatch_warning(branch: &str, expected_path: &Path) -> FormattedMessage {
+ let expected_display = format_path_for_display(expected_path);
+ warning_message(cformat!(
+ "Branch-worktree mismatch; expected <bold>{branch}</> @ <bold>{expected_display}</> <red>⚑</>"
+ ))
+}
+
/// Handle the result of a branch deletion attempt.
///
/// Shows appropriate messages for non-deleted branches:
@@ -298,13 +308,10 @@ pub fn handle_switch_output(
};
// Show branch-worktree mismatch warning after the main message
- let branch_worktree_mismatch_warning = branch_info.expected_path.as_ref().map(|expected| {
- let expected_display = format_path_for_display(expected);
- let branch = &branch_info.branch;
- warning_message(cformat!(
- "Branch-worktree mismatch; expected <bold>{branch}</> @ <bold>{expected_display}</> <red>⚑</>"
- ))
- });
+ let branch_worktree_mismatch_warning = branch_info
+ .expected_path
+ .as_ref()
+ .map(|expected| format_path_mismatch_warning(&branch_info.branch, expected));
let display_path_for_hooks = match result {
SwitchResult::AlreadyAt(_) => {
@@ -430,6 +437,7 @@ pub fn handle_remove_output(
target_branch,
integration_reason,
force_worktree,
+ expected_path,
} => handle_removed_worktree_output(
main_path,
worktree_path,
@@ -439,6 +447,7 @@ pub fn handle_remove_output(
target_branch.as_deref(),
*integration_reason,
*force_worktree,
+ expected_path.as_ref(),
background,
verify,
),
@@ -533,6 +542,7 @@ fn handle_removed_worktree_output(
target_branch: Option<&str>,
pre_computed_integration: Option<IntegrationReason>,
force_worktree: bool,
+ expected_path: Option<&PathBuf>,
background: bool,
verify: bool,
) -> anyhow::Result<()> {
@@ -655,6 +665,11 @@ fn handle_removed_worktree_output(
};
super::print(FormattedMessage::new(action))?;
+ // Show path mismatch warning if the worktree is at an unexpected location
+ if let Some(expected) = expected_path {
+ super::print(format_path_mismatch_warning(branch_name, expected))?;
+ }
+
// Show hints for branch status
if !should_delete_branch {
if deletion_mode.should_keep() && branch_was_integrated {
@@ -761,6 +776,11 @@ fn handle_removed_worktree_output(
};
super::print(FormattedMessage::new(msg))?;
+ // Show path mismatch warning if the worktree was at an unexpected location
+ if let Some(expected) = expected_path {
+ super::print(format_path_mismatch_warning(branch_name, expected))?;
+ }
+
// Show hints for branch status
if !branch_deleted {
if deletion_mode.should_keep() && branch_was_integrated {
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 427d02f2c..56acbeae2 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1353,3 +1353,62 @@ approved-commands = ["echo 'branch={{{{ branch }}}}' > {branch_path}"]
"{{ branch }} should expand to 'HEAD' for detached HEAD worktrees"
);
}
+
+/// Test that removing a worktree at a non-standard path shows a path mismatch warning.
+///
+/// When a worktree is created at a path that doesn't match the config template,
+/// `wt remove` should show a warning about the path mismatch.
+#[rstest]
+fn test_remove_path_mismatch_warning(repo: TestRepo) {
+ // Create a worktree at a non-standard path using raw git
+ // (wt switch --create would put it at the expected path)
+ let unexpected_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("weird-path-for-feature");
+
+ repo.git_command()
+ .args([
+ "worktree",
+ "add",
+ unexpected_path.to_str().unwrap(),
+ "-b",
+ "feature",
+ ])
+ .output()
+ .unwrap();
+
+ // Remove the worktree - should show path mismatch warning
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature"], None));
+}
+
+/// Test that removing a worktree at a non-standard path shows warning in foreground mode.
+#[rstest]
+fn test_remove_path_mismatch_warning_foreground(repo: TestRepo) {
+ // Create a worktree at a non-standard path using raw git
+ let unexpected_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("another-weird-path");
+
+ repo.git_command()
+ .args([
+ "worktree",
+ "add",
+ unexpected_path.to_str().unwrap(),
+ "-b",
+ "feature-fg",
+ ])
+ .output()
+ .unwrap();
+
+ // Remove in foreground mode - should show path mismatch warning
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--no-background", "feature-fg"],
+ None
+ ));
+}
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning.snap b/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning.snap
new file mode 100644
index 000000000..7441ddd76
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning.snap
@@ -0,0 +1,36 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - 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: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature worktree & branch in background (same commit as main, _)
+▲ Branch-worktree mismatch; expected feature @ _REPO_.feature ⚑
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning_foreground.snap b/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning_foreground.snap
new file mode 100644
index 000000000..710068888
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning_foreground.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--no-background"
+ - feature-fg
+ 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: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature-fg worktree...
+✓ Removed feature-fg worktree & branch (same commit as main, _)
+▲ Branch-worktree mismatch; expected feature-fg @ _REPO_.feature-fg ⚑