Skip to main content

jouet_git/
status.rs

1//! The state of a work tree from `git status --porcelain=v2 --branch`, as
2//! the rules' `jouet.git.state()` probe and the routines' `git.state()`
3//! report it.
4
5use serde_json::{Value, json};
6
7/// The branch, its upstream and how far apart they are, and whether the
8/// work tree is clean.
9pub fn parse(out: &str) -> Value {
10    let (mut head, mut branch, mut upstream) = (None, None, None);
11    let (mut ahead, mut behind): (Option<u64>, Option<u64>) = (None, None);
12    let (mut changed, mut untracked, mut conflicted) = (0u64, 0u64, 0u64);
13    for line in out.lines() {
14        if let Some(header) = line.strip_prefix("# ") {
15            let (key, value) = header.split_once(' ').unwrap_or((header, ""));
16            match key {
17                "branch.oid" if value != "(initial)" => {
18                    head = Some(value.chars().take(12).collect::<String>());
19                }
20                "branch.head" if value != "(detached)" => branch = Some(value.to_string()),
21                "branch.upstream" => upstream = Some(value.to_string()),
22                "branch.ab" => {
23                    let mut parts = value.split(' ');
24                    ahead = parts
25                        .next()
26                        .and_then(|a| a.trim_start_matches('+').parse().ok());
27                    behind = parts
28                        .next()
29                        .and_then(|b| b.trim_start_matches('-').parse().ok());
30                }
31                _ => {}
32            }
33        } else if line.starts_with("? ") {
34            untracked += 1;
35        } else if line.starts_with("u ") {
36            conflicted += 1;
37        } else if line.starts_with("1 ") || line.starts_with("2 ") {
38            changed += 1;
39        }
40    }
41    let mut state = json!({
42        "detached": branch.is_none(),
43        "dirty": changed + untracked + conflicted > 0,
44        "changed": changed,
45        "untracked": untracked,
46        "conflicted": conflicted,
47    });
48    for (key, value) in [("head", head), ("branch", branch), ("upstream", upstream)] {
49        if let Some(value) = value {
50            state[key] = value.into();
51        }
52    }
53    for (key, value) in [("ahead", ahead), ("behind", behind)] {
54        if let Some(value) = value {
55            state[key] = value.into();
56        }
57    }
58    state
59}