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 set_usage_lists_the_same_options_in_both_languages() {
137        let options = |locale| {
138            text_in(locale, "command_usage_set")
139                .split_once(": ")
140                .unwrap()
141                .1
142        };
143        assert_eq!(options(Locale::En), options(Locale::ZhCn));
144    }
145    #[test]
146    fn formatted_values_are_not_reinterpreted_as_placeholders() {
147        assert_eq!(
148            format_text("Hello {name}: {missing}", &[("name", "{missing}".into())]),
149            "Hello {missing}: {missing}"
150        );
151        assert_eq!(format_text("Hello {name", &[]), "Hello {name");
152    }
153
154    #[test]
155    fn locale_precedence_and_fallback_are_deterministic() {
156        assert_eq!(
157            select(Some("zh-CN"), Some("en"), None, None, None).0,
158            Locale::ZhCn
159        );
160        assert_eq!(
161            select(None, Some("en"), Some("zh-CN"), None, None).0,
162            Locale::En
163        );
164        assert_eq!(
165            select(None, None, Some("zh-CN"), Some("en"), None).0,
166            Locale::ZhCn
167        );
168        assert_eq!(
169            select(None, None, None, Some("zh_CN.UTF-8"), Some("en")).0,
170            Locale::ZhCn
171        );
172        assert_eq!(
173            select(None, None, None, Some(""), Some("zh_CN.UTF-8")).0,
174            Locale::ZhCn
175        );
176        assert_eq!(
177            select(Some("fr"), None, Some("zh-CN"), None, None),
178            (Locale::En, Some("fr".into()))
179        );
180        assert_eq!(select(None, None, None, None, None), (Locale::En, None));
181    }
182
183    fn literal_keys(source: &str) -> BTreeSet<String> {
184        ["crate::t!", "messages::text", "messages::text_in"]
185            .into_iter()
186            .flat_map(|call| {
187                source.split(call).skip(1).filter_map(|part| {
188                    let args = part.trim_start().strip_prefix('(')?;
189                    let literal = if call.ends_with("text_in") {
190                        args.split_once(',')?.1
191                    } else {
192                        args
193                    }
194                    .trim_start()
195                    .strip_prefix('"')?;
196                    Some(literal.split('"').next().unwrap().to_owned())
197                })
198            })
199            .collect()
200    }
201
202    /// Strip `//` and `/* */` comments while preserving string and char
203    /// literals, so commented-out message lookups never register as used keys
204    /// and comment-looking text inside strings stays intact.
205    fn strip_comments(source: &str) -> String {
206        let chars: Vec<char> = source.chars().collect();
207        let mut out = String::with_capacity(source.len());
208        let mut i = 0;
209        while i < chars.len() {
210            let c = chars[i];
211            match c {
212                '/' if chars.get(i + 1) == Some(&'/') => {
213                    while i < chars.len() && chars[i] != '\n' {
214                        i += 1;
215                    }
216                }
217                '/' if chars.get(i + 1) == Some(&'*') => {
218                    // Rust block comments nest.
219                    let mut depth = 1usize;
220                    i += 2;
221                    while i < chars.len() && depth > 0 {
222                        match (chars[i], chars.get(i + 1)) {
223                            ('/', Some('*')) => {
224                                depth += 1;
225                                i += 2;
226                            }
227                            ('*', Some('/')) => {
228                                depth -= 1;
229                                i += 2;
230                            }
231                            _ => i += 1,
232                        }
233                    }
234                }
235                // Raw strings keep their content verbatim.
236                'r' if matches!(chars.get(i + 1), Some('"') | Some('#')) => {
237                    out.push('r');
238                    i += 1;
239                    let mut hashes = 0usize;
240                    while chars.get(i) == Some(&'#') {
241                        out.push('#');
242                        hashes += 1;
243                        i += 1;
244                    }
245                    if chars.get(i) == Some(&'"') {
246                        out.push('"');
247                        i += 1;
248                        loop {
249                            match chars.get(i) {
250                                None => break,
251                                Some('"')
252                                    if (0..hashes).all(|h| chars.get(i + 1 + h) == Some(&'#')) =>
253                                {
254                                    out.push('"');
255                                    out.extend(std::iter::repeat_n('#', hashes));
256                                    i += 1 + hashes;
257                                    break;
258                                }
259                                Some(&d) => {
260                                    out.push(d);
261                                    i += 1;
262                                }
263                            }
264                        }
265                    }
266                }
267                '"' => {
268                    out.push('"');
269                    i += 1;
270                    while let Some(&d) = chars.get(i) {
271                        out.push(d);
272                        i += 1;
273                        match d {
274                            '\\' => {
275                                if let Some(&e) = chars.get(i) {
276                                    out.push(e);
277                                    i += 1;
278                                }
279                            }
280                            '"' => break,
281                            _ => {}
282                        }
283                    }
284                }
285                // A quote only opens a char literal for `'x'`/`'\n'` shapes, so
286                // lifetimes such as `&'a str` stay ordinary text.
287                '\'' if is_char_literal(&chars, i) => {
288                    out.push('\'');
289                    i += 1;
290                    while let Some(&d) = chars.get(i) {
291                        out.push(d);
292                        i += 1;
293                        match d {
294                            '\\' => {
295                                if let Some(&e) = chars.get(i) {
296                                    out.push(e);
297                                    i += 1;
298                                }
299                            }
300                            '\'' => break,
301                            _ => {}
302                        }
303                    }
304                }
305                _ => {
306                    out.push(c);
307                    i += 1;
308                }
309            }
310        }
311        out
312    }
313
314    fn is_char_literal(chars: &[char], i: usize) -> bool {
315        match chars.get(i + 1) {
316            Some('\\') => true,
317            Some(_) => chars.get(i + 2) == Some(&'\''),
318            None => false,
319        }
320    }
321
322    #[test]
323    fn key_scan_includes_direct_message_lookups() {
324        let source = r#"crate::t!("macro"); messages::text("direct");
325            crate::messages::text ( "qualified" ); messages::text_in(locale, "explicit_locale");"#;
326        assert_eq!(
327            literal_keys(source),
328            ["macro", "direct", "qualified", "explicit_locale"]
329                .into_iter()
330                .map(str::to_owned)
331                .collect()
332        );
333    }
334
335    #[test]
336    fn key_scan_ignores_commented_out_lookups() {
337        let source = r##"crate::t!("real");
338            // messages::text("line_comment")
339            /* messages::text("block_comment") */
340            /* nested /* messages::text("nested_comment") */ tail */
341            let url = "https://example.com"; // crate::t!("trailing_comment")
342            let script = "#!/bin/sh\ntouch '{}'"; // crate::t!("after_string")
343            result.push('…'); KeyCode::Char(':') '\n' '\x1b'
344            let lifetime: &'a str = ""; // crate::t!("after_lifetime")
345            let raw = r#"messages::text("raw_content")"#;
346        "##;
347        // Commented-out lookups never register; string content (including the
348        // raw string, which keeps today's heuristic scanning) still does.
349        assert_eq!(
350            literal_keys(&strip_comments(source)),
351            ["raw_content", "real"]
352                .into_iter()
353                .map(str::to_owned)
354                .collect::<BTreeSet<_>>()
355        );
356    }
357
358    #[test]
359    fn catalogs_have_exactly_the_used_keys_and_matching_placeholders() {
360        let en: toml::Table = toml::from_str(include_str!("../locales/en.toml")).unwrap();
361        let zh: toml::Table = toml::from_str(include_str!("../locales/zh-CN.toml")).unwrap();
362        let mut used: BTreeSet<String> = ErrorCode::ALL.iter().map(|c| c.as_str().into()).collect();
363        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
364        let mut directories = vec![root.join("src"), root.join("tests")];
365        while let Some(directory) = directories.pop() {
366            for entry in std::fs::read_dir(directory).unwrap() {
367                let path = entry.unwrap().path();
368                if path.is_dir() {
369                    directories.push(path);
370                    continue;
371                }
372                if path.extension().is_none_or(|ext| ext != "rs") || path.ends_with("messages.rs") {
373                    continue;
374                }
375                let source = std::fs::read_to_string(path).unwrap();
376                used.extend(literal_keys(&strip_comments(&source)));
377            }
378        }
379        assert_eq!(en.keys().cloned().collect::<BTreeSet<_>>(), used);
380        assert_eq!(zh.keys().cloned().collect::<BTreeSet<_>>(), used);
381        let placeholders = |s: &str| {
382            s.split('{')
383                .skip(1)
384                .map(|p| p.split('}').next().unwrap().to_string())
385                .collect::<BTreeSet<_>>()
386        };
387        for key in used {
388            let a = text_in(Locale::En, &key);
389            let b = text_in(Locale::ZhCn, &key);
390            assert!(!a.is_empty() && !b.is_empty());
391            assert_eq!(placeholders(a), placeholders(b), "{key}");
392        }
393    }
394}