Skip to main content

iphone_cli/
i18n.rs

1//! Guidance text follows the Mac's language: Korean on a Korean Mac, English
2//! otherwise. JSON keys and error codes stay English.
3
4use std::sync::OnceLock;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Lang {
8    Ko,
9    En,
10}
11
12fn detect() -> Lang {
13    if let Ok(v) = std::env::var("IPH_LANG") {
14        return if v.to_lowercase().starts_with("ko") { Lang::Ko } else { Lang::En };
15    }
16    // The system language list is the truth on macOS; the shell's LANG often
17    // stays en_US on a Korean Mac.
18    if let Ok(out) = std::process::Command::new("defaults")
19        .args(["read", "-g", "AppleLanguages"])
20        .output()
21    {
22        let text = String::from_utf8_lossy(&out.stdout);
23        if let Some(first) = text
24            .lines()
25            .map(|l| l.trim().trim_matches(|c| c == '"' || c == ','))
26            .find(|l| !l.is_empty() && *l != "(" && *l != ")")
27        {
28            return if first.to_lowercase().starts_with("ko") { Lang::Ko } else { Lang::En };
29        }
30    }
31    // Windows: the user's locale in the registry, e.g. "ko-KR".
32    #[cfg(windows)]
33    if let Ok(out) = std::process::Command::new("reg")
34        .args(["query", r"HKCU\Control Panel\International", "/v", "LocaleName"])
35        .output()
36        && let Some(name) = String::from_utf8_lossy(&out.stdout).split_whitespace().last()
37    {
38        return if name.to_lowercase().starts_with("ko") { Lang::Ko } else { Lang::En };
39    }
40    for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
41        if let Ok(v) = std::env::var(key)
42            && !v.is_empty() {
43                return if v.to_lowercase().starts_with("ko") { Lang::Ko } else { Lang::En };
44            }
45    }
46    Lang::En
47}
48
49pub fn lang() -> Lang {
50    static LANG: OnceLock<Lang> = OnceLock::new();
51    *LANG.get_or_init(detect)
52}
53
54/// Pick the text for the current language.
55pub fn t<'a>(ko: &'a str, en: &'a str) -> &'a str {
56    match lang() {
57        Lang::Ko => ko,
58        Lang::En => en,
59    }
60}