diff options
Diffstat (limited to '')
| -rw-r--r-- | src/git.rs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..78348af --- /dev/null +++ b/src/git.rs | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | //! Git helpers for the checkpoint/undo feature. In a separate module so they | ||
| 2 | //! are unit-testable without driving the whole CLI. | ||
| 3 | |||
| 4 | use std::path::Path; | ||
| 5 | use std::process::Command; | ||
| 6 | |||
| 7 | /// Runs `git -C <dir> <args>`, returning trimmed stdout on success. | ||
| 8 | pub fn run(dir: &Path, args: &[&str]) -> Option<String> { | ||
| 9 | Command::new("git") | ||
| 10 | .arg("-C") | ||
| 11 | .arg(dir) | ||
| 12 | .args(args) | ||
| 13 | .output() | ||
| 14 | .ok() | ||
| 15 | .and_then(|output| { | ||
| 16 | output | ||
| 17 | .status | ||
| 18 | .success() | ||
| 19 | .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string()) | ||
| 20 | }) | ||
| 21 | } | ||
| 22 | |||
| 23 | /// True when `dir` is inside a work tree (a `.git` dir or file up the tree). | ||
| 24 | pub fn in_repo(dir: &Path) -> bool { | ||
| 25 | let mut current = dir.to_path_buf(); | ||
| 26 | loop { | ||
| 27 | if current.join(".git").exists() { | ||
| 28 | return true; | ||
| 29 | } | ||
| 30 | if !current.pop() { | ||
| 31 | return false; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | } | ||
| 35 | |||
| 36 | /// Snapshots the tree as a commit when it is dirty, and returns HEAD. Returns | ||
| 37 | /// `None` outside a repository. | ||
| 38 | pub fn checkpoint(dir: &Path) -> Option<String> { | ||
| 39 | if !in_repo(dir) { | ||
| 40 | return None; | ||
| 41 | } | ||
| 42 | run(dir, &["add", "-A"]); | ||
| 43 | let dirty = run(dir, &["status", "--porcelain"]) | ||
| 44 | .map(|status| !status.is_empty()) | ||
| 45 | .unwrap_or(false); | ||
| 46 | if dirty { | ||
| 47 | run(dir, &["commit", "-m", "agent686: checkpoint"]); | ||
| 48 | } | ||
| 49 | run(dir, &["rev-parse", "HEAD"]) | ||
| 50 | } | ||
| 51 | |||
| 52 | /// Resets to the checkpoint commit and drops untracked files, undoing a turn's | ||
| 53 | /// changes. | ||
| 54 | pub fn undo(dir: &Path, sha: &str) { | ||
| 55 | run(dir, &["reset", "--hard", sha]); | ||
| 56 | run(dir, &["clean", "-fd"]); | ||
| 57 | } | ||
