use std::collections::HashMap;
use std::path::Path;
#[derive(Debug, thiserror::Error)]
pub enum LangError {
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("{file}: {source}")]
Json {
file: String,
source: serde_json::Error,
},
#[error("invalid locale name {0:?}")]
BadLocale(String),
}
pub fn valid_locale(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 35
&& s.starts_with(|c: char| c.is_ascii_alphanumeric())
&& s.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}
fn norm(s: &str) -> String {
s.to_ascii_lowercase().replace('_', "-")
}
#[derive(Debug, Clone)]
pub struct Lang {
messages: HashMap<String, HashMap<String, String>>,
locale: String,
fallback: String,
}
impl Lang {
pub fn new(fallback: &str) -> Self {
Self {
messages: HashMap::new(),
locale: norm(fallback),
fallback: norm(fallback),
}
}
pub fn load_dir(dir: impl AsRef<Path>, fallback: &str) -> Result<Self, LangError> {
let mut l = Self::new(fallback);
for e in std::fs::read_dir(dir.as_ref())? {
let p = e?.path();
if p.extension().is_some_and(|x| x == "json")
&& let Some(stem) = p.file_stem().and_then(|s| s.to_str())
{
if valid_locale(stem) {
l.load_file(&p, stem)?;
} else {
tracing::warn!("lang: skipping file with invalid locale name {stem:?}");
}
}
}
Ok(l)
}
pub fn load_locale(&mut self, dir: impl AsRef<Path>, locale: &str) -> Result<(), LangError> {
if !valid_locale(locale) {
return Err(LangError::BadLocale(locale.into()));
}
self.load_file(&dir.as_ref().join(format!("{locale}.json")), locale)
}
fn load_file(&mut self, path: &Path, locale: &str) -> Result<(), LangError> {
let text = std::fs::read_to_string(path)?;
let map: HashMap<String, String> =
serde_json::from_str(&text).map_err(|source| LangError::Json {
file: path.display().to_string(),
source,
})?;
self.messages.entry(norm(locale)).or_default().extend(map);
Ok(())
}
pub fn insert<'a>(&mut self, locale: &str, msgs: impl IntoIterator<Item = (&'a str, &'a str)>) {
self.messages
.entry(norm(locale))
.or_default()
.extend(msgs.into_iter().map(|(k, v)| (k.into(), v.into())));
}
pub fn set_locale(&mut self, locale: &str) {
self.locale = norm(locale);
}
pub fn trans(&self, key: &str, args: &[(&str, &str)]) -> String {
self.trans_in(&self.locale, key, args)
}
pub fn trans_in(&self, locale: &str, key: &str, args: &[(&str, &str)]) -> String {
match self.lookup(locale, key) {
Some(m) => fill(m, args),
None => key.to_string(),
}
}
pub fn trans_choice(&self, key: &str, count: i64, args: &[(&str, &str)]) -> String {
self.trans_choice_in(&self.locale, key, count, args)
}
pub fn trans_choice_in(
&self,
locale: &str,
key: &str,
count: i64,
args: &[(&str, &str)],
) -> String {
let Some(m) = self.lookup(locale, key) else {
return key.to_string();
};
let form = if count == 1 {
m.split('|').next()
} else {
m.split('|').nth(1).or_else(|| m.split('|').next())
}
.unwrap_or(m);
let c = count.to_string();
let mut all: Vec<(&str, &str)> = args.to_vec();
all.push(("count", &c));
fill(form, &all)
}
fn lookup(&self, locale: &str, key: &str) -> Option<&str> {
let l = norm(locale);
let lang = l.split('-').next().unwrap_or(&l);
[l.as_str(), lang, self.fallback.as_str()]
.into_iter()
.find_map(|loc| self.messages.get(loc)?.get(key))
.map(String::as_str)
}
pub fn locales(&self) -> Vec<String> {
let mut v: Vec<String> = self.messages.keys().cloned().collect();
v.sort();
v
}
pub fn negotiate(&self, header: &str) -> String {
let mut prefs: Vec<(f32, usize, String)> = header
.split(',')
.enumerate()
.filter_map(|(i, part)| {
let mut it = part.split(';');
let tag = it.next()?.trim();
let q = it
.find_map(|p| p.trim().strip_prefix("q="))
.map_or(Some(1.0), |v| v.trim().parse::<f32>().ok())?;
(q > 0.0 && tag != "*" && !tag.is_empty()).then(|| (q, i, norm(tag)))
})
.collect();
prefs.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
for (_, _, tag) in prefs {
let lang = tag.split('-').next().unwrap_or(&tag);
for cand in [tag.as_str(), lang] {
if self.messages.contains_key(cand) {
return cand.to_string();
}
}
}
self.fallback.clone()
}
}
fn fill(msg: &str, args: &[(&str, &str)]) -> String {
let mut out = String::with_capacity(msg.len());
let mut rest = msg;
while let Some(i) = rest.find(':') {
out.push_str(&rest[..i]);
let after = &rest[i + 1..];
let end = after
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(after.len());
match args
.iter()
.find(|(k, _)| !k.is_empty() && *k == &after[..end])
{
Some((_, v)) => {
out.push_str(v);
rest = &after[end..];
}
None => {
out.push(':');
rest = after;
}
}
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Lang {
let mut l = Lang::new("en");
l.insert(
"en",
[
("hi", "Hello :name"),
("items", ":count item|:count items"),
("only", "same"),
],
);
l.insert("fr", [("hi", "Salut :name")]);
l.insert("pt", [("hi", "Ola :name")]);
l
}
#[test]
fn trans_fallback_and_missing() {
let mut l = sample();
assert_eq!(l.trans("hi", &[("name", "A")]), "Hello A");
l.set_locale("fr");
assert_eq!(l.trans("hi", &[("name", "A")]), "Salut A");
assert_eq!(l.trans("only", &[]), "same", "falls back to en");
assert_eq!(l.trans("nope", &[]), "nope");
l.set_locale("../../etc/passwd");
assert_eq!(l.trans("hi", &[("name", "A")]), "Hello A", "unknown locale");
assert_eq!(l.trans_in("pt-BR", "hi", &[("name", "A")]), "Ola A");
assert_eq!(l.trans_in("pt_br", "hi", &[("name", "A")]), "Ola A");
assert_eq!(l.trans_in("", "hi", &[("name", "A")]), "Hello A");
}
#[test]
fn placeholders_single_pass() {
let l = sample();
assert_eq!(l.trans("hi", &[("name", ":name")]), "Hello :name");
assert_eq!(fill("a :x b :y: c:", &[("x", "1")]), "a 1 b :y: c:");
assert_eq!(fill("time 10:30", &[("30", "x")]), "time 10x");
}
#[test]
fn choice() {
let l = sample();
assert_eq!(l.trans_choice("items", 1, &[]), "1 item");
assert_eq!(l.trans_choice("items", 0, &[]), "0 items");
assert_eq!(l.trans_choice("items", 5, &[]), "5 items");
assert_eq!(l.trans_choice("only", 5, &[]), "same");
assert_eq!(l.trans_choice("zzz", 5, &[]), "zzz");
}
#[test]
fn negotiate_q_values() {
let l = sample();
assert_eq!(l.negotiate("fr-CA,fr;q=0.9,en;q=0.8"), "fr");
assert_eq!(l.negotiate("de, en;q=0.4, pt;q=0.7"), "pt");
assert_eq!(l.negotiate("fr;q=0, en;q=0.1"), "en", "q=0 refused");
assert_eq!(l.negotiate("de, ja;q=0.5"), "en", "no match -> fallback");
assert_eq!(l.negotiate("*"), "en");
assert_eq!(l.negotiate(""), "en");
assert_eq!(
l.negotiate(";;q=,,=x, fr;q=abc"),
"en",
"garbage never panics"
);
}
#[test]
fn load_dir_and_traversal() {
let ns = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("ryuk-lang-{ns}"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("en.json"), r#"{"hi":"Hello :name"}"#).unwrap();
std::fs::write(dir.join("fr.json"), r#"{"hi":"Salut :name"}"#).unwrap();
std::fs::write(dir.join("bad name.json"), r#"{"hi":"x"}"#).unwrap();
let mut l = Lang::load_dir(&dir, "en").unwrap();
assert_eq!(l.locales(), ["en", "fr"]);
assert_eq!(l.trans_in("fr", "hi", &[("name", "Z")]), "Salut Z");
for bad in [
"../en",
"a/b",
"a\\b",
"",
"..",
".x",
"en\0",
&"a".repeat(36),
] {
assert!(!valid_locale(bad), "{bad:?}");
assert!(matches!(
l.load_locale(&dir, bad),
Err(LangError::BadLocale(_))
));
}
std::fs::write(dir.join("zz.json"), r#"{"a":1}"#).unwrap();
assert!(matches!(
l.load_locale(&dir, "zz"),
Err(LangError::Json { .. })
));
assert!(matches!(l.load_locale(&dir, "xx"), Err(LangError::Io(_))));
l.load_locale(&dir, "pt-BR").unwrap_err();
std::fs::remove_file(dir.join("bad name.json")).unwrap();
std::fs::remove_file(dir.join("zz.json")).unwrap();
std::fs::remove_file(dir.join("en.json")).unwrap();
std::fs::remove_file(dir.join("fr.json")).unwrap();
std::fs::remove_dir(&dir).unwrap();
}
}