cargo_rub 0.0.3

Rust Builder for Cargo
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Rust Builder for [Cargo](https://github.com/rust-lang/cargo).
//!
//! This crate is intended for use with
//! [rub](https://github.com/rust-builder/rub).
//!
//! If you don't have `rub` installed, visit https://github.com/rust-builder/rub
//! for installation instructions.
//!
//! # Rub Options
//! <pre>
//! $ rub cargo --help
//! cargo - Rust Builder
//!
//! Usage:
//!     rub cargo [options] [&lt;lifecycle&gt;...]
//!     rub cargo (-h | --help)
//!     rub cargo --version
//!
//! Options:
//!     -d --dir &lt;dir&gt;        Set the projects directory.
//!     -b --branch &lt;branch&gt;  Set the build branch. [default: master]
//!     -t --enable-test      Enable tests.
//!     -p --prefix &lt;prefix&gt;  Set the installation prefix.
//!     -u --url &lt;url&gt;        Set the SCM URL.
//!     -h --help             Show this usage.
//!     --force-configure     Force the configure lifecycle to run.
//!     --disable-optimize    Disable compile-time optimization.
//!     --version             Show cargo-rub version.
//! </pre>
//!
//! # Examples
//! ```rust
//! # extern crate buildable; extern crate cargo_rub; fn main() {
//! use buildable::Buildable;
//! use cargo_rub::CargoRub;
//!
//! // To run lifecycle methods outside of rub...
//! let mut cr = CargoRub::new();
//! let b = Buildable::new(&mut cr, &vec!["rub".to_string(),
//!                                       "cargo".to_string(),
//!                                       "--version".to_string()]);
//! assert_eq!(Ok(0), b.version());
//! # }
//! ```
#![experimental]
#![allow(unstable)]
extern crate buildable;
extern crate commandext;
extern crate docopt;
extern crate "rustc-serialize" as rustc_serialize;
extern crate scm;
extern crate utils;

use buildable::{Buildable,BuildConfig,LifeCycle};
use commandext::{CommandExt,to_res};
use utils::usable_cores;
use utils::empty::to_opt;
use scm::git::GitCommand;
use docopt::Docopt;
use std::default::Default;
use std::io::fs;
use std::io::fs::PathExtensions;

static USAGE: &'static str = "cargo - Rust Builder

Usage:
    rub cargo [options] [<lifecycle>...]
    rub cargo (-h | --help)
    rub cargo --version

Options:
    -d --dir <dir>        Set the projects directory.
    -b --branch <branch>  Set the build branch. [default: master]
    -t --enable-test      Enable tests.
    -p --prefix <prefix>  Set the installation prefix.
    -u --url <url>        Set the SCM URL.
    -h --help             Show this usage.
    --force-configure     Force the configure lifecycle to run.
    --disable-optimize    Disable compile-time optimization.
    --version             Show cargo-rub version.";

include!(concat!(env!("OUT_DIR"), "/version.rs"));

#[derive(RustcDecodable)]
struct Args {
    flag_dir: String,
    flag_branch: String,
    flag_enable_test: bool,
    flag_prefix: String,
    flag_url: String,
    flag_force_configure: bool,
    flag_disable_optimize: bool,
    flag_version: bool,
    flag_help: bool,
    arg_lifecycle: Vec<String>,
}

fn install_deps(wd: &Path) -> Result<u8,u8> {
    let mut cmd = CommandExt::new(".travis.install.deps.sh");
    cmd.wd(wd);
    cmd.header(true);

    if cfg!(target_word_size = "64") {
        cmd.env("BITS","64");
    } else if cfg!(target_word_size = "32") {
        cmd.env("BITS","32");
    }

    cmd.exec(to_res())
}

#[cfg(target_os = "linux")]
fn os_clean(wd: &Path) -> Result<u8,u8> {
    let mut cmd = CommandExt::new("sudo");
    cmd.wd(wd);
    cmd.header(true);
    cmd.args(&["make", "clean"]);
    cmd.exec(to_res())
}

#[cfg(not(target_os = "linux"))]
fn os_clean(wd: &Path) -> Result<u8,u8> {
    let mut cmd = CommandExt::new("make");
    cmd.wd(wd);
    cmd.header(true);
    cmd.args(&["clean"]);
    cmd.exec(to_res())
}

#[cfg(target_os = "linux")]
fn os_install(wd: &Path) -> Result<u8,u8> {
    let mut jobs = String::from_str("-j");
    jobs.push_str(usable_cores().to_string().as_slice());
    let mut cmd = CommandExt::new("sudo");
    cmd.wd(wd);
    cmd.header(true);
    cmd.args(&["make", jobs.as_slice(), "install"]);
    cmd.exec(to_res())
}

#[cfg(not(target_os = "linux"))]
fn os_install(wd: &Path) -> Result<u8,u8> {
    let mut jobs = String::from_str("-j");
    jobs.push_str(usable_cores().to_string().as_slice());
    let mut cmd = CommandExt::new("make");
    cmd.wd(wd);
    cmd.header(true);
    cmd.args(&[jobs.as_slice(), "install"]);
    cmd.exec(to_res())
}

/// Cargo specific configuration for the `Buildable` lifecycle methods.
#[experimental]
#[derive(Clone,Default)]
pub struct CargoRub {
    config: BuildConfig,
    prefix: String,
    url: String,
    force_config: bool,
    disable_optimize: bool,
}

impl CargoRub {
    /// Create a new default CargoRub.
    pub fn new() -> CargoRub {
        Default::default()
    }
}

impl Buildable for CargoRub {
    /// Update the CargoRub struct after parsing the given args vector.
    ///
    /// Normally, the args vector would be supplied from the command line, but
    /// they can be supplied as in the example below as well.
    ///
    /// # Example
    /// ```rust
    /// # extern crate buildable; extern crate cargo_rub; fn main() {
    /// use buildable::Buildable;
    /// use cargo_rub::CargoRub;
    ///
    /// // To run lifecycle methods outside of rub...
    /// let mut cr = CargoRub::new();
    /// let b = Buildable::new(&mut cr, &vec!["rub".to_string(),
    ///                                       "cargo".to_string()]);
    /// assert_eq!(Ok(0), b.version());
    /// # }
    fn new(&mut self, args: &Vec<String>) -> &mut CargoRub {
        let dargs: Args = Docopt::new(USAGE)
            .and_then(|d| Ok(d.help(false)))
            .and_then(|d| d.argv(args.clone().into_iter()).decode())
            .unwrap_or_else( |e| e.exit());
        self.prefix = dargs.flag_prefix;
        self.url = dargs.flag_url;
        self.force_config = dargs.flag_force_configure;
        self.disable_optimize = dargs.flag_disable_optimize;

        if dargs.flag_version {
            let mut cfg = BuildConfig::new();
            cfg.lifecycle(vec!["version"]);
            self.config = cfg;
        } else if dargs.flag_help {
            let mut cfg = BuildConfig::new();
            cfg.lifecycle(vec!["help"]);
            self.config = cfg;
        } else {
            let mut cfg = BuildConfig::new();

            if to_opt(dargs.flag_dir.as_slice()).is_some() {
                cfg.dir(Path::new(dargs.flag_dir.as_slice()));
            }
            cfg.project("cargo");
            if to_opt(dargs.flag_branch.as_slice()).is_some() {
                cfg.branch(dargs.flag_branch.as_slice());
            }
            cfg.test(dargs.flag_enable_test);

            let lc = dargs.arg_lifecycle;
            if to_opt(lc.clone()).is_some() {
                let mut mylc = Vec::new();
                for lc in lc.iter() {
                    mylc.push(lc.as_slice());
                }
                cfg.lifecycle(mylc);
            }
            self.config = cfg;
        }
        self
    }

    /// Get the `BuildConfig` associated with the `CargoRub`.
    ///
    /// # Example
    /// ```rust
    /// # extern crate buildable; extern crate cargo_rub; fn main() {
    /// use buildable::Buildable;
    /// use cargo_rub::CargoRub;
    ///
    /// // To run lifecycle methods outside of rub...
    /// let mut cr = CargoRub::new();
    /// let b = Buildable::new(&mut cr, &vec!["rub".to_string(),
    ///                                       "cargo".to_string()]);
    /// let bc = b.get_bc();
    /// assert_eq!("cargo", bc.get_project());
    /// # }
    fn get_bc(&self) -> &BuildConfig {
        &self.config
    }

    /// No lifecycle reorder is necessary for Cargo.
    fn reorder<'a>(&self, lc: &'a mut Vec<LifeCycle>) -> &'a mut Vec<LifeCycle> {
        lc
    }

    /// Check for cargo dependencies.
    ///
    /// TODO: Implement
    fn chkdeps(&self) -> Result<u8,u8> {
        Ok(0)
    }

    /// Peform the git operations necessary to get the project directory ready
    /// for the rest of the build lifecycle operations.
    ///
    /// # Notes
    /// * If the project directory doesn't exist, `cargo` will be cloned from
    /// github automatically.  You can adjust where is is cloned from by using
    /// the `--url` flag at the command line.
    /// * If the project does exist, the requested branch is updated via
    /// `update_branch` to prepare for the rest of the build cycle.
    fn scm(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        let base = Path::new(cfg.get_dir());
        let u = if self.url.is_empty() {
            "git@github.com:rust-lang/cargo.git"
        } else {
            self.url.as_slice()
        };

        let mut cmd = GitCommand::new();
        cmd.wd(base.clone());
        cmd.verbose(true);

        if !base.join(cfg.get_project()).exists() {
            cmd.clone(Some(vec!["--recursive", u]), to_res())
        } else {
            Ok(0)
        }.and({
            cmd.wd(base.join(cfg.get_project()));
            cmd.update_branch(self.config.get_branch())
        })
    }

    /// Run `make clean` in the project directory.
    ///
    /// # Notes
    /// * This will fail if `configure` hasn't be run at least once, because
    /// no `Makefile` will exist.
    fn clean(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        os_clean(&Path::new(cfg.get_dir()).join(cfg.get_project()))
    }

    /// Run `configure` in the project directory.
    ///
    /// # Examples
    /// <pre>
    /// rub cargo --force-configure
    /// rub cargo --prefix=/usr/local --disable-optimize
    /// rub cargo -b auto
    /// </pre>
    ///
    /// # Notes
    /// * If a rustc hasn't been installed locally to the project directory or
    /// `--force-config` was supplied then `.travis.install.deps.sh` will be run
    /// to do so.
    /// * If a `Makefile` doesn't exist or `--force-config` was supplied then
    /// configure will run.  Otherwise, it will be skipped.
    /// * The default `configure` command is setup as:
    /// ``
    /// configure --prefix=/opt/cargo-<branch> --enable-optimize --local-rust-root=`pwd`/rustc
    /// ``
    /// * You can adjust the `prefix` by using the `--prefix <x>` flag or the
    /// `--branch X` flag.
    /// * You can remove the `--enable-optimize` config flag by using the
    /// `--disable-optimize` flag.
    fn configure(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        let wd = Path::new(cfg.get_dir()).join(cfg.get_project());

        let res = if !wd.join("rustc").exists() || self.force_config {
            install_deps(&wd)
        } else {
            Ok(0)
        };

        if res.is_ok() && (!wd.join("Makefile").exists()
                           || wd.join("dirty").exists() || self.force_config) {
            fs::unlink(&Path::new(wd.join("dirty"))).unwrap_or_else(|why| {
                println!("{}", why);
            });
            let wd = Path::new(self.config.get_dir())
                .join(self.config.get_project());
            let mut cmd = CommandExt::new("configure");
            cmd.wd(&wd);
            cmd.header(true);

            let mut prefix = String::from_str(" --prefix=");

            if self.prefix.is_empty() {
                prefix.push_str("/opt/cargo-");
                prefix.push_str(self.config.get_branch());
            } else {
                prefix.push_str(self.prefix.as_slice());
            }

            cmd.arg(prefix.as_slice());
            cmd.arg("--local-rust-root=`pwd`/rustc");

            if !self.disable_optimize {
                cmd.arg("--enable-optimize");
            }

            cmd.exec(to_res())
        } else {
            res
        }
    }

    /// Run 'make' in the project directory.
    ///
    /// Runs `make -j<X>` where X is the number of usable cores (nproc - 1).
    fn make(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        let mut jobs = String::from_str("-j");
        jobs.push_str(usable_cores().to_string().as_slice());
        let wd = Path::new(cfg.get_dir()).join(cfg.get_project());
        let mut cmd = CommandExt::new("make");
        cmd.wd(&wd);
        cmd.arg(jobs.as_slice());
        cmd.header(true);
        cmd.exec(to_res())
    }

    /// Run 'make test' in the project directory.
    ///
    /// Runs `make -j<X> test` where X is the number of usable cores
    /// (nproc - 1).
    fn test(&self) -> Result<u8,u8> {
        if self.config.get_test() {
            let cfg = &self.config;
            let mut jobs = String::from_str("-j");
            jobs.push_str(usable_cores().to_string().as_slice());
            let wd = Path::new(cfg.get_dir()).join(cfg.get_project());
            let mut cmd = CommandExt::new("make");
            cmd.wd(&wd);
            cmd.args(&[jobs.as_slice(), "test"]);
            cmd.header(true);
            cmd.exec(to_res())
        } else {
            Ok(0)
        }
    }

    /// Run 'make install' or 'sudo make install' in the project directory.
    ///
    /// Runs `make -j<X> install` where X is the number of usable cores
    /// (nproc - 1).
    fn install(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        os_install(&Path::new(cfg.get_dir()).join(cfg.get_project()))
    }

    /// Not implemented in this crate.
    fn cleanup(&self) -> Result<u8,u8> {
        Ok(0)
    }

    /// Show the docopt USAGE string on stdout.
    fn help(&self) -> Result<u8,u8> {
        println!("{}", USAGE);
        Ok(0)
    }

    /// Show the crate version on stdout.
    fn version(&self) -> Result<u8,u8> {
        println!("{} {} cargo-rub {}", now(), sha(), branch());
        Ok(0)
    }
}

#[cfg(test)]
mod test {
    use buildable::{Buildable,BuildConfig};
    use super::CargoRub;

    fn check_cr(cr: &CargoRub) {
        assert_eq!(cr.prefix, "");
        assert_eq!(cr.url, "");
        assert!(!cr.force_config);
        assert!(!cr.disable_optimize);
    }

    fn check_bc(bc: &BuildConfig, lc: &Vec<&str>) {
        let mut tdir = env!("HOME").to_string();
        tdir.push_str("/projects");
        assert_eq!(bc.get_lifecycle(), lc);
        assert_eq!(bc.get_dir().as_str().unwrap(), tdir.as_slice());
        assert_eq!(bc.get_project(), "cargo");
        assert_eq!(bc.get_branch(), "master");
        assert!(!bc.get_test());
    }

    #[test]
    fn test_new() {
        let cr = CargoRub::new();
        check_cr(&cr);
    }

    #[test]
    fn test_version() {
        let args = vec!["rub".to_string(),
                        "cargo".to_string(),
                        "--version".to_string()];
        let mut cr = CargoRub::new();
        check_cr(&cr);
        let b = Buildable::new(&mut cr, &args);
        let bc = b.get_bc();
        assert_eq!(bc.get_lifecycle(), &vec!["version"]);
        assert_eq!(b.version(), Ok(0))
    }

    #[test]
    fn test_help() {
        let args = vec!["rub".to_string(),
                        "cargo".to_string(),
                        "-h".to_string()];
        let mut cr = CargoRub::new();
        check_cr(&cr);
        let b = Buildable::new(&mut cr, &args);
        let bc = b.get_bc();
        assert_eq!(bc.get_lifecycle(), &vec!["help"]);
        assert_eq!(b.help(), Ok(0))
    }

    #[test]
    fn test_base() {
        let args = vec!["rub".to_string(),
                        "cargo".to_string()];
        let mut cr = CargoRub::new();
        check_cr(&cr);
        let b = Buildable::new(&mut cr, &args);
        let bc = b.get_bc();
        check_bc(bc, &vec!["most"]);
        assert_eq!(b.version(), Ok(0));
    }

    #[test]
    fn test_scm() {
        let args = vec!["rub".to_string(),
                        "cargo".to_string(),
                        "scm".to_string()];
        let mut cr = CargoRub::new();
        check_cr(&cr);
        let b = Buildable::new(&mut cr, &args);
        let bc = b.get_bc();
        check_bc(bc, &vec!["scm"]);
        assert_eq!(b.version(), Ok(0));
    }

    #[test]
    fn test_all() {
        let args = vec!["rub".to_string(),
                        "cargo".to_string(),
                        "all".to_string()];
        let mut cr = CargoRub::new();
        check_cr(&cr);
        let b = Buildable::new(&mut cr, &args);
        let bc = b.get_bc();
        check_bc(bc, &vec!["all"]);
        assert_eq!(b.version(), Ok(0));
    }
}