//! Shared file mechanics. //! //! Each caller keeps its own policy: which paths and characters it accepts, its size limits, //! and its error messages. This module holds only the mechanics that the callers share. use std::fs::{self, File, Metadata}; use std::io::{self, Read, Write}; use std::path::Path; use crate::error::{Error, Result}; /// True for the reserved Windows device names, also with an extension (`NUL.txt`). pub fn is_reserved_windows_name(name: &str) -> bool { let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4 && matches!(stem.as_bytes()[3], b'1'..=b'9')) } /// True for a name that can be one path component on every platform: not empty, /// not `.` or `..`, no trailing dot, and no reserved Windows name. /// Callers add their own character and length rules. pub fn is_plain_component(name: &str) -> bool { !name.is_empty() && name != "." && name != ".." && !name.ends_with('.') && !is_reserved_windows_name(name) } /// True for a Windows reparse point, which includes symbolic links and junctions. #[cfg(windows)] pub fn is_reparse_point(metadata: &Metadata) -> bool { use std::os::windows::fs::MetadataExt; use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT; metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 } #[cfg(not(windows))] pub fn is_reparse_point(_metadata: &Metadata) -> bool { false } /// True for a symbolic link, or for a junction or other reparse point on Windows. /// Use metadata from `fs::symlink_metadata` or from an open file. pub fn is_link(metadata: &Metadata) -> bool { metadata.file_type().is_symlink() || is_reparse_point(metadata) } /// Open a file for reading. On Windows, open a link entry itself, so that a replaced link cannot redirect the read. pub fn open_entry(path: &Path) -> io::Result { let mut options = File::options(); options.read(true); #[cfg(windows)] { use std::os::windows::fs::OpenOptionsExt; use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT; options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); } options.open(path) } /// Read at most `limit` bytes. Return `None` when the source holds more than `limit` bytes. pub fn read_to_limit(reader: impl Read, limit: u64) -> io::Result>> { let mut bytes = Vec::new(); reader.take(limit.saturating_add(1)).read_to_end(&mut bytes)?; Ok((bytes.len() as u64 <= limit).then_some(bytes)) } /// Create `temp`, write `bytes`, flush them to the disk, and then call `publish`. /// Remove `temp` if a step after its creation fails. Never remove a file that this call did not create. fn write_temp_then(temp: &Path, bytes: &[u8], publish: impl FnOnce() -> io::Result<()>) -> io::Result<()> { let mut file = File::options().write(true).create_new(true).open(temp)?; let written = file.write_all(bytes).and_then(|()| file.sync_all()); drop(file); let result = written.and_then(|()| publish()); if result.is_err() { let _ = fs::remove_file(temp); } result } /// Replace `path` with `bytes`. Write a complete copy at `temp` beside it first, then rename it, /// so that a failed write leaves the previous file intact. pub fn replace_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> { write_temp_then(temp, bytes, || fs::rename(temp, path)) } /// Publish a complete new file at `path` through `temp`. Fail if `path` exists, /// so that a file created by another writer is never replaced. /// /// The publish step moves `temp` to `path` without replacement. Some volumes (exFAT, FAT32, /// and many network or FUSE mounts) support neither an exclusive rename nor hard links. /// On these volumes, write the file in place with `create_new`. That write is not atomic, /// but it still never replaces an existing file. pub fn create_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> { create_file_with(path, temp, bytes, rename_no_replace) } fn create_file_with( path: &Path, temp: &Path, bytes: &[u8], publish: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> io::Result<()> { let mut unsupported = false; let result = write_temp_then(temp, bytes, || { publish(temp, path).inspect_err(|reason| unsupported = is_unsupported(reason)) }); if unsupported { return write_new(path, bytes); } result } /// Create `path` with `create_new`, write `bytes`, and flush them to the disk. /// Remove the file again if the write fails, because this call created it. fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> { let mut file = File::options().write(true).create_new(true).open(path)?; let written = file.write_all(bytes).and_then(|()| file.sync_all()); drop(file); if written.is_err() { let _ = fs::remove_file(path); } written } /// True when the volume does not support the operation, as opposed to a conflict or a permission problem. fn is_unsupported(reason: &io::Error) -> bool { if reason.kind() == io::ErrorKind::Unsupported { return true; } #[cfg(windows)] { use windows_sys::Win32::Foundation::{ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED}; matches!(reason.raw_os_error(), Some(code) if code == ERROR_INVALID_FUNCTION as i32 || code == ERROR_NOT_SUPPORTED as i32) } #[cfg(unix)] { // Linux returns EPERM from link(2) when the file system has no hard links. matches!(reason.raw_os_error(), Some(code) if code == libc::ENOTSUP || code == libc::EOPNOTSUPP || code == libc::ENOSYS || code == libc::EINVAL || code == libc::EPERM) } #[cfg(not(any(windows, unix)))] false } /// Move `from` to `to`. Fail with `AlreadyExists` if `to` exists, and never replace it. #[cfg(windows)] pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Storage::FileSystem::MoveFileExW; let wide = |value: &Path| value.as_os_str().encode_wide().chain(Some(0)).collect::>(); let (from_wide, to_wide) = (wide(from), wide(to)); // Without MOVEFILE_REPLACE_EXISTING, Windows refuses an existing destination. if unsafe { MoveFileExW(from_wide.as_ptr(), to_wide.as_ptr(), 0) } != 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } /// Move `from` to `to`. Fail with `AlreadyExists` if `to` exists, and never replace it. #[cfg(unix)] pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { match rename_exclusive(from, to) { Err(reason) if is_unsupported(&reason) => { // A hard link also refuses an existing destination. Remove the source name after it. fs::hard_link(from, to)?; let _ = fs::remove_file(from); Ok(()) } result => result, } } #[cfg(target_os = "linux")] fn rename_exclusive(from: &Path, to: &Path) -> io::Result<()> { use std::os::unix::ffi::OsStrExt; let from = std::ffi::CString::new(from.as_os_str().as_bytes())?; let to = std::ffi::CString::new(to.as_os_str().as_bytes())?; // The raw system call does not need the glibc 2.28 wrapper. let result = unsafe { libc::syscall(libc::SYS_renameat2, libc::AT_FDCWD, from.as_ptr(), libc::AT_FDCWD, to.as_ptr(), libc::RENAME_NOREPLACE) }; if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } #[cfg(target_os = "macos")] fn rename_exclusive(from: &Path, to: &Path) -> io::Result<()> { use std::os::unix::ffi::OsStrExt; let from = std::ffi::CString::new(from.as_os_str().as_bytes())?; let to = std::ffi::CString::new(to.as_os_str().as_bytes())?; let result = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_EXCL) }; if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))] fn rename_exclusive(_from: &Path, _to: &Path) -> io::Result<()> { Err(io::Error::from(io::ErrorKind::Unsupported)) } #[cfg(not(any(windows, unix)))] pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { fs::hard_link(from, to)?; let _ = fs::remove_file(from); Ok(()) } /// True when `left` and `right` name the same directory entry, for example the same file /// with a different letter case on a case-insensitive volume. Links are not followed. pub fn same_entry(left: &Path, right: &Path) -> io::Result { Ok(entry_identity(left)? == entry_identity(right)?) } #[cfg(unix)] fn entry_identity(path: &Path) -> io::Result<(u64, u64)> { use std::os::unix::fs::MetadataExt; let metadata = fs::symlink_metadata(path)?; Ok((metadata.dev(), metadata.ino())) } #[cfg(windows)] fn entry_identity(path: &Path) -> io::Result<(u32, u64)> { use std::os::windows::fs::OpenOptionsExt; use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Storage::FileSystem::{ GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, }; // Open the entry itself, also a folder or a link, with attribute access only. let file = File::options() .access_mode(FILE_READ_ATTRIBUTES) .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) .open(path)?; let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; if unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, &mut info) } == 0 { return Err(io::Error::last_os_error()); } Ok((info.dwVolumeSerialNumber, (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow))) } #[cfg(not(any(unix, windows)))] fn entry_identity(path: &Path) -> io::Result { fs::canonicalize(path) } /// Save `contents` at `path`. With `expected`, save only if the file still holds `expected`. /// Write completely beside the destination, then replace it. A failed write /// leaves the original file intact rather than truncating it. pub fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> Result<()> { write_checked(path, contents.as_bytes(), expected.map(str::as_bytes)) } /// Save `bytes` at `path` with the same atomic replacement as `write_text`. pub fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> { write_checked(path, bytes, None) } fn write_checked(path: &Path, contents: &[u8], expected: Option<&[u8]>) -> Result<()> { if let Some(expected) = expected { let current = fs::read(path).map_err(|_| { Error::new("Save blocked: file was removed or cannot be read. Your edits are still open.") })?; if current != expected { return Err(Error::new( "Save blocked: file changed on disk. Review the external changes before saving.", )); } } static NEXT_WRITE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let parent = path.parent().ok_or_else(|| Error::new("file has no parent"))?; let temp = parent.join(format!( ".runestone-save-{}-{}", std::process::id(), NEXT_WRITE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) )); let mut file = fs::OpenOptions::new() .write(true) .create_new(true) .open(&temp).map_err(|reason| Error::new(format!("Could not create a save file for {}: {reason}", path.display())))?; let result = (|| -> Result<()> { file.write_all(contents).map_err(|reason| Error::new(format!("Could not write the save file for {}: {reason}", path.display())))?; file.sync_all().map_err(|reason| Error::new(format!("Could not flush the save file for {}: {reason}", path.display())))?; #[cfg(not(windows))] if let Ok(metadata) = fs::metadata(path) { fs::set_permissions(&temp, metadata.permissions()).map_err(|reason| Error::new(format!("Could not preserve file permissions for {}: {reason}", path.display())))?; } drop(file); // Recheck after preparing the replacement to narrow the external-write race. if let Some(expected) = expected { if fs::read(path).ok().as_deref() != Some(expected) { return Err(Error::new( "Save blocked: file changed while saving. Your edits are still open.", )); } } replace_saved_file(&temp, path, expected.is_none())?; Ok(()) })(); if result.is_err() { let _ = fs::remove_file(&temp); } result } #[cfg(not(windows))] fn replace_saved_file(temp: &Path, path: &Path, _allow_create: bool) -> Result<()> { fs::rename(temp, path).map_err(|reason| Error::new(format!( "Could not replace {}: {reason}. Your edits are still open.", path.display() ))) } #[cfg(windows)] fn replace_saved_file(temp: &Path, path: &Path, allow_create: bool) -> Result<()> { use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Storage::FileSystem::ReplaceFileW; let metadata = match fs::metadata(path) { Ok(metadata) => metadata, Err(reason) if reason.kind() == io::ErrorKind::NotFound && allow_create => { return fs::rename(temp, path).map_err(|reason| Error::new(format!( "Could not publish {}: {reason}. Your edits are still open.", path.display() ))); } Err(reason) => return Err(Error::new(format!( "Could not read the destination {}: {reason}. Your edits are still open.", path.display() ))), }; if metadata.permissions().readonly() { return Err(Error::new(format!("Cannot save {} because it is read-only. Your edits are still open.", path.display()))); } // Canonical Windows paths retain the extended prefix for long filenames. let target = fs::canonicalize(path)?; let replacement = fs::canonicalize(temp)?; let backup = target.parent().ok_or_else(|| Error::new("file has no parent"))? .join(format!(".runestone-save-backup-{}", uuid::Uuid::new_v4())); if backup.try_exists()? { return Err(Error::new("The save backup path already exists. Retry saving.")); } let wide = |value: &Path| value.as_os_str().encode_wide().chain(Some(0)).collect::>(); let target_wide = wide(&target); let replacement_wide = wide(&replacement); let backup_wide = wide(&backup); // ReplaceFile preserves Windows file metadata. A backup allows recovery if // Windows moves the original but cannot publish its replacement. let replaced = unsafe { ReplaceFileW( target_wide.as_ptr(), replacement_wide.as_ptr(), backup_wide.as_ptr(), 0, std::ptr::null(), std::ptr::null(), ) }; if replaced != 0 { let _ = fs::remove_file(&backup); return Ok(()); } let reason = io::Error::last_os_error(); if backup.try_exists()? { if !path.try_exists()? { if let Err(restore) = restore_save_backup(&backup, path) { return Err(Error::new(format!( "Could not save {}: {reason}. Restore failed: {restore}. The original file remains at {}.", path.display(), backup.display() ))); } } else { return Err(Error::new(format!( "Could not save {}: {reason}. A recovery copy remains at {}. Your edits are still open.", path.display(), backup.display() ))); } } Err(Error::new(format!("Could not replace {}: {reason}. Your edits are still open.", path.display()))) } #[cfg(windows)] fn restore_save_backup(backup: &Path, path: &Path) -> io::Result<()> { // A concurrent writer must never lose its file during recovery. // A move without replacement also works on volumes without hard links. rename_no_replace(backup, path) } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; fn fixture(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("rs-fsutil-{name}-{}", uuid::Uuid::new_v4())); fs::create_dir(&dir).unwrap(); dir } #[test] fn reserved_names_and_plain_components() { for name in ["CON", "prn", "Aux.txt", "nul.tar.gz", "COM1", "lpt9.md"] { assert!(is_reserved_windows_name(name), "{name}"); assert!(!is_plain_component(name), "{name}"); } for name in ["COM0", "COM10", "LPT", "CONSOLE", "notes", "con-notes.md"] { assert!(!is_reserved_windows_name(name), "{name}"); } for name in ["", ".", "..", "trailing."] { assert!(!is_plain_component(name), "{name}"); } for name in ["notes.md", ".hidden", "a b", "COM10"] { assert!(is_plain_component(name), "{name}"); } } #[test] fn limited_reads_return_none_above_the_limit() { assert_eq!(read_to_limit(&b"1234"[..], 4).unwrap().as_deref(), Some(&b"1234"[..])); assert_eq!(read_to_limit(&b"12345"[..], 4).unwrap(), None); assert_eq!(read_to_limit(&b""[..], 0).unwrap().as_deref(), Some(&b""[..])); assert_eq!(read_to_limit(&b"1"[..], u64::MAX).unwrap().as_deref(), Some(&b"1"[..])); } #[test] fn replace_file_writes_completely_and_cleans_up() { let dir = fixture("replace"); let path = dir.join("state.json"); replace_file(&path, &dir.join("one.tmp"), b"first").unwrap(); replace_file(&path, &dir.join("two.tmp"), b"second").unwrap(); assert_eq!(fs::read(&path).unwrap(), b"second"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); // An existing temporary path is never overwritten or removed. fs::write(dir.join("taken.tmp"), "other writer").unwrap(); assert!(replace_file(&path, &dir.join("taken.tmp"), b"third").is_err()); assert_eq!(fs::read_to_string(dir.join("taken.tmp")).unwrap(), "other writer"); assert_eq!(fs::read(&path).unwrap(), b"second"); // A failed rename removes the temporary file and keeps the destination. fs::create_dir(dir.join("folder")).unwrap(); fs::write(dir.join("folder/keep.txt"), "keep").unwrap(); assert!(replace_file(&dir.join("folder"), &dir.join("three.tmp"), b"third").is_err()); assert!(!dir.join("three.tmp").exists()); assert_eq!(fs::read_to_string(dir.join("folder/keep.txt")).unwrap(), "keep"); fs::remove_dir_all(dir).unwrap(); } #[test] fn create_file_never_replaces_an_existing_file() { let dir = fixture("create"); let path = dir.join("note.md"); create_file(&path, &dir.join("one.tmp"), b"complete note\n").unwrap(); assert!(create_file(&path, &dir.join("two.tmp"), b"replacement").is_err()); assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); fs::remove_dir_all(dir).unwrap(); } #[test] fn create_file_publishes_without_hard_links_or_replacement() { let dir = fixture("create-exclusive"); let (from, to) = (dir.join("from.tmp"), dir.join("to.md")); fs::write(&from, "new").unwrap(); fs::write(&to, "existing").unwrap(); assert_eq!(rename_no_replace(&from, &to).unwrap_err().kind(), io::ErrorKind::AlreadyExists); assert_eq!(fs::read_to_string(&to).unwrap(), "existing"); assert_eq!(fs::read_to_string(&from).unwrap(), "new"); fs::remove_file(&to).unwrap(); rename_no_replace(&from, &to).unwrap(); assert_eq!(fs::read_to_string(&to).unwrap(), "new"); assert!(!from.exists()); fs::remove_dir_all(dir).unwrap(); } #[test] fn create_file_writes_in_place_on_volumes_without_an_exclusive_publish() { // exFAT, FAT32, and many network or FUSE mounts support neither an exclusive rename nor hard links. let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported)); let dir = fixture("create-fallback"); let path = dir.join("note.md"); create_file_with(&path, &dir.join("one.tmp"), b"complete note\n", unsupported).unwrap(); assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n"); let error = create_file_with(&path, &dir.join("two.tmp"), b"replacement", unsupported).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::AlreadyExists); assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); // A conflict is not a missing feature: it never falls back. let conflict = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::AlreadyExists)); assert!(create_file_with(&dir.join("other.md"), &dir.join("three.tmp"), b"x", conflict).is_err()); assert!(!dir.join("other.md").exists()); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); fs::remove_dir_all(dir).unwrap(); } #[test] fn same_entry_compares_items_without_following_names() { let dir = fixture("same-entry"); fs::write(dir.join("note.md"), "note").unwrap(); fs::write(dir.join("other.md"), "other").unwrap(); fs::create_dir(dir.join("folder")).unwrap(); assert!(same_entry(&dir.join("note.md"), &dir.join("note.md")).unwrap()); assert!(!same_entry(&dir.join("note.md"), &dir.join("other.md")).unwrap()); assert!(same_entry(&dir.join("folder"), &dir.join("folder")).unwrap()); // On a case-insensitive volume another spelling names the same item. if dir.join("NOTE.md").exists() { assert!(same_entry(&dir.join("note.md"), &dir.join("NOTE.md")).unwrap()); } assert!(same_entry(&dir.join("note.md"), &dir.join("missing.md")).is_err()); fs::remove_dir_all(dir).unwrap(); } #[test] fn binary_writes_replace_completely_and_clean_up() { let dir = fixture("bytes"); let path = dir.join("image.png"); write_bytes(&path, b"\x89PNG first").unwrap(); write_bytes(&path, b"\x89PNG second").unwrap(); assert_eq!(fs::read(&path).unwrap(), b"\x89PNG second"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); fs::create_dir(dir.join("folder.png")).unwrap(); assert!(write_bytes(&dir.join("folder.png"), b"x").is_err()); assert_eq!(fs::read_dir(&dir).unwrap().count(), 2); fs::remove_dir_all(dir).unwrap(); } #[cfg(any(unix, windows))] #[test] fn links_are_detected_from_link_metadata() { let dir = fixture("links"); fs::write(dir.join("file.txt"), "file").unwrap(); assert!(!is_link(&fs::symlink_metadata(dir.join("file.txt")).unwrap())); assert!(!is_link(&fs::symlink_metadata(&dir).unwrap())); #[cfg(unix)] let linked = std::os::unix::fs::symlink(dir.join("file.txt"), dir.join("link.txt")); #[cfg(windows)] let linked = std::os::windows::fs::symlink_file(dir.join("file.txt"), dir.join("link.txt")); match linked { Ok(()) => { let metadata = fs::symlink_metadata(dir.join("link.txt")).unwrap(); assert!(is_link(&metadata)); assert_eq!(is_reparse_point(&metadata), cfg!(windows)); assert!(!is_link(&open_entry(&dir.join("file.txt")).unwrap().metadata().unwrap())); } #[cfg(windows)] Err(reason) if reason.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => { eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege."); } Err(reason) => panic!("Could not prepare the link test: {reason}"), } fs::remove_dir_all(dir).unwrap(); } #[test] fn guarded_save_preserves_an_external_edit() { let dir = fixture("save"); let path = dir.join("note.md"); fs::write(&path, "agent changed this").unwrap(); assert!(write_text(&path, "my edit", Some("original")).is_err()); assert_eq!(fs::read_to_string(&path).unwrap(), "agent changed this"); write_text(&path, "merged edit", Some("agent changed this")).unwrap(); assert_eq!(fs::read_to_string(&path).unwrap(), "merged edit"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); fs::remove_dir_all(dir).unwrap(); } #[test] fn deleted_files_are_not_silently_recreated() { let path = std::env::temp_dir().join(format!("rs-missing-{}.md", uuid::Uuid::new_v4())); assert!(write_text(&path, "local edits", Some("original")).is_err()); assert!(!path.exists()); } #[cfg(windows)] #[test] fn windows_card_updates_preserve_file_streams() { let dir = fixture("card-save"); let path = dir.join("card.md"); create_file(&path, &dir.join("card.tmp"), b"original card").unwrap(); let stream = PathBuf::from(format!("{}:review-tag", path.display())); fs::write(&stream, "keep this metadata").unwrap(); write_text(&path, "card with second image", Some("original card")).unwrap(); write_text(&path, "updated description", Some("card with second image")).unwrap(); assert_eq!(fs::read_to_string(&path).unwrap(), "updated description"); assert_eq!(fs::read_to_string(&stream).unwrap(), "keep this metadata"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); fs::remove_file(&path).unwrap(); fs::remove_dir(&dir).unwrap(); } #[cfg(windows)] #[test] fn windows_blocked_replacement_keeps_the_original() { use std::os::windows::fs::OpenOptionsExt; use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ; let dir = fixture("locked-save"); let path = dir.join("card.md"); fs::write(&path, "original").unwrap(); let reader = fs::OpenOptions::new().read(true).share_mode(FILE_SHARE_READ).open(&path).unwrap(); let error = write_text(&path, "new", Some("original")).unwrap_err().to_string(); assert!(error.contains("Could not replace"), "{error}"); assert!(error.contains("card.md"), "{error}"); assert_eq!(fs::read_to_string(&path).unwrap(), "original"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); drop(reader); write_text(&path, "new", Some("original")).unwrap(); fs::remove_file(&path).unwrap(); fs::remove_dir(&dir).unwrap(); } #[cfg(windows)] #[test] // The test runs only on Windows, where this call clears the read-only attribute. #[allow(clippy::permissions_set_readonly_false)] fn windows_read_only_files_remain_protected() { let dir = fixture("readonly-save"); let path = dir.join("card.md"); fs::write(&path, "original").unwrap(); let mut permissions = fs::metadata(&path).unwrap().permissions(); permissions.set_readonly(true); fs::set_permissions(&path, permissions).unwrap(); let result = write_text(&path, "new", Some("original")); let mut permissions = fs::metadata(&path).unwrap().permissions(); permissions.set_readonly(false); fs::set_permissions(&path, permissions).unwrap(); assert!(result.unwrap_err().to_string().contains("read-only")); assert_eq!(fs::read_to_string(&path).unwrap(), "original"); assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); fs::remove_file(&path).unwrap(); fs::remove_dir(&dir).unwrap(); } #[cfg(windows)] #[test] fn windows_save_recovery_never_overwrites_a_newer_file() { let dir = fixture("save-recovery"); let path = dir.join("card.md"); let backup = dir.join("original.backup"); fs::write(&path, "concurrent edit").unwrap(); fs::write(&backup, "original").unwrap(); assert!(restore_save_backup(&backup, &path).is_err()); assert_eq!(fs::read_to_string(&path).unwrap(), "concurrent edit"); assert_eq!(fs::read_to_string(&backup).unwrap(), "original"); fs::remove_file(&path).unwrap(); restore_save_backup(&backup, &path).unwrap(); assert_eq!(fs::read_to_string(&path).unwrap(), "original"); assert!(!backup.exists()); fs::remove_file(&path).unwrap(); fs::remove_dir(&dir).unwrap(); } #[cfg(windows)] #[test] fn windows_save_supports_extended_paths() { let root = fixture("long-save"); let mut dir = root.clone(); for _ in 0..7 { dir.push("long-workspace-directory-name-1234567890"); } fs::create_dir_all(&dir).unwrap(); let path = dir.join("card.md"); write_text(&path, "original", None).unwrap(); write_text(&path, "updated", Some("original")).unwrap(); assert_eq!(fs::read_to_string(&path).unwrap(), "updated"); assert!(root.starts_with(std::env::temp_dir())); fs::remove_dir_all(root).unwrap(); } }