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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//use super::errors::*;
use chrono::prelude::*;
use log::{debug, info, warn};
use std::collections::HashSet;
use std::convert::TryFrom;
use std::ffi::{OsStr, OsString};
use std::io::Write;
use std::path::{Path, PathBuf};
//use std::str::FromStr;
use std::time::{Duration, Instant};
use uuid::Uuid;

impl super::Command {
    pub fn execute(command: &str) -> super::errors::Result<super::Command> {
        let cmd = super::Command::exec(command);
        if !cmd.success() {
            bail!(format!(
                "{}\n{}\n{}",
                cmd.summary(),
                cmd.stdout(),
                cmd.stderr()
            ));
        }
        Ok(cmd)
    }

    pub fn execute_in(dir: &Path, command: &str) -> super::errors::Result<super::Command> {
        let orig_dir = std::env::current_dir()?;
        std::env::set_current_dir(&dir)?;
        let cmd = super::Command::execute(command)?;
        std::env::set_current_dir(orig_dir)?;
        if !cmd.success() {
            bail!(format!("{}", cmd.summary()));
        }
        Ok(cmd)
    }

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

    /// execute a command in a specific directory
    ///
    /// # Example
    /// ```
    /// use reef::Command;
    /// let path = std::env::temp_dir().join("test.rb");
    /// let git_version = Command::exec_in(&path,"git --version");
    /// ```
    pub fn exec_in(dir: &Path, command: &str) -> super::Command {
        let (name, args) = parse_command(command);
        let mut c = super::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 stderr(&self) -> &str {
        &self.stderr
    }

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

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

    pub fn log(&self) -> super::errors::Result<()> {
        let filename = super::Paths::log()
            .join("reef")
            .join("Command")
            .join(&format!("{}.json", self.uuid()));
        self.log_to(&filename)
    }

    pub fn log_to(&self, path: &Path) -> super::errors::Result<()> {
        debug!("command log filename: {}", path.display());
        match super::Paths::parent(&path) {
            Ok(parent) => {
                if !parent.exists() {
                    std::fs::create_dir_all(&parent)?;
                }
                let mut file = std::fs::File::create(&path)?;
                file.write(&self.to_json()?.as_bytes())?;
                Ok(())
            }
            Err(_) => {
                bail!(format!("unable to get parent of filename {}", path.display()).as_str())
            }
        }
    }
}

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

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

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

    let now = Instant::now();
    command.env = super::Env::default();
    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();
    command.success = true;
    command.exit_code = 0;
    command.uuid = format!("{}", Uuid::new_v4());

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

    match command.to_json() {
        Ok(json) => info!("{}", json),
        Err(e) => warn!("reef::Command error converting to json: {}", e),
    }
}

/*
impl FromStr for super::Command {
    type Err = super::errors::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match serde_json::from_str::<super::Command>(s) {
            Ok(c) => Ok(c),
            Err(e) => Err(super::errors::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::Paths::which(&name) {
        Some(path) => match super::Paths::shebang(&path) {
            Ok(shebang) => match super::Paths::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::Paths::which("rake") {
        Some(_) => {
            let (name, args) = parse_command("rake default");
            assert!(name.contains("ruby"), "name");
            assert_eq!(2, args.len(), "args: {:?}", args)
        }
        None => {}
    }
}