1use serde_json::{Value, json};
6
7pub 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}