From a932a9eb67e2c3ec32cfc196fa68a562c2605dcc Mon Sep 17 00:00:00 2001 From: Leonard Steppy Date: Wed, 8 Jan 2025 13:38:51 +0100 Subject: [PATCH] Add collect_output function to shell commands --- src/command.rs | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/command.rs b/src/command.rs index 529ce24..4b9073d 100644 --- a/src/command.rs +++ b/src/command.rs @@ -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; } impl LogRunnable for Command { @@ -18,6 +18,13 @@ impl LogRunnable for Command { error, }) } + + fn collect_output(&mut self) -> Result { + 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 { + 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,