Fix and refactor command module
This commit is contained in:
parent
f3e965394e
commit
9befc1fcf2
@ -6,43 +6,37 @@ use std::io;
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
|
||||
pub trait LogRunnable {
|
||||
fn run(&mut self, logger: &Logger) -> Result<(), ExecutionError>;
|
||||
fn run(&mut self, logger: &Logger) -> Result<(), SpecificExecutionError>;
|
||||
}
|
||||
|
||||
impl LogRunnable for Command {
|
||||
fn run(&mut self, logger: &Logger) -> Result<(), SpecificExecutionError> {
|
||||
//TODO I'm not happy yet with the implementation of this method
|
||||
match logger.level {
|
||||
LogLevel::Debug | LogLevel::Info => self
|
||||
.status()
|
||||
.map_err(ExecutionError::StartError)
|
||||
.and_then(|status| {
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ExecutionError::BadExitStatus(status))
|
||||
}
|
||||
}),
|
||||
LogLevel::Error => self
|
||||
.stdout(Stdio::piped())
|
||||
.output()
|
||||
.map_err(ExecutionError::StartError)
|
||||
.and_then(|output| {
|
||||
if output.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
log!(logger, error, "{}", String::from_utf8_lossy(&output.stderr));
|
||||
Err(ExecutionError::BadExitStatus(output.status))
|
||||
}
|
||||
}),
|
||||
}
|
||||
.map_err(|error| SpecificExecutionError {
|
||||
run(self, logger).map_err(|error| SpecificExecutionError {
|
||||
command: self,
|
||||
error,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn run(command: &mut Command, logger: &Logger) -> Result<(), ExecutionError> {
|
||||
match logger.level {
|
||||
LogLevel::Debug | LogLevel::Info => {
|
||||
let status = command.status()?;
|
||||
if !status.success() {
|
||||
Err(status)?;
|
||||
}
|
||||
}
|
||||
LogLevel::Error => {
|
||||
let output = command.stdout(Stdio::piped()).output()?;
|
||||
if !output.status.success() {
|
||||
log!(logger, error, "{}", String::from_utf8_lossy(&output.stderr));
|
||||
Err(output.status)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SpecificExecutionError<'a> {
|
||||
pub command: &'a Command,
|
||||
@ -53,7 +47,7 @@ impl Display for SpecificExecutionError<'_> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"Failed to execute command {}: {}",
|
||||
"Failed to execute command {:?}: {}",
|
||||
self.command, self.error
|
||||
)
|
||||
}
|
||||
@ -90,4 +84,4 @@ impl Display for ExecutionError {
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ExecutionError {}
|
||||
impl Error for ExecutionError {}
|
||||
Loading…
Reference in New Issue
Block a user