From 675b06352ddaf02807dd99df1cbaa9cfa437eb23 Mon Sep 17 00:00:00 2001 From: steven-omaha <35634100+steven-omaha@users.noreply.github.com> Date: Sat, 6 Apr 2024 18:32:37 +0200 Subject: [PATCH] refact(rustup): add run_external_command --- .../pacdef_core/src/backend/actual/rustup.rs | 10 +++------- crates/pacdef_core/src/cmd.rs | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/pacdef_core/src/backend/actual/rustup.rs b/crates/pacdef_core/src/backend/actual/rustup.rs index 0a12987..25ffa05 100644 --- a/crates/pacdef_core/src/backend/actual/rustup.rs +++ b/crates/pacdef_core/src/backend/actual/rustup.rs @@ -1,7 +1,8 @@ use crate::backend::backend_trait::{Backend, Switches, Text}; use crate::backend::macros::impl_backend_constants; +use crate::cmd::run_external_command; use crate::{Group, Package}; -use anyhow::{bail, ensure, Context, Result}; +use anyhow::{bail, Context, Result}; use std::collections::HashSet; use std::os::unix::process::ExitStatusExt; use std::process::{Command, ExitStatus}; @@ -198,12 +199,7 @@ impl Backend for Rustup { removed_toolchains.push(name); } - // TODO this should be abstracted - let exit_status = cmd.status().with_context(|| "running command [{cmd:?}]")?; - ensure!( - exit_status.success(), - "command returned non-zero exit status" - ); + run_external_command(cmd)?; } for component in components { diff --git a/crates/pacdef_core/src/cmd.rs b/crates/pacdef_core/src/cmd.rs index 695c61d..bfaaaea 100644 --- a/crates/pacdef_core/src/cmd.rs +++ b/crates/pacdef_core/src/cmd.rs @@ -1,7 +1,7 @@ use std::path::Path; use std::process::{Command, ExitStatus}; -use anyhow::{anyhow, Context, Result}; +use anyhow::{anyhow, ensure, Context, Result}; use crate::env::get_editor; @@ -21,9 +21,26 @@ where for f in files { cmd.arg(f.to_string_lossy().to_string()); } + // TODO this could also use the run_external_command function cmd.status().map_err(|e| anyhow!(e)) } let files: Vec<_> = files.iter().map(|p| p.as_ref()).collect(); inner(&files) } + +/// Run an external command. Use the anyhow framework to bubble up errors if they occur. +/// +/// # Errors +/// +/// This function will return an error if the command cannot be run or if it returns a non-zero +/// exit status. In case of an error the full command will be part of the error message. +pub fn run_external_command(mut cmd: Command) -> Result<()> { + let exit_status = cmd.status().with_context(|| "running command [{cmd:?}]")?; + let success = exit_status.success(); + ensure!( + success, + "command [{cmd:?}] returned non-zero exit status {success}" + ); + Ok(()) +}