buildable 0.0.2

Buildable trait definition and utilities helpful in build lifecycles
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! 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 buildable::command::{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 buildable::command::{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.
//! use buildable::command::{CommandExt,to_procout};
//!
//! let cmd = CommandExt::new("echo").arg("test").exec(to_procout());
//! let output = cmd.unwrap();
//!
//! assert_eq!([116, 101, 115, 116, 10], output.output); // "test\n" as [u8]
//! ```
#![experimental]
use std::cmp::{max,min};
use std::io::{Command,IoResult};
use std::io::process::{Process,ProcessExit,ProcessOutput,StdioContainer};
#[cfg(windows)]
use std::os;
use std::str;

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

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

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

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

/// Generate a closure that returns a ProcessOutput from the given command.
#[experimental]
pub fn to_procout<'a>() -> |Command|:'a -> IoResult<ProcessOutput> {
    |cmd| -> IoResult<ProcessOutput> {
        cmd.output()
    }
}

/// Generate a closure that returns a Process from the given command.
#[experimental]
pub fn to_proc<'a>() -> |Command|:'a -> IoResult<Process> {
    |cmd| -> IoResult<Process> {
        cmd.spawn()
    }
}

/// Generate a closure that returns a Result with the exit code of the process.
///
/// # Return Values
/// * `Ok(0)` - success
/// * `Err(x)` - failure
#[experimental]
pub fn to_res<'a>() -> |Command|:'a -> Result<u8,u8> {
    |cmd| -> Result<u8,u8> {
        let ref mut mcmd = cmd.clone();
        mcmd.stdout(StdioContainer::InheritFd(1));
        mcmd.stderr(StdioContainer::InheritFd(2));

        match mcmd.spawn() {
            Ok(mut p)  => match p.wait() {
                Ok(pe) => match pe {
                    ProcessExit::ExitStatus(code) => {
                        if code == 0 {
                            Ok(code as u8)
                        } else {
                            Err(code as u8)
                        }
                    },
                    ProcessExit::ExitSignal(code) => Err(code as u8),
                },
                Err(_) => Err(1),
            },
            Err(e)     => panic!("Failed to execute: {} {}", e.kind, e.desc),
        }
    }
}

#[experimental]
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)]
    #[experimental]
    pub fn new(cmd: &str) -> CommandExt {
        CommandExt{
            cmd: 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)]
    #[experimental]
    pub fn new(cmd: &str) -> CommandExt {
        CommandExt{
            cmd: 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.
    #[experimental]
    pub fn wd(&mut self, wd: &Path) -> &mut CommandExt {
        self.cmd.cwd(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.
    #[experimental]
    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)]
    #[experimental]
    pub fn arg(&mut self, arg: &str) -> &mut CommandExt {
        self.cmd.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)]
    #[experimental]
    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)]
    #[experimental]
    pub fn args(&mut self, args: &[&str]) -> &mut CommandExt {
        self.cmd.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)]
    #[experimental]
    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.
    #[experimental]
    pub fn env(&mut self, key: &str, val: &str) -> &mut CommandExt {
        self.cmd.env(key, val);
        self
    }

    /// Set the command environment.
    ///
    /// # Arguments
    /// * `env` - A vector of (k,v) enviromnent tuples, i.e [(DEBUG=true)].
    #[experimental]
    pub fn env_set_all(&mut self, env: &[(&str,&str)]) -> &mut CommandExt {
        self.cmd.env_set_all(env);
        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)]
    #[experimental]
    pub fn exec<T>(&self, execfn: |Command| -> T) -> T {
        if self.header {
            header(format!("  Executing '{}'", self.cmd).as_slice());
        }
        (execfn)(self.cmd.clone())
    }

    /// 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)]
    #[experimental]
    pub fn exec<T>(&self, execfn: |Command| -> T) -> T {
        let ref shargs = self.shargs;
        let mut new_cmd = self.cmd.clone();
        new_cmd.arg(shargs);

        if self.header {
            header(format!("  Executing '{}'", new_cmd).as_slice());
        }
        (execfn)(new_cmd)
    }
}

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

/// The number of available cpu cores.
#[experimental]
pub fn nproc() -> int {
    match CommandExt::new("nproc").exec(to_procout()) {
        Ok(p) => {
            match str::from_utf8(p.output.as_slice()).unwrap().trim().parse() {
                Some(i) => i,
                None    => panic!("unable to cast nproc output!"),
            }
        },
        Err(e) => panic!("Failed to execute nproc: {}", e),
    }
}

/// The number of usable cores `min(4, max(1, (nproc - 1)))`.
///
/// This returns a number between 1 and 4.
#[experimental]
pub fn usable_cores() -> int {
    let usable = nproc() - 1;
    min(4, max(1, usable))
}

/// The machine hardware value as given by "uname -m"
#[cfg(unix)]
#[experimental]
pub fn mh() -> String {
    match CommandExt::new("uname").arg("-m").exec(to_procout()) {
        Ok(o)  => {
            let mut res =  String::from_utf8_lossy(o.output.as_slice());
            res.to_mut().trim().to_string()
        },
        Err(e) => panic!("Failed to execute uname: {}", e),
    }
}

/// The machine hardware value as given in the PROCESSOR_ARCHITECTURE and
/// PROCESSOR_ARCHITEW6432 environment variables.
#[cfg(windows)]
#[experimental]
pub fn mh() -> String {
    let pa = "PROCESSOR_ARCHITECTURE";
    let val = match os::getenv(pa) {
        Some(v) => v,
        None    => "".to_string(),
    };

    if !(val == "AMD64") {
        let paw = "PROCESSOR_ARCHITEW6432";
        let val1 = match os::getenv(paw) {
            Some(v) => v,
            None => "".to_string(),
        };

        if val1 == "AMD64" {
            val1
        } else {
            "x86".to_string()
        }
    } else {
        val
    }
}

/// Is the current machine hardware 64-bit?
#[experimental]
pub fn is_64() -> bool {
    cfg!(target_word_size = "64")
}

/// Is the current machine hardware 32-bit?
#[experimental]
pub fn is_32() -> bool {
   cfg!(target_word_size = "32")
}

#[cfg(test)]
/// Tests
mod test {
    use super::{mh,nproc,to_procout,to_res};
    use super::is_64;
    use super::is_32;
    use super::CommandExt;
    use std::num::SignedInt;

    #[test]
    fn test_nproc() {
        assert!(SignedInt::is_positive(nproc()));
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn test_mh() {
        assert_eq!(mh(), "x86_64");
    }

    #[test]
    #[cfg(target_arch = "x86")]
    fn test_mh() {
        assert_eq!(mh(), "i686");
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn test_is_64() {
        assert!(is_64());
        assert!(!is_32());
    }

    #[test]
    #[cfg(target_arch = "x86")]
    fn test_is_32() {
        assert!(is_32());
        assert!(!is_64());
    }

    #[test]
    fn test_command_ext() {
        let cmd = CommandExt::new("echo").arg("test").exec(to_procout());
        let output = cmd.unwrap();

        if cfg!(unix) {
            assert_eq!([116, 101, 115, 116, 10], output.output);
        } else if cfg!(windows) {
            assert_eq!(vec![116, 101, 115, 116, 10], output.output);
        }
        assert!(output.error.is_empty());
        assert!(output.status.success());
    }

    #[test]
    fn test_output_env() {
        let cmd = CommandExt::new("env").env("TST", "1").exec(to_procout());
        let output = cmd.unwrap();

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

    #[test]
    fn test_output_env_set_all() {
        let env = [("TST", "1"),("USR","2")];
        let cmd = CommandExt::new("env").env_set_all(&env).exec(to_procout());
        let output = cmd.unwrap();

        // TST=1\nUSR=2\n
        if cfg!(unix) {
            // Can only check length, order is not guaranteed.
            // Note: on Windows env_set_all isn't replacing env, just adding to
            // it.
            assert_eq!(12,output.output.len());
        }
        assert!(output.error.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);
    }

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