uucore: localization keeps the first utility's strings when one process runs several utilities
When one process calls more than one utility through the uu crates, which nushell does for mktemp, mkdir, cp, mv, touch, uname and whoami, only the first utility gets its strings. Error messages from every later utility come out as raw Fluent IDs. Reported downstream in nushell/nushell#19004. This is related to #8940, but has a different cause: there, setup_localization was never called, while here it is called for every utility.
> mktemp foo # fresh process
too few X's in template 'foo'
> uname | ignore; mktemp foo # fresh process
mktemp-error-too-few-xs
Cause
Both are in src/uucore/src/lib/mods/locale.rs:
- Per thread:
setup_localization()returns early onceLOCALIZER_IS_SETis true, whatever the utility name.LOCALIZERis aOnceLock, so it can't be replaced either. A latersetup_localization("mktemp")on that thread does nothing. - Per process:
create_english_bundle_from_embeddedcaches the utility's resource instatic UTIL_FLUENT: OnceLock<FluentResource>, which isn't keyed by utility. So a thread that has never set up anything still gets the first utility's strings. In nushell, runningunameonly on a worker thread and thenmktempon the main thread reproduces it.
The errors call translate! from their Display impls, so callers can't work around this.
Proposed fix
- Cache utility resources per utility, e.g.
Mutex<HashMap<String, &'static FluentResource>>, leaked once per utility the same waycreate_bundlealready does. - Make
LOCALIZERaRefCell<Option<Localizer>>and track which utility it was built for. Keep the early return whensetup_localizationis called for the same utility. When the utility changes, rebuild instead of keeping the old one.
Standalone binaries and the multicall binary only ever set up one utility per process, so nothing changes for them. The existing "already initialized" error from init_localization stays as it is.
I've prototyped this against 0.12.0 (about 60 lines in locale.rs). With it, nushell prints the translated messages in all of the cases above. The existing locale tests give the same results with and without the change. If this approach is OK with you, I'll open a PR against main with a unit test that sets up two utilities on one thread and on separate threads.
cc @fdncred