use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::RwLock;
use crate::context::Context;
use crate::error::Error;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::{IntoResponse, Response};
pub const DEFAULT: &str = "en";
tokio::task_local! {
static LOCALE: String;
}
pub fn locale() -> String {
LOCALE
.try_with(String::clone)
.unwrap_or_else(|_| DEFAULT.to_owned())
}
pub async fn with_locale<F: Future>(locale: impl Into<String>, fut: F) -> F::Output {
LOCALE.scope(locale.into(), fut).await
}
static TRANSLATIONS: RwLock<Option<HashMap<String, String>>> = RwLock::new(None);
pub fn load(dir: impl AsRef<Path>) -> crate::Result<()> {
let dir = dir.as_ref();
let mut files: Vec<_> = std::fs::read_dir(dir)
.map_err(|e| Error::internal(format!("reading {}: {e}", dir.display())))?
.filter_map(|entry| entry.ok().map(|e| e.path()))
.filter(|path| {
path.extension()
.is_some_and(|ext| ext == "yml" || ext == "yaml")
})
.collect();
files.sort();
let mut translations = HashMap::new();
for file in files {
let text = std::fs::read_to_string(&file)
.map_err(|e| Error::internal(format!("reading {}: {e}", file.display())))?;
let yaml: serde_yaml::Value = serde_yaml::from_str(&text)
.map_err(|e| Error::internal(format!("{}: {e}", file.display())))?;
flatten(String::new(), &yaml, &mut translations);
}
*TRANSLATIONS.write().unwrap_or_else(|e| e.into_inner()) = Some(translations);
Ok(())
}
fn flatten(prefix: String, value: &serde_yaml::Value, out: &mut HashMap<String, String>) {
use serde_yaml::Value as Y;
let text = match value {
Y::Mapping(map) => {
for (key, value) in map {
let key = match key {
Y::String(s) => s.clone(),
Y::Bool(b) => b.to_string(),
Y::Number(n) => n.to_string(),
_ => continue,
};
let path = if prefix.is_empty() {
key
} else {
format!("{prefix}.{key}")
};
flatten(path, value, out);
}
return;
}
Y::String(s) => s.clone(),
Y::Bool(b) => b.to_string(),
Y::Number(n) => n.to_string(),
_ => return,
};
out.insert(prefix, text);
}
pub fn t(key: impl AsRef<str>) -> String {
let locale = locale();
let full = format!("{locale}.{}", key.as_ref());
TRANSLATIONS
.read()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.and_then(|translations| translations.get(&full).cloned())
.unwrap_or_else(|| format!("Translation missing: {full}"))
}
pub fn t_with(key: impl AsRef<str>, values: &[(&str, &str)]) -> String {
values.iter().fold(t(key), |text, (name, value)| {
text.replace(&format!("%{{{name}}}"), value)
})
}
pub struct Locales {
available: Vec<String>,
}
impl Locales {
pub fn new<S: Into<String>>(available: impl IntoIterator<Item = S>) -> Self {
let available: Vec<String> = available.into_iter().map(Into::into).collect();
assert!(
!available.is_empty(),
"Locales::new needs at least one locale"
);
Self { available }
}
}
impl Middleware for Locales {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let requested = ctx.params().get("locale").map(str::to_owned);
let locale = match requested {
None => self.available[0].clone(),
Some(locale) if self.available.contains(&locale) => locale,
Some(locale) => {
let error = Error::bad_request(format!("\"{locale}\" is not a valid locale"));
return Box::pin(async move { error.into_response() });
}
};
Box::pin(LOCALE.scope(locale, next.run(ctx)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::App;
use crate::testing::TestClient;
#[tokio::test]
async fn sets_the_locale_from_the_param() {
let app = App::new()
.middleware(Locales::new(["en", "he"]))
.routes(|r| {
r.get("/", |_ctx| async { locale() });
});
let client = TestClient::new(app);
assert_eq!(client.get("/").await.body_text(), "en");
assert_eq!(client.get("/?locale=he").await.body_text(), "he");
let unknown = client.get("/?locale=xx").await;
assert_eq!(unknown.status(), 400);
assert_eq!(locale(), DEFAULT, "outside a request");
assert_eq!(with_locale("he", async { locale() }).await, "he");
}
#[tokio::test]
async fn translates_from_rails_locale_files() {
let dir = std::env::temp_dir().join(format!("glacier-i18n-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("en.yml"),
"en:\n versions:\n ios:\n warning: Update soon\n errors:\n not_found: Not found\n busy: \"In use on %{device} (%{device})\"\n",
)
.unwrap();
std::fs::write(
dir.join("he.yml"),
"he:\n errors:\n not_found: \"לא נמצא\"\n",
)
.unwrap();
load(&dir).unwrap();
assert_eq!(t("versions.ios.warning"), "Update soon");
assert_eq!(
t_with("errors.busy", &[("device", "iPad")]),
"In use on iPad (iPad)"
);
assert_eq!(
with_locale("he", async { t("errors.not_found") }).await,
"לא נמצא"
);
assert_eq!(
with_locale("he", async { t("versions.ios.warning") }).await,
"Translation missing: he.versions.ios.warning"
);
std::fs::remove_dir_all(dir).unwrap();
}
}