|
| 1 | +//! Atomic no-overwrite backup of a path blocking a `--clobber` move. |
| 2 | +//! |
| 3 | +//! Both `wt switch --clobber` and `wt step relocate --clobber` need to move a |
| 4 | +//! stale or blocking path aside before they can take its place. They share this |
| 5 | +//! helper so the two paths behave identically: the backup name and the atomic |
| 6 | +//! no-overwrite rename are defined once. |
| 7 | +//! |
| 8 | +//! # Why an atomic rename |
| 9 | +//! |
| 10 | +//! The backup name is only second-resolution (`.bak.<YYYYmmdd-HHMMSS>`), so an |
| 11 | +//! `exists()` check followed by a rename would race: another process could |
| 12 | +//! create that path in the gap. [`renamore::rename_exclusive`] closes the gap |
| 13 | +//! — an atomic no-overwrite rename (`renameat2(RENAME_NOREPLACE)` on Linux, |
| 14 | +//! `renamex_np(RENAME_EXCL)` on macOS, `MoveFileExW` on Windows) that fails |
| 15 | +//! closed rather than overwriting an existing backup. `std::fs::rename` |
| 16 | +//! silently replaces an existing file or empty directory and cannot be used |
| 17 | +//! here. A name collision is not fatal: the move counts up (`…-2`, `…-3`, …) |
| 18 | +//! until it lands on a free name. |
| 19 | +
|
| 20 | +use std::path::{Path, PathBuf}; |
| 21 | + |
| 22 | +use worktrunk::path::format_path_for_display; |
| 23 | + |
| 24 | +/// Generate a backup path for the given path with a timestamp suffix. |
| 25 | +/// |
| 26 | +/// For paths with extensions: `file.txt` → `file.txt.bak.TIMESTAMP` |
| 27 | +/// For paths without extensions: `foo` → `foo.bak.TIMESTAMP` |
| 28 | +/// |
| 29 | +/// Returns an error for unusual paths without a file name (e.g., `/` or `..`). |
| 30 | +fn generate_backup_path(path: &Path, suffix: &str) -> anyhow::Result<PathBuf> { |
| 31 | + let file_name = path.file_name().ok_or_else(|| { |
| 32 | + anyhow::anyhow!( |
| 33 | + "Cannot generate backup path for {}", |
| 34 | + format_path_for_display(path) |
| 35 | + ) |
| 36 | + })?; |
| 37 | + |
| 38 | + if path.extension().is_none() { |
| 39 | + // Path has no extension (e.g., /repo/feature) |
| 40 | + Ok(path.with_file_name(format!("{}.bak.{suffix}", file_name.to_string_lossy()))) |
| 41 | + } else { |
| 42 | + // Path has an extension (e.g., /repo.feature or /file.txt) |
| 43 | + Ok(path.with_extension(format!( |
| 44 | + "{}.bak.{suffix}", |
| 45 | + path.extension() |
| 46 | + .map(|e| e.to_string_lossy().to_string()) |
| 47 | + .unwrap_or_default() |
| 48 | + ))) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Move `blocking_path` aside to a `.bak.<base_suffix>` sibling. |
| 53 | +/// |
| 54 | +/// If that name is already taken — a same-second clobber, or a path that raced |
| 55 | +/// in after planning — it counts up (`…-2`, `…-3`, …) until it finds a free |
| 56 | +/// name. Every attempt is an atomic no-overwrite rename |
| 57 | +/// ([`renamore::rename_exclusive`]), so an existing backup is never overwritten; |
| 58 | +/// the move just lands on the next free name. Returns the path the blocking |
| 59 | +/// directory was moved to. |
| 60 | +/// |
| 61 | +/// `base_suffix` is a parameter rather than computed internally so tests can |
| 62 | +/// pass a fixed value; [`back_up_clobbered_path_now`] is the production entry |
| 63 | +/// point that derives the timestamp. |
| 64 | +fn back_up_clobbered_path(blocking_path: &Path, base_suffix: &str) -> anyhow::Result<PathBuf> { |
| 65 | + // Count up until a free name is found. This cannot spin forever: a |
| 66 | + // directory holds finitely many entries, so some `-N` is always unused. |
| 67 | + let mut n: u64 = 1; |
| 68 | + loop { |
| 69 | + // First attempt uses the bare suffix; later ones disambiguate with -N. |
| 70 | + let suffix = if n == 1 { |
| 71 | + base_suffix.to_string() |
| 72 | + } else { |
| 73 | + format!("{base_suffix}-{n}") |
| 74 | + }; |
| 75 | + let candidate = generate_backup_path(blocking_path, &suffix)?; |
| 76 | + match renamore::rename_exclusive(blocking_path, &candidate) { |
| 77 | + Ok(()) => return Ok(candidate), |
| 78 | + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => n += 1, |
| 79 | + Err(err) => { |
| 80 | + return Err(anyhow::Error::new(err).context(format!( |
| 81 | + "Failed to move {} to {}", |
| 82 | + format_path_for_display(blocking_path), |
| 83 | + format_path_for_display(&candidate), |
| 84 | + ))); |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +/// Move `blocking_path` aside to a timestamped `.bak.<YYYYmmdd-HHMMSS>` sibling. |
| 91 | +/// |
| 92 | +/// Wraps [`back_up_clobbered_path`] with the timestamp suffix computed at move |
| 93 | +/// time, so the suffix reflects when the path is actually set aside. Returns the |
| 94 | +/// path the blocking directory was moved to. |
| 95 | +pub(crate) fn back_up_clobbered_path_now(blocking_path: &Path) -> anyhow::Result<PathBuf> { |
| 96 | + let timestamp_secs = worktrunk::utils::epoch_now() as i64; |
| 97 | + let datetime = |
| 98 | + chrono::DateTime::from_timestamp(timestamp_secs, 0).unwrap_or_else(chrono::Utc::now); |
| 99 | + let base_suffix = datetime.format("%Y%m%d-%H%M%S").to_string(); |
| 100 | + back_up_clobbered_path(blocking_path, &base_suffix) |
| 101 | +} |
| 102 | + |
| 103 | +#[cfg(test)] |
| 104 | +mod tests { |
| 105 | + use super::*; |
| 106 | + |
| 107 | + #[test] |
| 108 | + fn test_generate_backup_path_with_extension() { |
| 109 | + // Paths with extensions: file.txt -> file.txt.bak.TIMESTAMP |
| 110 | + let path = PathBuf::from("/tmp/repo.feature"); |
| 111 | + let backup = generate_backup_path(&path, "20250101-000000").unwrap(); |
| 112 | + assert_eq!( |
| 113 | + backup, |
| 114 | + PathBuf::from("/tmp/repo.feature.bak.20250101-000000") |
| 115 | + ); |
| 116 | + |
| 117 | + let path = PathBuf::from("/tmp/file.txt"); |
| 118 | + let backup = generate_backup_path(&path, "20250101-000000").unwrap(); |
| 119 | + assert_eq!(backup, PathBuf::from("/tmp/file.txt.bak.20250101-000000")); |
| 120 | + } |
| 121 | + |
| 122 | + #[test] |
| 123 | + fn test_generate_backup_path_without_extension() { |
| 124 | + // Paths without extensions: foo -> foo.bak.TIMESTAMP |
| 125 | + let path = PathBuf::from("/tmp/repo/feature"); |
| 126 | + let backup = generate_backup_path(&path, "20250101-000000").unwrap(); |
| 127 | + assert_eq!( |
| 128 | + backup, |
| 129 | + PathBuf::from("/tmp/repo/feature.bak.20250101-000000") |
| 130 | + ); |
| 131 | + |
| 132 | + let path = PathBuf::from("/tmp/mydir"); |
| 133 | + let backup = generate_backup_path(&path, "20250101-000000").unwrap(); |
| 134 | + assert_eq!(backup, PathBuf::from("/tmp/mydir.bak.20250101-000000")); |
| 135 | + } |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn test_generate_backup_path_unusual_paths() { |
| 139 | + // Root path has no file name |
| 140 | + let path = PathBuf::from("/"); |
| 141 | + assert!(generate_backup_path(&path, "20250101-000000").is_err()); |
| 142 | + |
| 143 | + // Parent reference has no file name |
| 144 | + let path = PathBuf::from(".."); |
| 145 | + assert!(generate_backup_path(&path, "20250101-000000").is_err()); |
| 146 | + } |
| 147 | + |
| 148 | + #[test] |
| 149 | + fn test_back_up_clobbered_path_moves_to_fresh_suffix() { |
| 150 | + let temp = tempfile::tempdir().unwrap(); |
| 151 | + let stale = temp.path().join("feature"); |
| 152 | + std::fs::create_dir(&stale).unwrap(); |
| 153 | + std::fs::write(stale.join("file"), "content").unwrap(); |
| 154 | + |
| 155 | + let used = back_up_clobbered_path(&stale, "20250101-000000").unwrap(); |
| 156 | + |
| 157 | + assert_eq!(used, temp.path().join("feature.bak.20250101-000000")); |
| 158 | + assert!(!stale.exists(), "stale path should be moved away"); |
| 159 | + assert_eq!( |
| 160 | + std::fs::read_to_string(used.join("file")).unwrap(), |
| 161 | + "content" |
| 162 | + ); |
| 163 | + } |
| 164 | + |
| 165 | + #[test] |
| 166 | + fn test_back_up_clobbered_path_falls_back_when_suffix_taken() { |
| 167 | + let temp = tempfile::tempdir().unwrap(); |
| 168 | + let stale = temp.path().join("feature"); |
| 169 | + std::fs::create_dir(&stale).unwrap(); |
| 170 | + |
| 171 | + // The preferred backup name and its first -N variant are both taken. |
| 172 | + let taken = temp.path().join("feature.bak.20250101-000000"); |
| 173 | + std::fs::create_dir(&taken).unwrap(); |
| 174 | + std::fs::write(taken.join("keep"), "pre-existing").unwrap(); |
| 175 | + std::fs::create_dir(temp.path().join("feature.bak.20250101-000000-2")).unwrap(); |
| 176 | + |
| 177 | + let used = back_up_clobbered_path(&stale, "20250101-000000").unwrap(); |
| 178 | + |
| 179 | + // Lands on -3; neither pre-existing backup is overwritten. |
| 180 | + assert_eq!(used, temp.path().join("feature.bak.20250101-000000-3")); |
| 181 | + assert!(!stale.exists()); |
| 182 | + assert_eq!( |
| 183 | + std::fs::read_to_string(taken.join("keep")).unwrap(), |
| 184 | + "pre-existing" |
| 185 | + ); |
| 186 | + } |
| 187 | + |
| 188 | + #[test] |
| 189 | + fn test_back_up_clobbered_path_errors_when_source_missing() { |
| 190 | + // A missing source fails the rename with a non-AlreadyExists error, |
| 191 | + // which surfaces (with the "Failed to move" context) rather than being |
| 192 | + // retried. |
| 193 | + let temp = tempfile::tempdir().unwrap(); |
| 194 | + let missing = temp.path().join("does-not-exist"); |
| 195 | + let err = back_up_clobbered_path(&missing, "20250101-000000").unwrap_err(); |
| 196 | + assert!( |
| 197 | + err.to_string().contains("Failed to move"), |
| 198 | + "expected wrapped error, got: {err}" |
| 199 | + ); |
| 200 | + } |
| 201 | + |
| 202 | + #[test] |
| 203 | + fn test_back_up_clobbered_path_keeps_incrementing_past_many_collisions() { |
| 204 | + // There is no attempt cap: the move keeps counting up until a free |
| 205 | + // name is found, however many backups already exist. |
| 206 | + let temp = tempfile::tempdir().unwrap(); |
| 207 | + let stale = temp.path().join("feature"); |
| 208 | + std::fs::create_dir(&stale).unwrap(); |
| 209 | + |
| 210 | + // Occupy the preferred name and the first 49 -N fallbacks (suffix "S"). |
| 211 | + std::fs::create_dir(temp.path().join("feature.bak.S")).unwrap(); |
| 212 | + for n in 2..=50 { |
| 213 | + std::fs::create_dir(temp.path().join(format!("feature.bak.S-{n}"))).unwrap(); |
| 214 | + } |
| 215 | + |
| 216 | + let used = back_up_clobbered_path(&stale, "S").unwrap(); |
| 217 | + |
| 218 | + assert_eq!(used, temp.path().join("feature.bak.S-51")); |
| 219 | + assert!(!stale.exists(), "stale path should be moved away"); |
| 220 | + } |
| 221 | + |
| 222 | + #[test] |
| 223 | + fn test_back_up_clobbered_path_now_uses_timestamped_suffix() { |
| 224 | + let temp = tempfile::tempdir().unwrap(); |
| 225 | + let stale = temp.path().join("feature"); |
| 226 | + std::fs::create_dir(&stale).unwrap(); |
| 227 | + |
| 228 | + let used = back_up_clobbered_path_now(&stale).unwrap(); |
| 229 | + |
| 230 | + let name = used.file_name().unwrap().to_string_lossy(); |
| 231 | + assert!( |
| 232 | + name.starts_with("feature.bak."), |
| 233 | + "expected timestamped backup name, got: {name}" |
| 234 | + ); |
| 235 | + assert!(!stale.exists(), "stale path should be moved away"); |
| 236 | + } |
| 237 | +} |
0 commit comments