mirror of
https://github.com/nushell/nushell.git
synced 2025-01-08 23:40:17 +01:00
0f4a073eaf
I was looking where we could remove the usage of once-cell dependency. As for now, I only found one place. Not a terrible improvement, but at least, it removes a dependency nu-test-support crate. Relies on `Mutex::new` constified in Rust 1.63.0
40 lines
1.3 KiB
Rust
40 lines
1.3 KiB
Rust
#![cfg(debug_assertions)]
|
|
|
|
use std::sync::Mutex;
|
|
|
|
use nu_utils::locale::LOCALE_OVERRIDE_ENV_VAR;
|
|
|
|
static LOCALE_OVERRIDE_MUTEX: Mutex<()> = Mutex::new(());
|
|
|
|
/// Run a closure in a fake locale environment.
|
|
///
|
|
/// Before the closure is executed, an environment variable whose name is
|
|
/// defined in `nu_utils::locale::LOCALE_OVERRIDE_ENV_VAR` is set to the value
|
|
/// provided by `locale_string`. When the closure is done, the previous value is
|
|
/// restored.
|
|
///
|
|
/// Environment variables are global values. So when they are changed by one
|
|
/// thread they are changed for all others. To prevent a test from overwriting
|
|
/// the environment variable of another test, a mutex is used.
|
|
pub fn with_locale_override<T>(locale_string: &str, func: fn() -> T) -> T {
|
|
let result = {
|
|
let _lock = LOCALE_OVERRIDE_MUTEX
|
|
.lock()
|
|
.expect("Failed to get mutex lock for locale override");
|
|
|
|
let saved = std::env::var(LOCALE_OVERRIDE_ENV_VAR).ok();
|
|
std::env::set_var(LOCALE_OVERRIDE_ENV_VAR, locale_string);
|
|
|
|
let result = std::panic::catch_unwind(func);
|
|
|
|
if let Some(locale_str) = saved {
|
|
std::env::set_var(LOCALE_OVERRIDE_ENV_VAR, locale_str);
|
|
} else {
|
|
std::env::remove_var(LOCALE_OVERRIDE_ENV_VAR);
|
|
}
|
|
|
|
result
|
|
};
|
|
result.unwrap_or_else(|err| std::panic::resume_unwind(err))
|
|
}
|