diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 559b660d08..7f4052dfb8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1895,13 +1895,25 @@ fn rename(host: &Host, a: &[Data]) -> Result { { return Ok(error(NAME_TAKEN)); } + // Open objects hold real paths with the names the file system keeps, and `from` keeps the last + // name as given, which where case does not matter can differ in case: they are matched by the + // kept name. A link is renamed itself, and no object holds a path through it. When the kept + // name cannot be learned, nothing is renamed, so no object goes on under the old path's rules. + let kept = if was.file_type().is_symlink() { + from.clone() + } else { + match std::fs::canonicalize(&from) { + Ok(kept) => kept, + Err(_) => return Ok(error(WRITE_FAILED)), + } + }; if std::fs::rename(&from, &to).is_err() { return Ok(error(WRITE_FAILED)); } // Open objects of the file, or of files in the folder, write to the new path, and the rules for // reading apply to them there. let moved = |p: &mut Option| { - if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&kept).ok()) { *p = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } }; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 62f031528b..9fc69e080f 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1192,6 +1192,28 @@ fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() let _ = std::fs::remove_dir_all(base); } +/// Where case does not matter, a folder renamed under its name in another case still moves the open +/// objects of the files in it: changes are written under the new name, not lost at the old one. +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn script_file_rename_of_a_folder_named_in_another_case_moves_its_open_files() { + let base = folder("renamecase"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName; new Folder(d + '/sub').create();\n\ + var f = new File(d + '/sub/f.txt'); f.open('w'); f.write('kept');\n\ + var out = [new Folder(d + '/SUB').rename('moved'), f.close(), f.error]; vc.log(out); vc.log(d);", + ) + .unwrap(); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert_eq!(r["log"][0], json!([true, true, ""])); + assert_eq!(std::fs::read(d.join("moved/f.txt")).unwrap(), b"kept"); + assert!(!d.join("sub").exists()); + let _ = std::fs::remove_dir_all(base); +} + /// Where case matters, a rename to a name that differs in case alone does not replace the other file. #[cfg(target_os = "linux")] #[test]