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
use chrono::prelude::*;
use log::{info, warn};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::convert::TryFrom;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::{Duration, Instant};

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
/// A data structure to hold the infomation about a std::process::Command that
/// has been executed.
pub struct Command {
    /// The working directory
    dir: PathBuf,
    /// The command name
    name: String,
    /// The command arguments
    args: Vec<String>,
    /// The standard output text
    stdout: String,
    /// The standard error text
    stderr: String,
    /// Indication of success or failure
    success: bool,
    /// The exit code of the process
    exit_code: i32,
    /// The duration of the command execution
    duration: Duration,
    /// The start time of the command execution
    start: String,
    /// Tags
    tags: HashSet<String>,
}

impl Command {
    /// execute a command
    ///
    /// # Example
    /// ```
    /// use reef::command::Command;
    /// let git_version = Command::exec("git --version");
    /// ```
    pub fn exec(command: &str) -> Command {
        let (name, args) = parse_command(command);
        let mut c = Command::default();
        c.name = name;
        c.args = args;
        _execute(&mut c);
        c
    }

    pub fn exec2(dir: &Path, command: &str) -> Command {
        let (name, args) = parse_command(command);
        let mut c = Command::default();
        c.name = name;
        c.args = args;
        match std::env::current_dir() {
            Ok(orig_dir) => match std::env::set_current_dir(dir) {
                Ok(_) => {
                    _execute(&mut c);
                    match std::env::set_current_dir(orig_dir) {
                        Ok(_) => c,
                        Err(e) => {
                            c.success = false;
                            c.exit_code = 1;
                            c.stderr = e.to_string();
                            c
                        }
                    }
                }
                Err(e) => {
                    c.success = false;
                    c.exit_code = 1;
                    c.stderr = e.to_string();
                    c
                }
            },
            Err(e) => {
                c.success = false;
                c.exit_code = 1;
                c.stderr = e.to_string();
                c
            }
        }
    }

    /// 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 duration(&self) -> &Duration {
        &self.duration
    }

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

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
    }
}

impl TryFrom<&Command> for Vec<u8> {
    type Error = super::error::Error;
    fn try_from(value: &Command) -> Result<Self, Self::Error> {
        match serde_json::to_vec(value) {
            Ok(bytes) => Ok(bytes),
            Err(e) => Err(super::error::Error::from(e)),
        }
    }
}

impl TryFrom<&Vec<u8>> for Command {
    type Error = super::error::Error;
    fn try_from(bytes: &Vec<u8>) -> Result<Self, Self::Error> {
        match serde_json::from_slice(bytes) {
            Ok(command) => Ok(command),
            Err(e) => Err(super::error::Error::from(e)),
        }
    }
}
fn _execute(command: &mut Command) {
    match std::env::current_dir() {
        Ok(p) => command.dir = p,
        Err(_) => command.dir = PathBuf::new(),
    };

    let now = Instant::now();
    let mut process_command = std::process::Command::new(&command.name);
    if command.dir().exists() {
        process_command.current_dir(command.dir());
    }
    process_command.args(get_vec_osstring(&command.args.clone()));
    command.start = Utc::now().to_string();

    match process_command.output() {
        Ok(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();
            info!("{}", command.summary());
        }
        Err(e) => {
            command.success = false;
            command.exit_code = 1;
            command.stderr = e.to_string();
            warn!("{}", command.summary())
        }
    };
}

impl FromStr for Command {
    type Err = super::error::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match serde_json::from_str::<Command>(s) {
            Ok(c) => Ok(c),
            Err(e) => Err(super::error::Error::from(e)),
        }
    }
}

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) {
        Some(path) => match super::path::shebang(&path) {
            Ok(shebang) => match super::path::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)
}

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