use once_cell::sync::Lazy;
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IconMode {
Classic,
NerdFont,
Auto,
}
type IconDetector = fn() -> IconMode;
static ICON_DETECTOR: Lazy<Mutex<IconDetector>> = Lazy::new(|| Mutex::new(default_icon_detector));
pub fn set_icon_detector(detector: IconDetector) {
let mut guard = ICON_DETECTOR.lock().unwrap();
*guard = detector;
}
pub fn detect_icon_mode() -> IconMode {
let detector = ICON_DETECTOR.lock().unwrap();
let mode = (*detector)();
match mode {
IconMode::Auto => resolve_auto(),
other => other,
}
}
fn resolve_auto() -> IconMode {
match std::env::var("NERD_FONT") {
Ok(val)
if val == "1"
|| val.eq_ignore_ascii_case("true")
|| val.eq_ignore_ascii_case("yes") =>
{
IconMode::NerdFont
}
_ => IconMode::Classic,
}
}
fn default_icon_detector() -> IconMode {
IconMode::Auto
}
#[cfg(test)]
mod tests {
use super::*;
use serial_test::serial;
#[test]
#[serial]
fn test_detect_icon_mode_default_is_classic() {
set_icon_detector(default_icon_detector);
std::env::remove_var("NERD_FONT");
let mode = detect_icon_mode();
assert_eq!(mode, IconMode::Classic);
}
#[test]
#[serial]
fn test_detect_icon_mode_with_env_var() {
set_icon_detector(default_icon_detector);
std::env::set_var("NERD_FONT", "1");
let mode = detect_icon_mode();
assert_eq!(mode, IconMode::NerdFont);
std::env::remove_var("NERD_FONT");
}
#[test]
#[serial]
fn test_detect_icon_mode_with_env_var_true() {
set_icon_detector(default_icon_detector);
std::env::set_var("NERD_FONT", "true");
let mode = detect_icon_mode();
assert_eq!(mode, IconMode::NerdFont);
std::env::remove_var("NERD_FONT");
}
#[test]
#[serial]
fn test_detect_icon_mode_with_env_var_yes() {
set_icon_detector(default_icon_detector);
std::env::set_var("NERD_FONT", "YES");
let mode = detect_icon_mode();
assert_eq!(mode, IconMode::NerdFont);
std::env::remove_var("NERD_FONT");
}
#[test]
#[serial]
fn test_detect_icon_mode_with_env_var_false() {
set_icon_detector(default_icon_detector);
std::env::set_var("NERD_FONT", "0");
let mode = detect_icon_mode();
assert_eq!(mode, IconMode::Classic);
std::env::remove_var("NERD_FONT");
}
#[test]
#[serial]
fn test_set_icon_detector_override() {
set_icon_detector(|| IconMode::NerdFont);
assert_eq!(detect_icon_mode(), IconMode::NerdFont);
set_icon_detector(|| IconMode::Classic);
assert_eq!(detect_icon_mode(), IconMode::Classic);
set_icon_detector(default_icon_detector);
}
#[test]
#[serial]
fn test_detect_never_returns_auto() {
set_icon_detector(|| IconMode::Auto);
let mode = detect_icon_mode();
assert_ne!(mode, IconMode::Auto);
set_icon_detector(default_icon_detector);
}
}