aboutsummaryrefslogtreecommitdiffstats
path: root/src/git.rs
blob: a36ce5074ea512293e6482d23979dec4e2fd92e8 (plain) (blame)
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
58
59
60
61
62
63
64
/*
 * This file is part of agent686
 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
 * SPDX-License-Identifier: GPL-3.0-or-later
 * https://git.2137697.xyz/agent686
 */

//! 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"]);
}