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 let locale_string = locale_string.replace('_', "-"); 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 || 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
46pub 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}