use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::FluentResource;
use std::sync::OnceLock;
use unic_langid::LanguageIdentifier;
const EN: &str = include_str!("../locales/en.ftl");
const PT: &str = include_str!("../locales/pt-BR.ftl");
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UiLang {
En,
PtBr,
}
impl UiLang {
pub fn resolve(explicit: Option<&str>) -> Result<Self, crate::error::Error> {
if let Some(tag) = explicit {
return Ok(match parse_tag(tag)? {
Some(lang) => lang,
None => {
static WARNED: OnceLock<()> = OnceLock::new();
if WARNED.set(()).is_ok() {
eprintln!("{}: {tag}", tr(Self::En, "lang_unsupported"));
}
Self::En
}
});
}
let sys = sys_locale::get_locale().unwrap_or_else(|| "en".into());
Ok(parse_tag(&sys).ok().flatten().unwrap_or(Self::En))
}
pub fn resolve_strict(tag: &str) -> Result<Self, crate::error::Error> {
parse_tag(tag)?
.ok_or_else(|| crate::error::Error::Usage(format!("unsupported locale: {tag}")))
}
pub fn resource(self) -> &'static str {
match self {
Self::En => EN,
Self::PtBr => PT,
}
}
pub fn langid(self) -> LanguageIdentifier {
self.tag()
.parse()
.unwrap_or_else(|_| "en".parse().expect("en is a valid language tag"))
}
pub fn tag(self) -> &'static str {
match self {
Self::En => "en",
Self::PtBr => "pt-BR",
}
}
}
fn parse_tag(tag: &str) -> Result<Option<UiLang>, crate::error::Error> {
let lid: LanguageIdentifier = tag
.parse()
.map_err(|_| crate::error::Error::Usage(format!("malformed locale tag: {tag}")))?;
Ok(match lid.language.as_str() {
"pt" => Some(UiLang::PtBr),
"en" => Some(UiLang::En),
_ => None,
})
}
fn build_bundle(lang: UiLang) -> Option<FluentBundle<FluentResource>> {
let resource = FluentResource::try_new(lang.resource().to_string()).ok()?;
let mut bundle = FluentBundle::new_concurrent(vec![lang.langid()]);
bundle.set_use_isolating(false);
bundle.add_resource(resource).ok()?;
Some(bundle)
}
fn bundle_for(lang: UiLang) -> Option<&'static FluentBundle<FluentResource>> {
static EN_BUNDLE: OnceLock<Option<FluentBundle<FluentResource>>> = OnceLock::new();
static PT_BUNDLE: OnceLock<Option<FluentBundle<FluentResource>>> = OnceLock::new();
let cell = match lang {
UiLang::En => &EN_BUNDLE,
UiLang::PtBr => &PT_BUNDLE,
};
cell.get_or_init(|| build_bundle(lang)).as_ref()
}
pub fn tr(lang: UiLang, key: &str) -> String {
for candidate in [lang, UiLang::En] {
let Some(bundle) = bundle_for(candidate) else {
continue;
};
let Some(message) = bundle.get_message(key) else {
continue;
};
let Some(pattern) = message.value() else {
continue;
};
let mut errors = Vec::new();
let text = bundle.format_pattern(pattern, None, &mut errors);
if errors.is_empty() {
return text.into_owned();
}
}
key.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn entries(body: &str) -> BTreeMap<String, String> {
body.lines()
.map(str::trim_end)
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
.filter_map(|l| l.split_once('='))
.map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
.collect()
}
#[test]
fn pt_does_not_change_json_keys() {
assert_eq!(UiLang::resolve(Some("pt-BR")).unwrap(), UiLang::PtBr);
assert_eq!(
tr(UiLang::PtBr, "warn_cuda_env"),
tr(UiLang::PtBr, "warn_cuda_env")
);
assert!(tr(UiLang::En, "warn_cuda_env").contains("CUDA_VISIBLE_DEVICES"));
}
#[test]
fn both_locales_expose_the_same_keys() {
let en: Vec<String> = entries(EN).into_keys().collect();
let pt: Vec<String> = entries(PT).into_keys().collect();
assert!(!en.is_empty(), "en.ftl must not be empty");
assert_eq!(en, pt, "en.ftl and pt-BR.ftl must expose identical keys");
}
#[test]
fn every_ftl_key_is_valid_utf8_and_nonempty() {
for (name, body) in [("en", EN), ("pt-BR", PT)] {
let map = entries(body);
assert!(!map.is_empty(), "{name}.ftl has no entries");
for (key, value) in map {
assert!(!key.is_empty(), "{name}.ftl has an empty key");
assert!(
!value.is_empty(),
"{name}.ftl key `{key}` has an empty value"
);
let lang = if name == "en" {
UiLang::En
} else {
UiLang::PtBr
};
assert_eq!(tr(lang, &key), value, "tr mismatch for {name}.ftl `{key}`");
}
}
}
#[test]
fn malformed_locale_tag_is_usage() {
for tag in ["!!", "en_US_bogus_tag"] {
let err = UiLang::resolve(Some(tag)).expect_err("a malformed tag must be rejected");
assert_eq!(
err.exit_code(),
2,
"{tag} is malformed and must be a usage error"
);
}
}
#[test]
fn unsupported_but_valid_tag_degrades_to_english() {
for tag in ["es", "xx", "ja-JP"] {
assert_eq!(
UiLang::resolve(Some(tag)).expect("a well-formed tag is not a usage error"),
UiLang::En,
"{tag} must degrade to English"
);
}
}
#[test]
fn strict_refuses_what_resolve_degrades() {
for tag in ["es", "xx", "ja-JP"] {
assert_eq!(
UiLang::resolve(Some(tag)).expect("use must degrade, not fail"),
UiLang::En,
"{tag} must degrade for --lang"
);
let err = UiLang::resolve_strict(tag).expect_err("config must refuse");
assert_eq!(err.exit_code(), 2, "{tag} must not be persisted");
}
assert_eq!(
UiLang::resolve_strict("pt-BR").expect("pt-BR ships with this build"),
UiLang::PtBr
);
let err = UiLang::resolve_strict("!!").expect_err("!! is not a language tag");
assert_eq!(err.exit_code(), 2);
}
#[test]
fn tr_is_stable_across_calls() {
for lang in [UiLang::En, UiLang::PtBr] {
let first = tr(lang, "gpu_missing");
let second = tr(lang, "gpu_missing");
assert!(!first.is_empty(), "{} lost gpu_missing", lang.tag());
assert_eq!(first, second, "{} is not stable across calls", lang.tag());
}
}
#[test]
fn pt_variants_resolve_to_ptbr() {
for tag in ["pt", "pt-BR", "pt-PT"] {
assert_eq!(
UiLang::resolve(Some(tag)).unwrap(),
UiLang::PtBr,
"{tag} must resolve to pt-BR"
);
}
}
#[test]
fn tr_does_not_match_key_prefix() {
assert!(entries(EN).contains_key("gpu_missing"));
assert!(!entries(EN).contains_key("gpu"));
assert_eq!(tr(UiLang::En, "gpu"), "gpu");
assert_ne!(tr(UiLang::En, "gpu"), tr(UiLang::En, "gpu_missing"));
assert_eq!(tr(UiLang::PtBr, "need"), "need");
assert_ne!(tr(UiLang::PtBr, "need"), tr(UiLang::PtBr, "need_yes"));
}
}