From 7e752d95b5ff45e6a292b0b592c831004ca32db7 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Fri, 28 May 2021 00:59:07 +0800 Subject: [PATCH] feat: cmd --- Cargo.toml | 2 +- src/util_cmd.rs | 32 +++++++++++++++++++++++++++++++- src/util_msg.rs | 6 ++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a903e7f..d779f55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust_util" -version = "0.6.33" +version = "0.6.34" authors = ["Hatter Jiang "] edition = "2018" description = "Hatter's Rust Util" diff --git a/src/util_cmd.rs b/src/util_cmd.rs index 5e14b04..289b771 100644 --- a/src/util_cmd.rs +++ b/src/util_cmd.rs @@ -1,5 +1,35 @@ use std::io::{self, Error, ErrorKind}; -use std::process::{Command, ExitStatus}; +use std::process::{Command, ExitStatus, Output}; +use crate::util_msg::{print_debug, print_error, MessageType}; + +pub fn run_command_or_exit(cmd: &str, args: &[&str]) -> Output { + let mut c = Command::new(cmd); + c.args(args); + crate::util_msg::when(MessageType::DEBUG, || { + print_debug(&format!("Run command: {:?}", c)); + }); + let output = c.output(); + match output { + Err(e) => { + print_error(&format!("Run command: {:?}, failed: {}", c, e)); + std::process::exit(-1); + }, + Ok(output) => { + if !output.status.success() { + print_error(&format!(r##"Run command failed, code: {:?} +-----std out--------------------------------------------------------------- +{} +-----std err--------------------------------------------------------------- +{} +---------------------------------------------------------------------------"##, + output.status.code(), + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr))); + } + output + } + } +} pub fn run_command_and_wait(cmd: &mut Command) -> io::Result { cmd.spawn()?.wait() diff --git a/src/util_msg.rs b/src/util_msg.rs index a4af550..7c22702 100644 --- a/src/util_msg.rs +++ b/src/util_msg.rs @@ -92,6 +92,12 @@ pub fn is_logger_level_enabled(mt: MessageType) -> bool { mt.get_u8_value() >= logger_level.get_u8_value() } +pub fn when(mt: MessageType, f: F) where F: Fn() -> () { + if is_logger_level_enabled(mt) { + f(); + } +} + pub fn print_message(mt: MessageType, message: &str) { if is_logger_level_enabled(mt) { match mt {