Update editor, workspace, Git services, appearance, and project guides
This commit is contained in:
+445
-45
@@ -392,12 +392,20 @@ fn workspace_info(root: &Path) -> WorkspaceInfo {
|
||||
}
|
||||
|
||||
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<String>) -> 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!("index.html?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),
|
||||
@@ -418,10 +426,10 @@ fn open_workspace_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn workspace_open_window(app: AppHandle, state: State<'_, WorkspaceState>, path: String) -> WsResult<()> {
|
||||
pub async fn workspace_open_window(app: AppHandle, state: State<'_, WorkspaceState>, path: String, transfer: Option<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")); }
|
||||
open_workspace_window(&app, &state, root)
|
||||
open_workspace_tab_window(&app, &state, root, transfer)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -456,12 +464,16 @@ pub fn workspace_open(
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<Vec<TreeEntry>> {
|
||||
pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel: String, show_internal: Option<bool>) -> WsResult<Vec<TreeEntry>> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
list_entries(&root, &rel)
|
||||
list_entries_visible(&root, &rel, show_internal.unwrap_or(false))
|
||||
}
|
||||
|
||||
fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
|
||||
list_entries_visible(root, rel, false)
|
||||
}
|
||||
|
||||
fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> WsResult<Vec<TreeEntry>> {
|
||||
let dir = resolve_existing(root, rel)?;
|
||||
if !dir.is_dir() {
|
||||
return Err(err("path is not a folder"));
|
||||
@@ -489,7 +501,7 @@ fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
|
||||
Some(n) => n.to_string_lossy().into_owned(),
|
||||
None => continue,
|
||||
};
|
||||
if is_internal_name(&name) {
|
||||
if is_internal_name(&name) && !(show_internal && name == ".runestone") {
|
||||
continue;
|
||||
}
|
||||
let rel_path = match to_rel(&root, path) {
|
||||
@@ -596,7 +608,7 @@ pub fn workspace_write(
|
||||
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)?;
|
||||
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())
|
||||
}
|
||||
@@ -624,12 +636,13 @@ fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<(
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)?;
|
||||
.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())?;
|
||||
file.sync_all()?;
|
||||
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())?;
|
||||
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.
|
||||
@@ -640,7 +653,7 @@ fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<(
|
||||
));
|
||||
}
|
||||
}
|
||||
fs::rename(&temp, path)?;
|
||||
replace_saved_file(&temp, path, expected.is_none())?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
@@ -649,6 +662,79 @@ fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<(
|
||||
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::<Vec<_>>();
|
||||
let target_wide = wide(&target);
|
||||
let replacement_wide = wide(&replacement);
|
||||
let backup_wide = wide(&backup);
|
||||
// ReplaceFile preserves Windows file metadata. A backup allows recovery if
|
||||
// Windows moves the original but cannot publish its replacement.
|
||||
let replaced = unsafe { ReplaceFileW(
|
||||
target_wide.as_ptr(), replacement_wide.as_ptr(), backup_wide.as_ptr(),
|
||||
0, std::ptr::null(), std::ptr::null(),
|
||||
) };
|
||||
if replaced != 0 {
|
||||
let _ = fs::remove_file(&backup);
|
||||
return Ok(());
|
||||
}
|
||||
let reason = 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-")
|
||||
}
|
||||
@@ -694,9 +780,21 @@ fn create_text_if_absent(path: &Path, contents: &str) -> WsResult<()> {
|
||||
result
|
||||
}
|
||||
|
||||
fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Option<&str>) -> WsResult<PathBuf> {
|
||||
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<WorkspaceState>, from: String, to: String) -> WsResult<()> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, from: String, to: String, expected_root: Option<String>) -> 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"));
|
||||
@@ -765,7 +863,7 @@ pub fn workspace_read_data_url(window: tauri::Window, state: State<WorkspaceStat
|
||||
))
|
||||
}
|
||||
|
||||
fn copy_destination(path: &Path) -> PathBuf {
|
||||
fn copy_destination(path: &Path, number: u32) -> PathBuf {
|
||||
let parent = path.parent().unwrap_or(path);
|
||||
let stem = path
|
||||
.file_stem()
|
||||
@@ -775,33 +873,41 @@ fn copy_destination(path: &Path) -> PathBuf {
|
||||
.extension()
|
||||
.map(|e| format!(".{}", e.to_string_lossy()))
|
||||
.unwrap_or_default();
|
||||
let mut n = 1u32;
|
||||
loop {
|
||||
let name = if n == 1 {
|
||||
format!("{stem} copy{ext}")
|
||||
} else {
|
||||
format!("{stem} copy {n}{ext}")
|
||||
};
|
||||
let dest = parent.join(name);
|
||||
if !dest.exists() {
|
||||
return dest;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
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<()> {
|
||||
if from.is_dir() {
|
||||
fs::create_dir_all(to)?;
|
||||
for entry in fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
copy_tree(&entry.path(), &to.join(entry.file_name()))?;
|
||||
}
|
||||
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 {
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::copy(from, to)?;
|
||||
return Err(std::io::Error::other("Only regular files and folders can be copied."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -814,14 +920,37 @@ pub struct CopyResult {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn workspace_copy(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<CopyResult> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
pub fn workspace_copy(window: tauri::Window, state: State<WorkspaceState>, rel: String, parent: Option<String>, expected_root: Option<String>) -> WsResult<CopyResult> {
|
||||
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<CopyResult> {
|
||||
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)?;
|
||||
let dest = copy_destination(&from);
|
||||
if !is_inside(&root, dest.parent().unwrap_or(&dest)) {
|
||||
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"));
|
||||
}
|
||||
copy_tree(&from, &dest)?;
|
||||
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
|
||||
@@ -843,6 +972,28 @@ pub fn workspace_abs_path(window: tauri::Window, state: State<WorkspaceState>, r
|
||||
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) -> 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<WorkspaceState>, 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(all(unix, not(target_os = "macos")))]
|
||||
let mut command = std::process::Command::new("x-terminal-emulator");
|
||||
command.current_dir(folder).spawn().map_err(|e| err(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State<WorkspaceState>, rel: String) -> WsResult<()> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
@@ -976,6 +1127,22 @@ 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()));
|
||||
@@ -1130,6 +1297,101 @@ mod tests {
|
||||
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()));
|
||||
@@ -1189,15 +1451,153 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn copy_destination_appends_copy() {
|
||||
let dir = std::env::temp_dir().join(format!("rs-copy-{}", std::process::id()));
|
||||
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);
|
||||
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);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user