Add collect_output function to shell commands

This commit is contained in:
Leonard Steppy 2025-01-08 13:38:51 +01:00
parent fefdffe1e9
commit a932a9eb67

View File

@ -4,11 +4,11 @@ use std::error::Error;
use std::fmt::{Display, Formatter};
use std::io;
use std::iter::once;
use std::process::{Command, ExitStatus, Stdio};
use std::process::{Command, ExitStatus, Output};
pub trait LogRunnable {
//TODO add function to query output on success, could further improve code readability
fn run(&mut self, logger: &Logger) -> Result<(), SpecificExecutionError>;
fn collect_output(&mut self) -> Result<Output, SpecificExecutionError>;
}
impl LogRunnable for Command {
@ -18,6 +18,13 @@ impl LogRunnable for Command {
error,
})
}
fn collect_output(&mut self) -> Result<Output, SpecificExecutionError> {
collect_output(self, None).map_err(|error| SpecificExecutionError {
command: self,
error,
})
}
}
fn run(command: &mut Command, logger: &Logger) -> Result<(), ExecutionError> {
@ -29,16 +36,26 @@ fn run(command: &mut Command, logger: &Logger) -> Result<(), ExecutionError> {
}
}
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)?;
}
collect_output(command, Some(logger))?;
}
}
Ok(())
}
fn collect_output(
command: &mut Command,
logger: Option<&Logger>,
) -> Result<Output, ExecutionError> {
let output = command.output()?; //pipes stdout and stderr automatically
if !output.status.success() {
if let Some(logger) = logger {
log!(logger, error, "{}", String::from_utf8_lossy(&output.stderr));
}
Err(output.status)?;
}
Ok(output)
}
#[derive(Debug)]
pub struct SpecificExecutionError<'a> {
pub command: &'a Command,