use crate::error::Result; use crate::workspace::{current_root, WorkspaceState}; use serde::Serialize; use std::collections::HashMap; use std::ffi::OsStr; use std::io::Read; use std::path::{Component, Path, PathBuf}; use std::process::{Child, Command, Output, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc, Mutex, OnceLock}; use std::time::{Duration, Instant, SystemTime}; use tauri::{State, Window}; const OUTPUT_LIMIT: usize = 2 * 1024 * 1024; const TIMEOUT: Duration = Duration::from_secs(30); /// RuneStone's SSH settings. Git uses them only when the user has not chosen an SSH command. const DEFAULT_SSH_COMMAND: &str = "core.sshCommand=ssh -oBatchMode=yes -oConnectTimeout=15"; /// Environment variables that choose the SSH client for Git. The Git service keeps them. const SSH_VARIABLES: [&str; 3] = ["GIT_SSH", "GIT_SSH_COMMAND", "GIT_SSH_VARIANT"]; #[cfg(test)] thread_local! { /// The number of Git processes that this test thread started. static RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GitChange { path: String, #[serde(skip_serializing_if = "Option::is_none")] original_path: Option, index: String, worktree: String, } #[derive(Debug, Serialize)] pub struct GitStatus { available: bool, repository: bool, branch: Option, changes: Vec, } #[derive(Debug, Serialize)] pub struct GitLineInfo { commit: String, author: String, date: String, summary: String, } fn read_output(mut stream: impl Read) -> Result> { let mut result = Vec::new(); let mut buffer = [0; 8192]; let mut overflow = false; loop { let count = stream.read(&mut buffer)?; 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) } } /// The Git program. Find it on `PATH` once, not at each start. fn program() -> &'static Path { static PROGRAM: OnceLock = OnceLock::new(); PROGRAM.get_or_init(|| { crate::terminal_platform::find_executable(if cfg!(windows) { "git.exe" } else { "git" }) .unwrap_or_else(|| PathBuf::from("git")) }) } /// True for an inherited environment variable that the Git service removes. /// /// A `GIT_*` variable in RuneStone's own environment can point Git at a different /// repository, index, or object store (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`), /// or add configuration (`GIT_CONFIG_*`). A shell or a hook that started RuneStone can /// leave such variables set. The Git service removes them, so that each command uses /// only the workspace repository and the checks in `repository`. /// The SSH variables only select the user's SSH client, so the service keeps them. fn removed_variable(key: &OsStr) -> bool { let key = key.to_string_lossy().to_ascii_uppercase(); key.starts_with("GIT_") && !SSH_VARIABLES.contains(&key.as_str()) } /// Stop a Git process that did not finish in time, with its helpers. fn stop(child: &mut Child) { #[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(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW) .stdout(Stdio::null()) .stderr(Stdio::null()) .status(); } let _ = child.kill(); let _ = child.wait(); } fn timed_out(child: &mut Child) -> crate::error::Error { stop(child); "Git did not finish within 30 seconds. Refresh to check the repository state.".into() } fn run(root: &Path, args: &[&str]) -> Result { #[cfg(test)] RUNS.with(|runs| runs.set(runs.get() + 1)); let mut command = Command::new(program()); command .current_dir(root) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); for (key, _) in std::env::vars_os() { if removed_variable(&key) { 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(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW); } let mut child = command .spawn() .map_err(|e| format!("Could not start Git. Install Git and restart RuneStone. {e}"))?; GIT_AVAILABLE.store(true, Ordering::Relaxed); let deadline = Instant::now() + TIMEOUT; let stdout = child.stdout.take().ok_or("Git output is unavailable.")?; let stderr = child.stderr.take().ok_or("Git errors are unavailable.")?; // Two readers empty both pipes, so that Git never stops on a full pipe. let (send, receive) = mpsc::channel(); let send_errors = send.clone(); std::thread::spawn(move || send.send((true, read_output(stdout)))); std::thread::spawn(move || send_errors.send((false, read_output(stderr)))); let (mut out, mut err) = (None, None); while out.is_none() || err.is_none() { match receive.recv_timeout(deadline.saturating_duration_since(Instant::now())) { Ok((true, result)) => out = Some(result), Ok((false, result)) => err = Some(result), Err(mpsc::RecvTimeoutError::Timeout) => return Err(timed_out(&mut child)), Err(mpsc::RecvTimeoutError::Disconnected) => { stop(&mut child); return Err("Could not read Git output.".into()); } } } // Git closes its pipes when it exits, so the process ends at once or very soon after. let status = loop { if let Some(status) = child.try_wait()? { break status; } if Instant::now() >= deadline { return Err(timed_out(&mut child)); } std::thread::sleep(Duration::from_millis(1)); }; Ok(Output { status, stdout: out.ok_or("Could not read Git output.")??, stderr: err.ok_or("Could not read Git errors.")??, }) } /// True after one Git process started. A failed start is checked again on the next status. static GIT_AVAILABLE: AtomicBool = AtomicBool::new(false); fn git_available(root: &Path) -> bool { GIT_AVAILABLE.load(Ordering::Relaxed) || run(root, &["--version"]).is_ok() } fn checked(root: &Path, args: &[&str]) -> Result { let output = run(root, args)?; if !output.status.success() { 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()) } /// The state of the files that decide where a repository's work tree and metadata are. /// The stamp changes when `.git` is removed or becomes a file (a linked worktree), and when /// the repository configuration (`core.worktree`) or `commondir` changes. /// Ordinary Git writes change the `.git` folder's time, so the stamp does not use it. type Stamp = Vec)>>; fn stamp(root: &Path) -> Stamp { let git = root.join(".git"); let metadata = |path: &Path| std::fs::symlink_metadata(path).ok(); let mut stamp = vec![metadata(&git).map(|metadata| (metadata.is_dir(), 0, None))]; for path in [git.join("config"), git.join("commondir")] { stamp.push(metadata(&path).map(|metadata| (metadata.is_dir(), metadata.len(), metadata.modified().ok()))); } stamp } /// Roots that passed the repository check, with the stamp at the time of the check. static REPOSITORIES: Mutex>> = Mutex::new(None); fn repository(root: &Path) -> Result<()> { let before = stamp(root); let cached = REPOSITORIES .lock() .ok() .and_then(|cache| cache.as_ref()?.get(root).cloned()); if cached.as_ref() == Some(&before) { return Ok(()); } check_repository(root)?; if let Ok(mut cache) = REPOSITORIES.lock() { cache.get_or_insert_with(HashMap::new).insert(root.to_owned(), before); } Ok(()) } fn check_repository(root: &Path) -> Result<()> { if root.to_string_lossy().contains('\n') { return Err("Git cannot use a workspace path that contains a line break.".into()); } let output = checked( root, &["rev-parse", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"], )?; let lines: Vec<&str> = output.lines().collect(); let [top, git_dir, common_dir] = lines[..] else { return Err("Git returned an invalid repository location.".into()); }; let top = dunce::canonicalize(top.trim())?; if top != root { return Err("Open the repository root as your workspace to use Git.".into()); } for git_dir in [git_dir, common_dir] { 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." .into(), ); } } Ok(()) } /// The lock for one repository root. Commands in other workspaces do not wait for it. fn root_lock(root: &Path) -> Result>> { static LOCKS: Mutex>>>> = Mutex::new(None); let mut locks = LOCKS.lock().map_err(|_| "The Git service lock is unavailable.")?; let locks = locks.get_or_insert_with(HashMap::new); // Forget the locks that no command holds or waits for. locks.retain(|_, lock| Arc::strong_count(lock) > 1); Ok(locks.entry(root.to_owned()).or_default().clone()) } /// The `-c` arguments that set RuneStone's SSH command, or none when the user chose an SSH client. /// `variable` reads one environment variable. fn ssh_arguments(root: &Path, variable: impl Fn(&str) -> Option) -> Vec<&'static str> { let environment = ["GIT_SSH", "GIT_SSH_COMMAND"] .into_iter() .any(|name| variable(name).is_some_and(|value| !value.is_empty())); // Git reads `core.sshCommand` from every configuration scope, also the repository. let configured = environment || run(root, &["config", "--get", "core.sshCommand"]).is_ok_and(|output| output.status.success()); if configured { Vec::new() } else { vec!["-c", DEFAULT_SSH_COMMAND] } } 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()); } 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)?; 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.into()), } } Ok(()) } fn parse_status(value: &str) -> Result> { 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) } /// The changed files. The caller checks the repository first. fn changes(root: &Path) -> Result> { parse_status(&checked( root, &["status", "--porcelain=v1", "-z", "--untracked-files=all"], )?) } fn status(root: &Path) -> Result { let empty = |available| GitStatus { available, repository: false, branch: None, changes: vec![], }; if !git_available(root) { 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 = changes(root)?; Ok(GitStatus { available: true, repository: true, branch: Some(branch.trim().to_owned()), changes, }) } fn diff(root: &Path, path: &str, staged: bool) -> Result { 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))?; 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()); } 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::() )); } let change = changes(root)? .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<()> { 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<()> { 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)> { 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<()> { repository(root)?; let (remote, reference) = upstream(root)?; if !push && !changes(root)?.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"]; // Keep the user's SSH client, for example Windows OpenSSH with its agent, or PuTTY plink. args.extend(ssh_arguments(root, |name| std::env::var_os(name))); 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, refs: Vec, summary: String, author: String, date: String, } #[derive(Debug, Serialize)] pub struct GitGraph { commits: Vec, } fn graph(root: &Path) -> Result { 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, status: String, } #[derive(Debug, Serialize)] pub struct GitCommitDetails { id: String, parents: Vec, author: String, date: String, message: String, files: Vec, } 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> { 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 { 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 = 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 { 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> { 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 { Ok(dunce::canonicalize(current_root(state, window.label())?)?) } /// Run a Git action on a blocking worker. Actions on the same root run one at a time. async fn task( root: PathBuf, action: impl FnOnce(&Path) -> Result + Send + 'static, ) -> Result { tauri::async_runtime::spawn_blocking(move || { let lock = root_lock(&root)?; let _guard = lock .lock() .map_err(|_| "The Git service lock is unavailable.")?; action(&root) }) .await? } #[tauri::command] pub async fn git_status( window: Window, state: State<'_, WorkspaceState>, ) -> Result { let root = root(&state, &window)?; task(root, status).await } #[tauri::command] pub async fn git_diff( window: Window, state: State<'_, WorkspaceState>, path: String, staged: bool, ) -> Result { let root = root(&state, &window)?; task(root, move |root| diff(root, &path, staged)).await } #[tauri::command] pub async fn git_stage( window: Window, state: State<'_, WorkspaceState>, paths: Vec, ) -> Result<()> { let root = root(&state, &window)?; task(root, move |root| change_index(root, &paths, true)).await } #[tauri::command] pub async fn git_unstage( window: Window, state: State<'_, WorkspaceState>, paths: Vec, ) -> Result<()> { let root = root(&state, &window)?; task(root, move |root| change_index(root, &paths, false)).await } #[tauri::command] pub async fn git_commit( window: Window, state: State<'_, WorkspaceState>, message: String, ) -> Result<()> { let root = root(&state, &window)?; task(root, move |root| commit(root, &message)).await } #[tauri::command] pub async fn git_blame( window: Window, state: State<'_, WorkspaceState>, path: String, line: u32, ) -> Result> { let root = root(&state, &window)?; task(root, move |root| blame(root, &path, line)).await } #[tauri::command] pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<()> { let root = root(&state, &window)?; task(root, move |root| synchronize(root, true)).await } #[tauri::command] pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<()> { let root = root(&state, &window)?; task(root, move |root| synchronize(root, false)).await } #[tauri::command] pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result { let root = root(&state, &window)?; task(root, graph).await } #[tauri::command] pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result { let root = root(&state, &window)?; task(root, move |root| commit_details(root, &commit)).await } #[tauri::command] pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result { let root = root(&state, &window)?; task(root, move |root| 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", "test@example.invalid"]).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() .to_string() .contains("Test hook rejected")); assert_eq!(status(&repo.0).unwrap().changes[0].index, "A"); } #[test] fn user_ssh_settings_are_kept_and_other_git_variables_are_removed() { for name in ["GIT_SSH", "GIT_SSH_COMMAND", "GIT_SSH_VARIANT", "git_ssh_command"] { assert!(!removed_variable(OsStr::new(name)), "removed {name}"); } for name in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "git_dir"] { assert!(removed_variable(OsStr::new(name)), "kept {name}"); } assert!(!removed_variable(OsStr::new("SSH_AUTH_SOCK"))); let repo = Repo::new(); let none = |_: &str| None; let plink = |name: &str| (name == "GIT_SSH").then(|| "C:/PuTTY/plink.exe".into()); let command = |name: &str| (name == "GIT_SSH_COMMAND").then(|| "C:/Windows/System32/OpenSSH/ssh.exe".into()); let empty = |name: &str| (name == "GIT_SSH_COMMAND").then(std::ffi::OsString::new); assert!(ssh_arguments(&repo.0, plink).is_empty()); assert!(ssh_arguments(&repo.0, command).is_empty()); // Another user scope can set core.sshCommand on a developer computer. let user_scope = ["--global", "--system"].iter().any(|scope| { run(&repo.0, &["config", scope, "--get", "core.sshCommand"]).is_ok_and(|output| output.status.success()) }); if !user_scope { assert_eq!(ssh_arguments(&repo.0, none), vec!["-c", DEFAULT_SSH_COMMAND]); assert_eq!(ssh_arguments(&repo.0, empty), vec!["-c", DEFAULT_SSH_COMMAND]); } checked(&repo.0, &["config", "core.sshCommand", "C:/Windows/System32/OpenSSH/ssh.exe"]).unwrap(); assert!(ssh_arguments(&repo.0, none).is_empty()); } #[test] fn repository_check_is_cached_until_git_metadata_changes() { let repo = Repo::new(); let outside = Repo::new(); repo.write("notes.txt", "notes\n"); let runs = || RUNS.with(std::cell::Cell::get); status(&repo.0).unwrap(); let start = runs(); let first = status(&repo.0).unwrap(); // One process reads the branch and one reads the changes. assert_eq!(runs() - start, 2); assert_eq!(first.branch.as_deref(), Some("main")); assert_eq!(first.changes[0].path, "notes.txt"); let start = runs(); assert!(diff(&repo.0, "notes.txt", false).unwrap().contains("+notes")); // One process checks whether Git tracks the file. assert_eq!(runs() - start, 1); change_index(&repo.0, &["notes.txt".into()], true).unwrap(); let start = runs(); assert!(diff(&repo.0, "notes.txt", true).unwrap().contains("+notes")); // One process reads the changes for rename paths and one makes the diff. assert_eq!(runs() - start, 2); // A changed configuration starts the full check again. checked(&repo.0, &["config", "core.worktree", outside.0.to_str().unwrap()]).unwrap(); assert!(repository(&repo.0).is_err()); assert!(status(&repo.0).is_err()); checked(&repo.0, &["config", "--unset", "core.worktree"]).unwrap(); repository(&repo.0).unwrap(); // A removed repository is not a repository from the cache. std::fs::remove_dir_all(repo.0.join(".git")).unwrap(); assert!(repository(&repo.0).is_err()); assert!(!status(&repo.0).unwrap().repository); } #[test] fn each_root_has_its_own_lock() { let first = Repo::new(); let second = Repo::new(); let lock = root_lock(&first.0).unwrap(); let _guard = lock.lock().unwrap(); assert!(Arc::ptr_eq(&lock, &root_lock(&first.0).unwrap())); let other = root_lock(&second.0).unwrap(); assert!(!Arc::ptr_eq(&lock, &other)); assert!(other.try_lock().is_ok(), "A command in one root must not wait for another root."); assert!(lock.try_lock().is_err()); } #[test] fn nonzero_exit_and_large_output_keep_their_results() { let repo = Repo::new(); let output = run(&repo.0, &["rev-parse", "--verify", "HEAD"]).unwrap(); assert!(!output.status.success()); assert!(!output.stderr.is_empty()); repo.write("large.txt", &"line of text\n".repeat(200_000)); assert!(checked(&repo.0, &["hash-object", "large.txt"]).unwrap().trim().len() >= 40); change_index(&repo.0, &["large.txt".into()], true).unwrap(); // The staged diff holds about 2.8 MiB, which exceeds the output limit. assert!(diff(&repo.0, "large.txt", true).unwrap_err().to_string().contains("2 MiB")); } }