pub mod active;
pub mod negotiate;
pub mod report;
pub use active::{active, install};
pub use negotiate::{negotiate, SUPPORTED};
use crate::error::{Failure, Result};
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};
use unic_langid::LanguageIdentifier;
const CATALOGUES: [(&str, &str); 12] = [
("en", include_str!("locales/en.ftl")),
("en", include_str!("locales/errors-usage.en.ftl")),
("en", include_str!("locales/errors-sql.en.ftl")),
("en", include_str!("locales/errors-config.en.ftl")),
("en", include_str!("locales/errors-server.en.ftl")),
("en", include_str!("locales/errors-data.en.ftl")),
("pt-BR", include_str!("locales/pt-BR.ftl")),
("pt-BR", include_str!("locales/errors-usage.pt-BR.ftl")),
("pt-BR", include_str!("locales/errors-sql.pt-BR.ftl")),
("pt-BR", include_str!("locales/errors-config.pt-BR.ftl")),
("pt-BR", include_str!("locales/errors-server.pt-BR.ftl")),
("pt-BR", include_str!("locales/errors-data.pt-BR.ftl")),
];
const FAILURE_MESSAGE_PREFIX: &str = "err-";
const FAILURE_HINT_PREFIX: &str = "hint-";
fn failure_id(prefix: &str, code: &str) -> String {
let mut id = String::with_capacity(prefix.len() + code.len());
id.push_str(prefix);
id.extend(code.chars().map(|part| match part {
'.' | '_' => '-',
other => other,
}));
id
}
pub struct Messages {
language: LanguageIdentifier,
bundle: FluentBundle<FluentResource>,
}
impl std::fmt::Debug for Messages {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Messages")
.field("language", &self.language.to_string())
.finish_non_exhaustive()
}
}
impl Messages {
pub fn load(language: LanguageIdentifier) -> Result<Self> {
let tag = language.to_string();
let sources: Vec<&str> = CATALOGUES
.iter()
.filter(|(name, _)| *name == tag)
.map(|(_, source)| *source)
.collect();
if sources.is_empty() {
return Err(
Failure::config("i18n.missing_catalogue", format!("`{tag}`"))
.with_detail("detail", tag)
.with_detail("languages", SUPPORTED.join(", "))
.with_hint(format!("carried languages: {}", SUPPORTED.join(", "))),
);
}
let mut bundle = FluentBundle::new(vec![language.clone()]);
bundle.set_use_isolating(false);
for source in sources {
add_catalogue(&mut bundle, source, &tag)?;
}
Ok(Self { language, bundle })
}
#[must_use]
pub fn empty(language: LanguageIdentifier) -> Self {
let mut bundle = FluentBundle::new(vec![language.clone()]);
bundle.set_use_isolating(false);
Self { language, bundle }
}
pub fn resolve(requested: Option<&str>, stored: Option<&str>) -> Result<Self> {
Self::load(negotiate::negotiate(requested, stored)?)
}
#[must_use]
pub const fn language(&self) -> &LanguageIdentifier {
&self.language
}
#[must_use]
pub fn get(&self, id: &str) -> String {
self.format(id, &[])
}
#[must_use]
pub fn format(&self, id: &str, arguments: &[(&str, &str)]) -> String {
let Some(pattern) = self.bundle.get_message(id).and_then(|found| found.value()) else {
return id.to_owned();
};
let mut args = FluentArgs::new();
for (name, value) in arguments {
args.set(*name, *value);
}
let mut ignored = Vec::new();
self.bundle
.format_pattern(pattern, Some(&args), &mut ignored)
.into_owned()
}
#[must_use]
pub fn carries(&self, id: &str) -> bool {
self.bundle
.get_message(id)
.is_some_and(|found| found.value().is_some())
}
#[must_use]
pub fn failure_message(
&self,
code: &str,
details: &[(&'static str, String)],
) -> Option<String> {
self.carried(&failure_id(FAILURE_MESSAGE_PREFIX, code), details)
}
#[must_use]
pub fn failure_hint(&self, code: &str, details: &[(&'static str, String)]) -> Option<String> {
self.carried(&failure_id(FAILURE_HINT_PREFIX, code), details)
}
fn carried(&self, id: &str, details: &[(&'static str, String)]) -> Option<String> {
if !self.carries(id) {
return None;
}
let arguments: Vec<(&str, &str)> = details
.iter()
.map(|(name, value)| (*name, value.as_str()))
.collect();
Some(self.format(id, &arguments))
}
}
fn add_catalogue(bundle: &mut FluentBundle<FluentResource>, source: &str, tag: &str) -> Result<()> {
let resource = FluentResource::try_new(source.to_owned()).map_err(|(_, errors)| {
Failure::config(
"i18n.malformed_catalogue",
format!("the messages carried for `{tag}` do not parse"),
)
.with_detail("detail", tag)
.with_cause(format!("{} problem(s) in the source", errors.len()))
})?;
bundle.add_resource(resource).map_err(|errors| {
Failure::config(
"i18n.duplicate_message",
format!("the messages carried for `{tag}` name the same message twice"),
)
.with_detail("detail", tag)
.with_cause(format!("{} duplicate(s)", errors.len()))
})
}
#[cfg(test)]
mod tests {
use super::*;
fn messages(tag: &str) -> Messages {
let language = negotiate::parse(tag).expect("a language");
Messages::load(language).expect("carried by this build")
}
#[test]
fn every_carried_language_loads() {
for tag in SUPPORTED {
let loaded = messages(tag);
assert_eq!(loaded.language().to_string(), tag);
}
}
fn named(tag: &str) -> std::collections::BTreeSet<&'static str> {
CATALOGUES
.iter()
.filter(|(name, _)| *name == tag)
.flat_map(|(_, source)| source.lines())
.filter(|line| !line.starts_with('#') && !line.starts_with(' '))
.filter_map(|line| line.split_once(" ="))
.map(|(id, _)| id)
.collect()
}
#[test]
fn every_carried_language_names_the_same_messages() {
let reference = named(SUPPORTED[0]);
assert!(
!reference.is_empty(),
"the reference language names nothing"
);
for tag in SUPPORTED {
let here = named(tag);
let missing: Vec<_> = reference.difference(&here).collect();
let extra: Vec<_> = here.difference(&reference).collect();
assert!(missing.is_empty(), "`{tag}` is missing {missing:?}");
assert!(
extra.is_empty(),
"`{tag}` names {extra:?} and no other does"
);
}
}
#[test]
fn every_named_message_loads() {
for tag in SUPPORTED {
let loaded = messages(tag);
for id in named(tag) {
assert!(loaded.carries(id), "`{id}` is missing from `{tag}`");
}
}
}
#[test]
fn a_failure_code_reaches_its_prose() {
let loaded = messages("pt-BR");
let translated = loaded
.failure_message("sql.multiple_statements", &[])
.expect("carried");
assert!(translated.contains("mais de um"));
assert!(loaded.failure_message("no.such_code", &[]).is_none());
}
#[test]
fn a_measured_value_survives_translation() {
let recorded = [("detail", "900000 > 65536".to_owned())];
let translated = messages("pt-BR")
.failure_message("sql.too_large", &recorded)
.expect("carried");
assert!(
translated.contains("65536"),
"the measurement was dropped: {translated}"
);
assert!(
!translated.contains("the statement"),
"the Portuguese wording carries English: {translated}"
);
}
#[test]
fn a_value_that_was_not_supplied_never_stops_the_work() {
let rendered = messages("en").get("copy-table");
assert!(!rendered.is_empty());
assert!(rendered.starts_with("copying"));
}
#[test]
fn a_substituted_value_arrives_without_stray_marks() {
let rendered = messages("en").format("copy-table", &[("table", "orders")]);
assert_eq!(rendered, "copying orders");
}
#[test]
fn the_two_languages_really_differ() {
let english = messages("en").format("copy-table", &[("table", "orders")]);
let portuguese = messages("pt-BR").format("copy-table", &[("table", "orders")]);
assert_ne!(english, portuguese);
assert!(portuguese.starts_with("copiando"));
}
#[test]
fn a_message_this_build_does_not_carry_never_stops_the_work() {
assert_eq!(messages("en").get("no-such-message"), "no-such-message");
}
#[test]
fn a_language_this_build_does_not_carry_is_refused_plainly() {
let language = negotiate::parse("de-DE").expect("a language");
let failure = Messages::load(language).expect_err("must refuse");
assert_eq!(failure.code(), "i18n.missing_catalogue");
}
#[test]
fn a_diagnostic_rendering_never_carries_the_whole_catalogue() {
let rendered = format!("{:?}", messages("pt-BR"));
assert!(rendered.contains("pt-BR"));
assert!(!rendered.contains("copiando"));
}
}