Skip to main content

radio_cli/
messages.rs

1use std::sync::{
2    OnceLock,
3    atomic::{AtomicU8, Ordering},
4};
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Locale {
8    En,
9    ZhCn,
10}
11
12static LOCALE: AtomicU8 = AtomicU8::new(0);
13static UNKNOWN_REPORTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
14
15pub fn select(
16    explicit: Option<&str>,
17    environment: Option<&str>,
18    config: Option<&str>,
19    lc_all: Option<&str>,
20    lang: Option<&str>,
21) -> (Locale, Option<String>) {
22    let value = [explicit, environment, config, lc_all, lang]
23        .into_iter()
24        .flatten()
25        .find(|s| !s.trim().is_empty())
26        .unwrap_or("en");
27    let normalized = value.trim().to_ascii_lowercase().replace('_', "-");
28    let base = normalized.split(['.', '@']).next().unwrap_or("en");
29    match base {
30        "en" | "c" | "posix" => (Locale::En, None),
31        "zh" | "zh-cn" | "zh-hans" => (Locale::ZhCn, None),
32        s if s.starts_with("en-") => (Locale::En, None),
33        _ => (Locale::En, Some(value.into())),
34    }
35}
36
37pub fn init(explicit: Option<&str>, config: Option<&str>) {
38    configure(explicit, config, true);
39}
40
41pub(crate) fn preview(explicit: Option<&str>, config: Option<&str>) {
42    configure(explicit, config, false);
43}
44
45fn configure(explicit: Option<&str>, config: Option<&str>, report_unknown: bool) {
46    let environment = std::env::var("RADIO_LANG").ok();
47    let lc_all = std::env::var("LC_ALL").ok();
48    let lang = std::env::var("LANG").ok();
49    let (locale, unknown) = select(
50        explicit,
51        environment.as_deref(),
52        config,
53        lc_all.as_deref(),
54        lang.as_deref(),
55    );
56    LOCALE.store(u8::from(locale == Locale::ZhCn), Ordering::Relaxed);
57    if report_unknown
58        && let Some(unknown) = unknown
59        && !UNKNOWN_REPORTED.swap(true, Ordering::Relaxed)
60    {
61        eprintln!(
62            "radio: unsupported language '{}'; using English",
63            crate::clean_text(&unknown)
64        );
65    }
66}
67
68pub fn locale() -> Locale {
69    if LOCALE.load(Ordering::Relaxed) == 1 {
70        Locale::ZhCn
71    } else {
72        Locale::En
73    }
74}
75
76pub fn text(key: &str) -> &'static str {
77    text_in(locale(), key)
78}
79
80pub fn text_in(locale: Locale, key: &str) -> &'static str {
81    static EN: OnceLock<toml::Table> = OnceLock::new();
82    static ZH: OnceLock<toml::Table> = OnceLock::new();
83    let table = match locale {
84        Locale::En => EN.get_or_init(|| {
85            toml::from_str(include_str!("../locales/en.toml")).expect("embedded English messages")
86        }),
87        Locale::ZhCn => ZH.get_or_init(|| {
88            toml::from_str(include_str!("../locales/zh-CN.toml"))
89                .expect("embedded Chinese messages")
90        }),
91    };
92    table
93        .get(key)
94        .and_then(toml::Value::as_str)
95        .unwrap_or("Unknown message")
96}
97
98pub fn format_text(template: &str, params: &[(&str, String)]) -> String {
99    let mut output = String::new();
100    let mut rest = template;
101    while let Some(start) = rest.find('{') {
102        output.push_str(&rest[..start]);
103        let Some(end) = rest[start..].find('}') else {
104            output.push_str(&rest[start..]);
105            return output;
106        };
107        let key = &rest[start + 1..start + end];
108        if let Some((_, value)) = params.iter().find(|(name, _)| *name == key) {
109            output.push_str(value);
110        } else {
111            output.push_str(&rest[start..=start + end]);
112        }
113        rest = &rest[start + end + 1..];
114    }
115    output.push_str(rest);
116    output
117}
118
119#[macro_export]
120macro_rules! t {
121    ($key:literal) => {
122        $crate::messages::text($key)
123    };
124    ($key:literal, $($name:literal => $value:expr),+ $(,)?) => {
125        $crate::messages::format_text($crate::messages::text($key), &[$(($name, $value.to_string())),+])
126    };
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use crate::error::ErrorCode;
133    use std::collections::BTreeSet;
134
135    #[test]
136    fn formatted_values_are_not_reinterpreted_as_placeholders() {
137        assert_eq!(
138            format_text("Hello {name}: {missing}", &[("name", "{missing}".into())]),
139            "Hello {missing}: {missing}"
140        );
141        assert_eq!(format_text("Hello {name", &[]), "Hello {name");
142    }
143
144    #[test]
145    fn locale_precedence_and_fallback_are_deterministic() {
146        assert_eq!(
147            select(Some("zh-CN"), Some("en"), None, None, None).0,
148            Locale::ZhCn
149        );
150        assert_eq!(
151            select(None, Some("en"), Some("zh-CN"), None, None).0,
152            Locale::En
153        );
154        assert_eq!(
155            select(None, None, Some("zh-CN"), Some("en"), None).0,
156            Locale::ZhCn
157        );
158        assert_eq!(
159            select(None, None, None, Some("zh_CN.UTF-8"), Some("en")).0,
160            Locale::ZhCn
161        );
162        assert_eq!(
163            select(None, None, None, Some(""), Some("zh_CN.UTF-8")).0,
164            Locale::ZhCn
165        );
166        assert_eq!(
167            select(Some("fr"), None, Some("zh-CN"), None, None),
168            (Locale::En, Some("fr".into()))
169        );
170        assert_eq!(select(None, None, None, None, None), (Locale::En, None));
171    }
172
173    fn literal_keys(source: &str) -> BTreeSet<String> {
174        ["crate::t!", "messages::text", "messages::text_in"]
175            .into_iter()
176            .flat_map(|call| {
177                source.split(call).skip(1).filter_map(|part| {
178                    let args = part.trim_start().strip_prefix('(')?;
179                    let literal = if call.ends_with("text_in") {
180                        args.split_once(',')?.1
181                    } else {
182                        args
183                    }
184                    .trim_start()
185                    .strip_prefix('"')?;
186                    Some(literal.split('"').next().unwrap().to_owned())
187                })
188            })
189            .collect()
190    }
191
192    /// Strip `//` and `/* */` comments while preserving string and char
193    /// literals, so commented-out message lookups never register as used keys
194    /// and comment-looking text inside strings stays intact.
195    fn strip_comments(source: &str) -> String {
196        let chars: Vec<char> = source.chars().collect();
197        let mut out = String::with_capacity(source.len());
198        let mut i = 0;
199        while i < chars.len() {
200            let c = chars[i];
201            match c {
202                '/' if chars.get(i + 1) == Some(&'/') => {
203                    while i < chars.len() && chars[i] != '\n' {
204                        i += 1;
205                    }
206                }
207                '/' if chars.get(i + 1) == Some(&'*') => {
208                    // Rust block comments nest.
209                    let mut depth = 1usize;
210                    i += 2;
211                    while i < chars.len() && depth > 0 {
212                        match (chars[i], chars.get(i + 1)) {
213                            ('/', Some('*')) => {
214                                depth += 1;
215                                i += 2;
216                            }
217                            ('*', Some('/')) => {
218                                depth -= 1;
219                                i += 2;
220                            }
221                            _ => i += 1,
222                        }
223                    }
224                }
225                // Raw strings keep their content verbatim.
226                'r' if matches!(chars.get(i + 1), Some('"') | Some('#')) => {
227                    out.push('r');
228                    i += 1;
229                    let mut hashes = 0usize;
230                    while chars.get(i) == Some(&'#') {
231                        out.push('#');
232                        hashes += 1;
233                        i += 1;
234                    }
235                    if chars.get(i) == Some(&'"') {
236                        out.push('"');
237                        i += 1;
238                        loop {
239                            match chars.get(i) {
240                                None => break,
241                                Some('"')
242                                    if (0..hashes).all(|h| chars.get(i + 1 + h) == Some(&'#')) =>
243                                {
244                                    out.push('"');
245                                    out.extend(std::iter::repeat_n('#', hashes));
246                                    i += 1 + hashes;
247                                    break;
248                                }
249                                Some(&d) => {
250                                    out.push(d);
251                                    i += 1;
252                                }
253                            }
254                        }
255                    }
256                }
257                '"' => {
258                    out.push('"');
259                    i += 1;
260                    while let Some(&d) = chars.get(i) {
261                        out.push(d);
262                        i += 1;
263                        match d {
264                            '\\' => {
265                                if let Some(&e) = chars.get(i) {
266                                    out.push(e);
267                                    i += 1;
268                                }
269                            }
270                            '"' => break,
271                            _ => {}
272                        }
273                    }
274                }
275                // A quote only opens a char literal for `'x'`/`'\n'` shapes, so
276                // lifetimes such as `&'a str` stay ordinary text.
277                '\'' if is_char_literal(&chars, i) => {
278                    out.push('\'');
279                    i += 1;
280                    while let Some(&d) = chars.get(i) {
281                        out.push(d);
282                        i += 1;
283                        match d {
284                            '\\' => {
285                                if let Some(&e) = chars.get(i) {
286                                    out.push(e);
287                                    i += 1;
288                                }
289                            }
290                            '\'' => break,
291                            _ => {}
292                        }
293                    }
294                }
295                _ => {
296                    out.push(c);
297                    i += 1;
298                }
299            }
300        }
301        out
302    }
303
304    fn is_char_literal(chars: &[char], i: usize) -> bool {
305        match chars.get(i + 1) {
306            Some('\\') => true,
307            Some(_) => chars.get(i + 2) == Some(&'\''),
308            None => false,
309        }
310    }
311
312    #[test]
313    fn key_scan_includes_direct_message_lookups() {
314        let source = r#"crate::t!("macro"); messages::text("direct");
315            crate::messages::text ( "qualified" ); messages::text_in(locale, "explicit_locale");"#;
316        assert_eq!(
317            literal_keys(source),
318            ["macro", "direct", "qualified", "explicit_locale"]
319                .into_iter()
320                .map(str::to_owned)
321                .collect()
322        );
323    }
324
325    #[test]
326    fn key_scan_ignores_commented_out_lookups() {
327        let source = r##"crate::t!("real");
328            // messages::text("line_comment")
329            /* messages::text("block_comment") */
330            /* nested /* messages::text("nested_comment") */ tail */
331            let url = "https://example.com"; // crate::t!("trailing_comment")
332            let script = "#!/bin/sh\ntouch '{}'"; // crate::t!("after_string")
333            result.push('…'); KeyCode::Char(':') '\n' '\x1b'
334            let lifetime: &'a str = ""; // crate::t!("after_lifetime")
335            let raw = r#"messages::text("raw_content")"#;
336        "##;
337        // Commented-out lookups never register; string content (including the
338        // raw string, which keeps today's heuristic scanning) still does.
339        assert_eq!(
340            literal_keys(&strip_comments(source)),
341            ["raw_content", "real"]
342                .into_iter()
343                .map(str::to_owned)
344                .collect::<BTreeSet<_>>()
345        );
346    }
347
348    #[test]
349    fn catalogs_have_exactly_the_used_keys_and_matching_placeholders() {
350        let en: toml::Table = toml::from_str(include_str!("../locales/en.toml")).unwrap();
351        let zh: toml::Table = toml::from_str(include_str!("../locales/zh-CN.toml")).unwrap();
352        let mut used: BTreeSet<String> = ErrorCode::ALL.iter().map(|c| c.as_str().into()).collect();
353        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
354        let mut directories = vec![root.join("src"), root.join("tests")];
355        while let Some(directory) = directories.pop() {
356            for entry in std::fs::read_dir(directory).unwrap() {
357                let path = entry.unwrap().path();
358                if path.is_dir() {
359                    directories.push(path);
360                    continue;
361                }
362                if path.extension().is_none_or(|ext| ext != "rs") || path.ends_with("messages.rs") {
363                    continue;
364                }
365                let source = std::fs::read_to_string(path).unwrap();
366                used.extend(literal_keys(&strip_comments(&source)));
367            }
368        }
369        assert_eq!(en.keys().cloned().collect::<BTreeSet<_>>(), used);
370        assert_eq!(zh.keys().cloned().collect::<BTreeSet<_>>(), used);
371        let placeholders = |s: &str| {
372            s.split('{')
373                .skip(1)
374                .map(|p| p.split('}').next().unwrap().to_string())
375                .collect::<BTreeSet<_>>()
376        };
377        for key in used {
378            let a = text_in(Locale::En, &key);
379            let b = text_in(Locale::ZhCn, &key);
380            assert!(!a.is_empty() && !b.is_empty());
381            assert_eq!(placeholders(a), placeholders(b), "{key}");
382        }
383    }
384}