use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use crate::command::EnvOp;
use crate::error::Error;
pub(crate) fn resolve_executable(exe: &Path) -> Result<PathBuf, Error> {
let base_cwd = std::env::current_dir()?;
let path = std::env::var_os("PATH");
resolve_executable_in(exe, &base_cwd, path.as_deref())
}
pub(crate) fn resolve_executable_in(exe: &Path, base_cwd: &Path, path: Option<&OsStr>) -> Result<PathBuf, Error> {
if exe.is_absolute() && exe.is_file() {
return Ok(exe.to_path_buf());
}
let append_exe = exe.extension().is_none();
let path_dirs = path.into_iter().flat_map(std::env::split_paths);
let dirs = std::iter::once(base_cwd.to_path_buf()).chain(path_dirs);
for dir in dirs {
let candidate = dir.join(exe);
if candidate.is_file() {
return Ok(candidate);
}
if append_exe {
let with_exe = candidate.with_extension("exe");
if with_exe.is_file() {
return Ok(with_exe);
}
}
}
Err(Error::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("could not resolve executable: {}", exe.display()),
)))
}
pub(crate) fn build_env_block(ops: &[EnvOp]) -> Result<Option<Vec<u16>>, Error> {
let base: Vec<(OsString, OsString)> = std::env::vars_os().collect();
build_env_block_from(&base, ops)
}
pub(crate) fn build_env_block_from(base: &[(OsString, OsString)], ops: &[EnvOp]) -> Result<Option<Vec<u16>>, Error> {
if ops.is_empty() {
return Ok(None);
}
let mut vars: BTreeMap<Vec<u16>, (OsString, OsString)> = BTreeMap::new();
for (key, val) in base {
vars.insert(fold_key(key), (key.clone(), val.clone()));
}
for op in ops {
match op {
EnvOp::Set(key, val) => {
vars.insert(fold_key(key), (key.clone(), val.clone()));
}
EnvOp::Remove(key) => {
vars.remove(&fold_key(key));
}
EnvOp::Clear => vars.clear(),
}
}
let mut block: Vec<u16> = Vec::new();
if vars.is_empty() {
block.push(0);
}
for (key, val) in vars.values() {
ensure_no_nul_wide(key)?;
ensure_no_nul_wide(val)?;
block.extend(key.encode_wide());
block.push(u16::from(b'='));
block.extend(val.encode_wide());
block.push(0);
}
block.push(0);
Ok(Some(block))
}
pub(crate) fn ensure_no_nul_wide(s: &OsStr) -> Result<(), Error> {
if s.encode_wide().any(|unit| unit == 0) {
return Err(Error::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"environment key or value contains an embedded NUL",
)));
}
Ok(())
}
fn fold_key(key: &OsStr) -> Vec<u16> {
let mut folded = Vec::new();
for unit in char::decode_utf16(key.encode_wide()) {
match unit {
Ok(c) => {
let mut buf = [0u16; 2];
for upper in c.to_uppercase() {
folded.extend_from_slice(upper.encode_utf16(&mut buf));
}
}
Err(e) => folded.push(e.unpaired_surrogate()),
}
}
folded
}
#[cfg(test)]
#[path = "resolve_tests.rs"]
mod resolve_tests;