Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(relocate): atomic no-overwrite rename for --clobber backup (#2865)
Maximilian Roos9e8c028476ff
diff --git a/docs/content/step.md b/docs/content/step.mdindex 20063c8c2..9405ba6a0 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -826,7 +826,9 @@ this by using a temporary location.### ClobberingWith `--clobber`, non-worktree paths at target locations are moved to-`<path>.bak-<timestamp>` before relocating.+`<path>.bak.<timestamp>` before relocating. If that name is already taken,+the move counts up (`…-2`, `…-3`, …) until it finds a free name, so an+existing backup is never overwritten.### Main worktree behavior@@ -866,7 +868,8 @@ Usage: <b><span class=c>wt step relocate</span></b> <span class=c>[OPTIONS]</spa<b><span class=c>--clobber</span></b>Backup non-worktree paths at target locations- Moves blocking paths to <b><path>.bak-<timestamp></b>.+ Moves blocking paths to <b><path>.bak.<timestamp></b>. If that name is taken, counts up (<b>…-2</b>, <b>…-3</b>+ , …) to a free name.<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>Print help (see a summary with '-h')diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex bd9680f2c..bb94f4d62 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -869,7 +869,9 @@ this by using a temporary location.### ClobberingWith `--clobber`, non-worktree paths at target locations are moved to-`<path>.bak-<timestamp>` before relocating.+`<path>.bak.<timestamp>` before relocating. If that name is already taken,+the move counts up (`…-2`, `…-3`, …) until it finds a free name, so an+existing backup is never overwritten.### Main worktree behavior@@ -909,7 +911,8 @@ Options:--clobberBackup non-worktree paths at target locations- Moves blocking paths to <path>.bak-<timestamp>.+ Moves blocking paths to <path>.bak.<timestamp>. If that name is taken, counts up (…-2, …-3+ , …) to a free name.-h, --helpPrint help (see a summary with '-h')diff --git a/src/cli/step.rs b/src/cli/step.rsindex 0f0f40b58..99573b800 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -631,7 +631,9 @@ this by using a temporary location.## ClobberingWith `--clobber`, non-worktree paths at target locations are moved to-`<path>.bak-<timestamp>` before relocating.+`<path>.bak.<timestamp>` before relocating. If that name is already taken,+the move counts up (`…-2`, `…-3`, …) until it finds a free name, so an+existing backup is never overwritten.## Main worktree behavior@@ -663,7 +665,8 @@ Note: This command is experimental and may change in future versions./// Backup non-worktree paths at target locations///- /// Moves blocking paths to `<path>.bak-<timestamp>`.+ /// Moves blocking paths to `<path>.bak.<timestamp>`. If that name is+ /// taken, counts up (`…-2`, `…-3`, …) to a free name.#[arg(long)]clobber: bool,diff --git a/src/commands/backup.rs b/src/commands/backup.rsnew file mode 100644index 000000000..517428d58--- /dev/null+++ b/src/commands/backup.rs@@ -0,0 +1,237 @@+//! Atomic no-overwrite backup of a path blocking a `--clobber` move.+//!+//! Both `wt switch --clobber` and `wt step relocate --clobber` need to move a+//! stale or blocking path aside before they can take its place. They share this+//! helper so the two paths behave identically: the backup name and the atomic+//! no-overwrite rename are defined once.+//!+//! # Why an atomic rename+//!+//! The backup name is only second-resolution (`.bak.<YYYYmmdd-HHMMSS>`), so an+//! `exists()` check followed by a rename would race: another process could+//! create that path in the gap. [`renamore::rename_exclusive`] closes the gap+//! — an atomic no-overwrite rename (`renameat2(RENAME_NOREPLACE)` on Linux,+//! `renamex_np(RENAME_EXCL)` on macOS, `MoveFileExW` on Windows) that fails+//! closed rather than overwriting an existing backup. `std::fs::rename`+//! silently replaces an existing file or empty directory and cannot be used+//! here. A name collision is not fatal: the move counts up (`…-2`, `…-3`, …)+//! until it lands on a free name.++use std::path::{Path, PathBuf};++use worktrunk::path::format_path_for_display;++/// Generate a backup path for the given path with a timestamp suffix.+///+/// For paths with extensions: `file.txt` → `file.txt.bak.TIMESTAMP`+/// For paths without extensions: `foo` → `foo.bak.TIMESTAMP`+///+/// Returns an error for unusual paths without a file name (e.g., `/` or `..`).+fn generate_backup_path(path: &Path, suffix: &str) -> anyhow::Result<PathBuf> {+ let file_name = path.file_name().ok_or_else(|| {+ anyhow::anyhow!(+ "Cannot generate backup path for {}",+ format_path_for_display(path)+ )+ })?;++ if path.extension().is_none() {+ // Path has no extension (e.g., /repo/feature)+ Ok(path.with_file_name(format!("{}.bak.{suffix}", file_name.to_string_lossy())))+ } else {+ // Path has an extension (e.g., /repo.feature or /file.txt)+ Ok(path.with_extension(format!(+ "{}.bak.{suffix}",+ path.extension()+ .map(|e| e.to_string_lossy().to_string())+ .unwrap_or_default()+ )))+ }+}++/// Move `blocking_path` aside to a `.bak.<base_suffix>` sibling.+///+/// If that name is already taken — a same-second clobber, or a path that raced+/// in after planning — it counts up (`…-2`, `…-3`, …) until it finds a free+/// name. Every attempt is an atomic no-overwrite rename+/// ([`renamore::rename_exclusive`]), so an existing backup is never overwritten;+/// the move just lands on the next free name. Returns the path the blocking+/// directory was moved to.+///+/// `base_suffix` is a parameter rather than computed internally so tests can+/// pass a fixed value; [`back_up_clobbered_path_now`] is the production entry+/// point that derives the timestamp.+fn back_up_clobbered_path(blocking_path: &Path, base_suffix: &str) -> anyhow::Result<PathBuf> {+ // Count up until a free name is found. This cannot spin forever: a+ // directory holds finitely many entries, so some `-N` is always unused.+ let mut n: u64 = 1;+ loop {+ // First attempt uses the bare suffix; later ones disambiguate with -N.+ let suffix = if n == 1 {+ base_suffix.to_string()+ } else {+ format!("{base_suffix}-{n}")+ };+ let candidate = generate_backup_path(blocking_path, &suffix)?;+ match renamore::rename_exclusive(blocking_path, &candidate) {+ Ok(()) => return Ok(candidate),+ Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => n += 1,+ Err(err) => {+ return Err(anyhow::Error::new(err).context(format!(+ "Failed to move {} to {}",+ format_path_for_display(blocking_path),+ format_path_for_display(&candidate),+ )));+ }+ }+ }+}++/// Move `blocking_path` aside to a timestamped `.bak.<YYYYmmdd-HHMMSS>` sibling.+///+/// Wraps [`back_up_clobbered_path`] with the timestamp suffix computed at move+/// time, so the suffix reflects when the path is actually set aside. Returns the+/// path the blocking directory was moved to.+pub(crate) fn back_up_clobbered_path_now(blocking_path: &Path) -> anyhow::Result<PathBuf> {+ let timestamp_secs = worktrunk::utils::epoch_now() as i64;+ let datetime =+ chrono::DateTime::from_timestamp(timestamp_secs, 0).unwrap_or_else(chrono::Utc::now);+ let base_suffix = datetime.format("%Y%m%d-%H%M%S").to_string();+ back_up_clobbered_path(blocking_path, &base_suffix)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_generate_backup_path_with_extension() {+ // Paths with extensions: file.txt -> file.txt.bak.TIMESTAMP+ let path = PathBuf::from("/tmp/repo.feature");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(+ backup,+ PathBuf::from("/tmp/repo.feature.bak.20250101-000000")+ );++ let path = PathBuf::from("/tmp/file.txt");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(backup, PathBuf::from("/tmp/file.txt.bak.20250101-000000"));+ }++ #[test]+ fn test_generate_backup_path_without_extension() {+ // Paths without extensions: foo -> foo.bak.TIMESTAMP+ let path = PathBuf::from("/tmp/repo/feature");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(+ backup,+ PathBuf::from("/tmp/repo/feature.bak.20250101-000000")+ );++ let path = PathBuf::from("/tmp/mydir");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(backup, PathBuf::from("/tmp/mydir.bak.20250101-000000"));+ }++ #[test]+ fn test_generate_backup_path_unusual_paths() {+ // Root path has no file name+ let path = PathBuf::from("/");+ assert!(generate_backup_path(&path, "20250101-000000").is_err());++ // Parent reference has no file name+ let path = PathBuf::from("..");+ assert!(generate_backup_path(&path, "20250101-000000").is_err());+ }++ #[test]+ fn test_back_up_clobbered_path_moves_to_fresh_suffix() {+ let temp = tempfile::tempdir().unwrap();+ let stale = temp.path().join("feature");+ std::fs::create_dir(&stale).unwrap();+ std::fs::write(stale.join("file"), "content").unwrap();++ let used = back_up_clobbered_path(&stale, "20250101-000000").unwrap();++ assert_eq!(used, temp.path().join("feature.bak.20250101-000000"));+ assert!(!stale.exists(), "stale path should be moved away");+ assert_eq!(+ std::fs::read_to_string(used.join("file")).unwrap(),+ "content"+ );+ }++ #[test]+ fn test_back_up_clobbered_path_falls_back_when_suffix_taken() {+ let temp = tempfile::tempdir().unwrap();+ let stale = temp.path().join("feature");+ std::fs::create_dir(&stale).unwrap();++ // The preferred backup name and its first -N variant are both taken.+ let taken = temp.path().join("feature.bak.20250101-000000");+ std::fs::create_dir(&taken).unwrap();+ std::fs::write(taken.join("keep"), "pre-existing").unwrap();+ std::fs::create_dir(temp.path().join("feature.bak.20250101-000000-2")).unwrap();++ let used = back_up_clobbered_path(&stale, "20250101-000000").unwrap();++ // Lands on -3; neither pre-existing backup is overwritten.+ assert_eq!(used, temp.path().join("feature.bak.20250101-000000-3"));+ assert!(!stale.exists());+ assert_eq!(+ std::fs::read_to_string(taken.join("keep")).unwrap(),+ "pre-existing"+ );+ }++ #[test]+ fn test_back_up_clobbered_path_errors_when_source_missing() {+ // A missing source fails the rename with a non-AlreadyExists error,+ // which surfaces (with the "Failed to move" context) rather than being+ // retried.+ let temp = tempfile::tempdir().unwrap();+ let missing = temp.path().join("does-not-exist");+ let err = back_up_clobbered_path(&missing, "20250101-000000").unwrap_err();+ assert!(+ err.to_string().contains("Failed to move"),+ "expected wrapped error, got: {err}"+ );+ }++ #[test]+ fn test_back_up_clobbered_path_keeps_incrementing_past_many_collisions() {+ // There is no attempt cap: the move keeps counting up until a free+ // name is found, however many backups already exist.+ let temp = tempfile::tempdir().unwrap();+ let stale = temp.path().join("feature");+ std::fs::create_dir(&stale).unwrap();++ // Occupy the preferred name and the first 49 -N fallbacks (suffix "S").+ std::fs::create_dir(temp.path().join("feature.bak.S")).unwrap();+ for n in 2..=50 {+ std::fs::create_dir(temp.path().join(format!("feature.bak.S-{n}"))).unwrap();+ }++ let used = back_up_clobbered_path(&stale, "S").unwrap();++ assert_eq!(used, temp.path().join("feature.bak.S-51"));+ assert!(!stale.exists(), "stale path should be moved away");+ }++ #[test]+ fn test_back_up_clobbered_path_now_uses_timestamped_suffix() {+ let temp = tempfile::tempdir().unwrap();+ let stale = temp.path().join("feature");+ std::fs::create_dir(&stale).unwrap();++ let used = back_up_clobbered_path_now(&stale).unwrap();++ let name = used.file_name().unwrap().to_string_lossy();+ assert!(+ name.starts_with("feature.bak."),+ "expected timestamped backup name, got: {name}"+ );+ assert!(!stale.exists(), "stale path should be moved away");+ }+}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 1ddd48c96..e3f87fa4f 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -1,4 +1,5 @@mod alias;+pub(crate) mod backup;pub(crate) mod command_approval;pub(crate) mod command_executor;pub(crate) mod commit;diff --git a/src/commands/relocate.rs b/src/commands/relocate.rsindex 9b7cb1c55..849a5bffe 100644--- a/src/commands/relocate.rs+++ b/src/commands/relocate.rs@@ -33,6 +33,7 @@ use worktrunk::styling::{warning_message,};+use super::backup;use super::commit::{CommitGenerator, StageMode};use super::worktree::compute_worktree_path;@@ -375,39 +376,13 @@ impl<'a> RelocationExecutor<'a> {}if clobber {- // Backup the blocker- let timestamp_secs = worktrunk::utils::epoch_now() as i64;- let datetime = chrono::DateTime::from_timestamp(timestamp_secs, 0)- .unwrap_or_else(chrono::Utc::now);- let suffix = datetime.format("%Y%m%d-%H%M%S");- let backup_path = expected_path.with_file_name(format!(- "{}.bak-{suffix}",- expected_path- .file_name()- .unwrap_or_default()- .to_string_lossy()- ));- // Fail closed if the backup destination already exists: `fs::rename`- // can silently replace an existing file (and some empty- // directories) on Unix, which would destroy a prior backup.- if backup_path.exists() {- anyhow::bail!(- "Backup path already exists: {}",- format_path_for_display(&backup_path)- );- }+ // Atomically move the blocker aside to a timestamped backup.+ // A backup name already taken is never overwritten — the move+ // falls back to the next free `-N` name.let src = format_path_for_display(expected_path);+ let backup_path = backup::back_up_clobbered_path_now(expected_path)?;let dest = format_path_for_display(&backup_path);- eprintln!(- "{}",- progress_message(cformat!("Backing up {src} → {dest}"))- );- std::fs::rename(expected_path, &backup_path).with_context(|| {- format!(- "Failed to backup {}",- format_path_for_display(expected_path)- )- })?;+ eprintln!("{}", progress_message(cformat!("Backed up {src} → {dest}")));} else {let blocked_path = format_path_for_display(expected_path);let msg = cformat!("Skipping <bold>{branch}</> (target blocked: {blocked_path})");diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rsindex 5681febc9..853b887b4 100644--- a/src/commands/step/relocate.rs+++ b/src/commands/step/relocate.rs@@ -18,7 +18,7 @@ use worktrunk::styling::println;/// |------|---------|/// | `--dry-run` | Show what would be moved without moving |/// | `--commit` | Auto-commit dirty worktrees with LLM-generated messages before relocating |-/// | `--clobber` | Move non-worktree paths out of the way (`<path>.bak-<timestamp>`) |+/// | `--clobber` | Move non-worktree paths out of the way (`<path>.bak.<timestamp>`) |/// | `[branches...]` | Specific branches to relocate (default: all mismatched) |pub fn step_relocate(branches: Vec<String>,diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 3b049972e..44b057736 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -202,74 +202,6 @@ pub fn worktree_display_name(}}-/// Generate a backup path for the given path with a timestamp suffix.-///-/// For paths with extensions: `file.txt` → `file.txt.bak.TIMESTAMP`-/// For paths without extensions: `foo` → `foo.bak.TIMESTAMP`-///-/// Returns an error for unusual paths without a file name (e.g., `/` or `..`).-pub(super) fn generate_backup_path(- path: &std::path::Path,- suffix: &str,-) -> anyhow::Result<PathBuf> {- let file_name = path.file_name().ok_or_else(|| {- anyhow::anyhow!(- "Cannot generate backup path for {}",- format_path_for_display(path)- )- })?;-- if path.extension().is_none() {- // Path has no extension (e.g., /repo/feature)- Ok(path.with_file_name(format!("{}.bak.{suffix}", file_name.to_string_lossy())))- } else {- // Path has an extension (e.g., /repo.feature or /file.txt)- Ok(path.with_extension(format!(- "{}.bak.{suffix}",- path.extension()- .map(|e| e.to_string_lossy().to_string())- .unwrap_or_default()- )))- }-}--/// Move a stale path aside so `wt switch --clobber` can take its place.-///-/// Renames `worktree_path` to a `.bak.<base_suffix>` sibling. If that name is-/// already taken — a same-second clobber, or a path that raced in after-/// planning — it counts up (`…-2`, `…-3`, …) until it finds a free name.-/// Every attempt is an atomic no-overwrite rename ([`renamore::rename_exclusive`]),-/// so an existing backup is never overwritten; the move just lands on the next-/// free name. Returns the path the stale directory was moved to.-pub(super) fn back_up_clobbered_path(- worktree_path: &Path,- base_suffix: &str,-) -> anyhow::Result<PathBuf> {- // Count up until a free name is found. This cannot spin forever: a- // directory holds finitely many entries, so some `-N` is always unused.- let mut n: u64 = 1;- loop {- // First attempt uses the bare suffix; later ones disambiguate with -N.- let suffix = if n == 1 {- base_suffix.to_string()- } else {- format!("{base_suffix}-{n}")- };- let candidate = generate_backup_path(worktree_path, &suffix)?;- match renamore::rename_exclusive(worktree_path, &candidate) {- Ok(()) => return Ok(candidate),- Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => n += 1,- Err(err) => {- return Err(anyhow::Error::new(err).context(format!(- "Failed to move {} to {}",- format_path_for_display(worktree_path),- format_path_for_display(&candidate),- )));- }- }- }-}-/// Suggested worktree-path template for bare repos with hidden directory names.////// Places worktrees as siblings of the bare repo directory inside the parent,@@ -423,116 +355,6 @@ fn print_accepted_message(display_path: &str, config_path: &str) {mod tests {use super::*;- #[test]- fn test_generate_backup_path_with_extension() {- // Paths with extensions: file.txt -> file.txt.bak.TIMESTAMP- let path = PathBuf::from("/tmp/repo.feature");- let backup = generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(- backup,- PathBuf::from("/tmp/repo.feature.bak.20250101-000000")- );-- let path = PathBuf::from("/tmp/file.txt");- let backup = generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(backup, PathBuf::from("/tmp/file.txt.bak.20250101-000000"));- }-- #[test]- fn test_generate_backup_path_without_extension() {- // Paths without extensions: foo -> foo.bak.TIMESTAMP- let path = PathBuf::from("/tmp/repo/feature");- let backup = generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(- backup,- PathBuf::from("/tmp/repo/feature.bak.20250101-000000")- );-- let path = PathBuf::from("/tmp/mydir");- let backup = generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(backup, PathBuf::from("/tmp/mydir.bak.20250101-000000"));- }-- #[test]- fn test_generate_backup_path_unusual_paths() {- // Root path has no file name- let path = PathBuf::from("/");- assert!(generate_backup_path(&path, "20250101-000000").is_err());-- // Parent reference has no file name- let path = PathBuf::from("..");- assert!(generate_backup_path(&path, "20250101-000000").is_err());- }-- #[test]- fn test_back_up_clobbered_path_moves_to_fresh_suffix() {- let temp = tempfile::tempdir().unwrap();- let stale = temp.path().join("feature");- std::fs::create_dir(&stale).unwrap();- std::fs::write(stale.join("file"), "content").unwrap();-- let used = back_up_clobbered_path(&stale, "20250101-000000").unwrap();-- assert_eq!(used, temp.path().join("feature.bak.20250101-000000"));- assert!(!stale.exists(), "stale path should be moved away");- assert_eq!(- std::fs::read_to_string(used.join("file")).unwrap(),- "content"- );- }-- #[test]- fn test_back_up_clobbered_path_falls_back_when_suffix_taken() {- let temp = tempfile::tempdir().unwrap();- let stale = temp.path().join("feature");- std::fs::create_dir(&stale).unwrap();-- // The preferred backup name and its first -N variant are both taken.- let taken = temp.path().join("feature.bak.20250101-000000");- std::fs::create_dir(&taken).unwrap();- std::fs::write(taken.join("keep"), "pre-existing").unwrap();- std::fs::create_dir(temp.path().join("feature.bak.20250101-000000-2")).unwrap();-- let used = back_up_clobbered_path(&stale, "20250101-000000").unwrap();-- // Lands on -3; neither pre-existing backup is overwritten.- assert_eq!(used, temp.path().join("feature.bak.20250101-000000-3"));- assert!(!stale.exists());- assert_eq!(- std::fs::read_to_string(taken.join("keep")).unwrap(),- "pre-existing"- );- }-- #[test]- fn test_back_up_clobbered_path_errors_when_source_missing() {- // A missing source fails the rename with a non-AlreadyExists error,- // which surfaces rather than being retried.- let temp = tempfile::tempdir().unwrap();- let missing = temp.path().join("does-not-exist");- assert!(back_up_clobbered_path(&missing, "20250101-000000").is_err());- }-- #[test]- fn test_back_up_clobbered_path_keeps_incrementing_past_many_collisions() {- // There is no attempt cap: the move keeps counting up until a free- // name is found, however many backups already exist.- let temp = tempfile::tempdir().unwrap();- let stale = temp.path().join("feature");- std::fs::create_dir(&stale).unwrap();-- // Occupy the preferred name and the first 49 -N fallbacks (suffix "S").- std::fs::create_dir(temp.path().join("feature.bak.S")).unwrap();- for n in 2..=50 {- std::fs::create_dir(temp.path().join(format!("feature.bak.S-{n}"))).unwrap();- }-- let used = back_up_clobbered_path(&stale, "S").unwrap();-- assert_eq!(used, temp.path().join("feature.bak.S-51"));- assert!(!stale.exists(), "stale path should be moved away");- }-#[test]fn test_template_references_repo_name_default() {// Default template uses {{ repo }}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex b5e22a48a..64b8db4d4 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -31,11 +31,10 @@ use worktrunk::styling::{warning_message,};-use super::resolve::{- back_up_clobbered_path, compute_worktree_path, offer_bare_repo_worktree_path_fix, path_mismatch,-};+use super::resolve::{compute_worktree_path, offer_bare_repo_worktree_path_fix, path_mismatch};use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};use crate::cli::SwitchFormat;+use crate::commands::backup::back_up_clobbered_path_now;use crate::commands::command_approval::approve_hooks;use crate::commands::command_executor::FailureStrategy;use crate::commands::command_executor::{CommandContext, build_hook_context};@@ -927,18 +926,11 @@ fn execute_switch(} => {// Handle --clobber backup if needed (shared for all creation methods)if needs_clobber_backup {- // Timestamped backup name, computed here at move time so the- // suffix reflects when the path is actually set aside.- let timestamp = worktrunk::utils::epoch_now() as i64;- let datetime =- chrono::DateTime::from_timestamp(timestamp, 0).unwrap_or_else(chrono::Utc::now);- let base_suffix = datetime.format("%Y%m%d-%H%M%S").to_string();-- // Atomically move the stale path aside. A backup name that is- // already taken (a same-second clobber, or one that raced in- // after planning) is never overwritten — the move falls back- // to the next free `-N` name.- let backup_path = back_up_clobbered_path(&worktree_path, &base_suffix)?;+ // Atomically move the stale path aside, to a timestamped backup+ // name. A name already taken (a same-second clobber, or one+ // that raced in after planning) is never overwritten — the move+ // falls back to the next free `-N` name.+ let backup_path = back_up_clobbered_path_now(&worktree_path)?;let path_display = worktrunk::path::format_path_for_display(&worktree_path);let backup_display = worktrunk::path::format_path_for_display(&backup_path);diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rsindex ff84a6ee6..b0e0f6ef5 100644--- a/tests/integration_tests/step_relocate.rs+++ b/tests/integration_tests/step_relocate.rs@@ -308,16 +308,17 @@ fn test_relocate_clobber_backs_up(repo: TestRepo) {.filter_map(|e| e.ok()).any(|e| {let name = e.file_name().to_string_lossy().to_string();- name.starts_with("repo.feature.bak-")+ name.starts_with("repo.feature.bak.")});assert!(backup_exists, "Backup directory should exist");}/// Regression: when the computed backup path already exists, relocate-/// --clobber must fail rather than silently overwriting it. (Matches the-/// `wt switch --clobber` contract — see test_switch_clobber_error_backup_exists.)+/// --clobber falls back to the next free `-N` name rather than overwriting it.+/// (Matches the `wt switch --clobber` contract — see+/// test_switch_clobber_falls_back_when_backup_taken.)#[rstest]-fn test_relocate_clobber_error_backup_exists(repo: TestRepo) {+fn test_relocate_clobber_falls_back_when_backup_taken(repo: TestRepo) {let parent = worktree_parent(&repo);// Create a worktree at a non-standard location.@@ -334,32 +335,40 @@ fn test_relocate_clobber_error_backup_exists(repo: TestRepo) {let expected_path = parent.join("repo.feature");fs::write(&expected_path, "blocker contents").unwrap();- // Pre-create the backup path that relocate would compute. TEST_EPOCH- // pins the timestamp suffix so this name is deterministic.+ // Pre-create the backup path relocate would compute. TEST_EPOCH pins the+ // timestamp suffix so this name is deterministic.// TEST_EPOCH=1735776000 -> 2025-01-02 00:00:00 UTC- let backup_path = parent.join("repo.feature.bak-20250102-000000");- fs::write(&backup_path, "existing backup").unwrap();+ let taken = parent.join("repo.feature.bak.20250102-000000");+ fs::write(&taken, "existing backup").unwrap();let output = make_snapshot_cmd(&repo, "step", &["relocate", "--clobber"], None).output().expect("relocate should run");assert!(- !output.status.success(),- "relocate must fail when backup path already exists; stderr:\n{}",+ output.status.success(),+ "relocate must fall back to a free backup name; stderr:\n{}",String::from_utf8_lossy(&output.stderr));- // Both the blocker and the existing backup must be intact.- assert_eq!(- fs::read_to_string(&expected_path).unwrap(),- "blocker contents",- "blocker file must not be moved"+ // The worktree was moved to the expected location.+ assert!(+ expected_path.is_dir(),+ "Worktree should be at expected location: {}",+ expected_path.display());++ // The pre-existing backup is untouched; the blocker moved to the -2 name.assert_eq!(- fs::read_to_string(&backup_path).unwrap(),+ fs::read_to_string(&taken).unwrap(),"existing backup","existing backup must not be overwritten");+ let fallback = parent.join("repo.feature.bak.20250102-000000-2");+ assert_eq!(+ fs::read_to_string(&fallback).unwrap(),+ "blocker contents",+ "blocker file must move to the -2 fallback name"+ );}/// Test that --clobber refuses to clobber an existing worktreediff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_backs_up.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_backs_up.snapindex 280e5686d..0f461db49 100644--- a/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_backs_up.snap+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_backs_up.snap@@ -12,13 +12,19 @@ info:COLUMNS: "500"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMON_DIR: ""GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/null+ GIT_DIR: ""GIT_EDITOR: ""+ GIT_INDEX_FILE: ""+ GIT_OBJECT_DIRECTORY: ""GIT_TERMINAL_PROMPT: "0"+ GIT_WORK_TREE: ""HOME: "[TEST_HOME]"LANG: CLC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"NO_COLOR: ""OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"@@ -31,13 +37,19 @@ info:WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"---success: true@@ -45,7 +57,7 @@ exit_code: 0----- stdout ---------- stderr ------[36m◎[39m [36mBacking up _REPO_.feature → _REPO_.feature.bak-20250102-000000[39m+[36m◎[39m [36mBacked up _REPO_.feature → _REPO_.feature.bak.20250102-000000[39m[32m✓[39m [32mRelocated [1mfeature[22m: _PARENT_/wrong-location → _REPO_.feature[39m[32m✓[39m [32mRelocated 1 worktree[39m