//! Git helpers for the checkpoint/undo feature. In a separate module so they
//! are unit-testable without driving the whole CLI.
use std::path::Path;
use std::process::Command;
/// Runs `git -C
`, returning trimmed stdout on success.
pub fn run(dir: &Path, args: &[&str]) -> Option {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.ok()
.and_then(|output| {
output
.status
.success()
.then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
})
}
/// True when `dir` is inside a work tree (a `.git` dir or file up the tree).
pub fn in_repo(dir: &Path) -> bool {
let mut current = dir.to_path_buf();
loop {
if current.join(".git").exists() {
return true;
}
if !current.pop() {
return false;
}
}
}
/// Snapshots the tree as a commit when it is dirty, and returns HEAD. Returns
/// `None` outside a repository.
pub fn checkpoint(dir: &Path) -> Option {
if !in_repo(dir) {
return None;
}
run(dir, &["add", "-A"]);
let dirty = run(dir, &["status", "--porcelain"])
.map(|status| !status.is_empty())
.unwrap_or(false);
if dirty {
run(dir, &["commit", "-m", "agent686: checkpoint"]);
}
run(dir, &["rev-parse", "HEAD"])
}
/// Resets to the checkpoint commit and drops untracked files, undoing a turn's
/// changes.
pub fn undo(dir: &Path, sha: &str) {
run(dir, &["reset", "--hard", sha]);
run(dir, &["clean", "-fd"]);
}