Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(remove): derive the trash directory in `wt _drain-trash` instead of taking it as an argument (#4536)
Maximilian Roosd6cb21a2416c
diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 87d905e3d..1b7867933 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -2725,9 +2725,9 @@ Hooks, aliases and `step.copy-ignored.exclude` accumulate rather than replace, sforce_delete: bool,},- /// Delete the worktrees staged in a trash directory.+ /// Delete the worktrees staged in this repository's trash directory.#[command(name = "_drain-trash", hide = true)]- InternalDrainTrash { trash_dir: std::path::PathBuf },+ InternalDrainTrash,/// Run a custom `wt-<name>` command found on PATH.///diff --git a/src/commands/process.rs b/src/commands/process.rsindex 84dafdd10..1de4d7080 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -280,6 +280,7 @@ fn spawn_detached_exec_unix(.stderr(Stdio::from(log_file)).process_group(0);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);+ worktrunk::shell_exec::scrub_git_discovery_env_vars(&mut cmd);set_background_hook_env(&mut cmd, is_background_hook);worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;@@ -315,6 +316,7 @@ fn spawn_detached_exec_windows(.stderr(Stdio::from(log_file)).creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);+ worktrunk::shell_exec::scrub_git_discovery_env_vars(&mut cmd);set_background_hook_env(&mut cmd, is_background_hook);worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;@@ -384,7 +386,7 @@ pub fn sweep_trash(repo: &Repository) {spawn_detached(repo,&repo.wt_dir(),- &build_drain_trash_command(executable, &trash_dir),+ &build_drain_trash_command(executable, repo),"",&HookLog::Shared(InternalOp::TrashSweep),)@@ -394,15 +396,20 @@ pub fn sweep_trash(repo: &Repository) {}}-/// Shell argv that runs `wt _drain-trash <trash_dir>`: a fixed script, its-/// `$0`, then native arguments. Paths are never interpolated into shell source.-pub fn build_drain_trash_command(executable: PathBuf, trash_dir: &Path) -> Vec<OsString> {+/// Shell argv that runs `wt -C <git-common-dir> _drain-trash`: a fixed script,+/// its `$0`, then native arguments. Paths are never interpolated into shell+/// source. The drain derives the trash directory from the repository it+/// discovers, so it can't be pointed at a directory outside a trash. `-C`+/// names that repository because the spawn's cwd may be the placeholder of a+/// worktree the removal just deleted.+pub fn build_drain_trash_command(executable: PathBuf, repo: &Repository) -> Vec<OsString> {vec![OsString::from(r#"exec "$@""#),OsString::from("wt"),executable.into_os_string(),+ OsString::from("-C"),+ repo.git_common_dir().as_os_str().to_os_string(),OsString::from("_drain-trash"),- trash_dir.as_os_str().to_os_string(),]}@@ -502,12 +509,16 @@ mod tests {}#[test]- fn drain_command_passes_trash_dir_as_its_own_argument() {- let trash_dir = Path::new("/repo/with space-'$(echo PWNED)\n/.git/wt/trash");- let args = build_drain_trash_command(PathBuf::from("/bin/wt"), trash_dir);+ fn drain_command_passes_paths_as_their_own_arguments() {+ let test = worktrunk::testing::TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();+ let executable = PathBuf::from("/opt/with space-'$(echo PWNED)\n/wt");+ let args = build_drain_trash_command(executable.clone(), &repo);assert_eq!(args[0], r#"exec "$@""#);- assert_eq!(args[3], "_drain-trash");- assert_eq!(args[4], trash_dir.as_os_str());+ assert_eq!(args[2], executable.as_os_str());+ assert_eq!(args[3], "-C");+ assert_eq!(args[4], repo.git_common_dir().as_os_str());+ assert_eq!(args[5], "_drain-trash");}#[test]diff --git a/src/main.rs b/src/main.rsindex 3d57df0d4..4adf8c748 100644--- a/src/main.rs+++ b/src/main.rs@@ -971,7 +971,9 @@ fn dispatch_command(expected_tip.as_deref(),force_delete,),- Commands::InternalDrainTrash { trash_dir } => worktrunk::git::drain_trash(&trash_dir),+ Commands::InternalDrainTrash => {+ worktrunk::git::drain_trash(&Repository::current()?.wt_trash_dir())+ }// `working_dir` is the top-level `-C <path>` flag, applied as the// child's current directory so global `-C` works for custom// subcommands the same way it does for built-ins.diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 37456f3e6..d61794ab6 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -236,7 +236,7 @@ fn execute_instant_removal_or_fallback(.context("Failed to locate Worktrunk executable").and_then(|executable| {spawn_cleanup(- &build_drain_trash_command(executable, &trash_dir),+ &build_drain_trash_command(executable, repo),InternalOp::Remove,)})@@ -2506,7 +2506,7 @@ mod tests {},BackgroundFallbackMode::Detached,|args, _| {- assert_eq!(args.last().unwrap(), repo.wt_trash_dir().as_os_str());+ assert_eq!(args.last().unwrap(), "_drain-trash");worktrunk::git::drain_trash(&repo.wt_trash_dir())},)diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 168d07bdb..4879bc3a3 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -704,7 +704,10 @@ pub fn apply_cd_directive_env(cmd: &mut std::process::Command, cd_file: &std::pa/// into a relocated command misdirects every `git` call in it; with both/// `GIT_DIR` and `GIT_WORK_TREE` present, a `git init` even writes/// `core.worktree` into the *inherited* repo's config, silently redirecting-/// every later plain git command there. See issue #3373.+/// every later plain git command there. See issue #3373. Detached children+/// (`spawn_detached_exec`: hook pipelines, trash drains) are relocated the+/// same way, and outlive the parent, so removing the invoking worktree would+/// also leave an inherited `GIT_DIR` naming a pruned gitdir.////// - **The child runs where the user already was** — aliases (the user's own/// top-level command, run from the invoking worktree) and `commit.generation`diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 7afdd69af..35c91e868 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -4586,6 +4586,69 @@ fn test_remove_leaves_entries_to_the_running_drain(mut repo: TestRepo) {});}+/// `wt _drain-trash` drains only the trash of the repository at its cwd, the+/// way the post-removal sweep runs it from `.git/wt`. Outside a repository it+/// fails and deletes nothing, however the directory's entries are named.+#[rstest]+fn test_drain_trash_derives_the_trash_from_the_repository(repo: TestRepo) {+ let outside = tempfile::tempdir().unwrap();+ let lookalike = outside.path().join("backup-2024");+ fs::create_dir(&lookalike).unwrap();+ let output = repo+ .wt_command()+ .arg("_drain-trash")+ .current_dir(outside.path())+ .output()+ .unwrap();+ assert!(!output.status.success());+ assert!(lookalike.exists());++ let wt_dir = crate::common::resolve_git_common_dir(repo.root_path()).join("wt");+ let staged = wt_dir.join("trash/feature-1700000000");+ fs::create_dir_all(&staged).unwrap();+ let output = repo+ .wt_command()+ .arg("_drain-trash")+ .current_dir(&wt_dir)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(!staged.exists());+}++/// Run as a `!wt` alias, `wt remove` inherits a `GIT_DIR` naming the invoking+/// worktree's gitdir, which the removal prunes. The detached drain discovers+/// the repository from its cwd instead, so it still empties the trash.+#[rstest]+fn test_remove_drains_trash_under_inherited_git_dir(mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");+ let git_dir = fs::read_to_string(feature_wt.join(".git")).unwrap();+ let git_dir = PathBuf::from(git_dir.trim().strip_prefix("gitdir: ").unwrap());++ let output = repo+ .wt_command()+ .current_dir(&feature_wt)+ .args(["remove", "--no-delete-branch", "--yes"])+ .env("GIT_DIR", &git_dir)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(!git_dir.exists());++ let trash_dir = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/trash");+ crate::common::wait_for("trash drained", || {+ fs::read_dir(&trash_dir).unwrap().next().is_none()+ });+}+/// `wt remove -vv` resolves every fsmonitor daemon in ONE `lsof` spawn and/// traces the sweep.///