From 5025faa4d332aec998387843f1d52838586e2f15 Mon Sep 17 00:00:00 2001 From: Colin Walters Date: Thu, 7 Nov 2024 13:02:58 -0500 Subject: [PATCH] utils: Add a helper to run command + capture output Factor out a helper that runs and captures output *and* checks exit status out of what we have existing in `run_and_parse_json`, so we can use it for things that output not-JSON. Signed-off-by: Colin Walters --- utils/src/command.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/utils/src/command.rs b/utils/src/command.rs index 3f3e7c42..d8400051 100644 --- a/utils/src/command.rs +++ b/utils/src/command.rs @@ -15,7 +15,12 @@ pub trait CommandRunExt { /// Execute the child process. fn run(&mut self) -> Result<()>; - /// Execute the child process, parsing its stdout as JSON. + /// Execute the child process and capture its output. This uses `run` internally + /// and will return an error if the child process exits abnormally. + fn run_get_output(&mut self) -> Result>; + + /// Execute the child process, parsing its stdout as JSON. This uses `run` internally + /// and will return an error if the child process exits abnormally. fn run_and_parse_json(&mut self) -> Result; } @@ -88,14 +93,18 @@ impl CommandRunExt for Command { self } - /// Synchronously execute the child, and parse its stdout as JSON. - fn run_and_parse_json(&mut self) -> Result { + fn run_get_output(&mut self) -> Result> { let mut stdout = tempfile::tempfile()?; self.stdout(stdout.try_clone()?); self.run()?; stdout.seek(std::io::SeekFrom::Start(0)).context("seek")?; - let stdout = std::io::BufReader::new(stdout); - serde_json::from_reader(stdout).map_err(Into::into) + Ok(Box::new(std::io::BufReader::new(stdout))) + } + + /// Synchronously execute the child, and parse its stdout as JSON. + fn run_and_parse_json(&mut self) -> Result { + let output = self.run_get_output()?; + serde_json::from_reader(output).map_err(Into::into) } }