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
+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");
}
}