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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::{ffi::OsStr, path::Path, process::Command};

use regex::Regex;
use semver::Version;

use crate::error::{BuildErrorKind, Error, Result, ResultExt};

use super::{process::streaming_output, Executable};

#[allow(clippy::module_name_repetitions)]
pub struct ExecutableRunner<Ex: Executable> {
    command: Command,
    executable: Ex,
}

#[derive(Debug)]
pub struct Output {
    pub stdout: String,
    pub stderr: String,
}

impl<Ex: Executable> ExecutableRunner<Ex> {
    pub fn new(executable: Ex) -> Self {
        ExecutableRunner {
            command: Command::new(executable.get_name()),
            executable,
        }
    }

    pub fn with_args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.command.args(args);
        self
    }

    pub fn with_env<K, V>(&mut self, key: K, val: V) -> &mut Self
    where
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.command.env(key, val);
        self
    }

    pub fn with_cwd<P>(&mut self, path: P) -> &mut Self
    where
        P: AsRef<Path>,
    {
        self.command.current_dir(path);
        self
    }

    pub fn run(&mut self) -> Result<Output> {
        self.check_version()?;

        let raw_output = {
            self.command.output().with_context(|| {
                BuildErrorKind::InternalError(format!(
                    "Unable to execute command '{}'",
                    self.executable.get_name()
                ))
            })?
        };

        let output = Output {
            stdout: String::from_utf8(raw_output.stdout).context(BuildErrorKind::OtherError)?,
            stderr: String::from_utf8(raw_output.stderr).context(BuildErrorKind::OtherError)?,
        };

        if raw_output.status.success() {
            Ok(output)
        } else {
            Err(Error::from(BuildErrorKind::CommandFailed {
                command: self.executable.get_name(),
                code: raw_output.status.code().unwrap_or(-1),
                stderr: output.stderr,
            }))
        }
    }

    pub fn run_live<O: FnMut(&str), E: FnMut(&str)>(
        &mut self,
        on_stdout_line: O,
        on_stderr_line: E,
    ) -> Result<Output> {
        self.check_version()?;

        let raw_output = streaming_output(&mut self.command, on_stdout_line, on_stderr_line)
            .with_context(|| {
                BuildErrorKind::InternalError(format!(
                    "Unable to execute command '{}'",
                    self.executable.get_name()
                ))
            })?;

        let output = Output {
            stdout: String::from_utf8(raw_output.stdout).context(BuildErrorKind::OtherError)?,
            stderr: String::from_utf8(raw_output.stderr).context(BuildErrorKind::OtherError)?,
        };

        if raw_output.status.success() {
            Ok(output)
        } else {
            Err(Error::from(BuildErrorKind::CommandFailed {
                command: self.executable.get_name(),
                code: raw_output.status.code().unwrap_or(-1),
                stderr: output.stderr,
            }))
        }
    }

    fn check_version(&self) -> Result<()> {
        let current = self.executable.get_current_version()?;
        let required = self.executable.get_required_version();

        match required {
            Some(ref required) if !required.matches(&current) => {
                Err(Error::from(BuildErrorKind::CommandVersionNotFulfilled {
                    command: self.executable.get_name(),
                    current,
                    required: required.clone(),
                    hint: self.executable.get_version_hint(),
                }))
            }

            _ => Ok(()),
        }
    }
}

pub(crate) fn parse_executable_version<E: Executable>(executable: &E) -> Result<Version> {
    let mut command = Command::new(executable.get_name());

    command.args(["-V"]);

    let raw_output = {
        command
            .output()
            .with_context(|| BuildErrorKind::CommandNotFound {
                command: executable.get_name(),
                hint: executable.get_verification_hint(),
            })?
    };

    let output = Output {
        stdout: String::from_utf8(raw_output.stdout).context(BuildErrorKind::OtherError)?,
        stderr: String::from_utf8(raw_output.stderr).context(BuildErrorKind::OtherError)?,
    };

    if !raw_output.status.success() {
        bail!(BuildErrorKind::CommandFailed {
            command: executable.get_name(),
            code: raw_output.status.code().unwrap_or(-1),
            stderr: output.stderr,
        });
    }

    let version_regex = Regex::new(&format!(r"{}\s(\S+)", executable.get_name()))
        .context(BuildErrorKind::OtherError)?;

    match version_regex.captures(&(output.stdout + &output.stderr)) {
        Some(captures) => Ok(Version::parse(&captures[1]).context(BuildErrorKind::OtherError)?),

        None => Err(Error::from(BuildErrorKind::InternalError(
            "Unable to find executable version".into(),
        ))),
    }
}