Skip to content

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

feat: Improve worktree creation error handling and testing

Maximilian Roos5fb9e58a0efb
diff --git a/_typos.toml b/_typos.toml
new file mode 100644
index 000000000..4c3dac8be
--- /dev/null
+++ b/_typos.toml
@@ -0,0 +1,3 @@
+[default.extend-words]
+# Git commit hashes that typos flags as potential typos
+ba = "ba" # Part of commit hashes like e28e0ba
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index e0bd2fb4f..2cba7b2bb 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -236,8 +236,33 @@ pub fn handle_switch(
args.push(&resolved_branch);
}
- repo.run_command(&args)
- .git_context("Failed to create worktree")?;
+ // Create worktree and parse specific error cases
+ if let Err(e) = repo.run_command(&args) {
+ // Check if error is about directory already existing
+ if let GitError::CommandFailed(ref msg) = e
+ && msg.contains("already exists")
+ {
+ // Parse the path from git's error message
+ // Format: "fatal: '/path/to/dir' already exists"
+ if let Some(path_str) = msg
+ .lines()
+ .find(|line| line.contains("already exists"))
+ .and_then(|line| {
+ // Extract path between quotes
+ line.split('\'').nth(1).or_else(|| line.split('"').nth(1))
+ })
+ {
+ let path = std::path::PathBuf::from(path_str);
+ // Canonicalize if possible, otherwise use as-is
+ let normalized_path = path.canonicalize().unwrap_or(path);
+ return Err(GitError::WorktreePathExists {
+ path: normalized_path,
+ });
+ }
+ }
+ // Fall back to generic error with context
+ return Err(e).git_context("Failed to create worktree");
+ }
// Canonicalize the path to resolve any .. components
let worktree_path = worktree_path
diff --git a/src/git/error.rs b/src/git/error.rs
index 354ae44b1..3105b07ed 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -54,6 +54,8 @@ pub enum GitError {
target_branch: String,
git_output: String,
},
+ /// Worktree path already exists on filesystem
+ WorktreePathExists { path: PathBuf },
}
impl std::fmt::Display for GitError {
@@ -61,8 +63,16 @@ impl std::fmt::Display for GitError {
use crate::styling::{ERROR, ERROR_BOLD, ERROR_EMOJI, HINT, HINT_EMOJI};
match self {
- // Plain message that will be displayed by main.rs
- GitError::CommandFailed(msg) => write!(f, "{}", msg),
+ // Generic error - format with emoji and styling
+ // Skip formatting if message already contains ANSI codes (from nested error formatting)
+ GitError::CommandFailed(msg) => {
+ if msg.contains("\x1b[") || msg.contains("[31m") || msg.contains("[0m") {
+ // Already formatted, just pass through
+ write!(f, "{}", msg)
+ } else {
+ write!(f, "{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
+ }
+ }
// ParseError messages need formatting
GitError::ParseError(msg) => {
@@ -235,6 +245,15 @@ impl std::fmt::Display for GitError {
Ok(())
}
+
+ // Worktree path already exists
+ GitError::WorktreePathExists { path } => {
+ write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Directory already exists: {ERROR_BOLD}{}{ERROR_BOLD:#}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove the directory or use a different branch name{HINT:#}",
+ path.display()
+ )
+ }
}
}
}
diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rs
index 265b2cc31..d7254b3f4 100644
--- a/tests/integration_tests/configure_shell.rs
+++ b/tests/integration_tests/configure_shell.rs
@@ -216,7 +216,7 @@ fn test_configure_shell_no_files() {
----- stdout -----
----- stderr -----
- No shell config files found in $HOME. Checked: [TEMP_HOME]/.bash_profile, [TEMP_HOME]/.zshrc, and more. Create a config file or use --shell to specify a shell.
+ ❌ No shell config files found in $HOME. Checked: [TEMP_HOME]/.bash_profile, [TEMP_HOME]/.zshrc, and more. Create a config file or use --shell to specify a shell.
");
});
}
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index 834248a18..4289b37bf 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -29,7 +29,8 @@ fn test_switch_internal_directive() {
----- stdout -----
----- stderr -----
- Failed to create worktree: fatal: invalid reference: my-feature
+ Failed to create worktree: ❌ fatal: invalid reference: my-feature
+ 
");
});
}
@@ -56,7 +57,8 @@ fn test_switch_without_internal() {
----- stdout -----
----- stderr -----
- Failed to create worktree: fatal: invalid reference: my-feature
+ Failed to create worktree: ❌ fatal: invalid reference: my-feature
+ 
");
});
}
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap
index 712ce89a9..c78f6e87f 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap
@@ -3,7 +3,7 @@ source: tests/integration_tests/shell_wrapper.rs
expression: output.normalized()
---
πŸ”„ Running pre-merge: check1:
-  /Users/maximilian/workspace/worktrunk.select-diff/tests/fixtures/mixed-output.sh check1 3
+  /Users/maximilian/workspace/worktrunk.worktree-failure/tests/fixtures/mixed-output.sh check1 3
[check1] stdout line 1
[check1] stderr line 1
@@ -15,7 +15,7 @@ expression: output.normalized()
[check1] stderr complete
πŸ”„ Running pre-merge: check2:
-  /Users/maximilian/workspace/worktrunk.select-diff/tests/fixtures/mixed-output.sh check2 3
+  /Users/maximilian/workspace/worktrunk.worktree-failure/tests/fixtures/mixed-output.sh check2 3
[check2] stdout line 1
[check2] stderr line 1
@@ -26,9 +26,9 @@ expression: output.normalized()
[check2] stdout complete
[check2] stderr complete
-πŸ”„ Merging 1 commit to main @ 1c75520 (no commit/squash/rebase needed)
+πŸ”„ Merging 1 commit to main @ e28e0ba (no commit/squash/rebase needed)
-  * 1c75520 (HEAD -> feature) Add feature
+  * e28e0ba (HEAD -> feature) Add feature
  feature.txt | 1 +
  1 file changed, 1 insertion(+)
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap
index e7e7c79b5..fff418f41 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap
@@ -19,16 +19,16 @@ expression: output.normalized()
[check2] stdout complete
[check2] stderr complete
πŸ”„ Running pre-merge: check1:
-  /Users/maximilian/workspace/worktrunk.select-diff/tests/fixtures/mixed-output.sh check1 3
+  /Users/maximilian/workspace/worktrunk.worktree-failure/tests/fixtures/mixed-output.sh check1 3
πŸ”„ Running pre-merge: check2:
-  /Users/maximilian/workspace/worktrunk.select-diff/tests/fixtures/mixed-output.sh check2 3
+  /Users/maximilian/workspace/worktrunk.worktree-failure/tests/fixtures/mixed-output.sh check2 3
-πŸ”„ Merging 1 commit to main @ 1c75520 (no commit/squash/rebase needed)
+πŸ”„ Merging 1 commit to main @ e28e0ba (no commit/squash/rebase needed)
-  * 1c75520 (HEAD -> feature) Add feature
+  * e28e0ba (HEAD -> feature) Add feature
  feature.txt | 1 +
  1 file changed, 1 insertion(+)
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snap b/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snap
index cfc9bcc27..14c17898b 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmptCZRr2/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpckAh44/test-config.toml
---
success: false
exit_code: 1
@@ -33,7 +33,8 @@ exit_code: 1
πŸ”„ Switching to main...
----- stderr -----
-Failed to switch to 'main': error: Your local changes to the following files would be overwritten by checkout:
+Failed to switch to 'main': ❌ error: Your local changes to the following files would be overwritten by checkout:
file.txt
Please commit your changes or stash them before you switch branches.
Aborting
+
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap
index 2f80d2dd4..d34614039 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap
@@ -17,15 +17,16 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpg4vWIx/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmplMp93t/test-config.toml
---
success: false
exit_code: 1
----- stdout -----
----- stderr -----
-Failed to load project config: Failed to parse TOML: TOML parse error at line 1, column 39
+❌ Failed to load project config: Failed to parse TOML: TOML parse error at line 1, column 39
|
1 | post-create-command = [invalid syntax
| ^
unclosed array, expected `]`
+
diff --git a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
index fc75aae2f..ed8ae1668 100644
--- a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
+++ b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
@@ -17,11 +17,12 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpv0PFuF/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmph6Ajb4/test-config.toml
---
success: false
exit_code: 1
----- stdout -----
----- stderr -----
-Failed to create worktree: fatal: invalid reference: __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6
+Failed to create worktree: ❌ fatal: invalid reference: __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6
+
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap
index 397b7f32d..54bc2cdf1 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap
@@ -16,11 +16,11 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRhT5DU/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpVDcpEb/test-config.toml
---
success: false
exit_code: 1
----- stdout -----
----- stderr -----
-No previous branch found in reflog. Use 'wt list' to see available worktrees.
+❌ No previous branch found in reflog. Use 'wt list' to see available worktrees.