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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
use super::Command;
use chrono::prelude::*;
use regex::Regex;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter, Result};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use uuid::Uuid;

impl Command {
    /// uses the PATH environment variable to search
    /// for a filename matching the specified name.
    /// if a matching filename is not found, it
    /// will check for the existence of name.exe
    /// and name.bat
    ///
    /// Example
    ///
    /// ```
    /// use reef::Command;
    /// let git_path = Command::which("git").unwrap();
    /// assert!(git_path.exists());
    /// ```
    pub fn which(name: &str) -> Option<PathBuf> {
        _which(name)
    }

    /// extracts the text following the shebang #!
    ///
    /// Example
    ///
    /// given a file
    /// with the contents:
    ///
    /// #!C:/Ruby26-x64/bin/ruby.exe
    ///
    /// the shebang method will return C:/Ruby26-x64/bin/ruby.exe
    ///
    /// ```
    /// use reef::Command;
    /// use std::env;
    /// let path = std::env::temp_dir().join("test.rb");
    /// std::fs::write(&path,b"#!C:/Ruby26-x64/bin/ruby.exe")?;
    /// let target = Command::shebang(&path).unwrap();
    /// assert_eq!("C:/Ruby26-x64/bin/ruby.exe",target);
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn shebang(path: &Path) -> std::result::Result<String, Box<dyn std::error::Error>> {
        _shebang(path)
    }

    pub fn new(command: &str, path: &Path) -> super::Command {
        let (name, args) = parse_command(command);
        let mut c = super::Command::default();
        c.timeout = Duration::from_secs(300);
        c.name = name;
        c.args = args;
        c.dir = path.to_path_buf();
        c
    }

    /// execute a command
    pub fn exec(&self) -> std::result::Result<super::Command, Box<dyn std::error::Error>> {
        _exec(self)
    }

    /// The working directory
    pub fn dir(&self) -> PathBuf {
        let mut dir = PathBuf::new();
        dir.push(&self.dir);
        dir
    }
    /// The command name
    pub fn name(&self) -> &str {
        &self.name
    }
    // Indication of success or failure
    pub fn success(&self) -> bool {
        self.success
    }

    pub fn success_symbol(&self) -> String {
        match self.success() {
            true => "✓".to_string(),
            false => "X".to_string(),
        }
    }

    /// The exit code of the process
    pub fn exit_code(&self) -> i32 {
        self.exit_code
    }
    pub fn stdout(&self) -> &str {
        &self.stdout
    }

    pub fn stderr(&self) -> &str {
        &self.stderr
    }

    pub fn duration(&self) -> &Duration {
        &self.duration
    }

    pub fn timeout(&self) -> &Duration {
        &self.timeout
    }

    pub fn set_timeout(&self, timeout: Duration) -> super::Command {
        let mut command = self.clone();
        command.timeout = timeout;
        command
    }

    pub fn tags(&self) -> &HashSet<String> {
        &self.tags
    }

    pub fn set_tags(&mut self, tags: &HashSet<String>) {
        self.tags = tags.clone()
    }

    pub fn uuid(&self) -> &str {
        &self.uuid
    }

    pub fn duration_string(&self) -> String {
        let duration = self.duration();
        match duration.as_micros() > 999 {
            false => format!("{}\u{00b5}s", duration.as_micros()),
            true => match duration.as_millis() > 999 {
                false => format!("{}ms", duration.as_millis()),
                true => match duration.as_secs() > 300 {
                    false => format!("{}s", duration.as_secs()),
                    true => format!("{}m", duration.as_secs() / 60),
                },
            },
        }
    }

    pub fn summary(&self) -> String {
        format!(
            "{} {} {} {} ({})",
            &self.success_symbol(),
            &self.duration_string(),
            &self.name(),
            &self.args.join(" "),
            &self.dir.display()
        )
    }

    pub fn details(&self) -> Vec<String> {
        let mut details = Vec::new();
        details.push(self.summary());
        details.push("stdout".to_string());
        for line in self.stdout().lines() {
            details.push(line.to_string());
        }
        details.push("stderr".to_string());
        for line in self.stderr().lines() {
            details.push(line.to_string());
        }
        details.push(format!("success {:?}", self.success()));
        details.push(format!("exit code {:?}", self.exit_code()));
        details
    }

    pub fn start_utc(&self) -> DateTime<Utc> {
        match &self.start.parse::<DateTime<Utc>>() {
            Ok(dt) => *dt,
            Err(_) => Utc::now(),
        }
    }

    pub fn start_local(&self) -> DateTime<Local> {
        match &self.start.parse::<DateTime<Local>>() {
            Ok(lt) => *lt,
            Err(_) => Local::now(),
        }
    }

    pub fn env(&self) -> &super::Env {
        &self.env
    }

    pub fn to_json(&self) -> std::result::Result<String, Box<dyn std::error::Error>> {
        Ok(serde_json::to_string_pretty(&self)?)
    }
}

impl Display for Command {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{}", self.summary())
    }
}

impl PartialOrd for Command {
    fn partial_cmp(&self, other: &Command) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Command {
    fn cmp(&self, other: &Command) -> Ordering {
        self.start_utc().cmp(&other.start_utc())
    }
}
impl From<std::io::Error> for super::Command {
    fn from(error: std::io::Error) -> Self {
        let mut cmd = super::Command::default();
        cmd.exit_code = 1;
        cmd.stderr = format!("{}", error);
        cmd
    }
}

// TODO: add timeout support: https://docs.rs/wait-timeout/0.2.0/wait_timeout/
fn _exec(cmd: &super::Command) -> std::result::Result<super::Command, Box<dyn std::error::Error>> {
    let mut command = cmd.clone();
    let now = Instant::now();
    command.env = super::Env::default();
    let mut process_command = std::process::Command::new(&command.name);
    process_command.current_dir(command.dir());
    process_command.args(get_vec_osstring(&command.args.clone()));
    command.start = Utc::now().to_string();
    command.success = true;
    command.exit_code = 0;
    command.uuid = format!("{}", Uuid::new_v4());
    let output = process_command.output()?;
    command.stdout = match std::str::from_utf8(&output.stdout) {
        Ok(text) => text.to_string(),
        Err(_) => "".to_string(),
    };

    command.stderr = match std::str::from_utf8(&output.stderr) {
        Ok(text) => text.to_string(),
        Err(_) => "".to_string(),
    };
    command.success = output.status.success();
    command.duration = now.elapsed();
    Ok(command)
}

fn get_vec_osstring<I, S>(args: I) -> Vec<OsString>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let mut results = Vec::new();
    for arg in args.into_iter() {
        let s: &OsStr = arg.as_ref();
        results.push(s.to_os_string());
    }
    results
}

fn parse_command(command_text: &str) -> (String, Vec<String>) {
    let words: Vec<&str> = command_text.split(' ').collect();
    let mut name = "".to_string();
    let mut args = Vec::new();
    if words.len() > 0 {
        name = words[0].to_string();
        if words.len() > 1 {
            for i in 1..words.len() {
                args.push(words[i].to_string());
            }
        }
    }

    // test for file with content similar to:
    // #! ruby
    // #!/bin/bash
    match _which(&name) {
        Some(path) => match _shebang(&path) {
            Ok(shebang) => match _which(&shebang) {
                Some(_) => {
                    let name2 = shebang;
                    let mut args2 = Vec::new();
                    args2.push(path.display().to_string());
                    for arg in args {
                        args2.push(arg);
                    }
                    return (name2, args2);
                }
                None => {}
            },
            Err(_) => {}
        },
        None => {}
    };

    (name, args)
}

fn _which(name: &str) -> Option<PathBuf> {
    let extensions = vec!["", ".exe", ".bat"];
    for ext in extensions.iter() {
        let exe_name = format!("{}{}", name, ext);
        match _which_exact(&exe_name) {
            Some(path) => {
                return Some(path);
            }
            None => {}
        }
    }
    None
}

fn _shebang(path: &Path) -> std::result::Result<String, Box<dyn std::error::Error>> {
    //} super::Result<String> {
    match std::fs::read_to_string(path) {
        Ok(text) => match Regex::new(r"#!\s*([/:\.\w\-]+)") {
            Ok(re) => match re.captures(&text) {
                Some(caps) => {
                    if caps.len() > 1 {
                        Ok(caps[1].to_string())
                    } else {
                        Ok("".to_string())
                    }
                }
                None => Ok("".to_string()),
            },
            Err(e) => Err(Box::new(e)), // Err(super::errors::Error::from(e)),
        },
        Err(e) => Err(Box::new(e)), //super::errors::Error::from(e)),
    }
}
fn _which_exact(name: &str) -> Option<PathBuf> {
    std::env::var_os("PATH").and_then(|paths| {
        std::env::split_paths(&paths)
            .filter_map(|dir| {
                let full_path = dir.join(&name);
                if full_path.is_file() {
                    Some(full_path)
                } else {
                    None
                }
            })
            .next()
    })
}

#[cfg(test)]
#[test]
fn parse_command_test() {
    match super::Command::which("rake") {
        Some(_) => {
            let (name, args) = parse_command("rake default");
            assert!(name.contains("ruby"), "name");
            assert_eq!(2, args.len(), "args: {:?}", args)
        }
        None => {}
    }
}