Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: only suggest `wt switch ^` when resolvable after CWD removal (#1238)
Maximilian Roos550009775c93
diff --git a/src/git/mod.rs b/src/git/mod.rsindex d63953486..101224219 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -54,7 +54,7 @@ pub use error::{exit_code,};pub use parse::{parse_porcelain_z, parse_untracked_files};-pub use recover::current_or_recover;+pub use recover::{current_or_recover, cwd_removed_hint};pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree, set_base_path};pub use url::GitRemoteUrl;pub use url::{parse_owner_repo, parse_remote_owner};diff --git a/src/git/recover.rs b/src/git/recover.rsindex 0018cb499..420c11811 100644--- a/src/git/recover.rs+++ b/src/git/recover.rs@@ -7,6 +7,8 @@use std::path::{Path, PathBuf};+use color_print::cformat;+use crate::styling::eprintln;use super::Repository;@@ -33,6 +35,32 @@ pub fn current_or_recover() -> anyhow::Result<(Repository, bool)> {}}+/// Determine the hint to show when the user's CWD has been removed.+///+/// Tries to find the parent repository and checks if `wt switch ^` would work+/// (i.e., the default branch has an existing worktree). Falls back to+/// progressively less specific hints when recovery or resolution fails.+pub fn cwd_removed_hint() -> String {+ let Some(repo) = Repository::current().ok().or_else(recover_from_deleted_cwd) else {+ return "Current directory was removed.".to_string();+ };+ hint_for_repo(&repo)+}++fn hint_for_repo(repo: &Repository) -> String {+ if let Some(branch) = repo.default_branch()+ && repo+ .worktree_for_branch(&branch)+ .ok()+ .flatten()+ .is_some_and(|p| p.exists())+ {+ return cformat!("Current directory was removed. Try: <bright-black>wt switch ^</>");+ }++ cformat!("Current directory was removed. Run <bright-black>wt list</> to see worktrees.")+}+/// Attempt to recover a repository when the current directory has been deleted.////// Returns `Some(Repository)` if:@@ -117,8 +145,8 @@ fn find_validated_repo_near(dir: &Path, deleted_path: &Path) -> Option<Repositor/// and `Repository::at()` succeeds.////// Note: This only matches `.git` directories, so bare repos (which have no-/// `.git` subdirectory) won't be discovered. The fallback hint in `main.rs`-/// covers this gracefully.+/// `.git` subdirectory) won't be discovered. `cwd_removed_hint()` handles+/// this gracefully by falling back to progressively less specific hints.fn try_repo_at(dir: &Path) -> Option<Repository> {let git_path = dir.join(".git");// Only match .git directories (main repos), not .git files (linked worktrees)@@ -179,6 +207,7 @@ fn paths_match(worktree_path: &Path, deleted_path: &Path) -> bool {mod tests {use super::*;use crate::shell_exec::Cmd;+ use ansi_str::AnsiStr;fn git_init(path: &Path) {Cmd::new("git")@@ -465,4 +494,34 @@ mod tests {let deep_path = wt_path.join("src").join("lib.rs");assert!(recover_from_path(&deep_path).is_some());}++ #[test]+ fn test_hint_for_repo_suggests_switch() {+ // A normal repo with a main worktree should suggest `wt switch ^`.+ let tmp = tempfile::tempdir().unwrap();+ git_init(tmp.path());+ Cmd::new("git")+ .args(["commit", "--allow-empty", "-m", "init"])+ .current_dir(tmp.path())+ .run()+ .unwrap();+ let repo = Repository::at(tmp.path()).unwrap();+ let hint = hint_for_repo(&repo);+ insta::assert_snapshot!(hint.ansi_strip(), @"Current directory was removed. Try: wt switch ^");+ }++ #[test]+ fn test_hint_for_repo_fallback_to_list() {+ // A bare repo with no worktrees has no default branch worktree,+ // so it should suggest `wt list` instead of `wt switch ^`.+ let tmp = tempfile::tempdir().unwrap();+ Cmd::new("git")+ .args(["init", "--bare", "--quiet"])+ .current_dir(tmp.path())+ .run()+ .unwrap();+ let repo = Repository::at(tmp.path()).unwrap();+ let hint = hint_for_repo(&repo);+ insta::assert_snapshot!(hint.ansi_strip(), @"Current directory was removed. Run wt list to see worktrees.");+ }}diff --git a/src/main.rs b/src/main.rsindex b01f591d7..3b4688ffd 100644--- a/src/main.rs+++ b/src/main.rs@@ -7,7 +7,9 @@ use clap::error::ErrorKind as ClapErrorKind;use color_print::{ceprintln, cformat};use std::process;use worktrunk::config::{UserConfig, set_config_path};-use worktrunk::git::{Repository, ResolvedWorktree, current_or_recover, exit_code, set_base_path};+use worktrunk::git::{+ Repository, ResolvedWorktree, current_or_recover, cwd_removed_hint, exit_code, set_base_path,+};use worktrunk::path::format_path_for_display;use worktrunk::shell::extract_filename_from_path;use worktrunk::styling::{@@ -1066,16 +1068,13 @@ fn main() {}}- // If the CWD has been deleted, hint the user to use `wt switch ^`.+ // If the CWD has been deleted, hint the user about recovery options.// Check both: (1) explicit flag set by merge/remove when it knows the CWD// worktree was removed (reliable on all platforms), and (2) OS-level detection// for cases not covered by the flag (e.g., external worktree removal).let cwd_gone = output::was_cwd_removed() || std::env::current_dir().is_err();if cwd_gone {- eprintln!(- "{}",- hint_message("Current directory was removed. Try: wt switch ^")- );+ eprintln!("{}", hint_message(cwd_removed_hint()));}// Preserve exit code from child processes (especially for signals like SIGINT)diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 09d4375dc..087a68366 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -715,13 +715,63 @@ fn test_merge_post_merge_command_failure(mut repo: TestRepo) {let feature_wt = repo.add_feature();- // Merge with --yes - post-merge command should fail but merge should complete- assert_cmd_snapshot!(make_snapshot_cmd(- &repo,- "merge",- &["main", "--yes"],- Some(&feature_wt)- ));+ // Merge with --yes - post-merge command should fail but merge should complete.+ // Set PWD to repo root so CWD recovery consistently finds the test repo+ // (without this, $PWD is inherited from the test runner and recovery may+ // find a different repo in CI).+ let mut cmd = make_snapshot_cmd(&repo, "merge", &["main", "--yes"], Some(&feature_wt));+ cmd.env("PWD", repo.root_path());+ assert_cmd_snapshot!(cmd);+}++/// When the CWD is removed but the default branch can't be resolved,+/// the hint should suggest `wt list` instead of `wt switch ^`.+#[rstest]+fn test_merge_cwd_removed_hint_fallback_to_list(mut repo: TestRepo) {+ // Create project config with failing post-merge command+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).unwrap();+ fs::write(config_dir.join("wt.toml"), r#"post-merge = "exit 1""#).unwrap();++ repo.commit("Add config");++ // Set default branch to a nonexistent branch so `wt switch ^` won't resolve+ repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);++ let feature_wt = repo.add_feature();++ // Set PWD to repo root so recovery finds the test repo after CWD deletion.+ // (Without this, $PWD is inherited from the test runner and recovery finds+ // the dev repo instead.)+ let mut cmd = make_snapshot_cmd(&repo, "merge", &["main", "--yes"], Some(&feature_wt));+ cmd.env("PWD", repo.root_path());+ assert_cmd_snapshot!(cmd);+}++/// When the CWD is removed and recovery can't find any repo,+/// the hint should show just the message with no command suggestion.+///+/// Windows-only skip: on Windows, `current_dir()` succeeds even after+/// directory deletion (process handle keeps it alive), so `Repository::current()`+/// works and the hint correctly suggests `wt switch ^` instead.+#[cfg(not(target_os = "windows"))]+#[rstest]+fn test_merge_cwd_removed_hint_no_recovery(mut repo: TestRepo) {+ // Create project config with failing post-merge command+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).unwrap();+ fs::write(config_dir.join("wt.toml"), r#"post-merge = "exit 1""#).unwrap();++ repo.commit("Add config");++ let feature_wt = repo.add_feature();++ // Set PWD to the feature worktree. After merge removes it, recovery walks up+ // from the deleted path but can't associate it with the repo (worktree was+ // properly cleaned up), so recovery fails.+ let mut cmd = make_snapshot_cmd(&repo, "merge", &["main", "--yes"], Some(&feature_wt));+ cmd.env("PWD", &feature_wt);+ assert_cmd_snapshot!(cmd);}#[rstest]diff --git a/tests/snapshots/integration__integration_tests__merge__merge_cwd_removed_hint_fallback_to_list.snap b/tests/snapshots/integration__integration_tests__merge__merge_cwd_removed_hint_fallback_to_list.snapnew file mode 100644index 000000000..d562ccded--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_cwd_removed_hint_fallback_to_list.snap@@ -0,0 +1,57 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ PWD: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp4hdWnb/repo+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mMerging 1 commit to [1mmain[22m @ [2m[HASH][22m (no commit/squash/rebase needed)[39m+[107m [0m * [33m[HASH][m Add feature file+[107m [0m feature.txt | 1 [32m+[m+[107m [0m 1 file changed, 1 insertion(+)+[32m✓[39m [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39m+[36m◎ Removing [1mfeature[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m+[36m◎[39m [36mRunning post-merge project hook @ [1m_REPO_[22m[39m+[107m [0m [2m[0m[2m[34mexit[0m[2m 1+[0m[31m✗[39m [31mCommand failed: exit status: 1[39m+[2m↳[22m [2mCurrent directory was removed. Run [90mwt list[39m to see worktrees.[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_cwd_removed_hint_no_recovery.snap b/tests/snapshots/integration__integration_tests__merge__merge_cwd_removed_hint_no_recovery.snapnew file mode 100644index 000000000..4ac3a00ab--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_cwd_removed_hint_no_recovery.snap@@ -0,0 +1,57 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ PWD: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpbWAT4p/repo.feature+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mMerging 1 commit to [1mmain[22m @ [2m[HASH][22m (no commit/squash/rebase needed)[39m+[107m [0m * [33m[HASH][m Add feature file+[107m [0m feature.txt | 1 [32m+[m+[107m [0m 1 file changed, 1 insertion(+)+[32m✓[39m [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39m+[36m◎ Removing [1mfeature[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m+[36m◎[39m [36mRunning post-merge project hook @ [1m_REPO_[22m[39m+[107m [0m [2m[0m[2m[34mexit[0m[2m 1+[0m[31m✗[39m [31mCommand failed: exit status: 1[39m+[2m↳[22m [2mCurrent directory was removed.[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snapindex 20e7a2a9e..d3f66f386 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap@@ -53,4 +53,4 @@ exit_code: 1[36m◎[39m [36mRunning post-merge project hook @ [1m_REPO_[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m[31m✗[39m [31mCommand failed: exit status: 1[39m-[2m↳[22m [2mCurrent directory was removed. Try: wt switch ^[22m+[2m↳[22m [2mCurrent directory was removed. Try: [90mwt switch ^[39m[22m