Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: clear error when new branch name collides with existing branch namespace (#3528)
Worktrunk Bot56249f912206
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 577011469..b2e4688ae 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1031,6 +1031,21 @@ fn execute_switch(Repository::SLOW_OPERATION_DELAY_MS,progress_msg,) {+ // A new branch whose name is a path prefix of (or sits+ // under) an existing branch can't be created: git stores+ // refs as file paths, so `release` and `release/2026.4`+ // can't coexist. Surface that as a clear, actionable+ // error instead of git's raw "cannot lock ref" text.+ if *create_branch+ && let Some(conflicting) =+ detect_branch_namespace_conflict(repo, &branch)+ {+ return Err(GitError::BranchNamespaceConflict {+ branch: branch.clone(),+ conflicting,+ }+ .into());+ }return Err(worktree_creation_error(&e,branch.clone(),@@ -1209,6 +1224,28 @@ fn execute_switch(}}+/// Detect a git ref directory/file (D/F) conflict for a branch about to be+/// created, returning an existing branch it collides with.+///+/// Git stores refs as file paths under `refs/heads/`, so a branch name can't+/// be both a file and a directory: creating `release` fails when+/// `release/2026.4` exists, and creating `release/foo` fails when `release`+/// exists. This inspects the cached local-branch inventory (no extra+/// subprocess) for either shape and returns the first colliding branch.+fn detect_branch_namespace_conflict(repo: &Repository, branch: &str) -> Option<String> {+ let prefix = format!("{branch}/");+ repo.local_branches()+ .ok()?+ .iter()+ .map(|b| b.name.as_str())+ .find(|name| {+ // `branch` is a directory prefix of an existing branch, or an+ // existing branch is a directory prefix of `branch`.+ name.starts_with(&prefix) || branch.starts_with(&format!("{name}/"))+ })+ .map(String::from)+}+/// Build a `GitError::WorktreeCreationFailed` from a failed `git worktree add`,/// extracting the underlying command output for the error message.fn worktree_creation_error(diff --git a/src/git/error.rs b/src/git/error.rsindex 3ef7cdc0e..258933a7c 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -463,6 +463,16 @@ pub enum GitError {/// The git command that failed, shown separately from git outputcommand: Option<FailedCommand>,},+ /// A new branch can't be created because its name collides with the+ /// directory namespace of an existing branch. Git stores refs as file+ /// paths, so `release` and `release/2026.4` can't both exist — one would+ /// have to be a file and a directory at the same path.+ BranchNamespaceConflict {+ /// The branch the user tried to create.+ branch: String,+ /// An existing branch whose name collides with `branch`.+ conflicting: String,+ },WorktreeRemovalFailed {branch: String,path: PathBuf,@@ -668,6 +678,13 @@ impl GitError {None => cformat!("Failed to create worktree for <bold>{branch}</>"),},+ GitError::BranchNamespaceConflict {+ branch,+ conflicting,+ } => cformat!(+ "Cannot create branch <bold>{branch}</> — it collides with existing branch <bold>{conflicting}</>"+ ),+GitError::WorktreeRemovalFailed { branch, path, .. } => {let path_display = format_path_for_display(path);cformat!(@@ -1008,6 +1025,21 @@ impl GitError {Ok(())}+ GitError::BranchNamespaceConflict {+ branch,+ conflicting,+ } => {+ let title = self.title();+ write!(+ f,+ "{}\n{}",+ error_message(&title),+ hint_message(cformat!(+ "Git stores branches as file paths, so <underline>{branch}</> and <underline>{conflicting}</> can't both exist. Pick a different name, or rename the existing branch."+ ))+ )+ }+GitError::WorktreeRemovalFailed {error,remaining_entries,diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex aad7deade..8f680b1e2 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -130,6 +130,23 @@ fn test_switch_create_existing_branch_error(mut repo: TestRepo) {);}+/// Creating a branch whose name is a path prefix of an existing branch is a git+/// ref directory/file conflict: `release` can't be created while `release/2026.4`+/// exists. Regression for #3527 — surface a clear namespace-collision error+/// instead of git's raw "cannot lock ref" text.+#[rstest]+fn test_switch_create_branch_namespace_conflict(repo: TestRepo) {+ // An existing branch living under the `release/` namespace.+ repo.run_git(&["branch", "release/2026.4"]);++ // `release` can't be both a branch and a directory of branches.+ snapshot_switch(+ "switch_create_namespace_conflict",+ &repo,+ &["--create", "release"],+ );+}+/// When --execute is passed and the branch already exists, the error hint should/// include --execute and trailing args in the suggested command.#[rstest]diff --git a/tests/snapshots/integration__integration_tests__switch__switch_create_namespace_conflict.snap b/tests/snapshots/integration__integration_tests__switch__switch_create_namespace_conflict.snapnew file mode 100644index 000000000..5c0badbc5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_create_namespace_conflict.snap@@ -0,0 +1,53 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - release+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ 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_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot create branch [1mrelease[22m — it collides with existing branch [1mrelease/2026.4[22m[39m+[2m↳[22m [2mGit stores branches as file paths, so [4mrelease[24m and [4mrelease/2026.4[24m can't both exist. Pick a different name, or rename the existing branch.[22m