#![deny(
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications,
warnings,
)]
extern crate checked_command;
extern crate cmdline_words_parser;
use cmdline_words_parser::StrExt;
use std::error;
use std::fmt;
use std::io;
use std::process::ExitStatus;
#[derive(Debug, Default)]
pub struct Output {
pub stdout: String,
pub stderr: String,
}
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Failure(ExitStatus, Output),
}
impl From<checked_command::Error> for Error {
fn from(error: checked_command::Error) -> Self {
match error {
checked_command::Error::Io(e) => Error::Io(e),
checked_command::Error::Failure(ex, err) => Error::Failure(
ex,
match err {
Some(e) => Output {
stdout: String::from_utf8_lossy(&e.stdout).to_string(),
stderr: String::from_utf8_lossy(&e.stderr).to_string(),
},
None => Output::default(),
},
),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
"Process error"
}
fn cause(&self) -> Option<&error::Error> {
Some(self)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Io(e) => write!(f, "unexpected I/O Error: {}", e),
Error::Failure(ex, output) => write!(
f,
"status: {:?} stdout: {:?} stderr: {:?}",
ex.code(),
output.stdout,
output.stderr
),
}
}
}
pub fn run(cmd: &str) -> Result<Output, Error> {
let mut cmd = cmd.to_string();
let mut cmd = cmd.parse_cmdline_words();
let mut p = checked_command::CheckedCommand::new(cmd.next().unwrap());
for arg in cmd {
p.arg(arg);
}
let o = p.output()?;
Ok(Output {
stdout: String::from_utf8_lossy(&o.stdout).to_string(),
stderr: String::from_utf8_lossy(&o.stderr).to_string(),
})
}
#[test]
fn failing_command() {
match run(r#"sh -c 'echo "error" >&2; exit 1'"#) {
Ok(_) => panic!("call should have failed"),
Err(Error::Io(io_err)) => panic!("unexpected I/O Error: {:?}", io_err),
Err(Error::Failure(ex, output)) => {
assert_eq!(ex.code().unwrap(), 1);
assert_eq!(&output.stderr, "error\n");
}
}
}