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; use notify::{Config, Event, PollWatcher, RecommendedWatcher, RecursiveMode, Watcher}; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, Manager, State}; use tauri_plugin_opener::OpenerExt; 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, pub name: String, pub watch_mode: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TreeEntry { pub name: String, pub rel_path: String, pub kind: String, } #[derive(Debug, Clone, Serialize)] pub struct WorkspaceEvent { pub root: String, pub kind: String, pub paths: Vec, } pub struct WorkspaceState { inner: Mutex>, } struct OpenWorkspace { root: PathBuf, _watcher: Option>, } impl WorkspaceState { pub fn new() -> Self { Self { inner: Mutex::new(HashMap::new()), } } pub fn close_window(&self, label: &str) { 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"))? .insert(label.to_owned(), OpenWorkspace { root, _watcher: None }); Ok(()) } } fn last_workspace_file(app: &AppHandle) -> WsResult { let dir = app .path() .app_data_dir() .map_err(|e| err(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"))?; let path = last_workspace_file(app)?; let mut roots = load_workspace_history(&path); remember_workspace(&mut roots, root.to_string_lossy().into_owned()); let payload = serde_json::json!({ "root": root.to_string_lossy(), "recent": roots }); fs::write(path, serde_json::to_string_pretty(&payload).unwrap())?; Ok(()) } fn load_workspace_history(path: &Path) -> Vec { let Ok(bytes) = fs::read(path) else { return Vec::new() }; let Ok(value) = serde_json::from_slice::(&bytes) else { return Vec::new() }; let mut roots: Vec = value.get("recent").and_then(|v| v.as_array()) .map(|items| items.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect()) .unwrap_or_default(); if let Some(root) = value.get("root").and_then(|v| v.as_str()) { remember_workspace(&mut roots, root.to_owned()); } roots } fn remember_workspace(roots: &mut Vec, root: String) { roots.retain(|previous| { if cfg!(windows) { !previous.eq_ignore_ascii_case(&root) } else { previous != &root } }); roots.insert(0, root); roots.truncate(20); } #[tauri::command] pub fn workspace_recent(app: AppHandle) -> WsResult> { let _guard = HISTORY_LOCK.lock().map_err(|_| err("workspace history lock"))?; Ok(load_workspace_history(&last_workspace_file(&app)?)) } fn forget_workspace(path: &Path, root: &str) -> WsResult> { let mut roots = load_workspace_history(path); roots.retain(|previous| { if cfg!(windows) { !previous.eq_ignore_ascii_case(root) } else { previous != root } }); let payload = serde_json::json!({ "root": roots.first(), "recent": roots }); fs::write(path, serde_json::to_string_pretty(&payload).unwrap())?; Ok(roots) } #[tauri::command] pub fn workspace_forget(app: AppHandle, path: String) -> WsResult> { let _guard = HISTORY_LOCK.lock().map_err(|_| err("workspace history lock"))?; forget_workspace(&last_workspace_file(&app)?, &path) } fn create_workspace_folder(parent: &str, name: &str) -> WsResult { let name = name.trim(); let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); if name.is_empty() || name == "." || name == ".." || name.ends_with('.') || 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.")); } 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 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}")) } })?; Ok(root) } #[tauri::command] pub async fn workspace_new(app: AppHandle, state: State<'_, WorkspaceState>, parent: String, name: String) -> WsResult<()> { let root = create_workspace_folder(&parent, &name)?; match open_workspace_window(&app, &state, root.clone()) { Ok(()) => Ok(()), Err(error) => { // Only remove the empty folder created by this request if opening failed. let _ = fs::remove_dir(&root); Err(error) } } } fn load_last_workspace(app: &AppHandle) -> Option { let _guard = HISTORY_LOCK.lock().ok()?; let path = last_workspace_file(app).ok()?; let bytes = fs::read(path).ok()?; let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?; let root = value.get("root")?.as_str()?; Some(PathBuf::from(root)) } pub fn check_rel(rel: &str) -> WsResult<()> { if rel.contains('\0') { return Err(err("path contains a null byte")); } let normalized = rel.replace('\\', "/"); if normalized.starts_with('/') || normalized.starts_with('\\') { return Err(err("absolute paths are not allowed")); } if normalized.contains(':') { return Err(err("drive prefixes are not allowed")); } for part in normalized.split('/') { if part == ".." { return Err(err("parent path segments are not allowed")); } } Ok(()) } fn join_rel(root: &Path, rel: &str) -> WsResult { check_rel(rel)?; let normalized = rel.replace('\\', "/"); if normalized.is_empty() { return Ok(root.to_path_buf()); } let mut joined = root.to_path_buf(); for part in normalized.split('/') { if part.is_empty() || part == "." { continue; } joined.push(part); } Ok(joined) } fn is_inside(root: &Path, candidate: &Path) -> bool { let root = dunce::simplified(root); let candidate = dunce::simplified(candidate); candidate.starts_with(root) } fn resolve_existing(root: &Path, rel: &str) -> WsResult { let joined = join_rel(root, rel)?; let canon = dunce::canonicalize(&joined).map_err(|_| err("path does not exist"))?; if !is_inside(root, &canon) { return Err(err("path is outside the workspace")); } Ok(canon) } fn resolve_for_write(root: &Path, rel: &str) -> WsResult { let joined = join_rel(root, rel)?; if joined == root { return Err(err("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. for ancestor in joined.ancestors() { 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")); } if ancestor == joined { return Ok(canonical); } break; } if !is_inside(root, ancestor) { return Err(err("path is outside the workspace")); } } Ok(joined) } fn to_rel(root: &Path, path: &Path) -> Option { let root = dunce::simplified(root); let path = dunce::simplified(path); let rel = path.strip_prefix(root).ok()?; Some(rel.to_string_lossy().replace('\\', "/")) } #[cfg(windows)] fn is_network_path(path: &Path) -> bool { let s = path.to_string_lossy(); if s.starts_with("\\\\") || s.starts_with("//") { return true; } use std::os::windows::ffi::OsStrExt; let mut wide: Vec = path.as_os_str().encode_wide().collect(); wide.push(0); unsafe { let mut volume = [0u16; 260]; let ok = windows_sys::Win32::Storage::FileSystem::GetVolumePathNameW( wide.as_ptr(), volume.as_mut_ptr(), volume.len() as u32, ); if ok == 0 { return false; } let drive_type = windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(volume.as_ptr()); // DRIVE_REMOTE is 4 in Win32. drive_type == 4 } } #[cfg(not(windows))] fn is_network_path(path: &Path) -> bool { let s = path.to_string_lossy(); s.starts_with("//") } fn emit_watch_event(app: &AppHandle, root: &Path, event: Event) { let kind = format!("{:?}", event.kind) .split('(') .next() .unwrap_or("other") .to_lowercase(); let paths: Vec = event.paths.iter().filter_map(|p| to_rel(root, p)).collect(); if paths.is_empty() { return; } let _ = app.emit( "workspace-event", WorkspaceEvent { root: root.to_string_lossy().into_owned(), kind, paths, }, ); } fn start_watcher( app: AppHandle, root: PathBuf, network: bool, ) -> WsResult> { let handler_root = root.clone(); let handler_app = app.clone(); let handler = move |res: notify::Result| { if let Ok(event) = res { emit_watch_event(&handler_app, &handler_root, event); } }; if network { let mut watcher = PollWatcher::new( handler, Config::default().with_poll_interval(Duration::from_secs(2)), )?; watcher.watch(&root, RecursiveMode::Recursive)?; return Ok(Box::new(watcher)); } match RecommendedWatcher::new(handler, Config::default()) { Ok(mut watcher) => { watcher.watch(&root, RecursiveMode::Recursive)?; Ok(Box::new(watcher)) } Err(_) => { let handler_root = root.clone(); let handler_app = app.clone(); let mut watcher = PollWatcher::new( move |res: notify::Result| { if let Ok(event) = res { emit_watch_event(&handler_app, &handler_root, event); } }, Config::default().with_poll_interval(Duration::from_secs(2)), )?; watcher.watch(&root, RecursiveMode::Recursive)?; Ok(Box::new(watcher)) } } } fn current_root(state: &WorkspaceState, label: &str) -> WsResult { let guard = state.inner.lock().map_err(|_| err("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) } #[tauri::command] pub fn workspace_last_path(app: AppHandle, window: tauri::Window, state: State) -> Option { current_root(&state, window.label()).ok() .or_else(|| if window.label() == "main" { load_last_workspace(&app) } else { None }) .map(|p| p.to_string_lossy().into_owned()) } fn workspace_info(root: &Path) -> WorkspaceInfo { WorkspaceInfo { root: root.to_string_lossy().into_owned(), name: root.file_name().map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| root.to_string_lossy().into_owned()), watch_mode: if is_network_path(root) { "poll" } else { "native" }.to_owned(), } } fn open_workspace_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf) -> WsResult<()> { open_workspace_tab_window(app, state, root, None) } fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf, transfer: Option) -> WsResult<()> { 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"))?; 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."))?; 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 { root: root.clone(), _watcher: Some(watcher), }); let result = (|| -> WsResult<()> { 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()))?; if let Err(error) = save_last_workspace(app, &root) .and_then(|_| window.show().map_err(|e| err(e.to_string()))) { let _ = window.destroy(); return Err(error); } let _ = window.set_focus(); Ok(()) })(); if result.is_err() { state.close_window(&label); } result } #[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")); } open_workspace_tab_window(&app, &state, root, transfer) } #[tauri::command] pub fn workspace_open( app: AppHandle, window: tauri::Window, state: State, path: String, ) -> 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")); } 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.")); } 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"))?; guard.insert(window.label().to_owned(), OpenWorkspace { root: root.clone(), _watcher: Some(watcher), }); } let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name)); // A settings session opened before this workspace must start with its new context. crate::settings::close_owned_window(&app, window.label()); Ok(workspace_info(&root)) } #[tauri::command] pub fn workspace_list(window: tauri::Window, state: State, rel: String, show_internal: Option) -> WsResult> { 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> { let dir = resolve_existing(root, rel)?; if !dir.is_dir() { return Err(err("path is not a folder")); } let mut entries = Vec::new(); let walker = ignore::WalkBuilder::new(&dir) .max_depth(Some(1)) .standard_filters(false) .build(); for result in walker { let dent = match result { Ok(d) => d, Err(_) => continue, }; if dent.depth() == 0 { continue; } let path = dent.path(); if dent.file_type().is_some_and(|kind| kind.is_symlink()) { continue; } let name = match path.file_name() { Some(n) => n.to_string_lossy().into_owned(), None => continue, }; if is_internal_name(&name) && !(show_internal && name == ".runestone") { continue; } let rel_path = match to_rel(&root, path) { Some(r) => r, None => continue, }; let kind = if path.is_dir() { "folder" } else { "file" }; entries.push(TreeEntry { name, rel_path, kind: kind.to_string(), }); } entries.sort_by(|a, b| match (a.kind.as_str(), b.kind.as_str()) { ("folder", "file") => std::cmp::Ordering::Less, ("file", "folder") => std::cmp::Ordering::Greater, _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()), }); Ok(entries) } #[tauri::command] pub async fn workspace_list_markdown(window: tauri::Window, state: State<'_, WorkspaceState>) -> WsResult> { let root = current_root_path(&state, window.label())?; tauri::async_runtime::spawn_blocking(move || markdown_paths(&root)) .await.map_err(|error| err(format!("Markdown scan failed: {error}")))? } fn markdown_paths(root: &Path) -> WsResult> { let mut folders = vec![root.to_path_buf()]; let mut paths = Vec::new(); while let Some(folder) = folders.pop() { for entry in fs::read_dir(folder)? { let entry = entry?; let name = entry.file_name(); // Match PM discovery without a desktop request for every directory. if name.to_string_lossy().starts_with('.') { continue; } let kind = entry.file_type()?; if kind.is_symlink() { continue; } let path = entry.path(); if kind.is_dir() { folders.push(path); } else if kind.is_file() { let extension = path.extension().and_then(|value| value.to_str()).unwrap_or("").to_ascii_lowercase(); if matches!(extension.as_str(), "md" | "markdown" | "mdown") { if let Some(rel) = to_rel(root, &path) { paths.push(rel); } } } } } paths.sort(); Ok(paths) } #[tauri::command] pub fn workspace_read(window: tauri::Window, state: State, rel: String, missing_ok: Option) -> WsResult> { 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")); } read_optional_text(&path, missing_ok.unwrap_or(false)) } fn read_optional_text(path: &Path, missing_ok: bool) -> WsResult> { match fs::read(path) { Ok(bytes) => String::from_utf8(bytes).map(Some).map_err(|_| err("file is not valid UTF-8")), Err(error) if missing_ok && error.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(error) => Err(error.into()), } } #[derive(Debug, Serialize)] pub struct TextRead { path: String, #[serde(skip_serializing_if = "Option::is_none")] source: Option, #[serde(skip_serializing_if = "Option::is_none")] 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.")); } let mut remaining = 16 * 1024 * 1024usize; Ok(paths.into_iter().map(|path| { let result = (|| -> WsResult { 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.")); } remaining -= bytes.len(); String::from_utf8(bytes).map_err(|_| err("The file is not valid UTF-8.")) })(); match result { Ok(source) => TextRead { path, source: Some(source), error: None }, Err(error) => TextRead { path, source: None, error: Some(error.to_string()) }, } }).collect()) } #[tauri::command] pub async fn workspace_read_many(window: tauri::Window, state: State<'_, WorkspaceState>, paths: Vec) -> WsResult> { 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()))? } const MAX_BINARY_BYTES: u64 = 64 * 1024 * 1024; fn read_workspace_bytes(root: &Path, rel: &str) -> WsResult> { 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) } #[tauri::command] pub async fn workspace_read_bytes(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String) -> WsResult { 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()))??; Ok(tauri::ipc::Response::new(bytes)) } #[tauri::command] pub fn workspace_write( window: tauri::Window, state: State, rel: String, contents: String, expected: Option, ) -> WsResult<()> { 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())))?; } 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(()) } fn is_internal_name(name: &str) -> bool { matches!(name, ".git" | ".obsidian" | ".runestone") || name.starts_with(".runestone-save-") } #[tauri::command] pub fn workspace_create(window: tauri::Window, state: State, rel: String, kind: String, contents: Option) -> WsResult<()> { let root = current_root(&state, window.label())?; let path = resolve_for_write(&root, &rel)?; if path.exists() { return Err(err("path already exists")); } if kind == "folder" { fs::create_dir_all(&path)?; } else if let Some(contents) = contents { create_text_if_absent(&path, &contents)?; } else { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } fs::OpenOptions::new() .write(true) .create_new(true) .open(&path)?; } Ok(()) } // Publish a complete file without replacing a destination created by another writer. fn create_text_if_absent(path: &Path, contents: &str) -> WsResult<()> { 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"))?; 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 } fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Option<&str>) -> WsResult { 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."); 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())?; if expected != current { return Err(changed()); } } Ok(root) } #[tauri::command] pub fn workspace_rename(window: tauri::Window, state: State, from: String, to: String, expected_root: Option) -> WsResult<()> { 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")); } let to_path = resolve_for_write(&root, &to)?; if to_path.exists() { return Err(err("destination already exists")); } if let Some(parent) = to_path.parent() { fs::create_dir_all(parent)?; } fs::rename(from_path, to_path)?; Ok(()) } #[tauri::command] pub fn workspace_delete(window: tauri::Window, state: State, rel: String) -> WsResult<()> { 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")); } if path.is_dir() { fs::remove_dir_all(path)?; } else { fs::remove_file(path)?; } Ok(()) } const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024; fn mime_from_path(path: &Path) -> Option<&'static str> { let ext = path .extension() .and_then(|e| e.to_str()) .map(|e| e.to_ascii_lowercase())?; match ext.as_str() { "png" => Some("image/png"), "jpg" | "jpeg" => Some("image/jpeg"), "gif" => Some("image/gif"), "webp" => Some("image/webp"), "svg" => Some("image/svg+xml"), "bmp" => Some("image/bmp"), "ico" => Some("image/x-icon"), "avif" => Some("image/avif"), _ => None, } } #[tauri::command] pub fn workspace_read_data_url(window: tauri::Window, state: State, rel: String) -> WsResult { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; if path.is_dir() { return Err(err("path is a folder")); } let mime = mime_from_path(&path).ok_or_else(|| err("file is not an image"))?; let bytes = fs::read(&path)?; if bytes.len() > MAX_IMAGE_BYTES { return Err(err("image is too large")); } Ok(format!( "data:{mime};base64,{}", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes) )) } fn copy_destination(path: &Path, number: u32) -> PathBuf { let parent = path.parent().unwrap_or(path); let stem = path .file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_else(|| "copy".to_string()); let ext = path .extension() .map(|e| format!(".{}", e.to_string_lossy())) .unwrap_or_default(); let name = if number == 1 { format!("{stem} copy{ext}") } else { format!("{stem} copy {number}{ext}") }; parent.join(name) } fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> { let metadata = fs::symlink_metadata(from)?; if metadata.file_type().is_symlink() { return Err(std::io::Error::other("Cannot copy symbolic links.")); } let partial = |reason| std::io::Error::other(format!( "Could not complete the copy at {}: {reason}. Any copied items remain there.", to.display() )); if metadata.is_dir() { // This reserves the directory. Never merge into an existing destination. fs::create_dir(to)?; let result = (|| -> std::io::Result<()> { for entry in fs::read_dir(from)? { let entry = entry?; copy_tree(&entry.path(), &to.join(entry.file_name()))?; } Ok(()) })(); // Only a root reservation failure can cause a retry with another name. result.map_err(partial)?; } else if metadata.is_file() { let mut source = fs::File::open(from)?; let mut target = fs::OpenOptions::new().write(true).create_new(true).open(to)?; let result = (|| -> std::io::Result<()> { std::io::copy(&mut source, &mut target)?; target.set_permissions(metadata.permissions())?; Ok(()) })(); result.map_err(partial)?; } else { return Err(std::io::Error::other("Only regular files and folders can be copied.")); } Ok(()) } #[derive(Debug, Clone, Serialize)] pub struct CopyResult { pub name: String, pub rel_path: String, pub kind: String, } #[tauri::command] pub fn workspace_copy(window: tauri::Window, state: State, rel: String, parent: Option, expected_root: Option) -> WsResult { 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 { if fs::symlink_metadata(join_rel(root, rel)?)?.file_type().is_symlink() { return Err(err("Cannot copy symbolic links.")); } let from = resolve_existing(&root, &rel)?; if from == root { return Err(err("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."))?) } else { from.clone() }; if !is_inside(&root, candidate.parent().unwrap_or(&candidate)) { return Err(err("path is outside the workspace")); } let mut number = if parent.is_some() { 0 } else { 1 }; let dest = loop { let dest = if number == 0 { candidate.clone() } else { copy_destination(&candidate, number) }; 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."))?; } Err(reason) => return Err(reason.into()), } }; let rel_path = to_rel(&root, &dest).ok_or_else(|| err("copied path is outside the workspace"))?; let name = dest .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| rel_path.clone()); let kind = if dest.is_dir() { "folder" } else { "file" }; Ok(CopyResult { name, rel_path, kind: kind.to_string(), }) } #[tauri::command] pub fn workspace_abs_path(window: tauri::Window, state: State, rel: String) -> WsResult { 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<()> { 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())) } #[tauri::command] pub fn workspace_open_terminal(window: tauri::Window, state: State, rel: String) -> WsResult<()> { 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."))? }; #[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()))?; Ok(()) } #[cfg(all(unix, not(target_os = "macos")))] { crate::terminal_platform::open_external_terminal(folder).map_err(|reason| err(reason.to_string())) } } #[tauri::command] pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State, rel: String) -> WsResult<()> { 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())); } if app.opener().reveal_item_in_dir(&path).is_ok() { return Ok(()); } #[cfg(windows)] { std::process::Command::new("explorer") .arg(format!("/select,{}", path.display())) .spawn() .map_err(|e| err(e.to_string()))?; return Ok(()); } #[cfg(not(windows))] Err(err("could not reveal the path")) } #[derive(Debug, Clone, Serialize)] pub struct SearchHit { pub rel_path: String, pub line: u32, pub text: String, } #[tauri::command] pub fn workspace_search(window: tauri::Window, state: State, query: String) -> WsResult> { let root = current_root(&state, window.label())?; search_entries(&root, &query) } fn search_entries(root: &Path, query: &str) -> WsResult> { let needle = query.trim().to_lowercase(); if needle.is_empty() { return Ok(Vec::new()); } let mut hits = Vec::new(); let walker = ignore::WalkBuilder::new(root) .standard_filters(false) .filter_entry(|entry| { entry.depth() == 0 || !is_internal_name(&entry.file_name().to_string_lossy()) }) .build(); for dent in walker.flatten() { if dent.depth() == 0 { continue; } let path = dent.path(); let name = match path.file_name().and_then(|n| n.to_str()) { Some(n) => n, None => continue, }; if is_internal_name(name) || !dent.file_type().is_some_and(|kind| kind.is_file()) { continue; } let rel = match to_rel(&root, path) { Some(r) => r, None => continue, }; if name.to_lowercase().contains(&needle) { hits.push(SearchHit { rel_path: rel.clone(), line: 1, text: name.to_string(), }); } if path.is_file() && hits.len() < 80 && dent .metadata() .map(|m| m.len() <= 1_000_000) .unwrap_or(false) { if let Ok(bytes) = fs::read(path) { if bytes.len() <= 1_000_000 { if let Ok(text) = String::from_utf8(bytes) { for (index, line) in text.lines().enumerate() { if line.to_lowercase().contains(&needle) { hits.push(SearchHit { rel_path: rel.clone(), line: (index + 1) as u32, text: line.trim().chars().take(120).collect(), }); if hits.len() >= 80 { break; } } } } } } } if hits.len() >= 80 { break; } } Ok(hits) } #[tauri::command] pub fn workspace_write_bytes( window: tauri::Window, state: State, rel: String, base64: String, ) -> WsResult<()> { 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; let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, base64.trim()) .map_err(|_| err("invalid image data"))?; if bytes.len() > MAX_IMAGE_BYTES { return Err(err("image is too large")); } if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } fs::write(path, bytes)?; Ok(()) } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; #[test] fn optional_internal_folder_only_changes_the_file_tree() { let root = std::env::temp_dir().join(format!("rs-visible-internal-{}", uuid::Uuid::new_v4())); for folder in [".runestone", ".git", ".obsidian", "notes"] { fs::create_dir_all(root.join(folder)).unwrap(); 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")); 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")); assert!(!search_entries(&root, "sample").unwrap().iter().any(|entry| entry.rel_path.starts_with(".runestone/"))); fs::remove_dir_all(root).unwrap(); } #[test] fn markdown_listing_preserves_discovery_and_excludes_hidden_storage() { let root = std::env::temp_dir().join(format!("rs-markdown-list-{}", uuid::Uuid::new_v4())); for rel in ["Notes", "target/deep", ".runestone/pm/cards", "Notes/.hidden", ".git"] { fs::create_dir_all(root.join(rel)).unwrap(); } for rel in ["Board.MD", "Notes/one.markdown", "target/deep/two.mdown", ".runestone/pm/cards/private.md", "Notes/.hidden/secret.md", ".git/hidden.md", "Notes/.hidden.md", "Notes/plain.txt"] { fs::write(root.join(rel), "text").unwrap(); } fs::write(root.join(".gitignore"), "Notes/\ntarget/\n").unwrap(); assert_eq!(markdown_paths(&root).unwrap(), vec!["Board.MD", "Notes/one.markdown", "target/deep/two.mdown"]); fs::remove_dir_all(&root).unwrap(); assert!(markdown_paths(&root).is_err()); } #[test] #[ignore = "Set RUNESTONE_SCAN_BENCH_ROOT to an existing workspace."] fn markdown_listing_workspace_benchmark() { let root = dunce::canonicalize(std::env::var("RUNESTONE_SCAN_BENCH_ROOT").unwrap()).unwrap(); let start = std::time::Instant::now(); let paths = markdown_paths(&root).unwrap(); println!("Native Markdown discovery: {} paths, {:?}", paths.len(), start.elapsed()); } #[test] fn binary_reads_preserve_bytes_and_enforce_workspace_and_size_limits() { let fixture = std::env::temp_dir().join(format!("rs-binary-{}", std::process::id())); let root = fixture.join("workspace"); fs::create_dir_all(&root).unwrap(); let root = dunce::canonicalize(root).unwrap(); let bytes = b"%PDF-1.7\n\xff\x00\xfe"; fs::write(root.join("test.pdf"), bytes).unwrap(); fs::write(fixture.join("outside.pdf"), bytes).unwrap(); assert_eq!(read_workspace_bytes(&root, "test.pdf").unwrap(), bytes); assert!(read_workspace_bytes(&root, "../outside.pdf").is_err()); assert!(read_workspace_bytes(&root, &fixture.join("outside.pdf").to_string_lossy()).is_err()); assert!(read_workspace_bytes(&root, "").is_err()); assert!(read_workspace_bytes(&root, "missing.pdf").is_err()); fs::File::create(root.join("large.pdf")).unwrap().set_len(MAX_BINARY_BYTES + 1).unwrap(); assert!(read_workspace_bytes(&root, "large.pdf").unwrap_err().to_string().contains("64 MiB")); fs::remove_dir_all(fixture).unwrap(); } #[test] fn plugin_files_publish_complete_text_without_overwriting() { let root = std::env::temp_dir().join(format!("rs-plugin-create-{}", std::process::id())); fs::create_dir_all(&root).unwrap(); let path = root.join("note.md"); assert_eq!(read_optional_text(&path, true).unwrap(), None); assert!(read_optional_text(&path, false).is_err()); create_text_if_absent(&path, "complete note\n").unwrap(); assert_eq!(read_optional_text(&path, true).unwrap().as_deref(), Some("complete note\n")); assert!(create_text_if_absent(&path, "replacement").is_err()); assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n"); assert_eq!(fs::read_dir(&root).unwrap().count(), 1); assert!(read_optional_text(&root, true).is_err()); fs::remove_file(path).unwrap(); fs::remove_dir(root).unwrap(); } #[test] fn ignore_files_do_not_hide_workspace_entries_or_search_results() { let fixture = std::env::temp_dir().join(format!("rs-ignore-rules-{}", std::process::id())); let root = fixture.join("workspace"); fs::create_dir_all(root.join(".git/info")).unwrap(); fs::write(fixture.join(".ignore"), "parent-excluded/\n").unwrap(); fs::write(root.join(".gitignore"), "papers/\n").unwrap(); fs::write(root.join(".ignore"), "local-excluded/\n").unwrap(); fs::write(root.join(".git/info/exclude"), "git-excluded/\n").unwrap(); for folder in ["papers", "local-excluded", "git-excluded", "parent-excluded", ".hidden-notes"] { fs::create_dir_all(root.join(folder)).unwrap(); fs::write(root.join(folder).join("note.md"), "unique search phrase").unwrap(); } fs::write(root.join("papers/.gitignore"), "note.md\n").unwrap(); let root = dunce::canonicalize(root).unwrap(); let entries = list_entries(&root, "").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!(hits.iter().any(|hit| hit.rel_path == note && hit.line == 1), "{note}"); } assert!(!entries.iter().any(|entry| entry.name == ".git")); fs::remove_dir_all(fixture).unwrap(); } #[test] fn windows_keep_independent_roots_and_cleanup() { let state = WorkspaceState::new(); let first = PathBuf::from("D:/notes"); 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.close_window("workspace-0"); assert!(current_root_path(&state, "workspace-0").is_err()); assert_eq!(current_root_path(&state, "main").unwrap(), first); state.close_window("main"); assert_eq!(current_root_path(&state, "terminal-0").unwrap(), first); } #[test] fn recent_workspaces_migrate_persist_and_reorder() { let path = std::env::temp_dir().join(format!("rs-history-{}.json", std::process::id())); fs::write(&path, r#"{"root":"D:/old"}"#).unwrap(); let mut roots = load_workspace_history(&path); assert_eq!(roots, vec!["D:/old"]); remember_workspace(&mut roots, "D:/new".into()); remember_workspace(&mut roots, "D:/old".into()); assert_eq!(roots, vec!["D:/old", "D:/new"]); fs::write(&path, serde_json::json!({"root": "D:/old", "recent": roots}).to_string()).unwrap(); assert_eq!(load_workspace_history(&path), roots); for i in 0..30 { remember_workspace(&mut roots, format!("D:/workspace-{i}")); } assert_eq!(roots.len(), 20); assert_eq!(roots[0], "D:/workspace-29"); fs::remove_file(path).unwrap(); } #[test] fn forgetting_workspaces_persists_without_restoring_the_last_root() { let path = std::env::temp_dir().join(format!("rs-forget-history-{}.json", std::process::id())); fs::write(&path, r#"{"root":"D:/first","recent":["D:/first","D:/second"]}"#).unwrap(); assert_eq!(forget_workspace(&path, "D:/first").unwrap(), vec!["D:/second"]); assert_eq!(load_workspace_history(&path), vec!["D:/second"]); assert!(forget_workspace(&path, "D:/second").unwrap().is_empty()); assert!(load_workspace_history(&path).is_empty()); fs::remove_file(path).unwrap(); } #[test] fn batch_reads_keep_errors_per_file_and_enforce_workspace_limits() { let root = std::env::temp_dir().join(format!("rs-read-many-{}", std::process::id())); fs::create_dir_all(&root).unwrap(); let root = dunce::canonicalize(root).unwrap(); fs::write(root.join("valid.md"), "card text").unwrap(); fs::write(root.join("binary"), [0xff]).unwrap(); let items = read_many_text(&root, vec!["valid.md".into(), "missing".into(), "../outside".into(), ".".into(), "binary".into()]).unwrap(); assert_eq!(items[0].source.as_deref(), Some("card text")); assert!(items[1..].iter().all(|item| item.source.is_none() && item.error.is_some())); assert!(read_many_text(&root, vec!["valid.md".into(); 65]).is_err()); fs::write(root.join("large"), vec![b'x'; 16 * 1024 * 1024 + 1]).unwrap(); assert!(read_many_text(&root, vec!["large".into()]).unwrap()[0].error.is_some()); fs::remove_dir_all(root).unwrap(); } #[test] fn new_workspace_creates_only_a_new_child_folder() { let parent = std::env::temp_dir().join(format!("rs-new-workspace-{}", std::process::id())); fs::create_dir_all(&parent).unwrap(); let location = parent.to_string_lossy(); for name in ["", ".", "..", "../outside", "a/b", "a\\b", "C:drive", "CON", "nul.txt", "COM1", "trailing."] { assert!(create_workspace_folder(&location, name).is_err(), "{name}"); } let root = create_workspace_folder(&location, " My notes ").unwrap(); assert!(root.is_dir()); assert_eq!(root.file_name().unwrap(), "My notes"); fs::write(root.join("keep.md"), "existing content").unwrap(); assert!(create_workspace_folder(&location, "My notes").is_err()); assert_eq!(fs::read_to_string(root.join("keep.md")).unwrap(), "existing content"); assert_eq!(fs::read_dir(&parent).unwrap().count(), 1); 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(); assert!(resolve_for_write(&root, "").is_err()); assert!(resolve_for_write(&root, ".").is_err()); } #[test] fn internal_folders_are_excluded() { for name in [".git", ".obsidian", ".runestone", ".runestone-save-42-1"] { assert!(is_internal_name(name)); } assert!(!is_internal_name(".github")); assert!(!is_internal_name("notes")); } #[test] fn rejects_parent_segments() { assert!(check_rel("../secret").is_err()); assert!(check_rel("notes/../../secret").is_err()); } #[test] fn rejects_absolute_paths() { assert!(check_rel("/etc/passwd").is_err()); assert!(check_rel("C:/Windows").is_err()); } #[test] fn accepts_nested_rel() { assert!(check_rel("notes/inbox.md").is_ok()); assert!(check_rel("").is_ok()); } #[test] fn join_rel_stays_under_root() { let root = PathBuf::from("D:/ws"); let joined = join_rel(&root, "notes/a.md").unwrap(); assert!(joined.ends_with("notes/a.md") || joined.ends_with(r"notes\a.md")); } #[test] fn mime_from_png() { assert_eq!( mime_from_path(Path::new("screenshot.png")), Some("image/png") ); assert_eq!(mime_from_path(Path::new("notes/inbox.md")), None); } #[test] fn copy_destination_appends_copy() { let dir = std::env::temp_dir().join(format!("rs-copy-{}", uuid::Uuid::new_v4())); fs::create_dir_all(&dir).unwrap(); let src = dir.join("hello.py"); fs::write(&src, "x").unwrap(); let dest = copy_destination(&src, 1); assert_eq!(dest.file_name().unwrap(), "hello copy.py"); fs::write(&dest, "y").unwrap(); let dest2 = copy_destination(&src, 2); assert_eq!(dest2.file_name().unwrap(), "hello copy 2.py"); let _ = fs::remove_dir_all(&dir); } #[test] fn copy_and_rename_guard_rejects_a_changed_window_root_before_mutation() { let fixture = std::env::temp_dir().join(format!("rs-root-guard-{}", uuid::Uuid::new_v4())); fs::create_dir_all(fixture.join("first")).unwrap(); fs::create_dir(fixture.join("second")).unwrap(); let first = dunce::canonicalize(fixture.join("first")).unwrap(); let second = dunce::canonicalize(fixture.join("second")).unwrap(); fs::write(first.join("note.md"), "first workspace").unwrap(); fs::write(second.join("note.md"), "second workspace").unwrap(); let state = WorkspaceState::new(); state.bind_terminal("main", first.clone()).unwrap(); state.bind_terminal("other", second.clone()).unwrap(); let expected = first.to_str().unwrap(); assert_eq!(guarded_mutation_root(&state, "main", Some(expected)).unwrap(), first); assert_eq!(guarded_mutation_root(&state, "main", Some(first.join(".").to_str().unwrap())).unwrap(), first); assert!(guarded_mutation_root(&state, "other", Some(expected)).is_err()); state.bind_terminal("main", second.clone()).unwrap(); let copy = guarded_mutation_root(&state, "main", Some(expected)).and_then(|root| copy_workspace_item(&root, "note.md", None)); assert!(copy.unwrap_err().to_string().contains("workspace changed")); let rename = guarded_mutation_root(&state, "main", Some(expected)).and_then(|root| { fs::rename(root.join("note.md"), root.join("renamed.md"))?; Ok(()) }); assert!(rename.is_err()); assert_eq!(fs::read_to_string(first.join("note.md")).unwrap(), "first workspace"); assert_eq!(fs::read_to_string(second.join("note.md")).unwrap(), "second workspace"); assert_eq!(fs::read_dir(&second).unwrap().count(), 1); assert_eq!(guarded_mutation_root(&state, "main", None).unwrap(), second); assert!(guarded_mutation_root(&state, "main", Some(".")).is_err()); assert!(guarded_mutation_root(&state, "missing", Some(expected)).is_err()); fs::remove_dir_all(fixture).unwrap(); } #[test] fn copy_tree_never_replaces_an_existing_file_or_directory() { let root = std::env::temp_dir().join(format!("rs-copy-existing-{}", uuid::Uuid::new_v4())); fs::create_dir(&root).unwrap(); fs::write(root.join("source.txt"), "source").unwrap(); fs::write(root.join("existing.txt"), "keep existing").unwrap(); fs::create_dir(root.join("existing-dir")).unwrap(); fs::write(root.join("existing-dir/keep.txt"), "keep directory").unwrap(); for (from, to) in [("source.txt", "existing.txt"), ("source.txt", "existing-dir"), ("existing-dir", "existing.txt"), ("existing-dir", "existing-dir")] { assert_eq!(copy_tree(&root.join(from), &root.join(to)).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); } assert_eq!(fs::read_to_string(root.join("existing.txt")).unwrap(), "keep existing"); assert_eq!(fs::read_to_string(root.join("existing-dir/keep.txt")).unwrap(), "keep directory"); assert_eq!(fs::read_dir(root.join("existing-dir")).unwrap().count(), 1); fs::remove_dir_all(root).unwrap(); } #[test] fn concurrent_copies_reserve_unique_files_and_directories() { use std::sync::{Arc, Barrier}; for directory in [false, true] { let root = std::env::temp_dir().join(format!("rs-copy-race-{}", uuid::Uuid::new_v4())); fs::create_dir(&root).unwrap(); fs::create_dir(root.join("target")).unwrap(); let root = dunce::canonicalize(root).unwrap(); let mut sources = Vec::new(); for index in 0..8 { let parent = root.join(format!("source-{index}")); fs::create_dir(&parent).unwrap(); if directory { fs::create_dir(parent.join("item")).unwrap(); fs::write(parent.join("item/content.txt"), format!("source {index}")).unwrap(); } else { fs::write(parent.join("item"), format!("source {index}")).unwrap(); } sources.push(format!("source-{index}/item")); } // Existing user content occupies the unsuffixed name. fs::write(root.join("target/item"), "existing user content").unwrap(); let barrier = Arc::new(Barrier::new(sources.len())); let threads: Vec<_> = sources.into_iter().enumerate().map(|(index, source)| { let root = root.clone(); let barrier = barrier.clone(); std::thread::spawn(move || { barrier.wait(); (index, copy_workspace_item(&root, &source, Some("target")).unwrap()) }) }).collect(); let mut destinations = std::collections::HashSet::new(); for thread in threads { let (index, result) = thread.join().unwrap(); assert!(destinations.insert(result.rel_path.clone())); let path = root.join(&result.rel_path); assert_eq!(fs::read_to_string(if directory { path.join("content.txt") } else { path }).unwrap(), format!("source {index}")); } assert_eq!(fs::read_to_string(root.join("target/item")).unwrap(), "existing user content"); assert_eq!(fs::read_dir(root.join("target")).unwrap().count(), 9); fs::remove_dir_all(root).unwrap(); } } #[test] fn copy_rejects_the_workspace_root_and_descendant_destinations() { let root = std::env::temp_dir().join(format!("rs-copy-root-{}", uuid::Uuid::new_v4())); fs::create_dir_all(root.join("folder/child")).unwrap(); let root = dunce::canonicalize(root).unwrap(); fs::write(root.join("folder/note.md"), "source").unwrap(); for (source, parent) in [("", None), ("folder", Some("folder")), ("folder", Some("folder/child")), ("folder", Some(".."))] { assert!(copy_workspace_item(&root, source, parent).is_err()); } let duplicate = copy_workspace_item(&root, "folder/note.md", None).unwrap(); assert_eq!(duplicate.name, "note copy.md"); assert_eq!(fs::read_to_string(root.join(&duplicate.rel_path)).unwrap(), "source"); assert!(!root.join("folder/child/folder").exists()); fs::remove_dir_all(root).unwrap(); } #[cfg(any(unix, windows))] #[test] fn copy_rejects_source_links_and_preserves_destination_links_and_partial_folders() { let root = std::env::temp_dir().join(format!("rs-copy-links-{}", uuid::Uuid::new_v4())); fs::create_dir_all(root.join("source-folder")).unwrap(); fs::create_dir(root.join("target")).unwrap(); let root = dunce::canonicalize(root).unwrap(); fs::write(root.join("original.txt"), "original user content").unwrap(); fs::write(root.join("copy.txt"), "copy content").unwrap(); #[cfg(unix)] let symlink = std::os::unix::fs::symlink; #[cfg(windows)] 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; } panic!("Could not prepare the link test: {reason}"); } assert!(copy_workspace_item(&root, "source-link", Some("target")).unwrap_err().to_string().contains("symbolic links")); symlink(root.join("original.txt"), root.join("target/copy.txt")).unwrap(); let first = copy_workspace_item(&root, "copy.txt", Some("target")).unwrap(); assert_eq!(first.name, "copy copy.txt"); assert_eq!(fs::read_to_string(root.join("original.txt")).unwrap(), "original user content"); assert!(fs::symlink_metadata(root.join("target/copy.txt")).unwrap().file_type().is_symlink()); symlink(root.join("missing.txt"), root.join("target/copy copy 2.txt")).unwrap(); let second = copy_workspace_item(&root, "copy.txt", Some("target")).unwrap(); assert_eq!(second.name, "copy copy 3.txt"); assert!(!root.join("missing.txt").exists()); symlink(root.join("original.txt"), root.join("source-folder/link.txt")).unwrap(); let error = copy_workspace_item(&root, "source-folder", Some("target")).unwrap_err().to_string(); assert!(error.contains("Any copied items remain there"), "{error}"); assert!(root.join("target/source-folder").is_dir()); assert!(!root.join("target/source-folder copy").exists()); assert_eq!(fs::read_to_string(root.join("original.txt")).unwrap(), "original user content"); fs::remove_dir_all(root).unwrap(); } }