Skip to main content

greengate_runtime/
ui.rs

1//! The signs the hooks print.
2//!
3//! **Colour is the terminal's decision, not ours.** These used to be 256-colour
4//! codes — `38;5;112`, `38;5;160`, `38;5;208` — which live in the fixed xterm
5//! cube. A terminal theme remaps only indices 0–15; anything above renders
6//! identically whatever palette the user chose. So a carefully themed terminal
7//! was being overridden by three numbers picked years ago.
8//!
9//! The base ANSI colours ARE theme-controlled, so `32` means "whatever this
10//! terminal calls green". That is the whole fix: output follows a `vivid`
11//! palette, a Solarized profile or a high-contrast one, without reading any
12//! configuration.
13//!
14//! `LS_COLORS` is deliberately NOT consulted. It maps FILE TYPES — `di`, `ex`,
15//! `mi` — while this output needs ok/warning/error. There is no honest
16//! correspondence, and the nearest candidates are worse than nothing: under
17//! `vivid lava`, `mi` and `or` are dark grey on red, which as a foreground for
18//! `✗` is close to invisible.
19//!
20//! The earlier note here said the signs were "kept byte-identical" with the zsh
21//! originals so a user could not tell which implementation ran. That mattered
22//! during the migration and no longer does — no zsh hook remains to match.
23
24use std::sync::OnceLock;
25
26/// Base ANSI, deliberately. See the module docs.
27const GREEN: &str = "32";
28const RED: &str = "31";
29const YELLOW: &str = "33";
30
31/// Does the caller want colour at all?
32///
33/// Only when stdout — where every sign and highlighted fragment goes — is a
34/// terminal (decisions ADR-0021, `cli.output.no-color-off-terminal`): escape
35/// codes in a CI log, a file, or a string an agent captured are noise the
36/// reader has to strip. Under a git hook stdout is git's stderr, which is the
37/// terminal when a person commits. The cursor-moving region on stderr has its
38/// own gate, `live::watching`.
39///
40/// `NO_COLOR` per no-color.org: present and NON-EMPTY disables it, whatever the
41/// value. `TERM=dumb` is a terminal that cannot render SGR. `FORCE_COLOR`
42/// (non-empty, not `0` or `false`) turns colour on through a pipe, for a
43/// caller that will render it; `NO_COLOR` and `TERM=dumb` still win.
44///
45/// Read once — a hook is a short-lived process and its environment does not
46/// change underneath it.
47pub fn colors_enabled() -> bool {
48    use std::io::IsTerminal;
49    static ENABLED: OnceLock<bool> = OnceLock::new();
50    *ENABLED.get_or_init(|| {
51        wants_colour(&ColourEnv {
52            no_color: std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()),
53            dumb: std::env::var("TERM").is_ok_and(|t| t == "dumb"),
54            force: std::env::var("FORCE_COLOR").is_ok_and(|v| forces(&v)),
55            terminal: std::io::stdout().is_terminal(),
56        })
57    })
58}
59
60/// What [`colors_enabled`] decides from: read once from the environment, and
61/// passed in so the decision is testable without touching the process's.
62struct ColourEnv {
63    no_color: bool,
64    dumb: bool,
65    force: bool,
66    terminal: bool,
67}
68
69fn wants_colour(env: &ColourEnv) -> bool {
70    if env.no_color || env.dumb {
71        return false;
72    }
73    env.force || env.terminal
74}
75
76/// `FORCE_COLOR` as the ecosystem reads it: set and not empty, `0` or `false`.
77fn forces(value: &str) -> bool {
78    !matches!(value.trim(), "" | "0" | "false")
79}
80
81fn paint(text: &str, sgr: &str) -> String {
82    if colors_enabled() {
83        format!("\u{1b}[{sgr}m{text}\u{1b}[0m")
84    } else {
85        text.to_string()
86    }
87}
88
89fn sign(glyph: &str, sgr: &str) -> String {
90    format!("  {}", paint(glyph, sgr))
91}
92
93/// The glyph carries the meaning and the colour only reinforces it, so under
94/// `NO_COLOR` — and for the ~8% of men with red-green colour vision deficiency
95/// — `✓ ✗ !` stay distinguishable on their own.
96pub fn valid_sign() -> &'static str {
97    static S: OnceLock<String> = OnceLock::new();
98    S.get_or_init(|| sign("✓", GREEN))
99}
100
101pub fn error_sign() -> &'static str {
102    static S: OnceLock<String> = OnceLock::new();
103    S.get_or_init(|| sign("✗", RED))
104}
105
106pub fn warning_sign() -> &'static str {
107    static S: OnceLock<String> = OnceLock::new();
108    S.get_or_init(|| sign("!", YELLOW))
109}
110
111/// A check that never started because one before it blocked (ADR-0020).
112/// The word `skipped` always follows it, so the glyph is never the only
113/// carrier of the meaning.
114pub fn skipped_sign() -> String {
115    sign("↷", YELLOW)
116}
117
118/// Emphasise a fragment inside a message, in the terminal's own accent.
119///
120/// Sanitises what it is given, because most of what is highlighted came from
121/// somewhere else: a declared check's name, a program it wants to run, a term
122/// matched in a staged file. An escape sequence inside would also break this
123/// function's own painting — the reset it emits is no longer the last word —
124/// so this is as much about the colouring being correct as about the text
125/// being safe.
126pub fn highlight(text: &str) -> String {
127    paint(&sanitize(text), YELLOW)
128}
129
130/// Text from a repository, made safe to hand a terminal.
131///
132/// A name or a command in `amont.conf` is chosen by whoever wrote the
133/// repository, and the trust prompt exists precisely so a person can read the
134/// declarations before accepting them. `\x1b[8m` is the conceal attribute:
135/// putting it in one declaration's name HID THE NEXT ONE from that prompt, so
136/// the reader saw two declarations, pressed y, and got three. The trust model
137/// was never bypassed — the rendering lied about what was being trusted, which
138/// is the same outcome by a shorter route.
139///
140/// What is escaped, and why each:
141///   * C0 (`< 0x20`) — ESC starts every sequence; CR redraws the line; BEL,
142///     backspace and the rest are all display control. TAB becomes a single
143///     space instead, because these strings sit in aligned columns and a real
144///     tab would break the layout it is trying to preserve.
145///   * DEL and C1 (`0x80..=0x9f`) — a terminal in 8-bit mode takes `0x9b` as
146///     CSI directly, with no ESC in sight.
147///   * The bidi overrides (`U+202A..=202E`, `U+2066..=2069`) and the
148///     directional marks — "Trojan Source": they reorder what is displayed
149///     without changing a byte of what is parsed.
150///
151/// Everything else passes through untouched, including all other UTF-8 and
152/// emoji: this is a display guard, not a charset policy.
153pub fn sanitize(text: &str) -> String {
154    let mut out = String::with_capacity(text.len());
155    for c in text.chars() {
156        match c {
157            '\t' => out.push(' '),
158            c if (c as u32) < 0x20 || c == '\u{7f}' => {
159                out.push_str(&format!("\\x{:02x}", c as u32));
160            }
161            c if ('\u{80}'..='\u{9f}').contains(&c) => {
162                out.push_str(&format!("\\x{:02x}", c as u32));
163            }
164            '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' => {
165                out.push_str(&format!("\\u{{{:04x}}}", c as u32));
166            }
167            c => out.push(c),
168        }
169    }
170    out
171}
172
173/// The same, for a path that came off a walk of somebody's disk.
174///
175/// `Path::display()` does not escape control bytes, and the fleet prints paths
176/// it found by scanning directories it does not own.
177pub fn sanitize_path(p: &std::path::Path) -> String {
178    sanitize(&p.display().to_string())
179}
180
181#[cfg(test)]
182mod tests {
183    use super::{forces, wants_colour, ColourEnv};
184
185    fn env(no_color: bool, dumb: bool, force: bool, terminal: bool) -> ColourEnv {
186        ColourEnv {
187            no_color,
188            dumb,
189            force,
190            terminal,
191        }
192    }
193
194    /// Colour only on a terminal, or when the caller forces it; the off
195    /// switches win over the force.
196    #[test]
197    fn colour_follows_the_terminal_and_the_switches() {
198        assert!(wants_colour(&env(false, false, false, true)), "a terminal");
199        assert!(!wants_colour(&env(false, false, false, false)), "a pipe");
200        assert!(
201            wants_colour(&env(false, false, true, false)),
202            "forced through a pipe"
203        );
204        assert!(
205            !wants_colour(&env(true, false, true, true)),
206            "NO_COLOR beats force"
207        );
208        assert!(
209            !wants_colour(&env(false, true, true, true)),
210            "TERM=dumb beats force"
211        );
212    }
213
214    #[test]
215    fn force_color_values() {
216        for on in ["1", "2", "3", "true", "always"] {
217            assert!(forces(on), "{on}");
218        }
219        for off in ["", "0", "false", " 0 "] {
220            assert!(!forces(off), "{off:?}");
221        }
222    }
223
224    use super::*;
225
226    /// Every byte a terminal would act on, and nothing else.
227    #[test]
228    fn sanitize_escapes_what_a_terminal_would_obey() {
229        // The one that hid a declaration from the trust prompt.
230        assert_eq!(sanitize("a\u{1b}[8mb"), "a\\x1b[8mb");
231        assert_eq!(sanitize("bell\u{7}"), "bell\\x07");
232        assert_eq!(sanitize("cr\r"), "cr\\x0d");
233        assert_eq!(sanitize("del\u{7f}"), "del\\x7f");
234        // 8-bit CSI: no ESC in sight.
235        assert_eq!(sanitize("csi\u{9b}"), "csi\\x9b");
236        // Trojan Source.
237        assert_eq!(sanitize("rtl\u{202e}"), "rtl\\u{202e}");
238        assert_eq!(sanitize("iso\u{2066}"), "iso\\u{2066}");
239        // A tab keeps its width without keeping its behaviour.
240        assert_eq!(sanitize("a\tb"), "a b");
241    }
242
243    /// It is a display guard, not a charset policy.
244    #[test]
245    fn sanitize_leaves_ordinary_text_alone() {
246        for s in ["plain ascii", "café", "日本語", "✓ ✗ !", "a/b-c_d.e", "🐛"] {
247            assert_eq!(sanitize(s), s, "{s:?} should pass through");
248        }
249    }
250
251    /// `highlight` wraps text in its own escapes, so text that carries an
252    /// escape of its own would break the wrapping as well as the reader.
253    #[test]
254    fn highlight_emits_only_its_own_escapes() {
255        let out = highlight("a\u{1b}[0m\u{1b}[8mb");
256        let escapes = out.matches('\u{1b}').count();
257        // Either colour is off (0) or it is exactly the pair this function
258        // writes — never the ones that came in with the text.
259        assert!(
260            escapes == 0 || escapes == 2,
261            "{out:?} has {escapes} escapes"
262        );
263        // The `[8m` TEXT survives, harmlessly — what must not survive is the
264        // ESC that would make a terminal read it as a command.
265        assert!(
266            !out.contains("\u{1b}[8m"),
267            "a conceal sequence survived: {out:?}"
268        );
269        assert!(
270            !out.contains("\u{1b}[0m\u{1b}[8m"),
271            "an injected reset survived: {out:?}"
272        );
273    }
274
275    /// The point of the change: nothing emits a code above 15, because those
276    /// ignore the terminal's palette entirely.
277    #[test]
278    fn no_sign_uses_the_fixed_256_colour_cube() {
279        for s in [valid_sign(), error_sign(), warning_sign()] {
280            assert!(
281                !s.contains("38;5;"),
282                "a 256-colour code overrides the user's theme: {s:?}"
283            );
284        }
285    }
286
287    #[test]
288    fn signs_carry_a_distinct_glyph_not_only_a_colour() {
289        assert!(valid_sign().contains('✓'));
290        assert!(error_sign().contains('✗'));
291        assert!(warning_sign().contains('!'));
292    }
293
294    /// No source file may emit a 256-colour escape directly.
295    ///
296    /// The migration to base ANSI converted the sign helpers but missed a raw
297    /// `\u{1b}[38;5;208m` in the pre-push error line, which therefore ignored
298    /// the terminal theme for two more PRs. Checking the helpers was not enough
299    /// because the offender did not use them.
300    #[test]
301    fn no_source_file_emits_a_256_colour_escape() {
302        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src");
303        let mut offenders = Vec::new();
304        fn walk(d: &std::path::Path, out: &mut Vec<String>) {
305            for e in std::fs::read_dir(d).expect("src").flatten() {
306                let p = e.path();
307                if p.is_dir() {
308                    walk(&p, out);
309                } else if p.extension().is_some_and(|x| x == "rs") {
310                    for (i, line) in std::fs::read_to_string(&p)
311                        .unwrap_or_default()
312                        .lines()
313                        .enumerate()
314                    {
315                        let mentions_the_pattern =
316                            line.contains("offenders") || line.trim_start().starts_with("//");
317                        if mentions_the_pattern {
318                            continue;
319                        }
320                        // Split so this line is not itself an offender.
321                        if line.contains(concat!("[38", ";5;")) {
322                            out.push(format!("{}:{}", p.display(), i + 1));
323                        }
324                    }
325                }
326            }
327        }
328        walk(std::path::Path::new(dir), &mut offenders);
329        assert!(
330            offenders.is_empty(),
331            "a fixed 256-colour code overrides the user's terminal theme: {offenders:?}"
332        );
333    }
334
335    /// A success glyph must never be painted with the warning accent.
336    ///
337    /// The mechanical rewrite from 256-colour codes turned `color("✓", "112")`
338    /// into `highlight("✓")` in two places, which renders a tick in the warning
339    /// colour — the kind of damage a regex does quietly. Sign glyphs belong to
340    /// the sign functions; `highlight` is for emphasising words.
341    #[test]
342    fn glyphs_are_not_routed_through_highlight() {
343        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src");
344        let mut offenders = Vec::new();
345        fn walk(d: &std::path::Path, out: &mut Vec<String>) {
346            for e in std::fs::read_dir(d).expect("src").flatten() {
347                let p = e.path();
348                if p.is_dir() {
349                    walk(&p, out);
350                } else if p.extension().is_some_and(|x| x == "rs") {
351                    let body = std::fs::read_to_string(&p).unwrap_or_default();
352                    for (i, line) in body.lines().enumerate() {
353                        let is_test_or_doc =
354                            line.trim_start().starts_with("//") || line.contains("offenders");
355                        if is_test_or_doc {
356                            continue;
357                        }
358                        for g in ["\\u{2713}", "\\u{2717}", "✓", "✗"] {
359                            if line.contains("highlight(") && line.contains(g) {
360                                out.push(format!("{}:{}", p.display(), i + 1));
361                            }
362                        }
363                    }
364                }
365            }
366        }
367        walk(std::path::Path::new(dir), &mut offenders);
368        assert!(
369            offenders.is_empty(),
370            "a status glyph is being painted as emphasis: {offenders:?}"
371        );
372    }
373
374    /// `colors_enabled` memoises, so the predicate is tested directly rather
375    /// than through a cache whichever test happens to fill first.
376    #[test]
377    fn no_color_is_honoured_per_the_standard() {
378        fn decide(no_color: Option<&str>, term: &str) -> bool {
379            let nc = no_color.map(|v| !v.is_empty()).unwrap_or(false);
380            !nc && term != "dumb"
381        }
382        assert!(decide(None, "xterm-256color"), "colour by default");
383        assert!(!decide(Some("1"), "xterm-256color"), "any value disables");
384        assert!(!decide(Some("0"), "xterm-256color"), "even \"0\" disables");
385        assert!(
386            decide(Some(""), "xterm-256color"),
387            "an EMPTY value does NOT disable — no-color.org is explicit"
388        );
389        assert!(!decide(None, "dumb"), "a dumb terminal cannot render SGR");
390    }
391}