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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
use regex::Regex;
use semver::{Version, VersionReq};
use std::ffi::OsStr;
use std::path::Path;
use std::process::Command;

use error::*;

pub trait Executable {
    fn get_name(&self) -> String;
    fn get_verification_hint(&self) -> String;

    fn get_version_hint(&self) -> String;
    fn get_required_version(&self) -> Option<VersionReq>;

    fn get_current_version(&self) -> Result<Version>
    where
        Self: Sized,
    {
        parse_executable_version(self)
    }
}

pub struct Cargo;
pub struct Xargo;
pub struct Linker;

pub struct ExecutableRunner<Ex: Executable> {
    command: Command,
    executable: Ex,
}

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().chain_err(|| {
                ErrorKind::InternalError(format!(
                    "Unable to execute command '{}'",
                    self.executable.get_name()
                ))
            })?
        };

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

        match raw_output.status.success() {
            true => Ok(output),

            false => bail!(ErrorKind::CommandFailed(
                self.executable.get_name(),
                raw_output.status.code().unwrap_or(-1),
                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) => {
                bail!(ErrorKind::CommandVersionNotFulfilled(
                    self.executable.get_name(),
                    current,
                    required.clone(),
                    self.executable.get_version_hint()
                ));
            }

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

impl Executable for Cargo {
    fn get_name(&self) -> String {
        String::from("cargo")
    }

    fn get_verification_hint(&self) -> String {
        String::from("Please make sure you have it installed and in PATH")
    }

    fn get_version_hint(&self) -> String {
        String::from("Please update Rust and Cargo to latest nightly versions")
    }

    fn get_required_version(&self) -> Option<VersionReq> {
        Some(VersionReq::parse(">= 1.27.0-nightly").unwrap())
    }

    fn get_current_version(&self) -> Result<Version> {
        // Omit Rust channel name because it's not really semver-correct
        // https://github.com/steveklabnik/semver/issues/105

        parse_executable_version(self).map(|mut version| {
            version.pre = vec![];
            version
        })
    }
}

impl Executable for Linker {
    fn get_name(&self) -> String {
        String::from("ptx-linker")
    }

    fn get_verification_hint(&self) -> String {
        String::from("You can install it with: 'cargo install ptx-linker'")
    }

    fn get_version_hint(&self) -> String {
        String::from("You can update it with: 'cargo install -f ptx-linker'")
    }

    fn get_required_version(&self) -> Option<VersionReq> {
        Some(VersionReq::parse(">= 0.7.0").unwrap())
    }
}

impl Executable for Xargo {
    fn get_name(&self) -> String {
        String::from("xargo")
    }

    fn get_verification_hint(&self) -> String {
        String::from("You can install it with: 'cargo install xargo'")
    }

    fn get_version_hint(&self) -> String {
        String::from("You can update it with: 'cargo install -f xargo'")
    }

    fn get_required_version(&self) -> Option<VersionReq> {
        Some(VersionReq::parse(">= 0.3.12").unwrap())
    }
}

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

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

    let raw_output = {
        command.output().chain_err(|| {
            ErrorKind::CommandNotFound(executable.get_name(), executable.get_verification_hint())
        })?
    };

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

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

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

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

        None => bail!(ErrorKind::InternalError(
            "Unable to find executable version".into()
        )),
    }
}