use std::ffi::OsString;
use std::process::Command;
use anyhow::{bail, Context, Result};
pub trait AutoRun {
fn run(&mut self) -> Result<()>;
}
impl AutoRun for Command {
fn run(&mut self) -> Result<()> {
let status = self.status().with_context(|| {
format!(
"Internal failure before invoking command: {}",
render_command(self).to_string_lossy()
)
})?;
if !status.success() {
bail!("Failed command: {}", render_command(self).to_string_lossy());
}
Ok(())
}
}
fn render_command(cmd: &Command) -> OsString {
let mut str = OsString::new();
for (k, v) in cmd.get_envs() {
if let Some(v) = v {
str.push(k);
str.push("=\"");
str.push(v);
str.push("\" ");
}
}
str.push(cmd.get_program());
for a in cmd.get_args() {
str.push(" ");
if a.to_string_lossy().contains(' ') {
str.push("\"");
str.push(a);
str.push("\"");
} else {
str.push(a);
}
}
str
}