Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(switch): refuse --path naming the bare repository; drop rm -rf hint for --path (#4532)
Maximilian Roos1fe07b3145f2
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex dd962c986..541399eb7 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -22,7 +22,7 @@ use worktrunk::git::{ErrorExt, ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,SwitchSuggestionCtx, WorktreeId, branch_tracks_ref, current_or_recover, resolve_input_path,};-use worktrunk::path::format_path_for_display;+use worktrunk::path::{canonicalize_with_parents, format_path_for_display};use worktrunk::shell_exec::{ShellEscapeMode, shell_cwd};use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, println, progress_message,@@ -787,6 +787,7 @@ fn validate_worktree_creation(path: &Path,clobber: bool,method: &CreationMethod,+ from_path_flag: bool,) -> anyhow::Result<bool> {// For regular switches without --create, validate branch existsif let CreationMethod::Regular {@@ -846,6 +847,7 @@ fn validate_worktree_creation(branch: branch.to_string(),path: path.to_path_buf(),create: is_create,+ from_path_flag,}.into())}@@ -1028,6 +1030,7 @@ fn plan_switch(};// Phase 3: Compute expected path. `--path` replaces the template outright.+ let from_path_flag = requested_path.is_some();let expected_path = match requested_path {Some(path) => {reject_path_overlapping_worktrees(repo, &path)?;@@ -1037,8 +1040,14 @@ fn plan_switch(};// Phase 4: Validate we can create at this path- let needs_clobber_backup =- validate_worktree_creation(repo, &branch, &expected_path, clobber, &method)?;+ let needs_clobber_backup = validate_worktree_creation(+ repo,+ &branch,+ &expected_path,+ clobber,+ &method,+ from_path_flag,+ )?;// Phase 5: Return the planOk(SwitchPlan::Create {@@ -1051,8 +1060,8 @@ fn plan_switch(})}-/// Refuse a `--path` directory that holds a worktree or the repository, or-/// that sits inside one.+/// Refuse a `--path` directory that holds a worktree or the repository, that+/// sits inside one, or that is its git directory.////// Such a directory always exists, so `validate_worktree_creation` would/// otherwise offer `--clobber`, which moves it aside: `--path ..` would move@@ -1061,14 +1070,29 @@ fn plan_switch(/// directory that does not exist yet is left alone — nesting a new worktree/// inside another is git's call, not a clobber.fn reject_path_overlapping_worktrees(repo: &Repository, requested: &Path) -> anyhow::Result<()> {- let Ok(requested) = canonicalize(requested) else {+ if !requested.exists() {return Ok(());- };- let registered = repo.list_worktrees()?.iter().map(|wt| wt.path.as_path());- for existing in registered.chain([repo.git_common_dir()]) {- let existing = canonicalize(existing).unwrap_or_else(|_| existing.to_path_buf());+ }+ // The comparison form: `dunce` keeps `\\?\` on a deep Windows path and+ // drops it from a short root, which `starts_with` reads as unrelated.+ let requested = canonicalize_with_parents(requested);+ let registered = repo+ .list_worktrees()?+ .iter()+ .map(|wt| (wt.path.as_path(), true));+ for (existing, is_worktree) in registered.chain([(repo.git_common_dir(), false)]) {+ let existing = canonicalize_with_parents(existing);if existing == requested {- continue;+ // A worktree at exactly this path is `validate_worktree_creation`'s+ // to report, naming its branch. The git directory has no such+ // check; in a bare repository it is the repository itself.+ if is_worktree {+ continue;+ }+ let requested = format_path_for_display(&requested);+ bail!(cformat!(+ "<bold>--path {requested}</> is the repository's git directory; choose a directory outside the repository and its worktrees"+ ));}let relation = if existing.starts_with(&requested) {"contains"diff --git a/src/git/error.rs b/src/git/error.rsindex 1e7f58975..18bd939bc 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -546,6 +546,10 @@ pub enum GitError {branch: String,path: PathBuf,create: bool,+ /// The path came from `--path`, so it can name any directory, such as+ /// a project of its own, rather than the template's worktree location.+ /// The hint then suggests another path instead of deleting this one.+ from_path_flag: bool,},WorktreeCreationFailed {branch: String,@@ -1321,9 +1325,9 @@ impl GitError {branch,path,create,+ from_path_flag,} => {let title = self.title();- let path_display = format_path_for_display(path);let flags: &[&str] = if *create {&["--create", "--clobber"]} else {@@ -1333,12 +1337,20 @@ impl GitError {if let Some(ctx) = ctx {switch_cmd = ctx.apply(switch_cmd);}+ let alternative = if *from_path_flag {+ cformat!(+ "To place the worktree elsewhere, choose a different <underline>--path</>"+ )+ } else {+ let path_display = format_path_for_display(path);+ cformat!("To remove manually, run <underline>rm -rf {path_display}</>")+ };write!(f,"{}\n{}",error_message(&title),hint_message(cformat!(- "To remove manually, run <underline>rm -rf {path_display}</>; to overwrite (with backup), run <underline>{switch_cmd}</>"+ "{alternative}; to overwrite (with backup), run <underline>{switch_cmd}</>")))}@@ -2255,6 +2267,7 @@ mod tests {branch: "feature".to_string(),path: PathBuf::from("/some/path"),create: true,+ from_path_flag: false,};assert_snapshot!(err.render(), @"[31m✗[39m [31mDirectory already exists: [1m/some/path[22m[39m@@ -3043,6 +3056,7 @@ mod tests {branch: "emails".into(),path: PathBuf::from("/tmp/repo.emails"),create: true,+ from_path_flag: false,}),ctx: SwitchSuggestionCtx {extra_flags: vec!["--execute=claude".into()],diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex 7876bbbdf..3c557330d 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -90,6 +90,40 @@ fn test_bare_repo_list_no_worktrees() {});}+/// `--path` naming the bare repository itself is refused, even with+/// `--clobber`, which would otherwise move the repository aside and strand+/// every worktree's gitfile on the backup.+#[test]+fn test_bare_repo_switch_path_rejects_the_repository() {+ let test = bare_repo_without_worktrees();+ let bare = test.bare_repo_path();++ let settings = setup_temp_snapshot_settings(test.temp_path());+ settings.bind(|| {+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ cmd.args([+ "switch",+ "--create",+ "feature-b",+ "--clobber",+ "--path",+ ".",+ ])+ .current_dir(bare);++ assert_cmd_snapshot!(cmd);+ });++ assert!(bare.join("HEAD").is_file());+ let siblings: Vec<_> = fs::read_dir(bare.parent().unwrap())+ .unwrap()+ .map(|entry| entry.unwrap().file_name())+ .filter(|name| name.to_string_lossy().contains(".bak."))+ .collect();+ assert!(siblings.is_empty(), "unexpected backup: {siblings:?}");+}+/// `--format json` owes its consumer a payload in the same state: the schema-2/// envelope with `items: []`, not an empty stdout that no parser accepts.#[test]diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex 4b5729c60..a09c584d7 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -244,6 +244,7 @@ fn worktree_errors_render() {branch: "feature".into(),path: PathBuf::from("/tmp/repo.feature"),create: false,+ from_path_flag: false,}.render(),),diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 9a136ae61..5ed8cd860 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -9011,8 +9011,9 @@ fn test_switch_path_occupied_suggests_path_in_clobber_hint(repo: TestRepo) {let custom = repo.root_path().parent().unwrap().join("occupied");std::fs::create_dir_all(&custom).unwrap();- // The `--clobber` suggestion must keep `--path`, or following it would- // back up the template's path instead of this one.+ // `--path` can name any directory, so the hint suggests another path+ // rather than deleting this one. The `--clobber` suggestion must keep+ // `--path`, or following it would back up the template's path instead.snapshot_switch("switch_path_occupied",&repo,@@ -9020,6 +9021,27 @@ fn test_switch_path_occupied_suggests_path_in_clobber_hint(repo: TestRepo) {);}+#[rstest]+fn test_switch_path_naming_another_worktree(mut repo: TestRepo) {+ let occupied = repo.add_worktree("feature-z");++ // Another branch's worktree is reported by its branch, never moved aside+ // by `--clobber`.+ snapshot_switch(+ "switch_path_another_worktree",+ &repo,+ &[+ "--create",+ "feature-n",+ "--clobber",+ "--path",+ "../repo.feature-z",+ ],+ );++ assert!(occupied.join(".git").is_file());+}+#[rstest]fn test_switch_path_rejects_directory_overlapping_repo(repo: TestRepo) {std::fs::create_dir_all(repo.root_path().join("src")).unwrap();diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_switch_path_rejects_the_repository.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_switch_path_rejects_the_repository.snapnew file mode 100644index 000000000..49ab2bda6--- /dev/null+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_switch_path_rejects_the_repository.snap@@ -0,0 +1,57 @@+---+source: tests/integration_tests/bare_repository.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature-b+ - "--clobber"+ - "--path"+ - "."+ env:+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ TERM: alacritty+ 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_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+✗ --path [TEMP]/repo is the repository's git directory; choose a directory outside the repository and its worktreesdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_path_another_worktree.snap b/tests/snapshots/integration__integration_tests__switch__switch_path_another_worktree.snapnew file mode 100644index 000000000..75935c9c9--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_path_another_worktree.snap@@ -0,0 +1,67 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature-n+ - "--clobber"+ - "--path"+ - "../repo.feature-z"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ 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_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ 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_PROBE_TIMEOUT_MS: "60000"+ 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 switch to [1mfeature-n[22m — there's a worktree at the expected path [1m_REPO_.feature-z[22m on branch [1mfeature-z[22m[39m+[2m↳[22m [2mTo switch the worktree at [4m_REPO_.feature-z[24m to [4mfeature-n[24m, run [4mcd _REPO_.feature-z && git switch feature-n[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_path_occupied.snap b/tests/snapshots/integration__integration_tests__switch__switch_path_occupied.snapindex ad248e810..9720a9a97 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_path_occupied.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_path_occupied.snap@@ -63,4 +63,4 @@ exit_code: 1----- stderr -----[31m✗[39m [31mDirectory already exists: [1m_PARENT_/occupied[22m[39m-[2m↳[22m [2mTo remove manually, run [4mrm -rf _PARENT_/occupied[24m; to overwrite (with backup), run [4mwt switch --create --clobber feature-y --path=../occupied[24m[22m+[2m↳[22m [2mTo place the worktree elsewhere, choose a different [4m--path[24m; to overwrite (with backup), run [4mwt switch --create --clobber feature-y --path=../occupied[24m[22m