use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
#[derive(Debug, Clone)]
pub enum Snapshot {
Git { root: PathBuf, tree: String },
Files(BTreeMap<String, String>),
}
pub fn capture_snapshot(root: &Path) -> Snapshot {
if is_git_repo(root) {
Snapshot::Git {
root: root.to_path_buf(),
tree: snapshot_git_tree(root),
}
} else {
Snapshot::Files(snapshot_files(root))
}
}
pub fn diff_snapshots(before: &Snapshot, after: &Snapshot) -> String {
match (before, after) {
(
Snapshot::Git {
root,
tree: before_tree,
},
Snapshot::Git {
tree: after_tree, ..
},
) => {
if before_tree == after_tree || before_tree.is_empty() || after_tree.is_empty() {
String::new()
} else {
git_diff_trees(root, before_tree, after_tree)
}
}
(Snapshot::Files(before_map), Snapshot::Files(after_map)) => {
diff_file_maps(before_map, after_map)
}
_ => String::new(),
}
}
fn is_git_repo(root: &Path) -> bool {
crate::binding::is_git_worktree(root)
}
fn snapshot_git_tree(root: &Path) -> String {
let Ok(index_dir) = tempfile::tempdir() else {
return String::new();
};
let index_path = index_dir.path().join("throwaway-index");
let _ = run_git_with_index(root, &index_path, &["read-tree", "HEAD"]);
let _ = run_git_with_index(root, &index_path, &["add", "-A"]);
run_git_with_index(root, &index_path, &["write-tree"])
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_default()
}
fn run_git_with_index(root: &Path, index_path: &Path, args: &[&str]) -> Option<Output> {
Command::new("git")
.arg("-C")
.arg(root)
.env("GIT_INDEX_FILE", index_path)
.args(args)
.output()
.ok()
}
fn git_diff_trees(root: &Path, before_tree: &str, after_tree: &str) -> String {
Command::new("git")
.arg("-C")
.arg(root)
.args(["diff", "--no-color", before_tree, after_tree])
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).to_string())
.unwrap_or_default()
}
fn snapshot_files(root: &Path) -> BTreeMap<String, String> {
let mut map = BTreeMap::new();
collect_files(root, root, &mut map, 0);
map
}
const MAX_WALK_DEPTH: usize = 128;
fn is_os_metadata(name: &str) -> bool {
name == ".DS_Store"
|| name == ".apdisk"
|| name.starts_with("._")
|| name.starts_with(".com.apple.")
|| name.starts_with(".Spotlight-")
|| name.starts_with(".Trashes")
|| name.starts_with(".fseventsd")
|| name.starts_with(".TemporaryItems")
}
fn collect_files(base: &Path, dir: &Path, map: &mut BTreeMap<String, String>, depth: usize) {
if depth > MAX_WALK_DEPTH {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str == ".git" || is_os_metadata(&name_str) {
continue;
}
let Ok(meta) = std::fs::symlink_metadata(&path) else {
continue;
};
if meta.is_symlink() {
continue;
}
if meta.is_dir() {
collect_files(base, &path, map, depth + 1);
} else if meta.is_file() {
let rel = path
.strip_prefix(base)
.unwrap_or(&path)
.to_string_lossy()
.to_string();
let content =
std::fs::read_to_string(&path).unwrap_or_else(|_| "<binary or unreadable>".into());
map.insert(rel, content);
}
}
}
fn diff_file_maps(before: &BTreeMap<String, String>, after: &BTreeMap<String, String>) -> String {
let mut out = String::new();
for (path, content) in after {
match before.get(path) {
None => {
out.push_str(&format!("+++ added: {path}\n{content}\n"));
}
Some(old) if old != content => {
out.push_str(&format!(
"~~~ changed: {path}\n--- before\n{old}\n+++ after\n{content}\n"
));
}
Some(_) => {}
}
}
for path in before.keys() {
if !after.contains_key(path) {
out.push_str(&format!("--- removed: {path}\n"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn file_map_diff_reports_addition() {
let before = BTreeMap::new();
let mut after = BTreeMap::new();
after.insert("hello.py".to_string(), "print('hi')".to_string());
let diff = diff_file_maps(&before, &after);
assert!(diff.contains("+++ added: hello.py"), "diff: {diff}");
assert!(diff.contains("print('hi')"), "diff: {diff}");
}
#[test]
fn file_map_diff_reports_change() {
let mut before = BTreeMap::new();
before.insert("a.txt".to_string(), "old".to_string());
let mut after = BTreeMap::new();
after.insert("a.txt".to_string(), "new".to_string());
let diff = diff_file_maps(&before, &after);
assert!(diff.contains("~~~ changed: a.txt"), "diff: {diff}");
assert!(diff.contains("old") && diff.contains("new"), "diff: {diff}");
}
#[test]
fn identical_maps_produce_empty_diff() {
let mut m = BTreeMap::new();
m.insert("x".to_string(), "y".to_string());
assert!(diff_file_maps(&m, &m).is_empty());
}
#[test]
fn capture_and_diff_non_git_dir() {
let tmp = tempfile::tempdir().expect("tempdir");
let before = capture_snapshot(tmp.path());
std::fs::write(tmp.path().join("new.rs"), "fn main() {}").expect("write");
let after = capture_snapshot(tmp.path());
let diff = diff_snapshots(&before, &after);
assert!(diff.contains("+++ added: new.rs"), "diff: {diff}");
assert!(diff.contains("fn main()"), "diff: {diff}");
}
#[test]
#[cfg(unix)]
fn collect_files_terminates_on_symlink_cycle() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(tmp.path().join("real.txt"), "hello").expect("write real file");
std::os::unix::fs::symlink(tmp.path(), tmp.path().join("loop"))
.expect("create symlink cycle");
let map = snapshot_files(tmp.path());
assert!(
map.contains_key("real.txt"),
"the real file must still be captured: {map:?}"
);
assert!(
!map.keys().any(|k| k.starts_with("loop/")),
"the symlink must not have been traversed into: {map:?}"
);
}
#[test]
fn collect_files_ignores_macos_metadata_noise() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(tmp.path().join(".DS_Store"), "binary junk").expect("write .DS_Store");
std::fs::write(tmp.path().join("._foo"), "appledouble junk").expect("write ._foo");
std::fs::write(tmp.path().join("real.txt"), "real content").expect("write real.txt");
let map = snapshot_files(tmp.path());
assert_eq!(
map.keys().collect::<Vec<_>>(),
vec!["real.txt"],
"only the real deliverable must be collected: {map:?}"
);
}
#[test]
fn collect_files_still_collects_dot_git_lookalikes() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(tmp.path().join(".gitignore"), "target/").expect("write .gitignore");
std::fs::create_dir(tmp.path().join(".github")).expect("mkdir .github");
std::fs::write(tmp.path().join(".github").join("workflow.yml"), "name: ci")
.expect("write workflow");
let map = snapshot_files(tmp.path());
assert!(
map.contains_key(".gitignore"),
".gitignore must still be collected: {map:?}"
);
assert!(
map.keys()
.any(|k| k == ".github/workflow.yml" || k == ".github\\workflow.yml"),
".github/workflow.yml must still be collected: {map:?}"
);
}
#[test]
fn git_index_and_working_tree_are_unchanged_after_capture() {
let repo = init_repo_with_commit();
std::fs::write(repo.path().join("committed.txt"), "staged edit").expect("write");
run(&repo, &["add", "committed.txt"]);
std::fs::write(repo.path().join("unstaged.txt"), "unstaged\n").expect("write");
run(&repo, &["add", "unstaged.txt"]);
run(&repo, &["commit", "-m", "second"]);
std::fs::write(repo.path().join("unstaged.txt"), "unstaged edit").expect("write");
std::fs::write(repo.path().join("untracked.txt"), "new").expect("write");
let index_path = repo.path().join(".git").join("index");
let index_before = std::fs::read(&index_path).expect("read index");
let status_before = porcelain_status(&repo);
let _ = capture_snapshot(repo.path());
let index_after = std::fs::read(&index_path).expect("read index");
let status_after = porcelain_status(&repo);
assert_eq!(
index_before, index_after,
"the real .git/index must be byte-identical before/after capture_snapshot"
);
assert_eq!(
status_before, status_after,
"git status --porcelain must be unchanged before/after capture_snapshot"
);
}
#[test]
fn dirty_tree_diff_contains_only_the_tasks_own_change() {
let repo = init_repo_with_commit();
std::fs::write(
repo.path().join("committed.txt"),
"pre-existing unstaged edit",
)
.expect("write");
std::fs::write(repo.path().join("pre-existing-untracked.txt"), "noise").expect("write");
let before = capture_snapshot(repo.path());
std::fs::write(repo.path().join("task_output.py"), "print('task ran')").expect("write");
let after = capture_snapshot(repo.path());
let diff = diff_snapshots(&before, &after);
assert!(
diff.contains("task_output.py"),
"diff must contain the task's own new file: {diff}"
);
assert!(
!diff.contains("pre-existing-untracked.txt"),
"diff must NOT contain the pre-existing untracked noise: {diff}"
);
assert!(
!diff.contains("pre-existing unstaged edit"),
"diff must NOT contain the pre-existing unstaged edit's content: {diff}"
);
}
fn init_repo_with_commit() -> tempfile::TempDir {
let repo = tempfile::tempdir().expect("tempdir");
run(&repo, &["init", "-q"]);
run(&repo, &["config", "user.email", "test@example.com"]);
run(&repo, &["config", "user.name", "Test"]);
std::fs::write(repo.path().join("committed.txt"), "original\n").expect("write");
run(&repo, &["add", "committed.txt"]);
run(&repo, &["commit", "-q", "-m", "initial"]);
repo
}
fn run(repo: &tempfile::TempDir, args: &[&str]) {
let output = Command::new("git")
.arg("-C")
.arg(repo.path())
.args(args)
.output()
.expect("run git");
assert!(
output.status.success(),
"git {args:?} must succeed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
fn porcelain_status(repo: &tempfile::TempDir) -> String {
Command::new("git")
.arg("-C")
.arg(repo.path())
.args(["status", "--porcelain"])
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).to_string())
.expect("git status")
}
}