color.rs

 1use std::io::IsTerminal;
 2
 3pub struct Theme {
 4    pub red: &'static str,
 5    pub green: &'static str,
 6    pub yellow: &'static str,
 7    pub blue: &'static str,
 8    pub bold: &'static str,
 9    pub reset: &'static str,
10}
11
12const ON: Theme = Theme {
13    red: "\x1b[31m",
14    green: "\x1b[32m",
15    yellow: "\x1b[33m",
16    blue: "\x1b[34m",
17    bold: "\x1b[1m",
18    reset: "\x1b[0m",
19};
20
21const OFF: Theme = Theme {
22    red: "",
23    green: "",
24    yellow: "",
25    blue: "",
26    bold: "",
27    reset: "",
28};
29
30fn use_color(is_tty: bool) -> bool {
31    std::env::var_os("NO_COLOR").is_none() && is_tty
32}
33
34/// Colour theme for stdout.
35pub fn stdout_theme() -> &'static Theme {
36    if use_color(std::io::stdout().is_terminal()) {
37        &ON
38    } else {
39        &OFF
40    }
41}
42
43/// Colour theme for stderr.
44pub fn stderr_theme() -> &'static Theme {
45    if use_color(std::io::stderr().is_terminal()) {
46        &ON
47    } else {
48        &OFF
49    }
50}