use std::io::{self, IsTerminal};
pub fn color_enabled() -> bool {
std::env::var_os("NO_COLOR").is_none()
}
pub fn color_on_stdout() -> bool {
color_enabled() && !term_is_dumb() && io::stdout().is_terminal()
}
pub fn color_on_stderr() -> bool {
color_enabled() && !term_is_dumb() && io::stderr().is_terminal()
}
fn term_is_dumb() -> bool {
std::env::var_os("TERM").is_some_and(|v| v == "dumb")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_env;
#[test]
fn respects_no_color() {
let _guard = test_env::lock();
unsafe {
std::env::remove_var("NO_COLOR");
}
assert!(color_enabled());
unsafe {
std::env::set_var("NO_COLOR", "1");
}
assert!(!color_enabled());
assert!(!color_on_stdout());
assert!(!color_on_stderr());
unsafe {
std::env::remove_var("NO_COLOR");
}
}
#[test]
fn term_dumb_disables_color() {
let _guard = test_env::lock();
let saved_term = std::env::var_os("TERM");
unsafe {
std::env::remove_var("NO_COLOR");
std::env::set_var("TERM", "dumb");
}
assert!(color_enabled());
assert!(!color_on_stdout());
assert!(!color_on_stderr());
unsafe {
match saved_term {
Some(term) => std::env::set_var("TERM", term),
None => std::env::remove_var("TERM"),
}
}
}
}