Add a shared error type and shared file helpers to the Rust host

Replace the three error styles with one Error type and one Result alias in
error.rs. The error crosses IPC as the same plain string as before. The
message text does not change.

Move the shared file mechanics to fsutil.rs. These are the reserved-name
check, the link and junction check, the limited reads, and the atomic
writes. Each module keeps its own path rules, limits, and messages. The
plugin settings writer now flushes its file to disk before the rename.

Remove the current_root_path and list_entries wrappers and an unused mime
value. Use named windows-sys constants for the process, file, drive, and
error codes.

Add a test that compares the command lists in lib.rs, build.rs, and the
capability files. The settings capability must be a subset of the full list.

In Cargo.toml, set the author, keep only the rlib crate type, and remove
the unused thiserror dependency. Remove panic = "abort" from the release
profile. A panic on a worker thread then stops only that thread. It does
not stop the editor with unsaved buffers.
This commit is contained in:
Knotty Wyvern
2026-10-27 22:41:11 -07:00
parent 69f90df571
commit bd46f3a189
18 changed files with 1103 additions and 882 deletions
+49 -53
View File
@@ -1,4 +1,5 @@
use crate::workspace::{current_root_path, WorkspaceState};
use crate::error::Result;
use crate::workspace::{current_root, WorkspaceState};
use serde::Serialize;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
@@ -34,12 +35,12 @@ pub struct GitLineInfo {
summary: String,
}
fn read_output(mut stream: impl Read) -> Result<Vec<u8>, String> {
fn read_output(mut stream: impl Read) -> Result<Vec<u8>> {
let mut result = Vec::new();
let mut buffer = [0; 8192];
let mut overflow = false;
loop {
let count = stream.read(&mut buffer).map_err(|e| e.to_string())?;
let count = stream.read(&mut buffer)?;
if count == 0 {
break;
}
@@ -59,7 +60,7 @@ fn read_output(mut stream: impl Read) -> Result<Vec<u8>, String> {
}
}
fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
fn run(root: &Path, args: &[&str]) -> Result<Output> {
let mut command = Command::new("git");
command
.current_dir(root)
@@ -88,7 +89,7 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
}
let mut child = command
.spawn()
@@ -101,7 +102,7 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
let mut completed = None;
let status = loop {
if completed.is_none() {
completed = child.try_wait().map_err(|e| e.to_string())?;
completed = child.try_wait()?;
}
if let Some(status) = completed {
if out.is_finished() && err.is_finished() {
@@ -115,7 +116,7 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
// Git can start SSH and credential helpers that also hold its output pipes.
let _ = Command::new("taskkill")
.args(["/PID", &child.id().to_string(), "/T", "/F"])
.creation_flags(0x08000000)
.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
@@ -136,24 +137,24 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
})
}
fn checked(root: &Path, args: &[&str]) -> Result<String, String> {
fn checked(root: &Path, args: &[&str]) -> Result<String> {
let output = run(root, args)?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
return Err(String::from_utf8_lossy(&output.stderr).trim().into());
}
String::from_utf8(output.stdout)
.map_err(|_| "Git returned a filename that is not UTF-8.".into())
}
fn repository(root: &Path) -> Result<(), String> {
fn repository(root: &Path) -> Result<()> {
let top = checked(root, &["rev-parse", "--show-toplevel"])?;
let top = dunce::canonicalize(top.trim()).map_err(|e| e.to_string())?;
let top = dunce::canonicalize(top.trim())?;
if top != root {
return Err("Open the repository root as your workspace to use Git.".into());
}
for argument in ["--absolute-git-dir", "--git-common-dir"] {
let git_dir = checked(root, &["rev-parse", argument])?;
let git_dir = dunce::canonicalize(root.join(git_dir.trim())).map_err(|e| e.to_string())?;
let git_dir = dunce::canonicalize(root.join(git_dir.trim()))?;
if !git_dir.starts_with(root) {
return Err(
"Git metadata must be inside the workspace. Linked worktrees are not supported."
@@ -164,7 +165,7 @@ fn repository(root: &Path) -> Result<(), String> {
Ok(())
}
fn safe_path(root: &Path, value: &str) -> Result<(), String> {
fn safe_path(root: &Path, value: &str) -> Result<()> {
if value.is_empty() || value.contains('\0') || value.contains('\\') || value.contains(':') {
return Err("Choose a relative Git file path inside the workspace.".into());
}
@@ -183,19 +184,19 @@ fn safe_path(root: &Path, value: &str) -> Result<(), String> {
cursor.push(part);
match std::fs::symlink_metadata(&cursor) {
Ok(_) => {
let real = dunce::canonicalize(&cursor).map_err(|e| e.to_string())?;
let real = dunce::canonicalize(&cursor)?;
if !real.starts_with(root) {
return Err("The Git path points outside the workspace.".into());
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
Err(e) => return Err(e.to_string()),
Err(e) => return Err(e.into()),
}
}
Ok(())
}
fn parse_status(value: &str) -> Result<Vec<GitChange>, String> {
fn parse_status(value: &str) -> Result<Vec<GitChange>> {
let mut records = value.split('\0').filter(|s| !s.is_empty());
let mut changes = Vec::new();
while let Some(record) = records.next() {
@@ -224,7 +225,7 @@ fn parse_status(value: &str) -> Result<Vec<GitChange>, String> {
Ok(changes)
}
fn status(root: &Path) -> Result<GitStatus, String> {
fn status(root: &Path) -> Result<GitStatus> {
let empty = |available| GitStatus {
available,
repository: false,
@@ -253,19 +254,15 @@ fn status(root: &Path) -> Result<GitStatus, String> {
})
}
fn diff(root: &Path, path: &str, staged: bool) -> Result<String, String> {
fn diff(root: &Path, path: &str, staged: bool) -> Result<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 {
let file = std::fs::File::open(root.join(path))?;
let Some(bytes) = crate::fsutil::read_to_limit(file, 512 * 1024)? else {
return Ok("This new file is too large to preview (512 KiB limit).".into());
}
};
if bytes.contains(&0) {
return Ok("Binary file. No text preview is available.".into());
}
@@ -297,7 +294,7 @@ fn diff(root: &Path, path: &str, staged: bool) -> Result<String, String> {
checked(root, &args)
}
fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String> {
fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<()> {
repository(root)?;
if paths.is_empty() || paths.len() > 10000 {
return Err("Choose between 1 and 10,000 files.".into());
@@ -320,7 +317,7 @@ fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String
Ok(())
}
fn commit(root: &Path, message: &str) -> Result<(), String> {
fn commit(root: &Path, message: &str) -> Result<()> {
repository(root)?;
if message.trim().is_empty() || message.len() > 65536 || message.contains('\0') {
return Err("Enter a commit message between 1 and 65,536 bytes.".into());
@@ -329,7 +326,7 @@ fn commit(root: &Path, message: &str) -> Result<(), String> {
Ok(())
}
fn upstream(root: &Path) -> Result<(String, String), String> {
fn upstream(root: &Path) -> Result<(String, String)> {
let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"])
.map_err(|_| "Select a branch outside RuneStone before you push or pull.")?;
let branch = branch.trim();
@@ -360,7 +357,7 @@ fn upstream(root: &Path) -> Result<(String, String), String> {
Ok((remote.into(), merge.into()))
}
fn synchronize(root: &Path, push: bool) -> Result<(), String> {
fn synchronize(root: &Path, push: bool) -> Result<()> {
repository(root)?;
let (remote, reference) = upstream(root)?;
if !push && !status(root)?.changes.is_empty() {
@@ -418,7 +415,7 @@ pub struct GitGraph {
commits: Vec<GitGraphCommit>,
}
fn graph(root: &Path) -> Result<GitGraph, String> {
fn graph(root: &Path) -> Result<GitGraph> {
repository(root)?;
let has_head = run(root, &["rev-parse", "--verify", "HEAD"])?
.status
@@ -480,13 +477,13 @@ pub struct GitCommitDetails {
message: String,
files: Vec<GitCommitFile>,
}
fn commit_id(value: &str) -> Result<(), String> {
fn commit_id(value: &str) -> Result<()> {
if ![40, 64].contains(&value.len()) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err("Select a commit from the Git graph.".into());
}
Ok(())
}
fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>, String> {
fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>> {
let mut records = value.split('\0').filter(|field| !field.is_empty());
let mut files = Vec::new();
while let Some(status) = records.next() {
@@ -497,7 +494,7 @@ fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>, String> {
}
Ok(files)
}
fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails, String> {
fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails> {
commit_id(id)?;
repository(root)?;
let metadata = checked(root, &["show", "--no-patch", "--no-show-signature", "--format=%H%x00%P%x00%an%x00%aI%x00%B", id, "--"])?;
@@ -511,7 +508,7 @@ fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails, String> {
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> {
fn commit_diff(root: &Path, id: &str, path: &str) -> Result<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.")?;
@@ -525,7 +522,7 @@ fn commit_diff(root: &Path, id: &str, path: &str) -> Result<String, String> {
checked(root, &args)
}
fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>, String> {
fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>> {
repository(root)?;
safe_path(root, path)?;
if line == 0 {
@@ -558,27 +555,25 @@ fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>, Stri
}))
}
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())
fn root(state: &WorkspaceState, window: &Window) -> Result<PathBuf> {
Ok(dunce::canonicalize(current_root(state, window.label())?)?)
}
async fn task<T: Send + 'static>(
action: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
action: impl FnOnce() -> Result<T> + Send + 'static,
) -> Result<T> {
tauri::async_runtime::spawn_blocking(move || {
let _guard = GIT_LOCK
.lock()
.map_err(|_| "The Git service lock is unavailable.")?;
action()
})
.await
.map_err(|e| e.to_string())?
.await?
}
#[tauri::command]
pub async fn git_status(
window: Window,
state: State<'_, WorkspaceState>,
) -> Result<GitStatus, String> {
) -> Result<GitStatus> {
let root = root(&state, &window)?;
task(move || status(&root)).await
}
@@ -588,7 +583,7 @@ pub async fn git_diff(
state: State<'_, WorkspaceState>,
path: String,
staged: bool,
) -> Result<String, String> {
) -> Result<String> {
let root = root(&state, &window)?;
task(move || diff(&root, &path, staged)).await
}
@@ -597,7 +592,7 @@ pub async fn git_stage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
) -> Result<()> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, true)).await
}
@@ -606,7 +601,7 @@ pub async fn git_unstage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
) -> Result<()> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, false)).await
}
@@ -615,7 +610,7 @@ pub async fn git_commit(
window: Window,
state: State<'_, WorkspaceState>,
message: String,
) -> Result<(), String> {
) -> Result<()> {
let root = root(&state, &window)?;
task(move || commit(&root, &message)).await
}
@@ -625,37 +620,37 @@ pub async fn git_blame(
state: State<'_, WorkspaceState>,
path: String,
line: u32,
) -> Result<Option<GitLineInfo>, String> {
) -> Result<Option<GitLineInfo>> {
let root = root(&state, &window)?;
task(move || blame(&root, &path, line)).await
}
#[tauri::command]
pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<()> {
let root = root(&state, &window)?;
task(move || synchronize(&root, true)).await
}
#[tauri::command]
pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<()> {
let root = root(&state, &window)?;
task(move || synchronize(&root, false)).await
}
#[tauri::command]
pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result<GitGraph, String> {
pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result<GitGraph> {
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> {
pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result<GitCommitDetails> {
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> {
pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result<String> {
let root = root(&state, &window)?;
task(move || commit_diff(&root, &commit, &path)).await
}
@@ -834,6 +829,7 @@ mod tests {
}
assert!(commit(&repo.0, "Must fail")
.unwrap_err()
.to_string()
.contains("Test hook rejected"));
assert_eq!(status(&repo.0).unwrap().changes[0].index, "A");
}