1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
//! 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 <dir> <args>`, returning trimmed stdout on success.
pub fn run(dir: &Path, args: &[&str]) -> Option<String> {
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<String> {
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"]);
}
|