Skip to main content

bynk_driver/
colour.rs

1//! When the driver's human output is coloured, and the few styles it uses.
2//!
3//! One decision for the whole process, set once from the global `--color`
4//! (alias `--colour`) flag: `auto` (the default), `always` or `never`. Under
5//! `auto` a stream is coloured when it is a terminal, or when `FORCE_COLOR` or
6//! `CLICOLOR_FORCE` asks for colour without one, and never when `NO_COLOR` is
7//! set (`allowed` has the exact rules). `always` and `never` override the
8//! terminal check and the environment alike.
9//!
10//! The palette has one meaning per colour: blue for information, green for
11//! success, red for an error or a failure, amber for a warning, and bold for a
12//! heading.
13//!
14//! Machine-readable output (`--format json`, `ndjson`, and `bynk check`'s and
15//! `bynk doctor`'s `short`) is never coloured, whatever the choice: only the
16//! human renderings ask this module.
17
18use std::io::IsTerminal;
19use std::sync::atomic::{AtomicU8, Ordering};
20
21/// `--color <WHEN>`: when to colour the driver's human output.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
23pub enum ColourChoice {
24    /// Colour a terminal, unless `NO_COLOR` is set; `FORCE_COLOR` or
25    /// `CLICOLOR_FORCE` colours one that isn't.
26    #[default]
27    Auto,
28    /// Always colour, even into a pipe or a file.
29    Always,
30    /// Never colour.
31    Never,
32}
33
34impl ColourChoice {
35    /// clap's own choice for the same setting, for its help and errors.
36    pub fn clap(self) -> clap::ColorChoice {
37        match self {
38            ColourChoice::Auto => clap::ColorChoice::Auto,
39            ColourChoice::Always => clap::ColorChoice::Always,
40            ColourChoice::Never => clap::ColorChoice::Never,
41        }
42    }
43
44    /// The choice named by `--color`/`--colour` in `args` (the process's
45    /// arguments, program name first), if one is given before a `--`. For
46    /// clap's own help and errors, which are rendered while the arguments are
47    /// parsed, so before [`set_choice`] can run. An unknown value is left for
48    /// clap to report.
49    pub fn from_args<I, S>(args: I) -> Option<ColourChoice>
50    where
51        I: IntoIterator<Item = S>,
52        S: AsRef<std::ffi::OsStr>,
53    {
54        use clap::ValueEnum;
55        let mut found = None;
56        let mut args = args.into_iter().skip(1);
57        while let Some(arg) = args.next() {
58            let Some(arg) = arg.as_ref().to_str() else {
59                continue;
60            };
61            if arg == "--" {
62                break;
63            }
64            let value = match arg.split_once('=') {
65                Some(("--color" | "--colour", value)) => value.to_string(),
66                None if arg == "--color" || arg == "--colour" => {
67                    match args
68                        .next()
69                        .and_then(|v| v.as_ref().to_str().map(str::to_string))
70                    {
71                        Some(value) => value,
72                        None => break,
73                    }
74                }
75                _ => continue,
76            };
77            // The last one wins, as it does for clap.
78            if let Ok(choice) = ColourChoice::from_str(&value, true) {
79                found = Some(choice);
80            }
81        }
82        found
83    }
84}
85
86static CHOICE: AtomicU8 = AtomicU8::new(0);
87
88/// Set this process's choice (from `--color`). Until it is called the choice
89/// is [`ColourChoice::Auto`].
90pub fn set_choice(choice: ColourChoice) {
91    CHOICE.store(choice as u8, Ordering::Relaxed);
92}
93
94/// This process's choice.
95pub fn choice() -> ColourChoice {
96    match CHOICE.load(Ordering::Relaxed) {
97        1 => ColourChoice::Always,
98        2 => ColourChoice::Never,
99        _ => ColourChoice::Auto,
100    }
101}
102
103/// Whether human output on stdout is coloured.
104pub fn stdout() -> bool {
105    resolve(choice(), || std::io::stdout().is_terminal())
106}
107
108/// Whether human output on stderr is coloured.
109pub fn stderr() -> bool {
110    resolve(choice(), || std::io::stderr().is_terminal())
111}
112
113fn resolve(choice: ColourChoice, is_terminal: impl FnOnce() -> bool) -> bool {
114    match choice {
115        ColourChoice::Always => true,
116        ColourChoice::Never => false,
117        ColourChoice::Auto => allowed(is_terminal(), |name| std::env::var_os(name)),
118    }
119}
120
121/// Make a child process (a `wrangler`) whose output reaches the user colour
122/// as we do: under `never`, `NO_COLOR` set and `FORCE_COLOR` taken away;
123/// under `always`, the reverse. Under `auto` the child decides for itself,
124/// unless its output is `piped` through us, where it can no longer see our
125/// terminal: then `FORCE_COLOR` when we would colour stderr.
126pub fn apply_to_child(cmd: &mut std::process::Command, piped: bool) {
127    match choice() {
128        ColourChoice::Never => {
129            cmd.env_remove("FORCE_COLOR").env("NO_COLOR", "1");
130        }
131        ColourChoice::Always => {
132            cmd.env_remove("NO_COLOR").env("FORCE_COLOR", "1");
133        }
134        ColourChoice::Auto => {
135            if piped && stderr() {
136                cmd.env("FORCE_COLOR", "1");
137            }
138        }
139    }
140}
141
142/// #1666: under `auto`, colour needs a terminal, and `NO_COLOR` set to
143/// anything but the empty string (<https://no-color.org>) turns it off. Colour
144/// piped into a file or a CI log is noise.
145///
146/// #1777: `FORCE_COLOR` (<https://force-color.org>) or `CLICOLOR_FORCE`
147/// (<https://bixense.com/clicolors/>), set to anything but the empty string or
148/// `0`, turns colour on without a terminal, for `less -R` or a CI log that
149/// renders ANSI. `0` means "don't force", not "force off": `NO_COLOR` is the
150/// off switch, and it wins over both. That is clap's order for `NO_COLOR` and
151/// `CLICOLOR_FORCE`; clap doesn't read `FORCE_COLOR`, so only
152/// `CLICOLOR_FORCE` also colours clap's own help and errors.
153pub(crate) fn allowed(is_terminal: bool, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
154    let set = |name| var(name).is_some_and(|v| !v.is_empty());
155    let forced = |name| var(name).is_some_and(|v| !v.is_empty() && v != "0");
156    if set("NO_COLOR") {
157        false
158    } else {
159        is_terminal || forced("FORCE_COLOR") || forced("CLICOLOR_FORCE")
160    }
161}
162
163/// A style the driver paints text in: one meaning per colour.
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub enum Style {
166    /// Information: a `note:`, a mutant that didn't compile.
167    Blue,
168    /// Success: a pass, a killed mutant, a check that passed.
169    Green,
170    /// A warning: partial coverage, a mutant no suite reaches.
171    Amber,
172    /// An error or a failure: a failing case, a surviving mutant, a refusal.
173    Red,
174    /// A heading.
175    Bold,
176    /// Detail the eye can skip.
177    Dim,
178}
179
180impl Style {
181    fn codes(self) -> (&'static str, &'static str) {
182        match self {
183            Style::Blue => ("\x1b[34m", "\x1b[39m"),
184            Style::Green => ("\x1b[32m", "\x1b[39m"),
185            Style::Amber => ("\x1b[33m", "\x1b[39m"),
186            Style::Red => ("\x1b[31m", "\x1b[39m"),
187            Style::Bold => ("\x1b[1m", "\x1b[22m"),
188            Style::Dim => ("\x1b[2m", "\x1b[22m"),
189        }
190    }
191}
192
193/// `text` in `style` when `on`, otherwise `text` unchanged.
194pub fn paint(on: bool, style: Style, text: &str) -> String {
195    if on {
196        let (open, close) = style.codes();
197        format!("{open}{text}{close}")
198    } else {
199        text.to_string()
200    }
201}
202
203/// `bynk test`'s human output (the runner's, as it is forwarded), coloured a
204/// line at a time: a passing case's `✓` green, a failing case red, a suite
205/// heading bold, a detached effect's report yellow, and the closing tally's
206/// counts green and, when any failed, red. Any other line passes through as
207/// it is. A heading is a line the runner starts after a blank one (each
208/// suite's results end with one, and `Running tests...` with two), so a
209/// test's own `console.log("Response:")` mid-suite is not taken for one.
210#[derive(Debug, Default)]
211pub struct TestLines {
212    /// The line before was blank (or this is the first line).
213    after_blank: bool,
214}
215
216impl TestLines {
217    /// `line` coloured, its own end (`\n`, `\r\n` or none) kept.
218    pub fn paint(&mut self, line: &str) -> String {
219        let (body, end) = split_end(line);
220        let after_blank = std::mem::replace(&mut self.after_blank, body.is_empty());
221        let styled = if let Some(name) = body.strip_prefix("  \u{2713} ") {
222            format!("  {} {name}", paint(true, Style::Green, "\u{2713}"))
223        } else if body.starts_with("  \u{2717} ") {
224            paint(true, Style::Red, body)
225        } else if body.starts_with("    ! ") {
226            paint(true, Style::Amber, body)
227        } else if let Some(tally) = tally(body) {
228            tally
229        } else if after_blank && !body.starts_with(' ') && body.ends_with(':') {
230            paint(true, Style::Bold, body)
231        } else {
232            return line.to_string();
233        };
234        format!("{styled}{end}")
235    }
236}
237
238/// The runner's closing `<n> passed, <m> failed.`, coloured.
239fn tally(body: &str) -> Option<String> {
240    let (passed, rest) = body.split_once(" passed, ")?;
241    let failed = rest.strip_suffix(" failed.")?;
242    let p: u64 = passed.parse().ok()?;
243    let f: u64 = failed.parse().ok()?;
244    let passed = format!("{p} passed");
245    let failed = format!("{f} failed");
246    Some(format!(
247        "{}, {}.",
248        if p > 0 && f == 0 {
249            paint(true, Style::Green, &passed)
250        } else {
251            passed
252        },
253        if f > 0 {
254            paint(true, Style::Red, &failed)
255        } else {
256            paint(true, Style::Dim, &failed)
257        },
258    ))
259}
260
261fn split_end(line: &str) -> (&str, &str) {
262    if let Some(body) = line.strip_suffix("\r\n") {
263        (body, "\r\n")
264    } else if let Some(body) = line.strip_suffix('\n') {
265        (body, "\n")
266    } else {
267        (line, "")
268    }
269}
270
271/// A message for stderr (`bynk: warning: …`), with its `error:`, `warning:`
272/// or `note:` label red, amber or blue: the first such label on each line,
273/// whether it opens the line (after any indent or `= `) or follows the
274/// `bynk …:` or `<program> …:` that names who is speaking. Nothing else
275/// changes, so a line with no label is returned as it is.
276pub fn message(text: &str) -> String {
277    text.split_inclusive('\n').map(message_line).collect()
278}
279
280const LABELS: [(&str, Style); 3] = [
281    ("error:", Style::Red),
282    ("warning:", Style::Amber),
283    ("note:", Style::Blue),
284];
285
286fn message_line(line: &str) -> String {
287    // Where a label may start: after the indent and any `= `, and after each
288    // `<speaker>: ` that opens the line, such as `bynk dev: `.
289    let mut at = line.len() - line.trim_start().len();
290    if line[at..].starts_with("= ") {
291        at += 2;
292    }
293    let mut starts = vec![at];
294    while let Some(colon) = line[at..].find(": ") {
295        if !is_speaker(&line[at..at + colon]) {
296            break;
297        }
298        at += colon + 2;
299        starts.push(at);
300    }
301    for start in starts {
302        for (label, style) in LABELS {
303            if let Some(end) = label_end(&line[start..], label) {
304                let (label, end) = (&line[start..start + end], start + end);
305                return format!(
306                    "{}{}{}",
307                    &line[..start],
308                    paint(true, style, label),
309                    &line[end..]
310                );
311            }
312        }
313    }
314    line.to_string()
315}
316
317/// Where `label` (`error:`) ends at the start of `text`, also in its coded
318/// form, `error[bynk.fetch.status]:`, as the registry and fetch errors have it.
319fn label_end(text: &str, label: &str) -> Option<usize> {
320    if text.starts_with(label) {
321        return Some(label.len());
322    }
323    let word = label.trim_end_matches(':');
324    let code = text.strip_prefix(word)?.strip_prefix('[')?;
325    let close = code.find("]:")?;
326    let plain = |c: char| c.is_ascii_alphanumeric() || "._-".contains(c);
327    (close > 0 && code[..close].chars().all(plain)).then_some(word.len() + 1 + close + 2)
328}
329
330/// A few plain words naming who speaks (`bynk`, `bynk dev`, `bynk test
331/// --coverage`, or a workspace member, `packages/ok`), and never a label
332/// itself.
333fn is_speaker(text: &str) -> bool {
334    !text.is_empty()
335        && text.len() <= 40
336        && !LABELS.iter().any(|(l, _)| l.trim_end_matches(':') == text)
337        && text
338            .chars()
339            .all(|c| c.is_ascii_alphanumeric() || " -_./".contains(c))
340}
341
342/// `text` for stderr: its labels coloured as [`message`] does when stderr is
343/// coloured, and unchanged when it isn't.
344pub fn stderr_message(text: &str) -> String {
345    if stderr() {
346        message(text)
347    } else {
348        text.to_string()
349    }
350}
351
352/// Print `text` and a newline to stderr, as [`stderr_message`] has it. What
353/// [`emsg!`](crate::emsg) expands to.
354pub fn eprint_message(text: &str) {
355    eprintln!("{}", stderr_message(text));
356}
357
358/// `eprint!("{text}")`, coloured as [`stderr_message`] has it.
359pub fn eprint(text: &str) {
360    eprint!("{}", stderr_message(text));
361}
362
363/// `eprintln!("{text}")`, coloured as [`stderr_message`] has it.
364pub fn eprintln(text: &str) {
365    eprint_message(text);
366}
367
368/// `eprintln!` for a message with an `error:`, `warning:` or `note:` label,
369/// coloured as [`colour::message`](crate::colour::message) does when stderr is.
370#[macro_export]
371macro_rules! emsg {
372    ($($arg:tt)*) => {
373        $crate::colour::eprint_message(&format!($($arg)*))
374    };
375}
376
377/// The style for a coverage percentage: green from 80%, yellow (amber) from
378/// 50%, red below.
379pub fn coverage_style(percent: u32) -> Style {
380    match percent {
381        80.. => Style::Green,
382        50.. => Style::Amber,
383        _ => Style::Red,
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    /// #1666: colour needs a terminal, and `NO_COLOR` set to anything but
392    /// the empty string turns it off. #1777: `FORCE_COLOR` or
393    /// `CLICOLOR_FORCE`, set to anything but the empty string or `0`, turns
394    /// it on without one; `NO_COLOR` wins over both.
395    #[test]
396    fn auto_needs_a_terminal_or_a_force_and_no_no_color() {
397        use std::ffi::OsString;
398        let allowed = |is_terminal, vars: &[(&str, &str)]| {
399            allowed(is_terminal, |name| {
400                vars.iter()
401                    .find(|(n, _)| *n == name)
402                    .map(|(_, v)| OsString::from(v))
403            })
404        };
405        assert!(allowed(true, &[]));
406        assert!(allowed(true, &[("NO_COLOR", "")]));
407        assert!(!allowed(true, &[("NO_COLOR", "1")]));
408        assert!(!allowed(false, &[]));
409        assert!(!allowed(false, &[("NO_COLOR", "")]));
410
411        for force in ["FORCE_COLOR", "CLICOLOR_FORCE"] {
412            assert!(allowed(false, &[(force, "1")]), "{force}=1");
413            assert!(allowed(false, &[(force, "true")]), "{force}=true");
414            assert!(!allowed(false, &[(force, "")]), "{force}= is unset");
415            assert!(!allowed(false, &[(force, "0")]), "{force}=0 doesn't force");
416            assert!(allowed(true, &[(force, "0")]), "{force}=0 doesn't forbid");
417            assert!(allowed(false, &[(force, "1"), ("NO_COLOR", "")]));
418            assert!(!allowed(false, &[(force, "1"), ("NO_COLOR", "1")]));
419            assert!(!allowed(true, &[(force, "1"), ("NO_COLOR", "1")]));
420        }
421    }
422
423    #[test]
424    fn always_and_never_ignore_the_terminal() {
425        assert!(resolve(ColourChoice::Always, || false));
426        assert!(!resolve(ColourChoice::Never, || true));
427    }
428
429    #[test]
430    fn the_flag_is_found_in_either_spelling_and_the_last_wins() {
431        let find = |args: &[&str]| ColourChoice::from_args(args);
432        assert_eq!(find(&["bynk", "test"]), None);
433        assert_eq!(
434            find(&["bynk", "--color", "never", "test"]),
435            Some(ColourChoice::Never)
436        );
437        assert_eq!(
438            find(&["bynk", "test", "--colour=always"]),
439            Some(ColourChoice::Always)
440        );
441        assert_eq!(
442            find(&["bynk", "--color=never", "test", "--colour", "auto"]),
443            Some(ColourChoice::Auto)
444        );
445        // After `--` it belongs to wrangler; an unknown value is clap's to report.
446        assert_eq!(find(&["bynk", "dev", "--", "--color=never"]), None);
447        assert_eq!(find(&["bynk", "--color=sometimes"]), None);
448        assert_eq!(find(&["bynk", "--color"]), None);
449    }
450
451    /// Each line as the runner would print it, after a blank one.
452    fn test_line(line: &str) -> String {
453        TestLines { after_blank: true }.paint(line)
454    }
455
456    #[test]
457    fn a_heading_follows_a_blank_line() {
458        let mut lines = TestLines::default();
459        let out: Vec<String> = [
460            "Running tests...\n",
461            "\n",
462            "orders:\n",
463            "Response:\n",
464            "  \u{2713} adds\n",
465            "\n",
466            "billing:\n",
467        ]
468        .iter()
469        .map(|l| lines.paint(l))
470        .collect();
471        assert_eq!(out[2], "\x1b[1morders:\x1b[22m\n");
472        assert_eq!(out[3], "Response:\n", "a test's own output is left alone");
473        assert_eq!(out[6], "\x1b[1mbilling:\x1b[22m\n");
474    }
475
476    #[test]
477    fn test_lines_are_coloured_by_outcome() {
478        assert_eq!(
479            test_line("  \u{2713} adds\n"),
480            "  \x1b[32m\u{2713}\x1b[39m adds\n"
481        );
482        assert_eq!(
483            test_line("  \u{2717} subtracts\n"),
484            "\x1b[31m  \u{2717} subtracts\x1b[39m\n"
485        );
486        assert_eq!(test_line("orders:\n"), "\x1b[1morders:\x1b[22m\n");
487        assert_eq!(
488            test_line("3 passed, 0 failed.\n"),
489            "\x1b[32m3 passed\x1b[39m, \x1b[2m0 failed\x1b[22m.\n"
490        );
491        assert_eq!(
492            test_line("3 passed, 1 failed."),
493            "3 passed, \x1b[31m1 failed\x1b[39m."
494        );
495        // Anything else passes through untouched.
496        for line in [
497            "Running tests...\n",
498            "\n",
499            "    expected 1, got 2\n",
500            "a passed, b failed.\n",
501        ] {
502            assert_eq!(test_line(line), line);
503        }
504    }
505
506    #[test]
507    fn a_message_label_is_coloured_where_it_stands() {
508        let red = |l: &str| format!("\x1b[31m{l}\x1b[39m");
509        let amber = |l: &str| format!("\x1b[33m{l}\x1b[39m");
510        let blue = |l: &str| format!("\x1b[34m{l}\x1b[39m");
511        assert_eq!(
512            message("bynk: warning: kept it"),
513            format!("bynk: {} kept it", amber("warning:"))
514        );
515        assert_eq!(
516            message("bynk test: error: no tests found in x"),
517            format!("bynk test: {} no tests found in x", red("error:"))
518        );
519        assert_eq!(
520            message("bynk dev: note: `a.sql` changed"),
521            format!("bynk dev: {} `a.sql` changed", blue("note:"))
522        );
523        assert_eq!(
524            message("first\n  = note: the token came from X\n  note: y\nwarning: z"),
525            format!(
526                "first\n  = {} the token came from X\n  {} y\n{} z",
527                blue("note:"),
528                blue("note:"),
529                amber("warning:")
530            )
531        );
532        // Only the first label, and only where a label can stand.
533        assert_eq!(
534            message("bynk: warning: x said error: y"),
535            format!("bynk: {} x said error: y", amber("warning:"))
536        );
537        // A workspace member speaks after `bynk:`, as a path.
538        assert_eq!(
539            message("bynk: packages/ok: error: no member"),
540            format!("bynk: packages/ok: {} no member", red("error:"))
541        );
542        // The coded form takes the colour too, code and all.
543        assert_eq!(
544            message("bynk: error[bynk.fetch.status]: 404 from x"),
545            format!("bynk: {} 404 from x", red("error[bynk.fetch.status]:"))
546        );
547        for plain in [
548            "bynk: error[]: empty code",
549            "bynk: error[a b]: a space",
550            "bynk: signed out of `acme`",
551            "bynk: could not read `a: b`: error: no",
552            "",
553        ] {
554            assert_eq!(message(plain), plain);
555        }
556    }
557
558    #[test]
559    fn coverage_is_red_amber_green() {
560        assert_eq!(coverage_style(100), Style::Green);
561        assert_eq!(coverage_style(80), Style::Green);
562        assert_eq!(coverage_style(79), Style::Amber);
563        assert_eq!(coverage_style(50), Style::Amber);
564        assert_eq!(coverage_style(49), Style::Red);
565        assert_eq!(coverage_style(0), Style::Red);
566    }
567
568    #[test]
569    fn paint_off_is_plain() {
570        assert_eq!(paint(false, Style::Red, "x"), "x");
571        assert_eq!(paint(true, Style::Red, "x"), "\x1b[31mx\x1b[39m");
572    }
573}