Add a shared error type and shared file helpers to the Rust host

Replace the three error styles with one Error type and one Result alias in
error.rs. The error crosses IPC as the same plain string as before. The
message text does not change.

Move the shared file mechanics to fsutil.rs. These are the reserved-name
check, the link and junction check, the limited reads, and the atomic
writes. Each module keeps its own path rules, limits, and messages. The
plugin settings writer now flushes its file to disk before the rename.

Remove the current_root_path and list_entries wrappers and an unused mime
value. Use named windows-sys constants for the process, file, drive, and
error codes.

Add a test that compares the command lists in lib.rs, build.rs, and the
capability files. The settings capability must be a subset of the full list.

In Cargo.toml, set the author, keep only the rlib crate type, and remove
the unused thiserror dependency. Remove panic = "abort" from the release
profile. A panic on a worker thread then stops only that thread. It does
not stop the editor with unsaved buffers.
This commit is contained in:
Knotty Wyvern
2026-10-27 22:41:11 -07:00
parent 69f90df571
commit bd46f3a189
18 changed files with 1103 additions and 882 deletions
+431
View File
@@ -0,0 +1,431 @@
//! 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<File> {
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<Option<Vec<u8>>> {
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.
pub fn create_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> {
write_temp_then(temp, bytes, || {
fs::hard_link(temp, path)?;
let _ = fs::remove_file(temp);
Ok(())
})
}
/// 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<()> {
if let Some(expected) = expected {
let current = fs::read_to_string(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.as_bytes()).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_to_string(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::<Vec<_>>();
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.
fs::hard_link(backup, path)?;
let _ = fs::remove_file(backup);
Ok(())
}
#[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();
}
#[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();
}
}