use agnix_core::i18n::{is_supported, normalize_locale};
use rust_i18n::set_locale;
pub fn init_from_env() {
let locale = detect_locale();
set_locale(&locale);
}
pub fn init_from_config(config_locale: &str) {
let normalized = normalize_locale(config_locale);
if is_supported(&normalized) {
set_locale(&normalized);
}
}
fn detect_locale() -> String {
if let Ok(locale) = std::env::var("AGNIX_LOCALE") {
let normalized = normalize_locale(&locale);
if is_supported(&normalized) {
return normalized;
}
}
if let Ok(lang) = std::env::var("LC_ALL").or_else(|_| std::env::var("LANG")) {
let normalized = normalize_locale(&lang);
if is_supported(&normalized) {
return normalized;
}
}
if let Some(locale) = sys_locale::get_locale() {
let normalized = normalize_locale(&locale);
if is_supported(&normalized) {
return normalized;
}
}
"en".to_string()
}
#[cfg(test)]
pub(crate) static LOCALE_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normalize_english() {
assert_eq!(normalize_locale("en"), "en");
assert_eq!(normalize_locale("en_US"), "en");
assert_eq!(normalize_locale("en_US.UTF-8"), "en");
}
#[test]
fn test_normalize_spanish() {
assert_eq!(normalize_locale("es"), "es");
assert_eq!(normalize_locale("es_ES"), "es");
assert_eq!(normalize_locale("es_ES.UTF-8"), "es");
}
#[test]
fn test_normalize_chinese() {
assert_eq!(normalize_locale("zh_CN"), "zh-CN");
assert_eq!(normalize_locale("zh-CN"), "zh-CN");
assert_eq!(normalize_locale("zh_CN.UTF-8"), "zh-CN");
assert_eq!(normalize_locale("zh-Hans"), "zh-CN");
}
#[test]
fn test_unsupported_returns_language_code() {
assert_eq!(normalize_locale("fr_FR"), "fr");
assert!(!is_supported("fr"));
}
#[test]
fn test_is_supported() {
assert!(is_supported("en"));
assert!(is_supported("es"));
assert!(is_supported("zh-CN"));
assert!(!is_supported("fr"));
}
#[test]
fn test_init_from_env_does_not_panic() {
let _guard = LOCALE_MUTEX.lock().unwrap();
init_from_env();
}
#[test]
fn test_init_from_config_supported_and_unsupported() {
let _guard = LOCALE_MUTEX.lock().unwrap();
set_locale("en");
init_from_config("es");
let current = rust_i18n::locale();
assert_eq!(&*current, "es");
init_from_config("xx-unsupported");
let current = rust_i18n::locale();
assert_eq!(
&*current, "es",
"unsupported locale should not change current"
);
set_locale("en");
}
}