diff --git a/src/uucore/src/lib/mods/locale.rs b/src/uucore/src/lib/mods/locale.rs index 90b13d53b3c..ab323fc893a 100644 --- a/src/uucore/src/lib/mods/locale.rs +++ b/src/uucore/src/lib/mods/locale.rs @@ -618,21 +618,31 @@ pub fn setup_localization(p: &str) -> Result<(), LocalizationError> { if LOCALIZED_UTIL.with_borrow(|util| util.as_deref() == Some(p)) { return Ok(()); } + + let locale = detect_system_locale().unwrap_or_else(|_| { + LanguageIdentifier::from_str(DEFAULT_LOCALE).expect("Default locale should always be valid") + }); + + // English is embedded at build time, so there is no need to look for + // the locales directory (a readlink and several stats) or read files + let has_embedded_strings = get_embedded_locale(&format!("{p}/{DEFAULT_LOCALE}.ftl")).is_some(); + if locale == DEFAULT_LOCALE && has_embedded_strings { + set_localizer(Localizer::new(create_english_bundle_from_embedded( + &locale, p, + )?)); + LOCALIZED_UTIL.with_borrow_mut(|util| *util = Some(p.to_string())); + return Ok(()); + } + let locales_dir = get_locales_dir(p); // Callers such as the help template pass the invoked name (`dir`, `[`, // a prefixed binary name...), which has no strings of its own: keep the // utility that is already set up instead of switching to nothing - if LOCALIZED_UTIL.with_borrow(Option::is_some) - && locales_dir.is_err() - && get_embedded_locale(&format!("{p}/{DEFAULT_LOCALE}.ftl")).is_none() + if LOCALIZED_UTIL.with_borrow(Option::is_some) && locales_dir.is_err() && !has_embedded_strings { return Ok(()); } - let locale = detect_system_locale().unwrap_or_else(|_| { - LanguageIdentifier::from_str(DEFAULT_LOCALE).expect("Default locale should always be valid") - }); - // Load common strings along with utility-specific strings if let Ok(locales_dir) = locales_dir { // Load both utility-specific and common strings diff --git a/tests/test_localization_and_colors.rs b/tests/test_localization_and_colors.rs index 58034835b96..5954e8f5f38 100644 --- a/tests/test_localization_and_colors.rs +++ b/tests/test_localization_and_colors.rs @@ -305,3 +305,29 @@ fn test_french_colored_error_messages() { } } } + +/// English strings are embedded, so an English run must not look for or read +/// locale files +#[cfg(all(target_os = "linux", not(wasi_runner), feature = "true"))] +#[test] +fn test_english_does_not_touch_locales_dir() { + let Ok(output) = Command::new("strace") + .args(["-qq", "-f", "-e", "trace=file"]) + .arg(uutests::util::get_tests_binary()) + .args(["true", "--help"]) + .env("LANG", "en_US.UTF-8") + .output() + else { + return; + }; + let trace = String::from_utf8_lossy(&output.stderr); + if !trace.contains('(') { + return; // strace unavailable, e.g. restricted ptrace in a container + } + let lookups: Vec<_> = trace.lines().filter(|l| l.contains("locales")).collect(); + assert!( + lookups.is_empty(), + "true accessed locale files:\n{}", + lookups.join("\n") + ); +}