diff --git a/docs/development.md b/docs/development.md index 4137909..748a159 100644 --- a/docs/development.md +++ b/docs/development.md @@ -58,6 +58,7 @@ Windows is the primary platform. macOS and Linux builds are experimental. | Module | Responsibility | | --- | --- | | `lib.rs` | App setup, command registration, window events | +| `error.rs`, `fsutil.rs` | The shared error type, and the shared file mechanics: name and link checks, limited reads, atomic writes | | `workspace.rs` | The workspace root of each window, path checks, atomic saves, the file watcher, search | | `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery | | `plugin_sources.rs` | Plugin downloads from Gitea releases | diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 5e5046d..930bdd8 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3145,7 +3145,6 @@ dependencies = [ "tauri-build", "tauri-plugin-dialog", "tauri-plugin-opener", - "thiserror 2.0.20", "uuid", "webview2-com", "windows", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 932599f..864ea62 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -2,12 +2,12 @@ name = "runestone" version = "0.1.44" description = "Writing workspace plus script editor" -authors = ["you"] +authors = ["Knotty Wyvern"] edition = "2021" [lib] name = "runestone_lib" -crate-type = ["staticlib", "cdylib", "rlib"] +crate-type = ["rlib"] [build-dependencies] tauri-build = { version = "2", features = [] } @@ -17,7 +17,6 @@ tauri = { version = "2", features = [] } tauri-plugin-opener = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" -thiserror = "2.0.20" notify = "8.2.0" ignore = "0.4.33" dunce = "1.0.5" @@ -30,7 +29,7 @@ uuid = { version = "1", features = ["v4"] } reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] } [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] } +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_WindowsProgramming", "Win32_UI_Input_KeyboardAndMouse"] } webview2-com = "0.38.2" windows = { version = "0.61.3", features = ["Win32_Foundation", "Win32_System_Com", "Win32_Globalization"] } @@ -40,7 +39,6 @@ windows = { version = "0.61.3", features = ["Win32_Foundation", "Win32_System_Co codegen-units = 1 lto = true opt-level = 3 -panic = "abort" strip = true [package.metadata.runestone] diff --git a/src-tauri/src/backgrounds.rs b/src-tauri/src/backgrounds.rs index b1be2e0..a3bcf8d 100644 --- a/src-tauri/src/backgrounds.rs +++ b/src-tauri/src/backgrounds.rs @@ -1,8 +1,9 @@ +use crate::error::{Error, Result}; +use crate::fsutil::{self, is_link}; use crate::plugins::PluginState; use base64::Engine; use serde::Serialize; -use std::fs::{self, File, Metadata}; -use std::io::Read; +use std::fs; use std::path::{Component, Path, PathBuf}; use tauri::{AppHandle, Manager, Window}; use tauri_plugin_dialog::DialogExt; @@ -10,16 +11,12 @@ use tauri_plugin_dialog::DialogExt; const IMAGE_LIMIT: u64 = 50 * 1024 * 1024; const SETTINGS_LIMIT: u64 = 1024 * 1024; const SETTINGS_FILE: &str = ".runestone-backgrounds.json"; -type Result = std::result::Result; #[derive(Debug, Serialize)] pub struct BackgroundFile { name: String, } -fn fail(error: impl std::fmt::Display) -> String { - error.to_string() -} fn require_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> { app.state::() @@ -35,26 +32,13 @@ fn folder_root(folder: &Path) -> Result { { return Err("Supply an absolute background folder path without parent segments.".into()); } - let root = dunce::canonicalize(folder).map_err(fail)?; + let root = dunce::canonicalize(folder)?; if !root.is_dir() { return Err("The background folder does not exist.".into()); } Ok(root) } -fn is_link(metadata: &Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } - #[cfg(windows)] - { - use std::os::windows::fs::MetadataExt; - return metadata.file_attributes() & 0x400 != 0; - } - #[cfg(not(windows))] - false -} - fn supported(name: &str) -> bool { Path::new(name) .extension() @@ -81,11 +65,11 @@ fn image_path(root: &Path, name: &str) -> Result { return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into()); } let path = root.join(name); - let metadata = fs::symlink_metadata(&path).map_err(fail)?; + let metadata = fs::symlink_metadata(&path)?; if !metadata.is_file() || is_link(&metadata) { return Err("Background images must be ordinary files, not links.".into()); } - let resolved = dunce::canonicalize(&path).map_err(fail)?; + let resolved = dunce::canonicalize(&path)?; if resolved.parent() != Some(root) { return Err("The background image is outside its folder.".into()); } @@ -95,8 +79,8 @@ fn image_path(root: &Path, name: &str) -> Result { fn list_images(folder: &Path) -> Result> { let root = folder_root(folder)?; let mut images = Vec::new(); - for entry in fs::read_dir(&root).map_err(fail)? { - let entry = entry.map_err(fail)?; + for entry in fs::read_dir(&root)? { + let entry = entry?; let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue; }; @@ -119,16 +103,9 @@ fn raster_signature(bytes: &[u8]) -> bool { fn read_image(folder: &Path, name: &str) -> Result> { let root = folder_root(folder)?; let path = image_path(&root, name)?; - let mut options = File::options(); - options.read(true); - #[cfg(windows)] - { - use std::os::windows::fs::OpenOptionsExt; - // Open the entry itself so a replaced link cannot redirect the read. - options.custom_flags(0x00200000); - } - let file = options.open(&path).map_err(fail)?; - let metadata = file.metadata().map_err(fail)?; + // Open the entry itself so a replaced link cannot redirect the read. + let file = fsutil::open_entry(&path)?; + let metadata = file.metadata()?; if !metadata.is_file() || is_link(&metadata) { return Err("Background images must be ordinary files, not links.".into()); } @@ -136,13 +113,9 @@ fn read_image(folder: &Path, name: &str) -> Result> { return Err("The background image exceeds 50 MiB.".into()); } image_path(&root, name)?; - let mut bytes = Vec::new(); - file.take(IMAGE_LIMIT + 1) - .read_to_end(&mut bytes) - .map_err(fail)?; - if bytes.len() as u64 > IMAGE_LIMIT { + let Some(bytes) = fsutil::read_to_limit(file, IMAGE_LIMIT)? else { return Err("The background image exceeds 50 MiB.".into()); - } + }; if !raster_signature(&bytes) { return Err("The file is not a supported raster image.".into()); } @@ -156,9 +129,9 @@ pub async fn backgrounds_default_folder( id: String, ) -> Result { require_plugin(&app, &window, &id)?; - let pictures = app.path().picture_dir().map_err(fail)?; + let pictures = app.path().picture_dir()?; let folder = pictures.join("RuneStone Backgrounds"); - fs::create_dir_all(&folder).map_err(fail)?; + fs::create_dir_all(&folder)?; require_plugin(&app, &window, &id)?; folder_root(&folder).map(|root| root.to_string_lossy().into_owned()) } @@ -180,12 +153,11 @@ pub async fn backgrounds_choose_folder( .set_title("Choose background image folder") .blocking_pick_folder() }) - .await - .map_err(fail)?; + .await?; require_plugin(&app, &window, &id)?; selected .map(|source| { - let path = source.into_path().map_err(fail)?; + let path = source.into_path().map_err(Error::from_display)?; folder_root(&path).map(|root| root.to_string_lossy().into_owned()) }) .transpose() @@ -200,8 +172,7 @@ pub async fn backgrounds_list( ) -> Result> { require_plugin(&app, &window, &id)?; let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder))) - .await - .map_err(fail)??; + .await??; require_plugin(&app, &window, &id)?; Ok(result) } @@ -217,8 +188,7 @@ pub async fn backgrounds_read( require_plugin(&app, &window, &id)?; let result = tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name)) - .await - .map_err(fail)??; + .await??; require_plugin(&app, &window, &id)?; Ok(base64::engine::general_purpose::STANDARD.encode(result)) } @@ -229,38 +199,29 @@ fn read_image_settings(folder: &Path) -> Result> { let metadata = match fs::symlink_metadata(&path) { Ok(metadata) => metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(fail(error)), + Err(error) => return Err(Error::from(error)), }; if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT { return Err("Image settings must be an ordinary file within 1 MiB.".into()); } - let mut options = File::options(); - options.read(true); - #[cfg(windows)] - { - use std::os::windows::fs::OpenOptionsExt; - options.custom_flags(0x00200000); - } - let file = options.open(&path).map_err(fail)?; - let metadata = file.metadata().map_err(fail)?; + let file = fsutil::open_entry(&path)?; + let metadata = file.metadata()?; if !metadata.is_file() || is_link(&metadata) { return Err("Image settings must be an ordinary file, not a link.".into()); } - let mut bytes = Vec::new(); - file.take(SETTINGS_LIMIT + 1).read_to_end(&mut bytes).map_err(fail)?; - if bytes.len() as u64 > SETTINGS_LIMIT { + let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else { return Err("Image settings exceed 1 MiB.".into()); - } - String::from_utf8(bytes).map(Some).map_err(fail) + }; + String::from_utf8(bytes).map(Some).map_err(Error::from) } fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> { static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - let _lock = WRITE_LOCK.lock().map_err(fail)?; + let _lock = WRITE_LOCK.lock()?; if contents.len() as u64 > SETTINGS_LIMIT { return Err("Image settings exceed 1 MiB.".into()); } - let value: serde_json::Value = serde_json::from_str(contents).map_err(fail)?; + let value: serde_json::Value = serde_json::from_str(contents)?; if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1) || !value.get("images").is_some_and(serde_json::Value::is_object) { @@ -272,27 +233,18 @@ fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) - } let path = root.join(SETTINGS_FILE); if expected.is_some() { - crate::workspace::write_text(&path, contents, expected).map_err(fail) + fsutil::write_text(&path, contents, expected) } else { // Publish a complete new file without replacing a file created by another process. let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4())); - let result = (|| -> Result<()> { - use std::io::Write; - let mut file = File::options().write(true).create_new(true).open(&temp).map_err(fail)?; - file.write_all(contents.as_bytes()).map_err(fail)?; - file.sync_all().map_err(fail)?; - drop(file); - fs::hard_link(&temp, &path).map_err(fail) - })(); - let _ = fs::remove_file(temp); - result + Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?) } } #[tauri::command] pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result> { require_plugin(&app, &window, &id)?; - let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await.map_err(fail)??; + let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??; require_plugin(&app, &window, &id)?; Ok(result) } @@ -304,7 +256,7 @@ pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id tauri::async_runtime::spawn_blocking(move || { require_plugin(&app, &window, &id)?; write_image_settings(Path::new(&folder), &contents, expected.as_deref()) - }).await.map_err(fail)? + }).await? } #[cfg(test)] @@ -339,7 +291,7 @@ mod tests { write_image_settings(&fixture.0, next, Some(first)).unwrap(); assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err()); assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err()); - File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap(); + fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap(); assert!(read_image_settings(&fixture.0).is_err()); } @@ -380,11 +332,13 @@ mod tests { fs::write(fixture.0.join("invalid.png"), b"").unwrap(); assert!(read_image(&fixture.0, "invalid.png") .unwrap_err() + .to_string() .contains("raster")); - let file = File::create(fixture.0.join("large.png")).unwrap(); + let file = fs::File::create(fixture.0.join("large.png")).unwrap(); file.set_len(IMAGE_LIMIT + 1).unwrap(); assert!(read_image(&fixture.0, "large.png") .unwrap_err() + .to_string() .contains("50 MiB")); } @@ -413,7 +367,7 @@ mod tests { std::os::unix::fs::symlink(&original, &link).unwrap(); #[cfg(windows)] if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) { - if error.raw_os_error() == Some(1314) { + if error.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."); return; } diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index 14c3a2b..e98f6c6 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -11,7 +11,8 @@ use std::{ }; use tauri::{AppHandle, Emitter, Manager, State}; -type Result = std::result::Result; +use crate::error::{Error, Result}; + const PLUGIN: &str = "runestone.browser"; const COMMANDS: &[&str] = &[ "state", @@ -102,11 +103,8 @@ struct Worker { healthy: bool, } -fn fail(error: impl std::fmt::Display) -> String { - error.to_string() -} fn root(app: &AppHandle) -> Result { - Ok(app.path().app_data_dir().map_err(fail)?.join("browser")) + Ok(app.path().app_data_dir()?.join("browser")) } fn executable(app: &AppHandle) -> Result { let name = if cfg!(windows) { @@ -127,8 +125,7 @@ fn executable(app: &AppHandle) -> Result { } let packaged = app .path() - .resource_dir() - .map_err(fail)? + .resource_dir()? .join("browser-engine") .join(name); if packaged.is_file() { @@ -141,10 +138,10 @@ fn authenticate_connection( stream: TcpStream, token: &str, ) -> Result)>> { - stream.set_nonblocking(false).map_err(fail)?; - stream.set_nodelay(true).map_err(fail)?; - stream.set_read_timeout(Some(Duration::from_secs(1))).map_err(fail)?; - let mut reader = BufReader::new(stream.try_clone().map_err(fail)?); + stream.set_nonblocking(false)?; + stream.set_nodelay(true)?; + stream.set_read_timeout(Some(Duration::from_secs(1)))?; + let mut reader = BufReader::new(stream.try_clone()?); let mut bytes = Vec::new(); let read = reader.by_ref().take(256).read_until(b'\n', &mut bytes); let received = serde_json::from_slice::(&bytes) @@ -154,18 +151,18 @@ fn authenticate_connection( return Ok(None); } // Windows keeps the timeout on the cloned socket after the original changes. - reader.get_ref().set_read_timeout(None).map_err(fail)?; - stream.set_read_timeout(None).map_err(fail)?; + reader.get_ref().set_read_timeout(None)?; + stream.set_read_timeout(None)?; Ok(Some((stream, reader))) } impl Worker { fn start(app: &AppHandle, routing: Arc>) -> Result { let directory = root(app)?; - fs::create_dir_all(&directory).map_err(fail)?; - let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(fail)?; - listener.set_nonblocking(true).map_err(fail)?; - let port = listener.local_addr().map_err(fail)?.port(); + fs::create_dir_all(&directory)?; + let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?; + listener.set_nonblocking(true)?; + let port = listener.local_addr()?.port(); let token = format!( "{}{}", uuid::Uuid::new_v4().simple(), @@ -186,9 +183,9 @@ impl Worker { #[cfg(windows)] { use std::os::windows::process::CommandExt; - command.creation_flags(0x08000000); + command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW); } - let mut child = command.spawn().map_err(fail)?; + let mut child = command.spawn()?; let deadline = Instant::now() + Duration::from_secs(30); let (input, output): (Box, Box) = loop { if let Ok((stream, _)) = listener.accept() { @@ -196,7 +193,7 @@ impl Worker { break (Box::new(stream), Box::new(reader)); } } - if Instant::now() >= deadline || child.try_wait().map_err(fail)?.is_some() { + if Instant::now() >= deadline || child.try_wait()?.is_some() { let _ = child.kill(); let _ = child.wait(); return Err("The browser runtime did not start.".into()); @@ -284,8 +281,8 @@ impl Worker { fn exchange(&mut self, command: &str, args: Value) -> Result { self.sequence += 1; let message = json!({ "id": self.sequence, "command": command, "args": args }); - writeln!(self.input, "{}", message).map_err(fail)?; - self.input.flush().map_err(fail)?; + writeln!(self.input, "{}", message)?; + self.input.flush()?; let response = self .replies .recv_timeout(Duration::from_secs(30)) @@ -306,7 +303,7 @@ impl Worker { let requested = self.request("shutdown", json!({})); let deadline = Instant::now() + Duration::from_secs(5); while Instant::now() < deadline { - if self.child.try_wait().map_err(fail)?.is_some() { + if self.child.try_wait()?.is_some() { return requested.map(|_| ()); } std::thread::sleep(Duration::from_millis(20)); @@ -332,17 +329,17 @@ fn profile_id(value: &str) -> bool { } fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64) -> Result<()> { if !source.exists() { - fs::create_dir_all(target).map_err(fail)?; + fs::create_dir_all(target)?; return Ok(()); } - let metadata = fs::symlink_metadata(source).map_err(fail)?; + let metadata = fs::symlink_metadata(source)?; if metadata.file_type().is_symlink() { return Err("Profile links cannot be duplicated.".into()); } if metadata.is_dir() { - fs::create_dir_all(target).map_err(fail)?; - for entry in fs::read_dir(source).map_err(fail)? { - let entry = entry.map_err(fail)?; + fs::create_dir_all(target)?; + for entry in fs::read_dir(source)? { + let entry = entry?; copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes)?; } } else if metadata.is_file() { @@ -351,7 +348,7 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64 if *files > 50_000 || *bytes > 2_000_000_000 { return Err("This profile exceeds the duplication limit.".into()); } - fs::copy(source, target).map_err(fail)?; + fs::copy(source, target)?; } else { return Err("Unsupported profile entry.".into()); } @@ -359,11 +356,11 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64 } impl BrowserState { fn connect(&self, owner: &str) -> Result { - let mut sessions = self.sessions.lock().map_err(fail)?; + let mut sessions = self.sessions.lock()?; Ok(sessions.entry(owner.to_string()).or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone()) } fn require_session(&self, owner: &str, token: &str) -> Result<()> { - if self.sessions.lock().map_err(fail)?.get(owner).is_some_and(|saved| saved == token) { + if self.sessions.lock()?.get(owner).is_some_and(|saved| saved == token) { Ok(()) } else { Err("The browser session is unavailable in this window.".into()) @@ -395,7 +392,7 @@ impl BrowserState { if !COMMANDS.contains(&command) || args.to_string().len() > 180_000 || !args.is_object() { return Err("Invalid browser request.".into()); } - let mut guard = self.inner.lock().map_err(fail)?; + let mut guard = self.inner.lock()?; if guard.as_ref().is_some_and(|worker| !worker.healthy) { guard.take(); } @@ -403,7 +400,7 @@ impl BrowserState { *guard = Some(Worker::start(app, Arc::new(Mutex::new(WindowTabs::default())))?); } let worker = guard.as_mut().unwrap(); - worker.routing.lock().map_err(fail)?.windows.insert(owner.to_string()); + worker.routing.lock()?.windows.insert(owner.to_string()); if command == "adoptTab" { let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?; let result = worker.request("state", json!({}))?; @@ -411,15 +408,15 @@ impl BrowserState { return Err("Unknown browser tab.".into()); } let source = { - let mut routes = worker.routing.lock().map_err(fail)?; + let mut routes = worker.routing.lock()?; routes.adopt(id, owner, args["transferToken"].as_str())? }; let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id })); - return Ok(worker.routing.lock().map_err(fail)?.snapshot(result, owner)); + return Ok(worker.routing.lock()?.snapshot(result, owner)); } if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) { let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?; - match worker.routing.lock().map_err(fail)?.owners.get(id) { + match worker.routing.lock()?.owners.get(id) { Some(window) if window == owner => {}, Some(_) => return Err("This browser tab belongs to another window.".into()), None => return Err("Unknown browser tab.".into()), @@ -429,26 +426,26 @@ impl BrowserState { let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?; let label = format!("browser-{}", uuid::Uuid::new_v4()); { - let mut routes = worker.routing.lock().map_err(fail)?; + let mut routes = worker.routing.lock()?; if routes.pending.contains_key(id) { return Err("This tab already has a pending window move.".into()); } routes.pending.insert(id.into(), label.clone()); routes.windows.insert(label.clone()); } - let mut url = tauri::Url::parse("http://localhost/").map_err(fail)?; + let mut url = tauri::Url::parse("http://localhost/").map_err(Error::from_display)?; url.query_pairs_mut().append_pair("browserWindow", "true"); url.query_pairs_mut().append_pair("browserTab", id); if args["pinned"] == true { url.query_pairs_mut().append_pair("browserPinned", "true"); } let result = tauri::WebviewWindowBuilder::new(app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into())) .title("RuneStone Browser").inner_size(1100.0, 750.0).min_inner_size(500.0, 300.0).decorations(false).disable_drag_drop_handler().build(); if let Err(error) = result { - worker.routing.lock().map_err(fail)?.close(&label); - return Err(fail(error)); + worker.routing.lock()?.close(&label); + return Err(Error::from(error)); } return Ok(json!({ "windowLabel": label })); } if command != "duplicateProfile" { let result = worker.request(command, args.clone())?; - let mut routes = worker.routing.lock().map_err(fail)?; + let mut routes = worker.routing.lock()?; if command == "newTab" { if let Some(id) = result["tabId"].as_str() { routes.assign(id, owner); } } else if command == "closeTab" { @@ -479,7 +476,7 @@ impl BrowserState { copy_profile(&source, &destination, &mut 0, &mut 0)?; *guard = Some(Worker::start(app, routing.clone())?); let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?; - let snapshot = routing.lock().map_err(fail)?.snapshot(result, owner); + let snapshot = routing.lock()?.snapshot(result, owner); Ok(snapshot) } } @@ -507,8 +504,7 @@ pub async fn browser_request( app.state::() .request(&app, &owner, &command, args) }) - .await - .map_err(fail)? + .await? } #[tauri::command] pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window) -> Result<()> { diff --git a/src-tauri/src/completion.rs b/src-tauri/src/completion.rs index ed08a10..aa31bbf 100644 --- a/src-tauri/src/completion.rs +++ b/src-tauri/src/completion.rs @@ -3,6 +3,8 @@ use reqwest::{blocking::Client, Url}; use serde::Deserialize; use tauri::{ipc::Channel, State, WebviewWindow}; +use crate::error::Result; + #[derive(Default)] pub struct CompletionState { requests: Mutex>> } impl CompletionState { @@ -15,7 +17,7 @@ impl CompletionState { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct CompletionRequest { endpoint: String, route: String, body: Option, timeout_ms: Option } -fn target(endpoint: &str, route: &str) -> Result { +fn target(endpoint: &str, route: &str) -> Result { let mut url = Url::parse(endpoint).map_err(|_| "Enter a local server URL.")?; if !matches!(url.scheme(), "http" | "https") || !matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost")) || !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some() @@ -31,7 +33,7 @@ pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState if let Ok(requests) = state.requests.lock() { if let Some(flag) = requests.get(&format!("{}:{id}", window.label())) { flag.store(true, Ordering::Relaxed); } } } #[tauri::command] -pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel) -> Result<(), String> { +pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel) -> Result<()> { if id.len() > 80 || request.body.as_ref().is_some_and(|v| v.len() > 32768) { return Err("Completion request is too large.".into()); } let url = target(&request.endpoint, &request.route)?; let flag = Arc::new(AtomicBool::new(false)); @@ -41,29 +43,29 @@ pub async fn completion_request(window: WebviewWindow, state: State<'_, Completi if requests.len() >= 16 { return Err("The local server is busy. Wait before retrying.".into()); } requests.insert(key.clone(), flag.clone()); } - let result = tauri::async_runtime::spawn_blocking(move || { + let result = tauri::async_runtime::spawn_blocking(move || -> Result<()> { let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none()) .connect_timeout(Duration::from_secs(2)).timeout(Duration::from_millis(request.timeout_ms.unwrap_or(5000).clamp(100, 15000))) - .build().map_err(|_| "Could not create a local connection.".to_string())?; + .build().map_err(|_| "Could not create a local connection.")?; if flag.load(Ordering::Relaxed) { return Ok(()); } let call = if let Some(body) = request.body { client.post(url).header("Content-Type", "application/json").body(body) } else { client.get(url) }; - let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." }.to_string())?; - if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16())); } + let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." })?; + if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16()).into()); } let mut reader = BufReader::new(response); let mut total = 0; loop { if flag.load(Ordering::Relaxed) { return Ok(()); } let mut bytes = Vec::new(); - let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.".to_string())?; + let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.")?; if count == 0 { break; } total += count; if count > 65536 || total > 262144 { return Err("Local response exceeded the size limit.".into()); } if flag.load(Ordering::Relaxed) { return Ok(()); } - let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.".to_string())?; + let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.")?; if on_line.send(line).is_err() { break; } } Ok(()) - }).await.map_err(|_| "Local completion task stopped.".to_string()); + }).await.map_err(|_| "Local completion task stopped."); if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); } result? } diff --git a/src-tauri/src/error.rs b/src-tauri/src/error.rs new file mode 100644 index 0000000..e985daf --- /dev/null +++ b/src-tauri/src/error.rs @@ -0,0 +1,113 @@ +//! The one error type of the host. +//! +//! An error is a message for the user. It crosses IPC as a plain JSON string, +//! so the frontend and the plugins receive the same text as before this type existed. +//! Every conversion keeps the `Display` text of its source error without changes. + +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(String); + +pub type Result = std::result::Result; + +impl Error { + pub fn new(message: impl Into) -> Self { + Self(message.into()) + } + + /// Use the text of a value that has no `From` conversion, such as an error of an indirect dependency. + pub fn from_display(error: impl fmt::Display) -> Self { + Self(error.to_string()) + } +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +impl serde::Serialize for Error { + fn serialize(&self, serializer: S) -> std::result::Result { + serializer.serialize_str(&self.0) + } +} + +impl From for Error { + fn from(message: String) -> Self { + Self(message) + } +} + +impl From<&str> for Error { + fn from(message: &str) -> Self { + Self(message.to_owned()) + } +} + +impl From for String { + fn from(error: Error) -> Self { + error.0 + } +} + +impl From> for Error { + fn from(error: std::sync::PoisonError) -> Self { + Self(error.to_string()) + } +} + +macro_rules! from_display { + ($($source:ty),* $(,)?) => { + $(impl From<$source> for Error { + fn from(error: $source) -> Self { + Self(error.to_string()) + } + })* + }; +} + +from_display!( + std::io::Error, + std::path::StripPrefixError, + std::str::Utf8Error, + std::string::FromUtf8Error, + std::sync::mpsc::RecvError, + std::time::SystemTimeError, + serde_json::Error, + notify::Error, + tauri::Error, + tauri_plugin_opener::Error, + uuid::Error, + zip::result::ZipError, +); + +#[cfg(windows)] +from_display!(windows::core::Error); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serializes_as_the_plain_message() { + let error = Error::new("Save blocked: file changed on disk."); + assert_eq!(serde_json::to_string(&error).unwrap(), r#""Save blocked: file changed on disk.""#); + assert_eq!( + serde_json::to_value(Err::<(), _>(error.clone())).unwrap(), + serde_json::to_value(Err::<(), _>("Save blocked: file changed on disk.")).unwrap(), + ); + assert_eq!(error.to_string(), "Save blocked: file changed on disk."); + } + + #[test] + fn conversions_keep_the_source_text() { + let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing file"); + assert_eq!(Error::from(io).to_string(), "missing file"); + let json = serde_json::from_str::("{").unwrap_err(); + assert_eq!(Error::from(json.to_string()), Error::from(json)); + assert_eq!(Error::from("text"), Error::new(String::from("text"))); + assert_eq!(String::from(Error::from_display(42)), "42"); + } +} diff --git a/src-tauri/src/fsutil.rs b/src-tauri/src/fsutil.rs new file mode 100644 index 0000000..e8dc6d3 --- /dev/null +++ b/src-tauri/src/fsutil.rs @@ -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 { + 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. +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::>(); + 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(); + } +} diff --git a/src-tauri/src/git.rs b/src-tauri/src/git.rs index 1a9e79c..665742a 100644 --- a/src-tauri/src/git.rs +++ b/src-tauri/src/git.rs @@ -1,4 +1,5 @@ -use crate::workspace::{current_root_path, WorkspaceState}; +use crate::error::Result; +use crate::workspace::{current_root, WorkspaceState}; use serde::Serialize; use std::io::Read; use std::path::{Component, Path, PathBuf}; @@ -34,12 +35,12 @@ pub struct GitLineInfo { summary: String, } -fn read_output(mut stream: impl Read) -> Result, String> { +fn read_output(mut stream: impl Read) -> Result> { let mut result = Vec::new(); let mut buffer = [0; 8192]; let mut overflow = false; loop { - let count = stream.read(&mut buffer).map_err(|e| e.to_string())?; + let count = stream.read(&mut buffer)?; if count == 0 { break; } @@ -59,7 +60,7 @@ fn read_output(mut stream: impl Read) -> Result, String> { } } -fn run(root: &Path, args: &[&str]) -> Result { +fn run(root: &Path, args: &[&str]) -> Result { let mut command = Command::new("git"); command .current_dir(root) @@ -88,7 +89,7 @@ fn run(root: &Path, args: &[&str]) -> Result { #[cfg(windows)] { use std::os::windows::process::CommandExt; - command.creation_flags(0x08000000); + command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW); } let mut child = command .spawn() @@ -101,7 +102,7 @@ fn run(root: &Path, args: &[&str]) -> Result { let mut completed = None; let status = loop { if completed.is_none() { - completed = child.try_wait().map_err(|e| e.to_string())?; + completed = child.try_wait()?; } if let Some(status) = completed { if out.is_finished() && err.is_finished() { @@ -115,7 +116,7 @@ fn run(root: &Path, args: &[&str]) -> Result { // Git can start SSH and credential helpers that also hold its output pipes. let _ = Command::new("taskkill") .args(["/PID", &child.id().to_string(), "/T", "/F"]) - .creation_flags(0x08000000) + .creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW) .stdout(Stdio::null()) .stderr(Stdio::null()) .status(); @@ -136,24 +137,24 @@ fn run(root: &Path, args: &[&str]) -> Result { }) } -fn checked(root: &Path, args: &[&str]) -> Result { +fn checked(root: &Path, args: &[&str]) -> Result { let output = run(root, args)?; if !output.status.success() { - return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned()); + return Err(String::from_utf8_lossy(&output.stderr).trim().into()); } String::from_utf8(output.stdout) .map_err(|_| "Git returned a filename that is not UTF-8.".into()) } -fn repository(root: &Path) -> Result<(), String> { +fn repository(root: &Path) -> Result<()> { let top = checked(root, &["rev-parse", "--show-toplevel"])?; - let top = dunce::canonicalize(top.trim()).map_err(|e| e.to_string())?; + let top = dunce::canonicalize(top.trim())?; if top != root { return Err("Open the repository root as your workspace to use Git.".into()); } for argument in ["--absolute-git-dir", "--git-common-dir"] { let git_dir = checked(root, &["rev-parse", argument])?; - let git_dir = dunce::canonicalize(root.join(git_dir.trim())).map_err(|e| e.to_string())?; + let git_dir = dunce::canonicalize(root.join(git_dir.trim()))?; if !git_dir.starts_with(root) { return Err( "Git metadata must be inside the workspace. Linked worktrees are not supported." @@ -164,7 +165,7 @@ fn repository(root: &Path) -> Result<(), String> { Ok(()) } -fn safe_path(root: &Path, value: &str) -> Result<(), String> { +fn safe_path(root: &Path, value: &str) -> Result<()> { if value.is_empty() || value.contains('\0') || value.contains('\\') || value.contains(':') { return Err("Choose a relative Git file path inside the workspace.".into()); } @@ -183,19 +184,19 @@ fn safe_path(root: &Path, value: &str) -> Result<(), String> { cursor.push(part); match std::fs::symlink_metadata(&cursor) { Ok(_) => { - let real = dunce::canonicalize(&cursor).map_err(|e| e.to_string())?; + let real = dunce::canonicalize(&cursor)?; if !real.starts_with(root) { return Err("The Git path points outside the workspace.".into()); } } Err(e) if e.kind() == std::io::ErrorKind::NotFound => break, - Err(e) => return Err(e.to_string()), + Err(e) => return Err(e.into()), } } Ok(()) } -fn parse_status(value: &str) -> Result, String> { +fn parse_status(value: &str) -> Result> { let mut records = value.split('\0').filter(|s| !s.is_empty()); let mut changes = Vec::new(); while let Some(record) = records.next() { @@ -224,7 +225,7 @@ fn parse_status(value: &str) -> Result, String> { Ok(changes) } -fn status(root: &Path) -> Result { +fn status(root: &Path) -> Result { let empty = |available| GitStatus { available, repository: false, @@ -253,19 +254,15 @@ fn status(root: &Path) -> Result { }) } -fn diff(root: &Path, path: &str, staged: bool) -> Result { +fn diff(root: &Path, path: &str, staged: bool) -> Result { repository(root)?; safe_path(root, path)?; let untracked = !staged && checked(root, &["ls-files", "--error-unmatch", "--", path]).is_err(); if untracked { - let file = std::fs::File::open(root.join(path)).map_err(|e| e.to_string())?; - let mut bytes = Vec::new(); - file.take(512 * 1024 + 1) - .read_to_end(&mut bytes) - .map_err(|e| e.to_string())?; - if bytes.len() > 512 * 1024 { + let file = std::fs::File::open(root.join(path))?; + let Some(bytes) = crate::fsutil::read_to_limit(file, 512 * 1024)? else { return Ok("This new file is too large to preview (512 KiB limit).".into()); - } + }; if bytes.contains(&0) { return Ok("Binary file. No text preview is available.".into()); } @@ -297,7 +294,7 @@ fn diff(root: &Path, path: &str, staged: bool) -> Result { checked(root, &args) } -fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String> { +fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<()> { repository(root)?; if paths.is_empty() || paths.len() > 10000 { return Err("Choose between 1 and 10,000 files.".into()); @@ -320,7 +317,7 @@ fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String Ok(()) } -fn commit(root: &Path, message: &str) -> Result<(), String> { +fn commit(root: &Path, message: &str) -> Result<()> { repository(root)?; if message.trim().is_empty() || message.len() > 65536 || message.contains('\0') { return Err("Enter a commit message between 1 and 65,536 bytes.".into()); @@ -329,7 +326,7 @@ fn commit(root: &Path, message: &str) -> Result<(), String> { Ok(()) } -fn upstream(root: &Path) -> Result<(String, String), String> { +fn upstream(root: &Path) -> Result<(String, String)> { let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]) .map_err(|_| "Select a branch outside RuneStone before you push or pull.")?; let branch = branch.trim(); @@ -360,7 +357,7 @@ fn upstream(root: &Path) -> Result<(String, String), String> { Ok((remote.into(), merge.into())) } -fn synchronize(root: &Path, push: bool) -> Result<(), String> { +fn synchronize(root: &Path, push: bool) -> Result<()> { repository(root)?; let (remote, reference) = upstream(root)?; if !push && !status(root)?.changes.is_empty() { @@ -418,7 +415,7 @@ pub struct GitGraph { commits: Vec, } -fn graph(root: &Path) -> Result { +fn graph(root: &Path) -> Result { repository(root)?; let has_head = run(root, &["rev-parse", "--verify", "HEAD"])? .status @@ -480,13 +477,13 @@ pub struct GitCommitDetails { message: String, files: Vec, } -fn commit_id(value: &str) -> Result<(), String> { +fn commit_id(value: &str) -> Result<()> { if ![40, 64].contains(&value.len()) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err("Select a commit from the Git graph.".into()); } Ok(()) } -fn parse_commit_files(value: &str) -> Result, String> { +fn parse_commit_files(value: &str) -> Result> { let mut records = value.split('\0').filter(|field| !field.is_empty()); let mut files = Vec::new(); while let Some(status) = records.next() { @@ -497,7 +494,7 @@ fn parse_commit_files(value: &str) -> Result, String> { } Ok(files) } -fn commit_details(root: &Path, id: &str) -> Result { +fn commit_details(root: &Path, id: &str) -> Result { commit_id(id)?; repository(root)?; let metadata = checked(root, &["show", "--no-patch", "--no-show-signature", "--format=%H%x00%P%x00%an%x00%aI%x00%B", id, "--"])?; @@ -511,7 +508,7 @@ fn commit_details(root: &Path, id: &str) -> Result { let files = parse_commit_files(&checked(root, &args)?)?; Ok(GitCommitDetails { id: fields[0].into(), parents, author: fields[2].into(), date: fields[3].into(), message: fields[4].trim_end().into(), files }) } -fn commit_diff(root: &Path, id: &str, path: &str) -> Result { +fn commit_diff(root: &Path, id: &str, path: &str) -> Result { let details = commit_details(root, id)?; safe_path(root, path)?; let file = details.files.iter().find(|file| file.path == path).ok_or("This file is not part of the selected commit.")?; @@ -525,7 +522,7 @@ fn commit_diff(root: &Path, id: &str, path: &str) -> Result { checked(root, &args) } -fn blame(root: &Path, path: &str, line: u32) -> Result, String> { +fn blame(root: &Path, path: &str, line: u32) -> Result> { repository(root)?; safe_path(root, path)?; if line == 0 { @@ -558,27 +555,25 @@ fn blame(root: &Path, path: &str, line: u32) -> Result, Stri })) } -fn root(state: &WorkspaceState, window: &Window) -> Result { - dunce::canonicalize(current_root_path(state, window.label()).map_err(|e| e.to_string())?) - .map_err(|e| e.to_string()) +fn root(state: &WorkspaceState, window: &Window) -> Result { + Ok(dunce::canonicalize(current_root(state, window.label())?)?) } async fn task( - action: impl FnOnce() -> Result + Send + 'static, -) -> Result { + action: impl FnOnce() -> Result + Send + 'static, +) -> Result { tauri::async_runtime::spawn_blocking(move || { let _guard = GIT_LOCK .lock() .map_err(|_| "The Git service lock is unavailable.")?; action() }) - .await - .map_err(|e| e.to_string())? + .await? } #[tauri::command] pub async fn git_status( window: Window, state: State<'_, WorkspaceState>, -) -> Result { +) -> Result { let root = root(&state, &window)?; task(move || status(&root)).await } @@ -588,7 +583,7 @@ pub async fn git_diff( state: State<'_, WorkspaceState>, path: String, staged: bool, -) -> Result { +) -> Result { let root = root(&state, &window)?; task(move || diff(&root, &path, staged)).await } @@ -597,7 +592,7 @@ pub async fn git_stage( window: Window, state: State<'_, WorkspaceState>, paths: Vec, -) -> Result<(), String> { +) -> Result<()> { let root = root(&state, &window)?; task(move || change_index(&root, &paths, true)).await } @@ -606,7 +601,7 @@ pub async fn git_unstage( window: Window, state: State<'_, WorkspaceState>, paths: Vec, -) -> Result<(), String> { +) -> Result<()> { let root = root(&state, &window)?; task(move || change_index(&root, &paths, false)).await } @@ -615,7 +610,7 @@ pub async fn git_commit( window: Window, state: State<'_, WorkspaceState>, message: String, -) -> Result<(), String> { +) -> Result<()> { let root = root(&state, &window)?; task(move || commit(&root, &message)).await } @@ -625,37 +620,37 @@ pub async fn git_blame( state: State<'_, WorkspaceState>, path: String, line: u32, -) -> Result, String> { +) -> Result> { let root = root(&state, &window)?; task(move || blame(&root, &path, line)).await } #[tauri::command] -pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> { +pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<()> { let root = root(&state, &window)?; task(move || synchronize(&root, true)).await } #[tauri::command] -pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> { +pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<()> { let root = root(&state, &window)?; task(move || synchronize(&root, false)).await } #[tauri::command] -pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result { +pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result { let root = root(&state, &window)?; task(move || graph(&root)).await } #[tauri::command] -pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result { +pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result { let root = root(&state, &window)?; task(move || commit_details(&root, &commit)).await } #[tauri::command] -pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result { +pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result { let root = root(&state, &window)?; task(move || commit_diff(&root, &commit, &path)).await } @@ -834,6 +829,7 @@ mod tests { } assert!(commit(&repo.0, "Must fail") .unwrap_err() + .to_string() .contains("Test hook rejected")); assert_eq!(status(&repo.0).unwrap().changes[0].index, "A"); } diff --git a/src-tauri/src/git_sync_tests.rs b/src-tauri/src/git_sync_tests.rs index 0aa5217..ad8707d 100644 --- a/src-tauri/src/git_sync_tests.rs +++ b/src-tauri/src/git_sync_tests.rs @@ -114,6 +114,7 @@ fn dirty_missing_upstream_detached_and_remote_errors_are_clear() { fixture.git("local", &["config", "merge.autoStash", "true"]); assert!(synchronize(&fixture.path("local"), false) .unwrap_err() + .to_string() .contains("clean working tree")); assert_eq!( std::fs::read_to_string(fixture.path("local/first.txt")).unwrap(), @@ -122,10 +123,12 @@ fn dirty_missing_upstream_detached_and_remote_errors_are_clear() { fixture.git("local", &["branch", "--unset-upstream"]); assert!(synchronize(&fixture.path("local"), true) .unwrap_err() + .to_string() .contains("no remote upstream")); fixture.git("local", &["checkout", "--detach"]); assert!(synchronize(&fixture.path("local"), true) .unwrap_err() + .to_string() .contains("Select a branch")); fixture.git("local", &["checkout", "main"]); fixture.git("local", &["branch", "--set-upstream-to=origin/main"]); @@ -135,6 +138,7 @@ fn dirty_missing_upstream_detached_and_remote_errors_are_clear() { ); assert!(synchronize(&fixture.path("local"), true) .unwrap_err() + .to_string() .contains("Push failed")); } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9474320..8f9f827 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,5 @@ +mod error; +mod fsutil; mod pty; mod terminal_platform; mod plugins; @@ -118,3 +120,91 @@ pub fn run() { } }); } + +#[cfg(test)] +mod command_list_tests { + //! Each command is listed in four places. This test keeps the lists the same. + use std::collections::BTreeSet; + use std::path::Path; + + fn read(relative: &str) -> String { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(relative); + std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("Cannot read {}: {error}", path.display())) + } + + /// Fail on a duplicate entry, which a set would hide. + fn unique(file: &str, names: impl Iterator) -> BTreeSet { + let mut set = BTreeSet::new(); + for name in names { + assert!(set.insert(name.clone()), "{file} lists the command {name} more than once."); + } + set + } + + /// The text between the first `start` and the next `end` after it. + fn section<'a>(text: &'a str, start: &str, end: &str, file: &str) -> &'a str { + let from = text.find(start).unwrap_or_else(|| panic!("{file} has no `{start}`")) + start.len(); + let length = text[from..].find(end).unwrap_or_else(|| panic!("{file} has no `{end}` after `{start}`")); + &text[from..from + length] + } + + fn handler_commands() -> BTreeSet { + let source = read("src/lib.rs"); + let list = section(&source, "generate_handler![", "]", "src/lib.rs"); + unique("src/lib.rs", list.split(',') + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(|entry| entry.rsplit("::").next().unwrap().to_owned())) + } + + fn build_commands() -> BTreeSet { + let source = read("build.rs"); + let list = section(&source, ".commands(&[", "]", "build.rs"); + unique("build.rs", list.split(',') + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(|entry| entry.trim_matches('"').to_owned())) + } + + fn capability_commands(relative: &str) -> BTreeSet { + let value: serde_json::Value = serde_json::from_str(&read(relative)) + .unwrap_or_else(|error| panic!("{relative} is not valid JSON: {error}")); + let permissions = value["permissions"] + .as_array() + .unwrap_or_else(|| panic!("{relative} has no permissions list")) + .iter() + .filter_map(|permission| permission.as_str()) + // Plugin permissions such as `core:default` have a prefix. App commands do not. + .filter(|permission| !permission.contains(':')) + .map(|permission| { + let command = permission.strip_prefix("allow-") + .unwrap_or_else(|| panic!("{relative} has an app permission without `allow-`: {permission}")); + command.replace('-', "_") + }); + unique(relative, permissions) + } + + fn difference(left: &BTreeSet, right: &BTreeSet) -> Vec { + left.difference(right).cloned().collect() + } + + #[test] + fn command_lists_match() { + let handler = handler_commands(); + let build = build_commands(); + let default = capability_commands("capabilities/default.json"); + let settings = capability_commands("capabilities/settings.json"); + assert!(handler.len() > 50, "Found only {} commands in generate_handler! in src/lib.rs", handler.len()); + for (name, list) in [("build.rs", &build), ("capabilities/default.json", &default)] { + assert!( + &handler == list, + "The commands in {name} differ from generate_handler! in src/lib.rs.\nMissing from {name}: {:?}\nOnly in {name}: {:?}", + difference(&handler, list), + difference(list, &handler), + ); + } + // The settings windows get an intentional subset of the commands. + let unknown = difference(&settings, &handler); + assert!(unknown.is_empty(), "capabilities/settings.json allows commands that generate_handler! in src/lib.rs does not register: {unknown:?}"); + } +} diff --git a/src-tauri/src/plugin_sources.rs b/src-tauri/src/plugin_sources.rs index e2d1488..a306ce6 100644 --- a/src-tauri/src/plugin_sources.rs +++ b/src-tauri/src/plugin_sources.rs @@ -3,7 +3,8 @@ use reqwest::{blocking::Client, Url}; use serde_json::Value; use std::{io::Read, time::Duration}; -type Result = std::result::Result; +use crate::error::Result; + const MAX_METADATA: usize = 2 * 1024 * 1024; const MAX_ARCHIVE: usize = 100 * 1024 * 1024; @@ -86,15 +87,9 @@ pub struct Download { } fn read_limited(reader: impl Read, limit: usize) -> Result> { - let mut bytes = Vec::new(); - reader - .take(limit as u64 + 1) - .read_to_end(&mut bytes) - .map_err(|_| "The download was interrupted. Try again.")?; - if bytes.len() > limit { - return Err("The download exceeds its size limit.".into()); - } - Ok(bytes) + crate::fsutil::read_to_limit(reader, limit as u64) + .map_err(|_| "The download was interrupted. Try again.")? + .ok_or_else(|| "The download exceeds its size limit.".into()) } // Send credentials only to the release API's origin, including after redirects. @@ -142,7 +137,7 @@ fn get( 401 | 403 => "Access denied. Check the token and repository read access.".into(), 404 => "Release not found. Check the repository, release tag, and token for private access.".into(), 429 => "The server request limit was reached. Try again later.".into(), - code => format!("The release server returned HTTP {code}."), + code => format!("The release server returned HTTP {code}.").into(), }); } if response @@ -323,6 +318,7 @@ pub(crate) mod tests { let url = Url::parse(&base).unwrap(); assert!(get(&client, url.clone(), &url, None, limit) .unwrap_err() + .to_string() .contains(message)); handle.join().unwrap(); } diff --git a/src-tauri/src/plugins.rs b/src-tauri/src/plugins.rs index 85853c2..00b868a 100644 --- a/src-tauri/src/plugins.rs +++ b/src-tauri/src/plugins.rs @@ -13,13 +13,12 @@ use tauri_plugin_dialog::DialogExt; use tauri_plugin_opener::OpenerExt; use uuid::Uuid; -type Result = std::result::Result; +use crate::error::{Error, Result}; +use crate::fsutil; + const MAX_FILES: usize = 5000; const MAX_FILE: u64 = 25 * 1024 * 1024; const MAX_TOTAL: usize = 100 * 1024 * 1024; -fn fail(error: impl std::fmt::Display) -> String { - error.to_string() -} fn uid() -> String { Uuid::new_v4().to_string() } @@ -131,41 +130,11 @@ pub struct PluginState { } fn normal_component(name: &str) -> bool { - if name.is_empty() || name == "." || name == ".." || name.ends_with('.') || name.len() > 120 { - return false; - } - if !name - .bytes() - .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) - { - return false; - } - let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); - !matches!( - stem.as_str(), - "CON" - | "PRN" - | "AUX" - | "NUL" - | "COM1" - | "COM2" - | "COM3" - | "COM4" - | "COM5" - | "COM6" - | "COM7" - | "COM8" - | "COM9" - | "LPT1" - | "LPT2" - | "LPT3" - | "LPT4" - | "LPT5" - | "LPT6" - | "LPT7" - | "LPT8" - | "LPT9" - ) + fsutil::is_plain_component(name) + && name.len() <= 120 + && name + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) } fn valid_id(id: &str) -> bool { normal_component(id) @@ -176,18 +145,14 @@ fn valid_id(id: &str) -> bool { } fn relative(name: &str) -> Result { if name.len() > 180 || !name.split('/').all(normal_component) { - return Err(format!("Invalid package path: {name}")); + return Err(format!("Invalid package path: {name}").into()); } Ok(name.split('/').collect()) } fn plain(path: &Path) -> Result { - let meta = fs::symlink_metadata(path).map_err(fail)?; - #[cfg(windows)] - { - use std::os::windows::fs::MetadataExt; - if meta.file_attributes() & 0x400 != 0 { - return Err("Links and junctions are not allowed in plugin paths.".into()); - } + let meta = fs::symlink_metadata(path)?; + if fsutil::is_reparse_point(&meta) { + return Err("Links and junctions are not allowed in plugin paths.".into()); } if meta.file_type().is_symlink() { return Err("Links are not allowed in plugin paths.".into()); @@ -199,16 +164,8 @@ fn bounded(path: &Path, limit: u64) -> Result> { if !meta.is_file() || meta.len() > limit { return Err("The package contains an invalid or oversized file.".into()); } - let mut data = Vec::new(); - fs::File::open(path) - .map_err(fail)? - .take(limit + 1) - .read_to_end(&mut data) - .map_err(fail)?; - if data.len() as u64 > limit { - return Err("The file exceeds the size limit.".into()); - } - Ok(data) + fsutil::read_to_limit(fs::File::open(path)?, limit)? + .ok_or_else(|| "The file exceeds the size limit.".into()) } fn add_file( files: &mut BTreeMap>, @@ -237,15 +194,14 @@ fn walk( count: &mut usize, ) -> Result<()> { plain(directory)?; - for entry in fs::read_dir(directory).map_err(fail)? { - let path = entry.map_err(fail)?.path(); + for entry in fs::read_dir(directory)? { + let path = entry?.path(); *count += 1; if *count > MAX_FILES { return Err("The package contains too many entries.".into()); } let name = path - .strip_prefix(root) - .map_err(fail)? + .strip_prefix(root)? .to_str() .ok_or("The package path is not UTF-8.")? .replace('\\', "/"); @@ -300,15 +256,14 @@ fn package(source: &Path) -> Result { return Err("The archive exceeds 100 MiB.".into()); } let mut archive = - zip::ZipArchive::new(fs::File::open(source).map_err(fail)?).map_err(fail)?; + zip::ZipArchive::new(fs::File::open(source)?)?; if archive.len() > MAX_FILES { return Err("The archive contains too many entries.".into()); } let mut archive_names = BTreeSet::new(); for index in 0..archive.len() { - let mut file = archive.by_index(index).map_err(fail)?; - let name = std::str::from_utf8(file.name_raw()) - .map_err(fail)? + let mut file = archive.by_index(index)?; + let name = std::str::from_utf8(file.name_raw())? .trim_end_matches('/') .to_string(); relative(&name)?; @@ -326,11 +281,8 @@ fn package(source: &Path) -> Result { if file.size() > MAX_FILE { return Err("An archive file exceeds 25 MiB.".into()); } - let mut bytes = Vec::new(); - file.by_ref() - .take(MAX_FILE + 1) - .read_to_end(&mut bytes) - .map_err(fail)?; + let bytes = fsutil::read_to_limit(file.by_ref(), MAX_FILE)? + .ok_or("The package exceeds the file count or size limit.")?; add_file(&mut files, &mut names, &mut total, name, bytes)?; } } @@ -340,7 +292,7 @@ fn package(source: &Path) -> Result { if bytes.len() > 64 * 1024 { return Err("The manifest exceeds 64 KiB.".into()); } - let manifest: Manifest = serde_json::from_slice(bytes).map_err(fail)?; + let manifest: Manifest = serde_json::from_slice(bytes)?; if !valid_id(&manifest.id) { return Err("The plugin ID is invalid.".into()); } @@ -369,8 +321,7 @@ fn package(source: &Path) -> Result { files .get(&manifest.entry) .ok_or("The entry module is missing.")?, - ) - .map_err(fail)?; + )?; let hash = fingerprint(&files); Ok(Package { manifest, @@ -394,8 +345,8 @@ fn require_zip(source: &Path) -> Result<()> { fn safe_child(parent: &Path, child: &Path) -> Result<()> { plain(parent)?; plain(child)?; - let parent = dunce::canonicalize(parent).map_err(fail)?; - let resolved = dunce::canonicalize(child).map_err(fail)?; + let parent = dunce::canonicalize(parent)?; + let resolved = dunce::canonicalize(child)?; if resolved.parent() != Some(parent.as_path()) { return Err("The plugin path is outside its managed directory.".into()); } @@ -405,27 +356,26 @@ fn erase(parent: &Path, target: &Path) -> Result<()> { safe_child(parent, target)?; fn descend(path: &Path, boundary: &Path) -> Result<()> { let meta = plain(path)?; - if !dunce::canonicalize(path) - .map_err(fail)? + if !dunce::canonicalize(path)? .starts_with(boundary) { return Err("Removal escaped its managed directory.".into()); } if meta.is_dir() { - for item in fs::read_dir(path).map_err(fail)? { - descend(&item.map_err(fail)?.path(), boundary)?; + for item in fs::read_dir(path)? { + descend(&item?.path(), boundary)?; } - fs::remove_dir(path).map_err(fail) + fs::remove_dir(path).map_err(Error::from) } else { - fs::remove_file(path).map_err(fail) + fs::remove_file(path).map_err(Error::from) } } - let boundary = dunce::canonicalize(target).map_err(fail)?; + let boundary = dunce::canonicalize(target)?; descend(target, &boundary) } impl Service { fn open(root: PathBuf) -> Result { - fs::create_dir_all(&root).map_err(fail)?; + fs::create_dir_all(&root)?; plain(&root)?; for name in [ "plugins", @@ -437,13 +387,13 @@ impl Service { if path.exists() { plain(&path)?; } else { - fs::create_dir(&path).map_err(fail)?; + fs::create_dir(&path)?; } safe_child(&root, &path)?; } let state = root.join("plugin-state.json"); let catalog: Catalog = if state.exists() { - serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?).map_err(fail)? + serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?)? } else { Catalog::default() }; @@ -452,7 +402,7 @@ impl Service { return Err("The plugin catalog contains an invalid ID.".into()); } if let Some(token) = &record.removal { - Uuid::parse_str(token).map_err(fail)?; + Uuid::parse_str(token)?; } } let mut service = Self { @@ -485,15 +435,15 @@ impl Service { } fn recover_updates(&mut self) -> Result<()> { let staging = self.directory("plugin-staging")?; - for entry in fs::read_dir(&staging).map_err(fail)? { - let entry = entry.map_err(fail)?; + for entry in fs::read_dir(&staging)? { + let entry = entry?; let name = entry.file_name().to_string_lossy().into_owned(); if !name.starts_with("update-") || !name.ends_with(".json") { continue; } - let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?).map_err(fail)?; + let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?)?; let id = journal.previous.manifest.id.clone(); if !valid_id(&id) { return Err("Invalid plugin update journal.".into()); } - Uuid::parse_str(&journal.backup).map_err(fail)?; - Uuid::parse_str(&journal.staged).map_err(fail)?; + Uuid::parse_str(&journal.backup)?; + Uuid::parse_str(&journal.staged)?; let target = self.directory("plugins")?.join(&id); let backup = staging.join(&journal.backup); let staged = staging.join(&journal.staged); @@ -509,9 +459,9 @@ impl Service { if package(&target)?.hash != journal.next_hash || staged.exists() { return Err("Plugin update recovery requires inspection of the staging directory.".into()); } - fs::rename(&target, &staged).map_err(fail)?; + fs::rename(&target, &staged)?; } - fs::rename(&backup, &target).map_err(fail)?; + fs::rename(&backup, &target)?; } } if !committed { @@ -536,17 +486,8 @@ impl Service { plain(&path)?; } let temp = self.root.join(format!("plugin-state-{}.tmp", uid())); - let data = serde_json::to_vec_pretty(&self.catalog).map_err(fail)?; - use std::io::Write; - let mut file = fs::OpenOptions::new() - .create_new(true) - .write(true) - .open(&temp) - .map_err(fail)?; - file.write_all(&data).map_err(fail)?; - file.sync_all().map_err(fail)?; - drop(file); - fs::rename(&temp, path).map_err(fail) + let data = serde_json::to_vec_pretty(&self.catalog)?; + Ok(fsutil::replace_file(&path, &temp, &data)?) } fn row(&self, id: &str) -> Result { let record = self @@ -576,7 +517,7 @@ impl Service { Some("Plugin files changed. Review them before enabling this plugin.".into()), ), Ok(current) => (current.hash, self.cleanup_errors.get(id).cloned()), - Err(error) => (record.hash.clone(), Some(error)), + Err(error) => (record.hash.clone(), Some(error.to_string())), }; Ok(PluginRow { manifest, @@ -591,8 +532,8 @@ impl Service { fn snapshot(&mut self) -> Result { let mut changed = false; let directory = self.directory("plugins")?; - for entry in fs::read_dir(&directory).map_err(fail)? { - let path = entry.map_err(fail)?.path(); + for entry in fs::read_dir(&directory)? { + let path = entry?.path(); let id = path .file_name() .unwrap_or_default() @@ -643,7 +584,7 @@ impl Service { fn inspect(&mut self, owner: &str, source: PathBuf) -> CandidateRow { let token = uid(); let display = source.to_string_lossy().into_owned(); - let result = (|| { + let result = (|| -> Result { let current = package(&source)?; let previous = self.catalog.plugins.get(¤t.manifest.id).cloned(); if let Some(record) = &previous { @@ -655,7 +596,7 @@ impl Service { return Err("Refresh the plugin list before installing this package.".into()); } let staging = self.directory("plugin-staging")?.join(&token); - fs::create_dir(&staging).map_err(fail)?; + fs::create_dir(&staging)?; for (name, bytes) in ¤t.files { let target = staging.join(relative(name)?); if self @@ -669,8 +610,8 @@ impl Service { { return Err("The installed path would exceed 240 characters.".into()); } - fs::create_dir_all(target.parent().unwrap()).map_err(fail)?; - fs::write(target, bytes).map_err(fail)?; + fs::create_dir_all(target.parent().unwrap())?; + fs::write(target, bytes)?; } let manifest = current.manifest.clone(); self.candidates.insert( @@ -705,7 +646,7 @@ impl Service { token, source: display, manifest: None, - error: Some(error), + error: Some(error.to_string()), } } } @@ -713,7 +654,7 @@ impl Service { fn inspect_download(&mut self, owner: &str, download: crate::plugin_sources::Download) -> Result { let parent = self.directory("plugin-staging")?; let archive = parent.join(format!("{}.zip", uid())); - fs::write(&archive, download.bytes).map_err(fail)?; + fs::write(&archive, download.bytes)?; let mut row = self.inspect(owner, archive.clone()); if let Some(candidate) = self.candidates.get_mut(&row.token) { // Review pins the downloaded bytes. Remote releases can change independently. @@ -753,8 +694,7 @@ impl Service { } safe_child(&self.directory("plugin-staging")?, &candidate.directory)?; let installed_at = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(fail)? + .duration_since(UNIX_EPOCH)? .as_millis() as u64; // Persist disabled first. A crash cannot enable unreviewed or partial code. self.catalog.plugins.insert( @@ -776,13 +716,13 @@ impl Service { if let Err(error) = fs::rename(&candidate.directory, &target) { self.catalog.plugins.remove(&id); let _ = self.persist(); - return Err(fail(error)); + return Err(Error::from(error)); } if enabled { self.catalog.plugins.get_mut(&id).unwrap().enabled = true; if let Err(error) = self.persist() { self.catalog.plugins.get_mut(&id).unwrap().enabled = false; - return Err(format!("Installed but disabled: {error}")); + return Err(format!("Installed but disabled: {error}").into()); } } Ok(candidate.manifest.name) @@ -838,21 +778,21 @@ impl Service { let journal = UpdateJournal { previous: previous.clone(), next_hash: candidate.hash.clone(), backup: backup.file_name().unwrap().to_string_lossy().into_owned(), staged: candidate.directory.file_name().unwrap().to_string_lossy().into_owned() }; - fs::write(&journal_path, serde_json::to_vec(&journal).map_err(fail)?).map_err(fail)?; - fs::rename(&target, &backup).map_err(fail)?; + fs::write(&journal_path, serde_json::to_vec(&journal)?)?; + fs::rename(&target, &backup)?; if let Err(error) = fs::rename(&candidate.directory, &target) { - fs::rename(&backup, &target).map_err(fail)?; + fs::rename(&backup, &target)?; let _ = erase(&staging, &journal_path); - return Err(fail(error)); + return Err(Error::from(error)); } self.catalog.plugins.insert(id.clone(), Installed { manifest: candidate.manifest.clone(), hash: candidate.hash.clone(), enabled: previous.enabled, - installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH).map_err(fail)?.as_millis() as u64), + installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64), removal: None, removal_files: BTreeMap::new(), }); if let Err(error) = self.persist() { - fs::rename(&target, &candidate.directory).map_err(fail)?; - fs::rename(&backup, &target).map_err(fail)?; + fs::rename(&target, &candidate.directory)?; + fs::rename(&backup, &target)?; self.catalog.plugins.insert(id, previous); let _ = erase(&staging, &journal_path); return Err(error); @@ -927,7 +867,7 @@ impl Service { if let Some(error) = self.cleanup_errors.get(id) { return Err(format!( "Cleanup failed. Restart RuneStone before removal. {error}" - )); + ).into()); } let parent = self.directory("plugins")?; let target = parent.join(id); @@ -954,7 +894,7 @@ impl Service { if let Err(error) = fs::rename(&target, &destination) { self.catalog.plugins.get_mut(id).unwrap().removal = None; let _ = self.persist(); - return Err(fail(error)); + return Err(Error::from(error)); } if tree_hash(&destination)? != current_hash { return Err("Plugin files changed during removal. Inspect the removal directory before retrying.".into()); @@ -968,7 +908,7 @@ impl Service { .get(id) .and_then(|record| record.removal.clone()) .ok_or("No confirmed removal exists.")?; - Uuid::parse_str(&token).map_err(fail)?; + Uuid::parse_str(&token)?; let parent = self.directory("plugin-removals")?; let target = parent.join(&token); if self.directory("plugins")?.join(id).exists() { @@ -984,7 +924,7 @@ impl Service { return Err(format!( "Removal files changed. Inspect {} before retrying.", target.display() - )); + ).into()); } } erase(&parent, &target)?; @@ -1010,9 +950,9 @@ impl PluginState { app: &AppHandle, action: impl FnOnce(&mut Service) -> Result, ) -> Result { - let mut guard = self.inner.lock().map_err(fail)?; + let mut guard = self.inner.lock()?; if guard.is_none() { - *guard = Some(Service::open(app.path().app_data_dir().map_err(fail)?)?); + *guard = Some(Service::open(app.path().app_data_dir()?)?); } action(guard.as_mut().unwrap()) } @@ -1060,8 +1000,7 @@ pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result Result = sources .into_iter() - .map(|source| source.into_path().map_err(fail)) + .map(|source| source.into_path().map_err(Error::from_display)) .collect::>()?; for path in &paths { require_zip(path)?; @@ -1094,7 +1033,7 @@ pub async fn plugins_from_git( // Network access never holds the plugin service lock. let download = tauri::async_runtime::spawn_blocking(move || { crate::plugin_sources::download(&repository, token.as_deref()) - }).await.map_err(fail)??; + }).await??; app.state::().with(&app, |service| { Ok(vec![service.inspect_download(window.label(), download)?]) }) @@ -1149,7 +1088,7 @@ pub async fn plugins_install( let start = Instant::now(); while state.with(&app, |service| Ok(service.leases.get(id).is_some_and(|windows| !windows.is_empty())))? && start.elapsed() < Duration::from_secs(10) { - tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await.map_err(fail)?; + tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await?; } } let installed = state.with(&app, |service| { @@ -1168,7 +1107,7 @@ pub async fn plugins_install( installed.err() } }; - result.push(InstallResult { name, error }); + result.push(InstallResult { name, error: error.map(String::from) }); } changed(&app); Ok(result) @@ -1236,7 +1175,7 @@ pub async fn plugins_load( .entry(id) .or_default() .insert(window.label().into()); - String::from_utf8(current.files[¤t.manifest.entry].clone()).map_err(fail) + String::from_utf8(current.files[¤t.manifest.entry].clone()).map_err(Error::from) }) } #[tauri::command] @@ -1297,8 +1236,7 @@ pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String result }) }) - .await - .map_err(fail)?; + .await?; changed(&app); result } @@ -1335,9 +1273,9 @@ pub async fn plugins_reveal( if open_directory { app.opener() .open_path(path.to_string_lossy().into_owned(), None::<&str>) - .map_err(fail) + .map_err(Error::from) } else { - app.opener().reveal_item_in_dir(path).map_err(fail) + app.opener().reveal_item_in_dir(path).map_err(Error::from) } } #[tauri::command] @@ -1355,7 +1293,7 @@ pub async fn plugins_data( let parent = service.directory("plugin-data")?; let dir = parent.join(&id); if !dir.exists() { - fs::create_dir(&dir).map_err(fail)?; + fs::create_dir(&dir)?; } safe_child(&parent, &dir)?; let path = dir.join("settings.json"); @@ -1363,16 +1301,15 @@ pub async fn plugins_data( if value.len() > 1024 * 1024 { return Err("Plugin settings exceed 1 MiB.".into()); } - serde_json::from_str::(&value).map_err(fail)?; + serde_json::from_str::(&value)?; if path.exists() { plain(&path)?; } let temp = dir.join(format!("{}.tmp", uid())); - fs::write(&temp, value).map_err(fail)?; - fs::rename(temp, &path).map_err(fail)?; + fsutil::replace_file(&path, &temp, value.as_bytes())?; } if path.exists() { - String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(fail) + String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(Error::from) } else { Ok("null".into()) } @@ -1611,10 +1548,10 @@ mod tests { let candidate = f.service.inspect("main", f.source.clone()); f.service.leases.entry(id.clone()).or_default().insert("main".into()); f.service.begin_update("main", &candidate.token).unwrap(); - assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("cleanup")); + assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("cleanup")); f.service.leases.clear(); fs::write(f.source.join("main.js"), "changed after review").unwrap(); - assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("changed after review")); + assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("changed after review")); assert_eq!(f.service.row(&id).unwrap().manifest.version, "1.0.0"); assert_eq!(fs::read_to_string(f.service.directory("plugins").unwrap().join(&id).join("main.js")).unwrap(), "export function activate() {}"); } @@ -1684,7 +1621,7 @@ mod tests { assert!(require_zip(&upper).is_ok()); let wrapped = f.root.join("wrapped.zip"); archive(&wrapped, &[("demo/plugin.json", b"{}")]); - assert!(package(&wrapped).unwrap_err().contains("at its root")); + assert!(package(&wrapped).unwrap_err().to_string().contains("at its root")); } #[test] fn author_packager_produces_an_installable_repeatable_zip() { @@ -1829,7 +1766,7 @@ mod tests { assert!(package(&path).is_err()); assert!(!f.root.join("outside").exists()); archive(&path, &[("main.js", b"a"), ("MAIN.js", b"b")]); - assert!(package(&path).unwrap_err().contains("duplicate")); + assert!(package(&path).unwrap_err().to_string().contains("duplicate")); let manifest = fs::read_to_string(f.source.join("plugin.json")) .unwrap() .replace("\"apiVersion\":1", "\"apiVersion\":99"); diff --git a/src-tauri/src/pty.rs b/src-tauri/src/pty.rs index a4e182c..28dda84 100644 --- a/src-tauri/src/pty.rs +++ b/src-tauri/src/pty.rs @@ -8,15 +8,10 @@ use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager, State}; -use crate::workspace::{current_root_path, WorkspaceError, WorkspaceState}; +use crate::error::{Error, Result}; +use crate::workspace::{current_root, WorkspaceState}; use crate::terminal_platform::find_executable; -type PtyResult = Result; - -fn err(msg: impl Into) -> WorkspaceError { - WorkspaceError::from_message(msg) -} - pub struct PtyState { inner: Mutex>, } @@ -153,7 +148,7 @@ PROMPT_COMMAND=("${PROMPT_COMMAND[@]}" __rs_prompt) PS1="${PS1}"'\[\e]133;B\a\]' "#; -fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: &str) -> PtyResult { +fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: &str) -> Result { let system = native_pty_system(); let pair = system .openpty(PtySize { @@ -162,10 +157,10 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: pixel_width: 0, pixel_height: 0, }) - .map_err(|e| err(e.to_string()))?; + .map_err(Error::from_display)?; let profiles = pty_profiles(); let selected = profiles.iter().find(|p| profile.map_or(p.kind != "node", |id| p.id == id)) - .ok_or_else(|| err("The selected shell is not installed. Select another terminal profile."))?; + .ok_or_else(|| Error::new("The selected shell is not installed. Select another terminal profile."))?; let mut cmd = CommandBuilder::new(&selected.executable); let mut integration_file = None; match selected.kind.as_str() { @@ -183,7 +178,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: } "cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); } "node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); } - _ => return Err(err("Unsupported shell profile")), + _ => return Err(Error::new("Unsupported shell profile")), } cmd.cwd(&root); cmd.env("TERM", "xterm-256color"); @@ -191,12 +186,12 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: let reader = pair .master .try_clone_reader() - .map_err(|e| err(e.to_string()))?; - let writer = pair.master.take_writer().map_err(|e| err(e.to_string()))?; + .map_err(Error::from_display)?; + let writer = pair.master.take_writer().map_err(Error::from_display)?; let child = pair .slave .spawn_command(cmd) - .map_err(|e| err(e.to_string()))?; + .map_err(Error::from_display)?; drop(pair.slave); let session = OpenPty { owner: owner.into(), @@ -220,17 +215,17 @@ pub fn pty_open( cwd: String, profile: Option, directory: Option, -) -> PtyResult<()> { - let root = current_root_path(&workspace, window.label())?; +) -> Result<()> { + let root = current_root(&workspace, window.label())?; if root.to_string_lossy() != cwd { - return Err(err("workspace changed before the terminal started")); + return Err(Error::new("workspace changed before the terminal started")); } - let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?; + let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; if guard.contains_key(&id) { - return Err(err("terminal already exists")); + return Err(Error::new("terminal already exists")); } let directory = directory.map(PathBuf::from).unwrap_or(root); - if !directory.is_dir() { return Err(err("Terminal working directory does not exist")); } + if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); } let (session, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), window.label())?; guard.insert(id.clone(), session); drop(guard); @@ -282,21 +277,21 @@ pub fn pty_open( } #[tauri::command] -pub fn pty_write(pty: State, id: String, data: String) -> PtyResult<()> { - let guard = pty.inner.lock().map_err(|_| err("pty lock"))?; - let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?; - let mut writer = session.writer.lock().map_err(|_| err("pty writer lock"))?; +pub fn pty_write(pty: State, id: String, data: String) -> Result<()> { + let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; + let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?; + let mut writer = session.writer.lock().map_err(|_| Error::new("pty writer lock"))?; writer .write_all(data.as_bytes()) - .map_err(|e| err(e.to_string()))?; + .map_err(Error::from_display)?; writer.flush().ok(); Ok(()) } #[tauri::command] -pub fn pty_resize(pty: State, id: String, cols: u16, rows: u16) -> PtyResult<()> { - let guard = pty.inner.lock().map_err(|_| err("pty lock"))?; - let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?; +pub fn pty_resize(pty: State, id: String, cols: u16, rows: u16) -> Result<()> { + let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; + let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?; session .master .resize(PtySize { @@ -305,13 +300,13 @@ pub fn pty_resize(pty: State, id: String, cols: u16, rows: u16) -> Pty pixel_width: 0, pixel_height: 0, }) - .map_err(|e| err(e.to_string()))?; + .map_err(Error::from_display)?; Ok(()) } #[tauri::command] -pub fn pty_close(pty: State, id: String) -> PtyResult<()> { - let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?; +pub fn pty_close(pty: State, id: String) -> Result<()> { + let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let session = guard.remove(&id); drop(guard); drop(session); @@ -319,24 +314,24 @@ pub fn pty_close(pty: State, id: String) -> PtyResult<()> { } #[tauri::command] -pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> PtyResult<()> { - let root = current_root_path(&workspace, window.label())?; - if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(err("Invalid window ID")); } - let mut url = tauri::Url::parse("http://localhost/").map_err(|e| err(e.to_string()))?; +pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> { + let root = current_root(&workspace, window.label())?; + if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(Error::new("Invalid window ID")); } + let mut url = tauri::Url::parse("http://localhost/").map_err(Error::from_display)?; url.query_pairs_mut().append_pair("terminalWindow", &root.to_string_lossy()); let label = format!("terminal-{id}"); - if app.get_webview_window(&label).is_some() { return Err(err("Terminal window already exists")); } + if app.get_webview_window(&label).is_some() { return Err(Error::new("Terminal window already exists")); } workspace.bind_terminal(&label, root)?; let result = tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into())) .title("RuneStone — Terminal").inner_size(1000.0, 650.0).min_inner_size(500.0, 300.0).build() - .map_err(|e| err(e.to_string())); + .map_err(Error::from_display); if result.is_err() { workspace.close_window(&label); } result?; Ok(()) } #[tauri::command] -pub fn pty_dictation() -> PtyResult<()> { +pub fn pty_dictation() -> Result<()> { #[cfg(windows)] { use windows_sys::Win32::UI::Input::KeyboardAndMouse::{keybd_event, KEYEVENTF_KEYUP, VK_LWIN}; @@ -350,7 +345,7 @@ pub fn pty_dictation() -> PtyResult<()> { Ok(()) } #[cfg(not(windows))] - { Err(err("Use your operating system's dictation shortcut with the terminal focused.")) } + { Err(Error::new("Use your operating system's dictation shortcut with the terminal focused.")) } } #[cfg(test)] diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index 5b90bf6..18d43a1 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -2,7 +2,8 @@ use std::collections::HashMap; use std::path::PathBuf; use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; use tauri::{AppHandle, Manager, State}; -use crate::workspace::{current_root_path, WorkspaceState}; +use crate::error::Result; +use crate::workspace::{current_root, WorkspaceState}; #[derive(Default)] pub struct SettingsState(Mutex>>); @@ -14,7 +15,7 @@ struct PendingOpen<'a> { } impl SettingsState { - fn reserve(&self, label: &str) -> Result>, String> { + fn reserve(&self, label: &str) -> Result>> { let mut pending = self.0.lock().map_err(|_| "Settings window lock failed.")?; if let Some(cancelled) = pending.get(label) { return if cancelled.load(Ordering::SeqCst) { @@ -45,7 +46,7 @@ impl Drop for PendingOpen<'_> { } } -fn settings_label(owner: &str) -> Result { +fn settings_label(owner: &str) -> Result { if owner == "main" || owner.starts_with("workspace-") { Ok(format!("settings-{owner}")) } else { @@ -53,9 +54,9 @@ fn settings_label(owner: &str) -> Result { } } -fn bind_workspace(workspace: &WorkspaceState, owner: &str, label: &str) -> Result<(), String> { - if let Ok(root) = current_root_path(workspace, owner) { - workspace.bind_terminal(label, root).map_err(|error| error.to_string())?; +fn bind_workspace(workspace: &WorkspaceState, owner: &str, label: &str) -> Result<()> { + if let Ok(root) = current_root(workspace, owner) { + workspace.bind_terminal(label, root)?; } else { workspace.close_window(label); } @@ -68,14 +69,14 @@ pub async fn settings_open_window( window: tauri::Window, state: State<'_, SettingsState>, workspace: State<'_, WorkspaceState>, -) -> Result<(), String> { +) -> Result<()> { let label = settings_label(window.label())?; // The reservation survives native calls, but its mutex guard never does. let Some(pending) = state.reserve(&label)? else { return Ok(()); }; - let root = current_root_path(&workspace, window.label()).ok(); + let root = current_root(&workspace, window.label()).ok(); let valid = || pending.can_publish( app.get_webview_window(window.label()).is_some(), - &root, ¤t_root_path(&workspace, window.label()).ok(), + &root, ¤t_root(&workspace, window.label()).ok(), ); if !valid() { return Err("The workspace closed while settings opened.".into()); } bind_workspace(&workspace, window.label(), &label)?; @@ -97,14 +98,14 @@ pub async fn settings_open_window( .disable_drag_drop_handler() .build() { Ok(settings) => settings, - Err(error) => { workspace.close_window(&label); return Err(error.to_string()); } + Err(error) => { workspace.close_window(&label); return Err(error.into()); } } }; - let result = (|| { + let result = (|| -> Result<()> { if !valid() { return Err("The workspace changed while settings opened.".into()); } - settings.unminimize().map_err(|error| error.to_string())?; - settings.show().map_err(|error| error.to_string())?; - settings.set_focus().map_err(|error| error.to_string())?; + settings.unminimize()?; + settings.show()?; + settings.set_focus()?; if !valid() { return Err("The workspace changed while settings opened.".into()); } Ok(()) })(); @@ -174,7 +175,7 @@ mod tests { #[test] fn failed_build_releases_its_reservation_for_retry() { let state = SettingsState::default(); - let failed = || -> Result<(), String> { + let failed = || -> Result<()> { let _pending = state.reserve("settings-main")?.unwrap(); Err("Native build failed".into()) }; @@ -203,20 +204,20 @@ mod tests { workspace.bind_terminal("workspace-2", "/two".into()).unwrap(); bind_workspace(&workspace, "workspace-1", "settings-workspace-1").unwrap(); bind_workspace(&workspace, "workspace-2", "settings-workspace-2").unwrap(); - assert_eq!(current_root_path(&workspace, "settings-workspace-1").unwrap(), std::path::PathBuf::from("/one")); - assert_eq!(current_root_path(&workspace, "settings-workspace-2").unwrap(), std::path::PathBuf::from("/two")); + assert_eq!(current_root(&workspace, "settings-workspace-1").unwrap(), std::path::PathBuf::from("/one")); + assert_eq!(current_root(&workspace, "settings-workspace-2").unwrap(), std::path::PathBuf::from("/two")); workspace.close_window("settings-workspace-1"); - assert!(current_root_path(&workspace, "settings-workspace-1").is_err()); - assert!(current_root_path(&workspace, "workspace-1").is_ok()); + assert!(current_root(&workspace, "settings-workspace-1").is_err()); + assert!(current_root(&workspace, "workspace-1").is_ok()); } #[test] fn settings_without_a_workspace_never_use_the_recent_workspace() { let workspace = WorkspaceState::new(); bind_workspace(&workspace, "main", "settings-main").unwrap(); - assert!(current_root_path(&workspace, "settings-main").is_err()); + assert!(current_root(&workspace, "settings-main").is_err()); workspace.bind_terminal("main", "/opened-later".into()).unwrap(); bind_workspace(&workspace, "main", "settings-main").unwrap(); - assert_eq!(current_root_path(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later")); + assert_eq!(current_root(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later")); } } diff --git a/src-tauri/src/spelling.rs b/src-tauri/src/spelling.rs index 24c37be..525817b 100644 --- a/src-tauri/src/spelling.rs +++ b/src-tauri/src/spelling.rs @@ -1,6 +1,8 @@ //! Display WebView2 spelling commands through the shared frontend menu. //! Keep COM event arguments on the WebView thread until selection or cancellation. +use crate::error::Result; + #[cfg(any(windows, test))] #[derive(Debug, PartialEq)] enum Selection { Stale, Cancel, Native, Command(i32) } @@ -109,13 +111,13 @@ mod native { Ok(result) } - pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> Result<(), String> { + pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> crate::error::Result<()> { let label = window.label().to_owned(); if INSTALLED.with(|installed| installed.borrow().contains_key(&label)) { return Ok(()); } let app = window.app_handle().clone(); let owner = label.clone(); unsafe { - let core: ICoreWebView2_11 = controller.CoreWebView2().map_err(|e| e.to_string())?.cast().map_err(|e| e.to_string())?; + let core: ICoreWebView2_11 = controller.CoreWebView2()?.cast()?; let handler = ContextMenuRequestedEventHandler::create(Box::new(move |_, args| { let Some(args) = args else { return Ok(()); }; let mut editable = BOOL(0); @@ -143,7 +145,7 @@ mod native { Ok(()) })); let mut token = 0; - core.add_ContextMenuRequested(&handler, &mut token).map_err(|e| e.to_string())?; + core.add_ContextMenuRequested(&handler, &mut token)?; INSTALLED.with(|installed| { installed.borrow_mut().insert(label, (core, token)); }); } Ok(()) @@ -179,21 +181,21 @@ mod native { } #[tauri::command] -pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<(), String> { +pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<()> { #[cfg(windows)] { let (send, receive) = std::sync::mpsc::channel(); let owner = window.clone(); - window.with_webview(move |webview| { let _ = send.send(native::install(&owner, webview.controller())); }).map_err(|e| e.to_string())?; - tauri::async_runtime::spawn_blocking(move || receive.recv().map_err(|e| e.to_string())?).await.map_err(|e| e.to_string())? + window.with_webview(move |webview| { let _ = send.send(native::install(&owner, webview.controller())); })?; + tauri::async_runtime::spawn_blocking(move || receive.recv()?).await? } #[cfg(not(windows))] { let _ = window; Ok(()) } } #[tauri::command] -pub fn spelling_menu_select(window: tauri::WebviewWindow, request: String, command: Option, fallback: Option) -> Result<(), String> { +pub fn spelling_menu_select(window: tauri::WebviewWindow, request: String, command: Option, fallback: Option) -> Result<()> { #[cfg(windows)] { let label = window.label().to_owned(); - window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false))).map_err(|e| e.to_string())?; + window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false)))?; } #[cfg(not(windows))] { let _ = (window, request, command, fallback); } Ok(()) @@ -208,10 +210,10 @@ pub fn close_window(app: &tauri::AppHandle, label: &str) { } #[tauri::command] -pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), String> { +pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<()> { #[cfg(windows)] { let label = window.label().to_owned(); - window.with_webview(move |_| native::close(&label)).map_err(|e| e.to_string())?; + window.with_webview(move |_| native::close(&label))?; } #[cfg(not(windows))] { let _ = window; } Ok(()) @@ -223,9 +225,10 @@ pub struct Suggestions { language: String, words: Vec, misspelled: bool #[cfg(windows)] mod suggestions_worker { use super::Suggestions; + use crate::error::{Error, Result}; use std::{collections::HashMap, sync::{mpsc, OnceLock}}; use windows::{core::{HSTRING, PWSTR}, Win32::{Globalization::{ISpellChecker, ISpellCheckerFactory, SpellCheckerFactory}, System::Com::{CoInitializeEx, CoUninitialize, CoCreateInstance, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED}}}; - type Reply = Result; + type Reply = Result; type Request = (String, Vec, bool, mpsc::SyncSender); static WORKER: OnceLock> = OnceLock::new(); @@ -233,9 +236,9 @@ mod suggestions_worker { let worker = WORKER.get_or_init(|| { let (send, receive) = mpsc::channel::(); std::thread::spawn(move || unsafe { - let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(|error| error.to_string()); + let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(Error::from); let apartment_initialized = initialized.is_ok(); - let factory: Result = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(|error| error.to_string())); + let factory: Result = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(Error::from)); let mut checkers = HashMap::::new(); for (word, languages, add, reply) in receive { let result = (|| -> Reply { @@ -244,26 +247,26 @@ mod suggestions_worker { if language.len() > 85 || language.contains('\0') { continue; } if !checkers.contains_key(&language) { let tag = HSTRING::from(&language); - if !factory.IsSupported(&tag).map_err(|error| error.to_string())?.as_bool() { continue; } - let checker = factory.CreateSpellChecker(&tag).map_err(|error| error.to_string())?; + if !factory.IsSupported(&tag)?.as_bool() { continue; } + let checker = factory.CreateSpellChecker(&tag)?; checkers.insert(language.clone(), checker); } let checker = &checkers[&language]; let value = HSTRING::from(&word); if add { - checker.Add(&value).map_err(|error| error.to_string())?; + checker.Add(&value)?; return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); } - let errors = checker.Check(&value).map_err(|error| error.to_string())?; + let errors = checker.Check(&value)?; let mut error = None; - errors.Next(&mut error).ok().map_err(|error| error.to_string())?; + errors.Next(&mut error).ok()?; if error.is_none() { return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); } - let suggestions = checker.Suggest(&value).map_err(|error| error.to_string())?; + let suggestions = checker.Suggest(&value)?; let mut words = Vec::new(); for _ in 0..8 { let mut values = [PWSTR::null()]; let mut count = 0; - suggestions.Next(&mut values, Some(&mut count)).ok().map_err(|error| error.to_string())?; + suggestions.Next(&mut values, Some(&mut count)).ok()?; if count == 0 { break; } let suggestion = webview2_com::take_pwstr(values[0]); if !suggestion.is_empty() && suggestion != word { words.push(suggestion); } @@ -287,12 +290,12 @@ mod suggestions_worker { } #[tauri::command] -pub async fn spelling_suggestions(word: String, languages: Vec, add: Option) -> Result { +pub async fn spelling_suggestions(word: String, languages: Vec, add: Option) -> Result { if word.is_empty() || word.len() > 256 || word.contains('\0') || languages.len() > 20 { return Err("Invalid spelling request.".into()); } #[cfg(windows)] { - tauri::async_runtime::spawn_blocking(move || suggestions_worker::request(word, languages, add.unwrap_or(false))).await.map_err(|error| error.to_string())? + tauri::async_runtime::spawn_blocking(move || suggestions_worker::request(word, languages, add.unwrap_or(false))).await? } #[cfg(not(windows))] { let _ = (word, languages, add); Err("System spelling is unavailable.".into()) } } @@ -309,7 +312,7 @@ mod tests { let first = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false); let cold = start.elapsed(); if let Err(error) = &first { - if error.contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; } + if error.to_string().contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; } } let first = first.unwrap(); assert!(first.misspelled); diff --git a/src-tauri/src/theme.rs b/src-tauri/src/theme.rs index 0f901fb..4a83567 100644 --- a/src-tauri/src/theme.rs +++ b/src-tauri/src/theme.rs @@ -1,14 +1,16 @@ use tauri_plugin_dialog::DialogExt; +use crate::error::{Error, Result}; + #[tauri::command] -pub async fn theme_export(app: tauri::AppHandle, contents: String, default_name: String) -> Result, String> { +pub async fn theme_export(app: tauri::AppHandle, contents: String, default_name: String) -> Result> { if contents.len() > 1_048_576 { return Err("The theme exceeds the 1 MB limit.".into()); } - serde_json::from_str::(&contents).map_err(|_| "The theme contains invalid JSON.".to_string())?; + serde_json::from_str::(&contents).map_err(|_| "The theme contains invalid JSON.")?; let name = std::path::Path::new(&default_name).file_name().and_then(|name| name.to_str()).unwrap_or("theme.json").to_string(); - tauri::async_runtime::spawn_blocking(move || { + tauri::async_runtime::spawn_blocking(move || -> Result> { let Some(file) = app.dialog().file().set_title("Export theme").add_filter("Theme JSON", &["json"]).set_file_name(name).blocking_save_file() else { return Ok(None); }; - let path = file.into_path().map_err(|error| error.to_string())?; + let path = file.into_path().map_err(Error::from_display)?; std::fs::write(&path, contents).map_err(|error| format!("Could not export the theme: {error}"))?; Ok(Some(path.to_string_lossy().into_owned())) - }).await.map_err(|error| error.to_string())? + }).await? } diff --git a/src-tauri/src/workspace.rs b/src-tauri/src/workspace.rs index 66e83f9..bd0d740 100644 --- a/src-tauri/src/workspace.rs +++ b/src-tauri/src/workspace.rs @@ -1,6 +1,5 @@ use std::fs; use std::collections::HashMap; -use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::time::Duration; @@ -10,45 +9,12 @@ use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, Manager, State}; use tauri_plugin_opener::OpenerExt; +use crate::error::{Error, Result}; +use crate::fsutil; + const LAST_WORKSPACE_FILE: &str = "last-workspace.json"; static HISTORY_LOCK: Mutex<()> = Mutex::new(()); -#[derive(Debug, thiserror::Error)] -pub enum WorkspaceError { - #[error("{0}")] - Message(String), -} - -impl WorkspaceError { - pub fn from_message(msg: impl Into) -> Self { - WorkspaceError::Message(msg.into()) - } -} - -impl Serialize for WorkspaceError { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(&self.to_string()) - } -} - -impl From for WorkspaceError { - fn from(err: std::io::Error) -> Self { - WorkspaceError::Message(err.to_string()) - } -} - -impl From for WorkspaceError { - fn from(err: notify::Error) -> Self { - WorkspaceError::Message(err.to_string()) - } -} - -type WsResult = Result; - -fn err(msg: impl Into) -> WorkspaceError { - WorkspaceError::Message(msg.into()) -} - #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WorkspaceInfo { pub root: String, @@ -90,24 +56,24 @@ impl WorkspaceState { if let Ok(mut workspaces) = self.inner.lock() { workspaces.remove(label); } } - pub fn bind_terminal(&self, label: &str, root: PathBuf) -> WsResult<()> { - self.inner.lock().map_err(|_| err("workspace lock"))? + pub fn bind_terminal(&self, label: &str, root: PathBuf) -> Result<()> { + self.inner.lock().map_err(|_| Error::new("workspace lock"))? .insert(label.to_owned(), OpenWorkspace { root, _watcher: None }); Ok(()) } } -fn last_workspace_file(app: &AppHandle) -> WsResult { +fn last_workspace_file(app: &AppHandle) -> Result { let dir = app .path() .app_data_dir() - .map_err(|e| err(format!("app data dir: {e}")))?; + .map_err(|e| Error::new(format!("app data dir: {e}")))?; fs::create_dir_all(&dir)?; Ok(dir.join(LAST_WORKSPACE_FILE)) } -fn save_last_workspace(app: &AppHandle, root: &Path) -> WsResult<()> { - let _guard = HISTORY_LOCK.lock().map_err(|_| err("workspace history lock"))?; +fn save_last_workspace(app: &AppHandle, root: &Path) -> Result<()> { + let _guard = HISTORY_LOCK.lock().map_err(|_| Error::new("workspace history lock"))?; let path = last_workspace_file(app)?; let mut roots = load_workspace_history(&path); remember_workspace(&mut roots, root.to_string_lossy().into_owned()); @@ -137,12 +103,12 @@ fn remember_workspace(roots: &mut Vec, root: String) { } #[tauri::command] -pub fn workspace_recent(app: AppHandle) -> WsResult> { - let _guard = HISTORY_LOCK.lock().map_err(|_| err("workspace history lock"))?; +pub fn workspace_recent(app: AppHandle) -> Result> { + let _guard = HISTORY_LOCK.lock().map_err(|_| Error::new("workspace history lock"))?; Ok(load_workspace_history(&last_workspace_file(&app)?)) } -fn forget_workspace(path: &Path, root: &str) -> WsResult> { +fn forget_workspace(path: &Path, root: &str) -> Result> { let mut roots = load_workspace_history(path); roots.retain(|previous| { if cfg!(windows) { !previous.eq_ignore_ascii_case(root) } else { previous != root } @@ -153,35 +119,31 @@ fn forget_workspace(path: &Path, root: &str) -> WsResult> { } #[tauri::command] -pub fn workspace_forget(app: AppHandle, path: String) -> WsResult> { - let _guard = HISTORY_LOCK.lock().map_err(|_| err("workspace history lock"))?; +pub fn workspace_forget(app: AppHandle, path: String) -> Result> { + let _guard = HISTORY_LOCK.lock().map_err(|_| Error::new("workspace history lock"))?; forget_workspace(&last_workspace_file(&app)?, &path) } -fn create_workspace_folder(parent: &str, name: &str) -> WsResult { +fn create_workspace_folder(parent: &str, name: &str) -> Result { let name = name.trim(); - let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); - if name.is_empty() || name == "." || name == ".." || name.ends_with('.') + if !fsutil::is_plain_component(name) || name.chars().any(|c| c.is_control() || "<>:\"/\\|?*".contains(c)) - || 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')) { - return Err(err("Choose a valid folder name without path separators or reserved characters.")); + return Err(Error::new("Choose a valid folder name without path separators or reserved characters.")); } - let parent = dunce::canonicalize(parent).map_err(|_| err("Choose an existing location."))?; - if !parent.is_dir() { return Err(err("The location must be a folder.")); } + let parent = dunce::canonicalize(parent).map_err(|_| Error::new("Choose an existing location."))?; + if !parent.is_dir() { return Err(Error::new("The location must be a folder.")); } let root = parent.join(name); fs::create_dir(&root).map_err(|e| { if e.kind() == std::io::ErrorKind::AlreadyExists { - err("A file or folder with that name already exists. Choose another name or open the existing folder.") - } else { err(format!("Could not create workspace: {e}")) } + Error::new("A file or folder with that name already exists. Choose another name or open the existing folder.") + } else { Error::new(format!("Could not create workspace: {e}")) } })?; Ok(root) } #[tauri::command] -pub async fn workspace_new(app: AppHandle, state: State<'_, WorkspaceState>, parent: String, name: String) -> WsResult<()> { +pub async fn workspace_new(app: AppHandle, state: State<'_, WorkspaceState>, parent: String, name: String) -> Result<()> { let root = create_workspace_folder(&parent, &name)?; match open_workspace_window(&app, &state, root.clone()) { Ok(()) => Ok(()), @@ -202,26 +164,26 @@ fn load_last_workspace(app: &AppHandle) -> Option { Some(PathBuf::from(root)) } -pub fn check_rel(rel: &str) -> WsResult<()> { +pub fn check_rel(rel: &str) -> Result<()> { if rel.contains('\0') { - return Err(err("path contains a null byte")); + return Err(Error::new("path contains a null byte")); } let normalized = rel.replace('\\', "/"); if normalized.starts_with('/') || normalized.starts_with('\\') { - return Err(err("absolute paths are not allowed")); + return Err(Error::new("absolute paths are not allowed")); } if normalized.contains(':') { - return Err(err("drive prefixes are not allowed")); + return Err(Error::new("drive prefixes are not allowed")); } for part in normalized.split('/') { if part == ".." { - return Err(err("parent path segments are not allowed")); + return Err(Error::new("parent path segments are not allowed")); } } Ok(()) } -fn join_rel(root: &Path, rel: &str) -> WsResult { +fn join_rel(root: &Path, rel: &str) -> Result { check_rel(rel)?; let normalized = rel.replace('\\', "/"); if normalized.is_empty() { @@ -243,19 +205,19 @@ fn is_inside(root: &Path, candidate: &Path) -> bool { candidate.starts_with(root) } -fn resolve_existing(root: &Path, rel: &str) -> WsResult { +fn resolve_existing(root: &Path, rel: &str) -> Result { let joined = join_rel(root, rel)?; - let canon = dunce::canonicalize(&joined).map_err(|_| err("path does not exist"))?; + let canon = dunce::canonicalize(&joined).map_err(|_| Error::new("path does not exist"))?; if !is_inside(root, &canon) { - return Err(err("path is outside the workspace")); + return Err(Error::new("path is outside the workspace")); } Ok(canon) } -fn resolve_for_write(root: &Path, rel: &str) -> WsResult { +fn resolve_for_write(root: &Path, rel: &str) -> Result { let joined = join_rel(root, rel)?; if joined == root { - return Err(err("the workspace root cannot be modified")); + return Err(Error::new("the workspace root cannot be modified")); } // Validate the nearest existing ancestor, including the target itself. // This catches links to outside the workspace even below missing folders. @@ -263,7 +225,7 @@ fn resolve_for_write(root: &Path, rel: &str) -> WsResult { if fs::symlink_metadata(ancestor).is_ok() { let canonical = dunce::canonicalize(ancestor)?; if !is_inside(root, &canonical) { - return Err(err("path is outside the workspace")); + return Err(Error::new("path is outside the workspace")); } if ancestor == joined { return Ok(canonical); @@ -271,7 +233,7 @@ fn resolve_for_write(root: &Path, rel: &str) -> WsResult { break; } if !is_inside(root, ancestor) { - return Err(err("path is outside the workspace")); + return Err(Error::new("path is outside the workspace")); } } Ok(joined) @@ -304,8 +266,7 @@ fn is_network_path(path: &Path) -> bool { return false; } let drive_type = windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(volume.as_ptr()); - // DRIVE_REMOTE is 4 in Win32. - drive_type == 4 + drive_type == windows_sys::Win32::System::WindowsProgramming::DRIVE_REMOTE } } @@ -339,7 +300,7 @@ fn start_watcher( app: AppHandle, root: PathBuf, network: bool, -) -> WsResult> { +) -> Result> { let handler_root = root.clone(); let handler_app = app.clone(); let handler = move |res: notify::Result| { @@ -379,16 +340,12 @@ fn start_watcher( } } -fn current_root(state: &WorkspaceState, label: &str) -> WsResult { - let guard = state.inner.lock().map_err(|_| err("workspace lock"))?; +pub(crate) fn current_root(state: &WorkspaceState, label: &str) -> Result { + let guard = state.inner.lock().map_err(|_| Error::new("workspace lock"))?; guard .get(label) .map(|ws| ws.root.clone()) - .ok_or_else(|| err("no workspace is open")) -} - -pub fn current_root_path(state: &WorkspaceState, label: &str) -> WsResult { - current_root(state, label) + .ok_or_else(|| Error::new("no workspace is open")) } #[tauri::command] @@ -407,30 +364,30 @@ fn workspace_info(root: &Path) -> WorkspaceInfo { } } -fn open_workspace_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf) -> WsResult<()> { +fn open_workspace_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf) -> Result<()> { open_workspace_tab_window(app, state, root, None) } -fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf, transfer: Option) -> WsResult<()> { +fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf, transfer: Option) -> Result<()> { static NEXT_WINDOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let label = format!("workspace-{}", NEXT_WINDOW.fetch_add(1, std::sync::atomic::Ordering::Relaxed)); let watcher = start_watcher(app.clone(), root.clone(), is_network_path(&root))?; - let mut config = app.config().app.windows.first().cloned().ok_or_else(|| err("Missing window configuration"))?; + let mut config = app.config().app.windows.first().cloned().ok_or_else(|| Error::new("Missing window configuration"))?; config.label = label.clone(); config.title = format!("{} — RuneStone", workspace_info(&root).name); if let Some(token) = transfer { - let id = uuid::Uuid::parse_str(&token).map_err(|_| err("Invalid tab transfer."))?; + let id = uuid::Uuid::parse_str(&token).map_err(|_| Error::new("Invalid tab transfer."))?; config.url = tauri::WebviewUrl::App(format!("?tabTransfer={id}").into()); } // Bind before building: the new frontend asks for its own root on startup. - state.inner.lock().map_err(|_| err("workspace lock"))?.insert(label.clone(), OpenWorkspace { + state.inner.lock().map_err(|_| Error::new("workspace lock"))?.insert(label.clone(), OpenWorkspace { root: root.clone(), _watcher: Some(watcher), }); - let result = (|| -> WsResult<()> { + let result = (|| -> Result<()> { let window = tauri::WebviewWindowBuilder::from_config(app, &config) - .map_err(|e| err(e.to_string()))?.visible(false).build().map_err(|e| err(e.to_string()))?; + .map_err(Error::from_display)?.visible(false).build().map_err(Error::from_display)?; if let Err(error) = save_last_workspace(app, &root) - .and_then(|_| window.show().map_err(|e| err(e.to_string()))) { + .and_then(|_| window.show().map_err(Error::from_display)) { let _ = window.destroy(); return Err(error); } @@ -442,9 +399,9 @@ fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: Path } #[tauri::command] -pub async fn workspace_open_window(app: AppHandle, state: State<'_, WorkspaceState>, path: String, transfer: Option) -> WsResult<()> { - let root = dunce::canonicalize(path).map_err(|_| err("folder does not exist"))?; - if !root.is_dir() { return Err(err("path is not a folder")); } +pub async fn workspace_open_window(app: AppHandle, state: State<'_, WorkspaceState>, path: String, transfer: Option) -> Result<()> { + let root = dunce::canonicalize(path).map_err(|_| Error::new("folder does not exist"))?; + if !root.is_dir() { return Err(Error::new("path is not a folder")); } open_workspace_tab_window(&app, &state, root, transfer) } @@ -454,20 +411,20 @@ pub fn workspace_open( window: tauri::Window, state: State, path: String, -) -> WsResult { - let root = dunce::canonicalize(&path).map_err(|_| err("folder does not exist"))?; +) -> Result { + let root = dunce::canonicalize(&path).map_err(|_| Error::new("folder does not exist"))?; if !root.is_dir() { - return Err(err("path is not a folder")); + return Err(Error::new("path is not a folder")); } if let Ok(previous) = current_root(&state, window.label()) { if previous == root { return Ok(workspace_info(&root)); } - return Err(err("Open another workspace in a new window.")); + return Err(Error::new("Open another workspace in a new window.")); } let network = is_network_path(&root); let watcher = start_watcher(app.clone(), root.clone(), network)?; save_last_workspace(&app, &root)?; { - let mut guard = state.inner.lock().map_err(|_| err("workspace lock"))?; + let mut guard = state.inner.lock().map_err(|_| Error::new("workspace lock"))?; guard.insert(window.label().to_owned(), OpenWorkspace { root: root.clone(), _watcher: Some(watcher), @@ -480,19 +437,15 @@ pub fn workspace_open( } #[tauri::command] -pub fn workspace_list(window: tauri::Window, state: State, rel: String, show_internal: Option) -> WsResult> { +pub fn workspace_list(window: tauri::Window, state: State, rel: String, show_internal: Option) -> Result> { let root = current_root(&state, window.label())?; list_entries_visible(&root, &rel, show_internal.unwrap_or(false)) } -fn list_entries(root: &Path, rel: &str) -> WsResult> { - list_entries_visible(root, rel, false) -} - -fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> WsResult> { +fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> Result> { let dir = resolve_existing(root, rel)?; if !dir.is_dir() { - return Err(err("path is not a folder")); + return Err(Error::new("path is not a folder")); } let mut entries = Vec::new(); @@ -541,13 +494,13 @@ fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> WsResult } #[tauri::command] -pub async fn workspace_list_markdown(window: tauri::Window, state: State<'_, WorkspaceState>) -> WsResult> { - let root = current_root_path(&state, window.label())?; +pub async fn workspace_list_markdown(window: tauri::Window, state: State<'_, WorkspaceState>) -> Result> { + let root = current_root(&state, window.label())?; tauri::async_runtime::spawn_blocking(move || markdown_paths(&root)) - .await.map_err(|error| err(format!("Markdown scan failed: {error}")))? + .await.map_err(|error| Error::new(format!("Markdown scan failed: {error}")))? } -fn markdown_paths(root: &Path) -> WsResult> { +fn markdown_paths(root: &Path) -> Result> { let mut folders = vec![root.to_path_buf()]; let mut paths = Vec::new(); while let Some(folder) = folders.pop() { @@ -574,18 +527,18 @@ fn markdown_paths(root: &Path) -> WsResult> { } #[tauri::command] -pub fn workspace_read(window: tauri::Window, state: State, rel: String, missing_ok: Option) -> WsResult> { +pub fn workspace_read(window: tauri::Window, state: State, rel: String, missing_ok: Option) -> Result> { let root = current_root(&state, window.label())?; let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? }; if path.is_dir() { - return Err(err("path is a folder")); + return Err(Error::new("path is a folder")); } read_optional_text(&path, missing_ok.unwrap_or(false)) } -fn read_optional_text(path: &Path, missing_ok: bool) -> WsResult> { +fn read_optional_text(path: &Path, missing_ok: bool) -> Result> { match fs::read(path) { - Ok(bytes) => String::from_utf8(bytes).map(Some).map_err(|_| err("file is not valid UTF-8")), + Ok(bytes) => String::from_utf8(bytes).map(Some).map_err(|_| Error::new("file is not valid UTF-8")), Err(error) if missing_ok && error.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(error) => Err(error.into()), } @@ -600,21 +553,21 @@ pub struct TextRead { error: Option, } -fn read_many_text(root: &Path, paths: Vec) -> WsResult> { - if paths.len() > 64 { return Err(err("Read at most 64 files per request.")); } +fn read_many_text(root: &Path, paths: Vec) -> Result> { + if paths.len() > 64 { return Err(Error::new("Read at most 64 files per request.")); } let mut remaining = 16 * 1024 * 1024usize; Ok(paths.into_iter().map(|path| { - let result = (|| -> WsResult { + let result = (|| -> Result { let resolved = resolve_existing(root, &path)?; let file = fs::File::open(resolved)?; let metadata = file.metadata()?; - if !metadata.is_file() { return Err(err("The path must be a file.")); } - if metadata.len() > remaining as u64 { return Err(err("The batch exceeds the 16 MiB limit.")); } - let mut bytes = Vec::new(); - file.take(remaining as u64 + 1).read_to_end(&mut bytes)?; - if bytes.len() > remaining { return Err(err("The batch exceeds the 16 MiB limit.")); } + if !metadata.is_file() { return Err(Error::new("The path must be a file.")); } + if metadata.len() > remaining as u64 { return Err(Error::new("The batch exceeds the 16 MiB limit.")); } + let Some(bytes) = fsutil::read_to_limit(file, remaining as u64)? else { + return Err(Error::new("The batch exceeds the 16 MiB limit.")); + }; remaining -= bytes.len(); - String::from_utf8(bytes).map_err(|_| err("The file is not valid UTF-8.")) + String::from_utf8(bytes).map_err(|_| Error::new("The file is not valid UTF-8.")) })(); match result { Ok(source) => TextRead { path, source: Some(source), error: None }, @@ -624,31 +577,29 @@ fn read_many_text(root: &Path, paths: Vec) -> WsResult> { } #[tauri::command] -pub async fn workspace_read_many(window: tauri::Window, state: State<'_, WorkspaceState>, paths: Vec) -> WsResult> { +pub async fn workspace_read_many(window: tauri::Window, state: State<'_, WorkspaceState>, paths: Vec) -> Result> { let root = current_root(&state, window.label())?; tauri::async_runtime::spawn_blocking(move || read_many_text(&root, paths)) - .await.map_err(|error| err(error.to_string()))? + .await? } const MAX_BINARY_BYTES: u64 = 64 * 1024 * 1024; -fn read_workspace_bytes(root: &Path, rel: &str) -> WsResult> { +fn read_workspace_bytes(root: &Path, rel: &str) -> Result> { let path = resolve_existing(root, rel)?; let file = fs::File::open(path)?; let metadata = file.metadata()?; - if !metadata.is_file() { return Err(err("The path must be a file.")); } - if metadata.len() > MAX_BINARY_BYTES { return Err(err("The file exceeds the 64 MiB limit.")); } - let mut bytes = Vec::new(); - file.take(MAX_BINARY_BYTES + 1).read_to_end(&mut bytes)?; - if bytes.len() as u64 > MAX_BINARY_BYTES { return Err(err("The file exceeds the 64 MiB limit.")); } - Ok(bytes) + if !metadata.is_file() { return Err(Error::new("The path must be a file.")); } + if metadata.len() > MAX_BINARY_BYTES { return Err(Error::new("The file exceeds the 64 MiB limit.")); } + fsutil::read_to_limit(file, MAX_BINARY_BYTES)? + .ok_or_else(|| Error::new("The file exceeds the 64 MiB limit.")) } #[tauri::command] -pub async fn workspace_read_bytes(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String) -> WsResult { +pub async fn workspace_read_bytes(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String) -> Result { let root = current_root(&state, window.label())?; let bytes = tauri::async_runtime::spawn_blocking(move || read_workspace_bytes(&root, &rel)) - .await.map_err(|e| err(e.to_string()))??; + .await??; Ok(tauri::ipc::Response::new(bytes)) } @@ -659,135 +610,13 @@ pub fn workspace_write( rel: String, contents: String, expected: Option, -) -> WsResult<()> { +) -> Result<()> { let root = current_root(&state, window.label())?; let path = resolve_for_write(&root, &rel)?; if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|reason| err(format!("Could not prepare the save folder for {}: {reason}", path.display())))?; + fs::create_dir_all(parent).map_err(|reason| Error::new(format!("Could not prepare the save folder for {}: {reason}", path.display())))?; } - write_text(&path, &contents, expected.as_deref()) -} - -pub(crate) fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<()> { - if let Some(expected) = expected { - let current = fs::read_to_string(path).map_err(|_| { - err("Save blocked: file was removed or cannot be read. Your edits are still open.") - })?; - if current != expected { - return Err(err( - "Save blocked: file changed on disk. Review the external changes before saving.", - )); - } - } - // Write completely beside the destination, then replace it. A failed write - // leaves the original file intact rather than truncating it. - static NEXT_WRITE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let parent = path.parent().ok_or_else(|| err("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| err(format!("Could not create a save file for {}: {reason}", path.display())))?; - let result = (|| -> WsResult<()> { - file.write_all(contents.as_bytes()).map_err(|reason| err(format!("Could not write the save file for {}: {reason}", path.display())))?; - file.sync_all().map_err(|reason| err(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| err(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(err( - "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) -> WsResult<()> { - fs::rename(temp, path).map_err(|reason| err(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) -> WsResult<()> { - 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() == std::io::ErrorKind::NotFound && allow_create => { - return fs::rename(temp, path).map_err(|reason| err(format!( - "Could not publish {}: {reason}. Your edits are still open.", path.display() - ))); - } - Err(reason) => return Err(err(format!( - "Could not read the destination {}: {reason}. Your edits are still open.", path.display() - ))), - }; - if metadata.permissions().readonly() { - return Err(err(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(|| err("file has no parent"))? - .join(format!(".runestone-save-backup-{}", uuid::Uuid::new_v4())); - if backup.try_exists()? { return Err(err("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 = std::io::Error::last_os_error(); - if backup.try_exists()? { - if !path.try_exists()? { - if let Err(restore) = restore_save_backup(&backup, path) { - return Err(err(format!( - "Could not save {}: {reason}. Restore failed: {restore}. The original file remains at {}.", - path.display(), backup.display() - ))); - } - } else { - return Err(err(format!( - "Could not save {}: {reason}. A recovery copy remains at {}. Your edits are still open.", - path.display(), backup.display() - ))); - } - } - Err(err(format!("Could not replace {}: {reason}. Your edits are still open.", path.display()))) -} - -#[cfg(windows)] -fn restore_save_backup(backup: &Path, path: &Path) -> std::io::Result<()> { - // A concurrent writer must never lose its file during recovery. - fs::hard_link(backup, path)?; - let _ = fs::remove_file(backup); - Ok(()) + fsutil::write_text(&path, &contents, expected.as_deref()) } fn is_internal_name(name: &str) -> bool { @@ -795,11 +624,11 @@ fn is_internal_name(name: &str) -> bool { } #[tauri::command] -pub fn workspace_create(window: tauri::Window, state: State, rel: String, kind: String, contents: Option) -> WsResult<()> { +pub fn workspace_create(window: tauri::Window, state: State, rel: String, kind: String, contents: Option) -> Result<()> { let root = current_root(&state, window.label())?; let path = resolve_for_write(&root, &rel)?; if path.exists() { - return Err(err("path already exists")); + return Err(Error::new("path already exists")); } if kind == "folder" { fs::create_dir_all(&path)?; @@ -818,27 +647,18 @@ pub fn workspace_create(window: tauri::Window, state: State, rel } // Publish a complete file without replacing a destination created by another writer. -fn create_text_if_absent(path: &Path, contents: &str) -> WsResult<()> { +fn create_text_if_absent(path: &Path, contents: &str) -> Result<()> { static NEXT_CREATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let parent = path.parent().ok_or_else(|| err("file has no parent"))?; + let parent = path.parent().ok_or_else(|| Error::new("file has no parent"))?; fs::create_dir_all(parent)?; let temp = parent.join(format!(".runestone-save-create-{}-{}", std::process::id(), NEXT_CREATE.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); - let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&temp)?; - let result = (|| -> WsResult<()> { - file.write_all(contents.as_bytes())?; - file.sync_all()?; - drop(file); - fs::hard_link(&temp, path)?; - Ok(()) - })(); - let _ = fs::remove_file(&temp); - result + Ok(fsutil::create_file(path, &temp, contents.as_bytes())?) } -fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Option<&str>) -> WsResult { +fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Option<&str>) -> Result { let root = current_root(state, label)?; if let Some(expected) = expected_root { - let changed = || err("The workspace changed. Repeat the operation in the current workspace."); + let changed = || Error::new("The workspace changed. Repeat the operation in the current workspace."); if !Path::new(expected).is_absolute() { return Err(changed()); } let expected = dunce::canonicalize(expected).map_err(|_| changed())?; let current = dunce::canonicalize(&root).map_err(|_| changed())?; @@ -848,15 +668,15 @@ fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Opt } #[tauri::command] -pub fn workspace_rename(window: tauri::Window, state: State, from: String, to: String, expected_root: Option) -> WsResult<()> { +pub fn workspace_rename(window: tauri::Window, state: State, from: String, to: String, expected_root: Option) -> Result<()> { let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?; let from_path = resolve_existing(&root, &from)?; if from_path == root { - return Err(err("the workspace root cannot be renamed")); + return Err(Error::new("the workspace root cannot be renamed")); } let to_path = resolve_for_write(&root, &to)?; if to_path.exists() { - return Err(err("destination already exists")); + return Err(Error::new("destination already exists")); } if let Some(parent) = to_path.parent() { fs::create_dir_all(parent)?; @@ -866,11 +686,11 @@ pub fn workspace_rename(window: tauri::Window, state: State, fro } #[tauri::command] -pub fn workspace_delete(window: tauri::Window, state: State, rel: String) -> WsResult<()> { +pub fn workspace_delete(window: tauri::Window, state: State, rel: String) -> Result<()> { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; if path == root { - return Err(err("the workspace root cannot be deleted")); + return Err(Error::new("the workspace root cannot be deleted")); } if path.is_dir() { fs::remove_dir_all(path)?; @@ -901,16 +721,16 @@ fn mime_from_path(path: &Path) -> Option<&'static str> { } #[tauri::command] -pub fn workspace_read_data_url(window: tauri::Window, state: State, rel: String) -> WsResult { +pub fn workspace_read_data_url(window: tauri::Window, state: State, rel: String) -> Result { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; if path.is_dir() { - return Err(err("path is a folder")); + return Err(Error::new("path is a folder")); } - let mime = mime_from_path(&path).ok_or_else(|| err("file is not an image"))?; + let mime = mime_from_path(&path).ok_or_else(|| Error::new("file is not an image"))?; let bytes = fs::read(&path)?; if bytes.len() > MAX_IMAGE_BYTES { - return Err(err("image is too large")); + return Err(Error::new("image is too large")); } Ok(format!( "data:{mime};base64,{}", @@ -975,25 +795,25 @@ pub struct CopyResult { } #[tauri::command] -pub fn workspace_copy(window: tauri::Window, state: State, rel: String, parent: Option, expected_root: Option) -> WsResult { +pub fn workspace_copy(window: tauri::Window, state: State, rel: String, parent: Option, expected_root: Option) -> Result { let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?; copy_workspace_item(&root, &rel, parent.as_deref()) } -fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> WsResult { +fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> Result { if fs::symlink_metadata(join_rel(root, rel)?)?.file_type().is_symlink() { - return Err(err("Cannot copy symbolic links.")); + return Err(Error::new("Cannot copy symbolic links.")); } let from = resolve_existing(&root, &rel)?; - if from == root { return Err(err("Cannot copy the workspace root.")); } + if from == root { return Err(Error::new("Cannot copy the workspace root.")); } let candidate = if let Some(parent) = parent { let folder = resolve_existing(&root, &parent)?; - if !folder.is_dir() { return Err(err("Destination is not a folder.")); } - if from.is_dir() && folder.starts_with(&from) { return Err(err("Cannot copy a folder into itself.")); } - folder.join(from.file_name().ok_or_else(|| err("Cannot copy the workspace root."))?) + if !folder.is_dir() { return Err(Error::new("Destination is not a folder.")); } + if from.is_dir() && folder.starts_with(&from) { return Err(Error::new("Cannot copy a folder into itself.")); } + folder.join(from.file_name().ok_or_else(|| Error::new("Cannot copy the workspace root."))?) } else { from.clone() }; if !is_inside(&root, candidate.parent().unwrap_or(&candidate)) { - return Err(err("path is outside the workspace")); + return Err(Error::new("path is outside the workspace")); } let mut number = if parent.is_some() { 0 } else { 1 }; let dest = loop { @@ -1001,13 +821,13 @@ fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> WsResult match copy_tree(&from, &dest) { Ok(()) => break dest, Err(reason) if reason.kind() == std::io::ErrorKind::AlreadyExists => { - number = number.checked_add(1).ok_or_else(|| err("No copy name is available."))?; + number = number.checked_add(1).ok_or_else(|| Error::new("No copy name is available."))?; } Err(reason) => return Err(reason.into()), } }; let rel_path = - to_rel(&root, &dest).ok_or_else(|| err("copied path is outside the workspace"))?; + to_rel(&root, &dest).ok_or_else(|| Error::new("copied path is outside the workspace"))?; let name = dest .file_name() .map(|n| n.to_string_lossy().into_owned()) @@ -1021,45 +841,45 @@ fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> WsResult } #[tauri::command] -pub fn workspace_abs_path(window: tauri::Window, state: State, rel: String) -> WsResult { +pub fn workspace_abs_path(window: tauri::Window, state: State, rel: String) -> Result { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; Ok(dunce::simplified(&path).to_string_lossy().into_owned()) } #[tauri::command] -pub fn workspace_open_default(window: tauri::Window, app: AppHandle, state: State, rel: String) -> WsResult<()> { +pub fn workspace_open_default(window: tauri::Window, app: AppHandle, state: State, rel: String) -> Result<()> { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; - app.opener().open_path(dunce::simplified(&path).to_string_lossy().into_owned(), None::<&str>).map_err(|e| err(e.to_string())) + app.opener().open_path(dunce::simplified(&path).to_string_lossy().into_owned(), None::<&str>).map_err(Error::from_display) } #[tauri::command] -pub fn workspace_open_terminal(window: tauri::Window, state: State, rel: String) -> WsResult<()> { +pub fn workspace_open_terminal(window: tauri::Window, state: State, rel: String) -> Result<()> { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; - let folder = if path.is_dir() { path.as_path() } else { path.parent().ok_or_else(|| err("Folder unavailable."))? }; + let folder = if path.is_dir() { path.as_path() } else { path.parent().ok_or_else(|| Error::new("Folder unavailable."))? }; #[cfg(windows)] let mut command = { let mut c = std::process::Command::new("powershell.exe"); c.arg("-NoExit"); c }; #[cfg(target_os = "macos")] let mut command = { let mut c = std::process::Command::new("open"); c.args(["-a", "Terminal"]).arg(folder); c }; #[cfg(any(windows, target_os = "macos"))] { - command.current_dir(folder).spawn().map_err(|e| err(e.to_string()))?; + command.current_dir(folder).spawn().map_err(Error::from_display)?; Ok(()) } #[cfg(all(unix, not(target_os = "macos")))] - { crate::terminal_platform::open_external_terminal(folder).map_err(|reason| err(reason.to_string())) } + { crate::terminal_platform::open_external_terminal(folder).map_err(Error::from_display) } } #[tauri::command] -pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State, rel: String) -> WsResult<()> { +pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State, rel: String) -> Result<()> { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; if rel.is_empty() { return app.opener() .open_path(dunce::simplified(&path).to_string_lossy().into_owned(), None::<&str>) - .map_err(|e| err(e.to_string())); + .map_err(Error::from_display); } if app.opener().reveal_item_in_dir(&path).is_ok() { return Ok(()); @@ -1069,11 +889,11 @@ pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State, query: String) -> WsResult> { +pub fn workspace_search(window: tauri::Window, state: State, query: String) -> Result> { let root = current_root(&state, window.label())?; search_entries(&root, &query) } -fn search_entries(root: &Path, query: &str) -> WsResult> { +fn search_entries(root: &Path, query: &str) -> Result> { let needle = query.trim().to_lowercase(); if needle.is_empty() { return Ok(Vec::new()); @@ -1163,15 +983,14 @@ pub fn workspace_write_bytes( state: State, rel: String, base64: String, -) -> WsResult<()> { +) -> Result<()> { let root = current_root(&state, window.label())?; let path = resolve_for_write(&root, &rel)?; - let mime = mime_from_path(&path).ok_or_else(|| err("file is not an image"))?; - let _ = mime; + mime_from_path(&path).ok_or_else(|| Error::new("file is not an image"))?; let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, base64.trim()) - .map_err(|_| err("invalid image data"))?; + .map_err(|_| Error::new("invalid image data"))?; if bytes.len() > MAX_IMAGE_BYTES { - return Err(err("image is too large")); + return Err(Error::new("image is too large")); } if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; @@ -1193,7 +1012,7 @@ mod tests { fs::write(root.join(folder).join("sample.md"), "sample").unwrap(); } let root = dunce::canonicalize(root).unwrap(); - assert!(!list_entries(&root, "").unwrap().iter().any(|entry| entry.name == ".runestone")); + assert!(!list_entries_visible(&root, "", false).unwrap().iter().any(|entry| entry.name == ".runestone")); let shown = list_entries_visible(&root, "", true).unwrap(); assert!(shown.iter().any(|entry| entry.name == ".runestone")); assert!(!shown.iter().any(|entry| entry.name == ".git" || entry.name == ".obsidian")); @@ -1276,12 +1095,12 @@ mod tests { } fs::write(root.join("papers/.gitignore"), "note.md\n").unwrap(); let root = dunce::canonicalize(root).unwrap(); - let entries = list_entries(&root, "").unwrap(); + let entries = list_entries_visible(&root, "", false).unwrap(); let hits = search_entries(&root, "unique search phrase").unwrap(); for folder in ["papers", "local-excluded", "git-excluded", "parent-excluded", ".hidden-notes"] { assert!(entries.iter().any(|entry| entry.rel_path == folder && entry.kind == "folder"), "{folder}"); let note = format!("{folder}/note.md"); - assert!(list_entries(&root, folder).unwrap().iter().any(|entry| entry.rel_path == note), "{note}"); + assert!(list_entries_visible(&root, folder, false).unwrap().iter().any(|entry| entry.rel_path == note), "{note}"); assert!(hits.iter().any(|hit| hit.rel_path == note && hit.line == 1), "{note}"); } assert!(!entries.iter().any(|entry| entry.name == ".git")); @@ -1295,15 +1114,15 @@ mod tests { let second = PathBuf::from("D:/projects"); state.bind_terminal("main", first.clone()).unwrap(); state.bind_terminal("workspace-0", second.clone()).unwrap(); - state.bind_terminal("terminal-0", current_root_path(&state, "main").unwrap()).unwrap(); - assert_eq!(current_root_path(&state, "main").unwrap(), first); - assert_eq!(current_root_path(&state, "workspace-0").unwrap(), second); - assert!(current_root_path(&state, "unknown-window").is_err()); + state.bind_terminal("terminal-0", current_root(&state, "main").unwrap()).unwrap(); + assert_eq!(current_root(&state, "main").unwrap(), first); + assert_eq!(current_root(&state, "workspace-0").unwrap(), second); + assert!(current_root(&state, "unknown-window").is_err()); state.close_window("workspace-0"); - assert!(current_root_path(&state, "workspace-0").is_err()); - assert_eq!(current_root_path(&state, "main").unwrap(), first); + assert!(current_root(&state, "workspace-0").is_err()); + assert_eq!(current_root(&state, "main").unwrap(), first); state.close_window("main"); - assert_eq!(current_root_path(&state, "terminal-0").unwrap(), first); + assert_eq!(current_root(&state, "terminal-0").unwrap(), first); } #[test] @@ -1368,122 +1187,6 @@ mod tests { fs::remove_dir_all(parent).unwrap(); } - #[test] - fn guarded_save_preserves_an_external_edit() { - let dir = std::env::temp_dir().join(format!("rs-save-{}", std::process::id())); - fs::create_dir_all(&dir).unwrap(); - 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(); - } - - - #[cfg(windows)] - #[test] - fn windows_card_updates_preserve_file_streams() { - let dir = std::env::temp_dir().join(format!("rs-card-save-{}", uuid::Uuid::new_v4())); - fs::create_dir(&dir).unwrap(); - let path = dir.join("card.md"); - create_text_if_absent(&path, "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; - let dir = std::env::temp_dir().join(format!("rs-locked-save-{}", uuid::Uuid::new_v4())); - fs::create_dir(&dir).unwrap(); - let path = dir.join("card.md"); - fs::write(&path, "original").unwrap(); - let reader = fs::OpenOptions::new().read(true).share_mode(1).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] - fn windows_read_only_files_remain_protected() { - let dir = std::env::temp_dir().join(format!("rs-readonly-save-{}", uuid::Uuid::new_v4())); - fs::create_dir(&dir).unwrap(); - 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 = std::env::temp_dir().join(format!("rs-save-recovery-{}", uuid::Uuid::new_v4())); - fs::create_dir(&dir).unwrap(); - 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 = std::env::temp_dir().join(format!("rs-long-save-{}", uuid::Uuid::new_v4())); - 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(); - } - - #[test] - fn deleted_files_are_not_silently_recreated() { - let path = std::env::temp_dir().join(format!("rs-missing-{}.md", std::process::id())); - assert!(write_text(&path, "local edits", Some("original")).is_err()); - assert!(!path.exists()); - } - #[test] fn workspace_root_is_not_a_write_target() { let root = dunce::canonicalize(std::env::temp_dir()).unwrap(); @@ -1664,7 +1367,7 @@ mod tests { let symlink = std::os::windows::fs::symlink_file; if let Err(reason) = symlink(root.join("original.txt"), root.join("source-link")) { #[cfg(windows)] - if reason.raw_os_error() == Some(1314) { eprintln!("Symbolic-link test requires Windows Developer Mode or symlink privilege."); fs::remove_dir_all(root).unwrap(); return; } + if reason.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) { eprintln!("Symbolic-link test requires Windows Developer Mode or symlink privilege."); fs::remove_dir_all(root).unwrap(); return; } panic!("Could not prepare the link test: {reason}"); } assert!(copy_workspace_item(&root, "source-link", Some("target")).unwrap_err().to_string().contains("symbolic links"));