cuno-core 0.3.0

Error classification, output, the cuno home, and the environment snapshot, shared by the other crates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Writing what cuno shows the user: errors, warnings, help and status lines,
//! in color or not. See `docs/en/specs/commands.md`, "Output".

use std::borrow::Cow;
use std::fmt::Display;
use std::io::Write;

use crate::Env;

/// A color choice given with `--color` or `[term] color`
/// (`docs/en/specs/commands.md`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorChoice {
    /// Color only when writing to a terminal.
    Auto,
    /// Always color.
    Always,
    /// Never color.
    Never,
}

const RESET: &str = "\x1b[0m";
const BOLD_RED: &str = "\x1b[1;31m";
const BOLD_YELLOW: &str = "\x1b[1;33m";
const BOLD_CYAN: &str = "\x1b[1;36m";
const BOLD_GREEN: &str = "\x1b[1;32m";

/// Whether to color: `--color` (`given`), then `[term] color`
/// (`configured`), then `NO_COLOR` (`no_color`, set to anything, even
/// empty), then whether the output is a `terminal`. The one place this
/// order is written; see `docs/en/specs/commands.md`, "Available for all
/// commands".
pub fn colors(
    given: Option<ColorChoice>,
    configured: Option<ColorChoice>,
    no_color: bool,
    terminal: bool,
) -> bool {
    match given.or(configured) {
        Some(ColorChoice::Always) => true,
        Some(ColorChoice::Never) => false,
        Some(ColorChoice::Auto) => terminal,
        None => terminal && !no_color,
    }
}

/// How much a command shows: `-q`, nothing given, or `-v` (or
/// `[term] verbose`, which `-q` still wins over). One value, so quiet and
/// verbose cannot both be in effect (`docs/en/specs/commands.md`,
/// "Available for all commands").
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Verbosity {
    /// `-q`: status lines are left out.
    Quiet,
    /// What every command shows by default.
    #[default]
    Normal,
    /// `-v` or `[term] verbose`: also each step's command.
    Verbose,
}

/// Where cuno's messages go (stderr for the binary). Crates write through a
/// `Shell` instead of printing, so the color decision is made once.
pub struct Shell {
    out: Box<dyn Write>,
    /// `--color`, when given.
    given: Option<ColorChoice>,
    /// Whether `NO_COLOR` is set, even to nothing.
    no_color: bool,
    /// Whether `out` is a terminal.
    terminal: bool,
    color: bool,
    verbosity: Verbosity,
}

impl Shell {
    /// A shell writing to `out`. `choice` is the color choice the user gave,
    /// or `None` when they gave none; `out_is_terminal` says whether `out` is
    /// a terminal.
    ///
    /// With no choice given, `NO_COLOR` (set to anything, including empty)
    /// means no color, and otherwise color follows the terminal. A choice the
    /// user gave always wins over `NO_COLOR`, including an explicit `auto`.
    /// [`Shell::configure`] adds `[term] color` once it is read. See
    /// `docs/en/specs/commands.md`, "Available for all commands".
    pub fn new(
        out: Box<dyn Write>,
        choice: Option<ColorChoice>,
        env: &Env,
        out_is_terminal: bool,
    ) -> Shell {
        let mut shell = Shell {
            out,
            given: choice,
            no_color: env.get("NO_COLOR").is_some(),
            terminal: out_is_terminal,
            color: false,
            verbosity: Verbosity::Normal,
        };
        shell.configure(None, false);
        shell
    }

    /// Applies `[term]`, which is read after the shell is made: `color`
    /// ranks below `--color` and above `NO_COLOR`, and `verbose` makes the
    /// shell verbose unless `-q` or `-v` already decided.
    pub fn configure(&mut self, configured: Option<ColorChoice>, verbose: bool) {
        self.color = colors(self.given, configured, self.no_color, self.terminal);
        if verbose && self.verbosity == Verbosity::Normal {
            self.verbosity = Verbosity::Verbose;
        }
    }

    /// Applies `-q` or `-v`, once, before anything is written. Quiet, a
    /// [`Shell::status`] line writes nothing, and errors, warnings, help and
    /// other programs' output are written as before
    /// (`docs/en/specs/commands.md`, "Available for all commands").
    pub fn set_verbosity(&mut self, verbosity: Verbosity) {
        self.verbosity = verbosity;
    }

    /// Whether to show what only `-v` shows, such as each step's command.
    pub fn verbose(&self) -> bool {
        self.verbosity == Verbosity::Verbose
    }

    /// Whether this shell writes color escape codes.
    pub fn uses_color(&self) -> bool {
        self.color
    }

    /// `error: <message>`.
    pub fn error(&mut self, message: impl Display) {
        self.line(BOLD_RED, "error", message);
    }

    /// `warning: <message>`.
    pub fn warning(&mut self, message: impl Display) {
        self.line(BOLD_YELLOW, "warning", message);
    }

    /// `help: <message>`, how to fix what the previous line reported.
    pub fn help(&mut self, message: impl Display) {
        self.line(BOLD_CYAN, "help", message);
    }

    /// A status line: `verb` right-aligned in 12 columns, then `message`, as
    /// in `   Compiling mygame v0.1.0`. Nothing under `-q`
    /// ([`Shell::set_verbosity`]).
    pub fn status(&mut self, verb: &str, message: impl Display) {
        if self.verbosity == Verbosity::Quiet {
            return;
        }
        let verb = self.paint(BOLD_GREEN, &format!("{verb:>12}"));
        let message = message.to_string();
        let message = escaped_text(&message);
        self.write(format_args!("{verb} {message}"));
    }

    /// `bytes` written as they are, nothing escaped: for text cuno wrote
    /// itself, and for the output of a program the user asked cuno to run
    /// (`cuno test`, `cuno run`), which can reach the terminal directly
    /// anyway. A tool's output goes through [`Shell::tool_output`]
    /// (`docs/en/specs/commands.md`, "Format").
    pub fn raw(&mut self, bytes: &[u8]) {
        // A failed write to stderr cannot be reported anywhere better.
        let _ = self.out.write_all(bytes);
        let _ = self.out.flush();
    }

    /// The output of a tool cuno ran (a compiler, a linker, clang-tidy),
    /// written as it was produced, not decoded, so text in the console's
    /// code page reaches the console as such, but with the control
    /// characters it holds shown escaped. Its color sequences pass only when
    /// `asked`, cuno having asked that tool for color; any other tool's
    /// are a project's text (`docs/en/specs/commands.md`, "Format").
    pub fn tool_output(&mut self, bytes: &[u8], asked: bool) {
        let shown = escaped(bytes, asked && self.color);
        self.raw(&shown);
    }

    fn line(&mut self, style: &str, label: &str, message: impl Display) {
        let label = self.paint(style, label);
        // Formatted first, so the whole message is scanned for control
        // characters before anything is written.
        let message = message.to_string();
        let message = escaped_text(&message);
        self.write(format_args!("{label}: {message}"));
    }

    fn write(&mut self, line: std::fmt::Arguments<'_>) {
        // A failed write to stderr cannot be reported anywhere better.
        let _ = writeln!(self.out, "{line}");
    }

    fn paint(&self, style: &str, text: &str) -> String {
        if self.color {
            format!("{style}{text}{RESET}")
        } else {
            text.to_owned()
        }
    }
}

/// `bytes`, another program's output, with every C0 control character and
/// DEL written as `\xNN`, except a newline, a tab, a CR right before a
/// newline, and, when `color`, a color sequence ([`color_sequence`]).
/// Judged byte by byte, so text in a code page such as CP932, whose
/// two-byte characters never use these bytes, passes unchanged
/// (`docs/en/specs/commands.md`, "Format").
fn escaped(bytes: &[u8], color: bool) -> Vec<u8> {
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let byte = bytes[i];
        let kept = match byte {
            b'\n' | b'\t' => 1,
            b'\r' if bytes.get(i + 1) == Some(&b'\n') => 1,
            0x1b if color => color_sequence(&bytes[i..]),
            0x00..=0x1f | 0x7f => 0,
            _ => 1,
        };
        // An ESC that starts no color sequence falls to 0 and is escaped,
        // as is one cut off by the end of `bytes`.
        if kept == 0 {
            out.extend(format!("\\x{byte:02x}").bytes());
            i += 1;
        } else {
            out.extend(&bytes[i..i + kept]);
            i += kept;
        }
    }
    out
}

/// `bytes` without the color in it, for a tool's output saved in color
/// and shown when cuno does not color. Any other sequence stays, to be
/// shown escaped. What counts as color is in `docs/en/specs/commands.md`,
/// "Format".
pub fn without_color(bytes: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let color = if bytes[i] == 0x1b {
            color_sequence(&bytes[i..])
        } else {
            0
        };
        if color == 0 {
            out.push(bytes[i]);
            i += 1;
        } else {
            i += color;
        }
    }
    out
}

/// How long the color sequence `bytes` starts with is, or 0 when it starts
/// with none. A color sequence is what Clang and GCC write when cuno asks
/// them for color: an SGR (`ESC [`, codes, `m`) whose codes only style
/// text that is shown (bold, italic, underline, a foreground color, a
/// reset), or GCC's erase to the end of the line (`ESC [ K`). Codes that
/// hide text (conceal, reverse, blink, a background color) make it no
/// color sequence (`docs/en/specs/commands.md`, "Format").
fn color_sequence(bytes: &[u8]) -> usize {
    if bytes.get(1) != Some(&b'[') {
        return 0;
    }
    let length = bytes[2..]
        .iter()
        .take_while(|b| b.is_ascii_digit() || **b == b';' || **b == b':')
        .count();
    let parameters = &bytes[2..2 + length];
    let shown = match bytes.get(2 + length) {
        Some(b'm') => styles_shown_text(parameters),
        Some(b'K') => matches!(parameters, b"" | b"0"),
        _ => false,
    };
    if shown { 2 + length + 1 } else { 0 }
}

/// Whether every SGR code in `parameters` only styles text that is shown.
fn styles_shown_text(parameters: &[u8]) -> bool {
    let mut codes = parameters.split(|b| *b == b';' || *b == b':').map(|code| {
        if code.is_empty() {
            Some(0)
        } else {
            std::str::from_utf8(code).ok()?.parse::<u32>().ok()
        }
    });
    while let Some(code) = codes.next() {
        match code {
            Some(0 | 1 | 3 | 4 | 22 | 23 | 24 | 39 | 30..=37 | 90..=97) => {}
            // An extended foreground color: 256 colors or RGB, each with
            // every number it needs.
            Some(38) => {
                let numbers = match codes.next() {
                    Some(Some(5)) => 1,
                    Some(Some(2)) => 3,
                    _ => return false,
                };
                for _ in 0..numbers {
                    if !matches!(codes.next(), Some(Some(0..=255))) {
                        return false;
                    }
                }
            }
            _ => return false,
        }
    }
    true
}

/// `text`, which may hold a value cuno did not write, with every control
/// character but a newline, a tab and a CR right before a newline written
/// as `\xNN` below U+0080 and `\u{NN}` above (`docs/en/specs/commands.md`,
/// "Format").
fn escaped_text(text: &str) -> Cow<'_, str> {
    let plain = |c: char| !c.is_control() || c == '\n' || c == '\t';
    if text.chars().all(plain) {
        return Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            c if plain(c) => out.push(c),
            '\r' if chars.peek() == Some(&'\n') => out.push(c),
            c if (c as u32) < 0x80 => out.push_str(&format!("\\x{:02x}", c as u32)),
            c => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
        }
    }
    Cow::Owned(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::env::NameCase;
    use std::sync::{Arc, Mutex};

    /// A writer the test can read back after the `Shell` has written to it.
    #[derive(Clone, Default)]
    struct Captured(Arc<Mutex<Vec<u8>>>);

    impl Write for Captured {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().write(buf)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl Captured {
        fn text(&self) -> String {
            String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
        }
    }

    fn shell(
        choice: Option<ColorChoice>,
        env: &[(&str, &str)],
        terminal: bool,
    ) -> (Shell, Captured) {
        let out = Captured::default();
        let env = Env::from_pairs(
            env.iter().map(|(n, v)| (n.into(), v.into())),
            NameCase::Sensitive,
        );
        (
            Shell::new(Box::new(out.clone()), choice, &env, terminal),
            out,
        )
    }

    /// `[term] verbose` makes a shell verbose only when the command line
    /// said neither `-q` nor `-v`: `-q` wins over it, and it never makes a
    /// shell less verbose (`docs/en/specs/commands.md`, "Available for all
    /// commands").
    ///
    /// Mutation: start a new shell verbose, let `[term] verbose` override
    /// `-q`, ignore it, or let `false` quiet a `-v`; this test fails.
    #[test]
    fn configured_verbose_ranks_below_the_command_line() {
        // A new shell is neither quiet nor verbose until told.
        let (fresh, _) = shell(Some(ColorChoice::Never), &[], false);
        assert!(!fresh.verbose());
        for (given, configured, verbose, quiet) in [
            (Verbosity::Normal, true, true, false),
            (Verbosity::Normal, false, false, false),
            (Verbosity::Quiet, true, false, true),
            (Verbosity::Verbose, false, true, false),
        ] {
            let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
            sh.set_verbosity(given);
            sh.configure(None, configured);
            assert_eq!(sh.verbose(), verbose, "{given:?}, configured {configured}");
            sh.status("Compiling", "app");
            assert_eq!(
                out.text().is_empty(),
                quiet,
                "{given:?}, configured {configured}"
            );
        }
    }

    /// Under `-q` a status line is left out, and everything else is still
    /// written.
    ///
    /// Mutation: ignore `quiet` in `status`, or return early from `error`,
    /// `warning`, `help` or `raw` too; this test fails.
    #[test]
    fn quiet_leaves_out_status_lines_only() {
        let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
        sh.set_verbosity(Verbosity::Quiet);
        sh.status("Compiling", "mygame v0.1.0");
        sh.error("no compiler found");
        sh.help("install Build Tools");
        sh.warning("unused key");
        sh.raw(
            b"main.cpp(1): note
",
        );
        assert_eq!(
            out.text(),
            "error: no compiler found
help: install Build Tools
warning: unused key
main.cpp(1): note
"
        );
    }

    /// Mutation: change a label in `error`, `warning`, `help` or `status`,
    /// or the width in `status`; this test fails.
    #[test]
    fn lines_without_color() {
        let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
        sh.error("no compiler found");
        sh.help("install Build Tools");
        sh.warning("unused key");
        sh.status("Compiling", "mygame v0.1.0");
        assert_eq!(
            out.text(),
            "error: no compiler found\nhelp: install Build Tools\nwarning: unused key\n   Compiling mygame v0.1.0\n"
        );
    }

    /// Another program's output goes through byte for byte, with nothing
    /// added and nothing painted, even when it is not UTF-8.
    ///
    /// Mutation: decode it, add a newline, or paint it; this test fails.
    #[test]
    fn raw_output_is_written_as_produced() {
        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
        let cp932 = [0x83, 0x81, 0x83, 0x82, 0x0d, 0x0a];
        sh.raw(&cp932);
        sh.raw(b"x");
        assert_eq!(*out.0.lock().unwrap(), [&cp932[..], b"x"].concat());
    }
    /// A tool's output keeps newlines, tabs, CRLF and the bytes of a
    /// two-byte code page, and shows every other C0 control character and
    /// DEL escaped: a title-setting sequence, a lone CR, a CR that ends the
    /// output, a vertical tab, a NUL.
    ///
    /// Mutation: return the bytes unchanged, keep a lone CR or one at the
    /// end, or keep a vertical tab; this test fails.
    #[test]
    fn a_tools_control_characters_are_shown_escaped() {
        let cp932 = [0x83, 0x5c, 0x88, 0x9f];
        let mut bytes = b"a\tb\r\nc\x1b]0;x\x07d\re\x00\x7f\x0bf".to_vec();
        bytes.extend(cp932);
        bytes.push(b'\r');
        let mut expected = b"a\tb\r\nc\\x1b]0;x\\x07d\\x0de\\x00\\x7f\\x0bf".to_vec();
        expected.extend(cp932);
        expected.extend(b"\\x0d");
        assert_eq!(escaped(&bytes, false), expected);
        assert_eq!(escaped(&bytes, true), expected);
    }

    /// Only color passes, and only when asked: what Clang and GCC write
    /// (bold, a foreground color, a 256-color or RGB foreground, a reset,
    /// GCC's `ESC [ K`) passes; what hides text (conceal, reverse, blink, a
    /// background) or moves the cursor is shown escaped, as is anything
    /// when color is not asked for.
    ///
    /// Mutation: keep every SGR, keep every `ESC [` sequence, accept a `?`
    /// in the codes, drop GCC's `ESC [ K`, or keep color when not asked;
    /// this test fails.
    #[test]
    fn only_color_that_shows_text_passes() {
        for kept in [
            &b"\x1b[1;31merror\x1b[0m: x"[..],
            b"\x1b[01;35m\x1b[Kwarning: \x1b[m\x1b[K",
            b"\x1b[0;1;36mnote\x1b[0m",
            b"\x1b[38;5;1mx\x1b[38:2:1:2:3mx\x1b[39m",
        ] {
            assert_eq!(escaped(kept, true), kept);
        }
        assert_eq!(
            escaped(b"\x1b[1;31merror\x1b[0m: x", false),
            b"\\x1b[1;31merror\\x1b[0m: x".to_vec()
        );
        for (hiding, shown) in [
            (&b"\x1b[8mx"[..], &b"\\x1b[8mx"[..]),
            (b"\x1b[30;40mx", b"\\x1b[30;40mx"),
            (b"\x1b[7mx", b"\\x1b[7mx"),
            (b"\x1b[5mx", b"\\x1b[5mx"),
            (b"\x1b[38;5mx", b"\\x1b[38;5mx"),
            (b"\x1b[2J\x1b[?25l", b"\\x1b[2J\\x1b[?25l"),
            (b"\x1b[?1m", b"\\x1b[?1m"),
            (b"\x1b[2K", b"\\x1b[2K"),
            (b"\x1b[", b"\\x1b["),
        ] {
            assert_eq!(escaped(hiding, true), shown);
        }
    }

    /// Taking color out of saved output removes the color sequences and
    /// nothing else: a sequence that is not color stays, to be shown
    /// escaped, rather than disappearing on the next build.
    ///
    /// Mutation: remove every `ESC [` sequence, keep the color, or drop a
    /// byte after one; this test fails.
    #[test]
    fn taking_color_out_keeps_what_is_not_color() {
        assert_eq!(
            without_color(b"\x1b[1ma.cpp:1:1: \x1b[0;1;35mwarning: \x1b[0mx\x1b[K\n"),
            b"a.cpp:1:1: warning: x\n"
        );
        assert_eq!(
            without_color(b"a \x1b[2J b \x1b[8mhidden\x1b[0m c"),
            b"a \x1b[2J b \x1b[8mhidden c"
        );
        assert_eq!(without_color(b"lone \x1b here"), b"lone \x1b here");
    }

    /// cuno's own lines show a value's control characters escaped, C1
    /// included, keep their newlines, tabs and CRLF, show DEL as `\x7f`,
    /// and still paint the label.
    ///
    /// Mutation: write the message of an error or a status line as it is,
    /// keep a lone CR, escape the CR of a CRLF, or show DEL as `\u{7f}`;
    /// this test fails.
    #[test]
    fn a_value_in_a_message_is_shown_escaped() {
        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
        sh.error("unknown `\x1b]0;x\x07`\r\n\tbelow\u{9b}\x7f\rend");
        sh.status("Compiling", "a\x1b[2Jb");
        assert_eq!(
            out.text(),
            "\x1b[1;31merror\x1b[0m: unknown `\\x1b]0;x\\x07`\r\n\tbelow\\u{9b}\\x7f\\x0dend\n\
             \x1b[1;32m   Compiling\x1b[0m a\\x1b[2Jb\n"
        );
    }

    /// A tool's output goes through the shell escaped, its color kept only
    /// when cuno colors and asked the tool for it.
    ///
    /// Mutation: write a tool's output with `raw`, or keep its color when
    /// cuno did not ask for it; this test fails.
    #[test]
    fn a_tools_output_is_written_escaped() {
        let output = b"\x1b[1mwarning\x1b[0m\x1b]0;x\x07\n";
        let written = |choice, asked| {
            let (mut sh, out) = shell(Some(choice), &[], false);
            sh.tool_output(output, asked);
            out.text()
        };
        assert_eq!(
            written(ColorChoice::Always, true),
            "\x1b[1mwarning\x1b[0m\\x1b]0;x\\x07\n"
        );
        let escaped = "\\x1b[1mwarning\\x1b[0m\\x1b]0;x\\x07\n";
        assert_eq!(written(ColorChoice::Always, false), escaped);
        assert_eq!(written(ColorChoice::Never, true), escaped);
    }

    /// Mutation: swap or drop the style of any label, or stop painting the
    /// status verb; this test fails.
    #[test]
    fn lines_with_color_paint_only_the_label() {
        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
        sh.error("e");
        sh.help("h");
        sh.warning("w");
        sh.status("Compiling", "m");
        assert_eq!(
            out.text(),
            "\x1b[1;31merror\x1b[0m: e\n\
             \x1b[1;36mhelp\x1b[0m: h\n\
             \x1b[1;33mwarning\x1b[0m: w\n\
             \x1b[1;32m   Compiling\x1b[0m m\n"
        );
    }

    /// Mutation: let `NO_COLOR` override an explicit choice (including an
    /// explicit `auto`), ignore it when no choice was given, or color when not
    /// a terminal under `auto`; this test fails.
    #[test]
    fn color_follows_the_choice_the_terminal_and_no_color() {
        let on =
            |choice, env: &[(&str, &str)], terminal| shell(choice, env, terminal).0.uses_color();
        let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
        // No choice given: the terminal decides, and NO_COLOR (even empty)
        // turns color off.
        assert!(on(None, &[], true));
        assert!(!on(None, &[], false));
        assert!(!on(None, no_color, true));
        // A choice given wins over NO_COLOR.
        assert!(on(Some(ColorChoice::Auto), no_color, true));
        assert!(!on(Some(ColorChoice::Auto), &[], false));
        assert!(on(Some(ColorChoice::Always), no_color, false));
        assert!(!on(Some(ColorChoice::Never), &[], true));
    }

    /// `--color`, then `[term] color`, then `NO_COLOR`, then the terminal,
    /// each level deciding only when every level above it gave nothing.
    ///
    /// Mutation: swap any two levels, let `NO_COLOR` beat a choice given or
    /// configured, or let `auto` ignore the terminal; this test fails.
    #[test]
    fn colors_follows_the_order() {
        use ColorChoice::{Always, Auto, Never};
        // `--color` beats `[term] color`, and both beat `NO_COLOR`.
        assert!(colors(Some(Always), Some(Never), true, false));
        assert!(!colors(Some(Never), Some(Always), false, true));
        assert!(colors(None, Some(Always), true, false));
        assert!(!colors(None, Some(Never), false, true));
        // `auto`, given or configured, follows the terminal over `NO_COLOR`.
        assert!(colors(Some(Auto), None, true, true));
        assert!(!colors(Some(Auto), Some(Always), false, false));
        assert!(colors(None, Some(Auto), true, true));
        // With neither, `NO_COLOR` decides, then the terminal.
        assert!(!colors(None, None, true, true));
        assert!(colors(None, None, false, true));
        assert!(!colors(None, None, false, false));
    }

    /// `[term] color` ranks below `--color` and above `NO_COLOR`
    /// (`commands.md`, "Available for all commands").
    ///
    /// Mutation: let `[term] color` beat `--color`, let `NO_COLOR` beat
    /// `[term] color`, or ignore what `configure` is given; this test fails.
    #[test]
    fn the_configured_choice_ranks_between_the_flag_and_no_color() {
        let on = |given, configured, env: &[(&str, &str)], terminal| {
            let mut shell = shell(given, env, terminal).0;
            shell.configure(configured, false);
            shell.uses_color()
        };
        let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
        let (always, never) = (Some(ColorChoice::Always), Some(ColorChoice::Never));
        assert!(on(None, always, no_color, false));
        assert!(!on(None, never, &[], true));
        assert!(on(None, Some(ColorChoice::Auto), no_color, true));
        assert!(!on(never, always, &[], true));
        assert!(on(always, never, &[], false));
        assert!(!on(None, None, no_color, true));
        assert!(on(None, None, &[], true));
    }
}