/*
Hurry Curry! - a game about cooking
Copyright (C) 2025 Hurry Curry! Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, version 3 of the License only.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
*/
pub mod error;
pub use error::*;
pub mod message;
#[macro_use]
pub mod macros;
use anyhow::{Error, Result, anyhow};
use std::{collections::HashMap, fs::read_to_string, ops::Index, path::Path, sync::LazyLock};
pub struct Locale(HashMap);
impl Index<&'static str> for Locale {
type Output = str;
fn index(&self, index: &'static str) -> &Self::Output {
self.0.get(index).map(|s| s.as_str()).unwrap_or(index)
}
}
impl Locale {
// pub fn load_from_env() -> Result {
// if let Some(dir) = option_env!("LOCALE_DIR") {
// let mut test_order = Vec::new();
// test_order.extend(var("LC_MESSAGE").ok());
// test_order.extend(var("LC_ALL").or(var("LANG")).ok());
// test_order.push("en_US.UTF-8".to_string());
// } else {
// Ok(Self::load_fallback()?)
// }
// }
pub fn merge(&mut self, other: Self) {
for (k, v) in other.0 {
self.0.entry(k).or_insert(v);
}
}
pub fn load(path: &Path) -> Result {
Self::parse(&read_to_string(path)?)
}
pub fn load_fallback() -> Result {
Self::parse(include_str!("../../../locale/en.ini"))
}
pub fn parse(ini: &str) -> Result {
Ok(Self(
ini.lines()
.skip(1)
.map(|l| {
let (k, v) = l.split_once("=").ok_or(anyhow!("'=' missing"))?;
Ok::<_, Error>((k.trim_end().to_owned(), v.trim_start().replace("%n", "\n")))
})
.collect::>>()?,
))
}
pub fn get(&self, id: &str) -> Option<&str> {
self.0.get(id).map(|x| x.as_str())
}
}
pub static GLOBAL_LOCALE: LazyLock = LazyLock::new(|| Locale::load_fallback().unwrap());
pub fn tr(s: &'static str) -> &'static str {
&GLOBAL_LOCALE[s] // TODO crash or placeholder?
}