use std::{
borrow::Cow,
collections::BTreeMap,
ffi::{OsStr, OsString},
io,
path::Path,
process::Stdio,
};
pub use artifactize_foundation::platform::process::ResolvedCommand as Command;
pub(crate) use artifactize_foundation::platform::process::{
Child, ProcessOutcome, spawn_now, spawn_windowless, terminate,
};
pub type Environment = BTreeMap<OsString, OsString>;
pub fn variable(name: &str) -> Option<OsString> {
std::env::var_os(name)
}
pub fn output_text(bytes: &[u8]) -> Cow<'_, str> {
String::from_utf8_lossy(bytes)
}
pub fn output_line(bytes: &[u8]) -> &[u8] {
bytes
.strip_suffix(b"\r\n")
.or_else(|| bytes.strip_suffix(b"\n"))
.unwrap_or(bytes)
}
pub fn remove(environment: &mut Environment, name: &OsStr) {
environment.retain(|key, _| !same_name(key, name));
}
pub fn set(environment: &mut Environment, name: &str, value: impl Into<OsString>) {
remove(environment, OsStr::new(name));
environment.insert(name.into(), value.into());
}
#[cfg(unix)]
fn same_name(left: &OsStr, right: &OsStr) -> bool {
left == right
}
#[cfg(windows)]
fn same_name(left: &OsStr, right: &OsStr) -> bool {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};
let left: Vec<_> = left.encode_wide().collect();
let right: Vec<_> = right.encode_wide().collect();
let (Ok(left_len), Ok(right_len)) = (i32::try_from(left.len()), i32::try_from(right.len()))
else {
return false;
};
unsafe {
CompareStringOrdinal(left.as_ptr(), left_len, right.as_ptr(), right_len, 1) == CSTR_EQUAL
}
}
pub fn command(
program: &str,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
cwd: &Path,
environment: &Environment,
input: bool,
) -> io::Result<Command> {
let program =
artifactize_foundation::platform::process::resolve_with(Path::new(program), cwd, |name| {
environment
.iter()
.rev()
.find_map(|(key, value)| same_name(key, OsStr::new(name)).then(|| value.clone()))
})?;
let mut child = program.command(args)?;
child
.current_dir(cwd)
.env_clear()
.envs(environment)
.stdin(if input { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
Ok(child)
}