use crate::Capability;
use std::env;
use std::io::IsTerminal;
pub fn detect() -> Capability {
detect_from_env(|k| env::var(k).ok())
}
pub fn detect_color() -> bool {
detect_color_from(|k| env::var(k).ok(), std::io::stdout().is_terminal())
}
fn detect_from_env(get: impl Fn(&str) -> Option<String>) -> Capability {
if let Some(v) = get("APB_FORCE_CAP") {
return match v.as_str() {
"ascii" => Capability::Ascii,
"eighth" => Capability::EighthBlock,
_ => Capability::EighthBlock,
};
}
Capability::EighthBlock
}
fn detect_color_from(get: impl Fn(&str) -> Option<String>, is_tty: bool) -> bool {
if get("NO_COLOR").is_some() {
return false;
}
is_tty
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn env(pairs: &[(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<&'static str, &'static str> = pairs.iter().copied().collect();
move |k| map.get(k).map(|s| s.to_string())
}
#[test] fn force_overrides_default() {
assert_eq!(
detect_from_env(env(&[("APB_FORCE_CAP", "ascii")])),
Capability::Ascii
);
}
#[test] fn default_is_eighth() {
assert_eq!(detect_from_env(env(&[])), Capability::EighthBlock);
}
#[test] fn force_eighth_string() {
assert_eq!(
detect_from_env(env(&[("APB_FORCE_CAP", "eighth")])),
Capability::EighthBlock
);
}
#[test] fn invalid_force_falls_back_to_eighth() {
assert_eq!(
detect_from_env(env(&[("APB_FORCE_CAP", "garbage")])),
Capability::EighthBlock
);
}
#[test] fn color_off_when_no_color_set() {
assert!(!detect_color_from(env(&[("NO_COLOR", "1")]), true));
assert!(!detect_color_from(env(&[("NO_COLOR", "")]), true));
}
#[test] fn color_off_when_not_tty() {
assert!(!detect_color_from(env(&[]), false));
}
#[test] fn color_on_when_tty_and_no_no_color() {
assert!(detect_color_from(env(&[]), true));
}
#[test] fn no_color_beats_tty() {
assert!(!detect_color_from(env(&[("NO_COLOR", "1")]), true));
}
}