Skip to main content

gw_render/
status.rs

1//! `gw status` view.
2
3use crate::style::{BRANCH, BRANCH_BOLD, DIM, GREEN, RED, UPSTREAM, YELLOW, paint, sanitize};
4use gw_parse::{Entry, Numstat, Status, SubmoduleState};
5use unicode_width::UnicodeWidthStr;
6
7/// Rewrites a repo-root relative path to be relative to `prefix` (from `git rev-parse --show-prefix`).
8pub fn relative(path: &str, prefix: &str) -> String {
9    // Untracked directories come as `dir/`: resolve the dir itself, then restore the slash.
10    if let Some(dir) = path.strip_suffix('/') {
11        return relative(dir, prefix) + "/";
12    }
13    let pre: Vec<&str> = prefix.split('/').filter(|s| !s.is_empty()).collect();
14    let parts: Vec<&str> = path.split('/').collect();
15    let dirs = &parts[..parts.len() - 1];
16    let common = pre.iter().zip(dirs).take_while(|(a, b)| a == b).count();
17    let mut out = "../".repeat(pre.len() - common);
18    out += &parts[common..].join("/");
19    out
20}
21
22fn count(n: u32, sgr: &str, arrow: &str, color: bool) -> String {
23    paint(&format!("{arrow}{n}"), if n > 0 { sgr } else { DIM }, color)
24}
25
26/// Line counts per group, keyed by repo-relative path. Missing entries show no stat.
27#[derive(Default)]
28pub struct LineStats {
29    pub staged: Numstat,
30    pub unstaged: Numstat,
31    pub untracked: Numstat,
32    /// Checked-out commit per submodule path (from `git submodule status`), when known.
33    pub checkouts: std::collections::HashMap<String, String>,
34}
35
36fn short(sha: &str) -> &str {
37    &sha[..sha.len().min(7)]
38}
39
40/// `<recorded> → <current>  <labels>` for a submodule line.
41fn submodule_detail(e: &Entry, sub: &SubmoduleState, checkouts: &std::collections::HashMap<String, String>, color: bool) -> String {
42    // A newly added submodule has no commit in HEAD (all zeros): its recorded commit is the index one.
43    let recorded = if sub.head.bytes().all(|b| b == b'0') { &sub.index } else { &sub.head };
44    let current = if sub.commit_changed { checkouts.get(&e.path).unwrap_or(recorded) } else { &sub.index };
45    let mut s = if current == recorded {
46        paint(short(recorded), DIM, color)
47    } else {
48        format!("{} → {}", paint(short(recorded), DIM, color), paint(short(current), YELLOW, color))
49    };
50    let labels: Vec<String> = [
51        (sub.head != sub.index && recorded == &sub.head, "staged", GREEN),
52        (sub.commit_changed, "new commits", YELLOW),
53        (sub.modified, "modified content", YELLOW),
54        (sub.untracked, "untracked content", DIM),
55    ]
56    .into_iter()
57    .filter(|l| l.0)
58    .map(|(_, t, sgr)| paint(t, sgr, color))
59    .collect();
60    if !labels.is_empty() {
61        s += &format!("  {}", labels.join(", "));
62    }
63    s
64}
65
66/// `+a -d` (GitHub/GitLab style), `bin` for binary files.
67fn stat(n: Option<Option<(u64, u64)>>, color: bool) -> String {
68    match n {
69        Some(Some((a, d))) => format!(
70            "{} {}",
71            paint(&format!("+{a}"), if a > 0 { GREEN } else { DIM }, color),
72            paint(&format!("-{d}"), if d > 0 { RED } else { DIM }, color)
73        ),
74        Some(None) => paint("bin", DIM, color),
75        None => String::new(),
76    }
77}
78
79pub fn render_status(st: &Status, prefix: &str, stats: &LineStats, color: bool) -> String {
80    let mut out = match (&st.head, &st.oid) {
81        (Some(h), _) => paint(&sanitize(h), BRANCH_BOLD, color),
82        (None, Some(oid)) => paint(&format!("detached at {}", &oid[..oid.len().min(7)]), YELLOW, color),
83        (None, None) => paint("detached", YELLOW, color),
84    };
85    if st.head.is_some() {
86        match &st.upstream {
87            Some(up) => {
88                out += &format!(" -> {}", paint(&sanitize(up), UPSTREAM, color));
89                if let Some((a, b)) = st.ahead_behind {
90                    out += &format!("  {} {}", count(a, GREEN, "↑", color), count(b, YELLOW, "↓", color));
91                }
92            }
93            None => out += &format!("  {}", paint("no upstream", DIM, color)),
94        }
95    }
96    out.push('\n');
97
98    // -z output is unquoted: file names may carry escape sequences.
99    let rel = |p: &str| sanitize(&relative(p, prefix));
100    let name = |e: &Entry| match &e.orig {
101        Some(o) => format!("{} -> {}", rel(o), rel(&e.path)),
102        None => rel(&e.path),
103    };
104    let untracked = |e: &Entry| e.x == '?';
105    let file = |e: &&Entry| !e.unmerged && !untracked(e) && e.submodule.is_none();
106    // (code, path, stats, submodule detail)
107    type Line = (char, String, Option<Option<(u64, u64)>>, String);
108    let groups: [(&str, &str, Vec<Line>); 5] = [
109        ("Conflicts", RED, st.entries.iter().filter(|e| e.unmerged).map(|e| ('U', rel(&e.path), None, String::new())).collect()),
110        (
111            "Staged",
112            GREEN,
113            st.entries
114                .iter()
115                .filter(|e| file(e) && e.x != '.')
116                .map(|e| (e.x, name(e), stats.staged.get(&e.path).copied(), String::new()))
117                .collect(),
118        ),
119        (
120            "Changed",
121            YELLOW,
122            st.entries
123                .iter()
124                .filter(|e| file(e) && e.y != '.')
125                .map(|e| (e.y, rel(&e.path), stats.unstaged.get(&e.path).copied(), String::new()))
126                .collect(),
127        ),
128        (
129            "Submodules",
130            BRANCH,
131            st.entries
132                .iter()
133                .filter_map(|e| {
134                    let sub = e.submodule.as_ref().filter(|_| !e.unmerged)?;
135                    let code = if e.x == 'A' { 'A' } else { 'M' };
136                    Some((code, name(e), None, submodule_detail(e, sub, &stats.checkouts, color)))
137                })
138                .collect(),
139        ),
140        (
141            "Untracked",
142            DIM,
143            st.entries.iter().filter(|e| untracked(e)).map(|e| ('?', rel(&e.path), stats.untracked.get(&e.path).copied(), String::new())).collect(),
144        ),
145    ];
146    if groups.iter().all(|g| g.2.is_empty()) {
147        out += &paint("clean", DIM, color);
148        out.push('\n');
149        return out;
150    }
151    for (title, sgr, files) in groups.iter().filter(|g| !g.2.is_empty()) {
152        out += &format!("{}\n", paint(&format!("{title} ({})", files.len()), sgr, color));
153        let width = files.iter().filter(|f| f.2.is_some() || !f.3.is_empty()).map(|f| f.1.width()).max().unwrap_or(0);
154        for (code, path, n, detail) in files {
155            let code = paint(&code.to_string(), sgr, color);
156            let tail = if detail.is_empty() { stat(*n, color) } else { detail.clone() };
157            if tail.is_empty() {
158                out += &format!("  {code} {path}\n");
159            } else {
160                out += &format!("  {code} {path}{}  {tail}\n", " ".repeat(width.saturating_sub(path.width())));
161            }
162        }
163    }
164    // Sum of every count shown; binary files and files without stats add nothing.
165    let (a, d) = groups.iter().flat_map(|g| &g.2).filter_map(|f| f.2.flatten()).fold((0, 0), |t, (a, d)| (t.0 + a, t.1 + d));
166    if groups.iter().any(|g| g.2.iter().any(|f| f.2.is_some())) {
167        out += &format!("Total {}\n", stat(Some(Some((a, d))), color));
168    }
169    out
170}
171
172#[cfg(test)]
173mod tests {
174    use super::relative;
175
176    #[test]
177    fn relative_paths() {
178        assert_eq!(relative("src/a.rs", "src/"), "a.rs");
179        assert_eq!(relative("b.rs", "src/"), "../b.rs");
180        assert_eq!(relative("src2/x", "src/"), "../src2/x");
181        assert_eq!(relative("a/b/c", "a/d/"), "../b/c");
182        assert_eq!(relative("x", ""), "x");
183        assert_eq!(relative("src/", "src/"), "../src/");
184        assert_eq!(relative("src/d/", "src/"), "d/");
185    }
186}