Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/src/l10n.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ Locale selection is automatic and performed via:
fn detect_system_locale() -> Result<LanguageIdentifier, LocalizationError>
```

It reads the `LANG` environment variable (e.g., `fr-FR.UTF-8`), strips encoding, and parses the identifier.
It takes the first non-empty value of `LC_ALL`, `LC_MESSAGES` and `LANG` (e.g., `fr-FR.UTF-8`), strips encoding, and parses the identifier.

If parsing fails or `LANG` is not set, it falls back to:
If parsing fails or none of them is set, it falls back to:

```
const DEFAULT_LOCALE: &str = "en-US";
Expand Down
6 changes: 1 addition & 5 deletions src/uucore/src/lib/features/i18n/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,7 @@ const DEFAULT_LOCALE: Locale = locale!("und");
///
/// Or fallback on Posix locale, with ASCII encoding.
pub fn get_locale_from_env(locale_name: &str) -> (Locale, UEncoding) {
let locale_var = ["LC_ALL", locale_name, "LANG"]
.iter()
.find_map(|&key| std::env::var(key).ok().filter(|l| !l.is_empty()));

if let Some(locale_var_str) = locale_var {
if let Some(locale_var_str) = crate::locale::get_locale_env_var(locale_name) {
let mut split = locale_var_str.split(&['.', '@']);

if let Some(simple) = split.next() {
Expand Down
22 changes: 15 additions & 7 deletions src/uucore/src/lib/mods/clap_localization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -722,13 +722,21 @@ mod tests {
fn test_french_localization() {
use crate::locale::{get_message, setup_localization};

temp_env::with_var("LANG", Some("fr_FR.UTF-8"), || {
if setup_localization("test").is_ok() {
assert_eq!(get_message("common-error"), "erreur");
assert_eq!(get_message("common-usage"), "Utilisation");
assert_eq!(get_message("common-tip"), "conseil");
}
});
// LC_ALL and LC_MESSAGES take precedence over LANG
temp_env::with_vars(
[
("LC_ALL", None),
("LC_MESSAGES", None),
("LANG", Some("fr_FR.UTF-8")),
],
|| {
if setup_localization("test").is_ok() {
assert_eq!(get_message("common-error"), "erreur");
assert_eq!(get_message("common-usage"), "Utilisation");
assert_eq!(get_message("common-tip"), "conseil");
}
},
);
}
}
// spell-checker:enable
60 changes: 52 additions & 8 deletions src/uucore/src/lib/mods/locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,15 +560,24 @@ pub fn is_integer_literal(s: &str) -> bool {
!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
}

/// Function to detect system locale from environment variables
/// Returns the first non-empty value of `LC_ALL`, `category` and `LANG`,
/// following the POSIX precedence.
pub(crate) fn get_locale_env_var(category: &str) -> Option<String> {
["LC_ALL", category, "LANG"]
.into_iter()
.find_map(|key| std::env::var(key).ok().filter(|value| !value.is_empty()))
}

/// Detects the message locale from `LC_ALL`, `LC_MESSAGES` and `LANG`.
fn detect_system_locale() -> Result<LanguageIdentifier, LocalizationError> {
let locale_str = std::env::var("LANG")
.unwrap_or_else(|_| DEFAULT_LOCALE.to_string())
let locale_str = get_locale_env_var("LC_MESSAGES");
let locale_str = locale_str
.as_deref()
.unwrap_or(DEFAULT_LOCALE)
.split('.')
.next()
.unwrap_or(DEFAULT_LOCALE)
.to_string();
LanguageIdentifier::from_str(&locale_str).map_err(|_| {
.unwrap_or(DEFAULT_LOCALE);
LanguageIdentifier::from_str(locale_str).map_err(|_| {
LocalizationError::ParseLocale(format!("Failed to parse locale: {locale_str}"))
})
}
Expand All @@ -577,7 +586,7 @@ fn detect_system_locale() -> Result<LanguageIdentifier, LocalizationError> {
/// Always loads common strings in addition to utility-specific strings.
///
/// This function initializes the localization system based on the system's locale
/// preferences (via the LANG environment variable) or falls back to English
/// preferences (via `LC_ALL`, `LC_MESSAGES` or `LANG`) or falls back to English
/// if the system locale cannot be determined or the locale file doesn't exist.
/// English is always loaded as a fallback.
///
Expand Down Expand Up @@ -1703,13 +1712,48 @@ invalid-syntax = This is { $missing

#[test]
fn test_detect_system_locale_no_lang_env() {
temp_env::with_var_unset("LANG", || {
temp_env::with_vars_unset(["LC_ALL", "LC_MESSAGES", "LANG"], || {
let result = detect_system_locale();
assert!(result.is_ok());
assert_eq!(result.unwrap().to_string(), "en-US");
});
}

#[test]
fn test_detect_system_locale_precedence() {
// (LC_ALL, LC_MESSAGES, LANG, expected locale)
let cases = [
(Some("fr_FR.UTF-8"), None, None, "fr-FR"),
(None, Some("de_DE.UTF-8"), None, "de-DE"),
(None, None, Some("es_ES.UTF-8"), "es-ES"),
(Some("fr_FR"), Some("de_DE"), Some("es_ES"), "fr-FR"),
(None, Some("de_DE"), Some("es_ES"), "de-DE"),
(Some(""), Some(""), Some("fr_FR"), "fr-FR"),
(None, None, None, "en-US"),
];
for (lc_all, lc_messages, lang, expected) in cases {
temp_env::with_vars(
[
("LC_ALL", lc_all),
("LC_MESSAGES", lc_messages),
("LANG", lang),
],
|| assert_eq!(detect_system_locale().unwrap().to_string(), expected),
);
}
}

#[test]
fn test_detect_system_locale_c_overrides_lang() {
// "C" is not a valid language tag, so setup_localization falls back to English
temp_env::with_vars(
[("LC_ALL", Some("C")), ("LANG", Some("fr_FR.UTF-8"))],
|| {
assert!(detect_system_locale().is_err());
},
);
}

#[test]
fn test_setup_localization_success() {
std::thread::spawn(|| {
Expand Down
2 changes: 1 addition & 1 deletion tests/by-util/test_chmod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2232,7 +2232,7 @@ fn test_chmod_colored_output() {
new_ucmd!()
.arg("--invalid-option")
.env("CLICOLOR_FORCE", "1")
.env("LANG", "fr_FR.UTF-8")
.env("LC_ALL", "fr_FR.UTF-8")
.fails()
.code_is(1)
.stderr_contains("\x1b[31merreur\x1b[0m") // Red "erreur" in French
Expand Down
2 changes: 1 addition & 1 deletion tests/by-util/test_df.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1055,7 +1055,7 @@ fn test_file_column_width_if_filename_contains_unicode_chars() {
fn test_column_width_if_header_contains_unicode_chars() {
// the French "Used" header "Utilisé" is 7 columns wide but 8 bytes long
let output = new_ucmd!()
.env("LANG", "fr_FR.UTF-8")
.env("LC_ALL", "fr_FR.UTF-8")
.args(&["-h", "--output=used,target", "."])
.succeeds()
.stdout_str_lossy();
Expand Down
12 changes: 11 additions & 1 deletion tests/by-util/test_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2261,11 +2261,21 @@ fn test_simulation_of_terminal_pty_write_in_data_and_sends_eot_automatically() {
fn test_env_french() {
new_ucmd!()
.arg("--verbo")
.env("LANG", "fr_FR")
.env("LC_ALL", "fr_FR")
.fails()
.stderr_contains("erreur : argument inattendu");
}

#[test]
fn test_env_lc_all_c_overrides_lang() {
new_ucmd!()
.arg("--verbo")
.env("LC_ALL", "C")
.env("LANG", "fr_FR")
.fails()
.stderr_contains("error: unexpected argument");
}

#[test]
fn test_shebang_error() {
new_ucmd!()
Expand Down
7 changes: 7 additions & 0 deletions util/build-gnu.sh
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,13 @@ ln -vf "${UU_BUILD_DIR}/install" "${UU_BUILD_DIR}/ginstall" # The GNU tests use

cd "${path_GNU}" && echo "[ pwd:'${PWD}' ]"

# Let LANG select character handling and collation, and keep diagnostics in C.
sed -i \
-e '/^BEGIN { delete .*; \$ENV{LC_MESSAGES} = "C"; }$/d' \
-e 's/LC_ALL/LANG/g' \
-e '1a BEGIN { delete @ENV{grep /^LC_/, keys %ENV}; $ENV{LC_MESSAGES} = "C"; }' \
tests/cut/cut.pl tests/expr/expr.pl tests/fold/fold.pl tests/join/join.pl tests/uniq/uniq.pl

# Any binaries that aren't built become `false` to make tests failure
for binary in $(./build-aux/gen-lists-of-programs.sh --list-progs); do
bin_path="${UU_BUILD_DIR}/${binary}"
Expand Down
Loading