v8_rub 0.0.4

Rust Builder for v8
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Rust Builder for [v8](https://github.com/v8/v8-git-mirror).
//!
//! 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 v8 --help
//! v8 - Rust Builder
//!
//! Usage:
//!     rub v8 [options] [&lt;lifecycle&gt;...]
//!     rub v8 (-h | --help)
//!     rub v8 --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.
//!     --pump                Enable distcc pump mode.
//!     --static              Build a statically linked library.
//!     --disable-i18n        Disable i18n support.
//!     --version             Show rust-rub version.
//! </pre>
//!
//! # Examples
//! ```rust
//! # extern crate buildable; extern crate v8_rub; fn main() {
//! use buildable::Buildable;
//! use v8_rub::V8Rub;
//!
//! // To run lifecycle methods outside of rub...
//! let mut vr = V8Rub::new();
//! let b = Buildable::new(&mut vr, &vec!["rub".to_string(),
//!                                       "v8".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,header,to_res};
use scm::git::GitCommand;
use utils::{is_32,is_64,usable_cores};
use utils::empty::to_opt;
use docopt::Docopt;
use std::default::Default;
use std::io;
use std::io::fs;
use std::io::fs::PathExtensions;
use std::os;

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

Usage:
    rub v8 [options] [<lifecycle>...]
    rub v8 (-h | --help)
    rub v8 --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.
    --static              Build a statically linked library.
    --disable-i18n        Disable i18n support.
    --version             Show rust-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_static: bool,
    flag_disable_i18n: bool,
    flag_version: bool,
    flag_help: bool,
    arg_lifecycle: Vec<String>,
}

#[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 = "windows")]
fn update_depot_tools(dir: &Path) -> Result<u8,u8> {
    let mut cmd = CommandExt::new("update_depot_tools.bat");
    cmd.wd(dir);
    cmd.header(true);
    cmd.exec(to_res())
}

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

/// v8 specific configuration for the `Buildable` lifecycle methods.
#[experimental]
#[derive(Clone,Default)]
pub struct V8Rub {
    config: BuildConfig,
    prefix: String,
    url: String,
    stat: bool,
    disable_i18n: bool,
    version: bool,
}

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

impl Buildable for V8Rub {
    /// Update the V8Rub 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 v8_rub; fn main() {
    /// use buildable::Buildable;
    /// use v8_rub::V8Rub;
    ///
    /// // To run lifecycle methods outside of rub...
    /// let mut vr = V8Rub::new();
    /// let b = Buildable::new(&mut vr, &vec!["rub".to_string(),
    ///                                       "v8".to_string()]);
    /// assert_eq!(Ok(0), b.version());
    /// # }
    fn new(&mut self, args: &Vec<String>) -> &mut V8Rub {
        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.stat = dargs.flag_static;
        self.disable_i18n = dargs.flag_disable_i18n;

        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("v8");
            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 `V8Rub`.
    ///
    /// # Example
    /// ```rust
    /// # extern crate buildable; extern crate v8_rub; fn main() {
    /// use buildable::Buildable;
    /// use v8_rub::V8Rub;
    ///
    /// // To run lifecycle methods outside of rub...
    /// let mut vr = V8Rub::new();
    /// let b = Buildable::new(&mut vr, &vec!["rub".to_string(),
    ///                                       "v8".to_string()]);
    /// let bc = b.get_bc();
    /// assert_eq!("v8", bc.get_project());
    /// # }
    fn get_bc(&self) -> &BuildConfig {
        &self.config
    }

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

    /// Check for v8 dependencies.
    ///
    /// Note these aren't complete yet.
    ///
    /// # Dependencies
    /// 1. depot_tools
    fn chkdeps(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        let base = Path::new(cfg.get_dir());
        let durl = "https://chromium.googlesource.com/chromium/tools/depot_tools.git";
        let mut cmd = GitCommand::new();
        cmd.wd(base.clone());
        cmd.verbose(true);

        if !base.join("depot_tools").exists() {
            let depot_path = base.join("depot_tools");
            println!("depot_tools will be cloned.");
            println!("Please add {:?} to your PATH",
                     depot_path.as_str());
            cmd.wd(base);
            cmd.clone(Some(vec![durl]), to_res())
                .and(update_depot_tools(&depot_path))
                .and(Err(1))
        } else {
            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, `v8` 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());

        if !base.join(cfg.get_project()).exists() {
            let mut fetch = CommandExt::new("fetch");
            fetch.wd(&base);
            fetch.header(true);
            fetch.arg("v8");
            fetch.exec(to_res()).and({
                let mut cmd = CommandExt::new("gclient");
                cmd.wd(&base);
                cmd.header(true);
                cmd.arg("sync");
                cmd.exec(to_res())})
        } else {
            Ok(0)
        }.and({
            let mut cmd = GitCommand::new();
            cmd.wd(base.clone());
            cmd.verbose(true);
            cmd.wd(base.join(cfg.get_project()));
            cmd.update_branch(self.config.get_branch())
        })
    }

    /// Run `make clean` in the project directory.
    fn clean(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        os_clean(&Path::new(cfg.get_dir()).join(cfg.get_project()))
    }

    /// Run `gclient sync` in the base project directory.
    fn configure(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        let wd = Path::new(cfg.get_dir().join(cfg.get_project()));
        fs::unlink(&Path::new(wd.join("dirty"))).unwrap_or_else(|why| {
            println!("{}", why);
        });
        let mut cmd = CommandExt::new("gclient");
        cmd.wd(&wd);
        cmd.header(true);
        cmd.arg("sync");
        cmd.exec(to_res())
    }

    fn make(&self) -> Result<u8,u8> {
        let cfg = &self.config;
        let wd = Path::new(cfg.get_dir()).join(cfg.get_project());

        if cfg!(windows) {
            let mut mingw_cmd = CommandExt::new("tools/mingw-generate-makefiles.sh");
            mingw_cmd.wd(&wd);
            mingw_cmd.header(true);
            mingw_cmd.exec(to_res()).unwrap();
        }

        let mut jobs = String::from_str("-j");
        jobs.push_str(usable_cores().to_string().as_slice());

        let mut command: Vec<&str> = Vec::new();

        command.push("make");

        if !cfg!(windows) {
            command.push(jobs.as_slice());
        }

        if is_64() {
            if self.config.get_test() {
                command.push("x64.release.check");
            } else {
                command.push("x64.release");
            }
        } else if is_32() {
            if self.config.get_test() {
                command.push("ia32.release.check");
            } else {
                command.push("ia32.release");
            }
        }

        let mut soname = String::from_str("soname_version=");
        soname.push_str(self.config.get_branch());

        if !self.stat {
            command.push("library=shared");
            command.push(soname.as_slice());
        }

        if self.disable_i18n {
            command.push("i18nsupport=off");
        }

        let mut cmd = CommandExt::new(*command.first().unwrap());
        cmd.wd(&wd);
        cmd.header(true);
        cmd.env("CC","ccache gcc");
        cmd.env("CXX", "ccache g++");
        cmd.args(command.tail());
        cmd.exec(to_res())
    }

    fn test(&self) -> Result<u8,u8> {
        Ok(0)
    }

    fn install(&self) -> Result<u8,u8> {
        let wd = Path::new(&self.config.get_dir()).join(&self.config.get_project());
        let mut install_path = if self.prefix.is_empty() {
            Path::new(os::homedir().unwrap().as_str().unwrap()).join("lib")
        } else {
            Path::new(self.prefix.as_slice())
        };

        install_path.push_many(&["v8", self.config.get_branch()]);

        let include_path = install_path.join("include");
        let lib_path = install_path.join("lib");
        let mut libname = String::from_str("libv8.so.");
        libname.push_str(self.config.get_branch());

        fs::mkdir_recursive(&include_path, io::USER_DIR).unwrap();
        fs::mkdir_recursive(&lib_path, io::USER_DIR).unwrap();

        let basedir = Path::new(self.config.get_dir()).join(self.config.get_project());

        let mut res: Result<u8,u8> = Ok(0);

        for entry in fs::walk_dir(&basedir.join("include")).unwrap() {
            if entry.is_dir() {
                let inc = include_path.join(entry.filename_str().unwrap());
                fs::mkdir_recursive(&inc, io::USER_DIR).unwrap();
            } else {
                let base_inc = &basedir.join("include");
                let rel = entry.path_relative_from(base_inc).unwrap();
                let dest_path = include_path.join(rel);
                let dest = dest_path.as_str().unwrap();
                let src = entry.as_str().unwrap();

                let mut cmd = CommandExt::new("cp");
                cmd.wd(&wd);
                cmd.header(true);
                cmd.args(&["-puv", src, dest]);

                match cmd.exec(to_res()) {
                    Ok(_)  => { ; },
                    Err(e) => { res = Err(e); break; },
                }
            }
        }

        if res.is_ok() {
            let mut libs = Vec::<&str>::new();
            libs.push(libname.as_slice());
            libs.push("libicui18n.so");
            libs.push("libicuuc.so");

            let mode = if is_64() {
                "x64.release"
            } else {
                "ia32.release"
            };
            let target_path = basedir.join("out").join(mode).join("lib.target");

            for lib in libs.iter() {
                let src_path = target_path.join(lib);
                let src = src_path.as_str().unwrap();
                let dest_path = lib_path.join(lib);
                let dest = dest_path.as_str().unwrap();

                let mut cmd = CommandExt::new("cp");
                cmd.wd(&wd);
                cmd.header(true);
                cmd.args(&["-puv", src, dest]);

                match cmd.exec(to_res()) {
                    Ok(_)  => { ; },
                    Err(e) => { res = Err(e); break; },
                }
            }
        }

        if res.is_ok() {
            let symlink_path = lib_path.join("libv8.so");
            if !symlink_path.exists() {
                let mut head = String::from_str("  Excuting 'ln -s libv8.so.");
                head.push_str(libname.as_slice());
                head.push_str(" libv8.so'");
                header(head.as_slice());
                let src = lib_path.join(libname);
                let dest = lib_path.join("libv8.so");
                match fs::symlink(&src, &dest) {
                    Ok(_) => { ; },
                    Err(_) => { res = Err(1); },
                }
            }
        }
        res
    }

    fn cleanup(&self) -> Result<u8,u8> {
        Ok(0)
    }

    fn help(&self) -> Result<u8,u8> {
        println!("{}", USAGE);
        Ok(0)
    }

    fn version(&self) -> Result<u8,u8> {
        println!("{} {} v8-rub {}", now(), sha(), branch());
        Ok(0)
    }
}

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

    fn check_vr(vr: &V8Rub) {
        assert_eq!(vr.prefix, "");
        assert_eq!(vr.url, "");
        assert!(!vr.stat);
        assert!(!vr.disable_i18n);
        assert!(!vr.version);
    }

    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(), "v8");
        assert_eq!(bc.get_branch(), "master");
        assert!(!bc.get_test());
    }

    #[test]
    fn test_new() {
        let vr = V8Rub::new();
        check_vr(&vr);
    }

    #[test]
    fn test_version() {
        let args = vec!["rub".to_string(),
                        "v8".to_string(),
                        "--version".to_string()];
        let mut vr = V8Rub::new();
        check_vr(&vr);
        let b = Buildable::new(&mut vr, &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(),
                        "v8".to_string(),
                        "-h".to_string()];
        let mut vr = V8Rub::new();
        check_vr(&vr);
        let b = Buildable::new(&mut vr, &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(),
                        "v8".to_string()];
        let mut vr = V8Rub::new();
        check_vr(&vr);
        let b = Buildable::new(&mut vr, &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(),
                        "v8".to_string(),
                        "scm".to_string()];
        let mut vr = V8Rub::new();
        check_vr(&vr);
        let b = Buildable::new(&mut vr, &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(),
                        "v8".to_string(),
                        "all".to_string()];
        let mut vr = V8Rub::new();
        check_vr(&vr);
        let b = Buildable::new(&mut vr, &args);
        let bc = b.get_bc();
        check_bc(bc, &vec!["all"]);
        assert_eq!(b.version(), Ok(0));
    }
}