Skip to content

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

fix: don't cd into a directory removed before wt exits (#4602)

Maximilian Roos8ee0a701763d
diff --git a/src/main.rs b/src/main.rs
index 2dfe7e8ac..1c5b97c55 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1103,6 +1103,7 @@ fn print_cwd_removed_hint_if_needed() {
fn finish_command(verbose_level: u8, command_line: &str, error: Option<&anyhow::Error>) {
let error_text = error.map(|err| err.to_string());
diagnostic::write_if_verbose(verbose_level, command_line, error_text.as_deref());
+ output::withdraw_missing_cd_target();
let _ = output::terminate_output();
}
diff --git a/src/output/global.rs b/src/output/global.rs
index 8db35d931..c9f2a7a5f 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -8,7 +8,10 @@
//!
//! `WORKTRUNK_DIRECTIVE_CD_FILE` holds one raw path. The wrapper changes to it
//! after wt exits. `--execute` needs no directive: wt starts the external
-//! program directly with its working directory set to the switch target. The
+//! program directly with its working directory set to the switch target.
+//! Because that program can remove the target before wt exits (a session that
+//! ends by removing its own worktree), wt withdraws a target that no longer
+//! exists as it finishes, leaving the shell where it started. The
//! retired exec-file variable is recognized only to warn when an old wrapper
//! redirects `--execute` output away from the terminal.
//!
@@ -305,6 +308,34 @@ pub fn change_directory(path: impl AsRef<Path>) -> anyhow::Result<()> {
}
}
+/// Withdraw a directory change whose target no longer exists.
+///
+/// Called as wt finishes, after everything it runs in the foreground: an
+/// `--execute` program that removes the worktree it
+/// started in, or a hook or alias whose nested wt switches somewhere a later
+/// step removes. Emptying the file keeps the wrapper from `cd`-ing into a
+/// missing directory, so the shell stays where it was. Best-effort: if the
+/// file can't be read or emptied, the wrapper's own `cd` error names the
+/// directory.
+pub fn withdraw_missing_cd_target() {
+ let mode = state()
+ .lock()
+ .expect("OUTPUT_STATE lock poisoned")
+ .mode
+ .clone();
+ let DirectiveMode::ShellIntegration { cd_file } = mode else {
+ return;
+ };
+ let Ok(target) = std::fs::read_to_string(&cd_file) else {
+ return;
+ };
+ // Strip only the line terminator: a directory name can end in spaces.
+ let target = target.trim_end_matches(['\n', '\r']);
+ if !target.is_empty() && !Path::new(target).is_dir() {
+ let _ = std::fs::File::create(&cd_file);
+ }
+}
+
/// Mark that the current working directory's worktree has been removed.
///
/// Called by the removal handler (e.g., during `wt merge`) when it knows the
diff --git a/src/output/mod.rs b/src/output/mod.rs
index f065a383d..816e6570a 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -42,7 +42,7 @@ pub(crate) use global::{
change_directory, execute, is_shell_integration_active, mark_cwd_removed,
post_hook_display_path, pre_hook_display_path, print_outdated_shell_wrapper_hint_once,
retired_shell_wrapper_active, set_verbosity, terminate_output, to_logical_path,
- was_cwd_removed,
+ was_cwd_removed, withdraw_missing_cd_target,
};
// Re-export output handlers
pub(crate) use handlers::{
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index c84a23b08..4245dacac 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -1132,6 +1132,55 @@ fn test_switch_no_cd_execute_runs_in_worktree(mut repo: TestRepo) {
);
}
+/// An `--execute` program can remove the worktree it started in, as a session
+/// does when it ends by removing its own worktree. The shell wrapper would then
+/// `cd` into a directory that no longer exists, so wt withdraws the directive
+/// and the shell stays where it was.
+///
+/// Unix only: Windows refuses to delete a directory that a running process
+/// holds as its cwd, so there the program can't remove the worktree it runs in.
+#[cfg(unix)]
+#[rstest]
+fn test_switch_execute_that_removes_worktree_withdraws_cd(mut repo: TestRepo) {
+ let worktree = repo.add_worktree("feature");
+ let root = repo.root_path().to_string_lossy().to_string();
+ let worktree_arg = worktree.to_string_lossy().to_string();
+
+ let (cd_path, _guard) = directive_file();
+ let mut cmd = repo.wt_command();
+ configure_directive_file(&mut cmd, &cd_path);
+ cmd.current_dir(repo.root_path()).args([
+ "switch",
+ "feature",
+ "--execute",
+ "git",
+ "--",
+ "-C",
+ &root,
+ "worktree",
+ "remove",
+ "--force",
+ &worktree_arg,
+ ]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "switch --execute failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ !worktree.exists(),
+ "the --execute program should remove the worktree"
+ );
+ assert_eq!(
+ fs::read_to_string(&cd_path).unwrap(),
+ "",
+ "wt left a cd directive to the removed worktree"
+ );
+}
+
/// A switch from a subdirectory keeps the user's position, so the `--execute`
/// program starts in `<worktree>/<subdir>` — not at the worktree root the
/// background hooks run in. The header names the program's own directory
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index b688afbd6..25b993ee0 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -23,12 +23,14 @@ use worktrunk::config::HookSource;
#[rstest]
#[cfg(unix)]
fn test_concurrent_hooks_log_labels_and_pass_cd_directive(repo: TestRepo) {
- repo.write_project_config(
+ // The directive names a directory that exists, or wt withdraws it on exit.
+ let target = repo.home_path().to_string_lossy().to_string();
+ repo.write_project_config(&format!(
r#"[pre-start]
-first = 'printf CD > "$WORKTRUNK_DIRECTIVE_CD_FILE"'
+first = "printf %s '{target}' > \"$WORKTRUNK_DIRECTIVE_CD_FILE\""
second = 'true'
"#,
- );
+ ));
let cd_file = repo.home_path().join("cd-directive");
let output = repo
.wt_command()
@@ -37,7 +39,7 @@ second = 'true'
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
- assert_eq!(fs::read_to_string(cd_file).unwrap(), "CD");
+ assert_eq!(fs::read_to_string(cd_file).unwrap(), target);
let log = fs::read_to_string(repo.root_path().join(".git/wt/logs/commands.jsonl")).unwrap();
let mut labels: Vec<String> = log
.lines()
@@ -5018,6 +5020,73 @@ setup = "'{wt_toml}' switch --create hook-created --no-hooks"
);
}
+/// A nested wt's directive outlives its target when a later step removes the
+/// worktree it switched to. The outer wt withdraws it on exit, so the shell
+/// wrapper doesn't `cd` into a missing directory.
+#[rstest]
+fn test_directive_to_worktree_removed_by_later_step_is_withdrawn(repo: TestRepo) {
+ use crate::common::{configure_directive_file, directive_file, wt_bin};
+
+ repo.commit("initial");
+ let created = repo.root_path().parent().unwrap().join("repo.hook-created");
+
+ let wt_toml = wt_bin().to_string_lossy().replace('\\', r"\\");
+ let created_toml = created.to_string_lossy().replace('\\', r"\\");
+ repo.write_test_config(&format!(
+ r#"
+[pre-start]
+setup = "'{wt_toml}' switch --create hook-created --no-hooks && git worktree remove --force '{created_toml}'"
+"#,
+ ));
+
+ let (cd_path, _guard) = directive_file();
+ let mut cmd = repo.wt_command();
+ configure_directive_file(&mut cmd, &cd_path);
+ cmd.args(["hook", "pre-start", "setup"]);
+ let output = cmd.output().unwrap();
+
+ assert!(
+ output.status.success(),
+ "hook failed: stdout={}\nstderr={}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+ assert!(
+ !created.exists(),
+ "the hook should remove the worktree it created"
+ );
+ assert_eq!(
+ fs::read_to_string(&cd_path).unwrap(),
+ "",
+ "wt left a cd directive to the removed worktree"
+ );
+}
+
+/// A directive to a directory whose name ends in a space names a directory
+/// that exists, so wt keeps it. Unix only: Windows drops trailing spaces from
+/// directory names.
+#[cfg(unix)]
+#[rstest]
+fn test_directive_to_directory_ending_in_space_is_kept(repo: TestRepo) {
+ let target = repo.home_path().join("dir ");
+ fs::create_dir(&target).unwrap();
+ let target = target.to_string_lossy().to_string();
+ repo.write_project_config(&format!(
+ r#"[pre-start]
+cd = '''printf '%s\n' '{target}' > "$WORKTRUNK_DIRECTIVE_CD_FILE"'''
+"#,
+ ));
+ let cd_file = repo.home_path().join("cd-directive");
+ let output = repo
+ .wt_command()
+ .args(["hook", "pre-start", "--yes"])
+ .env("WORKTRUNK_DIRECTIVE_CD_FILE", &cd_file)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+ assert_eq!(fs::read_to_string(cd_file).unwrap(), format!("{target}\n"));
+}
+
// ============================================================================
// Pre-* Pipeline Concurrent Execution Tests
// ============================================================================