src/tools.rs: new helper to handle command_output (std::process::Output)

This commit is contained in:
Dietmar Maurer 2020-05-27 06:52:21 +02:00
parent ed216fd773
commit 97fab7aa11
2 changed files with 27 additions and 17 deletions

View File

@ -149,23 +149,8 @@ pub fn compute_file_diff(filename: &str, shadow: &str) -> Result<String, Error>
.output() .output()
.map_err(|err| format_err!("failed to execute diff - {}", err))?; .map_err(|err| format_err!("failed to execute diff - {}", err))?;
if !output.status.success() { let diff = crate::tools::command_output(output)
match output.status.code() { .map_err(|err| format_err!("diff failed: {}", err))?;
Some(code) => {
if code == 0 { return Ok(String::new()); }
if code != 1 {
let msg = String::from_utf8(output.stderr)
.map(|m| if m.is_empty() { String::from("no error message") } else { m })
.unwrap_or_else(|_| String::from("non utf8 error message (suppressed)"));
bail!("diff failed with status code: {} - {}", code, msg);
}
}
None => bail!("diff terminated by signal"),
}
}
let diff = String::from_utf8(output.stdout)?;
Ok(diff) Ok(diff)
} }

View File

@ -474,6 +474,31 @@ pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> {
Ok((path, components)) Ok((path, components))
} }
/// Helper to check result from std::process::Command output
pub fn command_output(output: std::process::Output) -> Result<String, Error> {
if !output.status.success() {
match output.status.code() {
Some(code) => {
if code == 0 { return Ok(String::new()); }
if code != 1 {
let msg = String::from_utf8(output.stderr)
.map(|m| if m.is_empty() { String::from("no error message") } else { m })
.unwrap_or_else(|_| String::from("non utf8 error message (suppressed)"));
bail!("status code: {} - {}", code, msg);
}
}
None => bail!("terminated by signal"),
}
}
let output = String::from_utf8(output.stdout)?;
Ok(output)
}
pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), Error> { pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), Error> {
use nix::fcntl::{fcntl, FdFlag, F_GETFD, F_SETFD}; use nix::fcntl::{fcntl, FdFlag, F_GETFD, F_SETFD};
let mut flags = FdFlag::from_bits(fcntl(fd, F_GETFD)?) let mut flags = FdFlag::from_bits(fcntl(fd, F_GETFD)?)