use std::{collections::BTreeMap, io, path::Path, process::Command};
const NUMERICAL: &[&str] = &[
"PYTHONHASHSEED",
"OMP_NUM_THREADS",
"OMP_DYNAMIC",
"OPENBLAS_NUM_THREADS",
"MKL_NUM_THREADS",
"MKL_CBWR",
"BLIS_NUM_THREADS",
"VECLIB_MAXIMUM_THREADS",
"NUMEXPR_NUM_THREADS",
"CUDA_VISIBLE_DEVICES",
"NVIDIA_TF32_OVERRIDE",
"CUBLAS_WORKSPACE_CONFIG",
"JULIA_NUM_THREADS",
];
use crate::config::validate_environment_name as validate_name;
pub(crate) fn capture(names: &[String]) -> io::Result<BTreeMap<String, Option<String>>> {
let mut values = BTreeMap::new();
for name in NUMERICAL
.iter()
.copied()
.map(str::to_owned)
.chain(names.iter().cloned())
{
validate_name(&name)?;
let value = match std::env::var(&name) {
Ok(value) => Some(value),
Err(std::env::VarError::NotPresent) => None,
Err(_) => {
return Err(io::Error::other(format!(
"scientific environment variable {name} is not UTF-8"
)));
}
};
let value = if name == "PYTHONHASHSEED" && value.is_none() {
Some("0".into())
} else {
value
};
values.insert(name, value);
}
Ok(values)
}
pub(crate) fn apply(command: &mut Command, values: &BTreeMap<String, Option<String>>) {
for (name, value) in values {
if let Some(value) = value {
command.env(name, value);
} else {
command.env_remove(name);
}
}
}
pub(crate) fn read(path: &Path) -> io::Result<BTreeMap<String, Option<String>>> {
serde_json::from_reader(std::fs::File::open(path)?).map_err(io::Error::other)
}