1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use eyre::eyre;
use std::process::Command;
use std::str;
use tracing::{debug, trace};

use crate::error::{handle_exec_error, handle_generic_error, Error};

pub struct ExecOutput {
    pub stdout: String,
    pub stderr: String,
}

pub fn simple_exec(desc: &str, command_path: &str, args: &[&str]) -> Result<ExecOutput, Error> {
    debug!(
        "Executing command for {}: {} {}",
        desc,
        command_path,
        itertools::join(args, " ")
    );

    let output = Command::new(command_path)
        .args(args)
        .output()
        .map_err(handle_exec_error(command_path))?;

    if output.status.success() {
        let stdout = str::from_utf8(&output.stdout)
            .map_err(handle_generic_error)?
            .to_string();

        let stderr = str::from_utf8(&output.stderr)
            .map_err(handle_generic_error)?
            .to_string();

        trace!(
            "command executed successfully with stdout: {}, stderr: {}",
            stdout,
            stderr
        );

        Ok(ExecOutput { stdout, stderr })
    } else {
        let message = str::from_utf8(&output.stderr).map_err(handle_generic_error)?;

        Err(Error::generic(eyre!(
            "command exited with error status {:?} and message: {}",
            output.status.code(),
            message
        )))
    }
}