use std::sync::atomic::{AtomicBool, Ordering};
static COLOR_ENABLED: AtomicBool = AtomicBool::new(true);
pub fn set_enabled(on: bool) {
COLOR_ENABLED.store(on, Ordering::Relaxed);
}
pub fn enabled() -> bool {
COLOR_ENABLED.load(Ordering::Relaxed)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
Gray,
None,
}
impl Color {
fn code(self) -> Option<&'static str> {
Some(match self {
Color::Red => "31",
Color::Green => "32",
Color::Yellow => "33",
Color::Blue => "34",
Color::Magenta => "35",
Color::Cyan => "36",
Color::Gray => "90",
Color::None => return None,
})
}
pub fn paint<S: AsRef<str>>(self, s: S) -> String {
match (enabled(), self.code()) {
(true, Some(c)) => format!("\x1b[{}m{}\x1b[0m", c, s.as_ref()),
_ => s.as_ref().to_string(),
}
}
}
pub fn env_default() -> bool {
if std::env::var_os("NO_COLOR").is_some() {
return false;
}
if let Some(term) = std::env::var_os("TERM") {
if term == "dumb" {
return false;
}
}
is_stdout_tty()
}
pub fn is_stdout_tty() -> bool {
is_tty(1)
}
pub fn is_stderr_tty() -> bool {
is_tty(2)
}
#[cfg(unix)]
fn is_tty(fd: i32) -> bool {
extern "C" {
fn isatty(fd: i32) -> i32;
}
unsafe { isatty(fd) == 1 }
}
#[cfg(not(unix))]
fn is_tty(_fd: i32) -> bool {
true
}
macro_rules! attr {
($name:ident, $open:expr) => {
pub fn $name<S: AsRef<str>>(s: S) -> String {
if enabled() {
format!("\x1b[{}m{}\x1b[0m", $open, s.as_ref())
} else {
s.as_ref().to_string()
}
}
};
}
attr!(bold, "1");
attr!(dim, "2");
attr!(italic, "3");
attr!(underline, "4");
pub fn red<S: AsRef<str>>(s: S) -> String { Color::Red.paint(s) }
pub fn green<S: AsRef<str>>(s: S) -> String { Color::Green.paint(s) }
pub fn yellow<S: AsRef<str>>(s: S) -> String { Color::Yellow.paint(s) }
pub fn blue<S: AsRef<str>>(s: S) -> String { Color::Blue.paint(s) }
pub fn magenta<S: AsRef<str>>(s: S) -> String { Color::Magenta.paint(s) }
pub fn cyan<S: AsRef<str>>(s: S) -> String { Color::Cyan.paint(s) }
pub fn gray<S: AsRef<str>>(s: S) -> String { Color::Gray.paint(s) }
pub fn heading<S: AsRef<str>>(s: S) -> String {
let c = crate::theme::active().color_heading;
bold(c.paint(s))
}