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::fmt::Display;
5use std::io::Write;
6
7use crate::Env;
8
9/// A color choice given with `--color` or `[term] color`
10/// (`docs/en/specs/commands.md`).
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum ColorChoice {
13    /// Color only when writing to a terminal.
14    Auto,
15    /// Always color.
16    Always,
17    /// Never color.
18    Never,
19}
20
21const RESET: &str = "\x1b[0m";
22const BOLD_RED: &str = "\x1b[1;31m";
23const BOLD_YELLOW: &str = "\x1b[1;33m";
24const BOLD_CYAN: &str = "\x1b[1;36m";
25const BOLD_GREEN: &str = "\x1b[1;32m";
26
27/// Whether to color: `--color` (`given`), then `[term] color`
28/// (`configured`), then `NO_COLOR` (`no_color`, set to anything, even
29/// empty), then whether the output is a `terminal`. The one place this
30/// order is written; see `docs/en/specs/commands.md`, "Available for all
31/// commands".
32pub fn colors(
33    given: Option<ColorChoice>,
34    configured: Option<ColorChoice>,
35    no_color: bool,
36    terminal: bool,
37) -> bool {
38    match given.or(configured) {
39        Some(ColorChoice::Always) => true,
40        Some(ColorChoice::Never) => false,
41        Some(ColorChoice::Auto) => terminal,
42        None => terminal && !no_color,
43    }
44}
45
46/// How much a command shows: `-q`, nothing given, or `-v` (or
47/// `[term] verbose`, which `-q` still wins over). One value, so quiet and
48/// verbose cannot both be in effect (`docs/en/specs/commands.md`,
49/// "Available for all commands").
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
51pub enum Verbosity {
52    /// `-q`: status lines are left out.
53    Quiet,
54    /// What every command shows by default.
55    #[default]
56    Normal,
57    /// `-v` or `[term] verbose`: also each step's command.
58    Verbose,
59}
60
61/// Where cuno's messages go (stderr for the binary). Crates write through a
62/// `Shell` instead of printing, so the color decision is made once.
63pub struct Shell {
64    out: Box<dyn Write>,
65    /// `--color`, when given.
66    given: Option<ColorChoice>,
67    /// Whether `NO_COLOR` is set, even to nothing.
68    no_color: bool,
69    /// Whether `out` is a terminal.
70    terminal: bool,
71    color: bool,
72    verbosity: Verbosity,
73}
74
75impl Shell {
76    /// A shell writing to `out`. `choice` is the color choice the user gave,
77    /// or `None` when they gave none; `out_is_terminal` says whether `out` is
78    /// a terminal.
79    ///
80    /// With no choice given, `NO_COLOR` (set to anything, including empty)
81    /// means no color, and otherwise color follows the terminal. A choice the
82    /// user gave always wins over `NO_COLOR`, including an explicit `auto`.
83    /// [`Shell::configure`] adds `[term] color` once it is read. See
84    /// `docs/en/specs/commands.md`, "Available for all commands".
85    pub fn new(
86        out: Box<dyn Write>,
87        choice: Option<ColorChoice>,
88        env: &Env,
89        out_is_terminal: bool,
90    ) -> Shell {
91        let mut shell = Shell {
92            out,
93            given: choice,
94            no_color: env.get("NO_COLOR").is_some(),
95            terminal: out_is_terminal,
96            color: false,
97            verbosity: Verbosity::Normal,
98        };
99        shell.configure(None, false);
100        shell
101    }
102
103    /// Applies `[term]`, which is read after the shell is made: `color`
104    /// ranks below `--color` and above `NO_COLOR`, and `verbose` makes the
105    /// shell verbose unless `-q` or `-v` already decided.
106    pub fn configure(&mut self, configured: Option<ColorChoice>, verbose: bool) {
107        self.color = colors(self.given, configured, self.no_color, self.terminal);
108        if verbose && self.verbosity == Verbosity::Normal {
109            self.verbosity = Verbosity::Verbose;
110        }
111    }
112
113    /// Applies `-q` or `-v`, once, before anything is written. Quiet, a
114    /// [`Shell::status`] line writes nothing, and errors, warnings, help and
115    /// other programs' output are written as before
116    /// (`docs/en/specs/commands.md`, "Available for all commands").
117    pub fn set_verbosity(&mut self, verbosity: Verbosity) {
118        self.verbosity = verbosity;
119    }
120
121    /// Whether to show what only `-v` shows, such as each step's command.
122    pub fn verbose(&self) -> bool {
123        self.verbosity == Verbosity::Verbose
124    }
125
126    /// Whether this shell writes color escape codes.
127    pub fn uses_color(&self) -> bool {
128        self.color
129    }
130
131    /// `error: <message>`.
132    pub fn error(&mut self, message: impl Display) {
133        self.line(BOLD_RED, "error", message);
134    }
135
136    /// `warning: <message>`.
137    pub fn warning(&mut self, message: impl Display) {
138        self.line(BOLD_YELLOW, "warning", message);
139    }
140
141    /// `help: <message>`, how to fix what the previous line reported.
142    pub fn help(&mut self, message: impl Display) {
143        self.line(BOLD_CYAN, "help", message);
144    }
145
146    /// A status line: `verb` right-aligned in 12 columns, then `message`, as
147    /// in `   Compiling mygame v0.1.0`. Nothing under `-q`
148    /// ([`Shell::set_verbosity`]).
149    pub fn status(&mut self, verb: &str, message: impl Display) {
150        if self.verbosity == Verbosity::Quiet {
151            return;
152        }
153        let verb = self.paint(BOLD_GREEN, &format!("{verb:>12}"));
154        self.write(format_args!("{verb} {message}"));
155    }
156
157    /// Another program's output (a compiler's diagnostics), written as it
158    /// was produced: not decoded, so text in the console's code page reaches
159    /// the console as such, and without anything added.
160    pub fn raw(&mut self, bytes: &[u8]) {
161        // A failed write to stderr cannot be reported anywhere better.
162        let _ = self.out.write_all(bytes);
163        let _ = self.out.flush();
164    }
165
166    fn line(&mut self, style: &str, label: &str, message: impl Display) {
167        let label = self.paint(style, label);
168        self.write(format_args!("{label}: {message}"));
169    }
170
171    fn write(&mut self, line: std::fmt::Arguments<'_>) {
172        // A failed write to stderr cannot be reported anywhere better.
173        let _ = writeln!(self.out, "{line}");
174    }
175
176    fn paint(&self, style: &str, text: &str) -> String {
177        if self.color {
178            format!("{style}{text}{RESET}")
179        } else {
180            text.to_owned()
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::env::NameCase;
189    use std::sync::{Arc, Mutex};
190
191    /// A writer the test can read back after the `Shell` has written to it.
192    #[derive(Clone, Default)]
193    struct Captured(Arc<Mutex<Vec<u8>>>);
194
195    impl Write for Captured {
196        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
197            self.0.lock().unwrap().write(buf)
198        }
199        fn flush(&mut self) -> std::io::Result<()> {
200            Ok(())
201        }
202    }
203
204    impl Captured {
205        fn text(&self) -> String {
206            String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
207        }
208    }
209
210    fn shell(
211        choice: Option<ColorChoice>,
212        env: &[(&str, &str)],
213        terminal: bool,
214    ) -> (Shell, Captured) {
215        let out = Captured::default();
216        let env = Env::from_pairs(
217            env.iter().map(|(n, v)| (n.into(), v.into())),
218            NameCase::Sensitive,
219        );
220        (
221            Shell::new(Box::new(out.clone()), choice, &env, terminal),
222            out,
223        )
224    }
225
226    /// `[term] verbose` makes a shell verbose only when the command line
227    /// said neither `-q` nor `-v`: `-q` wins over it, and it never makes a
228    /// shell less verbose (`docs/en/specs/commands.md`, "Available for all
229    /// commands").
230    ///
231    /// Mutation: start a new shell verbose, let `[term] verbose` override
232    /// `-q`, ignore it, or let `false` quiet a `-v`; this test fails.
233    #[test]
234    fn configured_verbose_ranks_below_the_command_line() {
235        // A new shell is neither quiet nor verbose until told.
236        let (fresh, _) = shell(Some(ColorChoice::Never), &[], false);
237        assert!(!fresh.verbose());
238        for (given, configured, verbose, quiet) in [
239            (Verbosity::Normal, true, true, false),
240            (Verbosity::Normal, false, false, false),
241            (Verbosity::Quiet, true, false, true),
242            (Verbosity::Verbose, false, true, false),
243        ] {
244            let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
245            sh.set_verbosity(given);
246            sh.configure(None, configured);
247            assert_eq!(sh.verbose(), verbose, "{given:?}, configured {configured}");
248            sh.status("Compiling", "app");
249            assert_eq!(
250                out.text().is_empty(),
251                quiet,
252                "{given:?}, configured {configured}"
253            );
254        }
255    }
256
257    /// Under `-q` a status line is left out, and everything else is still
258    /// written.
259    ///
260    /// Mutation: ignore `quiet` in `status`, or return early from `error`,
261    /// `warning`, `help` or `raw` too; this test fails.
262    #[test]
263    fn quiet_leaves_out_status_lines_only() {
264        let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
265        sh.set_verbosity(Verbosity::Quiet);
266        sh.status("Compiling", "mygame v0.1.0");
267        sh.error("no compiler found");
268        sh.help("install Build Tools");
269        sh.warning("unused key");
270        sh.raw(
271            b"main.cpp(1): note
272",
273        );
274        assert_eq!(
275            out.text(),
276            "error: no compiler found
277help: install Build Tools
278warning: unused key
279main.cpp(1): note
280"
281        );
282    }
283
284    /// Mutation: change a label in `error`, `warning`, `help` or `status`,
285    /// or the width in `status`; this test fails.
286    #[test]
287    fn lines_without_color() {
288        let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
289        sh.error("no compiler found");
290        sh.help("install Build Tools");
291        sh.warning("unused key");
292        sh.status("Compiling", "mygame v0.1.0");
293        assert_eq!(
294            out.text(),
295            "error: no compiler found\nhelp: install Build Tools\nwarning: unused key\n   Compiling mygame v0.1.0\n"
296        );
297    }
298
299    /// Another program's output goes through byte for byte, with nothing
300    /// added and nothing painted, even when it is not UTF-8.
301    ///
302    /// Mutation: decode it, add a newline, or paint it; this test fails.
303    #[test]
304    fn raw_output_is_written_as_produced() {
305        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
306        let cp932 = [0x83, 0x81, 0x83, 0x82, 0x0d, 0x0a];
307        sh.raw(&cp932);
308        sh.raw(b"x");
309        assert_eq!(*out.0.lock().unwrap(), [&cp932[..], b"x"].concat());
310    }
311
312    /// Mutation: swap or drop the style of any label, or stop painting the
313    /// status verb; this test fails.
314    #[test]
315    fn lines_with_color_paint_only_the_label() {
316        let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
317        sh.error("e");
318        sh.help("h");
319        sh.warning("w");
320        sh.status("Compiling", "m");
321        assert_eq!(
322            out.text(),
323            "\x1b[1;31merror\x1b[0m: e\n\
324             \x1b[1;36mhelp\x1b[0m: h\n\
325             \x1b[1;33mwarning\x1b[0m: w\n\
326             \x1b[1;32m   Compiling\x1b[0m m\n"
327        );
328    }
329
330    /// Mutation: let `NO_COLOR` override an explicit choice (including an
331    /// explicit `auto`), ignore it when no choice was given, or color when not
332    /// a terminal under `auto`; this test fails.
333    #[test]
334    fn color_follows_the_choice_the_terminal_and_no_color() {
335        let on =
336            |choice, env: &[(&str, &str)], terminal| shell(choice, env, terminal).0.uses_color();
337        let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
338        // No choice given: the terminal decides, and NO_COLOR (even empty)
339        // turns color off.
340        assert!(on(None, &[], true));
341        assert!(!on(None, &[], false));
342        assert!(!on(None, no_color, true));
343        // A choice given wins over NO_COLOR.
344        assert!(on(Some(ColorChoice::Auto), no_color, true));
345        assert!(!on(Some(ColorChoice::Auto), &[], false));
346        assert!(on(Some(ColorChoice::Always), no_color, false));
347        assert!(!on(Some(ColorChoice::Never), &[], true));
348    }
349
350    /// `--color`, then `[term] color`, then `NO_COLOR`, then the terminal,
351    /// each level deciding only when every level above it gave nothing.
352    ///
353    /// Mutation: swap any two levels, let `NO_COLOR` beat a choice given or
354    /// configured, or let `auto` ignore the terminal; this test fails.
355    #[test]
356    fn colors_follows_the_order() {
357        use ColorChoice::{Always, Auto, Never};
358        // `--color` beats `[term] color`, and both beat `NO_COLOR`.
359        assert!(colors(Some(Always), Some(Never), true, false));
360        assert!(!colors(Some(Never), Some(Always), false, true));
361        assert!(colors(None, Some(Always), true, false));
362        assert!(!colors(None, Some(Never), false, true));
363        // `auto`, given or configured, follows the terminal over `NO_COLOR`.
364        assert!(colors(Some(Auto), None, true, true));
365        assert!(!colors(Some(Auto), Some(Always), false, false));
366        assert!(colors(None, Some(Auto), true, true));
367        // With neither, `NO_COLOR` decides, then the terminal.
368        assert!(!colors(None, None, true, true));
369        assert!(colors(None, None, false, true));
370        assert!(!colors(None, None, false, false));
371    }
372
373    /// `[term] color` ranks below `--color` and above `NO_COLOR`
374    /// (`commands.md`, "Available for all commands").
375    ///
376    /// Mutation: let `[term] color` beat `--color`, let `NO_COLOR` beat
377    /// `[term] color`, or ignore what `configure` is given; this test fails.
378    #[test]
379    fn the_configured_choice_ranks_between_the_flag_and_no_color() {
380        let on = |given, configured, env: &[(&str, &str)], terminal| {
381            let mut shell = shell(given, env, terminal).0;
382            shell.configure(configured, false);
383            shell.uses_color()
384        };
385        let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
386        let (always, never) = (Some(ColorChoice::Always), Some(ColorChoice::Never));
387        assert!(on(None, always, no_color, false));
388        assert!(!on(None, never, &[], true));
389        assert!(on(None, Some(ColorChoice::Auto), no_color, true));
390        assert!(!on(never, always, &[], true));
391        assert!(on(always, never, &[], false));
392        assert!(!on(None, None, no_color, true));
393        assert!(on(None, None, &[], true));
394    }
395}