Skip to main content

trumly/
render.rs

1//! How `trumly check` reads on a terminal: the trumly mark and context on one line, a fixed four-character status
2//! column (pass, warn, FAIL, so it reads with colour off), and one summary line. Colour is decoration on top of
3//! the words and is dropped for NO_COLOR, `--no-color`, a dumb terminal and anything that is not a terminal.
4
5use std::collections::BTreeMap;
6use std::io::IsTerminal;
7
8use trumly_core::report::Report;
9use trumly_core::rules::Status;
10
11/// What the terminal can show.
12#[derive(Clone, Copy)]
13pub struct Style {
14    pub color: bool,
15    pub truecolor: bool,
16    pub unicode: bool,
17}
18
19impl Style {
20    pub fn detect(args: &[String]) -> Style {
21        let dumb = std::env::var("TERM").map_or(false, |t| t == "dumb");
22        let off = args.iter().any(|a| a == "--no-color") || std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()) || dumb || !std::io::stdout().is_terminal();
23        let truecolor = std::env::var("COLORTERM").map_or(false, |c| c == "truecolor" || c == "24bit");
24        let utf8 = ["LC_ALL", "LC_CTYPE", "LANG"].iter().filter_map(|k| std::env::var(k).ok()).find(|v| !v.is_empty()).is_none_or(|v| v.to_lowercase().contains("utf"));
25        Style { color: !off, truecolor, unicode: !dumb && utf8 }
26    }
27    #[cfg(test)]
28    pub const PLAIN: Style = Style { color: false, truecolor: false, unicode: true };
29
30    /// the brand's terminal colours: 24-bit values from the design system, or the nearest of the 16
31    fn paint(&self, role: &str, text: &str) -> String {
32        if !self.color {
33            return text.to_string();
34        }
35        let (rgb, basic) = match role {
36            "mark" => ("104;208;217", "36"),
37            "pass" => ("125;213;150", "32"),
38            "warn" => ("240;176;90", "33"),
39            "fail" => ("254;161;150", "91;1"),
40            "dim" => ("158;174;182", "2"),
41            "bold" => ("", "1"),
42            _ => return text.to_string(),
43        };
44        let code = if self.truecolor && !rgb.is_empty() { format!("38;2;{rgb}{}", if role == "fail" { ";1" } else { "" }) } else { basic.to_string() };
45        format!("\x1b[{code}m{text}\x1b[0m")
46    }
47}
48
49fn plural(n: usize, one: &str, many: &str) -> String {
50    format!("{n} {}", if n == 1 { one } else { many })
51}
52
53/// the `check` report, in the brand's terminal layout
54pub fn check_text(report: &Report, name: &str, style: Style) -> String {
55    let mark = style.paint("mark", if style.unicode { "◇" } else { "<>" });
56    let planes = report.graph.nodes().filter(|n| n.kind.as_deref() == Some("plane")).count();
57    let packs = report.graph.nodes().filter_map(|n| n.fields.get("pack").and_then(|v| v.as_str())).map(|p| p.split('@').next().unwrap_or(p).to_string()).collect::<std::collections::BTreeSet<_>>().len();
58    let mut out = format!(
59        "{mark} {}  {}\n\n",
60        style.paint("bold", "trumly check"),
61        style.paint("dim", &format!("{name} · {} · {} · {}", plural(report.graph.len(), "node", "nodes"), plural(planes, "plane", "planes"), plural(packs, "pack", "packs")))
62    );
63    let row = |out: &mut String, word: &str, role: &str, text: &str, dim: &str| {
64        let pad = style.paint(role, word);
65        out.push_str(&format!("  {pad}  {text}{}\n", if dim.is_empty() { String::new() } else { format!("  {}", style.paint("dim", dim)) }));
66    };
67    let detail = |out: &mut String, id: &str, rest: &str| out.push_str(&format!("        {}  {}\n", style.paint("dim", id), rest));
68
69    let (mut failing, mut warnings, mut notes, mut passing) = (0usize, 0usize, 0usize, 0usize);
70
71    // rules: one row each, with the nodes it fails under it
72    struct Row { title: String, id: String, pass: usize, fails: Vec<String>, severity: String }
73    let mut rules: BTreeMap<String, Row> = BTreeMap::new();
74    for r in &report.evaluation.results {
75        let e = rules.entry(r.rule.clone()).or_insert_with(|| Row {
76            title: report.graph.get(&r.rule).map_or(r.rule.clone(), |n| n.title.clone()),
77            id: r.rule.clone(), pass: 0, fails: vec![], severity: r.severity.clone(),
78        });
79        if r.status == Status::Fail { e.fails.push(r.node.clone()); } else { e.pass += 1; }
80    }
81    let width = rules.values().map(|r| r.title.chars().count()).max().unwrap_or(0).min(48);
82    let pad = |s: &str| format!("{s}{}", " ".repeat(width.saturating_sub(s.chars().count())));
83    for r in rules.values().filter(|r| r.fails.is_empty()) {
84        passing += r.pass;
85        row(&mut out, "pass", "pass", &pad(&r.title), &format!("{}  {}", r.id, plural(r.pass, "node", "nodes")));
86    }
87    for r in rules.values().filter(|r| !r.fails.is_empty()) {
88        passing += r.pass;
89        let (word, role) = match r.severity.as_str() { "error" => ("FAIL", "fail"), "info" => ("info", "dim"), _ => ("warn", "warn") };
90        match r.severity.as_str() { "error" => failing += r.fails.len(), "info" => notes += r.fails.len(), _ => warnings += r.fails.len() }
91        row(&mut out, word, role, &pad(&r.title), &r.id);
92        for n in &r.fails { detail(&mut out, n, &report.graph.get(n).map_or(String::new(), |x| x.title.clone())); }
93    }
94    for e in &report.load_errors {
95        failing += 1;
96        row(&mut out, "FAIL", "fail", &format!("{}  {}", e.file, e.kind), "");
97    }
98    for f in &report.structure.errors {
99        failing += 1;
100        row(&mut out, "FAIL", "fail", &format!("{}  {} {}", f.node, f.kind, f.reference.as_deref().unwrap_or("")).trim_end().to_string(), "");
101    }
102    for f in &report.structure.warnings {
103        warnings += 1;
104        row(&mut out, "warn", "warn", &format!("{}  {} {}", f.node, f.kind, f.reference.as_deref().unwrap_or("")).trim_end().to_string(), "");
105    }
106    if rules.is_empty() && report.load_errors.is_empty() && report.structure.errors.is_empty() && report.structure.warnings.is_empty() {
107        out.push_str(&format!("  {}\n", style.paint("dim", "no rules to run")));
108    }
109
110    out.push('\n');
111    let mut parts = vec![
112        style.paint(if failing > 0 { "fail" } else { "dim" }, &format!("{failing} failing")),
113        style.paint(if warnings > 0 { "warn" } else { "dim" }, &plural(warnings, "warning", "warnings")),
114    ];
115    if notes > 0 { parts.push(style.paint("dim", &format!("{notes} info"))); }
116    parts.push(style.paint(if passing > 0 { "pass" } else { "dim" }, &format!("{passing} passing")));
117    out.push_str(&format!("{}   {}\n", parts.join(" · "), style.paint("dim", &format!("exit {}", report.exit_code()))));
118    out
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124    use trumly_core::report::check;
125
126    fn nodes(list: &[(&str, &str)]) -> Report {
127        check(list.iter().map(|(p, t)| (p.to_string(), t.to_string())).collect())
128    }
129
130    #[test]
131    fn reads_the_same_with_colour_off() {
132        let r = nodes(&[("a.md", "---\nid: a\ntype: thing\n---\n"), ("b.md", "---\nid: b\ntype: thing\n---\n")]);
133        let text = check_text(&r, "demo", Style::PLAIN);
134        assert!(text.starts_with("◇ trumly check  demo · 2 nodes · 0 planes · 0 packs\n"), "{text}");
135        assert!(!text.contains('\x1b'));
136        assert!(text.trim_end().lines().last().unwrap().contains("exit 0"), "{text}");
137    }
138
139    #[test]
140    fn colour_adds_codes_but_not_words() {
141        let r = nodes(&[("a.md", "---\nid: a\ntype: thing\n---\n")]);
142        let plain = check_text(&r, "demo", Style::PLAIN);
143        let colour = check_text(&r, "demo", Style { color: true, truecolor: false, unicode: true });
144        assert!(colour.contains('\x1b'));
145        let stripped: String = { let mut s = String::new(); let mut it = colour.chars().peekable(); while let Some(c) = it.next() { if c == '\x1b' { for d in it.by_ref() { if d == 'm' { break; } } } else { s.push(c); } } s };
146        assert_eq!(stripped, plain);
147    }
148
149    #[test]
150    fn ascii_mark_when_unicode_is_off() {
151        let r = nodes(&[("a.md", "---\nid: a\ntype: thing\n---\n")]);
152        assert!(check_text(&r, "demo", Style { color: false, truecolor: false, unicode: false }).starts_with("<> trumly check"));
153    }
154}