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
use crate::{Duration, Env, Paths, Status};
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use std::path::Path;
use std::time::Instant;

#[derive(
    Serialize, Deserialize, Clone, Debug, Hash, Default, PartialEq, Eq, juniper::GraphQLObject,
)]
/// Metadata about a std::process::Command
pub struct Command {
    /// The working directory
    pub dir: String,
    /// The command name
    pub name: String,
    /// The command arguments
    pub args: Vec<String>,
    /// The standard output text
    pub stdout: String,
    /// The standard error text
    pub stderr: String,
    /// Indication of success or failure
    pub status: Status,
    /// The exit code of the process
    pub exit_code: i32,
    /// The duration of the command execution
    pub duration: Duration,
    /// The timeout duration for the command execution
    pub timeout: Duration,
    /// The start time of the command execution
    pub start: String,
    /// Environment metadata
    pub env: Env,
}

impl Command {
    pub fn new(command: &str) -> Command {
        let (name, args) = crate::text::parse_command(command);
        let mut c = Command::default();
        c.timeout = Duration::from_std(std::time::Duration::new(300, 0)).unwrap();
        c.name = name;
        c.args = args;
        c.dir = std::env::temp_dir().to_str().unwrap().to_string();
        c
    }

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

    pub fn age(&self) -> std::time::Duration {
        let chrono_duration = Utc::now()
            .naive_utc()
            .signed_duration_since(self.start_utc().naive_utc());
        match chrono_duration.to_std() {
            Ok(duration) => duration,
            Err(_) => std::time::Duration::new(0, 0),
        }
    }

    pub fn duration_string(&self) -> String {
        crate::duration::format(&self.duration.to_std().unwrap())
    }

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

    pub fn exec_in<P: AsRef<Path>>(&self, path: P) -> Command {
        let mut c = self.clone();
        c.dir = path
            .as_ref()
            .to_path_buf()
            .into_os_string()
            .into_string()
            .unwrap();
        c.exec()
    }

    // TODO: add timeout support: https://docs.rs/wait-timeout/0.2.0/wait_timeout/
    pub fn exec(&self) -> Command {
        let mut command = self.clone();
        let now = Instant::now();
        command.env = Env::default();

        match Env::which(&command.name) {
            Ok(command_path) => {
                let mut process_command = std::process::Command::new(&command.name);
                command.start = Utc::now().to_string();

                let ext = Paths::extension(&command_path);
                if ext == "bat" || ext == "cmd" {
                    process_command = std::process::Command::new(&format!(
                        "{}",
                        Paths::which("cmd").unwrap().display()
                    ));
                    process_command.current_dir(&command.dir);

                    let mut args: Vec<String> = Vec::new();
                    args.push("/C".to_string());
                    args.push(format!("{}", command_path.display()));
                    args.append(&mut command.args.clone());
                    process_command.args(crate::text::get_vec_osstring(&args.clone()));
                } else {
                    process_command.current_dir(&command.dir);
                    process_command.args(crate::text::get_vec_osstring(&command.args.clone()));
                }

                command.status = Status::Ok;
                command.exit_code = 0;

                match process_command.output() {
                    Ok(output) => {
                        command.exit_code = match output.status.code() {
                            Some(code) => code,
                            None => 0,
                        };
                        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.status = match output.status.success() {
                            true => Status::Ok,
                            false => Status::Error,
                        };
                        command.duration = Duration::from_std(now.elapsed()).unwrap();
                        command
                    }
                    Err(e) => {
                        command.status = Status::Error;
                        command.stderr.push_str(&format!("{}", e));
                        command
                    }
                }
            }
            Err(e) => {
                command.status = Status::Error;
                command.stderr.push_str(&format!("{}", e));
                command
            }
        }
    }
}

impl Display for Command {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}>{} {}\n{}{}",
            &self.dir,
            &self.name,
            &self.args.join(" "),
            &self.stdout,
            &self.stderr
        )
    }
}

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

#[cfg(test)]
use std::path::PathBuf;

#[test]
fn usage() {
    let git_version = Command::new("git --version").exec();
    assert_eq!(git_version.status, Status::Ok);
    assert!(git_version.stdout.contains("git version"));
    let dir = PathBuf::from(&git_version.dir);
    assert!(dir.exists(), "dir");
}