Skip to main content

cuno_core/
shell.rs

1//! Writing what cuno shows the user: errors, warnings, help and status lines,
2//! in color or not. See `docs/en/specs/commands.md`, "Output".
3
4use std::borrow::Cow;
5use std::fmt::Display;
6use std::io::Write;
7
8use crate::Env;
9
10/// A color choice given with `--color` or `[term] color`
11/// (`docs/en/specs/commands.md`).
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum ColorChoice {
14    /// Color only when writing to a terminal.
15    Auto,
16    /// Always color.
17    Always,
18    /// Never color.
19    Never,
20}
21
22const RESET: &str = "\x1b[0m";
23const BOLD_RED: &str = "\x1b[1;31m";
24const BOLD_YELLOW: &str = "\x1b[1;33m";
25const BOLD_CYAN: &str = "\x1b[1;36m";
26const BOLD_GREEN: &str = "\x1b[1;32m";
27
28/// Whether to color: `--color` (`given`), then `[term] color`
29/// (`configured`), then `NO_COLOR` (`no_color`, set to anything, even
30/// empty), then whether the output is a `terminal`. The one place this
31/// order is written; see `docs/en/specs/commands.md`, "Available for all
32/// commands".
33pub fn colors(
34    given: Option<ColorChoice>,
35    configured: Option<ColorChoice>,
36    no_color: bool,
37    terminal: bool,
38) -> bool {
39    match given.or(configured) {
40        Some(ColorChoice::Always) => true,
41        Some(ColorChoice::Never) => false,
42        Some(ColorChoice::Auto) => terminal,
43        None => terminal && !no_color,
44    }
45}
46
47/// How much a command shows: `-q`, nothing given, or `-v` (or
48/// `[term] verbose`, which `-q` still wins over). One value, so quiet and
49/// verbose cannot both be in effect (`docs/en/specs/commands.md`,
50/// "Available for all commands").
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
52pub enum Verbosity {
53    /// `-q`: status lines are left out.
54    Quiet,
55    /// What every command shows by default.
56    #[default]
57    Normal,
58    /// `-v` or `[term] verbose`: also each step's command.
59    Verbose,
60}
61
62/// Where cuno's messages go (stderr for the binary). Crates write through a
63/// `Shell` instead of printing, so the color decision is made once.
64pub struct Shell {
65    out: Box<dyn Write>,
66    /// `--color`, when given.
67    given: Option<ColorChoice>,
68    /// Whether `NO_COLOR` is set, even to nothing.
69    no_color: bool,
70    /// Whether `out` is a terminal.
71    terminal: bool,
72    color: bool,
73    verbosity: Verbosity,
74}
75
76impl Shell {
77    /// A shell writing to `out`. `choice` is the color choice the user gave,
78    /// or `None` when they gave none; `out_is_terminal` says whether `out` is
79    /// a terminal.
80    ///
81    /// With no choice given, `NO_COLOR` (set to anything, including empty)
82    /// means no color, and otherwise color follows the terminal. A choice the
83    /// user gave always wins over `NO_COLOR`, including an explicit `auto`.
84    /// [`Shell::configure`] adds `[term] color` once it is read. See
85    /// `docs/en/specs/commands.md`, "Available for all commands".
86    pub fn new(
87        out: Box<dyn Write>,
88        choice: Option<ColorChoice>,
89        env: &Env,
90        out_is_terminal: bool,
91    ) -> Shell {
92        let mut shell = Shell {
93            out,
94            given: choice,
95            no_color: env.get("NO_COLOR").is_some(),
96            terminal: out_is_terminal,
97            color: false,
98            verbosity: Verbosity::Normal,
99        };
100        shell.configure(None, false);
101        shell
102    }
103
104    /// Applies `[term]`, which is read after the shell is made: `color`
105    /// ranks below `--color` and above `NO_COLOR`, and `verbose` makes the
106    /// shell verbose unless `-q` or `-v` already decided.
107    pub fn configure(&mut self, configured: Option<ColorChoice>, verbose: bool) {
108        self.color = colors(self.given, configured, self.no_color, self.terminal);
109        if verbose && self.verbosity == Verbosity::Normal {
110            self.verbosity = Verbosity::Verbose;
111        }
112    }
113
114    /// Applies `-q` or `-v`, once, before anything is written. Quiet, a
115    /// [`Shell::status`] line writes nothing, and errors, warnings, help and
116    /// other programs' output are written as before
117    /// (`docs/en/specs/commands.md`, "Available for all commands").
118    pub fn set_verbosity(&mut self, verbosity: Verbosity) {
119        self.verbosity = verbosity;
120    }
121
122    /// Whether to show what only `-v` shows, such as each step's command.
123    pub fn verbose(&self) -> bool {
124        self.verbosity == Verbosity::Verbose
125    }
126
127    /// Whether this shell writes color escape codes.
128    pub fn uses_color(&self) -> bool {
129        self.color
130    }
131
132    /// `error: <message>`.
133    pub fn error(&mut self, message: impl Display) {
134        self.line(BOLD_RED, "error", message);
135    }
136
137    /// `warning: <message>`.
138    pub fn warning(&mut self, message: impl Display) {
139        self.line(BOLD_YELLOW, "warning", message);
140    }
141
142    /// `help: <message>`, how to fix what the previous line reported.
143    pub fn help(&mut self, message: impl Display) {
144        self.line(BOLD_CYAN, "help", message);
145    }
146
147    /// A status line: `verb` right-aligned in 12 columns, then `message`, as
148    /// in `   Compiling mygame v0.1.0`. Nothing under `-q`
149    /// ([`Shell::set_verbosity`]).
150    pub fn status(&mut self, verb: &str, message: impl Display) {
151        if self.verbosity == Verbosity::Quiet {
152            return;
153        }
154        let verb = self.paint(BOLD_GREEN, &format!("{verb:>12}"));
155        let message = message.to_string();
156        let message = escaped_text(&message);
157        self.write(format_args!("{verb} {message}"));
158    }
159
160    /// `bytes` written as they are, nothing escaped: for text cuno wrote
161    /// itself, and for the output of a program the user asked cuno to run
162    /// (`cuno test`, `cuno run`), which can reach the terminal directly
163    /// anyway. A tool's output goes through [`Shell::tool_output`]
164    /// (`docs/en/specs/commands.md`, "Format").
165    pub fn raw(&mut self, bytes: &[u8]) {
166        // A failed write to stderr cannot be reported anywhere better.
167        let _ = self.out.write_all(bytes);
168        let _ = self.out.flush();
169    }
170
171    /// The output of a tool cuno ran (a compiler, a linker, clang-tidy),
172    /// written as it was produced, not decoded, so text in the console's
173    /// code page reaches the console as such, but with the control
174    /// characters it holds shown escaped. Its color sequences pass only when
175    /// `asked`, cuno having asked that tool for color; any other tool's
176    /// are a project's text (`docs/en/specs/commands.md`, "Format").
177    pub fn tool_output(&mut self, bytes: &[u8], asked: bool) {
178        let shown = escaped(bytes, asked && self.color);
179        self.raw(&shown);
180    }
181
182    fn line(&mut self, style: &str, label: &str, message: impl Display) {
183        let label = self.paint(style, label);
184        // Formatted first, so the whole message is scanned for control
185        // characters before anything is written.
186        let message = message.to_string();
187        let message = escaped_text(&message);
188        self.write(format_args!("{label}: {message}"));
189    }
190
191    fn write(&mut self, line: std::fmt::Arguments<'_>) {
192        // A failed write to stderr cannot be reported anywhere better.
193        let _ = writeln!(self.out, "{line}");
194    }
195
196    fn paint(&self, style: &str, text: &str) -> String {
197        if self.color {
198            format!("{style}{text}{RESET}")
199        } else {
200            text.to_owned()
201        }
202    }
203}
204
205/// `bytes`, another program's output, with every C0 control character and
206/// DEL written as `\xNN`, except a newline, a tab, a CR right before a
207/// newline, and, when `color`, a color sequence ([`color_sequence`]).
208/// Judged byte by byte, so text in a code page such as CP932, whose
209/// two-byte characters never use these bytes, passes unchanged
210/// (`docs/en/specs/commands.md`, "Format").
211fn escaped(bytes: &[u8], color: bool) -> Vec<u8> {
212    let mut out = Vec::with_capacity(bytes.len());
213    let mut i = 0;
214    while i < bytes.len() {
215        let byte = bytes[i];
216        let kept = match byte {
217            b'\n' | b'\t' => 1,
218            b'\r' if bytes.get(i + 1) == Some(&b'\n') => 1,
219            0x1b if color => color_sequence(&bytes[i..]),
220            0x00..=0x1f | 0x7f => 0,
221            _ => 1,
222        };
223        // An ESC that starts no color sequence falls to 0 and is escaped,
224        // as is one cut off by the end of `bytes`.
225        if kept == 0 {
226            out.extend(format!("\\x{byte:02x}").bytes());
227            i += 1;
228        } else {
229            out.extend(&bytes[i..i + kept]);
230            i += kept;
231        }
232    }
233    out
234}
235
236/// `bytes` without the color in it, for a tool's output saved in color
237/// and shown when cuno does not color. Any other sequence stays, to be
238/// shown escaped. What counts as color is in `docs/en/specs/commands.md`,
239/// "Format".
240pub fn without_color(bytes: &[u8]) -> Vec<u8> {
241    let mut out = Vec::with_capacity(bytes.len());
242    let mut i = 0;
243    while i < bytes.len() {
244        let color = if bytes[i] == 0x1b {
245            color_sequence(&bytes[i..])
246        } else {
247            0
248        };
249        if color == 0 {
250            out.push(bytes[i]);
251            i += 1;
252        } else {
253            i += color;
254        }
255    }
256    out
257}
258
259/// How long the color sequence `bytes` starts with is, or 0 when it starts
260/// with none. A color sequence is what Clang and GCC write when cuno asks
261/// them for color: an SGR (`ESC [`, codes, `m`) whose codes only style
262/// text that is shown (bold, italic, underline, a foreground color, a
263/// reset), or GCC's erase to the end of the line (`ESC [ K`). Codes that
264/// hide text (conceal, reverse, blink, a background color) make it no
265/// color sequence (`docs/en/specs/commands.md`, "Format").
266fn color_sequence(bytes: &[u8]) -> usize {
267    if bytes.get(1) != Some(&b'[') {
268        return 0;
269    }
270    let length = bytes[2..]
271        .iter()
272        .take_while(|b| b.is_ascii_digit() || **b == b';' || **b == b':')
273        .count();
274    let parameters = &bytes[2..2 + length];
275    let shown = match bytes.get(2 + length) {
276        Some(b'm') => styles_shown_text(parameters),
277        Some(b'K') => matches!(parameters, b"" | b"0"),
278        _ => false,
279    };
280    if shown { 2 + length + 1 } else { 0 }
281}
282
283/// Whether every SGR code in `parameters` only styles text that is shown.
284fn styles_shown_text(parameters: &[u8]) -> bool {
285    let mut codes = parameters.split(|b| *b == b';' || *b == b':').map(|code| {
286        if code.is_empty() {
287            Some(0)
288        } else {
289            std::str::from_utf8(code).ok()?.parse::<u32>().ok()
290        }
291    });
292    while let Some(code) = codes.next() {
293        match code {
294            Some(0 | 1 | 3 | 4 | 22 | 23 | 24 | 39 | 30..=37 | 90..=97) => {}
295            // An extended foreground color: 256 colors or RGB, each with
296            // every number it needs.
297            Some(38) => {
298                let numbers = match codes.next() {
299                    Some(Some(5)) => 1,
300                    Some(Some(2)) => 3,
301                    _ => return false,
302                };
303                for _ in 0..numbers {
304                    if !matches!(codes.next(), Some(Some(0..=255))) {
305                        return false;
306                    }
307                }
308            }
309            _ => return false,
310        }
311    }
312    true
313}
314
315/// `text`, which may hold a value cuno did not write, with every control
316/// character but a newline, a tab and a CR right before a newline written
317/// as `\xNN` below U+0080 and `\u{NN}` above (`docs/en/specs/commands.md`,
318/// "Format").
319fn escaped_text(text: &str) -> Cow<'_, str> {
320    let plain = |c: char| !c.is_control() || c == '\n' || c == '\t';
321    if text.chars().all(plain) {
322        return Cow::Borrowed(text);
323    }
324    let mut out = String::with_capacity(text.len());
325    let mut chars = text.chars().peekable();
326    while let Some(c) = chars.next() {
327        match c {
328            c if plain(c) => out.push(c),
329            '\r' if chars.peek() == Some(&'\n') => out.push(c),
330            c if (c as u32) < 0x80 => out.push_str(&format!("\\x{:02x}", c as u32)),
331            c => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
332        }
333    }
334    Cow::Owned(out)
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use crate::env::NameCase;
341    use std::sync::{Arc, Mutex};
342
343    /// A writer the test can read back after the `Shell` has written to it.
344    #[derive(Clone, Default)]
345    struct Captured(Arc<Mutex<Vec<u8>>>);
346
347    impl Write for Captured {
348        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
349            self.0.lock().unwrap().write(buf)
350        }
351        fn flush(&mut self) -> std::io::Result<()> {
352            Ok(())
353        }
354    }
355
356    impl Captured {
357        fn text(&self) -> String {
358            String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
359        }
360    }
361
362    fn shell(
363        choice: Option<ColorChoice>,
364        env: &[(&str, &str)],
365        terminal: bool,
366    ) -> (Shell, Captured) {
367        let out = Captured::default();
368        let env = Env::from_pairs(
369            env.iter().map(|(n, v)| (n.into(), v.into())),
370            NameCase::Sensitive,
371        );
372        (
373            Shell::new(Box::new(out.clone()), choice, &env, terminal),
374            out,
375        )
376    }
377
378    /// `[term] verbose` makes a shell verbose only when the command line
379    /// said neither `-q` nor `-v`: `-q` wins over it, and it never makes a
380    /// shell less verbose (`docs/en/specs/commands.md`, "Available for all
381    /// commands").
382    ///
383    /// Mutation: start a new shell verbose, let `[term] verbose` override
384    /// `-q`, ignore it, or let `false` quiet a `-v`; this test fails.
385    #[test]
386    fn configured_verbose_ranks_below_the_command_line() {
387        // A new shell is neither quiet nor verbose until told.
388        let (fresh, _) = shell(Some(ColorChoice::Never), &[], false);
389        assert!(!fresh.verbose());
390        for (given, configured, verbose, quiet) in [
391            (Verbosity::Normal, true, true, false),
392            (Verbosity::Normal, false, false, false),
393            (Verbosity::Quiet, true, false, true),
394            (Verbosity::Verbose, false, true, false),
395        ] {
396            let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
397            sh.set_verbosity(given);
398            sh.configure(None, configured);
399            assert_eq!(sh.verbose(), verbose, "{given:?}, configured {configured}");
400            sh.status("Compiling", "app");
401            assert_eq!(
402                out.text().is_empty(),
403                quiet,
404                "{given:?}, configured {configured}"
405            );
406        }
407    }
408
409    /// Under `-q` a status line is left out, and everything else is still
410    /// written.
411    ///
412    /// Mutation: ignore `quiet` in `status`, or return early from `error`,
413    /// `warning`, `help` or `raw` too; this test fails.
414    #[test]
415    fn quiet_leaves_out_status_lines_only() {
416        let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
417        sh.set_verbosity(Verbosity::Quiet);
418        sh.status("Compiling", "mygame v0.1.0");
419        sh.error("no compiler found");
420        sh.help("install Build Tools");
421        sh.warning("unused key");
422        sh.raw(
423            b"main.cpp(1): note
424",
425        );
426        assert_eq!(
427            out.text(),
428            "error: no compiler found
429help: install Build Tools
430warning: unused key
431main.cpp(1): note
432"
433        );
434    }
435
436    /// Mutation: change a label in `error`, `warning`, `help` or `status`,
437    /// or the width in `status`; this test fails.
438    #[test]
439    fn lines_without_color() {
440        let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
441        sh.error("no compiler found");
442        sh.help("install Build Tools");
443        sh.warning("unused key");
444        sh.status("Compiling", "mygame v0.1.0");
445        assert_eq!(
446            out.text(),
447            "error: no compiler found\nhelp: install Build Tools\nwarning: unused key\n   Compiling mygame v0.1.0\n"
448        );
449    }
450
451    /// Another program's output goes through byte for byte, with nothing
452    /// added and nothing painted, even when it is not UTF-8.
453    ///
454    /// Mutation: decode it, add a newline, or paint it; this test fails.
455    #[test]
456    fn raw_output_is_written_as_produced() {
457        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
458        let cp932 = [0x83, 0x81, 0x83, 0x82, 0x0d, 0x0a];
459        sh.raw(&cp932);
460        sh.raw(b"x");
461        assert_eq!(*out.0.lock().unwrap(), [&cp932[..], b"x"].concat());
462    }
463    /// A tool's output keeps newlines, tabs, CRLF and the bytes of a
464    /// two-byte code page, and shows every other C0 control character and
465    /// DEL escaped: a title-setting sequence, a lone CR, a CR that ends the
466    /// output, a vertical tab, a NUL.
467    ///
468    /// Mutation: return the bytes unchanged, keep a lone CR or one at the
469    /// end, or keep a vertical tab; this test fails.
470    #[test]
471    fn a_tools_control_characters_are_shown_escaped() {
472        let cp932 = [0x83, 0x5c, 0x88, 0x9f];
473        let mut bytes = b"a\tb\r\nc\x1b]0;x\x07d\re\x00\x7f\x0bf".to_vec();
474        bytes.extend(cp932);
475        bytes.push(b'\r');
476        let mut expected = b"a\tb\r\nc\\x1b]0;x\\x07d\\x0de\\x00\\x7f\\x0bf".to_vec();
477        expected.extend(cp932);
478        expected.extend(b"\\x0d");
479        assert_eq!(escaped(&bytes, false), expected);
480        assert_eq!(escaped(&bytes, true), expected);
481    }
482
483    /// Only color passes, and only when asked: what Clang and GCC write
484    /// (bold, a foreground color, a 256-color or RGB foreground, a reset,
485    /// GCC's `ESC [ K`) passes; what hides text (conceal, reverse, blink, a
486    /// background) or moves the cursor is shown escaped, as is anything
487    /// when color is not asked for.
488    ///
489    /// Mutation: keep every SGR, keep every `ESC [` sequence, accept a `?`
490    /// in the codes, drop GCC's `ESC [ K`, or keep color when not asked;
491    /// this test fails.
492    #[test]
493    fn only_color_that_shows_text_passes() {
494        for kept in [
495            &b"\x1b[1;31merror\x1b[0m: x"[..],
496            b"\x1b[01;35m\x1b[Kwarning: \x1b[m\x1b[K",
497            b"\x1b[0;1;36mnote\x1b[0m",
498            b"\x1b[38;5;1mx\x1b[38:2:1:2:3mx\x1b[39m",
499        ] {
500            assert_eq!(escaped(kept, true), kept);
501        }
502        assert_eq!(
503            escaped(b"\x1b[1;31merror\x1b[0m: x", false),
504            b"\\x1b[1;31merror\\x1b[0m: x".to_vec()
505        );
506        for (hiding, shown) in [
507            (&b"\x1b[8mx"[..], &b"\\x1b[8mx"[..]),
508            (b"\x1b[30;40mx", b"\\x1b[30;40mx"),
509            (b"\x1b[7mx", b"\\x1b[7mx"),
510            (b"\x1b[5mx", b"\\x1b[5mx"),
511            (b"\x1b[38;5mx", b"\\x1b[38;5mx"),
512            (b"\x1b[2J\x1b[?25l", b"\\x1b[2J\\x1b[?25l"),
513            (b"\x1b[?1m", b"\\x1b[?1m"),
514            (b"\x1b[2K", b"\\x1b[2K"),
515            (b"\x1b[", b"\\x1b["),
516        ] {
517            assert_eq!(escaped(hiding, true), shown);
518        }
519    }
520
521    /// Taking color out of saved output removes the color sequences and
522    /// nothing else: a sequence that is not color stays, to be shown
523    /// escaped, rather than disappearing on the next build.
524    ///
525    /// Mutation: remove every `ESC [` sequence, keep the color, or drop a
526    /// byte after one; this test fails.
527    #[test]
528    fn taking_color_out_keeps_what_is_not_color() {
529        assert_eq!(
530            without_color(b"\x1b[1ma.cpp:1:1: \x1b[0;1;35mwarning: \x1b[0mx\x1b[K\n"),
531            b"a.cpp:1:1: warning: x\n"
532        );
533        assert_eq!(
534            without_color(b"a \x1b[2J b \x1b[8mhidden\x1b[0m c"),
535            b"a \x1b[2J b \x1b[8mhidden c"
536        );
537        assert_eq!(without_color(b"lone \x1b here"), b"lone \x1b here");
538    }
539
540    /// cuno's own lines show a value's control characters escaped, C1
541    /// included, keep their newlines, tabs and CRLF, show DEL as `\x7f`,
542    /// and still paint the label.
543    ///
544    /// Mutation: write the message of an error or a status line as it is,
545    /// keep a lone CR, escape the CR of a CRLF, or show DEL as `\u{7f}`;
546    /// this test fails.
547    #[test]
548    fn a_value_in_a_message_is_shown_escaped() {
549        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
550        sh.error("unknown `\x1b]0;x\x07`\r\n\tbelow\u{9b}\x7f\rend");
551        sh.status("Compiling", "a\x1b[2Jb");
552        assert_eq!(
553            out.text(),
554            "\x1b[1;31merror\x1b[0m: unknown `\\x1b]0;x\\x07`\r\n\tbelow\\u{9b}\\x7f\\x0dend\n\
555             \x1b[1;32m   Compiling\x1b[0m a\\x1b[2Jb\n"
556        );
557    }
558
559    /// A tool's output goes through the shell escaped, its color kept only
560    /// when cuno colors and asked the tool for it.
561    ///
562    /// Mutation: write a tool's output with `raw`, or keep its color when
563    /// cuno did not ask for it; this test fails.
564    #[test]
565    fn a_tools_output_is_written_escaped() {
566        let output = b"\x1b[1mwarning\x1b[0m\x1b]0;x\x07\n";
567        let written = |choice, asked| {
568            let (mut sh, out) = shell(Some(choice), &[], false);
569            sh.tool_output(output, asked);
570            out.text()
571        };
572        assert_eq!(
573            written(ColorChoice::Always, true),
574            "\x1b[1mwarning\x1b[0m\\x1b]0;x\\x07\n"
575        );
576        let escaped = "\\x1b[1mwarning\\x1b[0m\\x1b]0;x\\x07\n";
577        assert_eq!(written(ColorChoice::Always, false), escaped);
578        assert_eq!(written(ColorChoice::Never, true), escaped);
579    }
580
581    /// Mutation: swap or drop the style of any label, or stop painting the
582    /// status verb; this test fails.
583    #[test]
584    fn lines_with_color_paint_only_the_label() {
585        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
586        sh.error("e");
587        sh.help("h");
588        sh.warning("w");
589        sh.status("Compiling", "m");
590        assert_eq!(
591            out.text(),
592            "\x1b[1;31merror\x1b[0m: e\n\
593             \x1b[1;36mhelp\x1b[0m: h\n\
594             \x1b[1;33mwarning\x1b[0m: w\n\
595             \x1b[1;32m   Compiling\x1b[0m m\n"
596        );
597    }
598
599    /// Mutation: let `NO_COLOR` override an explicit choice (including an
600    /// explicit `auto`), ignore it when no choice was given, or color when not
601    /// a terminal under `auto`; this test fails.
602    #[test]
603    fn color_follows_the_choice_the_terminal_and_no_color() {
604        let on =
605            |choice, env: &[(&str, &str)], terminal| shell(choice, env, terminal).0.uses_color();
606        let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
607        // No choice given: the terminal decides, and NO_COLOR (even empty)
608        // turns color off.
609        assert!(on(None, &[], true));
610        assert!(!on(None, &[], false));
611        assert!(!on(None, no_color, true));
612        // A choice given wins over NO_COLOR.
613        assert!(on(Some(ColorChoice::Auto), no_color, true));
614        assert!(!on(Some(ColorChoice::Auto), &[], false));
615        assert!(on(Some(ColorChoice::Always), no_color, false));
616        assert!(!on(Some(ColorChoice::Never), &[], true));
617    }
618
619    /// `--color`, then `[term] color`, then `NO_COLOR`, then the terminal,
620    /// each level deciding only when every level above it gave nothing.
621    ///
622    /// Mutation: swap any two levels, let `NO_COLOR` beat a choice given or
623    /// configured, or let `auto` ignore the terminal; this test fails.
624    #[test]
625    fn colors_follows_the_order() {
626        use ColorChoice::{Always, Auto, Never};
627        // `--color` beats `[term] color`, and both beat `NO_COLOR`.
628        assert!(colors(Some(Always), Some(Never), true, false));
629        assert!(!colors(Some(Never), Some(Always), false, true));
630        assert!(colors(None, Some(Always), true, false));
631        assert!(!colors(None, Some(Never), false, true));
632        // `auto`, given or configured, follows the terminal over `NO_COLOR`.
633        assert!(colors(Some(Auto), None, true, true));
634        assert!(!colors(Some(Auto), Some(Always), false, false));
635        assert!(colors(None, Some(Auto), true, true));
636        // With neither, `NO_COLOR` decides, then the terminal.
637        assert!(!colors(None, None, true, true));
638        assert!(colors(None, None, false, true));
639        assert!(!colors(None, None, false, false));
640    }
641
642    /// `[term] color` ranks below `--color` and above `NO_COLOR`
643    /// (`commands.md`, "Available for all commands").
644    ///
645    /// Mutation: let `[term] color` beat `--color`, let `NO_COLOR` beat
646    /// `[term] color`, or ignore what `configure` is given; this test fails.
647    #[test]
648    fn the_configured_choice_ranks_between_the_flag_and_no_color() {
649        let on = |given, configured, env: &[(&str, &str)], terminal| {
650            let mut shell = shell(given, env, terminal).0;
651            shell.configure(configured, false);
652            shell.uses_color()
653        };
654        let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
655        let (always, never) = (Some(ColorChoice::Always), Some(ColorChoice::Never));
656        assert!(on(None, always, no_color, false));
657        assert!(!on(None, never, &[], true));
658        assert!(on(None, Some(ColorChoice::Auto), no_color, true));
659        assert!(!on(never, always, &[], true));
660        assert!(on(always, never, &[], false));
661        assert!(!on(None, None, no_color, true));
662        assert!(on(None, None, &[], true));
663    }
664}