From 1c90fa1a8574a64d97d22ce6120b6ea4ef79e0d6 Mon Sep 17 00:00:00 2001 From: John Costa Date: Tue, 1 Dec 2026 14:57:44 +0000 Subject: [PATCH] locale: honor LC_ALL and LC_MESSAGES precedence over LANG Message locale detection only read LANG. Use the POSIX order LC_ALL > LC_MESSAGES > LANG, skipping empty values, and share the lookup with i18n::get_locale_from_env. Tests that selected French through LANG alone now set LC_ALL, since the test harness sets LC_ALL=C by default. The GNU cut, expr, fold, join and uniq tests select their multibyte locale through LC_ALL while expecting English diagnostics, so build-gnu.sh moves that to LANG and pins LC_MESSAGES=C. Fixes #8922 Co-authored-by: soldierboy <191002121+sunsss123soldier@users.noreply.github.com> --- docs/src/l10n.md | 4 +- src/uucore/src/lib/features/i18n/mod.rs | 6 +- src/uucore/src/lib/mods/clap_localization.rs | 22 ++++--- src/uucore/src/lib/mods/locale.rs | 60 +++++++++++++++++--- tests/by-util/test_chmod.rs | 2 +- tests/by-util/test_df.rs | 2 +- tests/by-util/test_env.rs | 12 +++- util/build-gnu.sh | 7 +++ 8 files changed, 90 insertions(+), 25 deletions(-) diff --git a/docs/src/l10n.md b/docs/src/l10n.md index 2c2a5582fe2..cb2d6c2fa77 100644 --- a/docs/src/l10n.md +++ b/docs/src/l10n.md @@ -61,9 +61,9 @@ Locale selection is automatic and performed via: fn detect_system_locale() -> Result ``` -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"; diff --git a/src/uucore/src/lib/features/i18n/mod.rs b/src/uucore/src/lib/features/i18n/mod.rs index 3314c20c049..1e37f322ba1 100644 --- a/src/uucore/src/lib/features/i18n/mod.rs +++ b/src/uucore/src/lib/features/i18n/mod.rs @@ -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() { diff --git a/src/uucore/src/lib/mods/clap_localization.rs b/src/uucore/src/lib/mods/clap_localization.rs index 45fc60ae036..0c962a455ab 100644 --- a/src/uucore/src/lib/mods/clap_localization.rs +++ b/src/uucore/src/lib/mods/clap_localization.rs @@ -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 diff --git a/src/uucore/src/lib/mods/locale.rs b/src/uucore/src/lib/mods/locale.rs index ab323fc893a..003289d480e 100644 --- a/src/uucore/src/lib/mods/locale.rs +++ b/src/uucore/src/lib/mods/locale.rs @@ -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 { + ["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 { - 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}")) }) } @@ -577,7 +586,7 @@ fn detect_system_locale() -> Result { /// 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. /// @@ -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(|| { diff --git a/tests/by-util/test_chmod.rs b/tests/by-util/test_chmod.rs index fe1c587358d..abcc38366b0 100644 --- a/tests/by-util/test_chmod.rs +++ b/tests/by-util/test_chmod.rs @@ -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 diff --git a/tests/by-util/test_df.rs b/tests/by-util/test_df.rs index 0ad0badca83..adb764fd70d 100644 --- a/tests/by-util/test_df.rs +++ b/tests/by-util/test_df.rs @@ -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(); diff --git a/tests/by-util/test_env.rs b/tests/by-util/test_env.rs index b826de8a8ad..ee57d2ca891 100644 --- a/tests/by-util/test_env.rs +++ b/tests/by-util/test_env.rs @@ -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!() diff --git a/util/build-gnu.sh b/util/build-gnu.sh index c7db138519e..7f57623e8b0 100755 --- a/util/build-gnu.sh +++ b/util/build-gnu.sh @@ -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}"