nu_utils/
locale.rs

1use num_format::Locale;
2
3pub const LOCALE_OVERRIDE_ENV_VAR: &str = "NU_TEST_LOCALE_OVERRIDE";
4
5pub fn get_system_locale() -> Locale {
6    let locale_string = get_system_locale_string().unwrap_or_else(|| String::from("en-US"));
7    // Since get_locale() and Locale::from_name() don't always return the same items
8    // we need to try and parse it to match. For instance, a valid locale is de_DE
9    // however Locale::from_name() wants only de so we split and parse it out.
10    let locale_string = locale_string.replace('_', "-"); // en_AU -> en-AU
11
12    Locale::from_name(&locale_string).unwrap_or_else(|_| {
13        let all = num_format::Locale::available_names();
14        let locale_prefix = &locale_string.split('-').collect::<Vec<&str>>();
15        if all.contains(&locale_prefix[0]) {
16            Locale::from_name(locale_prefix[0]).unwrap_or(Locale::en)
17        } else {
18            Locale::en
19        }
20    })
21}
22
23#[cfg(debug_assertions)]
24pub fn get_system_locale_string() -> Option<String> {
25    std::env::var(LOCALE_OVERRIDE_ENV_VAR).ok().or_else(
26        #[cfg(not(test))]
27        {
28            sys_locale::get_locale
29        },
30        #[cfg(test)]
31        {
32            // For tests, we use the same locale on all systems.
33            // To override this, set `LOCALE_OVERRIDE_ENV_VAR`.
34            || Some(Locale::en_US_POSIX.name().to_owned())
35        },
36    )
37}
38
39#[cfg(not(debug_assertions))]
40pub fn get_system_locale_string() -> Option<String> {
41    sys_locale::get_locale()
42}