rust_util/
util_cmd.rs

1use std::io::{self, Error, ErrorKind};
2use std::process::{Command, ExitStatus, Output};
3use crate::util_msg::{print_debug, print_error, MessageType, print_message};
4
5pub fn run_command_or_exit(cmd: &str, args: &[&str]) -> Output {
6    let mut c = Command::new(cmd);
7    c.args(args);
8    crate::util_msg::when(MessageType::DEBUG, || {
9        print_debug(&format!("Run command: {:?}", c));
10    });
11    let output = c.output();
12    match output {
13        Err(e) => {
14            print_error(&format!("Run command: {:?}, failed: {}", c, e));
15            crate::util_runtime::invoke_callbacks();
16            std::process::exit(-1);
17        }
18        Ok(output) => {
19            if !output.status.success() {
20                print_output(MessageType::ERROR, &output);
21            }
22            output
23        }
24    }
25}
26
27pub fn print_output(message_type: MessageType, output: &Output) {
28    crate::util_msg::when(message_type, || {
29        print_message(message_type, &format!(r##"Run command failed, code: {:?}
30-----std out---------------------------------------------------------------
31{}
32-----std err---------------------------------------------------------------
33{}
34---------------------------------------------------------------------------"##,
35                                             output.status.code(),
36                                             String::from_utf8_lossy(&output.stdout),
37                                             String::from_utf8_lossy(&output.stderr)));
38    });
39}
40
41pub fn run_command_and_wait(cmd: &mut Command) -> io::Result<ExitStatus> {
42    cmd.spawn()?.wait()
43}
44
45pub fn extract_package_and_wait(dir: &str, file_name: &str) -> io::Result<ExitStatus> {
46    let mut cmd: Command;
47    if file_name.ends_with(".zip") {
48        cmd = Command::new("unzip");
49    } else if file_name.ends_with(".tar.gz") {
50        cmd = Command::new("tar");
51        cmd.arg("-xzvf");
52    } else {
53        let m: &str = &format!("Unknown file type: {}", file_name);
54        return Err(Error::new(ErrorKind::Other, m));
55    }
56    cmd.arg(file_name).current_dir(dir);
57    run_command_and_wait(&mut cmd)
58}
59