1use std::io;
31use std::path::Path;
32
33pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
36 #[cfg(windows)]
37 {
38 move_no_replace(from, to)
39 }
40 #[cfg(unix)]
41 {
42 match one_step(from, to) {
43 Some(result) => result,
44 None => in_steps(from, to),
45 }
46 }
47}
48
49#[cfg(windows)]
50fn move_no_replace(from: &Path, to: &Path) -> io::Result<()> {
51 use std::os::windows::ffi::OsStrExt;
52 #[link(name = "kernel32")]
54 extern "system" {
55 fn MoveFileExW(existing: *const u16, new: *const u16, flags: u32) -> i32;
56 }
57 let wide = |p: &Path| -> Vec<u16> { p.as_os_str().encode_wide().chain(std::iter::once(0)).collect() };
58 let (f, t) = (wide(from), wide(to));
59 if unsafe { MoveFileExW(f.as_ptr(), t.as_ptr(), 0) } == 0 {
63 return Err(io::Error::last_os_error());
64 }
65 Ok(())
66}
67
68#[cfg(any(target_os = "linux", target_os = "macos"))]
69fn c_path(p: &Path) -> io::Result<std::ffi::CString> {
70 use std::os::unix::ffi::OsStrExt;
71 Ok(std::ffi::CString::new(p.as_os_str().as_bytes())?)
72}
73
74#[cfg(target_os = "linux")]
76fn one_step(from: &Path, to: &Path) -> Option<io::Result<()>> {
77 const RENAME_NOREPLACE: libc::c_uint = 1;
79 let (f, t) = match (c_path(from), c_path(to)) {
80 (Ok(f), Ok(t)) => (f, t),
81 (Err(e), _) | (_, Err(e)) => return Some(Err(e)),
82 };
83 let r = unsafe {
86 libc::syscall(libc::SYS_renameat2, libc::AT_FDCWD, f.as_ptr(), libc::AT_FDCWD, t.as_ptr(), RENAME_NOREPLACE)
87 };
88 if r == 0 {
89 return Some(Ok(()));
90 }
91 let err = io::Error::last_os_error();
92 match err.raw_os_error() {
93 Some(libc::ENOSYS) | Some(libc::EINVAL) => None,
95 _ => Some(Err(err)),
96 }
97}
98
99#[cfg(target_os = "macos")]
100fn one_step(from: &Path, to: &Path) -> Option<io::Result<()>> {
101 let (f, t) = match (c_path(from), c_path(to)) {
102 (Ok(f), Ok(t)) => (f, t),
103 (Err(e), _) | (_, Err(e)) => return Some(Err(e)),
104 };
105 if unsafe { libc::renamex_np(f.as_ptr(), t.as_ptr(), libc::RENAME_EXCL) } == 0 {
107 return Some(Ok(()));
108 }
109 let err = io::Error::last_os_error();
110 match err.raw_os_error() {
111 Some(libc::ENOTSUP) | Some(libc::EINVAL) => None,
113 _ => Some(Err(err)),
114 }
115}
116
117#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
118fn one_step(_from: &Path, _to: &Path) -> Option<io::Result<()>> {
119 None
120}
121
122#[cfg(unix)]
125fn in_steps(from: &Path, to: &Path) -> io::Result<()> {
126 if std::fs::symlink_metadata(from)?.is_dir() {
128 return dir_by_claim(from, to);
129 }
130 match by_link(from, to) {
131 Err(e) if matches!(e.kind(), io::ErrorKind::AlreadyExists | io::ErrorKind::NotFound) => Err(e),
133 Err(_) => by_placeholder(from, to),
136 Ok(()) => Ok(()),
137 }
138}
139
140#[cfg(unix)]
143fn by_link(from: &Path, to: &Path) -> io::Result<()> {
144 std::fs::hard_link(from, to)?;
145 if let Err(e) = std::fs::remove_file(from) {
146 let _ = std::fs::remove_file(to);
148 return Err(e);
149 }
150 Ok(())
151}
152
153#[cfg(unix)]
156fn dir_by_claim(from: &Path, to: &Path) -> io::Result<()> {
157 std::fs::create_dir(to)?;
158 std::fs::rename(from, to).map_err(|e| {
159 let _ = std::fs::remove_dir(to);
161 match e.raw_os_error() {
162 Some(libc::ENOTEMPTY) | Some(libc::EEXIST) => io::Error::new(io::ErrorKind::AlreadyExists, e),
163 _ => e,
164 }
165 })
166}
167
168#[cfg(unix)]
171fn by_placeholder(from: &Path, to: &Path) -> io::Result<()> {
172 use std::os::unix::fs::MetadataExt;
173 let claim = std::fs::OpenOptions::new().write(true).create_new(true).open(to)?;
174 let still_the_claim = || match (claim.metadata(), std::fs::symlink_metadata(to)) {
176 (Ok(made), Ok(there)) => made.len() == 0 && made.dev() == there.dev() && made.ino() == there.ino(),
177 _ => false,
178 };
179 if !still_the_claim() {
180 return Err(io::Error::new(io::ErrorKind::AlreadyExists, "the new name was taken meanwhile"));
181 }
182 std::fs::rename(from, to).inspect_err(|_| {
183 if still_the_claim() {
184 let _ = std::fs::remove_file(to);
185 }
186 })
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use std::fs;
193 use std::sync::{Arc, Barrier};
194
195 type Rename = fn(&Path, &Path) -> io::Result<()>;
196
197 fn file_ways() -> Vec<(&'static str, Rename)> {
200 let mut ways: Vec<(&'static str, Rename)> = vec![("rename_no_replace", rename_no_replace)];
201 #[cfg(unix)]
202 ways.extend([
203 ("in_steps", in_steps as Rename),
204 ("by_link", by_link as Rename),
205 ("by_placeholder", by_placeholder as Rename),
206 ]);
207 ways
208 }
209
210 fn dir_ways() -> Vec<(&'static str, Rename)> {
211 let mut ways: Vec<(&'static str, Rename)> = vec![("rename_no_replace", rename_no_replace)];
212 #[cfg(unix)]
213 ways.extend([("in_steps", in_steps as Rename), ("dir_by_claim", dir_by_claim as Rename)]);
214 ways
215 }
216
217 #[test]
218 fn a_file_moves_to_a_free_name_with_its_content() {
219 for (way, rename) in file_ways() {
220 let dir = tempfile::tempdir().unwrap();
221 let (a, b) = (dir.path().join("a"), dir.path().join("b"));
222 fs::write(&a, "one").unwrap();
223 rename(&a, &b).unwrap_or_else(|e| panic!("{way}: {e}"));
224 assert!(!a.exists(), "{way}");
225 assert_eq!(fs::read_to_string(&b).unwrap(), "one", "{way}");
226 }
227 }
228
229 #[test]
230 fn a_taken_name_is_refused_and_both_files_keep_their_content() {
231 for (way, rename) in file_ways() {
232 let dir = tempfile::tempdir().unwrap();
233 let (a, b) = (dir.path().join("a"), dir.path().join("b"));
234 fs::write(&a, "one").unwrap();
235 fs::write(&b, "two").unwrap();
236 let err = rename(&a, &b).unwrap_err();
237 assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
238 assert_eq!(fs::read_to_string(&a).unwrap(), "one", "{way}");
239 assert_eq!(fs::read_to_string(&b).unwrap(), "two", "{way}");
240 }
241 }
242
243 #[test]
244 fn a_file_is_not_renamed_over_a_folder_even_an_empty_one() {
245 for (way, rename) in file_ways() {
246 let dir = tempfile::tempdir().unwrap();
247 let (a, b) = (dir.path().join("a"), dir.path().join("b"));
248 fs::write(&a, "one").unwrap();
249 fs::create_dir(&b).unwrap();
250 let err = rename(&a, &b).unwrap_err();
251 assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
252 assert!(a.is_file() && b.is_dir(), "{way}");
253 }
254 }
255
256 #[test]
257 fn a_missing_file_is_not_found_and_leaves_nothing_at_the_new_name() {
258 for (way, rename) in file_ways() {
259 let dir = tempfile::tempdir().unwrap();
260 let (a, b) = (dir.path().join("a"), dir.path().join("b"));
261 let err = rename(&a, &b).unwrap_err();
262 assert_eq!(err.kind(), io::ErrorKind::NotFound, "{way}: {err}");
263 assert!(fs::symlink_metadata(&b).is_err(), "{way}: something was left at the new name");
264 }
265 }
266
267 #[test]
268 fn a_folder_moves_with_what_is_in_it_and_never_over_another_folder() {
269 for (way, rename) in dir_ways() {
270 let dir = tempfile::tempdir().unwrap();
271 let (a, b, c) = (dir.path().join("a"), dir.path().join("b"), dir.path().join("c"));
272 fs::create_dir(&a).unwrap();
273 fs::write(a.join("inside"), "one").unwrap();
274 fs::create_dir(&b).unwrap();
276 let err = rename(&a, &b).unwrap_err();
277 assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
278 assert!(a.join("inside").is_file() && b.is_dir(), "{way}");
279
280 rename(&a, &c).unwrap_or_else(|e| panic!("{way}: {e}"));
281 assert!(!a.exists(), "{way}");
282 assert_eq!(fs::read_to_string(c.join("inside")).unwrap(), "one", "{way}");
283 }
284 }
285
286 #[cfg(unix)]
287 #[test]
288 fn a_link_stays_a_link_and_a_dangling_link_takes_its_name() {
289 use std::os::unix::fs::symlink;
290 for (way, rename) in [("rename_no_replace", rename_no_replace as Rename), ("by_link", by_link as Rename)] {
292 let dir = tempfile::tempdir().unwrap();
293 let (a, b, link, dangling) =
294 (dir.path().join("a"), dir.path().join("b"), dir.path().join("link"), dir.path().join("dangling"));
295 fs::write(&a, "one").unwrap();
296 symlink(&a, &link).unwrap();
297 symlink(dir.path().join("nowhere"), &dangling).unwrap();
298
299 let err = rename(&a, &dangling).unwrap_err();
300 assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{way}: {err}");
301 assert!(fs::symlink_metadata(&dangling).unwrap().file_type().is_symlink(), "{way}");
302
303 rename(&link, &b).unwrap_or_else(|e| panic!("{way}: {e}"));
304 assert!(fs::symlink_metadata(&b).unwrap().file_type().is_symlink(), "{way}");
305 assert_eq!(fs::read_to_string(&a).unwrap(), "one", "{way}");
306 }
307 }
308
309 #[cfg(unix)]
310 #[test]
311 fn a_folder_filled_while_it_is_renamed_over_keeps_what_was_put_in_it() {
312 let dir = tempfile::tempdir().unwrap();
314 let (a, b) = (dir.path().join("a"), dir.path().join("b"));
315 fs::create_dir(&a).unwrap();
316 fs::create_dir(&b).unwrap();
317 fs::write(b.join("theirs"), "two").unwrap();
318 let err = fs::rename(&a, &b).unwrap_err();
319 assert!(
320 matches!(err.raw_os_error(), Some(libc::ENOTEMPTY) | Some(libc::EEXIST)),
321 "a rename over a folder with something in it must fail: {err}"
322 );
323 assert_eq!(fs::read_to_string(b.join("theirs")).unwrap(), "two");
324 }
325
326 #[test]
329 fn two_renames_to_one_name_started_together_have_one_winner_and_lose_nothing() {
330 for (way, rename) in file_ways() {
331 let dir = tempfile::tempdir().unwrap();
332 for round in 0..100 {
333 let (a, b, to) = (dir.path().join("a"), dir.path().join("b"), dir.path().join(format!("to{round}")));
334 fs::write(&a, "one").unwrap();
335 fs::write(&b, "two").unwrap();
336 let start = Arc::new(Barrier::new(2));
337 let run = |from: std::path::PathBuf| {
338 let (start, to) = (start.clone(), to.clone());
339 std::thread::spawn(move || {
340 start.wait();
341 rename(&from, &to)
342 })
343 };
344 let (ra, rb) = (run(a.clone()), run(b.clone()));
345 let (ra, rb) = (ra.join().unwrap(), rb.join().unwrap());
346 let (won, lost, lost_at, lost_text, won_text) = match (&ra, &rb) {
347 (Ok(()), Err(e)) => (&a, e, &b, "two", "one"),
348 (Err(e), Ok(())) => (&b, e, &a, "one", "two"),
349 other => panic!("{way} round {round}: exactly one must win: {other:?}"),
350 };
351 assert_eq!(lost.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {lost}");
352 assert!(!won.exists(), "{way} round {round}: the winner's old name is still there");
353 assert_eq!(fs::read_to_string(&to).unwrap(), won_text, "{way} round {round}");
354 assert_eq!(fs::read_to_string(lost_at).unwrap(), lost_text, "{way} round {round}");
355 fs::remove_file(lost_at).unwrap();
356 }
357 }
358 }
359
360 #[test]
363 fn a_file_made_at_the_new_name_while_a_rename_is_under_way_is_never_replaced() {
364 for (way, rename) in file_ways() {
365 let dir = tempfile::tempdir().unwrap();
366 for round in 0..100 {
367 let (a, to) = (dir.path().join("a"), dir.path().join(format!("to{round}")));
368 fs::write(&a, "renamed").unwrap();
369 let start = Arc::new(Barrier::new(2));
370 let renamer = {
371 let (start, a, to) = (start.clone(), a.clone(), to.clone());
372 std::thread::spawn(move || {
373 start.wait();
374 rename(&a, &to)
375 })
376 };
377 let maker = {
378 let (start, to) = (start.clone(), to.clone());
379 std::thread::spawn(move || {
380 use std::io::Write;
381 start.wait();
382 fs::OpenOptions::new().write(true).create_new(true).open(&to)?.write_all(b"made")
383 })
384 };
385 let (renamed, made) = (renamer.join().unwrap(), maker.join().unwrap());
386 match (&renamed, &made) {
387 (Ok(()), Err(e)) => {
388 assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {e}");
389 assert_eq!(fs::read_to_string(&to).unwrap(), "renamed", "{way} round {round}");
390 assert!(!a.exists(), "{way} round {round}");
391 }
392 (Err(e), Ok(())) => {
393 assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {e}");
394 assert_eq!(fs::read_to_string(&to).unwrap(), "made", "{way} round {round}");
395 assert_eq!(fs::read_to_string(&a).unwrap(), "renamed", "{way} round {round}");
396 }
397 other => panic!("{way} round {round}: exactly one must get the name: {other:?}"),
398 }
399 }
400 }
401 }
402
403 #[test]
404 fn two_folders_renamed_to_one_name_together_have_one_winner_and_keep_their_files() {
405 for (way, rename) in dir_ways() {
406 let dir = tempfile::tempdir().unwrap();
407 for round in 0..50 {
408 let (a, b, to) = (dir.path().join("a"), dir.path().join("b"), dir.path().join(format!("to{round}")));
409 for (d, text) in [(&a, "one"), (&b, "two")] {
410 fs::create_dir(d).unwrap();
411 fs::write(d.join("inside"), text).unwrap();
412 }
413 let start = Arc::new(Barrier::new(2));
414 let run = |from: std::path::PathBuf| {
415 let (start, to) = (start.clone(), to.clone());
416 std::thread::spawn(move || {
417 start.wait();
418 rename(&from, &to)
419 })
420 };
421 let (ra, rb) = (run(a.clone()), run(b.clone()));
422 let (ra, rb) = (ra.join().unwrap(), rb.join().unwrap());
423 let (lost, lost_at, lost_text, won_text) = match (&ra, &rb) {
424 (Ok(()), Err(e)) => (e, &b, "two", "one"),
425 (Err(e), Ok(())) => (e, &a, "one", "two"),
426 other => panic!("{way} round {round}: exactly one must win: {other:?}"),
427 };
428 assert_eq!(lost.kind(), io::ErrorKind::AlreadyExists, "{way} round {round}: {lost}");
429 assert_eq!(fs::read_to_string(to.join("inside")).unwrap(), won_text, "{way} round {round}");
430 assert_eq!(fs::read_to_string(lost_at.join("inside")).unwrap(), lost_text, "{way} round {round}");
431 fs::remove_dir_all(lost_at).unwrap();
432 }
433 }
434 }
435}