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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#![deny(missing_docs)]

//! Utility for running a command in a subprocess.
//!
//! The [`Command`] type is a wrapper around the [`std::process::Command`]
//! type that adds a few convenient features:
//!
//! - Print or log the command before running it
//! - Optionally return an error if the command is not successful
//! - The command can be formatted as a command-line string
//! - The [`Command`] type can be cloned and its fields are public
//!
//! [`Command`]: struct.Command.html
//! [`std::process::Command`]: https://doc.rust-lang.org/std/process/struct.Command.html

use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::{fmt, io, process};

/// Type of error.
#[derive(Debug)]
pub enum ErrorKind {
    /// An error occurred in the calls used to run the command. For
    /// example, this variant is used if the program does not exist.
    Run(io::Error),

    /// The command exited non-zero or due to a signal.
    Exit(process::ExitStatus),
}

/// Error returned by [`Command::run`].
///
/// [`Command::run`]: struct.Command.html#method.run
#[derive(Debug)]
pub struct Error {
    /// The command that caused the error.
    pub command: Command,

    /// The type of error.
    pub kind: ErrorKind,
}

impl Error {
    /// Check if the error kind is `Run`.
    pub fn is_run_error(&self) -> bool {
        matches!(self.kind, ErrorKind::Run(_))
    }

    /// Check if the error kind is `Exit`.
    pub fn is_exit_error(&self) -> bool {
        matches!(self.kind, ErrorKind::Exit(_))
    }
}

/// Internal trait for converting an io::Error to an Error.
trait IntoError<T> {
    fn into_run_error(self, command: &Command) -> Result<T, Error>;
}

impl<T> IntoError<T> for Result<T, io::Error> {
    fn into_run_error(self, command: &Command) -> Result<T, Error> {
        self.map_err(|err| Error {
            command: command.clone(),
            kind: ErrorKind::Run(err),
        })
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match &self.kind {
            ErrorKind::Run(err) => write!(
                f,
                "failed to run '{}': {}",
                self.command.command_line_lossy(),
                err
            ),
            ErrorKind::Exit(err) => write!(
                f,
                "command '{}' failed: {}",
                self.command.command_line_lossy(),
                err
            ),
        }
    }
}

impl std::error::Error for Error {}

/// The output of a finished process.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Output {
    /// The status (exit code) of the process.
    pub status: process::ExitStatus,

    /// The data that the process wrote to stdout.
    pub stdout: Vec<u8>,

    /// The data that the process wrote to stderr.
    pub stderr: Vec<u8>,
}

impl Output {
    /// Get stdout as a string.
    pub fn stdout_string_lossy(&self) -> Cow<str> {
        String::from_utf8_lossy(&self.stdout)
    }

    /// Get stderr as a string.
    pub fn stderr_string_lossy(&self) -> Cow<str> {
        String::from_utf8_lossy(&self.stderr)
    }
}

impl From<process::Output> for Output {
    fn from(o: process::Output) -> Output {
        Output {
            status: o.status,
            stdout: o.stdout,
            stderr: o.stderr,
        }
    }
}

fn combine_output(mut cmd: process::Command) -> Result<Output, io::Error> {
    let (mut reader, writer) = os_pipe::pipe()?;
    let writer_clone = writer.try_clone()?;
    cmd.stdout(writer);
    cmd.stderr(writer_clone);

    let mut handle = cmd.spawn()?;

    drop(cmd);

    let mut output = Vec::new();
    reader.read_to_end(&mut output)?;
    let status = handle.wait()?;

    Ok(Output {
        stdout: output,
        stderr: Vec::new(),
        status,
    })
}

/// Where log messages go.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LogTo {
    /// Print to stdout.
    Stdout,

    /// Use the standard `log` crate.
    #[cfg(feature = "logging")]
    Log,
}

/// A command to run in a subprocess and options for how it is run.
///
/// Some notable trait implementations:
/// - Derives `Clone`, `Debug`, `Eq`, and `PartialEq`
/// - `Default` (see docstrings for each field for what the
///   corresponding default is)
/// - `From<&Command> for std::process::Command` to convert to a
///   [`std::process::Command`]
///
/// [`std::process::Command`]: https://doc.rust-lang.org/std/process/struct.Command.html
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Command {
    /// Program path.
    ///
    /// The path can be just a file name, in which case the `$PATH` is
    /// searched.
    pub program: PathBuf,

    /// Arguments passed to the program.
    pub args: Vec<OsString>,

    /// Directory from which to run the program.
    ///
    /// If not set (the default), the current working directory is
    /// used.
    pub dir: Option<PathBuf>,

    /// Where log messages go. The default is stdout.
    pub log_to: LogTo,

    /// If `true` (the default), log the command before running it.
    pub log_command: bool,

    /// If `true`, log the output if the command exits non-zero or due
    /// to a signal. This does nothing is `capture` is `false` or if
    /// `check` is `false`. The default is `false`.
    pub log_output_on_error: bool,

    /// If `true` (the default), check if the command exited
    /// successfully and return an error if not.
    pub check: bool,

    /// If `true`, capture the stdout and stderr of the
    /// command. The default is `false`.
    pub capture: bool,

    /// If `true`, send stderr to stdout; the `stderr` field in
    /// `Output` will be empty. The default is `false.`
    pub combine_output: bool,

    /// If `false` (the default), inherit environment variables from the
    /// current process.
    pub clear_env: bool,

    /// Add or update environment variables in the child process.
    pub env: HashMap<OsString, OsString>,
}

impl Command {
    /// Make a new Command with the given program.
    ///
    /// All other fields are set to the defaults.
    pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
        Command {
            program: program.as_ref().into(),
            ..Default::default()
        }
    }

    /// Make a new Command with the given program and args.
    ///
    /// All other fields are set to the defaults.
    pub fn with_args<I, S1, S2>(program: S1, args: I) -> Command
    where
        S1: AsRef<OsStr>,
        S2: AsRef<OsStr>,
        I: IntoIterator<Item = S2>,
    {
        Command {
            program: program.as_ref().into(),
            args: args.into_iter().map(|arg| arg.as_ref().into()).collect(),
            ..Default::default()
        }
    }

    /// Append a single argument.
    pub fn add_arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
        self.args.push(arg.as_ref().into());
        self
    }

    /// Append two arguments.
    ///
    /// This is equivalent to calling `add_arg` twice; it is for the
    /// common case where the arguments have different types, e.g. a
    /// literal string for the first argument and a `Path` for the
    /// second argument.
    pub fn add_arg_pair<S1, S2>(&mut self, arg1: S1, arg2: S2) -> &mut Self
    where
        S1: AsRef<OsStr>,
        S2: AsRef<OsStr>,
    {
        self.add_arg(arg1);
        self.add_arg(arg2);
        self
    }

    /// Append multiple arguments.
    pub fn add_args<I, S>(&mut self, args: I) -> &mut Self
    where
        S: AsRef<OsStr>,
        I: IntoIterator<Item = S>,
    {
        for arg in args {
            self.add_arg(arg);
        }
        self
    }

    /// Set `capture` to `true`.
    pub fn enable_capture(&mut self) -> &mut Self {
        self.capture = true;
        self
    }

    /// Set `combine_output` to `true`.
    pub fn combine_output(&mut self) -> &mut Self {
        self.combine_output = true;
        self
    }

    /// Set the directory from which to run the program.
    pub fn set_dir<S: AsRef<OsStr>>(&mut self, dir: S) -> &mut Self {
        self.dir = Some(dir.as_ref().into());
        self
    }

    /// Set `check` to `false`.
    pub fn disable_check(&mut self) -> &mut Self {
        self.check = false;
        self
    }

    /// Run the command.
    ///
    /// If `capture` is `true`, the command's output (stdout and
    /// stderr) is returned along with the status. If not, the stdout
    /// and stderr are empty.
    ///
    /// If the command fails to start an error is returned. If check
    /// is set, an error is also returned if the command exits
    /// non-zero or due to a signal.
    ///
    /// If `log_command` is `true` then the command line is logged
    /// before running it. If the command fails the error is not
    /// logged or printed, but the resulting error type implements
    /// `Display` and can be used for this purpose.
    pub fn run(&self) -> Result<Output, Error> {
        let cmd_str = self.command_line_lossy();
        if self.log_command {
            match self.log_to {
                LogTo::Stdout => println!("{}", cmd_str),

                #[cfg(feature = "logging")]
                LogTo::Log => log::info!("{}", cmd_str),
            }
        }

        let mut cmd: process::Command = self.into();
        let out = if self.capture {
            if self.combine_output {
                combine_output(cmd).into_run_error(self)?
            } else {
                cmd.output().into_run_error(self)?.into()
            }
        } else {
            let status = cmd.status().into_run_error(self)?;
            Output {
                stdout: Vec::new(),
                stderr: Vec::new(),
                status,
            }
        };
        if self.check && !out.status.success() {
            if self.capture && self.log_output_on_error {
                let mut msg =
                    format!("command '{}' failed: {}", cmd_str, out.status);
                if self.combine_output {
                    msg = format!(
                        "{}\noutput:\n{}",
                        msg,
                        out.stdout_string_lossy()
                    );
                } else {
                    msg = format!(
                        "{}\nstdout:\n{}\nstderr:\n{}",
                        msg,
                        out.stdout_string_lossy(),
                        out.stderr_string_lossy()
                    );
                }
                match self.log_to {
                    LogTo::Stdout => println!("{}", msg),

                    #[cfg(feature = "logging")]
                    LogTo::Log => log::error!("{}", msg),
                }
            }

            return Err(Error {
                command: self.clone(),
                kind: ErrorKind::Exit(out.status),
            });
        }
        Ok(out)
    }

    /// Format as a space-separated command line.
    ///
    /// The program path and the arguments are converted to strings
    /// with [`String::from_utf8_lossy`].
    ///
    /// If any component contains characters that are not ASCII
    /// alphanumeric or in the set `/-,:.=`, the component is
    /// quoted with `'` (single quotes). This is both too aggressive
    /// (unnecessarily quoting things that don't need to be quoted)
    /// and incorrect (e.g. a single quote will itself be quoted with
    /// a single quote). This method is mostly intended for logging
    /// though, and it should work reasonably well for that.
    ///
    /// [`String::from_utf8_lossy`]: https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_lossy
    pub fn command_line_lossy(&self) -> String {
        fn convert_word<S: AsRef<OsStr>>(word: S) -> String {
            fn char_requires_quoting(c: char) -> bool {
                if c.is_ascii_alphanumeric() {
                    return false;
                }
                let allowed_chars = "/-,:.=";
                !allowed_chars.contains(c)
            }

            let s =
                String::from_utf8_lossy(word.as_ref().as_bytes()).to_string();
            if s.chars().any(char_requires_quoting) {
                format!("'{}'", s)
            } else {
                s
            }
        }

        let mut out = convert_word(&self.program);
        for arg in &self.args {
            out.push(' ');
            out.push_str(&convert_word(arg));
        }
        out
    }
}

impl Default for Command {
    fn default() -> Self {
        Command {
            program: PathBuf::new(),
            args: Vec::new(),
            dir: None,
            log_to: LogTo::Stdout,
            log_command: true,
            log_output_on_error: false,
            check: true,
            capture: false,
            combine_output: false,
            clear_env: false,
            env: HashMap::new(),
        }
    }
}

impl From<&Command> for process::Command {
    fn from(cmd: &Command) -> Self {
        let mut out = process::Command::new(&cmd.program);
        out.args(&cmd.args);
        if let Some(dir) = &cmd.dir {
            out.current_dir(dir);
        }
        if cmd.clear_env {
            out.env_clear();
        }
        out.envs(&cmd.env);
        out
    }
}