1use std::collections::BTreeMap;
5
6pub static I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
8
9#[derive(Debug, Clone, Default)]
10pub struct Translations(BTreeMap<String, String>);
11
12impl Translations {
13 pub fn parse(ftl: &str) -> Self {
14 let mut out = Self::default();
15 out.add(ftl);
16 out
17 }
18
19 pub fn add(&mut self, ftl: &str) {
20 for line in ftl.lines() {
21 let line = line.trim();
22 if line.starts_with('#') {
23 continue;
24 }
25 if let Some((key, text)) = line.split_once('=') {
26 self.0.insert(key.trim().into(), text.trim().into());
27 }
28 }
29 }
30
31 pub fn has(&self, key: &str) -> bool {
32 self.0.contains_key(key)
33 }
34
35 pub fn tr<'a>(&'a self, key: &'a str) -> &'a str {
37 self.0.get(key).map_or(key, String::as_str)
38 }
39
40 pub fn tr_arg(&self, key: &str, arg: &str) -> String {
43 let text = self.tr(key);
44 if arg.is_empty() || text.contains("{ $arg }") {
45 text.replace("{ $arg }", arg)
46 } else {
47 format!("{arg}: {text}")
48 }
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn parses_messages_and_placeholders() {
58 let t = Translations::parse("# comment\nhello = Hallo\nbad-path = Fehlt: { $arg }\n");
59 assert_eq!(t.tr("hello"), "Hallo");
60 assert_eq!(t.tr("missing"), "missing");
61 assert_eq!(t.tr_arg("bad-path", "a.b"), "Fehlt: a.b");
62 assert_eq!(t.tr_arg("hello", "a.b"), "a.b: Hallo");
63 assert_eq!(t.tr_arg("hello", ""), "Hallo");
64 assert!(t.has("hello") && !t.has("comment"));
65 }
66}