use std::sync::OnceLock;
static COLOR_ENABLED: OnceLock<bool> = OnceLock::new();
pub fn color_enabled() -> bool {
*COLOR_ENABLED.get_or_init(|| {
if std::env::var("NO_COLOR").is_ok() {
return false;
}
if std::env::var("FORCE_COLOR").is_ok() {
return true;
}
is_tty()
})
}
#[cfg(unix)]
unsafe extern "C" {
fn isatty(fd: i32) -> i32;
}
fn is_tty() -> bool {
#[cfg(unix)]
{
unsafe { isatty(1) != 0 }
}
#[cfg(all(not(unix), windows))]
{
unsafe { is_tty_windows() }
}
#[cfg(all(not(unix), not(windows)))]
{
return false;
}
}
#[cfg(windows)]
unsafe extern "system" {
fn GetStdHandle(nStdHandle: u32) -> *mut u8;
fn GetConsoleMode(hConsoleHandle: *mut u8, lpMode: *mut u32) -> i32;
}
#[cfg(windows)]
fn is_tty_windows() -> bool {
const STD_OUTPUT_HANDLE: u32 = 0xFFFFFFF5;
unsafe {
let handle = GetStdHandle(STD_OUTPUT_HANDLE);
let mut mode: u32 = 0;
GetConsoleMode(handle, &mut mode) != 0
}
}