refact(rustup): add run_external_command

This commit is contained in:
steven-omaha
2024-04-06 18:32:37 +02:00
parent 9d3654f436
commit 675b06352d
2 changed files with 21 additions and 8 deletions
@@ -1,7 +1,8 @@
use crate::backend::backend_trait::{Backend, Switches, Text}; use crate::backend::backend_trait::{Backend, Switches, Text};
use crate::backend::macros::impl_backend_constants; use crate::backend::macros::impl_backend_constants;
use crate::cmd::run_external_command;
use crate::{Group, Package}; use crate::{Group, Package};
use anyhow::{bail, ensure, Context, Result}; use anyhow::{bail, Context, Result};
use std::collections::HashSet; use std::collections::HashSet;
use std::os::unix::process::ExitStatusExt; use std::os::unix::process::ExitStatusExt;
use std::process::{Command, ExitStatus}; use std::process::{Command, ExitStatus};
@@ -198,12 +199,7 @@ impl Backend for Rustup {
removed_toolchains.push(name); removed_toolchains.push(name);
} }
// TODO this should be abstracted run_external_command(cmd)?;
let exit_status = cmd.status().with_context(|| "running command [{cmd:?}]")?;
ensure!(
exit_status.success(),
"command returned non-zero exit status"
);
} }
for component in components { for component in components {
+18 -1
View File
@@ -1,7 +1,7 @@
use std::path::Path; use std::path::Path;
use std::process::{Command, ExitStatus}; use std::process::{Command, ExitStatus};
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, ensure, Context, Result};
use crate::env::get_editor; use crate::env::get_editor;
@@ -21,9 +21,26 @@ where
for f in files { for f in files {
cmd.arg(f.to_string_lossy().to_string()); 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)) cmd.status().map_err(|e| anyhow!(e))
} }
let files: Vec<_> = files.iter().map(|p| p.as_ref()).collect(); let files: Vec<_> = files.iter().map(|p| p.as_ref()).collect();
inner(&files) 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(())
}