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
// Copyright (c) 2016 vergen developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Defines the `CommandExt` type.
//!
//! `CommandExt` wraps `Command` and enhances it.
//!
//! A `CommandExt` is built similar to a `Command`. Supply the command name, add
//! args, set enviroment variables, etc. The `exec` function takes a closure
//! that executes the command and returns the given result `T`.
//!
//! # Examples
//!
//! ```rust
//! use commandext::{CommandExt,to_procout};
//!
//! let mut cmd = CommandExt::new("echo");
//! cmd.env("DEBUG", "true");
//! cmd.arg("test");
//!
//! let output = cmd.exec(to_procout());
//! ```
//!
//! ```rust
//! // Execute "echo 'Testing Spawn'" via spawn and verify the exit code was 0.
//! // As a side effect, you would see 'Testing Spawn' on stdout.
//! use commandext::{CommandExt,to_res};
//!
//! let res = CommandExt::new("echo").arg("Testing Spawn").exec(to_res());
//!
//! assert_eq!(Ok(0), res);
//! ```
//!
//! ```rust
//! // Exeute "echo test" via output and verify the output is indeed "test\n".
//! // In this case there is nothing on stdout.  The output is consumed here.
//! extern crate sodium_sys;
//! extern crate commandext;
//!
//! use commandext::{CommandExt,to_procout};
//! use sodium_sys::crypto::utils::secmem;
//!
//! fn main() {
//!     let cmd = CommandExt::new("echo").arg("test").exec(to_procout());
//!     let output = cmd.unwrap();
//!
//!     assert_eq!(secmem::memcmp(&[116, 101, 115, 116, 10], &output.stdout[..]), 0);
//! }
//! ```
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", deny(clippy, clippy_pedantic))]
#![deny(missing_docs)]
#[cfg(test)]
extern crate sodium_sys;

#[cfg(windows)]
use std::borrow::BorrowMut;
use std::cell::RefCell;
use std::io;
use std::path::Path;
use std::process::{Child, Command, Output, Stdio};

/// Extends `std::io::process::Command`.
#[cfg(unix)]
pub struct CommandExt {
    /// The command to execute.
    cmd: RefCell<Command>,
    /// If true, show a header containg the command to be executed.
    header: bool,
}

/// Extends `std::io::process::Command`.
#[cfg(windows)]
pub struct CommandExt {
    /// The command to execute.
    cmd: RefCell<Command>,
    /// The sh -c args string.
    shargs: String,
    /// If true, show a header containg the command to be executed.
    header: bool,
}

/// Surround a message with 80 # character lines.
///
/// <pre>
/// ################################################################################
///   msg
/// ################################################################################
/// </pre>
///
pub fn header(msg: &str) {
    println!("{:#<80}", "#");
    println!("{}", msg);
    println!("{:#<80}", "#");
}

#[cfg(unix)]
fn build_command(cmd: &str) -> Command {
    Command::new(cmd)
}

#[cfg(windows)]
fn build_command(_: &str) -> Command {
    let mut new_cmd = Command::new("sh");
    new_cmd.arg("-c");
    new_cmd
}

/// Generate a closure that returns a Output from the given command.
pub fn to_procout() -> fn(cmd: &mut Command) -> io::Result<Output> {
    fn blah(cmd: &mut Command) -> io::Result<Output> {
        cmd.output()
    };
    blah
}

/// Generate a closure that returns a Child from the given command.
pub fn to_proc() -> fn(cmd: &mut Command) -> io::Result<Child> {
    fn blah(cmd: &mut Command) -> io::Result<Child> {
        cmd.spawn()
    };
    blah
}

/// Generate a closure that returns a Result with the exit code of the process.
///
/// # Return Values
/// * `Ok(0)` - success
/// * `Err(x)` - failure
pub fn to_res() -> fn(cmd: &mut Command) -> Result<i32, i32> {
    fn blah(cmd: &mut Command) -> Result<i32, i32> {
        cmd.stdout(Stdio::inherit());
        cmd.stderr(Stdio::inherit());

        match cmd.spawn() {
            Ok(mut p) => {
                match p.wait() {
                    Ok(status) => {
                        match status.code() {
                            Some(code) => {
                                if code == 0 {
                                    Ok(code)
                                } else {
                                    Err(code)
                                }
                            }
                            None => Err(1),
                        }
                    }
                    Err(_) => Err(1),
                }
            }
            Err(e) => panic!("Failed to execute: {}", e),
        }
    };
    blah
}

impl CommandExt {
    /// Create a new CommandExt.
    ///
    /// # Arguments
    ///
    /// * cmd - The command to use, i.e. "echo".
    /// * exec - The Executable to use when executing the command.
    #[cfg(unix)]
    pub fn new(cmd: &str) -> CommandExt {
        CommandExt {
            cmd: RefCell::new(build_command(cmd)),
            header: false,
        }
    }

    /// Create a new CommandExt.
    ///
    /// # Arguments
    /// * cmd - The command to use, i.e. "echo".
    /// * exec - The Executable to use when executing the command.
    ///
    /// # Note
    /// On Windows, the cmd is built as "sh -c", and the cmd is added
    /// to the shargs string.  When the command is exeuted, this results
    /// in "sh -c 'shargs'".
    #[cfg(windows)]
    pub fn new(cmd: &str) -> CommandExt {
        CommandExt {
            cmd: RefCell::new(build_command(cmd)),
            shargs: cmd.to_string(),
            header: false,
        }
    }

    /// Set the working directory for the command.
    ///
    /// # Arguments
    /// * `wd` - The working directory for the command execution.
    pub fn wd(&mut self, wd: &Path) -> &mut CommandExt {
        self.cmd.borrow_mut().current_dir(wd);
        self
    }

    /// Set the header boolean.
    ///
    /// # Arguments
    /// * show_header - true, a header showing what will be executed is
    /// printed on stdout. Otherwise, no header is printed.
    pub fn header(&mut self, show_header: bool) -> &mut CommandExt {
        self.header = show_header;
        self
    }

    /// Add an argument to the command.
    ///
    /// # Arguments
    /// * arg - The argument to add to the command.
    #[cfg(unix)]
    pub fn arg(&mut self, arg: &str) -> &mut CommandExt {
        self.cmd.borrow_mut().arg(arg);
        self
    }

    /// Add an argument to the command.
    ///
    /// # Arguments
    /// * arg - The argument to add to the command.
    ///
    /// # Note
    /// On Windows, the argument is appended to the shargs value.
    #[cfg(windows)]
    pub fn arg(&mut self, arg: &str) -> &mut CommandExt {
        self.shargs.push_str(" ");
        self.shargs.push_str(arg);
        self
    }

    /// Add arguments to the command.
    ///
    /// # Arguments
    /// * `args` - A vector of argments to add to the command.
    #[cfg(unix)]
    pub fn args(&mut self, args: &[&str]) -> &mut CommandExt {
        self.cmd.borrow_mut().args(args);
        self
    }

    /// Add arguments to the command.
    ///
    /// # Arguments
    /// * `args` - A vector of argments to add to the command.
    ///
    /// # Note
    /// On Windows, the arguments are appended to the shargs value.
    #[cfg(windows)]
    pub fn args(&mut self, args: &[&str]) -> &mut CommandExt {
        for arg in args.iter() {
            self.shargs.push_str(" ");
            self.shargs.push_str(*arg);
        }
        self
    }

    /// Set the command environment.
    ///
    /// # Arguments
    /// * `key` - The key for the variable.
    /// * `value` - The value for the variable.
    pub fn env(&mut self, key: &str, val: &str) -> &mut CommandExt {
        self.cmd.borrow_mut().env(key, val);
        self
    }

    /// Execute the Command, returning result 'T'
    ///
    /// # Arguments
    /// * `execfn` - A closure taking a Command, executes it via output or spawn
    /// and returns result type `T`.
    #[cfg(unix)]
    pub fn exec<T>(&mut self, execfn: fn(cmd: &mut Command) -> T) -> T {
        let mut cmd = self.cmd.borrow_mut();
        if self.header {
            header(&format!("  Executing '{:?}'", cmd)[..]);
        }
        execfn(&mut cmd)
    }

    /// Execute the Command, returning result 'T'
    ///
    /// # Arguments
    /// * `execfn` - A closure taking a Command, executes it via output or spawn
    /// and returns result type `T`.
    #[cfg(windows)]
    pub fn exec<T>(&mut self, execfn: fn(cmd: &mut Command) -> T) -> T {
        let ref shargs = self.shargs;
        let mut new_cmd = self.cmd.borrow_mut();
        new_cmd.arg(shargs);

        if self.header {
            header(&format!("  Executing '{:?}'", new_cmd)[..]);
        }
        execfn(&mut new_cmd)
    }
}

#[cfg(test)]
/// Tests
mod test {
    use sodium_sys::crypto::utils::secmem;
    use super::{to_procout, to_res};
    use super::CommandExt;

    #[test]
    fn test_command_ext() {
        let cmd = CommandExt::new("echo").arg("test").exec(to_procout());
        let output = match cmd {
            Ok(o) => o,
            Err(e) => panic!("{:?}", e),
        };

        if cfg!(unix) {
            assert_eq!(secmem::memcmp(&[116, 101, 115, 116, 10], &output.stdout[..]),
                       0);
        } else if cfg!(windows) {
            assert_eq!(secmem::memcmp(&[116, 101, 115, 116, 10], &output.stdout[..]),
                       0);
        }
        assert!(output.stderr.is_empty());
        assert!(output.status.success());
    }

    #[test]
    fn test_output_env() {
        let cmd = CommandExt::new("env").env("TST", "1").exec(to_procout());
        let output = match cmd {
            Ok(o) => o,
            Err(e) => panic!("{:?}", e),
        };

        assert!(output.stderr.is_empty());
        assert!(output.status.success());
    }

    #[test]
    fn test_spawn() {
        let res = CommandExt::new("echo").arg("Testing Spawn").exec(to_res());
        assert_eq!(Ok(0), res);
    }

    #[test]
    fn test_spawn_header() {
        let mut cmd = CommandExt::new("echo");
        cmd.arg("Testing Spawn");
        cmd.header(true);
        let res = cmd.exec(to_res());
        assert_eq!(Ok(0), res);
    }

    #[test]
    fn test_spawn_env() {
        let cmd = CommandExt::new("env").env("TST", "1").exec(to_res());
        assert_eq!(Ok(0), cmd);
    }
}