Skip to content
Merged
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
24 changes: 17 additions & 7 deletions src/uucore/src/lib/mods/locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions tests/test_localization_and_colors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
);
}
Loading