1use std::sync::atomic::{AtomicBool, Ordering};
9
10static COLOR_ENABLED: AtomicBool = AtomicBool::new(true);
11
12pub fn set_enabled(on: bool) {
14 COLOR_ENABLED.store(on, Ordering::Relaxed);
15}
16pub fn enabled() -> bool {
18 COLOR_ENABLED.load(Ordering::Relaxed)
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Color {
24 Red,
25 Green,
26 Yellow,
27 Blue,
28 Magenta,
29 Cyan,
30 Gray,
31 None,
33}
34
35impl Color {
36 fn code(self) -> Option<&'static str> {
37 Some(match self {
38 Color::Red => "31",
39 Color::Green => "32",
40 Color::Yellow => "33",
41 Color::Blue => "34",
42 Color::Magenta => "35",
43 Color::Cyan => "36",
44 Color::Gray => "90",
45 Color::None => return None,
46 })
47 }
48 pub fn paint<S: AsRef<str>>(self, s: S) -> String {
50 match (enabled(), self.code()) {
51 (true, Some(c)) => format!("\x1b[{}m{}\x1b[0m", c, s.as_ref()),
52 _ => s.as_ref().to_string(),
53 }
54 }
55}
56
57pub fn env_default() -> bool {
60 if std::env::var_os("NO_COLOR").is_some() {
61 return false;
62 }
63 if let Some(term) = std::env::var_os("TERM") {
64 if term == "dumb" {
65 return false;
66 }
67 }
68 is_stdout_tty()
69}
70
71pub fn is_stdout_tty() -> bool {
72 is_tty(1)
73}
74pub fn is_stderr_tty() -> bool {
75 is_tty(2)
76}
77
78#[cfg(unix)]
79fn is_tty(fd: i32) -> bool {
80 extern "C" {
81 fn isatty(fd: i32) -> i32;
82 }
83 unsafe { isatty(fd) == 1 }
84}
85#[cfg(not(unix))]
86fn is_tty(_fd: i32) -> bool {
87 true
88}
89
90macro_rules! attr {
91 ($name:ident, $open:expr) => {
92 pub fn $name<S: AsRef<str>>(s: S) -> String {
94 if enabled() {
95 format!("\x1b[{}m{}\x1b[0m", $open, s.as_ref())
96 } else {
97 s.as_ref().to_string()
98 }
99 }
100 };
101}
102
103attr!(bold, "1");
104attr!(dim, "2");
105attr!(italic, "3");
106attr!(underline, "4");
107
108pub fn red<S: AsRef<str>>(s: S) -> String { Color::Red.paint(s) }
110pub fn green<S: AsRef<str>>(s: S) -> String { Color::Green.paint(s) }
111pub fn yellow<S: AsRef<str>>(s: S) -> String { Color::Yellow.paint(s) }
112pub fn blue<S: AsRef<str>>(s: S) -> String { Color::Blue.paint(s) }
113pub fn magenta<S: AsRef<str>>(s: S) -> String { Color::Magenta.paint(s) }
114pub fn cyan<S: AsRef<str>>(s: S) -> String { Color::Cyan.paint(s) }
115pub fn gray<S: AsRef<str>>(s: S) -> String { Color::Gray.paint(s) }
116
117pub fn heading<S: AsRef<str>>(s: S) -> String {
119 let c = crate::theme::active().color_heading;
120 bold(c.paint(s))
121}