Skip to content

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

Improve error message when worktree path is occupied by different branch (#334)

Maximilian Roos305efe102167
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 36150e03d..be2063db1 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -502,7 +502,7 @@ pub fn handle_switch(
// Compute expected worktree path for this branch
let expected_path = compute_worktree_path(&repo, &resolved_branch, config)?;
- // Helper to build switch result for an existing worktree
+ // Helper to build switch result for an existing worktree.
let switch_to_existing = |path: PathBuf| -> (SwitchResult, SwitchBranchInfo) {
let canonical_path = canonicalize(&path).unwrap_or(path.clone());
let current_dir = std::env::current_dir()
@@ -513,7 +513,7 @@ pub fn handle_switch(
.map(|cur| cur == &canonical_path)
.unwrap_or(false);
- // Check if the actual path matches the expected path
+ // 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())
@@ -555,6 +555,7 @@ pub fn handle_switch(
let branch = path_branch.unwrap_or_else(|| resolved_branch.clone());
return Err(GitError::WorktreeMissing { branch }.into());
}
+
// Path is occupied by a different branch's worktree
return Err(GitError::WorktreePathOccupied {
branch: resolved_branch.clone(),
diff --git a/src/git/error.rs b/src/git/error.rs
index 7f8f19627..47851c3a6 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -235,23 +235,25 @@ impl std::fmt::Display for GitError {
occupant,
} => {
let path_display = format_path_for_display(path);
- let error_detail = if let Some(occupant_branch) = occupant {
+ let reason = if let Some(occupant_branch) = occupant {
cformat!(
- "existing worktree at <bold>{path_display}</> on <bold>{occupant_branch}</>"
+ "there's a worktree at the expected path <bold>{path_display}</> on branch <bold>{occupant_branch}</>"
)
} else {
- cformat!("existing worktree at <bold>{path_display}</>, detached")
+ cformat!(
+ "there's a detached worktree at the expected path <bold>{path_display}</>"
+ )
};
// Hint leads into the command in the gutter block
- let hint = hint_message("To switch the worktree to this branch:");
+ let hint = hint_message(cformat!(
+ "To switch the worktree at <bold>{path_display}</> to branch <bold>{branch}</>:"
+ ));
let path_escaped = escape(Cow::Borrowed(path_display.as_ref()));
let command = format!("cd {path_escaped} && git switch {branch}");
write!(
f,
"{}\n{}\n{}",
- error_message(cformat!(
- "Cannot create worktree for <bold>{branch}</>: {error_detail}"
- )),
+ error_message(cformat!("Cannot switch to <bold>{branch}</> — {reason}")),
hint,
format_bash_with_gutter(&command)
)
@@ -911,9 +913,13 @@ mod tests {
occupant: Some("main".into()),
};
let display = err.to_string();
+ assert!(display.contains("Cannot switch to"));
assert!(display.contains("feature"));
+ assert!(display.contains("there's a worktree at the expected path"));
+ assert!(display.contains("on branch"));
assert!(display.contains("main"));
- assert!(display.contains("existing worktree"));
+ assert!(display.contains("To switch the worktree at"));
+ assert!(display.contains("to branch"));
// Without occupant (detached)
let err = GitError::WorktreePathOccupied {
@@ -922,7 +928,7 @@ mod tests {
occupant: None,
};
let display = err.to_string();
- assert!(display.contains("detached"));
+ assert!(display.contains("detached worktree"));
}
#[test]
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 a2466fcfe..e68f39f65 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
@@ -2,6 +2,6 @@
source: tests/integration_tests/git_error_display.rs
expression: err.to_string()
---
-✗ Cannot create worktree for feature-z: existing worktree at /tmp/repo.feature-z on other-branch
-↳ To switch the worktree to this branch:
+✗ Cannot switch to feature-z — there's a worktree at the expected path /tmp/repo.feature-z on branch other-branch
+↳ To switch the worktree at /tmp/repo.feature-z to branch 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 2aa4936b5..b62f63d2d 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -563,10 +563,10 @@ fn test_switch_error_path_occupied_detached(repo: TestRepo) {
/// 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.
+/// `git checkout feature`, `wt switch main` should error with a helpful message
+/// explaining how to get there. This matches GitHub issue #327.
#[rstest]
-fn test_switch_error_main_worktree_on_different_branch(repo: TestRepo) {
+fn test_switch_main_worktree_on_different_branch(repo: TestRepo) {
use std::process::Command;
// Switch the main worktree to a different branch
@@ -577,14 +577,43 @@ fn test_switch_error_main_worktree_on_different_branch(repo: TestRepo) {
.output()
.unwrap();
- // Now try to switch to main - should error because main worktree is on feature
+ // Now try to switch to main - should error since main worktree is on different branch
snapshot_switch_with_directive_file(
- "switch_error_main_worktree_on_different_branch",
+ "switch_main_worktree_on_different_branch",
&repo,
&["main"],
);
}
+/// Test switching to default branch FROM a feature worktree when main worktree is on different branch
+///
+/// This reproduces GitHub issue #327: user is in a feature worktree, main worktree has been
+/// switched to a different branch, and user runs `wt switch <default-branch>`.
+#[rstest]
+fn test_switch_default_branch_from_feature_worktree(mut repo: TestRepo) {
+ use std::process::Command;
+
+ // Create a feature worktree to work from
+ let feature_a_path = repo.add_worktree("feature-a");
+
+ // Switch main worktree to a different branch (simulates user running git checkout there)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["checkout", "-b", "feature-rpa"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // From feature-a worktree, try to switch to main (default branch)
+ // This should error because main worktree is now on feature-rpa
+ snapshot_switch_from_dir(
+ "switch_default_branch_from_feature_worktree",
+ &repo,
+ &["main"],
+ &feature_a_path,
+ );
+}
+
// Execute tests with directive file
/// Test that --execute with exit code is written to directive file.
/// The shell wrapper sources this file and propagates the exit code.
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_default_branch_from_feature_worktree.snap b/tests/snapshots/integration__integration_tests__switch__switch_default_branch_from_feature_worktree.snap
new file mode 100644
index 000000000..459f00a01
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_default_branch_from_feature_worktree.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - 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: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ 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 switch to main — there's a worktree at the expected path _REPO_ on branch feature-rpa
+↳ To switch the worktree at _REPO_ to branch 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
index 673e188a4..23b047a7d 100644
--- 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
@@ -31,6 +31,6 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Cannot create worktree for feature: existing worktree at _REPO_.feature, detached
-↳ To switch the worktree to this branch:
+✗ Cannot switch to feature — there's a detached worktree at the expected path _REPO_.feature
+↳ To switch the worktree at _REPO_.feature to branch 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
index c99ef9c0d..ff6edb831 100644
--- 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
@@ -31,6 +31,6 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Cannot create worktree for feature: existing worktree at _REPO_.feature on bugfix
-↳ To switch the worktree to this branch:
+✗ Cannot switch to feature — there's a worktree at the expected path _REPO_.feature on branch bugfix
+↳ To switch the worktree at _REPO_.feature to branch feature:
  cd _REPO_.feature && git switch feature
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_main_worktree_on_different_branch.snap
similarity index 78%
rename from tests/snapshots/integration__integration_tests__switch__switch_error_main_worktree_on_different_branch.snap
rename to tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
index 8b491265b..564cd899f 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_main_worktree_on_different_branch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
@@ -31,6 +31,6 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Cannot create worktree for main: existing worktree at _REPO_ on feature
-↳ To switch the worktree to this branch:
+✗ Cannot switch to main — there's a worktree at the expected path _REPO_ on branch feature
+↳ To switch the worktree at _REPO_ to branch main:
  cd _REPO_ && git switch main