//! Where a Review Loop round starts and ends: a full commit id (commit mode) or //! a tree id from a snapshot of the working tree (snapshot mode), and the diff //! between any two of them. A snapshot never touches the real index, `HEAD` or //! the working tree: it adds everything to a copy of the index and writes a tree //! from that copy, the same technique as `snapshotTree` in `changes.mjs`. use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicU64, Ordering}; use crate::loop_tools; /// A point in the project's history a round can be measured from. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Boundary { /// A full commit id. Commit(String), /// A tree id written from a snapshot of the working tree. Tree(String), } impl Boundary { /// The object id, whichever kind it is. pub fn id(&self) -> &str { match self { Boundary::Commit(id) | Boundary::Tree(id) => id, } } fn peel(&self) -> String { match self { Boundary::Commit(id) => format!("{id}^{{commit}}"), Boundary::Tree(id) => format!("{id}^{{tree}}"), } } } /// What a diff between two boundaries changed. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct DiffStats { pub files: u32, pub added: u32, pub removed: u32, } fn git(project: &Path, args: &[&str]) -> Command { let mut cmd = Command::new("git"); cmd.args(args).current_dir(project); #[cfg(windows)] { use std::os::windows::process::CommandExt; cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW } cmd } /// The first line git said on stderr, or `fallback`. fn why(stderr: &[u8], fallback: &str) -> String { String::from_utf8_lossy(stderr) .lines() .map(str::trim) .find(|line| !line.is_empty()) .map(str::to_string) .unwrap_or_else(|| fallback.to_string()) } /// A hex object id (git's full ids are 40 or 64 characters). fn is_object_id(id: &str) -> bool { matches!(id.len(), 40 | 64) && id.chars().all(|c| c.is_ascii_hexdigit()) } /// The boundary at `HEAD`, as a full commit id. pub fn head(project: &Path) -> Result { loop_tools::git_head_full(project).map(Boundary::Commit) } /// Deletes the copied index on every path out of `snapshot`. struct TempIndex(PathBuf); impl Drop for TempIndex { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } } static SNAPSHOTS: AtomicU64 = AtomicU64::new(0); /// Snapshot the working tree (tracked, changed and untracked, ignored files /// left out) as a tree id, without touching the real index, `HEAD` or any file. pub fn snapshot(project: &Path) -> Result { let located = git(project, &["rev-parse", "--git-path", "index"]) .output() .map_err(|err| format!("git could not run: {err}"))?; if !located.status.success() { return Err(format!( "git could not find the index: {}", why(&located.stderr, "not a git repository") )); } let real = String::from_utf8_lossy(&located.stdout).trim().to_string(); let temp = TempIndex(std::env::temp_dir().join(format!( "plan2code-round-index-{}-{}", std::process::id(), SNAPSHOTS.fetch_add(1, Ordering::Relaxed) ))); if !real.is_empty() { let source = project.join(&real); if source.is_file() { std::fs::copy(&source, &temp.0) .map_err(|err| format!("could not copy the index: {err}"))?; } } let run = |args: &[&str]| { git(project, args) .env("GIT_INDEX_FILE", &temp.0) .output() .map_err(|err| format!("git could not run: {err}")) }; let added = run(&["add", "-A"])?; if !added.status.success() { return Err(format!( "git could not snapshot the working tree: {}", why(&added.stderr, "git add failed") )); } let written = run(&["write-tree"])?; let tree = String::from_utf8_lossy(&written.stdout).trim().to_string(); if !written.status.success() || !is_object_id(&tree) { return Err(format!( "git could not write the snapshot: {}", why(&written.stderr, "git write-tree failed") )); } Ok(Boundary::Tree(tree)) } /// Whether the boundary's object is still in the repository (git may collect /// an unreferenced snapshot tree). pub fn exists(project: &Path, b: &Boundary) -> bool { if !is_object_id(b.id()) { return false; } git(project, &["cat-file", "-e", &b.peel()]) .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .map(|status| status.success()) .unwrap_or(false) } /// Write the plain unified diff from `from` to `to` into `out`, and say how big /// it is. A boundary gone from the repository is refused by name. pub fn diff( project: &Path, from: &Boundary, to: &Boundary, out: &Path, ) -> Result { for side in [from, to] { if !exists(project, side) { return Err(format!("round boundary missing: {}", side.id())); } } // Fixed prefixes and no external driver: a user's diff settings must not // change what the round agent reads. let base = [ "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", ]; let file = std::fs::File::create(out) .map_err(|err| format!("could not write {}: {err}", out.display()))?; let patch = git(project, &["diff"]) .args(base) .arg(from.id()) .arg(to.id()) .stdout(Stdio::from(file)) .stderr(Stdio::piped()) .output() .map_err(|err| { let _ = std::fs::remove_file(out); format!("git could not run: {err}") })?; if !patch.status.success() { let _ = std::fs::remove_file(out); return Err(format!( "git diff failed: {}", why(&patch.stderr, "no reason given") )); } let numstat = git(project, &["diff", "--numstat", "--no-ext-diff"]) .arg(from.id()) .arg(to.id()) .output() .map_err(|err| { let _ = std::fs::remove_file(out); format!("git could not run: {err}") })?; if !numstat.status.success() { let _ = std::fs::remove_file(out); return Err(format!( "git diff failed: {}", why(&numstat.stderr, "no reason given") )); } let mut stats = DiffStats::default(); for line in String::from_utf8_lossy(&numstat.stdout).lines() { let mut parts = line.split('\t'); let (Some(added), Some(removed)) = (parts.next(), parts.next()) else { continue; }; stats.files += 1; // A binary file shows `-` for both. stats.added += added.parse::().unwrap_or(0); stats.removed += removed.parse::().unwrap_or(0); } Ok(stats) } #[cfg(test)] mod tests { use super::*; fn git_in(repo: &Path, args: &[&str]) -> String { let out = git(repo, args).output().expect("git runs"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).to_string() } /// A new repository in a unique temp folder with one commit, its config /// scrubbed of anything global (no autocrlf, no hooks, no signing). fn scratch(name: &str) -> PathBuf { let repo = std::env::temp_dir() .join(format!("plan2code-round-{name}-{}", std::process::id())) .join("repo"); let _ = std::fs::remove_dir_all(repo.parent().unwrap()); std::fs::create_dir_all(&repo).unwrap(); git_in(&repo, &["init", "-q"]); for (key, value) in [ ("user.name", "Round Test"), ("user.email", "round@example.com"), ("commit.gpgsign", "false"), ("core.autocrlf", "false"), ("core.hooksPath", ".git/hooks"), ] { git_in(&repo, &["config", key, value]); } std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap(); git_in(&repo, &["add", "-A"]); git_in(&repo, &["commit", "-q", "-m", "first"]); repo } fn cleanup(repo: &Path) { let _ = std::fs::remove_dir_all(repo.parent().unwrap()); } #[test] fn head_is_a_full_commit_id() { let repo = scratch("head"); let boundary = head(&repo).unwrap(); assert!(matches!(&boundary, Boundary::Commit(id) if is_object_id(id))); assert!(exists(&repo, &boundary)); cleanup(&repo); } #[test] fn a_snapshot_leaves_status_and_the_index_unchanged() { let repo = scratch("untouched"); std::fs::write(repo.join("a.txt"), "one\ntwo\nthree\n").unwrap(); std::fs::write(repo.join("new.txt"), "new\n").unwrap(); // Settle git's own stat refresh before measuring. git_in(&repo, &["status", "--porcelain"]); let index = repo.join(".git/index"); let before = std::fs::read(&index).unwrap(); let head_before = git_in(&repo, &["rev-parse", "HEAD"]); let first = snapshot(&repo).unwrap(); let second = snapshot(&repo).unwrap(); assert_eq!(first, second, "the same tree twice"); assert_eq!(std::fs::read(&index).unwrap(), before, "index bytes"); assert_eq!(git_in(&repo, &["rev-parse", "HEAD"]), head_before); let status = git_in(&repo, &["status", "--porcelain"]); assert!(status.contains(" M a.txt"), "{status}"); assert!(status.contains("?? new.txt"), "still untracked: {status}"); assert_eq!( std::fs::read_to_string(repo.join("new.txt")).unwrap(), "new\n" ); cleanup(&repo); } #[test] fn an_untracked_file_shows_in_the_next_snapshots_diff() { let repo = scratch("untracked"); let one = snapshot(&repo).unwrap(); std::fs::write(repo.join("fresh.txt"), "a\nb\nc\n").unwrap(); let two = snapshot(&repo).unwrap(); assert_ne!(one, two); let out = repo.parent().unwrap().join("round-1.diff"); let stats = diff(&repo, &one, &two, &out).unwrap(); let text = std::fs::read_to_string(&out).unwrap(); assert!(text.contains("+++ b/fresh.txt"), "{text}"); assert_eq!( stats, DiffStats { files: 1, added: 3, removed: 0 } ); cleanup(&repo); } #[test] fn a_diff_between_two_commits_equals_git_diff() { let repo = scratch("commits"); let a = head(&repo).unwrap(); std::fs::write(repo.join("a.txt"), "one\nTWO\nthree\n").unwrap(); git_in(&repo, &["add", "-A"]); git_in(&repo, &["commit", "-q", "-m", "second"]); let b = head(&repo).unwrap(); let out = repo.parent().unwrap().join("between.diff"); let stats = diff(&repo, &a, &b, &out).unwrap(); let expected = git_in( &repo, &[ "diff", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", a.id(), b.id(), ], ); assert_eq!(std::fs::read_to_string(&out).unwrap(), expected); assert_eq!( stats, DiffStats { files: 1, added: 2, removed: 1 } ); cleanup(&repo); } #[test] fn a_commit_and_a_snapshot_can_be_diffed() { let repo = scratch("mixed"); let start = head(&repo).unwrap(); std::fs::write(repo.join("a.txt"), "one\n").unwrap(); let now = snapshot(&repo).unwrap(); let out = repo.parent().unwrap().join("mixed.diff"); let stats = diff(&repo, &start, &now, &out).unwrap(); assert_eq!(stats.removed, 1); cleanup(&repo); } #[test] fn a_made_up_id_does_not_exist_and_the_diff_refuses_it() { let repo = scratch("missing"); let real = head(&repo).unwrap(); let ghost = Boundary::Tree("0123456789abcdef0123456789abcdef01234567".to_string()); assert!(!exists(&repo, &ghost)); assert!(!exists(&repo, &Boundary::Commit("--output=x".to_string()))); let out = repo.parent().unwrap().join("ghost.diff"); let err = diff(&repo, &real, &ghost, &out).unwrap_err(); assert_eq!( err, "round boundary missing: 0123456789abcdef0123456789abcdef01234567" ); // Either side is checked. assert!(diff(&repo, &ghost, &real, &out).is_err()); assert!(!out.exists(), "nothing written for a refused diff"); cleanup(&repo); } #[test] fn a_snapshot_outside_a_repository_fails_with_a_reason() { let dir = std::env::temp_dir().join(format!("plan2code-round-none-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); // A `.git` file naming a gitdir that is not there: git stops here // whatever repository sits above the temp folder. std::fs::write( dir.join(".git"), "gitdir: /plan2code-no-such-gitdir ", ) .unwrap(); let err = snapshot(&dir).unwrap_err(); assert!(err.starts_with("git could not"), "{err}"); let _ = std::fs::remove_dir_all(&dir); } }