git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
//! Isolated git repositories for unit tests.
//!
//! ```ignore
//! use crate::testutil::TempRepo;
//! let repo = TempRepo::new(3).with_remote();      // 3 commits on main, pushed to a bare origin
//! repo.write("src/x.rs", "fn main() {}\n");       // create/overwrite a file (dirs created)
//! repo.git(&["add", "."]);                        // setup helper; panics with stderr on failure
//! let state = repo.run(crate::repo_state::load);  // every git:: runner inside targets the repo
//! ```
//!
//! cargo runs tests on parallel threads of ONE process, so never call `set_current_dir` or
//! `std::env::set_var` in a test. `run` installs the repo directory and an isolated environment
//! (HOME/USERPROFILE -> temp home, GIT_CONFIG_NOSYSTEM=1, GIT_CONFIG_GLOBAL -> empty temp file)
//! through `git::with_ctx`, which is thread-local. Code that spawns its own threads must carry
//! the context with `git::ctx_snapshot`/`ctx_restore` (as `ui::git_job` does).
//!
//! Commit `i` (1-based) writes `f<i>.txt` containing "<i>\n" with subject "commit <i>" and a
//! fixed author/committer date, so hashes are stable. Everything is deleted on drop.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};

static COUNTER: AtomicUsize = AtomicUsize::new(0);

pub struct TempRepo {
    root: PathBuf,
    repo: PathBuf,
}

impl TempRepo {
    /// A fresh repo on branch `main` with `commits` commits (0 = unborn branch).
    pub fn new(commits: usize) -> TempRepo {
        let repo = Self::bare_dirs();
        repo.git(&["init", "-q", "-b", "main"]);
        repo.git(&["config", "user.name", "Test User"]);
        repo.git(&["config", "user.email", "test@example.com"]);
        repo.git(&["config", "commit.gpgsign", "false"]);
        repo.git(&["config", "core.autocrlf", "false"]);
        for i in 1..=commits {
            repo.write(&format!("f{i}.txt"), &format!("{i}\n"));
            repo.git(&["add", "."]);
            let date = format!("{} +0000", 1_704_110_400 + i * 60);
            let output = repo
                .command(&repo.repo, &["commit", "-q", "-m", &format!("commit {i}")])
                .env("GIT_AUTHOR_DATE", &date)
                .env("GIT_COMMITTER_DATE", &date)
                .output()
                .expect("git not runnable");
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
        repo
    }

    /// An isolated empty directory that is NOT a repository (for "outside a repo" tests).
    pub fn outside() -> TempRepo {
        Self::bare_dirs()
    }

    fn bare_dirs() -> TempRepo {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.subsec_nanos());
        // The long, real path: on Windows temp_dir() can be an 8.3 short path (`BAZILS~1`), which
        // git never reports, so GIT_CEILING_DIRECTORIES would not stop the search for a parent
        // repository.
        let temp = real_path(&std::env::temp_dir());
        let root = temp.join(format!("gct-ut-{}-{n}-{nanos}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let repo = root.join("repo");
        std::fs::create_dir_all(root.join("home")).unwrap();
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::write(root.join("gitconfig"), "").unwrap();
        TempRepo { root, repo }
    }

    /// Adds a bare remote `origin` next to the repo and pushes `main` with upstream (if any
    /// commits exist).
    pub fn with_remote(self) -> TempRepo {
        let remote = self.root.join("remote.git");
        let output = self
            .command(
                &self.root,
                &["init", "-q", "--bare", "-b", "main", "remote.git"],
            )
            .output()
            .expect("git not runnable");
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        self.git(&["remote", "add", "origin", &remote.to_string_lossy()]);
        if !self.git(&["rev-list", "-n1", "--all"]).is_empty() {
            self.git(&["push", "-q", "-u", "origin", "main"]);
        }
        self
    }

    /// The working tree directory.
    pub fn path(&self) -> &Path {
        &self.repo
    }

    /// The bare remote created by `with_remote`.
    pub fn remote_path(&self) -> PathBuf {
        self.root.join("remote.git")
    }

    /// Writes `content` to `rel` inside the working tree, creating parent directories.
    pub fn write(&self, rel: &str, content: &str) {
        let path = self.repo.join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }

    /// Runs git in the repo (isolated) and returns trimmed stdout; panics with stderr on failure.
    pub fn git(&self, args: &[&str]) -> String {
        let output = self
            .command(&self.repo, args)
            .output()
            .expect("git not runnable");
        assert!(
            output.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout)
            .trim_end()
            .to_string()
    }

    /// Runs `f` with every `git::` runner targeting this repo with the isolated environment.
    pub fn run<T>(&self, f: impl FnOnce() -> T) -> T {
        crate::git::with_ctx(&self.repo, self.env(), f)
    }

    /// The isolation environment applied by `run` and `git`.
    pub fn env(&self) -> Vec<(String, String)> {
        let home = self.root.join("home").to_string_lossy().into_owned();
        vec![
            ("HOME".into(), home.clone()),
            ("USERPROFILE".into(), home.clone()),
            ("XDG_CONFIG_HOME".into(), format!("{home}/.config")),
            ("GIT_CONFIG_NOSYSTEM".into(), "1".into()),
            (
                "GIT_CONFIG_GLOBAL".into(),
                self.root.join("gitconfig").to_string_lossy().into_owned(),
            ),
            (
                "GIT_CEILING_DIRECTORIES".into(),
                self.root.to_string_lossy().into_owned(),
            ),
            ("GIT_TERMINAL_PROMPT".into(), "0".into()),
        ]
    }

    fn command(&self, dir: &Path, args: &[&str]) -> Command {
        let mut command = Command::new("git");
        command.args(args).current_dir(dir).envs(self.env());
        command
    }
}

/// `dir` canonicalized, without the `\\?\` verbatim prefix Windows adds (git and the
/// environment variables use plain paths). Falls back to `dir` when it cannot be resolved.
fn real_path(dir: &Path) -> PathBuf {
    match std::fs::canonicalize(dir) {
        Ok(path) => strip_verbatim(path),
        Err(_) => dir.to_path_buf(),
    }
}

fn strip_verbatim(path: PathBuf) -> PathBuf {
    let text = path.to_string_lossy();
    if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
        PathBuf::from(format!(r"\\{rest}"))
    } else if let Some(rest) = text.strip_prefix(r"\\?\") {
        PathBuf::from(rest)
    } else {
        path
    }
}

impl Drop for TempRepo {
    fn drop(&mut self) {
        for attempt in 0..5 {
            if std::fs::remove_dir_all(&self.root).is_ok() || !self.root.exists() {
                return;
            }
            // Git marks object files read-only, which blocks deletion on Windows; a git process
            // or virus scanner may also still hold a file for a moment.
            make_writable(&self.root);
            std::thread::sleep(std::time::Duration::from_millis(20 * (attempt + 1)));
        }
        if std::fs::remove_dir_all(&self.root).is_err() && self.root.exists() {
            eprintln!("testutil: could not delete {}", self.root.display());
        }
    }
}

fn make_writable(dir: &Path) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            make_writable(&path);
        } else if let Ok(meta) = entry.metadata() {
            let mut perms = meta.permissions();
            #[allow(clippy::permissions_set_readonly_false)]
            perms.set_readonly(false);
            let _ = std::fs::set_permissions(&path, perms);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn temp_repo_basics() {
        let root;
        {
            let repo = TempRepo::new(3).with_remote();
            root = repo.root.clone();
            assert_eq!(repo.git(&["rev-list", "--count", "HEAD"]), "3");
            assert_eq!(repo.git(&["log", "-1", "--format=%s"]), "commit 3");
            assert_eq!(
                repo.git(&["rev-parse", "--abbrev-ref", "@{u}"]),
                "origin/main"
            );
            assert!(repo.remote_path().is_dir());
            let count = repo.run(|| crate::git::run(&["rev-list", "--count", "HEAD"]).unwrap());
            assert_eq!(count, "3");
            // Same content and dates give the same hash in every TempRepo.
            let again = TempRepo::new(3);
            assert_eq!(
                again.git(&["rev-parse", "HEAD"]),
                repo.git(&["rev-parse", "HEAD"])
            );
        }
        assert!(!root.exists());
        let empty = TempRepo::new(0);
        assert!(empty.git(&["rev-list", "-n1", "--all"]).is_empty());
    }

    #[test]
    fn outside_is_never_inside_a_repo() {
        let outside = TempRepo::outside();
        let root = outside.root.to_string_lossy().into_owned();
        assert!(!root.starts_with(r"\\?\"), "{root}");
        assert_eq!(
            outside.root,
            real_path(&outside.root),
            "already the long, real path"
        );
        assert!(!outside.run(crate::repo_state::in_repo));
    }

    #[test]
    fn verbatim_prefix_is_stripped() {
        let cases = [
            (r"\\?\C:\Users\x", r"C:\Users\x"),
            (r"\\?\UNC\server\share\d", r"\\server\share\d"),
            ("/tmp/plain", "/tmp/plain"),
        ];
        for (input, expected) in cases {
            assert_eq!(
                strip_verbatim(PathBuf::from(input)),
                PathBuf::from(expected)
            );
        }
    }
}