Skip to main content

work_graph/
git.rs

1//! Git tip + tracked file list. Beat B needs SHA, branch, and dirty flag.
2
3use std::path::Path;
4use std::process::Command;
5
6use crate::IndexError;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct GitTip {
10    pub sha: String,
11    pub branch: String,
12    pub dirty: bool,
13}
14
15/// Reads tip.
16pub fn read_tip(root: &Path) -> Result<GitTip, IndexError> {
17    let sha = git_stdout(root, &["rev-parse", "HEAD"])?;
18    let branch = git_stdout(root, &["rev-parse", "--abbrev-ref", "HEAD"])?;
19    let porcelain = git_stdout_raw(root, &["status", "--porcelain"])?;
20    Ok(GitTip {
21        sha,
22        branch,
23        dirty: !porcelain.is_empty(),
24    })
25}
26
27/// `git ls-files` listing.
28pub fn ls_files(root: &Path) -> Result<Vec<String>, IndexError> {
29    let out = git_stdout_raw(root, &["ls-files", "-z"])?;
30    let mut files = Vec::new();
31    for chunk in out.split('\0') {
32        if chunk.is_empty() {
33            continue;
34        }
35        files.push(chunk.replace('\\', "/"));
36    }
37    files.sort();
38    Ok(files)
39}
40
41fn git_stdout(root: &Path, args: &[&str]) -> Result<String, IndexError> {
42    Ok(git_stdout_raw(root, args)?.trim().to_string())
43}
44
45fn git_stdout_raw(root: &Path, args: &[&str]) -> Result<String, IndexError> {
46    let output = Command::new("git")
47        .args(args)
48        .current_dir(root)
49        .output()
50        .map_err(|e| IndexError::Git(format!("failed to spawn git: {e}")))?;
51    if !output.status.success() {
52        let err = String::from_utf8_lossy(&output.stderr);
53        return Err(IndexError::Git(format!(
54            "git {} failed: {}",
55            args.join(" "),
56            err.trim()
57        )));
58    }
59    String::from_utf8(output.stdout)
60        .map_err(|e| IndexError::Git(format!("git output was not utf-8: {e}")))
61}