A browser puts only the first frame of an image on the clipboard, with HTML that names the image address. - Documents and cards download the original of a GIF, WebP, or AVIF address. The host commands workspace_save_image_url and workspace_download_image read the format from the file contents and refuse other data. A failed download keeps the first frame and shows a message. - Copy image in the RuneStone browser keeps the bytes that the page loaded. The engine reads them through the DevTools Protocol, so the website gets no second request. The new copiedImage command gives them in parts below the line limit of the host. A paste uses them first. - An empty dropped image file shows a message. Firefox gives such a file when the website refuses its download. Copy image needs a new browser engine build. Card 0d5c18f7.
1987 lines
87 KiB
Rust
1987 lines
87 KiB
Rust
use std::fs;
|
|
use std::collections::HashMap;
|
|
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, EventTarget, 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, 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<String>,
|
|
}
|
|
|
|
pub struct WorkspaceState {
|
|
inner: Mutex<HashMap<String, OpenWorkspace>>,
|
|
}
|
|
|
|
struct OpenWorkspace {
|
|
root: PathBuf,
|
|
/// The window that opened the workspace owns a watcher. A window bound to the
|
|
/// root of another window, such as a terminal window, has none.
|
|
watcher: Option<Box<dyn Watcher + Send>>,
|
|
}
|
|
|
|
impl WorkspaceState {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
inner: Mutex::new(HashMap::new()),
|
|
}
|
|
}
|
|
|
|
pub fn close_window(&self, label: &str) {
|
|
let removed = self.inner.lock().ok().and_then(|mut workspaces| workspaces.remove(label));
|
|
// Drop the watcher after the lock is released. On macOS the drop waits for the
|
|
// watcher thread, and that thread can wait for this lock to send an event.
|
|
drop(removed);
|
|
}
|
|
|
|
pub fn bind_terminal(&self, label: &str, root: PathBuf) -> Result<()> {
|
|
let replaced = self.inner.lock().map_err(|_| Error::new("workspace lock"))?
|
|
.insert(label.to_owned(), OpenWorkspace { root, watcher: None });
|
|
drop(replaced);
|
|
Ok(())
|
|
}
|
|
|
|
/// The windows that receive the events of the watcher that `owner` started for `root`:
|
|
/// the owner, and each window bound to the same root without a watcher of its own.
|
|
/// A window with its own watcher receives the events of that watcher only, so no window
|
|
/// receives the same change twice.
|
|
fn event_recipients(&self, owner: &str, root: &Path) -> Vec<String> {
|
|
let Ok(workspaces) = self.inner.lock() else { return Vec::new() };
|
|
workspaces.iter()
|
|
.filter(|(label, workspace)| workspace.root == root && (label.as_str() == owner || workspace.watcher.is_none()))
|
|
.map(|(label, _)| label.clone())
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
fn last_workspace_file(app: &AppHandle) -> Result<PathBuf> {
|
|
let dir = app
|
|
.path()
|
|
.app_data_dir()
|
|
.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) -> 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());
|
|
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<String> {
|
|
let Ok(bytes) = fs::read(path) else { return Vec::new() };
|
|
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else { return Vec::new() };
|
|
let mut roots: Vec<String> = 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<String>, 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) -> Result<Vec<String>> {
|
|
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) -> Result<Vec<String>> {
|
|
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) -> Result<Vec<String>> {
|
|
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) -> Result<PathBuf> {
|
|
let name = name.trim();
|
|
if !fsutil::is_plain_component(name)
|
|
|| name.chars().any(|c| c.is_control() || "<>:\"/\\|?*".contains(c))
|
|
{
|
|
return Err(Error::new("Choose a valid folder name without path separators or reserved characters."));
|
|
}
|
|
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 {
|
|
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) -> Result<()> {
|
|
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<PathBuf> {
|
|
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))
|
|
}
|
|
|
|
/// Check a workspace-relative path to an existing or a new item.
|
|
///
|
|
/// On Windows a colon starts a drive prefix or an alternate data stream, so it is rejected.
|
|
/// On macOS and Linux a colon is an ordinary name character. Existing files with a colon
|
|
/// in the name stay usable there. New names follow `check_portable_name`.
|
|
pub fn check_rel(rel: &str) -> Result<()> {
|
|
if rel.contains('\0') {
|
|
return Err(Error::new("path contains a null byte"));
|
|
}
|
|
let normalized = rel.replace('\\', "/");
|
|
if normalized.starts_with('/') || normalized.starts_with('\\') {
|
|
return Err(Error::new("absolute paths are not allowed"));
|
|
}
|
|
if cfg!(windows) && normalized.contains(':') {
|
|
return Err(Error::new("drive prefixes are not allowed"));
|
|
}
|
|
for part in normalized.split('/') {
|
|
if part == ".." {
|
|
return Err(Error::new("parent path segments are not allowed"));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Characters that Windows does not allow in a file or folder name.
|
|
const WINDOWS_INVALID_CHARACTERS: &str = "<>:\"|?*";
|
|
|
|
/// Check one new file or folder name.
|
|
///
|
|
/// Portability rule: a new name (create, rename destination, copy destination) cannot contain
|
|
/// a character that Windows rejects, on every platform. A workspace that is shared through Git
|
|
/// then stays usable on Windows. Existing names are not checked, so files with such characters
|
|
/// that other tools made on macOS or Linux stay readable, writable, renamable, and deletable.
|
|
fn check_portable_name(name: &str) -> Result<()> {
|
|
if name.chars().any(|c| c.is_control() || WINDOWS_INVALID_CHARACTERS.contains(c)) {
|
|
return Err(Error::new(format!(
|
|
"The name {name} contains a character that Windows does not allow: < > : \" | ? * or a control character. Choose another name."
|
|
)));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Apply `check_portable_name` to each component of `rel` that does not exist yet below `root`.
|
|
fn check_new_components(root: &Path, rel: &str) -> Result<()> {
|
|
let normalized = rel.replace('\\', "/");
|
|
let mut path = root.to_path_buf();
|
|
let mut missing = false;
|
|
for part in normalized.split('/').filter(|part| !part.is_empty() && *part != ".") {
|
|
path.push(part);
|
|
if !missing && fs::symlink_metadata(&path).is_ok() {
|
|
continue;
|
|
}
|
|
missing = true;
|
|
check_portable_name(part)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn join_rel(root: &Path, rel: &str) -> Result<PathBuf> {
|
|
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) -> Result<PathBuf> {
|
|
let joined = join_rel(root, rel)?;
|
|
let canon = dunce::canonicalize(&joined).map_err(|_| Error::new("path does not exist"))?;
|
|
if !is_inside(root, &canon) {
|
|
return Err(Error::new("path is outside the workspace"));
|
|
}
|
|
Ok(canon)
|
|
}
|
|
|
|
/// Resolve an existing item without following a link at its last component.
|
|
/// The parent folder must resolve inside the workspace. Delete and rename use this,
|
|
/// so that they act on a link itself and never on its target.
|
|
fn resolve_entry(root: &Path, rel: &str) -> Result<PathBuf> {
|
|
let joined = join_rel(root, rel)?;
|
|
if joined == root {
|
|
return Ok(joined);
|
|
}
|
|
let (Some(parent), Some(name)) = (joined.parent(), joined.file_name()) else {
|
|
return Err(Error::new("path does not exist"));
|
|
};
|
|
let parent = dunce::canonicalize(parent).map_err(|_| Error::new("path does not exist"))?;
|
|
if !is_inside(root, &parent) {
|
|
return Err(Error::new("path is outside the workspace"));
|
|
}
|
|
let path = parent.join(name);
|
|
fs::symlink_metadata(&path).map_err(|_| Error::new("path does not exist"))?;
|
|
Ok(path)
|
|
}
|
|
|
|
fn resolve_for_write(root: &Path, rel: &str) -> Result<PathBuf> {
|
|
let joined = join_rel(root, rel)?;
|
|
if joined == root {
|
|
return Err(Error::new("the workspace root cannot be modified"));
|
|
}
|
|
resolve_under(root, &joined)
|
|
}
|
|
|
|
/// Validate the nearest existing ancestor of `joined`, including `joined` itself.
|
|
/// Return the canonical path of an existing item, or `joined` for a missing one.
|
|
/// This catches links to outside the workspace even below missing folders.
|
|
fn resolve_under(root: &Path, joined: &Path) -> Result<PathBuf> {
|
|
for ancestor in joined.ancestors() {
|
|
if fs::symlink_metadata(ancestor).is_ok() {
|
|
let canonical = dunce::canonicalize(ancestor)?;
|
|
if !is_inside(root, &canonical) {
|
|
return Err(Error::new("path is outside the workspace"));
|
|
}
|
|
if ancestor == joined {
|
|
return Ok(canonical);
|
|
}
|
|
break;
|
|
}
|
|
if !is_inside(root, ancestor) {
|
|
return Err(Error::new("path is outside the workspace"));
|
|
}
|
|
}
|
|
Ok(joined.to_path_buf())
|
|
}
|
|
|
|
/// Resolve the destination of a rename. Keep the last component as the caller spelled it,
|
|
/// so that a rename can change only the letter case. Check new names for portability.
|
|
fn resolve_destination(root: &Path, rel: &str) -> Result<PathBuf> {
|
|
let joined = join_rel(root, rel)?;
|
|
if joined == root {
|
|
return Err(Error::new("the workspace root cannot be modified"));
|
|
}
|
|
let (Some(parent), Some(name)) = (joined.parent(), joined.file_name()) else {
|
|
return Err(Error::new("the workspace root cannot be modified"));
|
|
};
|
|
check_new_components(root, rel)?;
|
|
Ok(resolve_under(root, parent)?.join(name))
|
|
}
|
|
|
|
fn to_rel(root: &Path, path: &Path) -> Option<String> {
|
|
let root = dunce::simplified(root);
|
|
let path = dunce::simplified(path);
|
|
let rel = path.strip_prefix(root).ok()?;
|
|
Some(rel.to_string_lossy().replace('\\', "/"))
|
|
}
|
|
|
|
/// The Windows drive type of the volume that holds `path`, such as `DRIVE_FIXED` or `DRIVE_REMOTE`.
|
|
#[cfg(windows)]
|
|
fn drive_type(path: &Path) -> Option<u32> {
|
|
use std::os::windows::ffi::OsStrExt;
|
|
let mut wide: Vec<u16> = 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 None;
|
|
}
|
|
Some(windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(volume.as_ptr()))
|
|
}
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
fn is_network_path(path: &Path) -> bool {
|
|
let s = path.to_string_lossy();
|
|
if s.starts_with("\\\\") || s.starts_with("//") {
|
|
return true;
|
|
}
|
|
drive_type(path) == Some(windows_sys::Win32::System::WindowsProgramming::DRIVE_REMOTE)
|
|
}
|
|
|
|
#[cfg(not(windows))]
|
|
fn is_network_path(path: &Path) -> bool {
|
|
let s = path.to_string_lossy();
|
|
s.starts_with("//")
|
|
}
|
|
|
|
/// The name of a change for the frontend, such as "create" or "modify".
|
|
/// Access events are `None`: the frontend has no use for them.
|
|
fn event_kind(kind: ¬ify::EventKind) -> Option<String> {
|
|
if kind.is_access() {
|
|
return None;
|
|
}
|
|
Some(format!("{kind:?}").split('(').next().unwrap_or("other").to_lowercase())
|
|
}
|
|
|
|
fn emit_watch_event(app: &AppHandle, owner: &str, root: &Path, event: Event) {
|
|
let Some(kind) = event_kind(&event.kind) else { return };
|
|
let paths: Vec<String> = event.paths.iter().filter_map(|p| to_rel(root, p)).collect();
|
|
if paths.is_empty() {
|
|
return;
|
|
}
|
|
let recipients = app.state::<WorkspaceState>().event_recipients(owner, root);
|
|
if recipients.is_empty() {
|
|
return;
|
|
}
|
|
// The frontend listens with its own window label as the target (src/lib/workspace/api.ts).
|
|
// A listener without a target receives every event, so the filter cannot hide events from it.
|
|
let _ = app.emit_filter(
|
|
"workspace-event",
|
|
WorkspaceEvent {
|
|
root: root.to_string_lossy().into_owned(),
|
|
kind,
|
|
paths,
|
|
},
|
|
|target| event_target_label(target).is_some_and(|label| recipients.iter().any(|recipient| recipient == label)),
|
|
);
|
|
}
|
|
|
|
fn event_target_label(target: &EventTarget) -> Option<&str> {
|
|
match target {
|
|
EventTarget::AnyLabel { label }
|
|
| EventTarget::Window { label }
|
|
| EventTarget::Webview { label }
|
|
| EventTarget::WebviewWindow { label } => Some(label),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn start_watcher(
|
|
app: AppHandle,
|
|
owner: String,
|
|
root: PathBuf,
|
|
network: bool,
|
|
) -> Result<Box<dyn Watcher + Send>> {
|
|
let handler_root = root.clone();
|
|
let handler_app = app.clone();
|
|
let handler_owner = owner.clone();
|
|
let handler = move |res: notify::Result<Event>| {
|
|
if let Ok(event) = res {
|
|
emit_watch_event(&handler_app, &handler_owner, &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<Event>| {
|
|
if let Ok(event) = res {
|
|
emit_watch_event(&handler_app, &owner, &handler_root, event);
|
|
}
|
|
},
|
|
Config::default().with_poll_interval(Duration::from_secs(2)),
|
|
)?;
|
|
watcher.watch(&root, RecursiveMode::Recursive)?;
|
|
Ok(Box::new(watcher))
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn current_root(state: &WorkspaceState, label: &str) -> Result<PathBuf> {
|
|
let guard = state.inner.lock().map_err(|_| Error::new("workspace lock"))?;
|
|
guard
|
|
.get(label)
|
|
.map(|ws| ws.root.clone())
|
|
.ok_or_else(|| Error::new("no workspace is open"))
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn workspace_last_path(app: AppHandle, window: tauri::Window, state: State<WorkspaceState>) -> Option<String> {
|
|
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) -> Result<()> {
|
|
open_workspace_tab_window(app, state, root, None)
|
|
}
|
|
|
|
fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf, transfer: Option<String>) -> 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(), label.clone(), root.clone(), is_network_path(&root))?;
|
|
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(|_| 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(|_| Error::new("workspace lock"))?.insert(label.clone(), OpenWorkspace {
|
|
root: root.clone(), watcher: Some(watcher),
|
|
});
|
|
let result = (|| -> Result<()> {
|
|
let window = tauri::WebviewWindowBuilder::from_config(app, &config)
|
|
.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(Error::from_display)) {
|
|
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<String>) -> 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)
|
|
}
|
|
|
|
/// Run blocking file work on the blocking thread pool.
|
|
/// Tauri runs a synchronous command on the main thread, so long file work there freezes every window.
|
|
async fn blocking<T: Send + 'static>(work: impl FnOnce() -> Result<T> + Send + 'static) -> Result<T> {
|
|
tauri::async_runtime::spawn_blocking(work).await?
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn workspace_open(
|
|
app: AppHandle,
|
|
window: tauri::Window,
|
|
state: State<'_, WorkspaceState>,
|
|
path: String,
|
|
) -> Result<WorkspaceInfo> {
|
|
let label = window.label().to_owned();
|
|
let previous = current_root(&state, &label).ok();
|
|
let worker_app = app.clone();
|
|
let worker_label = label.clone();
|
|
// Canonicalization, the first scan of a polled network share, and the history file can block.
|
|
let (root, watcher) = blocking(move || {
|
|
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"));
|
|
}
|
|
if let Some(previous) = previous {
|
|
if previous == root { return Ok((root, None)); }
|
|
return Err(Error::new("Open another workspace in a new window."));
|
|
}
|
|
let network = is_network_path(&root);
|
|
let watcher = start_watcher(worker_app.clone(), worker_label, root.clone(), network)?;
|
|
save_last_workspace(&worker_app, &root)?;
|
|
Ok((root, Some(watcher)))
|
|
}).await?;
|
|
let Some(watcher) = watcher else { return Ok(workspace_info(&root)) };
|
|
{
|
|
let mut guard = state.inner.lock().map_err(|_| Error::new("workspace lock"))?;
|
|
// Another request for this window can finish first. Keep its workspace.
|
|
if let Some(current) = guard.get(&label) {
|
|
let same = current.root == root;
|
|
drop(guard);
|
|
drop(watcher);
|
|
return if same { Ok(workspace_info(&root)) } else { Err(Error::new("Open another workspace in a new window.")) };
|
|
}
|
|
guard.insert(label.clone(), 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, &label);
|
|
Ok(workspace_info(&root))
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn workspace_list(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, show_internal: Option<bool>) -> Result<Vec<TreeEntry>> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || list_entries_visible(&root, &rel, show_internal.unwrap_or(false))).await
|
|
}
|
|
|
|
fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> Result<Vec<TreeEntry>> {
|
|
let dir = resolve_existing(root, rel)?;
|
|
if !dir.is_dir() {
|
|
return Err(Error::new("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>) -> Result<Vec<String>> {
|
|
let root = current_root(&state, window.label())?;
|
|
tauri::async_runtime::spawn_blocking(move || markdown_paths(&root))
|
|
.await.map_err(|error| Error::new(format!("Markdown scan failed: {error}")))?
|
|
}
|
|
|
|
fn markdown_paths(root: &Path) -> Result<Vec<String>> {
|
|
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 async fn workspace_read(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, missing_ok: Option<bool>) -> Result<Option<String>> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || {
|
|
let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? };
|
|
if path.is_dir() {
|
|
return Err(Error::new("path is a folder"));
|
|
}
|
|
read_optional_text(&path, missing_ok.unwrap_or(false))
|
|
}).await
|
|
}
|
|
|
|
fn read_optional_text(path: &Path, missing_ok: bool) -> Result<Option<String>> {
|
|
match fs::read(path) {
|
|
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()),
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct TextRead {
|
|
path: String,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
source: Option<String>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
error: Option<String>,
|
|
}
|
|
|
|
fn read_many_text(root: &Path, paths: Vec<String>) -> Result<Vec<TextRead>> {
|
|
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 = (|| -> Result<String> {
|
|
let resolved = resolve_existing(root, &path)?;
|
|
let file = fs::File::open(resolved)?;
|
|
let metadata = file.metadata()?;
|
|
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(|_| Error::new("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<String>) -> Result<Vec<TextRead>> {
|
|
let root = current_root(&state, window.label())?;
|
|
tauri::async_runtime::spawn_blocking(move || read_many_text(&root, paths))
|
|
.await?
|
|
}
|
|
|
|
const MAX_BINARY_BYTES: u64 = 64 * 1024 * 1024;
|
|
|
|
fn read_workspace_bytes(root: &Path, rel: &str) -> Result<Vec<u8>> {
|
|
let path = resolve_existing(root, rel)?;
|
|
let file = fs::File::open(path)?;
|
|
let metadata = file.metadata()?;
|
|
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) -> Result<tauri::ipc::Response> {
|
|
let root = current_root(&state, window.label())?;
|
|
let bytes = tauri::async_runtime::spawn_blocking(move || read_workspace_bytes(&root, &rel))
|
|
.await??;
|
|
Ok(tauri::ipc::Response::new(bytes))
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn workspace_write(
|
|
window: tauri::Window,
|
|
state: State<'_, WorkspaceState>,
|
|
rel: String,
|
|
contents: String,
|
|
expected: Option<String>,
|
|
) -> Result<()> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || write_workspace_text(&root, &rel, &contents, expected.as_deref())).await
|
|
}
|
|
|
|
fn write_workspace_text(root: &Path, rel: &str, contents: &str, expected: Option<&str>) -> Result<()> {
|
|
let path = resolve_for_write(root, rel)?;
|
|
// A save of an existing file keeps its name. A save that creates a file names a new item.
|
|
check_new_components(root, rel)?;
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent).map_err(|reason| Error::new(format!("Could not prepare the save folder for {}: {reason}", path.display())))?;
|
|
}
|
|
fsutil::write_text(&path, contents, expected)
|
|
}
|
|
|
|
fn is_internal_name(name: &str) -> bool {
|
|
matches!(name, ".git" | ".obsidian" | ".runestone") || name.starts_with(".runestone-save-")
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn workspace_create(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, kind: String, contents: Option<String>) -> Result<()> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || create_item(&root, &rel, &kind, contents.as_deref())).await
|
|
}
|
|
|
|
fn create_item(root: &Path, rel: &str, kind: &str, contents: Option<&str>) -> Result<()> {
|
|
let path = resolve_for_write(root, rel)?;
|
|
if path.exists() {
|
|
return Err(Error::new("path already exists"));
|
|
}
|
|
check_new_components(root, rel)?;
|
|
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) -> Result<()> {
|
|
static NEXT_CREATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
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)));
|
|
Ok(fsutil::create_file(path, &temp, contents.as_bytes())?)
|
|
}
|
|
|
|
fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Option<&str>) -> Result<PathBuf> {
|
|
let root = current_root(state, label)?;
|
|
if let Some(expected) = expected_root {
|
|
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())?;
|
|
if expected != current { return Err(changed()); }
|
|
}
|
|
Ok(root)
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn workspace_rename(window: tauri::Window, state: State<'_, WorkspaceState>, from: String, to: String, expected_root: Option<String>) -> Result<()> {
|
|
let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?;
|
|
blocking(move || rename_item(&root, &from, &to)).await
|
|
}
|
|
|
|
fn rename_item(root: &Path, from: &str, to: &str) -> Result<()> {
|
|
// Rename the item itself. A link moves as a link, and its target stays in place.
|
|
let from_path = resolve_entry(root, from)?;
|
|
if from_path == root {
|
|
return Err(Error::new("the workspace root cannot be renamed"));
|
|
}
|
|
let to_path = resolve_destination(root, to)?;
|
|
if fs::symlink_metadata(&to_path).is_ok() {
|
|
// On a case-insensitive volume, `Note.md` already "exists" when `note.md` is renamed to it.
|
|
// Allow the rename only when the destination is the source item itself.
|
|
let case_only = from_path.file_name() != to_path.file_name()
|
|
&& fsutil::same_entry(&from_path, &to_path).unwrap_or(false);
|
|
if !case_only {
|
|
return Err(Error::new("destination already exists"));
|
|
}
|
|
fs::rename(&from_path, &to_path)?;
|
|
return Ok(());
|
|
}
|
|
if let Some(parent) = to_path.parent() {
|
|
fs::create_dir_all(parent)?;
|
|
}
|
|
fs::rename(from_path, to_path)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Move an item to the trash of the operating system, or delete it permanently with `permanent`.
|
|
/// The frontend asks for confirmation before a permanent delete.
|
|
#[tauri::command]
|
|
pub async fn workspace_delete(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, permanent: Option<bool>) -> Result<()> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || delete_item(&root, &rel, permanent.unwrap_or(false))).await
|
|
}
|
|
|
|
fn delete_item(root: &Path, rel: &str, permanent: bool) -> Result<()> {
|
|
// Delete the item itself. A link goes away, and its target stays in place.
|
|
let path = resolve_entry(root, rel)?;
|
|
if path == root {
|
|
return Err(Error::new("the workspace root cannot be deleted"));
|
|
}
|
|
if permanent {
|
|
remove_entry(&path)?;
|
|
Ok(())
|
|
} else {
|
|
move_to_trash(&path)
|
|
}
|
|
}
|
|
|
|
/// Remove `path` permanently. Remove a link itself and never follow it.
|
|
fn remove_entry(path: &Path) -> std::io::Result<()> {
|
|
let metadata = fs::symlink_metadata(path)?;
|
|
if metadata.file_type().is_symlink() {
|
|
// A Windows folder link or junction is a directory entry. Other links are files.
|
|
#[cfg(windows)]
|
|
{
|
|
use std::os::windows::fs::MetadataExt;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY;
|
|
if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
|
|
return fs::remove_dir(path);
|
|
}
|
|
}
|
|
return fs::remove_file(path);
|
|
}
|
|
if metadata.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
|
|
}
|
|
|
|
/// Move `path` to the trash of the operating system. The trash moves a link itself.
|
|
fn move_to_trash(path: &Path) -> Result<()> {
|
|
// Windows deletes permanently, without a prompt, where a drive has no Recycle Bin.
|
|
// Network shares and removable drives have none, so refuse them here.
|
|
#[cfg(windows)]
|
|
if drive_type(path) != Some(windows_sys::Win32::System::WindowsProgramming::DRIVE_FIXED) {
|
|
return Err(Error::new("The trash is not available on this drive."));
|
|
}
|
|
let target = path.to_path_buf();
|
|
// A new thread has no COM state from earlier work, so the trash crate can initialize COM on Windows.
|
|
let result = std::thread::spawn(move || trash_item(&target))
|
|
.join()
|
|
.map_err(|_| Error::new("Could not move the item to the trash."))?;
|
|
result.map_err(|reason| Error::new(format!("Could not move the item to the trash: {reason}")))
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
fn trash_item(path: &Path) -> std::result::Result<(), trash::Error> {
|
|
use trash::macos::{DeleteMethod, TrashContextExtMacos};
|
|
// The file manager method needs no Finder automation permission and plays no sound.
|
|
let mut context = trash::TrashContext::default();
|
|
context.set_delete_method(DeleteMethod::NsFileManager);
|
|
context.delete(path)
|
|
}
|
|
|
|
#[cfg(not(target_os = "macos"))]
|
|
fn trash_item(path: &Path) -> std::result::Result<(), trash::Error> {
|
|
trash::delete(path)
|
|
}
|
|
|
|
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 async fn workspace_read_data_url(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String) -> Result<String> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || read_data_url(&root, &rel)).await
|
|
}
|
|
|
|
fn read_data_url(root: &Path, rel: &str) -> Result<String> {
|
|
let path = resolve_existing(root, rel)?;
|
|
if path.is_dir() {
|
|
return Err(Error::new("path is a folder"));
|
|
}
|
|
let mime = mime_from_path(&path).ok_or_else(|| Error::new("file is not an image"))?;
|
|
// Check the size before the read, so that a large file is never loaded into memory.
|
|
let file = fs::File::open(&path)?;
|
|
if file.metadata()?.len() > MAX_IMAGE_BYTES as u64 {
|
|
return Err(Error::new("image is too large"));
|
|
}
|
|
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
|
|
.ok_or_else(|| Error::new("image is too large"))?;
|
|
Ok(data_url(mime, &bytes))
|
|
}
|
|
|
|
fn data_url(mime: &str, bytes: &[u8]) -> String {
|
|
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 async fn workspace_copy(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, parent: Option<String>, expected_root: Option<String>) -> Result<CopyResult> {
|
|
let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?;
|
|
blocking(move || copy_workspace_item(&root, &rel, parent.as_deref())).await
|
|
}
|
|
|
|
fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> Result<CopyResult> {
|
|
if fs::symlink_metadata(join_rel(root, rel)?)?.file_type().is_symlink() {
|
|
return Err(Error::new("Cannot copy symbolic links."));
|
|
}
|
|
let from = resolve_existing(root, rel)?;
|
|
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(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(Error::new("path is outside the workspace"));
|
|
}
|
|
// The copy gets a new name, so it follows the portability rule of new names.
|
|
check_portable_name(&candidate.file_name().unwrap_or_default().to_string_lossy())?;
|
|
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(|| Error::new("No copy name is available."))?;
|
|
}
|
|
Err(reason) => return Err(reason.into()),
|
|
}
|
|
};
|
|
let rel_path =
|
|
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())
|
|
.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<WorkspaceState>, rel: String) -> Result<String> {
|
|
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<WorkspaceState>, 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(Error::from_display)
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn workspace_open_terminal(window: tauri::Window, state: State<WorkspaceState>, 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(|| 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(Error::from_display)?;
|
|
Ok(())
|
|
}
|
|
#[cfg(all(unix, not(target_os = "macos")))]
|
|
{ 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<WorkspaceState>, 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(Error::from_display);
|
|
}
|
|
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(Error::from_display)?;
|
|
return Ok(());
|
|
}
|
|
#[cfg(not(windows))]
|
|
Err(Error::new("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 async fn workspace_search(window: tauri::Window, state: State<'_, WorkspaceState>, query: String) -> Result<Vec<SearchHit>> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || search_entries(&root, &query)).await
|
|
}
|
|
|
|
fn search_entries(root: &Path, query: &str) -> Result<Vec<SearchHit>> {
|
|
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)
|
|
}
|
|
|
|
/// Save an image. The only caller (`insertImage` in Workbench.svelte) writes a new, unique
|
|
/// attachment name, so it has no previous contents to compare. A conflict check needs an
|
|
/// `expected` value from a caller that replaces an existing image.
|
|
#[tauri::command]
|
|
pub async fn workspace_write_bytes(
|
|
window: tauri::Window,
|
|
state: State<'_, WorkspaceState>,
|
|
rel: String,
|
|
base64: String,
|
|
) -> Result<()> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || write_image(&root, &rel, &base64)).await
|
|
}
|
|
|
|
fn write_image(root: &Path, rel: &str, base64: &str) -> Result<()> {
|
|
let path = resolve_for_write(root, rel)?;
|
|
mime_from_path(&path).ok_or_else(|| Error::new("file is not an image"))?;
|
|
check_new_components(root, rel)?;
|
|
let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, base64.trim())
|
|
.map_err(|_| Error::new("invalid image data"))?;
|
|
if bytes.len() > MAX_IMAGE_BYTES {
|
|
return Err(Error::new("image is too large"));
|
|
}
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent)?;
|
|
}
|
|
// Write beside the destination, then replace it, so that a failed write keeps the old file.
|
|
fsutil::write_bytes(&path, &bytes)
|
|
}
|
|
|
|
/// Save the original of an image that a web page copied. The clipboard has only a still copy,
|
|
/// so an animated GIF needs its source file. `rel` has no extension. The format of the
|
|
/// downloaded file sets it. Returns the path of the new file.
|
|
#[tauri::command]
|
|
pub async fn workspace_save_image_url(
|
|
window: tauri::Window,
|
|
state: State<'_, WorkspaceState>,
|
|
url: String,
|
|
rel: String,
|
|
) -> Result<String> {
|
|
let root = current_root(&state, window.label())?;
|
|
blocking(move || {
|
|
let bytes = download_image(&url)?;
|
|
save_image(&root, &rel, &bytes)
|
|
})
|
|
.await
|
|
}
|
|
|
|
/// Download a web image and return it as a data URL. Project Management keeps card images
|
|
/// as data URLs, so this gives a card the original of a copied image.
|
|
#[tauri::command]
|
|
pub async fn workspace_download_image(url: String) -> Result<String> {
|
|
blocking(move || image_data_url(&download_image(&url)?)).await
|
|
}
|
|
|
|
fn image_data_url(bytes: &[u8]) -> Result<String> {
|
|
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
|
|
let mime = mime_from_path(Path::new(&format!("image.{extension}")))
|
|
.ok_or_else(|| Error::new("file is not an image"))?;
|
|
Ok(data_url(mime, bytes))
|
|
}
|
|
|
|
fn download_image(url: &str) -> Result<Vec<u8>> {
|
|
use std::io::Read;
|
|
let web = |url: &reqwest::Url| matches!(url.scheme(), "http" | "https");
|
|
let url = reqwest::Url::parse(url).map_err(|_| Error::new("invalid image address"))?;
|
|
if !web(&url) {
|
|
return Err(Error::new("image address is not http or https"));
|
|
}
|
|
let client = reqwest::blocking::Client::builder()
|
|
.user_agent(concat!("RuneStone/", env!("CARGO_PKG_VERSION")))
|
|
.connect_timeout(Duration::from_secs(10))
|
|
.timeout(Duration::from_secs(30))
|
|
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
|
|
if attempt.previous().len() >= 5 || !web(attempt.url()) {
|
|
attempt.stop()
|
|
} else {
|
|
attempt.follow()
|
|
}
|
|
}))
|
|
.build()
|
|
.map_err(Error::from_display)?;
|
|
let response = client.get(url).send().map_err(Error::from_display)?;
|
|
if !response.status().is_success() {
|
|
return Err(Error::new(format!("image server answered {}", response.status())));
|
|
}
|
|
let mut bytes = Vec::new();
|
|
response.take(MAX_IMAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?;
|
|
if bytes.len() > MAX_IMAGE_BYTES {
|
|
return Err(Error::new("image is too large"));
|
|
}
|
|
Ok(bytes)
|
|
}
|
|
|
|
fn save_image(root: &Path, rel: &str, bytes: &[u8]) -> Result<String> {
|
|
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
|
|
let rel = format!("{rel}.{extension}");
|
|
let path = resolve_for_write(root, &rel)?;
|
|
check_new_components(root, &rel)?;
|
|
if path.exists() {
|
|
return Err(Error::new("a file with that name already exists"));
|
|
}
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent)?;
|
|
}
|
|
fsutil::write_bytes(&path, bytes)?;
|
|
Ok(rel)
|
|
}
|
|
|
|
/// The extension of a raster image format from its first bytes. A web server can send a
|
|
/// wrong type, and an SVG file can contain scripts, so the type header and SVG do not count.
|
|
fn image_extension(bytes: &[u8]) -> Option<&'static str> {
|
|
let at = |start: usize, value: &[u8]| bytes.get(start..start + value.len()) == Some(value);
|
|
if at(0, b"GIF87a") || at(0, b"GIF89a") {
|
|
Some("gif")
|
|
} else if at(0, b"\x89PNG\r\n\x1a\n") {
|
|
Some("png")
|
|
} else if at(0, b"\xff\xd8\xff") {
|
|
Some("jpg")
|
|
} else if at(0, b"RIFF") && at(8, b"WEBP") {
|
|
Some("webp")
|
|
} else if at(4, b"ftypavif") || at(4, b"ftypavis") {
|
|
Some("avif")
|
|
} else if at(0, b"BM") {
|
|
Some("bmp")
|
|
} else if at(0, b"\0\0\x01\0") {
|
|
Some("ico")
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
#[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_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"));
|
|
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_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_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"));
|
|
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(&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(&state, "workspace-0").is_err());
|
|
assert_eq!(current_root(&state, "main").unwrap(), first);
|
|
state.close_window("main");
|
|
assert_eq!(current_root(&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 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("\\Windows").is_err());
|
|
// On macOS and Linux, `C:` is an ordinary folder name below the workspace root.
|
|
assert_eq!(check_rel("C:/Windows").is_err(), cfg!(windows));
|
|
}
|
|
|
|
fn workspace_fixture(name: &str) -> PathBuf {
|
|
let root = std::env::temp_dir().join(format!("rs-{name}-{}", uuid::Uuid::new_v4()));
|
|
fs::create_dir_all(&root).unwrap();
|
|
dunce::canonicalize(root).unwrap()
|
|
}
|
|
|
|
fn names(root: &Path) -> Vec<String> {
|
|
let mut names: Vec<String> = fs::read_dir(root).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
|
names.sort();
|
|
names
|
|
}
|
|
|
|
#[test]
|
|
fn events_go_to_the_watcher_owner_and_bound_windows_of_the_same_root() {
|
|
let state = WorkspaceState::new();
|
|
let (notes, other) = (PathBuf::from("D:/notes"), PathBuf::from("D:/other"));
|
|
{
|
|
let mut workspaces = state.inner.lock().unwrap();
|
|
for (label, root) in [("main", ¬es), ("workspace-0", ¬es), ("workspace-1", &other)] {
|
|
workspaces.insert(label.into(), OpenWorkspace { root: root.clone(), watcher: Some(Box::new(notify::NullWatcher)) });
|
|
}
|
|
}
|
|
state.bind_terminal("terminal-0", notes.clone()).unwrap();
|
|
state.bind_terminal("terminal-1", other.clone()).unwrap();
|
|
let sorted = |mut labels: Vec<String>| { labels.sort(); labels };
|
|
// Each window with a watcher gets its own watcher's events once. A terminal window has no watcher.
|
|
assert_eq!(sorted(state.event_recipients("main", ¬es)), ["main", "terminal-0"]);
|
|
assert_eq!(sorted(state.event_recipients("workspace-0", ¬es)), ["terminal-0", "workspace-0"]);
|
|
assert_eq!(sorted(state.event_recipients("workspace-1", &other)), ["terminal-1", "workspace-1"]);
|
|
state.close_window("main");
|
|
assert_eq!(state.event_recipients("main", ¬es), ["terminal-0"]);
|
|
assert_eq!(event_target_label(&EventTarget::AnyLabel { label: "main".into() }), Some("main"));
|
|
assert_eq!(event_target_label(&EventTarget::WebviewWindow { label: "main".into() }), Some("main"));
|
|
assert_eq!(event_target_label(&EventTarget::Any), None);
|
|
assert_eq!(event_target_label(&EventTarget::App), None);
|
|
}
|
|
|
|
#[test]
|
|
fn access_events_are_not_sent() {
|
|
use notify::event::{AccessKind, CreateKind, EventKind, ModifyKind};
|
|
assert_eq!(event_kind(&EventKind::Access(AccessKind::Any)), None);
|
|
assert_eq!(event_kind(&EventKind::Create(CreateKind::File)).as_deref(), Some("create"));
|
|
assert_eq!(event_kind(&EventKind::Modify(ModifyKind::Any)).as_deref(), Some("modify"));
|
|
assert_eq!(event_kind(&EventKind::Remove(notify::event::RemoveKind::Any)).as_deref(), Some("remove"));
|
|
}
|
|
|
|
#[test]
|
|
fn case_only_renames_change_the_name_of_the_same_item() {
|
|
let root = workspace_fixture("case-rename");
|
|
fs::write(root.join("note.md"), "note text").unwrap();
|
|
fs::create_dir(root.join("folder")).unwrap();
|
|
fs::write(root.join("folder/inside.md"), "inside").unwrap();
|
|
rename_item(&root, "note.md", "Note.md").unwrap();
|
|
rename_item(&root, "folder", "Folder").unwrap();
|
|
assert_eq!(names(&root), ["Folder", "Note.md"]);
|
|
assert_eq!(fs::read_to_string(root.join("Note.md")).unwrap(), "note text");
|
|
assert_eq!(fs::read_to_string(root.join("Folder/inside.md")).unwrap(), "inside");
|
|
// A different item at the destination is still a conflict.
|
|
fs::write(root.join("other.md"), "other").unwrap();
|
|
assert!(rename_item(&root, "other.md", "Note.md").unwrap_err().to_string().contains("destination already exists"));
|
|
if root.join("NOTE.MD").exists() {
|
|
// On a case-insensitive volume, another spelling of an existing name is also a conflict.
|
|
assert!(rename_item(&root, "other.md", "NOTE.MD").is_err());
|
|
}
|
|
assert_eq!(fs::read_to_string(root.join("Note.md")).unwrap(), "note text");
|
|
assert_eq!(fs::read_to_string(root.join("other.md")).unwrap(), "other");
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn new_names_reject_characters_that_windows_does_not_allow() {
|
|
let root = workspace_fixture("portable-names");
|
|
fs::write(root.join("note.md"), "note").unwrap();
|
|
for name in ["a:b.md", "a?b.md", "a*b.md", "a|b.md", "a\"b.md", "a<b.md", "a>b.md", "tab\there.md", "new/a:b.md"] {
|
|
assert!(check_new_components(&root, name).is_err(), "{name}");
|
|
assert!(create_item(&root, name, "file", None).is_err(), "{name}");
|
|
assert!(rename_item(&root, "note.md", name).is_err(), "{name}");
|
|
assert!(write_workspace_text(&root, name, "text", None).is_err(), "{name}");
|
|
}
|
|
assert_eq!(names(&root), ["note.md"]);
|
|
for name in ["plain.md", "a b.md", "日本語.md", "new/nested.md"] {
|
|
assert!(check_new_components(&root, name).is_ok(), "{name}");
|
|
}
|
|
create_item(&root, "new/nested.md", "file", Some("nested")).unwrap();
|
|
assert_eq!(fs::read_to_string(root.join("new/nested.md")).unwrap(), "nested");
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn existing_names_with_a_colon_stay_usable_on_macos_and_linux() {
|
|
let root = workspace_fixture("colon-names");
|
|
fs::create_dir(root.join("2026-10-27 10:00")).unwrap();
|
|
fs::write(root.join("2026-10-27 10:00/meeting: notes.md"), "notes").unwrap();
|
|
let rel = "2026-10-27 10:00/meeting: notes.md";
|
|
assert_eq!(read_optional_text(&resolve_existing(&root, rel).unwrap(), false).unwrap().as_deref(), Some("notes"));
|
|
write_workspace_text(&root, rel, "edited", Some("notes")).unwrap();
|
|
// A new file below an existing folder with a colon is allowed. Only the new name is checked.
|
|
create_item(&root, "2026-10-27 10:00/summary.md", "file", None).unwrap();
|
|
assert!(create_item(&root, "2026-10-27 10:00/summary: draft.md", "file", None).is_err());
|
|
assert!(copy_workspace_item(&root, rel, None).is_err());
|
|
rename_item(&root, rel, "2026-10-27 10:00/meeting notes.md").unwrap();
|
|
assert_eq!(fs::read_to_string(root.join("2026-10-27 10:00/meeting notes.md")).unwrap(), "edited");
|
|
fs::write(root.join("a:b.md"), "x").unwrap();
|
|
delete_item(&root, "a:b.md", true).unwrap();
|
|
assert!(!root.join("a:b.md").exists());
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn image_data_urls_check_the_size_before_reading() {
|
|
let root = workspace_fixture("data-url");
|
|
fs::write(root.join("dot.png"), b"\x89PNG").unwrap();
|
|
assert_eq!(read_data_url(&root, "dot.png").unwrap(), "data:image/png;base64,iVBORw==");
|
|
// A sparse file has the reported size without data on the disk.
|
|
fs::File::create(root.join("large.png")).unwrap().set_len(MAX_IMAGE_BYTES as u64 + 1).unwrap();
|
|
assert_eq!(read_data_url(&root, "large.png").unwrap_err().to_string(), "image is too large");
|
|
assert!(read_data_url(&root, "missing.png").is_err());
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn image_writes_replace_atomically() {
|
|
let root = workspace_fixture("write-image");
|
|
write_image(&root, "attachments/dot.png", "iVBORw==").unwrap();
|
|
assert_eq!(fs::read(root.join("attachments/dot.png")).unwrap(), b"\x89PNG");
|
|
write_image(&root, "attachments/dot.png", "AQID").unwrap();
|
|
assert_eq!(fs::read(root.join("attachments/dot.png")).unwrap(), [1, 2, 3]);
|
|
assert!(write_image(&root, "attachments/dot.png", "not base64!").is_err());
|
|
assert!(write_image(&root, "attachments/note.md", "AQID").is_err());
|
|
assert!(write_image(&root, "attachments/bad?.png", "AQID").is_err());
|
|
assert_eq!(fs::read(root.join("attachments/dot.png")).unwrap(), [1, 2, 3]);
|
|
assert_eq!(names(&root.join("attachments")), ["dot.png"]);
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn image_formats_come_from_the_file_contents() {
|
|
assert_eq!(image_extension(b"GIF89a\x01\0"), Some("gif"));
|
|
assert_eq!(image_extension(b"GIF87a"), Some("gif"));
|
|
assert_eq!(image_extension(b"\x89PNG\r\n\x1a\n\0"), Some("png"));
|
|
assert_eq!(image_extension(b"\xff\xd8\xff\xe0"), Some("jpg"));
|
|
assert_eq!(image_extension(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
|
|
assert_eq!(image_extension(b"\0\0\0\x1cftypavif"), Some("avif"));
|
|
assert_eq!(image_extension(b"BM\0\0"), Some("bmp"));
|
|
assert_eq!(image_extension(b"\0\0\x01\0\x01\0"), Some("ico"));
|
|
assert_eq!(image_extension(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), None);
|
|
assert_eq!(image_extension(b"<!doctype html>"), None);
|
|
assert_eq!(image_extension(b"RIFF"), None);
|
|
assert_eq!(image_extension(b""), None);
|
|
}
|
|
|
|
#[test]
|
|
fn web_images_keep_their_original_format() {
|
|
let root = workspace_fixture("image-url");
|
|
let gif = b"GIF89a\x01\0\x01\0\0\0\0;".to_vec();
|
|
let (base, server) = crate::plugin_sources::tests::server(vec![
|
|
("302 Found\r\nLocation: /cat.gif".into(), Vec::new()),
|
|
("200 OK\r\nContent-Type: image/png".into(), gif.clone()),
|
|
("200 OK\r\nContent-Type: image/gif".into(), b"<!doctype html>".to_vec()),
|
|
("404 Not Found".into(), Vec::new()),
|
|
]);
|
|
let bytes = download_image(&format!("{base}/image")).unwrap();
|
|
assert_eq!(save_image(&root, "attachments/pasted", &bytes).unwrap(), "attachments/pasted.gif");
|
|
assert_eq!(fs::read(root.join("attachments/pasted.gif")).unwrap(), gif);
|
|
assert_eq!(image_data_url(&bytes).unwrap(), "data:image/gif;base64,R0lGODlhAQABAAAAADs=");
|
|
let page = download_image(&format!("{base}/page")).unwrap();
|
|
assert_eq!(save_image(&root, "attachments/page", &page).unwrap_err().to_string(), "file is not an image");
|
|
assert_eq!(image_data_url(&page).unwrap_err().to_string(), "file is not an image");
|
|
assert_eq!(image_data_url(b"\xff\xd8\xff\xe0").unwrap(), "data:image/jpeg;base64,/9j/4A==");
|
|
assert!(download_image(&format!("{base}/missing")).unwrap_err().to_string().contains("404"));
|
|
let requests = server.join().unwrap();
|
|
assert!(requests[1].starts_with("GET /cat.gif "));
|
|
assert!(download_image("file:///C:/cat.gif").is_err());
|
|
assert!(save_image(&root, "attachments/pasted", &gif).is_err(), "an existing file stays");
|
|
assert!(save_image(&root, "../outside", &gif).is_err());
|
|
assert_eq!(names(&root.join("attachments")), ["pasted.gif"]);
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn permanent_delete_removes_files_and_folders_but_never_the_root() {
|
|
let root = workspace_fixture("delete");
|
|
fs::create_dir_all(root.join("folder/child")).unwrap();
|
|
fs::write(root.join("folder/child/note.md"), "note").unwrap();
|
|
fs::write(root.join("file.md"), "file").unwrap();
|
|
for rel in ["", ".", "missing.md", "../outside"] {
|
|
assert!(delete_item(&root, rel, true).is_err(), "{rel}");
|
|
assert!(delete_item(&root, rel, false).is_err(), "{rel}");
|
|
}
|
|
delete_item(&root, "folder", true).unwrap();
|
|
delete_item(&root, "file.md", true).unwrap();
|
|
assert!(names(&root).is_empty());
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
#[ignore = "Moves a temporary file to the system trash."]
|
|
fn delete_moves_items_to_the_trash() {
|
|
let root = workspace_fixture("trash");
|
|
fs::write(root.join("trash-me.md"), "trash").unwrap();
|
|
fs::create_dir(root.join("trash-folder")).unwrap();
|
|
delete_item(&root, "trash-me.md", false).unwrap();
|
|
delete_item(&root, "trash-folder", false).unwrap();
|
|
assert!(names(&root).is_empty());
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[cfg(any(unix, windows))]
|
|
#[test]
|
|
fn delete_and_rename_act_on_links_and_keep_their_targets() {
|
|
let fixture = workspace_fixture("link-actions");
|
|
let root = fixture.join("workspace");
|
|
fs::create_dir_all(root.join("folder")).unwrap();
|
|
fs::write(root.join("target.md"), "inside target").unwrap();
|
|
fs::write(fixture.join("outside.md"), "outside target").unwrap();
|
|
fs::write(root.join("folder/keep.md"), "keep").unwrap();
|
|
#[cfg(unix)]
|
|
let (file_link, folder_link) = (|from: &Path, to: &Path| std::os::unix::fs::symlink(from, to), |from: &Path, to: &Path| std::os::unix::fs::symlink(from, to));
|
|
#[cfg(windows)]
|
|
let (file_link, folder_link) = (|from: &Path, to: &Path| std::os::windows::fs::symlink_file(from, to), |from: &Path, to: &Path| std::os::windows::fs::symlink_dir(from, to));
|
|
if let Err(reason) = file_link(&root.join("target.md"), &root.join("link.md")) {
|
|
#[cfg(windows)]
|
|
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(fixture).unwrap(); return; }
|
|
panic!("Could not prepare the link test: {reason}");
|
|
}
|
|
file_link(&fixture.join("outside.md"), &root.join("outside-link.md")).unwrap();
|
|
folder_link(&root.join("folder"), &root.join("folder-link")).unwrap();
|
|
rename_item(&root, "link.md", "renamed-link.md").unwrap();
|
|
assert!(fs::symlink_metadata(root.join("renamed-link.md")).unwrap().file_type().is_symlink());
|
|
assert_eq!(fs::read_to_string(root.join("target.md")).unwrap(), "inside target");
|
|
for rel in ["renamed-link.md", "outside-link.md", "folder-link"] {
|
|
delete_item(&root, rel, true).unwrap();
|
|
assert!(fs::symlink_metadata(root.join(rel)).is_err(), "{rel}");
|
|
}
|
|
assert_eq!(fs::read_to_string(root.join("target.md")).unwrap(), "inside target");
|
|
assert_eq!(fs::read_to_string(fixture.join("outside.md")).unwrap(), "outside target");
|
|
assert_eq!(fs::read_to_string(root.join("folder/keep.md")).unwrap(), "keep");
|
|
assert_eq!(names(&root), ["folder", "target.md"]);
|
|
fs::remove_dir_all(fixture).unwrap();
|
|
}
|
|
|
|
#[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(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"));
|
|
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();
|
|
}
|
|
}
|