Skip to main content

nu_utils/
locale.rs

1use std::borrow::Cow;
2
3use num_format::Locale;
4
5pub const LOCALE_OVERRIDE_ENV_VAR: &str = "NU_TEST_LOCALE_OVERRIDE";
6
7pub fn get_system_locale() -> Locale {
8    let locale_string = get_system_locale_string().unwrap_or_else(|| String::from("en-US"));
9    // Since get_locale() and Locale::from_name() don't always return the same items
10    // we need to try and parse it to match. For instance, a valid locale is de_DE
11    // however Locale::from_name() wants only de so we split and parse it out.
12    let locale_string = locale_string.replace('_', "-"); // en_AU -> en-AU
13
14    Locale::from_name(&locale_string).unwrap_or_else(|_| {
15        let all = num_format::Locale::available_names();
16        let locale_prefix = &locale_string.split('-').collect::<Vec<&str>>();
17        if all.contains(&locale_prefix[0]) {
18            Locale::from_name(locale_prefix[0]).unwrap_or(Locale::en)
19        } else {
20            Locale::en
21        }
22    })
23}
24
25#[cfg(debug_assertions)]
26pub fn get_system_locale_string() -> Option<String> {
27    std::env::var(LOCALE_OVERRIDE_ENV_VAR).ok().or_else(
28        #[cfg(not(test))]
29        {
30            sys_locale::get_locale
31        },
32        #[cfg(test)]
33        {
34            // For tests, we use the same locale on all systems.
35            // To override this, set `LOCALE_OVERRIDE_ENV_VAR`.
36            || Some(Locale::en_US_POSIX.name().to_owned())
37        },
38    )
39}
40
41#[cfg(not(debug_assertions))]
42pub fn get_system_locale_string() -> Option<String> {
43    sys_locale::get_locale()
44}
45
46/// Get the current locale from environment variables.
47///
48/// - Checks multiple environment variables.
49/// - Generic over how to read environment variables (can be used to read environment variables from
50///   `StateWorkingSet`, `Stack`, or from process environment variables)
51/// - Allows specifying a locale category (`LC_TIME`, `LC_NUMERIC`, etc.)
52///
53/// Priority order as documented in [`gettext` manual][1]:
54/// - NU_TEST_LOCALE_OVERRIDE
55/// - LC_ALL
56/// - `locale_category` (if provided)
57/// - LANG
58///
59/// [1]: https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html
60pub fn get_locale_from_env_vars<'a, F, O>(
61    locale_category: Option<&str>,
62    env_getter: F,
63) -> Option<Cow<'a, str>>
64where
65    F: 'a,
66    F: Fn(&str) -> Option<O>,
67    O: Into<Cow<'a, str>>,
68{
69    let mut env_var_names = [LOCALE_OVERRIDE_ENV_VAR, "LC_ALL"]
70        .iter()
71        .copied()
72        .chain(locale_category)
73        .chain(["LANG"]);
74
75    let env_var = env_var_names.find_map(env_getter).map(Into::into);
76    env_var
77        .map(|s| match s {
78            Cow::Borrowed(s) => Cow::Borrowed(s.split('.').next().unwrap_or(s)),
79            Cow::Owned(s) => Cow::Owned(s.split('.').next().map(ToOwned::to_owned).unwrap_or(s)),
80        })
81        .or_else(|| {
82            get_system_locale_string()
83                .map(|l| l.replace('-', "_"))
84                .map(Cow::Owned)
85        })
86}