use std::env;
use std::ffi::OsString;
use std::io;
use std::path::Path;
use std::process::{Command, ExitStatus};
const HOST_PREFIX: &str = "host: ";
fn search_for_host(command: &mut Command) -> Option<String> {
let output = command.output().ok()?.stdout;
let output = String::from_utf8(output).ok()?;
output
.lines()
.find(|line| line.starts_with(HOST_PREFIX))
.map(|host_line| host_line.trim_start_matches(HOST_PREFIX).to_string())
}
pub fn driver() -> io::Result<ExitStatus> {
let cargo = env::var_os("CARGO").expect("CARGO environment variable is not set");
let rustc = Path::new(&cargo).with_file_name("rustc");
let host = search_for_host(Command::new(&cargo).arg("version").arg("-v"))
.or_else(|| search_for_host(Command::new(rustc).arg("rustc").arg("-vV")))
.ok_or_else(|| io::Error::other("could not determine host"))?;
let host = host.replace(['-', '.'], "_").to_uppercase();
let runner = format!("CARGO_TARGET_{host}_RUNNER");
let cargo_valgrind = env::args_os()
.next()
.unwrap_or_else(|| OsString::from("cargo-valgrind"));
Command::new(cargo)
.args(env::args_os().skip(2))
.envs(env::vars_os())
.env(runner, cargo_valgrind)
.spawn()?
.wait()
}