Skip to content

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

Preserve native Git paths and pass removal arguments without shell interpolation (#4453)

Maximilian Roos3e17648ae4ad
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 079a0e8cc..96fd3a1f3 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -2684,6 +2684,23 @@ Hooks, aliases and `step.copy-ignored.exclude` accumulate rather than replace, s
action: ConfigCommand,
},
+ /// Complete a detached branch deletion after worktree removal.
+ #[command(name = "_delete-branch-if-safe", hide = true)]
+ InternalDeleteBranchIfSafe {
+ #[arg(long, value_parser = non_empty_branch)]
+ branch: String,
+ #[arg(long)]
+ target: String,
+ #[arg(
+ long,
+ required_unless_present = "force_delete",
+ conflicts_with = "force_delete"
+ )]
+ expected_tip: Option<String>,
+ #[arg(long)]
+ force_delete: bool,
+ },
+
/// Run a custom `wt-<name>` command found on PATH.
///
/// Captured by clap when the first positional argument doesn't match any
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 752a9b9e9..75617a322 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -39,6 +39,7 @@
//! inner `wt` invocations can redirect the parent shell's cwd.
use std::collections::{BTreeMap, BTreeSet};
+use std::sync::LazyLock;
use anyhow::{Context, bail};
use color_print::cformat;
@@ -82,14 +83,22 @@ const BUILTIN_STEP_COMMANDS: &[&str] = &[
"tether",
];
-/// Built-in top-level `wt` subcommand names — visible and hidden. Aliases
-/// with these names are fully unreachable: clap matches the built-in before
-/// alias dispatch sees the name, so `wt list` always runs the built-in even
-/// if `[aliases] list = …` is configured. Kept in sync with `Cli` via
-/// `test_top_level_builtins_match_clap`.
-pub(crate) const TOP_LEVEL_BUILTINS: &[&str] = &[
- "config", "hook", "list", "merge", "remove", "select", "step", "switch",
-];
+/// Whether clap matches a visible or hidden top-level built-in before alias
+/// dispatch can see the name. Derive discovery from the same command schema
+/// as dispatch, so adding a hidden command also makes its shadowing visible.
+pub(crate) fn is_top_level_builtin(name: &str) -> bool {
+ static NAMES: LazyLock<BTreeSet<String>> = LazyLock::new(|| {
+ use clap::CommandFactory;
+
+ crate::cli::Cli::command()
+ .get_subcommands()
+ .map(|command| command.get_name())
+ .filter(|name| *name != "help")
+ .map(str::to_owned)
+ .collect()
+ });
+ NAMES.contains(name)
+}
/// Whether `--help` or `-h` appears in `args` before any `--` literal-forward
/// terminator. Aliases have no clap-style help page — the template *is* the
@@ -815,11 +824,6 @@ fn render_aliases_help_section(
) -> String {
use std::fmt::Write as _;
- let shadowed_names: &[&str] = match context {
- HelpContext::TopLevel => TOP_LEVEL_BUILTINS,
- HelpContext::Step => BUILTIN_STEP_COMMANDS,
- };
-
// `entries` is sorted by (name, source); collapse user/project duplicates.
let mut names: Vec<&str> = Vec::new();
for (name, _, _) in entries {
@@ -837,7 +841,11 @@ fn render_aliases_help_section(
let list = names
.iter()
.map(|&name| {
- let styled = if shadowed_names.contains(&name) {
+ let shadowed = match context {
+ HelpContext::TopLevel => is_top_level_builtin(name),
+ HelpContext::Step => BUILTIN_STEP_COMMANDS.contains(&name),
+ };
+ let styled = if shadowed {
cformat!("<bold><cyan>{name}</></> <yellow>(shadowed by built-in)</>")
} else {
cformat!("<bold><cyan>{name}</></>")
@@ -1626,38 +1634,29 @@ cmd = [
}
}
- /// Verify TOP_LEVEL_BUILTINS stays in sync with the actual `Cli` enum.
- ///
- /// Hidden subcommands like `select` count — clap still matches them
- /// before falling through to alias dispatch, so they shadow aliases of
- /// the same name. Only `help` (clap-internal) and custom subcommands
- /// are excluded.
+ /// Shadowing discovery agrees with actual clap dispatch for visible and
+ /// hidden commands, while step-only and unknown names reach aliases.
#[test]
- fn test_top_level_builtins_match_clap() {
- use crate::cli::Cli;
- use clap::CommandFactory;
-
- let app = Cli::command();
- let clap_names: Vec<&str> = app
- .get_subcommands()
- .map(|s| s.get_name())
- .filter(|n| *n != "help")
- .collect();
-
- for name in &clap_names {
- assert!(
- TOP_LEVEL_BUILTINS.contains(name),
- "Top-level subcommand '{name}' is missing from TOP_LEVEL_BUILTINS. \
- Add it so the help splice annotates aliases unreachable at the top level."
- );
- }
- for name in TOP_LEVEL_BUILTINS {
- assert!(
- clap_names.contains(name),
- "TOP_LEVEL_BUILTINS contains '{name}' but no such top-level subcommand exists. \
- Remove it from the list."
+ fn test_top_level_shadowing_matches_clap_dispatch() {
+ use crate::cli::{Cli, Commands};
+ use clap::Parser;
+
+ for (args, builtin) in [
+ (vec!["wt", "list"], true),
+ (vec!["wt", "select"], true),
+ (vec!["wt", "commit"], false),
+ (vec!["wt", "deploy"], false),
+ ] {
+ assert_eq!(is_top_level_builtin(args[1]), builtin, "{}", args[1]);
+ let parsed = Cli::try_parse_from(&args).unwrap();
+ assert_eq!(
+ !matches!(parsed.command, Some(Commands::Custom(_))),
+ builtin,
+ "{}",
+ args[1]
);
}
+ assert!(!is_top_level_builtin("help"));
}
#[test]
diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rs
index 50f20a082..fa8915a12 100644
--- a/src/commands/config/alias.rs
+++ b/src/commands/config/alias.rs
@@ -31,7 +31,7 @@ use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::styling::{eprint, format_bash_with_gutter, info_message, println};
use crate::commands::alias::{
- AliasOptions, TOP_LEVEL_BUILTINS, load_aliases, load_aliases_for_listing,
+ AliasOptions, is_top_level_builtin, load_aliases, load_aliases_for_listing,
};
use crate::commands::build_invalid_subcommand_error;
use crate::commands::command_executor::{
@@ -124,7 +124,7 @@ fn list_aliases() -> anyhow::Result<()> {
/// surface rather than silently during an invocation that never reaches the
/// alias.
fn warn_if_shadowed(name: &str) {
- if TOP_LEVEL_BUILTINS.contains(&name) {
+ if is_top_level_builtin(name) {
worktrunk::styling::eprintln!(
"{}",
worktrunk::styling::warning_message(cformat!(
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 9720d4c5c..6dd65eda1 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::{Path, PathBuf};
#[cfg(windows)]
@@ -106,20 +107,6 @@ impl HookLog {
}
}
-/// Get the separator needed before closing brace in POSIX shell command grouping.
-/// Returns empty string if command already ends with newline or semicolon.
-///
-/// Unix-only: the `{ …; } &` grouping it feeds is `spawn_detached_unix`'s
-/// backgrounding wrapper, which the Windows spawn has no counterpart for.
-#[cfg(unix)]
-fn posix_command_separator(command: &str) -> &'static str {
- if command.ends_with('\n') || command.ends_with(';') {
- ""
- } else {
- ";"
- }
-}
-
/// Create the log directory and file for a detached process.
///
/// Returns `(log_path, log_file)`. Shared by `spawn_detached` and
@@ -169,116 +156,26 @@ fn create_detach_log(
pub fn spawn_detached(
repo: &Repository,
worktree_path: &Path,
- command: &str,
+ args: &[OsString],
branch: &str,
hook_log: &HookLog,
-) -> anyhow::Result<std::path::PathBuf> {
- let (log_path, log_file) = create_detach_log(repo, branch, hook_log)?;
-
- tracing::debug!(
- command = %command,
- "$ {} (detached, logging to {})",
- command,
- log_path.file_name().unwrap_or_default().to_string_lossy()
- );
-
- #[cfg(unix)]
- {
- let low_priority = matches!(hook_log, HookLog::Internal(_) | HookLog::Shared(_));
- spawn_detached_unix(worktree_path, command, log_file, low_priority)?;
- }
-
- #[cfg(windows)]
- {
- spawn_detached_windows(worktree_path, command, log_file)?;
- }
-
- Ok(log_path)
-}
-
-#[cfg(unix)]
-fn spawn_detached_unix(
- worktree_path: &Path,
- command: &str,
- log_file: fs::File,
- low_priority: bool,
-) -> anyhow::Result<()> {
- use std::os::unix::process::CommandExt;
-
- // Wrap in braces so `&` backgrounds the entire compound command.
- // Without braces, `cmd1 && cmd2; cmd3 &` parses as two statements:
- // `cmd1 && cmd2` (foreground) then `cmd3 &` (background) — the semicolon
- // has lower precedence than `&`, so only the last segment is backgrounded.
- let shell_cmd = format!("{{ {}{} }} &", command, posix_command_separator(command));
-
- // Detachment via process_group(0): puts the spawned shell in its own process group.
- // When the controlling PTY closes, SIGHUP is sent to the foreground process group.
- // Since our process is in a different group, it doesn't receive the signal.
- //
- // For low-priority ops (internal cleanup), wrap the shell via
- // `worktrunk::priority::command`. The policy is inherited by the backgrounded
- // command and its grandchildren.
- let mut cmd = worktrunk::priority::command("sh", low_priority);
- cmd.arg("-c")
- .arg(&shell_cmd)
- .current_dir(worktree_path)
- .stdin(Stdio::null())
- .stdout(Stdio::from(
- log_file
- .try_clone()
- .context("Failed to clone log file handle")?,
- ))
- .stderr(Stdio::from(log_file))
- .process_group(0); // New process group, not in PTY's foreground group
- // Prevent hooks from writing to the directive file
- worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
- let mut child =
- worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;
-
- // Wait for sh to exit (immediate, doesn't block on background command)
- child
- .wait()
- .context("Failed to wait for detachment shell")?;
-
- Ok(())
-}
-
-#[cfg(windows)]
-fn spawn_detached_windows(
- worktree_path: &Path,
- command: &str,
- log_file: fs::File,
-) -> anyhow::Result<()> {
- use std::os::windows::process::CommandExt;
- use worktrunk::shell_exec::ShellConfig;
-
- // CREATE_NEW_PROCESS_GROUP: Creates new process group (0x00000200)
- // CREATE_NO_WINDOW: Creates process without console window (0x08000000)
- const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
-
- let shell = ShellConfig::get()?;
-
- // Git Bash runs the command as written; no stdin wrapper is needed.
- let mut cmd = shell.command(command);
-
- cmd.current_dir(worktree_path)
- .stdin(Stdio::null())
- .stdout(Stdio::from(
- log_file
- .try_clone()
- .context("Failed to clone log file handle")?,
- ))
- .stderr(Stdio::from(log_file))
- .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
- // Prevent hooks from writing to the directive file
- worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
- worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;
-
- // Windows: Process is fully detached with a hidden window via CREATE_NO_WINDOW flag,
- // no need to wait (unlike Unix which waits for the outer shell)
-
- Ok(())
+) -> anyhow::Result<PathBuf> {
+ let shell = worktrunk::shell_exec::ShellConfig::get()?;
+ let args: Vec<_> = shell
+ .args
+ .iter()
+ .map(OsString::from)
+ .chain(args.iter().cloned())
+ .collect();
+ spawn_detached_exec(
+ repo,
+ worktree_path,
+ &shell.executable,
+ &args,
+ branch,
+ hook_log,
+ &[],
+ )
}
/// Spawn a detached background process by executing a binary directly.
@@ -299,7 +196,7 @@ pub fn spawn_detached_exec(
repo: &Repository,
worktree_path: &Path,
program: &Path,
- args: &[&str],
+ args: &[impl AsRef<OsStr>],
branch: &str,
hook_log: &HookLog,
stdin_bytes: &[u8],
@@ -310,7 +207,7 @@ pub fn spawn_detached_exec(
program = %program.display(),
"$ {} {} (detached, logging to {})",
program.display(),
- args.join(" "),
+ args.iter().map(|arg| arg.as_ref().to_string_lossy()).collect::<Vec<_>>().join(" "),
log_path.file_name().unwrap_or_default().to_string_lossy()
);
@@ -360,7 +257,7 @@ fn set_background_hook_env(cmd: &mut std::process::Command, is_background_hook:
fn spawn_detached_exec_unix(
worktree_path: &Path,
program: &Path,
- args: &[&str],
+ args: &[impl AsRef<OsStr>],
log_file: fs::File,
stdin_bytes: &[u8],
low_priority: bool,
@@ -394,7 +291,7 @@ fn spawn_detached_exec_unix(
fn spawn_detached_exec_windows(
worktree_path: &Path,
program: &Path,
- args: &[&str],
+ args: &[impl AsRef<OsStr>],
log_file: fs::File,
stdin_bytes: &[u8],
is_background_hook: bool,
@@ -481,7 +378,7 @@ pub fn sweep_stale_trash(repo: &Repository) {
return;
}
- let command = build_trash_sweep_command(&stale);
+ let command = build_remove_paths_command(&stale);
// The sweep is repo-wide (not branch-scoped), so it logs to a top-level
// shared file alongside `commands.jsonl` and `trace.log`. The branch
@@ -497,17 +394,17 @@ pub fn sweep_stale_trash(repo: &Repository) {
}
}
-/// Build the `rm -rf -- …` command that [`sweep_stale_trash`] hands to
-/// [`spawn_detached`]. All entries are joined into a single invocation so the
-/// sweep spawns one background process regardless of how many stale entries
-/// exist; each path is POSIX-escaped so directories with spaces or shell
-/// metacharacters round-trip safely through the wrapping `sh -c`.
-fn build_trash_sweep_command(paths: &[PathBuf]) -> String {
- let escaped: Vec<String> = paths
- .iter()
- .map(|p| shell_escape::unix::escape(p.to_string_lossy().as_ref().into()).into_owned())
- .collect();
- format!("rm -rf -- {}", escaped.join(" "))
+/// Shell argv: a fixed script, its `$0`, then native path arguments.
+/// Paths are never interpolated into shell source.
+pub fn build_remove_paths_command(
+ paths: impl IntoIterator<Item = impl AsRef<OsStr>>,
+) -> Vec<OsString> {
+ let mut args = vec![
+ OsString::from(r#"exec rm -rf -- "$@""#),
+ OsString::from("wt"),
+ ];
+ args.extend(paths.into_iter().map(|path| path.as_ref().to_os_string()));
+ args
}
/// Collect paths in `trash_dir` whose embedded timestamp is older than
@@ -543,89 +440,35 @@ fn parse_trash_entry_timestamp(name: &str) -> Option<u64> {
suffix.parse::<u64>().ok()
}
-/// Remove an already-staged worktree's trash independently of branch deletion.
-///
-/// The worktree has been renamed and its registry entry pruned. This command
-/// can start immediately; it never touches the original worktree path.
-pub fn build_remove_command_staged(staged_path: &std::path::Path) -> String {
- use shell_escape::unix::escape;
-
- let staged_path_str = staged_path.to_string_lossy();
- let staged_escaped = escape(staged_path_str.as_ref().into());
- format!("rm -rf -- {}", staged_escaped)
-}
-
-/// Remove the empty shell-PWD placeholder after synchronous removal finishes.
-///
-/// The one-second delay gives the shell wrapper time to consume its cd
-/// directive. `rmdir` preserves any files written into the original path.
-pub fn build_remove_placeholder_command(original_path: &std::path::Path) -> String {
- use shell_escape::unix::escape;
-
- let original_path_str = original_path.to_string_lossy();
- let original_escaped = escape(original_path_str.as_ref().into());
- format!("sleep 1 && rmdir -- {} 2>/dev/null", original_escaped)
+/// Remove the empty shell-PWD placeholder after the wrapper consumes its cd directive.
+/// `rmdir` preserves any files written into the original path.
+pub fn build_remove_placeholder_command(path: &Path) -> Vec<OsString> {
+ vec![
+ r#"sleep 1 && rmdir -- "$1" 2>/dev/null"#.into(),
+ "wt".into(),
+ path.as_os_str().into(),
+ ]
}
-/// Build shell command for background worktree removal (legacy path).
-///
-/// This is the fallback for when rename-based removal fails (e.g., cross-filesystem)
-/// or for foreground mode where `git worktree remove` provides better error messages.
-///
-/// `branch_to_delete` is the branch to delete after removing the worktree.
-/// Pass `None` for detached HEAD or when branch should be retained.
-/// This decision is computed upfront (checking if branch is merged) before spawning the background process.
-///
-/// `force_worktree` adds `--force` to `git worktree remove`, allowing removal
-/// even when the worktree contains untracked files (like build artifacts).
-///
-/// When `changed_directory` is true, a 1-second delay runs first so the shell
-/// wrapper can cd away before the directory is removed. When false (removing a
-/// non-current worktree), the removal runs immediately.
+/// Fallback when staging fails. Only flags and sequencing enter the script;
+/// the checkout remains a separate process argument.
pub fn build_remove_command(
- worktree_path: &std::path::Path,
- branch_to_delete: Option<&str>,
+ path: &Path,
force_worktree: bool,
changed_directory: bool,
-) -> String {
- use shell_escape::unix::escape;
-
- let worktree_path_str = worktree_path.to_string_lossy();
- let worktree_escaped = escape(worktree_path_str.as_ref().into());
-
- let force_flag = if force_worktree { " --force" } else { "" };
-
- // The fsmonitor daemon is stopped (and force-killed if wedged) synchronously
- // in the Rust foreground by `stop_fsmonitor_daemon`, before this command is
- // built — see `spawn_background_removal`. The detached process only does the
- // `git worktree remove` / `rm -rf`.
- //
- // When removing the current worktree, delay so the shell wrapper can cd away
- // before the directory is removed. The primary fix for the "shell-init: error
- // retrieving current directory" race is in the fish wrapper (using builtins
- // instead of subprocesses to read the directive), but this provides defense in
- // depth for other shells and edge cases.
- let prefix = if changed_directory {
- "sleep 1 && ".to_string()
- } else {
- String::new()
- };
-
- match branch_to_delete {
- Some(branch_name) => {
- let branch_escaped = escape(branch_name.into());
- format!(
- "{}git worktree remove{} {} && git branch -D -- {}",
- prefix, force_flag, worktree_escaped, branch_escaped
- )
- }
- None => {
- format!(
- "{}git worktree remove{} {}",
- prefix, force_flag, worktree_escaped
- )
- }
+ tail: Option<&[OsString]>,
+) -> Vec<OsString> {
+ let delay = if changed_directory { "sleep 1 && " } else { "" };
+ let force = if force_worktree { " --force" } else { "" };
+ let mut script = format!(r#"{delay}git worktree remove{force} -- "$1""#);
+ if tail.is_some() {
+ script.push_str(r#" && shift && "$@""#);
+ }
+ let mut args = vec![script.into(), "wt".into(), path.as_os_str().into()];
+ if let Some(tail) = tail {
+ args.extend_from_slice(tail);
}
+ args
}
#[cfg(test)]
@@ -693,94 +536,25 @@ mod tests {
}
#[test]
- #[cfg(unix)]
- fn test_posix_command_separator() {
- // Commands ending with newline don't need separator
- assert_eq!(posix_command_separator("echo hello\n"), "");
-
- // Commands ending with semicolon don't need separator
- assert_eq!(posix_command_separator("echo hello;"), "");
-
- // Commands without trailing newline/semicolon need separator
- assert_eq!(posix_command_separator("echo hello"), ";");
-
- // Empty command needs separator
- assert_eq!(posix_command_separator(""), ";");
-
- // Commands with internal newlines but not trailing
- assert_eq!(posix_command_separator("echo\nhello"), ";");
-
- // Commands with internal semicolons but not trailing
- assert_eq!(posix_command_separator("echo; hello"), ";");
- }
-
- #[test]
- fn test_build_remove_command() {
- use std::path::PathBuf;
-
- let path = PathBuf::from("/tmp/test-worktree");
-
- // changed_directory=true: sleep before removal
- assert_snapshot!(build_remove_command(&path, None, false, true), @"sleep 1 && git worktree remove /tmp/test-worktree");
- assert_snapshot!(build_remove_command(&path, Some("feature-branch"), false, true), @"sleep 1 && git worktree remove /tmp/test-worktree && git branch -D -- feature-branch");
-
- // changed_directory=false: no sleep
- assert_snapshot!(build_remove_command(&path, None, false, false), @"git worktree remove /tmp/test-worktree");
- assert_snapshot!(build_remove_command(&path, Some("feature-branch"), false, false), @"git worktree remove /tmp/test-worktree && git branch -D -- feature-branch");
-
- // With force flag
- assert_snapshot!(build_remove_command(&path, None, true, true), @"sleep 1 && git worktree remove --force /tmp/test-worktree");
-
- // Shell escaping for special characters
- let special_path = PathBuf::from("/tmp/test worktree");
- assert_snapshot!(build_remove_command(&special_path, Some("feature/branch"), false, true), @"sleep 1 && git worktree remove '/tmp/test worktree' && git branch -D -- feature/branch");
- }
-
- #[test]
- fn test_build_remove_command_staged() {
- let staged_path = PathBuf::from("/tmp/repo/.git/wt/trash/my-project.feature-1234567890");
- let original_path = PathBuf::from("/tmp/my-project.feature");
- assert_snapshot!(build_remove_command_staged(&staged_path), @"rm -rf -- /tmp/repo/.git/wt/trash/my-project.feature-1234567890");
- assert_snapshot!(build_remove_placeholder_command(&original_path), @"sleep 1 && rmdir -- /tmp/my-project.feature 2>/dev/null");
-
- let special_path = PathBuf::from("/tmp/repo/.git/wt/trash/test worktree-123");
- let special_original = PathBuf::from("/tmp/test worktree");
- assert_snapshot!(build_remove_command_staged(&special_path), @"rm -rf -- '/tmp/repo/.git/wt/trash/test worktree-123'");
- assert_snapshot!(build_remove_placeholder_command(&special_original), @"sleep 1 && rmdir -- '/tmp/test worktree' 2>/dev/null");
- }
-
- #[test]
- fn test_build_trash_sweep_command() {
- // Empty list still produces a well-formed command — the caller
- // (`sweep_stale_trash`) bails before we get here, but the helper itself
- // must not panic on an empty slice.
- assert_snapshot!(build_trash_sweep_command(&[]), @"rm -rf -- ");
-
- // Plain paths — joined with spaces, no quoting.
- let paths = [
- PathBuf::from("/tmp/repo/.git/wt/trash/feature-1700000000"),
- PathBuf::from("/tmp/repo/.git/wt/trash/bugfix-1700000100"),
- ];
- assert_snapshot!(
- build_trash_sweep_command(&paths),
- @"rm -rf -- /tmp/repo/.git/wt/trash/feature-1700000000 /tmp/repo/.git/wt/trash/bugfix-1700000100"
- );
-
- // Shell metacharacters — POSIX single-quote escaping isolates each path
- // so the wrapping `sh -c` reads them as literal arguments. The embedded
- // single quote uses the standard `'\''` idiom. This is the regression
- // guard for the platform/MSYSTEM-sensitive `shell_escape::escape` we
- // replaced: under cmd.exe quoting `$(echo pwned)` would still execute
- // when spliced into a POSIX shell.
- let nasty = [
- PathBuf::from("/tmp/trash/with space-1"),
- PathBuf::from("/tmp/trash/$(echo pwned)-2"),
- PathBuf::from("/tmp/trash/a'b-3"),
- ];
- assert_snapshot!(
- build_trash_sweep_command(&nasty),
- @"rm -rf -- '/tmp/trash/with space-1' '/tmp/trash/$(echo pwned)-2' '/tmp/trash/a'\\''b-3'"
- );
+ fn removal_arguments_do_not_interpret_paths() {
+ let tmp = tempfile::tempdir().unwrap();
+ let name = if cfg!(windows) {
+ "with space-$(echo PWNED)"
+ } else {
+ "with space-'$(echo PWNED)\n"
+ };
+ let path = tmp.path().join(name);
+ fs::create_dir(&path).unwrap();
+ fs::write(path.join("payload"), "keep exact target").unwrap();
+ let args = build_remove_paths_command([&path]);
+ let shell = worktrunk::shell_exec::ShellConfig::get().unwrap();
+ let output = worktrunk::shell_exec::Cmd::new(shell.executable.to_str().unwrap())
+ .args(&shell.args)
+ .args(&args)
+ .run()
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+ assert!(!path.exists());
}
#[test]
diff --git a/src/git/error.rs b/src/git/error.rs
index 8f898ed3a..88c5ce474 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -23,6 +23,7 @@
use crate::config::HookSource;
use std::borrow::Cow;
+use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use color_print::cformat;
@@ -213,7 +214,7 @@ impl CommandError {
/// Build from the captured `Output` of a non-zero exit.
pub fn from_failed_output(
program: impl Into<String>,
- args: &[impl AsRef<str>],
+ args: &[impl AsRef<OsStr>],
output: &std::process::Output,
) -> Self {
let stderr = String::from_utf8_lossy(&output.stderr).replace('\r', "\n");
@@ -224,7 +225,10 @@ impl CommandError {
let signal = None;
Self {
program: program.into(),
- args: args.iter().map(|s| s.as_ref().to_string()).collect(),
+ args: args
+ .iter()
+ .map(|s| s.as_ref().to_string_lossy().into_owned())
+ .collect(),
stderr,
stdout,
exit_code: output.status.code(),
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 765642c1b..aebc9848a 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -2,6 +2,47 @@
use std::path::{Path, PathBuf};
+fn git_path_from_bytes(bytes: &[u8]) -> std::io::Result<PathBuf> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::ffi::OsStringExt;
+ Ok(PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec())))
+ }
+ #[cfg(not(unix))]
+ {
+ // Windows accepts Git's forward slashes; preserve its output spelling.
+ std::str::from_utf8(bytes)
+ .map(PathBuf::from)
+ .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
+ }
+}
+
+/// Decode one path from Git output, preserving bytes before its final LF.
+fn git_path_from_output(bytes: &[u8]) -> std::io::Result<PathBuf> {
+ let path = bytes.strip_suffix(b"\n").ok_or_else(|| {
+ std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "Unterminated Git path output",
+ )
+ })?;
+ git_path_from_bytes(path)
+}
+
+/// Gitfiles and backlinks terminate paths with CR/LF, unlike command output.
+fn git_path_from_file(bytes: &[u8]) -> std::io::Result<PathBuf> {
+ let mut path = bytes;
+ while matches!(path.last(), Some(b'\n' | b'\r')) {
+ path = &path[..path.len() - 1];
+ }
+ if path.is_empty() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "Empty Git path",
+ ));
+ }
+ git_path_from_bytes(path)
+}
+
// Submodules
mod ci_platform;
mod diff;
@@ -827,7 +868,7 @@ impl WorktreeInfo {
/// Build the canonical worktree subject for this inventory entry.
pub fn worktree_ref(&self) -> WorktreeRef {
- // `branch` is the short form produced by `parse_porcelain_list` (one
+ // `branch` is the short form produced by `parse_porcelain_list_z` (one
// `refs/heads/` prefix stripped). Re-qualifying it in the worktree
// constructor preserves even a pathological branch literally named
// `refs/heads/foo` as `refs/heads/refs/heads/foo`.
diff --git a/src/git/parse.rs b/src/git/parse.rs
index 5f0fa2d7e..ae36203b3 100644
--- a/src/git/parse.rs
+++ b/src/git/parse.rs
@@ -1,37 +1,37 @@
//! Git output parsing functions
-use std::path::PathBuf;
-
-use super::{GitError, WorktreeInfo};
+use super::{GitError, WorktreeInfo, git_path_from_bytes};
impl WorktreeInfo {
- pub(crate) fn parse_porcelain_list(output: &str) -> anyhow::Result<Vec<Self>> {
+ /// Parse NUL-delimited records, preserving worktree path bytes and embedded
+ /// newlines in paths and lock reasons.
+ pub(crate) fn parse_porcelain_list_z(output: &[u8]) -> anyhow::Result<Vec<Self>> {
let mut worktrees = Vec::new();
let mut current: Option<WorktreeInfo> = None;
- for line in output.lines() {
- if line.is_empty() {
+ for record in output.split(|byte| *byte == 0) {
+ if record.is_empty() {
if let Some(wt) = current.take() {
worktrees.push(wt);
}
continue;
}
- let (key, value) = match line.split_once(' ') {
- Some((k, v)) => (k, Some(v)),
- None => (line, None),
+ let (key, value) = match record.iter().position(|byte| *byte == b' ') {
+ Some(index) => (&record[..index], Some(&record[index + 1..])),
+ None => (record, None),
};
match key {
- "worktree" => {
+ b"worktree" => {
let Some(path) = value else {
return Err(GitError::ParseError {
- message: "worktree line missing path".into(),
+ message: "worktree record missing path".into(),
}
.into());
};
current = Some(WorktreeInfo {
- path: PathBuf::from(path),
+ path: git_path_from_bytes(path)?,
head: String::new(),
branch: None,
bare: false,
@@ -41,40 +41,41 @@ impl WorktreeInfo {
});
}
key => match (key, current.as_mut()) {
- ("HEAD", Some(wt)) => {
+ (b"HEAD", Some(wt)) => {
let Some(sha) = value else {
return Err(GitError::ParseError {
- message: "HEAD line missing SHA".into(),
+ message: "HEAD record missing SHA".into(),
}
.into());
};
- wt.head = sha.to_string();
+ wt.head = String::from_utf8_lossy(sha).into_owned();
}
- ("branch", Some(wt)) => {
+ (b"branch", Some(wt)) => {
// Strip refs/heads/ prefix if present
let Some(branch_ref) = value else {
return Err(GitError::ParseError {
- message: "branch line missing ref".into(),
+ message: "branch record missing ref".into(),
}
.into());
};
let branch = branch_ref
- .strip_prefix("refs/heads/")
- .unwrap_or(branch_ref)
- .to_string();
- wt.branch = Some(branch);
+ .strip_prefix(b"refs/heads/")
+ .unwrap_or(branch_ref);
+ wt.branch = Some(String::from_utf8_lossy(branch).into_owned());
}
- ("bare", Some(wt)) => {
+ (b"bare", Some(wt)) => {
wt.bare = true;
}
- ("detached", Some(wt)) => {
+ (b"detached", Some(wt)) => {
wt.detached = true;
}
- ("locked", Some(wt)) => {
- wt.locked = Some(value.unwrap_or_default().to_string());
+ (b"locked", Some(wt)) => {
+ wt.locked =
+ Some(String::from_utf8_lossy(value.unwrap_or_default()).into_owned());
}
- ("prunable", Some(wt)) => {
- wt.prunable = Some(value.unwrap_or_default().to_string());
+ (b"prunable", Some(wt)) => {
+ wt.prunable =
+ Some(String::from_utf8_lossy(value.unwrap_or_default()).into_owned());
}
_ => {
// Ignore unknown attributes or attributes before first worktree
@@ -83,7 +84,7 @@ impl WorktreeInfo {
}
}
- // Push the last worktree if the output doesn't end with a blank line
+ // Retain the last worktree if the final empty record is absent.
if let Some(wt) = current {
worktrees.push(wt);
}
@@ -205,6 +206,7 @@ pub fn parse_untracked_files(status_output: &str) -> Vec<String> {
#[cfg(test)]
mod tests {
use super::*;
+ use std::path::PathBuf;
// ============================================================================
// DefaultBranchName::from_local Tests
@@ -292,40 +294,31 @@ mod tests {
}
// ============================================================================
- // WorktreeInfo::parse_porcelain_list Tests
+ // WorktreeInfo::parse_porcelain_list_z Tests
// ============================================================================
#[test]
fn test_parse_porcelain_list_single_worktree() {
- let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let output = "worktree /path/to/repo\0HEAD abc123\0branch refs/heads/main\0\0";
+ let worktrees = WorktreeInfo::parse_porcelain_list_z(output.as_bytes()).unwrap();
let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
- assert_eq!(wt.path.to_str().unwrap(), "/path/to/repo");
+ assert_eq!(wt.path, PathBuf::from("/path/to/repo"));
assert_eq!(wt.head, "abc123");
assert_eq!(wt.branch, Some("main".to_string()));
}
- #[test]
- fn test_parse_porcelain_list_multiple_worktrees() {
- let output = "worktree /path/main\nHEAD aaa\nbranch refs/heads/main\n\nworktree /path/feature\nHEAD bbb\nbranch refs/heads/feature\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();
- assert_eq!(main_wt.branch, Some("main".to_string()));
- assert_eq!(feature_wt.branch, Some("feature".to_string()));
- }
-
#[test]
fn test_parse_porcelain_list_bare_repo() {
- let output = "worktree /path/to/repo.git\nHEAD abc123\nbare\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let output = "worktree /path/to/repo.git\0HEAD abc123\0bare\0\0";
+ let worktrees = WorktreeInfo::parse_porcelain_list_z(output.as_bytes()).unwrap();
let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
assert!(wt.bare);
}
#[test]
fn test_parse_porcelain_list_detached() {
- let output = "worktree /path/to/repo\nHEAD abc123\ndetached\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let output = "worktree /path/to/repo\0HEAD abc123\0detached\0\0";
+ let worktrees = WorktreeInfo::parse_porcelain_list_z(output.as_bytes()).unwrap();
let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
assert!(wt.detached);
assert!(wt.branch.is_none());
@@ -333,57 +326,42 @@ mod tests {
#[test]
fn test_parse_porcelain_list_locked() {
- let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked reason for lock\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let output = "worktree /path/to/repo\0HEAD abc123\0branch refs/heads/main\0locked reason for lock\0\0";
+ let worktrees = WorktreeInfo::parse_porcelain_list_z(output.as_bytes()).unwrap();
let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
assert_eq!(wt.locked, Some("reason for lock".to_string()));
}
#[test]
fn test_parse_porcelain_list_prunable() {
- let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable gitdir file missing\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let output = "worktree /path/to/repo\0HEAD abc123\0branch refs/heads/main\0prunable gitdir file missing\0\0";
+ let worktrees = WorktreeInfo::parse_porcelain_list_z(output.as_bytes()).unwrap();
let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
assert_eq!(wt.prunable, Some("gitdir file missing".to_string()));
}
#[test]
fn test_parse_porcelain_list_empty() {
- let result = WorktreeInfo::parse_porcelain_list("");
+ let result = WorktreeInfo::parse_porcelain_list_z(b"");
assert!(result.is_ok());
let worktrees = result.unwrap();
assert!(worktrees.is_empty());
}
#[test]
- fn test_parse_porcelain_list_no_trailing_blank() {
- // Git output may not always end with a blank line
- let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main";
- let result = WorktreeInfo::parse_porcelain_list(output);
+ fn test_parse_porcelain_list_no_trailing_empty_record() {
+ let output = "worktree /path/to/repo\0HEAD abc123\0branch refs/heads/main";
+ let result = WorktreeInfo::parse_porcelain_list_z(output.as_bytes());
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 1);
}
- #[test]
- fn test_parse_porcelain_list_missing_worktree_path() {
- let output = "worktree\nHEAD abc123\n\n";
- let result = WorktreeInfo::parse_porcelain_list(output);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_parse_porcelain_list_missing_head_sha() {
- let output = "worktree /path\nHEAD\n\n";
- let result = WorktreeInfo::parse_porcelain_list(output);
- assert!(result.is_err());
- }
-
#[test]
fn test_parse_porcelain_list_branch_without_refs_prefix() {
// This can happen in some edge cases
- let output = "worktree /path/to/repo\nHEAD abc123\nbranch main\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let output = "worktree /path/to/repo\0HEAD abc123\0branch main\0\0";
+ let worktrees = WorktreeInfo::parse_porcelain_list_z(output.as_bytes()).unwrap();
let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
// Should use the branch name as-is when no refs/heads/ prefix
assert_eq!(wt.branch, Some("main".to_string()));
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 8b673559d..dc4bd5cba 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -194,7 +194,7 @@ fn force_kill_fsmonitor_via_socket(socket: &Path) {
let output = match Cmd::new("lsof")
.arg("-t")
.arg("--")
- .arg(socket.to_string_lossy().into_owned())
+ .arg(socket)
.timeout(FSMONITOR_LSOF_TIMEOUT)
.run()
{
@@ -588,21 +588,11 @@ fn rename_into_trash(repo: &Repository, worktree_path: &Path, git_dir: &Path) ->
}
}
-/// Capture fresh refs and run a planned branch deletion.
+/// Capture fresh refs and run branch deletion.
///
-/// The spelling of "the plan said delete; do it now" for every synchronous
-/// site that doesn't already hold a fresh snapshot (the background fast path,
-/// prune's synchronous fallback, branch-only removal, a picker row). The
-/// invariant it carries — no deletion ever runs against the planning-time
-/// snapshot, so the topology guard and CAS in [`delete_branch_if_safe`]
-/// re-decide against live state — also holds on the two paths that don't call
-/// it: the foreground removal captures its own fresh snapshot just before
-/// [`remove_worktree_with_cleanup`], and the detached fallback can't call
-/// Rust, so it gets the guarantee from a fresh porcelain topology read followed
-/// by an `update-ref -d <ref> <sha>` shell tail instead. A hook or concurrent
-/// process that advanced the branch after the integration check cannot lose
-/// that commit: the CAS rejects the deletion. Checkout protection is best
-/// effort, retaining any checkout observed by the fresh topology read.
+/// Used after worktree removal and for branch-only deletion. Every path,
+/// including the detached fallback, uses [`delete_branch_if_safe`] to recheck
+/// integration and checkout ownership; safe deletion uses CAS against the captured tip.
pub fn execute_branch_deletion(
repo: &Repository,
branch_name: &str,
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index cd3f24c44..348b987eb 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -148,7 +148,7 @@ use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};
// Import types from parent module
use super::{
CommandError, DefaultBranchName, ErrorExt, ForgeKind, GitError, GitItemId, LineDiff,
- WorktreeInfo,
+ WorktreeInfo, git_path_from_bytes,
};
// Re-export types needed by submodules
@@ -536,9 +536,10 @@ struct RepositoryLocks {
/// keyed by the canonicalized path used as the cache key (same convention as
/// [`Repository::worktree_at`] / [`WorkingTree`]).
///
-/// **Invariant:** `WORKTREE_ROOTS.contains_key(path)` ⇔ `path` is inside a git
-/// work tree. The fallback path `WorkingTree::root` returns when `rev-parse
-/// --show-toplevel` fails (deleted CWD, bare repo root, non-repo dir) is
+/// Cached values are confirmed worktree roots. Ambiguous batch output leaves
+/// discovery to the exact single-selector accessor. The fallback path returned
+/// by `WorkingTree::root` when `rev-parse --show-toplevel` fails (deleted CWD,
+/// bare repo root, non-repo dir) is
/// **not** persisted, which keeps the membership check usable as a
/// "is-inside-worktree" signal — see [`WorkingTree::prewarm_info`]'s fast path.
///
@@ -811,6 +812,16 @@ impl Drop for TemporaryObjectStore {
}
}
+/// Accept only complete selector batches; an unborn HEAD is Git's one
+/// expected partial failure. Embedded path newlines invalidate the framing.
+fn rev_parse_fields(output: &std::process::Output, count: usize) -> Option<Vec<&[u8]>> {
+ let bytes = output.stdout.strip_suffix(b"\n")?;
+ let fields: Vec<_> = bytes.split(|byte| *byte == b'\n').collect();
+ (fields.len() == count
+ && (output.status.success() || fields.last() == Some(&b"HEAD".as_slice())))
+ .then_some(fields)
+}
+
impl Repository {
/// Discover the repository from the current directory.
///
@@ -1132,17 +1143,28 @@ impl Repository {
return;
};
- let stdout = String::from_utf8_lossy(&output.stdout);
- let mut lines = stdout.lines();
+ // Bare discovery stops after the common directory and `false`.
+ let bare = output
+ .stdout
+ .strip_suffix(b"\nfalse\n")
+ .filter(|path| !path.contains(&b'\n'));
+ let fields = if let Some(common) = bare {
+ vec![common, b"false".as_slice()]
+ } else {
+ let Some(fields) = rev_parse_fields(&output, 5).filter(|fields| fields[1] == b"true")
+ else {
+ return;
+ };
+ fields
+ };
+ let mut fields = fields.into_iter();
- // Line 1: --git-common-dir. Cache even on non-zero exit — git emits
- // this line before bailing out of `--show-toplevel` in a bare repo.
- let Some(common_raw) = lines.next() else {
+ // Common-dir precedes selectors that can fail in bare or unborn repos.
+ let Some(common_path) = fields.next().and_then(|raw| git_path_from_bytes(raw).ok()) else {
return;
};
- let common_path = PathBuf::from(common_raw.trim());
let common_absolute = if common_path.is_relative() {
- discovery_path.join(&common_path)
+ discovery_path.join(common_path)
} else {
common_path
};
@@ -1150,57 +1172,35 @@ impl Repository {
return;
};
GIT_COMMON_DIR_CACHE.insert(discovery_path.to_path_buf(), common_resolved);
-
- // Per-worktree maps key on the canonicalized form of `discovery_path`,
- // matching what `worktree_at` derives. Use the same fallback as
- // `worktree_at` so the keys line up (canonicalize when the path
- // exists, raw otherwise).
let worktree_key =
canonicalize(discovery_path).unwrap_or_else(|_| discovery_path.to_path_buf());
-
- // Line 2: --is-inside-work-tree. "false" or missing → leave the
- // per-worktree maps untouched. The membership invariant on
- // `WORKTREE_ROOTS` ("contains_key ⇔ inside a worktree") forbids
- // recording a sentinel here; `WorkingTree::root` and `prewarm_info`
- // would misclassify the path as inside a worktree on the next call.
- let is_inside = lines.next().is_some_and(|s| s.trim() == "true");
- if !is_inside {
+ if fields.next() != Some(b"true".as_slice()) {
return;
}
- // Line 3: --show-toplevel. Always emits when is_inside=true; mirror
- // `prewarm_info`'s `self.path` fallback when canonicalize fails.
- let raw_toplevel = lines.next().unwrap_or("").trim();
- let canonical_root =
- canonicalize(PathBuf::from(raw_toplevel)).unwrap_or_else(|_| worktree_key.clone());
- WORKTREE_ROOTS
- .entry(worktree_key.clone())
- .or_insert(canonical_root);
-
- // Line 4: --git-dir. Resolve relative-to-discovery and canonicalize;
- // only land it when canonicalize succeeds, matching `prewarm_info`.
- if let Some(git_dir) = lines.next().and_then(|raw| {
- let path = PathBuf::from(raw.trim());
+ if let Some(root) = fields
+ .next()
+ .and_then(|raw| canonicalize(git_path_from_bytes(raw).ok()?).ok())
+ {
+ WORKTREE_ROOTS.entry(worktree_key.clone()).or_insert(root);
+ }
+ if let Some(git_dir) = fields.next().and_then(|raw| {
+ let path = git_path_from_bytes(raw).ok()?;
let absolute = if path.is_relative() {
- discovery_path.join(&path)
+ discovery_path.join(path)
} else {
path
};
- canonicalize(&absolute).ok()
+ canonicalize(absolute).ok()
}) {
GIT_DIRS.entry(worktree_key.clone()).or_insert(git_dir);
}
-
- // Line 5: --symbolic-full-name HEAD. Only trustworthy when the whole
- // batch succeeded — on unborn HEAD this lands as the literal string
- // "HEAD" (indistinguishable from detached HEAD without exit status).
- // On unborn HEAD we leave `CURRENT_BRANCHES` empty so the
- // `symbolic-ref --short HEAD` fallback in `WorkingTree::branch`
- // resolves the unborn branch name.
+ // An unborn HEAD prints a fallback despite the failed batch; leave
+ // its branch unresolved so the canonical branch accessor can ask Git.
if output.status.success()
- && let Some(raw) = lines.next()
+ && let Some(raw) = fields.next().and_then(|raw| std::str::from_utf8(raw).ok())
{
- let branch = raw.trim().strip_prefix("refs/heads/").map(str::to_owned);
+ let branch = raw.strip_prefix("refs/heads/").map(str::to_owned);
CURRENT_BRANCHES.entry(worktree_key).or_insert(branch);
}
}
@@ -1378,8 +1378,7 @@ impl Repository {
);
}
- let stdout = String::from_utf8_lossy(&output.stdout);
- let path = PathBuf::from(stdout.trim());
+ let path = super::git_path_from_output(&output.stdout)?;
// Always canonicalize to resolve symlinks (e.g., /var -> /private/var on macOS)
let absolute_path = if path.is_relative() {
discovery_path.join(&path)
@@ -1466,49 +1465,32 @@ impl Repository {
}
}
- /// The git dir a directory's own `.git` entry names, without forking
- /// `git rev-parse --git-dir`. A `.git` directory *is* the git dir (a main
- /// worktree, or the root of some other repository); a `.git` file holds
- /// `gitdir: <path>` pointing at `<common>/worktrees/<id>` (a linked
- /// worktree). Returns the canonicalized git dir, or `None` when the entry
- /// is missing, unreadable, or in a form not worth second-guessing. Mirrors
- /// the `--git-dir` canonicalization in [`Self::prewarm`]
- /// (`prewarm_rev_parse`).
- ///
- /// Answers for the directory rather than for a repository: it reads the
- /// `.git` entry sitting there and never walks up to a parent, which is what
- /// lets [`WorkingTree::ensure_holds_this_worktree`] compare the answer
- /// against this repository and learn something. Every call reads the
- /// filesystem, so a caller consulting it twice sees any change in between —
- /// the reason that gate uses it rather than the `GIT_DIRS`-cached
- /// [`WorkingTree::git_dir`].
- ///
- /// Three callers, with different readings of `None`:
- /// [`Self::prime_worktree_path_caches`] declines to seed a cache entry and
- /// leaves the answer to the subprocess, `separate_git_dir_work_tree`
- /// declines the backlink it was confirming and falls back to
- /// `parent(git_common_dir)`, and the removal gate refuses.
+ /// Read this directory's own `.git`, without a subprocess or walking up
+ /// to a parent. A directory is its own Git store; a gitfile points to the
+ /// store with `gitdir: <path>`. The returned directory is canonical.
+ ///
+ /// Reads are deliberately uncached so removal can detect replacement
+ /// between gates; `WorkingTree::git_dir` uses a process-wide cache instead.
+ /// Read and resolution errors refuse removal; cache priming and main-path
+ /// discovery decline entries they cannot resolve.
fn git_dir_at(dir: &Path) -> Option<PathBuf> {
let dot_git = dir.join(".git");
- // Follows a symlinked `.git`, as git and the subprocess fallback do.
- let file_type = std::fs::metadata(&dot_git).ok()?.file_type();
- if file_type.is_dir() {
- return canonicalize(&dot_git).ok();
- }
- if !file_type.is_file() {
- return None;
- }
- // `.git` file: `gitdir: <path>` (git writes it absolute; resolve a
- // relative form against the worktree, as `prewarm_rev_parse` does).
- let content = std::fs::read_to_string(&dot_git).ok()?;
- let gitdir = content.lines().find_map(|l| l.strip_prefix("gitdir: "))?;
- let path = PathBuf::from(gitdir.trim());
- let absolute = if path.is_relative() {
- dir.join(path)
+ let metadata = std::fs::metadata(&dot_git).ok()?;
+ let target = if metadata.is_dir() {
+ dot_git
+ } else if metadata.is_file() {
+ let content = std::fs::read(&dot_git).ok()?;
+ let path = super::git_path_from_file(content.strip_prefix(b"gitdir: ")?).ok()?;
+ if path.is_relative() {
+ dir.join(path)
+ } else {
+ path
+ }
} else {
- path
+ return None;
};
- canonicalize(&absolute).ok()
+ let path = canonicalize(target).ok()?;
+ std::fs::metadata(&path).ok()?.is_dir().then_some(path)
}
/// Get a branch handle for branch-specific operations.
@@ -1660,7 +1642,7 @@ impl Repository {
.run()
&& out.status.success()
{
- return Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()));
+ return Ok(super::git_path_from_output(&out.stdout)?);
}
if let Some(work_tree) = self.separate_git_dir_work_tree() {
@@ -1708,7 +1690,7 @@ impl Repository {
/// repository. That round trip is also why a normal repository or a
/// submodule can't misfire here on a stray `gitdir` file.
fn separate_git_dir_work_tree(&self) -> Option<PathBuf> {
- let work_tree = registration_worktree_path(&self.git_common_dir)?;
+ let work_tree = registration_worktree_path(&self.git_common_dir).ok()?;
(Self::git_dir_at(&work_tree)? == self.git_common_dir).then_some(work_tree)
}
@@ -1983,7 +1965,7 @@ impl Repository {
/// let branches = repo.run_command(&["branch", "--list"])?;
/// # Ok::<(), anyhow::Error>(())
/// ```
- pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {
+ pub fn run_command(&self, args: &[impl AsRef<OsStr>]) -> anyhow::Result<String> {
self.run_command_bounded(args, None)
}
@@ -1999,34 +1981,32 @@ impl Repository {
/// else limits how long an unreachable host takes to not answer.
pub(super) fn run_command_bounded(
&self,
- args: &[&str],
+ args: &[impl AsRef<OsStr>],
timeout: Option<std::time::Duration>,
) -> anyhow::Result<String> {
Ok(String::from_utf8_lossy(&self.run_command_bytes_bounded(args, timeout)?).into_owned())
}
/// Run a git command and return stdout without decoding paths.
- pub fn run_command_bytes(&self, args: &[&str]) -> anyhow::Result<Vec<u8>> {
+ pub fn run_command_bytes(&self, args: &[impl AsRef<OsStr>]) -> anyhow::Result<Vec<u8>> {
self.run_command_bytes_bounded(args, None)
}
fn run_command_bytes_bounded(
&self,
- args: &[&str],
+ args: &[impl AsRef<OsStr>],
timeout: Option<std::time::Duration>,
) -> anyhow::Result<Vec<u8>> {
let mut cmd = self.with_object_store_env(
Cmd::new("git")
- .args(args.iter().copied())
+ .args(args)
.current_dir(&self.discovery_path)
.context(self.logging_context()),
);
if let Some(timeout) = timeout {
cmd = cmd.timeout(timeout);
}
- let output = cmd
- .run()
- .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;
+ let output = cmd.run()?;
if !output.status.success() {
return Err(
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 88655e8b3..153525ccb 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -25,46 +25,6 @@ fn alternate_object_directory_uses_git_c_style_quoting() {
assert_eq!(quoted, "\"a;b\\n\\r\\t\\\\\\\"\"");
}
-#[test]
-fn test_parse_worktree_list() {
- let output = "worktree /path/to/main
-HEAD abcd1234
-branch refs/heads/main
-
-worktree /path/to/feature
-HEAD efgh5678
-branch refs/heads/feature
-
-";
-
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();
-
- assert_eq!(main_wt.path, PathBuf::from("/path/to/main"));
- assert_eq!(main_wt.head, "abcd1234");
- assert_eq!(main_wt.branch, Some("main".to_string()));
- assert!(!main_wt.bare);
- assert!(!main_wt.detached);
-
- assert_eq!(feature_wt.path, PathBuf::from("/path/to/feature"));
- assert_eq!(feature_wt.head, "efgh5678");
- assert_eq!(feature_wt.branch, Some("feature".to_string()));
-}
-
-#[test]
-fn test_parse_detached_worktree() {
- let output = "worktree /path/to/detached
-HEAD abcd1234
-detached
-
-";
-
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
- assert!(wt.detached);
- assert_eq!(wt.branch, None);
-}
-
#[test]
fn test_finalize_worktree_with_branch() {
// Worktree with a branch should not be modified
@@ -208,33 +168,6 @@ fn test_finalize_worktree_stale_reads_its_own_rebase() {
assert_eq!(rebasing.branch.as_deref(), Some("feature"));
}
-#[test]
-fn test_parse_locked_worktree() {
- let output = "worktree /path/to/locked
-HEAD abcd1234
-branch refs/heads/main
-locked reason for lock
-
-";
-
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
- assert_eq!(wt.locked, Some("reason for lock".to_string()));
-}
-
-#[test]
-fn test_parse_bare_worktree() {
- let output = "worktree /path/to/bare
-HEAD abcd1234
-bare
-
-";
-
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
- assert!(wt.bare);
-}
-
#[test]
fn test_parse_local_default_branch_with_prefix() {
let output = "origin/main\n";
@@ -407,36 +340,6 @@ fn test_resolved_worktree_none_branch() {
}
}
-#[test]
-fn test_worktree_locked_empty_reason() {
- let output = "worktree /path/to/locked
-HEAD abcd1234
-branch refs/heads/main
-locked
-
-";
-
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
- // Empty lock reason should still be recorded
- assert_eq!(wt.locked, Some(String::new()));
-}
-
-#[test]
-fn test_worktree_prunable() {
- let output = "worktree /path/to/prunable
-HEAD abcd1234
-detached
-prunable gitdir file points to non-existent location
-
-";
-
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
- assert!(wt.prunable.is_some());
- assert!(wt.prunable.as_ref().unwrap().contains("non-existent"));
-}
-
#[test]
fn test_parse_multiple_worktrees() {
let output = "worktree /main
@@ -457,7 +360,8 @@ detached
";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let worktrees =
+ WorktreeInfo::parse_porcelain_list_z(output.replace('\n', "\0").as_bytes()).unwrap();
let [main_wt, feature_a, feature_b, detached_wt]: [WorktreeInfo; 4] =
worktrees.try_into().unwrap();
assert_eq!(main_wt.branch, Some("main".to_string()));
@@ -2148,7 +2052,8 @@ HEAD efgh5678
detached
";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
+ let worktrees =
+ WorktreeInfo::parse_porcelain_list_z(output.replace('\n', "\0").as_bytes()).unwrap();
// The duplicated branch yields both paths, in git's listing order — the
// first is what resolution uses, the rest are what the warning surfaces.
@@ -2844,9 +2749,8 @@ fn list_worktrees_names_the_work_tree_of_a_separate_git_dir_repo() {
fn repo_path_declines_a_stale_separate_git_dir_backlink() {
// The backlink is one-way, so `repo_path` confirms it: a work tree that
// has moved away leaves a `gitdir` file naming a path that no longer
- // points back. Falling through to `parent(git_common_dir)` returns the
- // pre-#4235 answer rather than a path that doesn't hold this repository.
- use super::{Repository, canonicalize};
+ // points back. Decline it and retain the conventional parent fallback.
+ use super::Repository;
let (_tmp, store, work_tree) = build_separate_git_dir_layout();
let moved = work_tree.with_file_name("moved");
@@ -2861,11 +2765,7 @@ fn repo_path_declines_a_stale_separate_git_dir_backlink() {
assert!(out.status.success(), "git init failed");
let repo = Repository::at(&store).unwrap();
- assert_eq!(
- canonicalize(repo.repo_path().unwrap()).unwrap(),
- canonicalize(store.parent().unwrap()).unwrap(),
- "a backlink whose work tree no longer points back must not be used"
- );
+ assert_eq!(repo.repo_path().unwrap(), store.parent().unwrap());
}
#[test]
@@ -2894,3 +2794,260 @@ fn repo_path_follows_a_relative_separate_git_dir_backlink() {
"a relative backlink must resolve against the store, not the cwd"
);
}
+
+#[cfg(unix)]
+#[test]
+fn worktree_inventory_preserves_native_paths_and_lock_reasons() {
+ use std::os::unix::ffi::{OsStrExt, OsStringExt};
+
+ let mut test = TestRepo::with_initial_commit();
+ let reason = "keep this checkout\nwith its work";
+ let names = [
+ (b"checkout\nline\tback\\slash ".as_slice(), false),
+ #[cfg(target_os = "linux")]
+ (b"checkout-\xff ".as_slice(), false),
+ (b"checkout-direct".as_slice(), true),
+ ];
+ for (index, (name, direct_backlink)) in names.into_iter().enumerate() {
+ let branch = format!("native-{index}");
+ let original = test.add_worktree(&branch);
+ test.run_git(&[
+ "worktree",
+ "lock",
+ "--reason",
+ reason,
+ original.to_str().unwrap(),
+ ]);
+ let git_dir = Repository::git_dir_at(&original).unwrap();
+ let checkout = test
+ .root_path()
+ .parent()
+ .unwrap()
+ .join(std::ffi::OsString::from_vec(name.to_vec()));
+ std::fs::rename(&original, &checkout).unwrap();
+ let mut backlink = checkout.join(".git").into_os_string().into_vec();
+ backlink.push(b'\n');
+ std::fs::write(git_dir.join("gitdir"), backlink).unwrap();
+ assert_eq!(
+ super::working_tree::registration_worktree_path(&git_dir).unwrap(),
+ checkout
+ );
+ assert_eq!(Repository::git_dir_at(&checkout).unwrap(), git_dir);
+ if direct_backlink {
+ // Git accepts a direct checkout backlink, trimming trailing whitespace.
+ let mut direct = checkout.clone().into_os_string().into_vec();
+ direct.push(b'\n');
+ std::fs::write(git_dir.join("gitdir"), direct).unwrap();
+ assert_eq!(
+ super::working_tree::registration_worktree_path(&git_dir).unwrap(),
+ checkout
+ );
+ }
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ let worktrees = repo.list_worktrees().unwrap();
+ let wt = worktrees
+ .iter()
+ .find(|wt| wt.branch.as_deref() == Some(&branch))
+ .unwrap();
+ assert_eq!(
+ wt.path.as_os_str().as_bytes(),
+ checkout.as_os_str().as_bytes()
+ );
+ assert_eq!(wt.locked.as_deref(), Some(reason));
+ assert!(wt.path.join(".git").is_file());
+ let working_tree = repo.worktree_at(&checkout);
+ let info = working_tree.prewarm_info().unwrap();
+ assert!(info.is_inside);
+ assert_eq!(info.root.unwrap(), checkout);
+ assert_eq!(working_tree.git_dir().unwrap(), git_dir);
+ assert_eq!(
+ working_tree.branch().unwrap().as_deref(),
+ Some(branch.as_str())
+ );
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn git_dir_at_declines_unusable_entries() {
+ use nix::{sys::stat::Mode, unistd::mkfifo};
+
+ let directory = crate::testing::test_tempdir();
+ let entry = directory.path().join(".git");
+ for content in [b"gitdir: \r\n".as_slice(), b"not a gitfile".as_slice()] {
+ std::fs::write(&entry, content).unwrap();
+ assert!(Repository::git_dir_at(directory.path()).is_none());
+ }
+ std::fs::remove_file(&entry).unwrap();
+ // Reading a FIFO would block; discovery must reject it from its file type.
+ mkfifo(&entry, Mode::S_IRUSR | Mode::S_IWUSR).unwrap();
+ assert!(Repository::git_dir_at(directory.path()).is_none());
+}
+
+#[cfg(unix)]
+#[test]
+fn git_dir_at_preserves_native_gitfile_target() {
+ use std::os::unix::ffi::OsStrExt;
+
+ let test = TestRepo::with_initial_commit();
+ let target = test
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("store\twith\nwhitespace ");
+ let neighbor = test
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("store\twith\nwhitespace");
+ let child = test.root_path().parent().unwrap().join("gitfile");
+ let output = test
+ .git_command()
+ .arg("clone")
+ .arg(test.root_path())
+ .arg(&child)
+ .run()
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+ std::fs::rename(child.join(".git"), &target).unwrap();
+ std::fs::create_dir(&neighbor).unwrap();
+ let output = test
+ .git_command()
+ .current_dir(&neighbor)
+ .args(["init", "--bare"])
+ .run()
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+ assert_ne!(
+ dunce::canonicalize(&target).unwrap(),
+ dunce::canonicalize(&neighbor).unwrap()
+ );
+ // CRLF is a Git terminator; the trailing spaces belong to the path.
+ let mut content = b"gitdir: ".to_vec();
+ content.extend_from_slice(target.as_os_str().as_bytes());
+ content.extend_from_slice(b"\r\n");
+ std::fs::write(child.join(".git"), content).unwrap();
+ assert_eq!(
+ Repository::git_dir_at(&child).unwrap(),
+ dunce::canonicalize(&target).unwrap()
+ );
+ let output = test
+ .git_command()
+ .current_dir(&child)
+ .args(["rev-parse", "--absolute-git-dir"])
+ .run()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "Git must accept the real gitfile: {output:?}"
+ );
+ let mut expected = dunce::canonicalize(target)
+ .unwrap()
+ .as_os_str()
+ .as_bytes()
+ .to_vec();
+ expected.push(b'\n');
+ assert_eq!(output.stdout, expected);
+}
+
+#[cfg(unix)]
+#[test]
+fn prewarm_preserves_native_common_directory_paths() {
+ use std::os::unix::ffi::OsStringExt;
+
+ let seed = TestRepo::with_initial_commit();
+ let names = [
+ b"bare\ntrue\nstore\nHEAD".as_slice(),
+ b"bare ".as_slice(),
+ #[cfg(target_os = "linux")]
+ b"bare-\xff ".as_slice(),
+ ];
+ for name in names {
+ let directory = crate::testing::test_tempdir();
+ let prefix = directory.path().join("bare");
+ let initial = directory.path().join("initial");
+ for target in [&prefix, &initial] {
+ seed.run_git(&[
+ "clone",
+ "--bare",
+ seed.root_path().to_str().unwrap(),
+ target.to_str().unwrap(),
+ ]);
+ }
+ let store = directory
+ .path()
+ .join(std::ffi::OsString::from_vec(name.to_vec()));
+ std::fs::rename(&initial, &store).unwrap();
+ let child = store.join("subdirectory");
+ std::fs::create_dir(&child).unwrap();
+ let expected = dunce::canonicalize(&store).unwrap();
+ assert_ne!(expected, dunce::canonicalize(&prefix).unwrap());
+ for discovery in [&store, &child] {
+ Repository::prewarm_at(discovery);
+ let repo = Repository::at(discovery).unwrap();
+ assert_eq!(repo.git_common_dir(), expected);
+ assert!(repo.is_bare().unwrap());
+ assert_eq!(repo.repo_path().unwrap(), expected);
+ assert_eq!(
+ repo.current_worktree().root().unwrap(),
+ dunce::canonicalize(discovery).unwrap()
+ );
+ }
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn repo_path_preserves_local_core_worktree_path_bytes() {
+ use std::os::unix::ffi::OsStrExt;
+
+ let seed = TestRepo::with_initial_commit();
+ let directory = crate::testing::test_tempdir();
+ let main = directory.path().join("configured main\n\t ");
+ let store = directory.path().join("store");
+ seed.run_git(&[
+ "clone",
+ "--separate-git-dir",
+ store.to_str().unwrap(),
+ seed.root_path().to_str().unwrap(),
+ main.to_str().unwrap(),
+ ]);
+ seed.run_git_in(&store, &["config", "core.worktree", main.to_str().unwrap()]);
+ let oracle = seed
+ .git_command()
+ .args(["rev-parse", "--show-toplevel"])
+ .current_dir(&store)
+ .run()
+ .unwrap();
+ assert!(oracle.status.success());
+ let expected = dunce::canonicalize(&main).unwrap();
+ assert_eq!(
+ oracle.stdout.strip_suffix(b"\n").unwrap(),
+ expected.as_os_str().as_bytes()
+ );
+ let repo = Repository::at(&main).unwrap();
+ assert_eq!(repo.repo_path().unwrap(), expected);
+}
+
+/// Git retains native bytes in a registration id as well as its checkout path.
+#[cfg(target_os = "linux")]
+#[test]
+fn stale_worktree_work_preserves_native_registration_arguments() {
+ use std::os::unix::ffi::OsStringExt;
+
+ let test = TestRepo::with_initial_commit();
+ let checkout = test
+ .home_path()
+ .join(std::ffi::OsString::from_vec(b"feature-\xff".to_vec()));
+ let output = test
+ .git_command()
+ .args(["worktree", "add", "-b", "feature"])
+ .arg(&checkout)
+ .run()
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+ std::fs::remove_dir_all(&checkout).unwrap();
+ let repo = Repository::at(test.root_path()).unwrap();
+ assert_eq!(repo.stale_worktree_work(&checkout).unwrap(), None);
+}
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index c9ead5447..72bef8fd1 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -188,15 +188,19 @@ fn sequencer_operation(git_dir: &Path) -> Option<InProgressOperation> {
/// no longer exist — the case the caller is usually asking about, and the path it
/// then shows the user. Normalizing rewrites spellings only, so it cannot make
/// two directories compare equal.
-pub(super) fn registration_worktree_path(registration: &Path) -> Option<PathBuf> {
- let content = std::fs::read_to_string(registration.join("gitdir")).ok()?;
- let recorded = PathBuf::from(content.trim());
- let absolute = if recorded.is_relative() {
+pub(super) fn registration_worktree_path(registration: &Path) -> std::io::Result<PathBuf> {
+ let content = std::fs::read(registration.join("gitdir"))?;
+ let recorded = super::super::git_path_from_file(&content)?;
+ let mut absolute = if recorded.is_relative() {
registration.join(recorded)
} else {
recorded
};
- absolute.parent().map(canonicalize_with_parents)
+ // Git accepts a checkout path directly or its `.git` entry.
+ if absolute.file_name() == Some(std::ffi::OsStr::new(".git")) {
+ absolute.pop();
+ }
+ Ok(canonicalize_with_parents(&absolute))
}
/// The git operation the worktree whose git dir is `git_dir` is partway
@@ -256,7 +260,8 @@ pub(super) fn operation_in_progress_at(git_dir: &Path) -> Option<InProgressOpera
///
/// When `is_inside` is false every other field is `None` — nothing else ran.
/// When `is_inside` is true, `root` lands unconditionally and `git_dir` lands
-/// unless canonicalization failed. `current_branch` is only populated when
+/// unless canonicalization failed or the batch framing was ambiguous.
+/// `current_branch` is only populated when
/// the whole batch succeeded; on unborn HEAD it stays `None` and the
/// per-accessor fallback paths handle the symbolic-ref lookup.
#[derive(Debug, Clone, Default)]
@@ -267,11 +272,11 @@ pub struct WorkingTreeGitInfo {
/// Canonicalized top-level directory. Always `Some` when `is_inside`.
pub root: Option<PathBuf>,
/// Canonicalized git directory (may differ from common dir in linked
- /// worktrees). `Some` when `is_inside` and canonicalization succeeded.
+ /// worktrees). `None` when canonicalization or batch framing failed.
pub git_dir: Option<PathBuf>,
/// Current branch: outer `Some(Some(name))` on a branch, `Some(None)`
/// detached. `None` when HEAD was unresolvable (unborn branch) or outside
- /// a work tree.
+ /// a work tree, or the batch framing was ambiguous.
pub current_branch: Option<Option<String>>,
}
@@ -402,7 +407,7 @@ impl<'a> WorkingTree<'a> {
///
/// `--show-toplevel` and `--git-dir` succeed even on unborn branches —
/// rev-parse prints them before HEAD errors — so `root`/`git_dir` are
- /// cached whenever we're inside a work tree. `current_branch` is only
+ /// cached unless a newline makes the batch framing ambiguous. `current_branch` is only
/// populated when the whole batch succeeded, so [`Self::branch`]'s
/// `symbolic-ref` fallback still handles genuine unborn HEADs. On unborn
/// the symbolic-full-name line lands as a fallback literal "HEAD", which
@@ -444,60 +449,60 @@ impl<'a> WorkingTree<'a> {
"--symbolic-full-name",
"HEAD",
])?;
- let stdout = String::from_utf8_lossy(&output.stdout);
- let mut lines = stdout.lines();
-
- let is_inside = lines.next().is_some_and(|s| s.trim() == "true");
+ let is_inside = output.stdout.starts_with(b"true\n");
if !is_inside {
return Ok(WorkingTreeGitInfo::default());
}
-
- // `root` and `git_dir` are safe to cache whenever their lines landed,
- // because any failure in the batch is from HEAD — which comes after.
- // `--show-toplevel` always emits a line when `is_inside=true`; if
- // canonicalize of that line fails (e.g., pathological filesystem
- // state), fall back to `self.path` which is already canonicalized by
- // `worktree_at` and guaranteed inside the work tree.
- let raw_toplevel = lines.next().unwrap_or("").trim();
- let canonical = canonicalize(PathBuf::from(raw_toplevel)).unwrap_or(self.path.clone());
- super::WORKTREE_ROOTS
- .entry(self.path.clone())
- .or_insert_with(|| canonical.clone());
- let root = Some(canonical);
-
- let git_dir = lines.next().and_then(|raw| {
- let path = PathBuf::from(raw.trim());
+ let Some(fields) = super::rev_parse_fields(&output, 4) else {
+ return Ok(WorkingTreeGitInfo {
+ is_inside,
+ root: Some(self.root()?),
+ ..WorkingTreeGitInfo::default()
+ });
+ };
+ let mut fields = fields.into_iter().skip(1);
+ let root = if let Some(root) = fields
+ .next()
+ .and_then(|raw| canonicalize(super::git_path_from_bytes(raw).ok()?).ok())
+ {
+ super::WORKTREE_ROOTS
+ .entry(self.path.clone())
+ .or_insert_with(|| root.clone());
+ root
+ } else {
+ self.root()?
+ };
+ let git_dir = fields.next().and_then(|raw| {
+ let path = super::git_path_from_bytes(raw).ok()?;
let absolute = if path.is_relative() {
- self.path.join(&path)
+ self.path.join(path)
} else {
path
};
- let resolved = canonicalize(&absolute).ok()?;
+ let resolved = canonicalize(absolute).ok()?;
super::GIT_DIRS
.entry(self.path.clone())
.or_insert_with(|| resolved.clone());
Some(resolved)
});
-
- // The `--symbolic-full-name HEAD` line is only trustworthy when the
- // batch succeeded. On unborn HEAD the line lands but is the literal
- // "HEAD" fallback — we can't tell that from detached HEAD without the
- // exit status.
let current_branch = if output.status.success() {
- lines.next().map(|raw| {
- let branch = raw.trim().strip_prefix("refs/heads/").map(str::to_owned);
- super::CURRENT_BRANCHES
- .entry(self.path.clone())
- .or_insert_with(|| branch.clone());
- branch
- })
+ fields
+ .next()
+ .and_then(|raw| std::str::from_utf8(raw).ok())
+ .map(|raw| {
+ let branch = raw.strip_prefix("refs/heads/").map(str::to_owned);
+ super::CURRENT_BRANCHES
+ .entry(self.path.clone())
+ .or_insert_with(|| branch.clone());
+ branch
+ })
} else {
None
};
Ok(WorkingTreeGitInfo {
is_inside: true,
- root,
+ root: Some(root),
git_dir,
current_branch,
})
@@ -645,9 +650,9 @@ impl<'a> WorkingTree<'a> {
match super::WORKTREE_ROOTS.entry(self.path.clone()) {
Entry::Occupied(e) => Ok(e.get().clone()),
Entry::Vacant(e) => match self
- .run_command(&["rev-parse", "--show-toplevel"])
+ .run_command_bytes(&["rev-parse", "--show-toplevel"])
.ok()
- .map(|s| PathBuf::from(s.trim()))
+ .and_then(|bytes| super::super::git_path_from_output(&bytes).ok())
.and_then(|p| canonicalize(&p).ok())
{
Some(root) => Ok(e.insert(root).clone()),
@@ -665,7 +670,7 @@ impl<'a> WorkingTree<'a> {
match super::GIT_DIRS.entry(self.path.clone()) {
Entry::Occupied(e) => Ok(e.get().clone()),
Entry::Vacant(e) => {
- let stdout = self.run_command(&["rev-parse", "--git-dir"])?;
+ let stdout = self.run_command_bytes(&["rev-parse", "--git-dir"])?;
Ok(e.insert(self.resolve_git_dir(&stdout)?).clone())
}
}
@@ -700,7 +705,7 @@ impl<'a> WorkingTree<'a> {
if !output.status.success() {
return Err(CommandError::from_failed_output("git", &ARGS, &output).into());
}
- let git_dir = wt.resolve_git_dir(&String::from_utf8_lossy(&output.stdout))?;
+ let git_dir = wt.resolve_git_dir(&output.stdout)?;
Ok(super::GIT_DIRS
.entry(wt.path.clone())
.or_insert(git_dir)
@@ -710,8 +715,8 @@ impl<'a> WorkingTree<'a> {
}
/// Canonicalize `git rev-parse --git-dir` output run in this worktree.
- fn resolve_git_dir(&self, stdout: &str) -> anyhow::Result<PathBuf> {
- let path = PathBuf::from(stdout.trim());
+ fn resolve_git_dir(&self, stdout: &[u8]) -> anyhow::Result<PathBuf> {
+ let path = super::super::git_path_from_output(stdout)?;
// Always canonicalize to resolve symlinks (e.g., /var -> /private/var on macOS)
let absolute_path = if path.is_relative() {
@@ -917,9 +922,10 @@ impl<'a> WorkingTree<'a> {
// different repository, or its registration here has lost its `gitdir`
// file.
let registrations = common_dir.join("worktrees");
- let registration =
- git_dir.filter(|git_dir| git_dir.parent() == Some(registrations.as_path()));
- let occupant_registered_at = registration.as_deref().and_then(registration_worktree_path);
+ let registration = git_dir.filter(|dir| dir.parent() == Some(registrations.as_path()));
+ let occupant_registered_at = registration
+ .as_deref()
+ .and_then(|entry| registration_worktree_path(entry).ok());
if let Some(registration) = registration
&& occupant_registered_at
.as_deref()
@@ -1410,7 +1416,7 @@ impl TempIndex {
pub(super) fn command<I, S>(&self, args: I) -> Cmd
where
I: IntoIterator<Item = S>,
- S: Into<String>,
+ S: AsRef<std::ffi::OsStr>,
{
let command = Cmd::new("git")
.args(args)
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index d82e39262..162063c60 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -1,6 +1,7 @@
//! Worktree management operations for Repository.
use std::collections::HashSet;
+use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
@@ -40,9 +41,9 @@ impl Repository {
.get_or_try_init(|| {
let stdout = {
let _registry = self.worktree_registry_read();
- self.run_command(&["worktree", "list", "--porcelain"])?
+ self.run_command_bytes(&["worktree", "list", "--porcelain", "-z"])?
};
- let raw_worktrees = WorktreeInfo::parse_porcelain_list(&stdout)?;
+ let raw_worktrees = WorktreeInfo::parse_porcelain_list_z(&stdout)?;
let mut worktrees: Vec<_> =
raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();
@@ -298,10 +299,9 @@ impl Repository {
// The registration is a git dir in its own right, so its index is read
// against its `HEAD` without the working tree git can no longer find.
// Both commands answer with exit 0 or 1; anything else is a failure.
- let registration_arg = registration.to_string_lossy();
let git = |args: &[&str]| -> anyhow::Result<(bool, String)> {
- let mut all = vec!["--git-dir", registration_arg.as_ref()];
- all.extend_from_slice(args);
+ let mut all = vec![OsStr::new("--git-dir"), registration.as_os_str()];
+ all.extend(args.iter().map(OsStr::new));
let output = self
.with_object_store_env(
Cmd::new("git")
@@ -309,8 +309,7 @@ impl Repository {
.context(path_to_logging_context(path))
.scrub_git_discovery_env(),
)
- .run()
- .with_context(|| format!("Failed to execute: git {}", all.join(" ")))?;
+ .run()?;
match output.status.code() {
Some(0 | 1) => Ok((
output.status.success(),
@@ -340,7 +339,7 @@ impl Repository {
.filter_map(Result::ok)
.map(|entry| entry.path())
.find_map(|registration| {
- let recorded = registration_worktree_path(&registration)?;
+ let recorded = registration_worktree_path(&registration).ok()?;
paths_match(&recorded, path).then_some((registration, recorded))
})
.with_context(|| format!("No worktree registered @ {}", format_path_for_display(path)))
@@ -376,24 +375,16 @@ impl Repository {
/// user-requested `force`, the user opted into destructive removal, so no
/// re-check.)
pub fn remove_worktree(&self, path: &std::path::Path, force: bool) -> anyhow::Result<()> {
- let path_str = path.to_str().ok_or_else(|| {
- anyhow::Error::from(GitError::Other {
- message: format!(
- "Worktree path contains invalid UTF-8: {}",
- format_path_for_display(path)
- ),
- })
- })?;
let use_force = if force {
true
} else {
self.worktree_at(path).has_initialized_submodules()?
};
- let mut args = vec!["worktree", "remove"];
+ let mut args = vec![OsStr::new("worktree"), OsStr::new("remove")];
if use_force {
- args.push("--force");
+ args.push(OsStr::new("--force"));
}
- args.push(path_str);
+ args.push(path.as_os_str());
// The synthesized-force cleanliness check and destructive command are
// one critical section. If this waited for another registry teardown
diff --git a/src/git/test.rs b/src/git/test.rs
index d9915e62a..19a55736b 100644
--- a/src/git/test.rs
+++ b/src/git/test.rs
@@ -7,43 +7,31 @@ use super::{DefaultBranchName, LineDiff, WorktreeInfo};
use insta::assert_debug_snapshot;
use rstest::rstest;
-/// Helper to parse a single worktree from porcelain output
-fn parse_single(input: &str) -> WorktreeInfo {
- let list = WorktreeInfo::parse_porcelain_list(input).expect("parse ok");
- assert_eq!(list.len(), 1);
- list.into_iter().next().unwrap()
-}
-
#[test]
-fn test_parse_worktree_list_no_trailing_blank_line() {
- // Bug hypothesis: If output doesn't end with blank line,
- // the last worktree might not be added.
- // The end-of-input handling in parse_porcelain_list should cover this.
- let output = "worktree /path/to/repo1\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/repo2\nHEAD def456\nbranch refs/heads/dev";
- let result = WorktreeInfo::parse_porcelain_list(output);
+fn git_path_decoders_preserve_content_and_distinguish_terminators() {
+ use super::{git_path_from_file, git_path_from_output};
+ use std::path::Path;
- assert!(result.is_ok());
- let worktrees = result.unwrap();
-
- // Should have 2 worktrees - code handles this with "if let Some(wt) = current" at end
assert_eq!(
- worktrees.len(),
- 2,
- "Should parse both worktrees even without trailing blank line"
+ git_path_from_output(b"store\nwith spaces \t\n").unwrap(),
+ Path::new("store\nwith spaces \t")
+ );
+ assert_eq!(
+ git_path_from_file(b"store\nwith spaces \t\r\n").unwrap(),
+ Path::new("store\nwith spaces \t")
+ );
+ assert_eq!(
+ git_path_from_output(b"unterminated").unwrap_err().kind(),
+ std::io::ErrorKind::InvalidData
);
}
-#[test]
-fn test_parse_worktree_list_multiple_worktrees() {
- let output = "worktree /path/to/main\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/feature\nHEAD def456\nbranch refs/heads/feature\ndetached\n\n";
- let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
- let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();
-
- assert_eq!(main_wt.branch, Some("main".to_string()));
- assert!(!main_wt.detached);
-
- assert_eq!(feature_wt.branch, Some("feature".to_string()));
- assert!(feature_wt.detached);
+/// Helper to parse a single worktree from porcelain output
+fn parse_single(input: &str) -> WorktreeInfo {
+ let list = WorktreeInfo::parse_porcelain_list_z(input.replace('\n', "\0").as_bytes())
+ .expect("parse ok");
+ assert_eq!(list.len(), 1);
+ list.into_iter().next().unwrap()
}
#[rstest]
@@ -54,7 +42,7 @@ fn test_parse_worktree_list_multiple_worktrees() {
)]
#[case::branch_missing_ref("worktree /path/to/repo\nHEAD abc123\nbranch\n\n", "missing ref")]
fn test_parse_worktree_list_error_cases(#[case] input: &str, #[case] expected_message: &str) {
- let result = WorktreeInfo::parse_porcelain_list(input);
+ let result = WorktreeInfo::parse_porcelain_list_z(input.replace('\n', "\0").as_bytes());
assert!(result.is_err(), "Parsing should fail");
let err = result.unwrap_err();
@@ -193,12 +181,6 @@ fn test_line_diff_from_shortstat(
assert_eq!(diff.deleted, expected_deleted);
}
-#[test]
-fn snapshot_parse_worktree_list_empty_output() {
- let result = WorktreeInfo::parse_porcelain_list("").expect("parse ok");
- assert_debug_snapshot!(result, @"[]");
-}
-
#[test]
fn snapshot_parse_worktree_list_missing_head() {
let wt = parse_single("worktree /path/to/repo\nbranch refs/heads/main\n\n");
@@ -238,28 +220,6 @@ fn snapshot_parse_worktree_list_locked_with_empty_reason() {
"#);
}
-#[test]
-fn snapshot_parse_worktree_list_locked_with_reason() {
- let wt = parse_single(
- "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked working on it\n\n",
- );
- assert_debug_snapshot!(wt, @r#"
- WorktreeInfo {
- path: "/path/to/repo",
- head: "abc123",
- branch: Some(
- "main",
- ),
- bare: false,
- detached: false,
- locked: Some(
- "working on it",
- ),
- prunable: None,
- }
- "#);
-}
-
#[test]
fn snapshot_parse_worktree_list_prunable_empty() {
let wt =
@@ -299,76 +259,6 @@ fn snapshot_parse_worktree_list_fields_before_worktree() {
"#);
}
-#[test]
-fn snapshot_parse_worktree_list_bare_repository() {
- let wt = parse_single("worktree /path/to/repo\nbare\n\n");
- assert_debug_snapshot!(wt, @r#"
- WorktreeInfo {
- path: "/path/to/repo",
- head: "",
- branch: None,
- bare: true,
- detached: false,
- locked: None,
- prunable: None,
- }
- "#);
-}
-
-#[test]
-fn snapshot_parse_worktree_list_detached_head() {
- let wt = parse_single("worktree /path/to/repo\nHEAD abc123\ndetached\n\n");
- assert_debug_snapshot!(wt, @r#"
- WorktreeInfo {
- path: "/path/to/repo",
- head: "abc123",
- branch: None,
- bare: false,
- detached: true,
- locked: None,
- prunable: None,
- }
- "#);
-}
-
-#[test]
-fn snapshot_parse_worktree_list_branch_with_refs_prefix() {
- let wt = parse_single(
- "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/feature/nested/branch\n\n",
- );
- assert_debug_snapshot!(wt, @r#"
- WorktreeInfo {
- path: "/path/to/repo",
- head: "abc123",
- branch: Some(
- "feature/nested/branch",
- ),
- bare: false,
- detached: false,
- locked: None,
- prunable: None,
- }
- "#);
-}
-
-#[test]
-fn snapshot_parse_worktree_list_branch_without_refs_prefix() {
- let wt = parse_single("worktree /path/to/repo\nHEAD abc123\nbranch main\n\n");
- assert_debug_snapshot!(wt, @r#"
- WorktreeInfo {
- path: "/path/to/repo",
- head: "abc123",
- branch: Some(
- "main",
- ),
- bare: false,
- detached: false,
- locked: None,
- prunable: None,
- }
- "#);
-}
-
#[test]
fn snapshot_parse_worktree_list_unknown_attributes() {
let wt = parse_single("worktree /path/to/repo\nHEAD abc123\nfutureattr somevalue\n\n");
diff --git a/src/main.rs b/src/main.rs
index 78a5e3ddc..62440e12c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -960,6 +960,17 @@ fn dispatch_command(
Commands::Switch(args) => handle_switch_command(args, yes),
Commands::Remove(args) => handle_remove_command(args, yes),
Commands::Merge(args) => handle_merge_command(args, yes),
+ Commands::InternalDeleteBranchIfSafe {
+ branch,
+ target,
+ expected_tip,
+ force_delete,
+ } => output::handlers::delete_branch_from_detached_fallback(
+ &branch,
+ &target,
+ expected_tip.as_deref(),
+ force_delete,
+ ),
// `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.rs
index 20d914439..2b8dec8a5 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1,10 +1,12 @@
//! Output handlers for worktree operations using the global output context
+use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use anstyle::AnsiColor;
+use anyhow::Context as _;
use color_print::cformat;
use worktrunk::shell_exec::{Cmd, shell_cwd};
use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};
@@ -14,7 +16,7 @@ use crate::commands::command_executor::FailureStrategy;
use crate::commands::hook_plan::{ApprovedHookPlan, execute_planned_hook, register_planned};
use crate::commands::hooks::HookAnnouncer;
use crate::commands::process::{
- HookLog, InternalOp, build_remove_command, build_remove_command_staged,
+ HookLog, InternalOp, build_remove_command, build_remove_paths_command,
build_remove_placeholder_command, spawn_detached,
};
use crate::commands::template_vars::TemplateVars;
@@ -30,7 +32,8 @@ use worktrunk::git::Repository;
use worktrunk::git::path_dir_name;
use worktrunk::git::{
BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemoveOptions,
- execute_branch_deletion, remove_worktree_with_cleanup, stage_worktree_removal,
+ delete_branch_if_safe, execute_branch_deletion, remove_worktree_with_cleanup,
+ stage_worktree_removal,
};
use worktrunk::path::{canonicalize_with_parents, format_path_for_display};
use worktrunk::progress::{Progress, format_stats_paren};
@@ -133,7 +136,7 @@ enum BackgroundRemovalPlan {
/// The worktree has been removed and trash cleanup scheduling was attempted.
Staged(anyhow::Result<()>),
/// The detached command still has to remove the worktree.
- Deferred(String),
+ Deferred(Vec<OsString>),
CompletedSynchronously,
}
@@ -143,30 +146,6 @@ struct BackgroundRemovalOutcome {
branch_fate: anyhow::Result<BranchFate>,
}
-/// Print `live` when a complete porcelain record names the requested branch
-/// and is either non-prunable or locked.
-///
-/// The caller checks both this script's exit status and its exact output:
-/// an empty successful result means no live checkout, `live` means retain, and
-/// any tool failure or unexpected output fails closed. Paragraph mode (`RS =
-/// ""`) keeps each worktree's `branch`, `prunable`, and `locked` fields
-/// associated. A lock wins if a record ever carries both status fields.
-const LIVE_BRANCH_WORKTREE_AWK: &str = r#"BEGIN { RS = ""; FS = "\n" }
-{
- has_branch = 0
- prunable = 0
- locked = 0
- for (i = 1; i <= NF; i++) {
- if ($i == worktrunk_wanted_branch) has_branch = 1
- if ($i == "prunable" || index($i, "prunable ") == 1) prunable = 1
- if ($i == "locked" || index($i, "locked ") == 1) locked = 1
- }
- if (has_branch && (!prunable || locked)) {
- print "live"
- exit
- }
-}"#;
-
/// Spawn background worktree removal: clean-check, stop fsmonitor,
/// rename-then-prune, spawn detached rm.
///
@@ -175,7 +154,7 @@ const LIVE_BRANCH_WORKTREE_AWK: &str = r#"BEGIN { RS = ""; FS = "\n" }
/// after. An outer error means removal was neither completed nor scheduled;
/// the inner result reports branch deletion or cleanup scheduling after removal,
/// so callers register teardown before propagating it. The fate is known synchronously
-/// except on the detached fallback, whose CAS tail runs after this process exits.
+/// except on the detached fallback, whose branch-deletion child runs after this process exits.
fn spawn_background_removal(
repo: &Repository,
main_path: &Path,
@@ -183,7 +162,7 @@ fn spawn_background_removal(
log_label: &str,
fallback_mode: BackgroundFallbackMode,
) -> anyhow::Result<anyhow::Result<BranchFate>> {
- let spawn = |remove_command: &str, operation: InternalOp| {
+ let spawn = |remove_command: &[OsString], operation: InternalOp| {
spawn_detached(
repo,
main_path,
@@ -224,7 +203,7 @@ fn execute_instant_removal_or_fallback(
repo: &Repository,
removal: &BackgroundRemoval<'_>,
fallback_mode: BackgroundFallbackMode,
- spawn_cleanup: impl Fn(&str, InternalOp) -> anyhow::Result<()>,
+ spawn_cleanup: impl Fn(&[OsString], InternalOp) -> anyhow::Result<()>,
) -> anyhow::Result<BackgroundRemovalOutcome> {
let BackgroundRemoval {
worktree_path,
@@ -250,7 +229,7 @@ fn execute_instant_removal_or_fallback(
// Trash cleanup is independent of branch deletion. Start it before a
// deletion lock wait, and still attempt deletion if scheduling fails.
let cleanup = spawn_cleanup(
- &build_remove_command_staged(&staged_path),
+ &build_remove_paths_command([&staged_path]),
InternalOp::Remove,
);
// Delete branch synchronously now that prune has removed the worktree metadata.
@@ -310,72 +289,44 @@ fn execute_instant_removal_or_fallback(
});
}
- // Fallback: cross-filesystem, permissions, Windows file locking, etc.
- // Use legacy git worktree remove which handles these cases. For
- // safe-delete, decide here whether to append a branch-deletion step:
- // run worktrunk's full integration check now, and if the branch is
- // integrated, append an atomic `git update-ref -d <ref> <sha>` keyed
- // to the snapshotted SHA. This matches the fast path and the
- // synchronous fallback — same `BranchDeletionMode::SafeDelete` input
- // yields the same semantics (squash-merged, ancestor, patch-id-match
- // all accepted), and the CAS protects against tip movement between
- // the foreground check and the detached delete. Force-delete keeps
- // the unconditional `git branch -D` shell tail.
- let (command, fate) = match (branch_name, deletion_mode) {
- (Some(branch), BranchDeletionMode::ForceDelete) => (
- build_remove_command(
- worktree_path,
- Some(branch),
- force_worktree,
- changed_directory,
- ),
- BranchFate::Deferred,
- ),
- (Some(branch), BranchDeletionMode::SafeDelete) => {
- let cas_tail = build_cas_branch_delete_tail(repo, branch, target_branch);
- // No tail means the foreground integration check declined (or
- // couldn't run): the detached process won't touch the branch,
- // so its survival is known here, not deferred — and when the
- // planner promised deletion, the progress message already said
- // "worktree & branch", so the survival gets the same
- // correction the fast path emits. (A check that errored
- // collapses into this: it couldn't confirm integration, which
- // is the message's effective claim.)
- let fate = match cas_tail {
- Some(_) => BranchFate::Deferred,
- None => {
- warn_if_branch_retained(
- branch,
- &Ok(BranchDeletionResult {
- outcome: BranchDeletionOutcome::NotDeleted,
- integration_target: target_branch.unwrap_or("HEAD").to_string(),
- }),
- planner_expected_retention,
- );
- // Same `NotDeleted` the warning was built from: the
- // foreground check declined, so the branch survives
- // unmerged as far as anything downstream can tell.
- BranchFate::Retained(RetainedReason::Unmerged)
- }
- };
- (
- build_remove_command_with_tail(
- worktree_path,
- force_worktree,
- changed_directory,
- cas_tail.as_deref(),
- ),
- fate,
- )
- }
- _ => (
- build_remove_command(worktree_path, None, force_worktree, changed_directory),
- BranchFate::NotAttempted,
- ),
+ // Fallback: Git handles cross-filesystem moves and file locking.
+ // Safe deletion is scheduled only for an integrated branch. The Rust
+ // child retains a changed tip, then rechecks integration and live topology
+ // before CAS. Force uses the same child, skipping integration.
+ let (tail, fate) = match branch_name.filter(|_| !deletion_mode.should_keep()) {
+ Some(branch) => match build_branch_delete_tail(
+ repo,
+ branch,
+ target_branch,
+ deletion_mode.is_force(),
+ ) {
+ Ok(Some(tail)) => (Some(tail), Ok(BranchFate::Deferred)),
+ Ok(None) => {
+ warn_if_branch_retained(
+ branch,
+ &Ok(BranchDeletionResult {
+ outcome: BranchDeletionOutcome::NotDeleted,
+ integration_target: target_branch.unwrap_or("HEAD").to_string(),
+ }),
+ planner_expected_retention,
+ );
+ (None, Ok(BranchFate::Retained(RetainedReason::Unmerged)))
+ }
+ // Removal is independent of branch deletion. Preserve the
+ // branch error after arranging removal, as on the fast path.
+ Err(error) => (None, Err(error)),
+ },
+ None => (None, Ok(BranchFate::NotAttempted)),
};
+ let command = build_remove_command(
+ worktree_path,
+ force_worktree,
+ changed_directory,
+ tail.as_deref(),
+ );
Ok(BackgroundRemovalOutcome {
plan: BackgroundRemovalPlan::Deferred(command),
- branch_fate: Ok(fate),
+ branch_fate: fate,
})
}
}
@@ -466,64 +417,82 @@ fn warn_if_branch_retained(
}
}
-/// Compute the safe-delete branch-deletion shell tail for the Detached
-/// fallback path.
-///
-/// Captures a fresh snapshot, runs the same `integration_reason` check the
-/// fast path uses, and — if the branch is integrated — returns a fail-closed
-/// topology guard followed by atomic
-/// `git update-ref -d refs/heads/<branch> <expected-sha>`. The detached process
-/// re-reads `git worktree list --porcelain` after removing the original
-/// worktree and skips deletion if any non-prunable worktree now holds the
-/// branch; stale `prunable` records do not strand it. The tail is joined to
-/// `git worktree remove` with `&&`, so the exact target's registration is
-/// already gone before this guard runs; every same-branch record that remains
-/// belongs to a different worktree. The CAS then protects against tip movement.
-/// The detached executor provides POSIX `sh` on Unix and requires Git Bash on
-/// Windows, so the record-aware `awk` guard is available on both paths.
-///
-/// Returns `None` when the branch is not integrated, when the snapshot
-/// doesn't carry the branch SHA, or when the snapshot/integration call
-/// errors — all "don't delete" outcomes that preserve the pre-CAS detached
-/// behavior of skipping branch deletion.
-fn build_cas_branch_delete_tail(
+/// Build the Rust branch-deletion child for the detached removal fallback.
+///
+/// Safe deletion captures the integrated tip and target commit for the child.
+/// The child retains a moved tip and rechecks live checkout ownership. Force
+/// skips the integration and captured-tip gates.
+/// Neither paths nor worktree records are parsed by the shell.
+fn build_branch_delete_tail(
repo: &Repository,
branch: &str,
target_branch: Option<&str>,
-) -> Option<String> {
- use shell_escape::unix::escape;
-
+ force_delete: bool,
+) -> anyhow::Result<Option<Vec<OsString>>> {
let target = target_branch.unwrap_or("HEAD");
- let snapshot = repo.capture_refs().ok()?;
- let (_effective_target, reason) = repo.integration_reason(&snapshot, branch, target).ok()?;
- reason?;
- let expected_sha = snapshot.local_branch(branch)?.commit_sha.clone();
-
- let ref_name = format!("refs/heads/{branch}");
- let branch_line = format!("branch {ref_name}");
- let branch_line_escaped = escape(branch_line.as_str().into());
- let ref_escaped = escape(ref_name.as_str().into());
- let sha_escaped = escape(expected_sha.as_str().into());
- Some(format!(
- "worktrunk_worktrees=$(git worktree list --porcelain) && {{ worktrunk_live_checkout=$(printf '%s\\n' \"$worktrunk_worktrees\" | awk -v worktrunk_wanted_branch={branch_line_escaped} '{LIVE_BRANCH_WORKTREE_AWK}') && {{ if [ \"$worktrunk_live_checkout\" = live ]; then :; elif [ -z \"$worktrunk_live_checkout\" ]; then git update-ref -d {ref_escaped} {sha_escaped}; else false; fi; }}; }}"
- ))
+ let mut expected_tip = None;
+ let target = if force_delete {
+ target.to_string()
+ } else {
+ let snapshot = repo.capture_refs()?;
+ let (effective_target, reason) = repo.integration_reason(&snapshot, branch, target)?;
+ let Some(branch_ref) = snapshot.local_branch(branch).filter(|_| reason.is_some()) else {
+ return Ok(None);
+ };
+ expected_tip = Some(branch_ref.commit_sha.clone());
+ // Resolve after integration chooses local or upstream, while HEAD
+ // still belongs to the invoking checkout rather than the child.
+ repo.run_command(&[
+ "rev-parse",
+ "--verify",
+ "--end-of-options",
+ &format!("{effective_target}^{{commit}}"),
+ ])?
+ .trim()
+ .to_string()
+ };
+ let executable = std::env::current_exe().context("Failed to locate Worktrunk executable")?;
+ let mut args = vec![
+ executable.into_os_string(),
+ "_delete-branch-if-safe".into(),
+ format!("--branch={branch}").into(),
+ format!("--target={target}").into(),
+ ];
+ if let Some(tip) = expected_tip {
+ args.push(format!("--expected-tip={tip}").into());
+ }
+ if force_delete {
+ args.push("--force-delete".into());
+ }
+ Ok(Some(args))
}
-/// Build the detached worktree-removal command, optionally appending a
-/// branch-deletion tail (force-delete or CAS-delete) with `&&` so the branch
-/// step runs only when the worktree removal succeeded.
-fn build_remove_command_with_tail(
- worktree_path: &Path,
- force_worktree: bool,
- changed_directory: bool,
- tail: Option<&str>,
-) -> String {
- let remove_command =
- build_remove_command(worktree_path, None, force_worktree, changed_directory);
- match tail {
- Some(tail) => format!("{remove_command} && {tail}"),
- None => remove_command,
- }
+/// Complete detached deletion without expanding the foreground's candidate.
+/// A moved tip is retained before rechecking integration and checkout ownership.
+/// Force still uses Git's checkout-protected branch deletion.
+pub(crate) fn delete_branch_from_detached_fallback(
+ branch: &str,
+ target: &str,
+ expected_tip: Option<&str>,
+ force_delete: bool,
+) -> anyhow::Result<()> {
+ let repo = Repository::current()?;
+ let snapshot = repo.capture_refs()?;
+ let result = if expected_tip.is_some_and(|tip| {
+ snapshot
+ .local_branch(branch)
+ .map(|branch| branch.commit_sha.as_str())
+ != Some(tip)
+ }) {
+ BranchDeletionResult {
+ outcome: BranchDeletionOutcome::RetainedRaced,
+ integration_target: target.to_string(),
+ }
+ } else {
+ delete_branch_if_safe(&repo, &snapshot, branch, target, force_delete)?
+ };
+ warn_if_branch_retained(branch, &Ok(result), false);
+ Ok(())
}
/// List top-level entries remaining in a directory after a failed removal.
@@ -1408,9 +1377,8 @@ fn handle_branch_only_output(
let check_target = target_branch.unwrap_or("HEAD");
- // Force-delete bypasses CAS entirely — `git branch -D` is the user's
- // explicit override. For safe-delete with a pre-computed integration
- // reason, re-run the deletion against fresh refs
+ // Force-delete bypasses integration and CAS. For safe-delete with a
+ // pre-computed integration reason, re-run deletion against fresh refs
// (`execute_branch_deletion`): the atomic CAS catches any tip movement
// since planning, rather than trusting the planner's stale view of the ref.
let deletion = if let Some(integrated_reason) = integration_reason
@@ -1431,14 +1399,8 @@ fn handle_branch_only_output(
handle_branch_deletion_result(result, branch_name)?
} else if deletion_mode.is_force() {
let repo = worktrunk::git::Repository::current()?;
- let result = repo.run_command(&["branch", "-D", "--", branch_name]);
- handle_branch_deletion_result(
- result.map(|_| BranchDeletionResult {
- outcome: BranchDeletionOutcome::ForceDeleted,
- integration_target: check_target.to_string(),
- }),
- branch_name,
- )?
+ let result = execute_branch_deletion(&repo, branch_name, check_target, true);
+ handle_branch_deletion_result(result, branch_name)?
} else {
BranchDeletionDisplay {
result: BranchDeletionResult {
@@ -2446,146 +2408,91 @@ mod tests {
assert!(!branch_only.contains("Removed worktree"));
}
+ /// A failed branch query must not cancel a removal that Git can perform.
#[test]
- fn build_remove_command_with_tail_appends_only_when_present() {
- let path = Path::new("/tmp/wt");
- let bare = build_remove_command_with_tail(path, false, false, None);
- // No tail → the command is exactly the bare worktree removal.
- assert!(!bare.contains("&&"));
- let tailed = build_remove_command_with_tail(
- path,
- false,
- false,
- Some("git update-ref -d refs/heads/x deadbeef"),
- );
- // A tail is chained with `&&` so it runs only after a successful removal.
- assert_eq!(
- tailed,
- format!("{bare} && git update-ref -d refs/heads/x deadbeef")
- );
- }
-
- /// The detached safe-delete tail samples worktree topology immediately
- /// before the ref CAS. A checkout created after the tail was planned must
- /// make the tail succeed without deleting the branch.
- #[test]
- fn detached_cas_tail_retains_branch_checked_out_after_planning() {
- let test = worktrunk::testing::TestRepo::with_initial_commit();
- test.create_branch("feature");
+ fn detached_fallback_schedules_removal_after_branch_preparation_error() {
+ let mut test = worktrunk::testing::TestRepo::with_initial_commit();
+ let checkout = test.add_worktree("feature");
let repo = Repository::at(test.root_path()).unwrap();
- let expected_sha = test.git_output(&["rev-parse", "feature"]);
- let tail = build_cas_branch_delete_tail(&repo, "feature", Some("main")).unwrap();
-
- let normalized_tail = tail.replace(&expected_sha, "<sha>");
- assert!(
- normalized_tail.contains("awk -v worktrunk_wanted_branch='branch refs/heads/feature'")
- && normalized_tail.contains("git update-ref -d refs/heads/feature <sha>"),
- "the guard must associate the exact branch record with the existing CAS: {normalized_tail}"
- );
-
- let checkout = test.home_path().join("repo.feature-detached-race");
- test.run_git(&["worktree", "add", checkout.to_str().unwrap(), "feature"]);
-
- let guarded = Cmd::new("sh")
- .args(["-c", &tail])
- .current_dir(test.root_path())
- .run()
- .unwrap();
- assert!(
- guarded.status.success(),
- "a matching checkout is a clean skip"
- );
- assert!(
- repo.run_command(&["rev-parse", "--verify", "refs/heads/feature"])
- .is_ok(),
- "the detached guard must retain a newly checked-out branch"
- );
- assert!(
- repo.worktree_at(&checkout)
- .run_command(&["rev-parse", "--verify", "HEAD"])
- .is_ok(),
- "the guarded tail must not orphan the checkout"
- );
-
- let failing_awk = format!("awk() {{ return 2; }}; {tail}");
- let failed_guard = Cmd::new("sh")
- .args(["-c", &failing_awk])
+ let trash = repo.wt_trash_dir();
+ std::fs::create_dir_all(trash.parent().unwrap()).unwrap();
+ std::fs::write(&trash, "block staging").unwrap();
+ let outcome = execute_instant_removal_or_fallback(
+ &repo,
+ &BackgroundRemoval {
+ worktree_path: &checkout,
+ branch_name: Some("feature"),
+ deletion_mode: BranchDeletionMode::SafeDelete,
+ target_branch: Some("missing-target"),
+ force_worktree: false,
+ changed_directory: false,
+ planner_expected_retention: false,
+ },
+ BackgroundFallbackMode::Detached,
+ |_, _| unreachable!("the blocked staging path must defer removal"),
+ )
+ .unwrap();
+ assert!(format!("{:#}", outcome.branch_fate.unwrap_err()).contains("missing-target"));
+ let BackgroundRemovalPlan::Deferred(args) = outcome.plan else {
+ panic!("the checkout removal must still be scheduled");
+ };
+ let shell = worktrunk::shell_exec::ShellConfig::get().unwrap();
+ let output = Cmd::new(shell.executable.to_str().unwrap())
+ .args(&shell.args)
+ .args(&args)
.current_dir(test.root_path())
.run()
.unwrap();
+ assert!(output.status.success(), "{output:?}");
+ assert!(!checkout.exists());
assert!(
- !failed_guard.status.success(),
- "an awk/tool failure is not the no-match case"
- );
- assert!(
- repo.run_command(&["rev-parse", "--verify", "refs/heads/feature"])
- .is_ok(),
- "a topology-parser failure must fail closed"
- );
- }
-
- /// A lock protects a temporarily absent worktree. The detached parser must
- /// let it win even over a synthetic record that also says `prunable`.
- #[test]
- fn detached_topology_parser_retains_locked_prunable_record() {
- let porcelain = "worktree /missing/feature
-HEAD 0123456789abcdef
-branch refs/heads/feature
-locked detachable media
-prunable gitdir file points to non-existent location
-
-";
- let command = format!(
- "awk -v worktrunk_wanted_branch='branch refs/heads/feature' '{LIVE_BRANCH_WORKTREE_AWK}'"
+ repo.run_command(&["rev-parse", "--verify", "feature"])
+ .is_ok()
);
- let output = Cmd::new("sh")
- .args(["-c", &command])
- .stdin_bytes(porcelain)
- .run()
- .unwrap();
-
- assert!(output.status.success());
- assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "live");
}
- /// The exact porcelain branch line and ref argument are shell-escaped. A
- /// prunable stale registration is not a live checkout, so that arm still
- /// reaches the expected-SHA CAS without interpreting a valid but
- /// shell-active branch name.
+ #[cfg(target_os = "linux")]
#[test]
- fn detached_cas_tail_escapes_branch_and_deletes_when_not_checked_out() {
- let test = worktrunk::testing::TestRepo::with_initial_commit();
- let branch = "feature;touch${IFS}PWNED";
- test.create_branch(branch);
+ fn background_removal_preserves_native_path_arguments() {
+ use std::os::unix::ffi::{OsStrExt, OsStringExt};
+ let mut test = worktrunk::testing::TestRepo::with_initial_commit();
+ let original = test.add_worktree("feature");
let repo = Repository::at(test.root_path()).unwrap();
- let tail = build_cas_branch_delete_tail(&repo, branch, Some("main")).unwrap();
- assert!(
- tail.contains("'branch refs/heads/feature;touch${IFS}PWNED'"),
- "the complete porcelain line must be one escaped shell word: {tail}"
- );
- assert!(
- tail.contains("'refs/heads/feature;touch${IFS}PWNED'"),
- "the CAS ref must be escaped independently: {tail}"
- );
-
- let stale = test.home_path().join("repo.feature-stale");
- test.run_git(&["worktree", "add", stale.to_str().unwrap(), branch]);
- std::fs::remove_dir_all(&stale).unwrap();
-
- let output = Cmd::new("sh")
- .args(["-c", &tail])
- .current_dir(test.root_path())
- .run()
- .unwrap();
- assert!(output.status.success(), "no checkout should run the CAS");
- assert!(
- repo.run_command(&["rev-parse", "--verify", &format!("refs/heads/{branch}")])
- .is_err(),
- "the intended branch should be deleted"
- );
+ let registration = repo.worktree_at(&original).git_dir().unwrap();
+ let checkout =
+ original.with_file_name(std::ffi::OsString::from_vec(b"feature-\xff".to_vec()));
+ std::fs::rename(&original, &checkout).unwrap();
+ let mut backlink = checkout.join(".git").as_os_str().as_bytes().to_vec();
+ backlink.push(b'\n');
+ std::fs::write(registration.join("gitdir"), &backlink).unwrap();
+ execute_instant_removal_or_fallback(
+ &repo,
+ &BackgroundRemoval {
+ worktree_path: &checkout,
+ branch_name: Some("feature"),
+ deletion_mode: BranchDeletionMode::Keep,
+ target_branch: None,
+ force_worktree: false,
+ changed_directory: false,
+ planner_expected_retention: true,
+ },
+ BackgroundFallbackMode::Detached,
+ |args, _| {
+ let shell = worktrunk::shell_exec::ShellConfig::get()?;
+ let output = Cmd::new(shell.executable.to_str().unwrap())
+ .args(&shell.args)
+ .args(args)
+ .run()?;
+ assert!(output.status.success());
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert!(!checkout.exists());
+ assert!(!registration.exists());
assert!(
- !test.root_path().join("PWNED").exists(),
- "the branch name must never be interpreted by the shell"
+ repo.run_command(&["rev-parse", "--verify", "feature"])
+ .is_ok()
);
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 21c691c3e..195d4b70e 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -1221,7 +1221,7 @@ fn kill_timed_out_tree(pid: u32) {
pub struct Cmd {
/// Program name or shell command string (if shell_wrap is true)
program: String,
- args: Vec<String>,
+ args: Vec<OsString>,
current_dir: Option<std::path::PathBuf>,
context: Option<String>,
stdin_data: Option<Vec<u8>>,
@@ -1585,7 +1585,15 @@ impl Cmd {
if self.shell_wrap || self.args.is_empty() {
self.program.clone()
} else {
- format!("{} {}", self.program, self.args.join(" "))
+ format!(
+ "{} {}",
+ self.program,
+ self.args
+ .iter()
+ .map(|arg| arg.to_string_lossy())
+ .collect::<Vec<_>>()
+ .join(" ")
+ )
}
}
@@ -1686,8 +1694,8 @@ impl Cmd {
}
/// Add a single argument.
- pub fn arg(mut self, arg: impl Into<String>) -> Self {
- self.args.push(arg.into());
+ pub fn arg(mut self, arg: impl AsRef<OsStr>) -> Self {
+ self.args.push(arg.as_ref().to_os_string());
self
}
@@ -1695,9 +1703,10 @@ impl Cmd {
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
- S: Into<String>,
+ S: AsRef<OsStr>,
{
- self.args.extend(args.into_iter().map(Into::into));
+ self.args
+ .extend(args.into_iter().map(|arg| arg.as_ref().to_os_string()));
self
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 55ea1acea..b33ffa45f 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -4273,17 +4273,23 @@ fn test_remove_background_fallback_on_rename_failure(mut repo: TestRepo) {
fn block_staged_rename(repo: &TestRepo, worktree_path: &std::path::Path) -> std::path::PathBuf {
let trash_dir = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/trash");
std::fs::create_dir_all(&trash_dir).unwrap();
- let staged_path = trash_dir.join(format!(
- "{}-{}",
- worktree_path.file_name().unwrap().to_string_lossy(),
- crate::common::TEST_EPOCH
- ));
+ let git_dir = repo
+ .git_command()
+ .args(["rev-parse", "--absolute-git-dir"])
+ .current_dir(worktree_path)
+ .run()
+ .unwrap();
+ assert!(git_dir.status.success(), "{git_dir:?}");
+ let path = std::str::from_utf8(git_dir.stdout.strip_suffix(b"\n").unwrap()).unwrap();
+ let mut staged_name = Path::new(path).file_name().unwrap().to_os_string();
+ staged_name.push(format!("-{}", crate::common::TEST_EPOCH));
+ let staged_path = trash_dir.join(staged_name);
std::fs::write(&staged_path, "blocking file").unwrap();
staged_path
}
/// The rename-failure fallback honors `-D`: an unmerged branch is force-deleted
-/// in the legacy `git worktree remove && git branch -D` command.
+/// by the Rust child after `git worktree remove` succeeds.
#[rstest]
fn test_remove_background_fallback_force_delete_branch(mut repo: TestRepo) {
repo.commit("initial");
@@ -5420,8 +5426,8 @@ fn test_remove_json_branch_outcome_distinguishes_requested_retention(mut repo: T
/// The detached legacy fallback also corrects a broken deletion promise.
///
/// When the rename-into-trash fast path fails, the removal falls back to a
-/// detached `git worktree remove`, and the branch deletion becomes a CAS
-/// shell tail — built in the foreground. A `pre-remove` hook that advances
+/// detached `git worktree remove`, followed by the Rust branch-deletion child
+/// planned in the foreground. A `pre-remove` hook that advances
/// the branch makes the integration re-check decline the tail, so the branch
/// definitively survives while the progress message already promised
/// "worktree & branch". That survival must be warned and reported, exactly as
@@ -5910,7 +5916,7 @@ fn test_force_remove_with_corrupt_index_reports_unreadable_status(mut repo: Test
let removal = repo
.git_command()
.args(["worktree", "remove", "--force"])
- .arg(worktree.to_string_lossy())
+ .arg(&worktree)
.run()
.unwrap();
assert!(
@@ -6103,3 +6109,104 @@ fn test_force_remove_interrupted_status_preserves_worktrees(
assert!(!stderr.contains("discarding"));
assert!(!stderr.contains("Removing later-worktree"));
}
+
+/// The child uses the invoking checkout's target and retains a moved tip,
+/// even when the replacement commit is integrated into that target.
+#[test]
+fn test_detached_delete_child_captured_target_and_tip() {
+ let mut repo = TestRepo::with_initial_commit();
+ let original = repo.git_output(&["rev-parse", "HEAD"]);
+ let invoking = repo.add_worktree("invoking");
+ repo.commit_in_worktree(&invoking, "new.txt", "new content", "new commit");
+ let target = repo.git_output(&["rev-parse", "invoking"]);
+ repo.run_git(&["branch", "feature", &target]);
+
+ let run_child = |tip: &str| {
+ repo.wt_command()
+ .args([
+ "_delete-branch-if-safe",
+ "--branch=feature",
+ &format!("--target={target}"),
+ &format!("--expected-tip={tip}"),
+ ])
+ .output()
+ .unwrap()
+ };
+ // The child runs from main, whose HEAD is behind the invoking target.
+ let output = run_child(&target);
+ assert!(output.status.success(), "{output:?}");
+ assert_branch_exists(
+ &repo,
+ "feature",
+ false,
+ &String::from_utf8_lossy(&output.stderr),
+ );
+
+ repo.run_git(&["branch", "feature", &original]);
+ repo.run_git(&["update-ref", "refs/heads/feature", &target, &original]);
+ let output = run_child(&original);
+ assert!(output.status.success(), "{output:?}");
+ assert!(
+ String::from_utf8_lossy(&output.stderr).contains("moved during deletion"),
+ "{output:?}"
+ );
+ assert_eq!(repo.git_output(&["rev-parse", "feature"]), target);
+}
+
+/// A detached fallback must preserve a new checkout even when its path looks
+/// like a porcelain status field. Branches and checkout paths remain argv data.
+#[cfg(unix)]
+#[rstest]
+fn test_detached_fallback_native_arguments_and_fresh_checkout(mut repo: TestRepo) {
+ use shell_escape::unix::escape;
+
+ let branch = "feature;touch${IFS}PWNED";
+ let parent = repo.root_path().parent().unwrap().to_path_buf();
+ let survivor = parent.join("survivor\nprunable");
+ let removed = parent.join("checkout '$(touch PWNED)");
+ let hook = format!(
+ "git worktree add --force {} {}",
+ escape(survivor.to_str().unwrap().into()),
+ escape(branch.into()),
+ );
+ repo.write_project_config(&format!("pre-remove = {hook:?}"));
+ repo.commit("Add config");
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
+approved-commands = [{hook:?}]
+"#
+ ));
+ let removed = repo.add_worktree_at_path(branch, &removed);
+ let staged_path = block_staged_rename(&repo, &removed);
+ let output = repo
+ .wt_command()
+ .args(["remove", "--yes", branch])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+
+ let log = crate::common::resolve_git_common_dir(repo.root_path())
+ .join("wt/logs")
+ .join(worktrunk::path::sanitize_for_filename(branch))
+ .join("internal/remove.log");
+ let completion = format!(
+ "detached child retained the new checkout; log {} initially {:?}; blocker {}; foreground {output:?}",
+ log.display(),
+ fs::read_to_string(&log),
+ staged_path.display(),
+ );
+ crate::common::wait_for(&completion, || {
+ fs::read_to_string(&log).is_ok_and(|text| text.contains("checked out @"))
+ });
+ assert!(!removed.exists());
+ assert_branch_exists(
+ &repo,
+ branch,
+ true,
+ &String::from_utf8_lossy(&output.stderr),
+ );
+ assert_not_orphaned(&repo, &survivor, "detached child completed");
+ assert!(!repo.root_path().join("PWNED").exists());
+ assert!(!parent.join("PWNED").exists());
+ let _ = fs::remove_file(staged_path);
+}