Skip to main content
← dvs documentation Rust API reference

dvs/
git.rs

1use std::path::Path;
2use std::process::Command;
3
4/// Represents the current checkout.
5/// If a command fails, it just returns None, it doesn't error.
6#[derive(Debug, Default, Clone, PartialEq)]
7pub struct Checkout {
8    pub branch: Option<String>,
9    pub commit: Option<String>,
10}
11
12fn git(root: &Path, args: &[&str]) -> Option<String> {
13    let output = Command::new("git")
14        .arg("-C")
15        .arg(root)
16        .args(args)
17        .output()
18        .ok()?;
19    if !output.status.success() {
20        return None;
21    }
22    let value = String::from_utf8(output.stdout).ok()?;
23    let value = value.trim();
24    (!value.is_empty()).then(|| value.to_string())
25}
26
27pub fn current_checkout(root: &Path) -> Checkout {
28    // Fails on an unborn branch, which has no commit yet
29    let commit = git(root, &["rev-parse", "HEAD"]);
30    // Fails on a detached HEAD, which is on no branch
31    let branch = git(root, &["symbolic-ref", "--short", "-q", "HEAD"]);
32    Checkout { branch, commit }
33}