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
use super::errors::*;
use super::{Command, Env};
use chrono::prelude::*;
use colored::*;
use std::cmp::Ordering;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter};
use std::path::Path;
use std::time::{Duration, Instant};
use uuid::Uuid;

impl Command {
    pub fn new(command: &str, path: &Path) -> 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(&mut self) -> Result<Command> {
        _exec(self)
    }

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

    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 to_json(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(&self)?)
    }
}

impl Display for Command {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self.success {
            true => write!(
                f,
                "{} {} {} {}{}",
                &self.success_symbol().green().bold(),
                &self.duration_string().normal(),
                &self.name.yellow().bold(),
                &self.args.join(" ").yellow().bold(),
                "".clear()
            ),
            false => write!(
                f,
                "{} {} {} {}\n{}\n{}",
                &self.success_symbol().red().bold(),
                &self.duration_string().normal(),
                &self.name.yellow().bold(),
                &self.args.join(" ").yellow().bold(),
                &self.stdout.as_str().clear(),
                &self.stderr.as_str().clear()
            ),
        }
    }
}

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 Command {
    fn from(error: std::io::Error) -> Self {
        let mut cmd = 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: &mut Command) -> Result<Command> {
    let mut command = cmd.clone();
    let now = Instant::now();
    command.env = super::Env::default();

    // test that the command.name is known by the system
    Env::which(&command.name)?;

    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(),
    };

    // TODO: command failure should be an error condition
    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 super::path::which(&name) {
        Ok(path) => match super::path::shebang(&path) {
            Ok(shebang) => match super::path::which(&shebang) {
                Ok(_) => {
                    let name2 = shebang;
                    let mut args2 = Vec::new();
                    args2.push(path.display().to_string());
                    for arg in args {
                        args2.push(arg);
                    }
                    return (name2, args2);
                }
                Err(_) => {}
            },
            Err(_) => {}
        },
        Err(_) => {}
    }

    (name, args)
}

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