Update editor, workspace, Git services, appearance, and project guides

This commit is contained in:
Knotty Wyvern
2026-10-11 09:41:16 -07:00
parent a8b1defb9d
commit 909894b9c8
153 changed files with 7967 additions and 775 deletions
+42 -2
View File
@@ -37,11 +37,15 @@ const COMMANDS: &[&str] = &[
"removeBookmark",
"settings",
"clearData",
"webData",
"removeCookie",
"removeHistory",
"agentSnapshot",
];
#[derive(Default)]
pub struct BrowserState {
inner: Mutex<Option<Worker>>,
sessions: Mutex<HashMap<String, String>>,
}
#[derive(Default)]
struct WindowTabs {
@@ -347,7 +351,19 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64
Ok(())
}
impl BrowserState {
fn connect(&self, owner: &str) -> Result<String> {
let mut sessions = self.sessions.lock().map_err(fail)?;
Ok(sessions.entry(owner.to_string()).or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone())
}
fn require_session(&self, owner: &str, token: &str) -> Result<()> {
if self.sessions.lock().map_err(fail)?.get(owner).is_some_and(|saved| saved == token) {
Ok(())
} else {
Err("The browser session is unavailable in this window.".into())
}
}
pub fn close_window(&self, owner: &str) {
if let Ok(mut sessions) = self.sessions.lock() { sessions.remove(owner); }
if let Ok(mut guard) = self.inner.lock() {
let Some(worker) = guard.as_mut() else { return; };
let (closed, empty) = match worker.routing.lock() {
@@ -361,6 +377,7 @@ impl BrowserState {
}
}
pub fn close_all(&self) {
if let Ok(mut sessions) = self.sessions.lock() { sessions.clear(); }
if let Ok(mut guard) = self.inner.lock() {
if let Some(mut worker) = guard.take() {
let _ = worker.stop();
@@ -460,16 +477,25 @@ impl BrowserState {
}
}
#[tauri::command]
pub async fn browser_connect(state: State<'_, BrowserState>, window: tauri::Window) -> Result<String> {
state.connect(window.label())
}
#[tauri::command]
pub async fn browser_request(
app: AppHandle,
window: tauri::Window,
command: String,
args: Value,
session: Option<String>,
) -> Result<Value> {
let owner = window.label().to_string();
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
if let Some(token) = session {
app.state::<BrowserState>().require_session(&owner, &token)?;
} else {
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
}
tauri::async_runtime::spawn_blocking(move || {
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
@@ -487,6 +513,20 @@ pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window)
mod tests {
use super::*;
#[test]
fn builtin_sessions_are_scoped_to_a_window_and_revoked_on_close() {
let state = BrowserState::default();
assert!(state.require_session("main", "missing").is_err());
let token = state.connect("main").unwrap();
assert!(state.require_session("main", &token).is_ok());
assert!(state.require_session("other", &token).is_err());
state.close_window("main");
assert!(state.require_session("main", &token).is_err());
let next = state.connect("main").unwrap();
assert_ne!(next, token);
state.close_all();
assert!(state.require_session("main", &next).is_err());
}
#[test]
fn drag_transfer_requires_the_owner_token_and_rejects_replays() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
+840
View File
@@ -0,0 +1,840 @@
use crate::workspace::{current_root_path, WorkspaceState};
use serde::Serialize;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tauri::{State, Window};
const OUTPUT_LIMIT: usize = 2 * 1024 * 1024;
static GIT_LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GitChange {
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
original_path: Option<String>,
index: String,
worktree: String,
}
#[derive(Debug, Serialize)]
pub struct GitStatus {
available: bool,
repository: bool,
branch: Option<String>,
changes: Vec<GitChange>,
}
#[derive(Debug, Serialize)]
pub struct GitLineInfo {
commit: String,
author: String,
date: String,
summary: String,
}
fn read_output(mut stream: impl Read) -> Result<Vec<u8>, String> {
let mut result = Vec::new();
let mut buffer = [0; 8192];
let mut overflow = false;
loop {
let count = stream.read(&mut buffer).map_err(|e| e.to_string())?;
if count == 0 {
break;
}
if result.len() + count <= OUTPUT_LIMIT {
result.extend_from_slice(&buffer[..count]);
} else {
overflow = true;
}
}
if overflow {
Err(
"Git output exceeds the 2 MiB limit. Use Git outside RuneStone for this operation."
.into(),
)
} else {
Ok(result)
}
}
fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
let mut command = Command::new("git");
command
.current_dir(root)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for (key, _) in std::env::vars_os() {
if key
.to_string_lossy()
.to_ascii_uppercase()
.starts_with("GIT_")
{
command.env_remove(key);
}
}
command
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_OPTIONAL_LOCKS", "0")
.args([
"--no-pager",
"--literal-pathspecs",
"-c",
"core.fsmonitor=false",
])
.args(args);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
}
let mut child = command
.spawn()
.map_err(|e| format!("Could not start Git. Install Git and restart RuneStone. {e}"))?;
let stdout = child.stdout.take().ok_or("Git output is unavailable.")?;
let stderr = child.stderr.take().ok_or("Git errors are unavailable.")?;
let out = std::thread::spawn(move || read_output(stdout));
let err = std::thread::spawn(move || read_output(stderr));
let start = Instant::now();
let mut completed = None;
let status = loop {
if completed.is_none() {
completed = child.try_wait().map_err(|e| e.to_string())?;
}
if let Some(status) = completed {
if out.is_finished() && err.is_finished() {
break status;
}
}
if start.elapsed() > Duration::from_secs(30) {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// Git can start SSH and credential helpers that also hold its output pipes.
let _ = Command::new("taskkill")
.args(["/PID", &child.id().to_string(), "/T", "/F"])
.creation_flags(0x08000000)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
let _ = child.kill();
let _ = child.wait();
return Err(
"Git did not finish within 30 seconds. Refresh to check the repository state."
.into(),
);
}
std::thread::sleep(Duration::from_millis(15));
};
Ok(Output {
status,
stdout: out.join().map_err(|_| "Could not read Git output.")??,
stderr: err.join().map_err(|_| "Could not read Git errors.")??,
})
}
fn checked(root: &Path, args: &[&str]) -> Result<String, String> {
let output = run(root, args)?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
}
String::from_utf8(output.stdout)
.map_err(|_| "Git returned a filename that is not UTF-8.".into())
}
fn repository(root: &Path) -> Result<(), String> {
let top = checked(root, &["rev-parse", "--show-toplevel"])?;
let top = dunce::canonicalize(top.trim()).map_err(|e| e.to_string())?;
if top != root {
return Err("Open the repository root as your workspace to use Git.".into());
}
for argument in ["--absolute-git-dir", "--git-common-dir"] {
let git_dir = checked(root, &["rev-parse", argument])?;
let git_dir = dunce::canonicalize(root.join(git_dir.trim())).map_err(|e| e.to_string())?;
if !git_dir.starts_with(root) {
return Err(
"Git metadata must be inside the workspace. Linked worktrees are not supported."
.into(),
);
}
}
Ok(())
}
fn safe_path(root: &Path, value: &str) -> Result<(), String> {
if value.is_empty() || value.contains('\0') || value.contains('\\') || value.contains(':') {
return Err("Choose a relative Git file path inside the workspace.".into());
}
let path = Path::new(value);
if path
.components()
.any(|c| !matches!(c, Component::Normal(_)))
|| path
.components()
.any(|c| c.as_os_str().to_string_lossy().eq_ignore_ascii_case(".git"))
{
return Err("The Git path is outside the workspace or names Git metadata.".into());
}
let mut cursor = root.to_owned();
for part in path.components() {
cursor.push(part);
match std::fs::symlink_metadata(&cursor) {
Ok(_) => {
let real = dunce::canonicalize(&cursor).map_err(|e| e.to_string())?;
if !real.starts_with(root) {
return Err("The Git path points outside the workspace.".into());
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
Err(e) => return Err(e.to_string()),
}
}
Ok(())
}
fn parse_status(value: &str) -> Result<Vec<GitChange>, String> {
let mut records = value.split('\0').filter(|s| !s.is_empty());
let mut changes = Vec::new();
while let Some(record) = records.next() {
if record.len() < 4 || record.as_bytes()[2] != b' ' {
return Err("Git returned an invalid status record.".into());
}
let index = record.as_bytes()[0] as char;
let worktree = record.as_bytes()[1] as char;
let original_path = if matches!(index, 'R' | 'C') || matches!(worktree, 'R' | 'C') {
Some(
records
.next()
.ok_or("Git returned an incomplete rename.")?
.to_owned(),
)
} else {
None
};
changes.push(GitChange {
path: record[3..].to_owned(),
original_path,
index: index.to_string(),
worktree: worktree.to_string(),
});
}
Ok(changes)
}
fn status(root: &Path) -> Result<GitStatus, String> {
let empty = |available| GitStatus {
available,
repository: false,
branch: None,
changes: vec![],
};
if run(root, &["--version"]).is_err() {
return Ok(empty(false));
}
if !root.join(".git").exists() {
return Ok(empty(true));
}
repository(root)?;
let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).or_else(|_| {
checked(root, &["rev-parse", "--short", "HEAD"]).map(|id| format!("Detached {}", id.trim()))
})?;
let changes = parse_status(&checked(
root,
&["status", "--porcelain=v1", "-z", "--untracked-files=all"],
)?)?;
Ok(GitStatus {
available: true,
repository: true,
branch: Some(branch.trim().to_owned()),
changes,
})
}
fn diff(root: &Path, path: &str, staged: bool) -> Result<String, String> {
repository(root)?;
safe_path(root, path)?;
let untracked = !staged && checked(root, &["ls-files", "--error-unmatch", "--", path]).is_err();
if untracked {
let file = std::fs::File::open(root.join(path)).map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
file.take(512 * 1024 + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() > 512 * 1024 {
return Ok("This new file is too large to preview (512 KiB limit).".into());
}
if bytes.contains(&0) {
return Ok("Binary file. No text preview is available.".into());
}
let source = String::from_utf8(bytes).map_err(|_| "This file is not UTF-8 text.")?;
return Ok(format!(
"New file: {path}\n{}",
source
.lines()
.map(|line| format!("+{line}\n"))
.collect::<String>()
));
}
let change = status(root)?
.changes
.into_iter()
.find(|change| change.path == path);
let original = change.and_then(|change| change.original_path);
if let Some(original) = original.as_ref() {
safe_path(root, original)?;
}
let mut args = vec!["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
if staged {
args.push("--cached");
}
args.extend(["--", path]);
if let Some(original) = original.as_deref() {
args.push(original);
}
checked(root, &args)
}
fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String> {
repository(root)?;
if paths.is_empty() || paths.len() > 10000 {
return Err("Choose between 1 and 10,000 files.".into());
}
for path in paths {
safe_path(root, path)?;
}
let has_head = !stage && run(root, &["rev-parse", "--verify", "HEAD"])?
.status
.success();
let mut args = if stage {
vec!["add", "--"]
} else if has_head {
vec!["restore", "--staged", "--"]
} else {
vec!["rm", "--cached", "--ignore-unmatch", "--"]
};
args.extend(paths.iter().map(String::as_str));
checked(root, &args)?;
Ok(())
}
fn commit(root: &Path, message: &str) -> Result<(), String> {
repository(root)?;
if message.trim().is_empty() || message.len() > 65536 || message.contains('\0') {
return Err("Enter a commit message between 1 and 65,536 bytes.".into());
}
checked(root, &["commit", "-m", message])?;
Ok(())
}
fn upstream(root: &Path) -> Result<(String, String), String> {
let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"])
.map_err(|_| "Select a branch outside RuneStone before you push or pull.")?;
let branch = branch.trim();
let missing = "This branch has no remote upstream. Set its upstream with Git outside RuneStone, then refresh.";
let remote = checked(
root,
&["config", "--get", &format!("branch.{branch}.remote")],
)
.map_err(|_| missing)?;
let merge = checked(
root,
&["config", "--get-all", &format!("branch.{branch}.merge")],
)
.map_err(|_| missing)?;
let remote = remote.trim();
let merge = merge.trim();
if remote.is_empty()
|| remote.starts_with('-')
|| remote == "."
|| remote.contains('\n')
|| !merge.starts_with("refs/heads/")
|| merge.contains('\n')
{
return Err("Set one remote branch as the upstream with Git outside RuneStone.".into());
}
checked(root, &["check-ref-format", merge])?;
checked(root, &["remote", "get-url", "--", remote])?;
Ok((remote.into(), merge.into()))
}
fn synchronize(root: &Path, push: bool) -> Result<(), String> {
repository(root)?;
let (remote, reference) = upstream(root)?;
if !push && !status(root)?.changes.is_empty() {
return Err("Commit your changes or stash them with Git before you pull. Pull requires a clean working tree.".into());
}
// Explicit arguments prevent repository defaults from forcing a push or rebasing a pull.
let mirror = format!("remote.{remote}.mirror=false");
let target = format!("HEAD:{reference}");
let mut args = vec![
"-c",
"credential.interactive=false",
"-c",
"core.sshCommand=ssh -oBatchMode=yes -oConnectTimeout=15",
];
if push {
args.extend([
"-c",
&mirror,
"push",
"--porcelain",
"--no-follow-tags",
"--recurse-submodules=no",
"--",
&remote,
&target,
]);
} else {
args.extend([
"pull",
"--ff-only",
"--no-rebase",
"--no-autostash",
"--no-recurse-submodules",
"--",
&remote,
&reference,
]);
}
checked(root, &args).map_err(|error| format!("{} failed. {error}\nIf Git needs credentials, sign in with Git outside RuneStone, then retry.", if push { "Push" } else { "Pull" }))?;
Ok(())
}
#[derive(Debug, Serialize)]
pub struct GitGraphCommit {
id: String,
parents: Vec<String>,
refs: Vec<String>,
summary: String,
author: String,
date: String,
}
#[derive(Debug, Serialize)]
pub struct GitGraph {
commits: Vec<GitGraphCommit>,
}
fn graph(root: &Path) -> Result<GitGraph, String> {
repository(root)?;
let has_head = run(root, &["rev-parse", "--verify", "HEAD"])?
.status
.success();
if !has_head
&& checked(root, &["rev-list", "--all", "--max-count=1"])?
.trim()
.is_empty()
{
return Ok(GitGraph { commits: Vec::new() });
}
let mut args = vec![
"log",
"--all",
"--max-count=100",
"--topo-order",
"--no-color",
"--decorate=short",
"--date=short",
"-z",
"--format=%H%x00%P%x00%D%x00%s%x00%an%x00%ad",
];
if has_head {
args.push("HEAD");
}
args.push("--");
let output = checked(root, &args)?;
let fields: Vec<&str> = output.split('\0').collect();
let mut commits = Vec::new();
for record in fields.chunks(6) {
if record.len() == 1 && record[0].trim().is_empty() { continue; }
if record.len() != 6 { return Err("Git returned incomplete commit history.".into()); }
commits.push(GitGraphCommit {
id: record[0].trim().to_owned(),
parents: record[1].split_whitespace().map(str::to_owned).collect(),
refs: record[2].split(", ").filter(|value| !value.is_empty()).map(str::to_owned).collect(),
summary: record[3].to_owned(),
author: record[4].to_owned(),
date: record[5].to_owned(),
});
}
Ok(GitGraph { commits })
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GitCommitFile {
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
original_path: Option<String>,
status: String,
}
#[derive(Debug, Serialize)]
pub struct GitCommitDetails {
id: String,
parents: Vec<String>,
author: String,
date: String,
message: String,
files: Vec<GitCommitFile>,
}
fn commit_id(value: &str) -> Result<(), String> {
if ![40, 64].contains(&value.len()) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err("Select a commit from the Git graph.".into());
}
Ok(())
}
fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>, String> {
let mut records = value.split('\0').filter(|field| !field.is_empty());
let mut files = Vec::new();
while let Some(status) = records.next() {
let first = records.next().ok_or("Git returned an incomplete file change.")?;
let renamed = status.starts_with('R') || status.starts_with('C');
let path = if renamed { records.next().ok_or("Git returned an incomplete rename.")? } else { first };
files.push(GitCommitFile { path: path.into(), original_path: renamed.then(|| first.into()), status: status.into() });
}
Ok(files)
}
fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails, String> {
commit_id(id)?;
repository(root)?;
let metadata = checked(root, &["show", "--no-patch", "--no-show-signature", "--format=%H%x00%P%x00%an%x00%aI%x00%B", id, "--"])?;
let fields: Vec<_> = metadata.splitn(5, '\0').collect();
if fields.len() != 5 { return Err("Git returned incomplete commit details.".into()); }
let parents: Vec<String> = fields[1].split_whitespace().map(str::to_owned).collect();
let mut args = vec!["diff-tree", "--root", "--no-commit-id", "--name-status", "-r", "-z", "-M"];
// Merge details use the first parent, as the graph's main line does.
if let Some(parent) = parents.first() { args.push(parent); }
args.extend([id, "--"]);
let files = parse_commit_files(&checked(root, &args)?)?;
Ok(GitCommitDetails { id: fields[0].into(), parents, author: fields[2].into(), date: fields[3].into(), message: fields[4].trim_end().into(), files })
}
fn commit_diff(root: &Path, id: &str, path: &str) -> Result<String, String> {
let details = commit_details(root, id)?;
safe_path(root, path)?;
let file = details.files.iter().find(|file| file.path == path).ok_or("This file is not part of the selected commit.")?;
let mut args = if let Some(parent) = details.parents.first() {
vec!["diff", "--no-ext-diff", "--no-textconv", "--no-color", "-M", parent, id]
} else {
vec!["show", "--format=", "--root", "--no-ext-diff", "--no-textconv", "--no-color", "-M", id]
};
args.extend(["--", path]);
if let Some(original) = &file.original_path { safe_path(root, original)?; args.push(original); }
checked(root, &args)
}
fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>, String> {
repository(root)?;
safe_path(root, path)?;
if line == 0 {
return Err("The Git line number must be at least 1.".into());
}
let range = format!("{line},{line}");
let output = run(
root,
&["blame", "--line-porcelain", "-L", &range, "--", path],
)?;
if !output.status.success() {
return Ok(None);
}
let text = String::from_utf8_lossy(&output.stdout);
let commit = text.split_whitespace().next().unwrap_or("");
if commit.is_empty() || commit.chars().all(|c| c == '0') {
return Ok(None);
}
let field = |key: &str| {
text.lines()
.find_map(|line| line.strip_prefix(key))
.unwrap_or("")
.to_owned()
};
Ok(Some(GitLineInfo {
commit: commit.into(),
author: field("author "),
date: field("author-time "),
summary: field("summary "),
}))
}
fn root(state: &WorkspaceState, window: &Window) -> Result<PathBuf, String> {
dunce::canonicalize(current_root_path(state, window.label()).map_err(|e| e.to_string())?)
.map_err(|e| e.to_string())
}
async fn task<T: Send + 'static>(
action: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
tauri::async_runtime::spawn_blocking(move || {
let _guard = GIT_LOCK
.lock()
.map_err(|_| "The Git service lock is unavailable.")?;
action()
})
.await
.map_err(|e| e.to_string())?
}
#[tauri::command]
pub async fn git_status(
window: Window,
state: State<'_, WorkspaceState>,
) -> Result<GitStatus, String> {
let root = root(&state, &window)?;
task(move || status(&root)).await
}
#[tauri::command]
pub async fn git_diff(
window: Window,
state: State<'_, WorkspaceState>,
path: String,
staged: bool,
) -> Result<String, String> {
let root = root(&state, &window)?;
task(move || diff(&root, &path, staged)).await
}
#[tauri::command]
pub async fn git_stage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, true)).await
}
#[tauri::command]
pub async fn git_unstage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, false)).await
}
#[tauri::command]
pub async fn git_commit(
window: Window,
state: State<'_, WorkspaceState>,
message: String,
) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || commit(&root, &message)).await
}
#[tauri::command]
pub async fn git_blame(
window: Window,
state: State<'_, WorkspaceState>,
path: String,
line: u32,
) -> Result<Option<GitLineInfo>, String> {
let root = root(&state, &window)?;
task(move || blame(&root, &path, line)).await
}
#[tauri::command]
pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || synchronize(&root, true)).await
}
#[tauri::command]
pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || synchronize(&root, false)).await
}
#[tauri::command]
pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result<GitGraph, String> {
let root = root(&state, &window)?;
task(move || graph(&root)).await
}
#[tauri::command]
pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result<GitCommitDetails, String> {
let root = root(&state, &window)?;
task(move || commit_details(&root, &commit)).await
}
#[tauri::command]
pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result<String, String> {
let root = root(&state, &window)?;
task(move || commit_diff(&root, &commit, &path)).await
}
#[cfg(test)]
#[path = "git_sync_tests.rs"]
mod sync_tests;
#[cfg(test)]
mod tests {
use super::*;
struct Repo(PathBuf);
impl Repo {
fn new() -> Self {
let path =
std::env::temp_dir().join(format!("runestone-git-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&path).unwrap();
let root = dunce::canonicalize(path).unwrap();
checked(&root, &["init", "--initial-branch=main"]).unwrap();
checked(&root, &["config", "user.name", "RuneStone Test"]).unwrap();
checked(&root, &["config", "user.email", "[email protected]"]).unwrap();
Self(root)
}
fn write(&self, path: &str, text: &str) {
std::fs::write(self.0.join(path), text).unwrap();
}
}
impl Drop for Repo {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn commit_details_cover_root_rename_deletion_and_full_messages() {
let repo = Repo::new();
repo.write("before 名.txt", "retained content\n");
change_index(&repo.0, &["before 名.txt".into()], true).unwrap();
commit(&repo.0, "Initial title\n\nFull commit description.").unwrap();
let first = checked(&repo.0, &["rev-parse", "HEAD"]).unwrap().trim().to_owned();
let details = commit_details(&repo.0, &first).unwrap();
assert!(details.parents.is_empty());
assert_eq!(details.files[0].status, "A");
assert_eq!(details.files[0].path, "before 名.txt");
assert!(details.message.contains("Full commit description."));
assert!(commit_diff(&repo.0, &first, "before 名.txt").unwrap().contains("+retained content"));
checked(&repo.0, &["mv", "before 名.txt", "after 名.txt"]).unwrap();
commit(&repo.0, "Rename file").unwrap();
let renamed = checked(&repo.0, &["rev-parse", "HEAD"]).unwrap().trim().to_owned();
let details = commit_details(&repo.0, &renamed).unwrap();
assert_eq!(details.files[0].original_path.as_deref(), Some("before 名.txt"));
assert!(commit_diff(&repo.0, &renamed, "after 名.txt").unwrap().contains("similarity index 100%"));
checked(&repo.0, &["rm", "after 名.txt"]).unwrap();
commit(&repo.0, "Delete file").unwrap();
let deleted = checked(&repo.0, &["rev-parse", "HEAD"]).unwrap().trim().to_owned();
assert_eq!(commit_details(&repo.0, &deleted).unwrap().files[0].status, "D");
assert!(commit_diff(&repo.0, &deleted, "after 名.txt").unwrap().contains("-retained content"));
for id in ["HEAD", "--all", "../outside", "abc123", "g123456789012345678901234567890123456789"] { assert!(commit_details(&repo.0, id).is_err()); }
assert!(commit_diff(&repo.0, &first, "missing.txt").is_err());
assert!(commit_diff(&repo.0, &first, "../escape").is_err());
}
#[test]
fn unborn_stage_unstage_commit_diff_and_blame() {
let repo = Repo::new();
repo.write("notes with spaces.md", "first\n");
let initial = status(&repo.0).unwrap();
assert_eq!(initial.branch.as_deref(), Some("main"));
assert_eq!(initial.changes[0].index, "?");
assert!(diff(&repo.0, "notes with spaces.md", false)
.unwrap()
.contains("+first"));
let paths = vec!["notes with spaces.md".to_owned()];
change_index(&repo.0, &paths, true).unwrap();
assert_eq!(status(&repo.0).unwrap().changes[0].index, "A");
change_index(&repo.0, &paths, false).unwrap();
assert!(repo.0.join(&paths[0]).exists());
change_index(&repo.0, &paths, true).unwrap();
commit(&repo.0, "First notes").unwrap();
assert!(status(&repo.0).unwrap().changes.is_empty());
assert_eq!(
blame(&repo.0, &paths[0], 1).unwrap().unwrap().author,
"RuneStone Test"
);
repo.write(&paths[0], "second\n");
assert!(diff(&repo.0, &paths[0], false).unwrap().contains("+second"));
change_index(&repo.0, &paths, true).unwrap();
assert!(diff(&repo.0, &paths[0], true).unwrap().contains("+second"));
change_index(&repo.0, &paths, false).unwrap();
assert_eq!(
std::fs::read_to_string(repo.0.join(&paths[0])).unwrap(),
"second\n"
);
}
#[test]
fn rename_and_deleted_files_keep_correct_index_paths() {
let repo = Repo::new();
repo.write("before.txt", "retained content\n");
change_index(&repo.0, &["before.txt".into()], true).unwrap();
commit(&repo.0, "Initial").unwrap();
std::fs::rename(repo.0.join("before.txt"), repo.0.join("after.txt")).unwrap();
change_index(&repo.0, &["before.txt".into(), "after.txt".into()], true).unwrap();
let changes = status(&repo.0).unwrap().changes;
assert_eq!(changes[0].path, "after.txt");
assert_eq!(changes[0].original_path.as_deref(), Some("before.txt"));
assert!(diff(&repo.0, "after.txt", true)
.unwrap()
.contains("rename from before.txt"));
change_index(&repo.0, &["before.txt".into(), "after.txt".into()], false).unwrap();
assert!(repo.0.join("after.txt").exists());
assert!(!repo.0.join("before.txt").exists());
}
#[test]
fn rejects_unsafe_paths_and_parent_repository() {
let repo = Repo::new();
for path in [
"../escape",
"/escape",
"C:/escape",
".git/config",
"nested/../../escape",
"nested\\escape",
":(glob)*",
] {
assert!(safe_path(&repo.0, path).is_err(), "accepted {path}");
}
std::fs::create_dir(repo.0.join("child")).unwrap();
assert!(repository(&repo.0.join("child")).is_err());
assert!(!status(&repo.0.join("child")).unwrap().repository);
repo.write("--all", "literal\n");
change_index(&repo.0, &["--all".into()], true).unwrap();
assert_eq!(status(&repo.0).unwrap().changes[0].path, "--all");
assert!(commit(&repo.0, " ").is_err());
}
#[test]
fn parser_handles_unicode_and_newline_names() {
let changes = parse_status("R new\n名.txt\0old name.txt\0?? new file.txt\0").unwrap();
assert_eq!(changes[0].path, "new\n名.txt");
assert_eq!(changes[0].original_path.as_deref(), Some("old name.txt"));
assert_eq!(changes.len(), 2);
}
#[test]
fn configured_external_worktree_is_rejected() {
let repo = Repo::new();
let outside = Repo::new();
checked(
&repo.0,
&["config", "core.worktree", outside.0.to_str().unwrap()],
)
.unwrap();
assert!(repository(&repo.0).is_err());
assert!(change_index(&repo.0, &["outside.txt".into()], true).is_err());
}
#[test]
fn binary_untracked_preview_does_not_decode_bytes() {
let repo = Repo::new();
std::fs::write(repo.0.join("image.bin"), [0, 255, 1]).unwrap();
assert_eq!(
diff(&repo.0, "image.bin", false).unwrap(),
"Binary file. No text preview is available."
);
}
#[test]
fn commit_keeps_repository_hook_checks() {
let repo = Repo::new();
repo.write("notes.txt", "notes\n");
change_index(&repo.0, &["notes.txt".into()], true).unwrap();
let hook = repo.0.join(".git/hooks/pre-commit");
std::fs::write(
&hook,
"#!/bin/sh\necho 'Test hook rejected the commit' >&2\nexit 1\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert!(commit(&repo.0, "Must fail")
.unwrap_err()
.contains("Test hook rejected"));
assert_eq!(status(&repo.0).unwrap().changes[0].index, "A");
}
}
+179
View File
@@ -0,0 +1,179 @@
use super::*;
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root =
std::env::temp_dir().join(format!("runestone-git-sync-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&root).unwrap();
let fixture = Self(dunce::canonicalize(root).unwrap());
fixture.git(
".",
&["init", "--bare", "--initial-branch=main", "remote.git"],
);
fixture.git(".", &["clone", "remote.git", "local"]);
for directory in ["local"] {
fixture.git(directory, &["config", "user.name", "RuneStone Test"]);
fixture.git(directory, &["config", "user.email", "[email protected]"]);
}
fixture
}
fn path(&self, directory: &str) -> PathBuf {
self.0.join(directory)
}
fn git(&self, directory: &str, args: &[&str]) -> String {
checked(&self.path(directory), args).unwrap()
}
fn commit(&self, directory: &str, name: &str, contents: &str) {
std::fs::write(self.path(directory).join(name), contents).unwrap();
self.git(directory, &["add", "--", name]);
self.git(
directory,
&[
"-c",
"user.name=RuneStone Test",
"-c",
"[email protected]",
"commit",
"-m",
contents,
],
);
}
fn seed(&self) {
self.commit("local", "first.txt", "Initial commit");
synchronize(&self.path("local"), true).unwrap();
self.git(".", &["clone", "remote.git", "peer"]);
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn push_and_fast_forward_pull_use_only_the_upstream_branch() {
let fixture = Fixture::new();
fixture.seed();
fixture.git("local", &["branch", "unpublished"]);
fixture.git("local", &["tag", "unpublished-tag"]);
fixture.git("local", &["config", "push.default", "matching"]);
fixture.git("local", &["config", "remote.origin.mirror", "true"]);
fixture.commit("local", "second.txt", "Local change");
synchronize(&fixture.path("local"), true).unwrap();
let refs = fixture.git("remote.git", &["for-each-ref", "--format=%(refname)"]);
assert_eq!(refs.trim(), "refs/heads/main");
fixture.git("peer", &["pull", "--ff-only"]);
fixture.commit("peer", "peer.txt", "Peer change");
fixture.git("peer", &["push"]);
fixture.git("local", &["config", "pull.rebase", "true"]);
synchronize(&fixture.path("local"), false).unwrap();
assert_eq!(
fixture.git("local", &["rev-parse", "HEAD"]),
fixture.git("peer", &["rev-parse", "HEAD"])
);
assert_eq!(
std::fs::read_to_string(fixture.path("local").join("peer.txt")).unwrap(),
"Peer change"
);
}
#[test]
fn divergent_push_and_pull_preserve_local_and_remote_commits() {
let fixture = Fixture::new();
fixture.seed();
fixture.commit("peer", "peer.txt", "Peer change");
fixture.git("peer", &["push"]);
fixture.commit("local", "local.txt", "Local change");
fixture.git(
"local",
&[
"config",
"remote.origin.push",
"+refs/heads/main:refs/heads/main",
],
);
fixture.git("local", &["config", "pull.rebase", "true"]);
fixture.git("local", &["config", "pull.ff", "false"]);
let local = fixture.git("local", &["rev-parse", "HEAD"]);
let remote = fixture.git("remote.git", &["rev-parse", "HEAD"]);
assert!(synchronize(&fixture.path("local"), true).is_err());
assert!(synchronize(&fixture.path("local"), false).is_err());
assert_eq!(fixture.git("local", &["rev-parse", "HEAD"]), local);
assert_eq!(fixture.git("remote.git", &["rev-parse", "HEAD"]), remote);
assert!(!fixture.path("local/.git/MERGE_HEAD").exists());
assert!(!fixture.path("local/.git/rebase-merge").exists());
}
#[test]
fn dirty_missing_upstream_detached_and_remote_errors_are_clear() {
let fixture = Fixture::new();
fixture.seed();
std::fs::write(fixture.path("local/first.txt"), "Unsaved change").unwrap();
fixture.git("local", &["config", "merge.autoStash", "true"]);
assert!(synchronize(&fixture.path("local"), false)
.unwrap_err()
.contains("clean working tree"));
assert_eq!(
std::fs::read_to_string(fixture.path("local/first.txt")).unwrap(),
"Unsaved change"
);
fixture.git("local", &["branch", "--unset-upstream"]);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.contains("no remote upstream"));
fixture.git("local", &["checkout", "--detach"]);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.contains("Select a branch"));
fixture.git("local", &["checkout", "main"]);
fixture.git("local", &["branch", "--set-upstream-to=origin/main"]);
fixture.git(
"local",
&["remote", "set-url", "origin", "../missing-remote.git"],
);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.contains("Push failed"));
}
#[test]
fn graph_shows_branch_forks_merges_tags_and_detached_history() {
let fixture = Fixture::new();
assert!(graph(&fixture.path("local")).unwrap().commits.is_empty());
fixture.seed();
fixture.git("local", &["checkout", "-b", "feature"]);
fixture.commit("local", "feature.txt", "Feature commit");
fixture.git("local", &["checkout", "main"]);
fixture.commit("local", "main.txt", "Main commit");
fixture.git(
"local",
&["merge", "--no-ff", "feature", "-m", "Merge feature"],
);
fixture.git("local", &["tag", "test-tag"]);
let history = graph(&fixture.path("local")).unwrap();
for expected in [
"HEAD -> main",
"feature",
"test-tag",
"Merge feature",
"RuneStone Test",
] {
assert!(format!("{history:?}").contains(expected), "Missing {expected}: {history:?}");
}
let merge = history.commits.iter().find(|commit| commit.summary == "Merge feature").unwrap();
assert_eq!(merge.parents.len(), 2);
let details = commit_details(&fixture.path("local"), &merge.id).unwrap();
assert_eq!(details.files.len(), 1);
assert_eq!(details.files[0].path, "feature.txt");
assert!(commit_diff(&fixture.path("local"), &merge.id, "feature.txt").unwrap().contains("+Feature commit"));
for parent in &merge.parents {
assert!(history.commits.iter().any(|commit| &commit.id == parent));
}
fixture.git("local", &["checkout", "--detach"]);
fixture.commit("local", "detached.txt", "Detached commit");
assert!(graph(&fixture.path("local"))
.unwrap()
.commits.iter().any(|commit| commit.summary == "Detached commit"));
}
+20
View File
@@ -3,8 +3,10 @@ mod plugins;
mod plugin_sources;
mod workspace;
mod browser;
mod git;
mod completion;
mod settings;
mod spelling;
use pty::PtyState;
use tauri::Manager;
@@ -22,11 +24,26 @@ pub fn run() {
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.invoke_handler(tauri::generate_handler![
spelling::spelling_menu_install,
spelling::spelling_menu_select,
spelling::spelling_menu_uninstall,
settings::settings_open_window,
completion::completion_request,
completion::completion_cancel,
browser::browser_request,
browser::browser_connect,
browser::browser_stop,
git::git_status,
git::git_diff,
git::git_stage,
git::git_unstage,
git::git_commit,
git::git_blame,
git::git_push,
git::git_pull,
git::git_graph,
git::git_commit_diff,
git::git_commit_details,
workspace::workspace_open,
workspace::workspace_open_window,
workspace::workspace_last_path,
@@ -45,6 +62,8 @@ pub fn run() {
workspace::workspace_copy,
workspace::workspace_abs_path,
workspace::workspace_reveal,
workspace::workspace_open_terminal,
workspace::workspace_open_default,
workspace::workspace_search,
plugins::plugins_snapshot,
plugins::plugins_choose,
@@ -73,6 +92,7 @@ pub fn run() {
.run(|app, event| {
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
settings::close_owned_window(app, label);
spelling::close_window(app, label);
app.state::<PtyState>().close_window(label);
app.state::<completion::CompletionState>().close_window(label);
app.state::<browser::BrowserState>().close_window(label);
+1 -1
View File
@@ -91,7 +91,7 @@ pub async fn settings_open_window(
.title(title)
.inner_size(920.0, 650.0)
.min_inner_size(540.0, 420.0)
.decorations(true)
.decorations(false)
.resizable(true)
.visible(false)
.disable_drag_drop_handler()
+216
View File
@@ -0,0 +1,216 @@
//! Display WebView2 spelling commands through the shared frontend menu.
//! Keep COM event arguments on the WebView thread until selection or cancellation.
#[cfg(any(windows, test))]
#[derive(Debug, PartialEq)]
enum Selection { Stale, Cancel, Native, Command(i32) }
#[cfg(any(windows, test))]
fn requires_native_label(kind: i32, label: &str) -> bool {
kind != 3 && label.trim().is_empty()
}
#[cfg(any(windows, test))]
fn selection(current: &str, request: &str, command: Option<i32>, fallback: bool, enabled: &std::collections::HashSet<i32>) -> Selection {
if current != request { return Selection::Stale; }
if fallback { return Selection::Native; }
command.filter(|id| enabled.contains(id)).map(Selection::Command).unwrap_or(Selection::Cancel)
}
#[cfg(windows)]
mod native {
use std::{cell::RefCell, collections::{HashMap, HashSet}};
use serde::Serialize;
use tauri::{Emitter, Manager};
use webview2_com::{take_pwstr, ContextMenuRequestedEventHandler, Microsoft::Web::WebView2::Win32::*};
use windows::core::{Interface, PWSTR, BOOL};
#[derive(Clone, Serialize)]
pub struct Item {
id: i32, name: String, label: String, shortcut: String, kind: i32,
enabled: bool, checked: bool, children: Vec<Item>,
}
#[derive(Clone, Serialize)]
struct Menu { request: String, items: Vec<Item> }
fn requires_native(items: &[Item]) -> bool {
items.iter().any(|item| super::requires_native_label(item.kind, &item.label) || requires_native(&item.children))
}
struct Pending {
request: String, args: ICoreWebView2ContextMenuRequestedEventArgs,
deferral: ICoreWebView2Deferral, commands: HashSet<i32>,
}
impl Drop for Pending {
fn drop(&mut self) { unsafe { let _ = self.deferral.Complete(); } }
}
thread_local! {
static PENDING: RefCell<HashMap<String, Pending>> = RefCell::new(HashMap::new());
static INSTALLED: RefCell<HashMap<String, (ICoreWebView2_11, i64)>> = RefCell::new(HashMap::new());
}
unsafe fn text(read: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
let mut value = PWSTR::null();
let result = read(&mut value);
let text = take_pwstr(value);
result.map(|_| text)
}
unsafe fn items(collection: ICoreWebView2ContextMenuItemCollection, commands: &mut HashSet<i32>, parent_enabled: bool) -> windows::core::Result<Vec<Item>> {
let mut count = 0;
collection.Count(&mut count)?;
let mut result = Vec::new();
for index in 0..count {
let item = collection.GetValueAtIndex(index)?;
let (mut id, mut kind, mut enabled, mut checked) = (0, COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_COMMAND, BOOL(0), BOOL(0));
item.CommandId(&mut id)?;
item.Kind(&mut kind)?;
item.IsEnabled(&mut enabled)?;
item.IsChecked(&mut checked)?;
let enabled = parent_enabled && enabled.as_bool();
let children = if kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { items(item.Children()?, commands, enabled)? } else { Vec::new() };
if enabled && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SEPARATOR && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { commands.insert(id); }
result.push(Item {
id, name: text(|value| item.Name(value))?, label: text(|value| item.Label(value))?,
shortcut: text(|value| item.ShortcutKeyDescription(value))?, kind: kind.0,
enabled, checked: checked.as_bool(), children,
});
}
Ok(result)
}
pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> Result<(), String> {
let label = window.label().to_owned();
if INSTALLED.with(|installed| installed.borrow().contains_key(&label)) { return Ok(()); }
let app = window.app_handle().clone();
let owner = label.clone();
unsafe {
let core: ICoreWebView2_11 = controller.CoreWebView2().map_err(|e| e.to_string())?.cast().map_err(|e| e.to_string())?;
let handler = ContextMenuRequestedEventHandler::create(Box::new(move |_, args| {
let Some(args) = args else { return Ok(()); };
let mut editable = BOOL(0);
args.ContextMenuTarget()?.IsEditable(&mut editable)?;
if !editable.as_bool() { return Ok(()); }
let mut commands = HashSet::new();
let entries = items(args.MenuItems()?, &mut commands, true)?;
// WebView2 can omit spelling labels and reject their command IDs.
// Its native menu still owns the suggestion text and correction.
if requires_native(&entries) { return Ok(()); }
let Some(window) = app.get_webview_window(&owner) else { return Ok(()); };
let pending = Pending { request: uuid::Uuid::new_v4().to_string(), args: args.clone(), deferral: args.GetDeferral()?, commands };
let menu = Menu { request: pending.request.clone(), items: entries };
args.SetHandled(true)?;
let previous = PENDING.with(|state| state.borrow_mut().insert(owner.clone(), pending));
drop(previous);
if window.emit("spelling-menu", menu).is_err() {
// Restore the native menu if the frontend cannot receive the request.
let _ = args.SetHandled(false);
let pending = PENDING.with(|state| state.borrow_mut().remove(&owner));
drop(pending);
}
Ok(())
}));
let mut token = 0;
core.add_ContextMenuRequested(&handler, &mut token).map_err(|e| e.to_string())?;
INSTALLED.with(|installed| { installed.borrow_mut().insert(label, (core, token)); });
}
Ok(())
}
pub fn select(label: &str, request: &str, command: Option<i32>, fallback: bool) {
let result = PENDING.with(|state| {
let mut state = state.borrow_mut();
let pending = state.get(label)?;
let choice = super::selection(&pending.request, request, command, fallback, &pending.commands);
if choice == super::Selection::Stale { return None; }
Some((state.remove(label)?, choice))
});
if let Some((pending, choice)) = result {
unsafe {
match choice {
super::Selection::Command(id) => { let _ = pending.args.SetSelectedCommandId(id); }
super::Selection::Native => { let _ = pending.args.SetHandled(false); }
_ => {}
}
}
// Drop completes the deferral after the selected command is set.
}
}
pub fn close(label: &str) {
let pending = PENDING.with(|state| state.borrow_mut().remove(label));
drop(pending);
if let Some((core, token)) = INSTALLED.with(|installed| installed.borrow_mut().remove(label)) {
unsafe { let _ = core.remove_ContextMenuRequested(token); }
}
}
}
#[tauri::command]
pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<(), String> {
#[cfg(windows)] {
let (send, receive) = std::sync::mpsc::channel();
let owner = window.clone();
window.with_webview(move |webview| { let _ = send.send(native::install(&owner, webview.controller())); }).map_err(|e| e.to_string())?;
tauri::async_runtime::spawn_blocking(move || receive.recv().map_err(|e| e.to_string())?).await.map_err(|e| e.to_string())?
}
#[cfg(not(windows))] { let _ = window; Ok(()) }
}
#[tauri::command]
pub fn spelling_menu_select(window: tauri::WebviewWindow, request: String, command: Option<i32>, fallback: Option<bool>) -> Result<(), String> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false))).map_err(|e| e.to_string())?;
}
#[cfg(not(windows))] { let _ = (window, request, command, fallback); }
Ok(())
}
pub fn close_window(app: &tauri::AppHandle, label: &str) {
#[cfg(windows)] {
let label = label.to_owned();
let _ = app.run_on_main_thread(move || native::close(&label));
}
#[cfg(not(windows))] { let _ = (app, label); }
}
#[tauri::command]
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), String> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::close(&label)).map_err(|e| e.to_string())?;
}
#[cfg(not(windows))] { let _ = window; }
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn stale_requests_cannot_select_or_cancel_a_new_menu() {
for command in [None, Some(42)] {
assert_eq!(selection("new", "old", command, false, &HashSet::from([42])), Selection::Stale);
assert_eq!(selection("new", "old", command, true, &HashSet::from([42])), Selection::Stale);
}
}
#[test]
fn only_enabled_commands_from_the_current_request_can_run() {
let enabled = HashSet::from([42]);
assert_eq!(selection("a", "a", Some(42), false, &enabled), Selection::Command(42));
assert_eq!(selection("a", "a", Some(43), false, &enabled), Selection::Cancel);
assert_eq!(selection("a", "a", None, false, &enabled), Selection::Cancel);
}
#[test]
fn unmatched_editable_target_keeps_the_native_menu() {
assert_eq!(selection("a", "a", None, true, &HashSet::new()), Selection::Native);
}
#[test]
fn blank_commands_keep_native_suggestions_but_separators_do_not() {
assert!(requires_native_label(0, ""));
assert!(requires_native_label(0, " "));
assert!(requires_native_label(4, ""));
assert!(!requires_native_label(3, ""));
assert!(!requires_native_label(0, "received"));
}
}
+445 -45
View File
@@ -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();
}
}