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
use std::io;
use std::io::Write;
use std::process::{Command, ExitStatus};

pub trait CommandExt {
    fn inherit(&mut self);

    // wait and check
    fn wait_and_check(&mut self);

    // just wait
    fn wait(&mut self);

    fn print(&mut self) -> &mut Self;

    fn rust_log(&mut self, log_option: Option<&str>) -> &mut Self;
}

impl CommandExt for Command {
    /// execute and ensure command has been executed ok
    fn inherit(&mut self) {
        use std::process::Stdio;

        self.print();

        let output = self
            .stdout(Stdio::inherit())
            .output()
            .expect("execution failed");

        if !output.status.success() {
            io::stderr().write_all(&output.stderr).unwrap();
        }

        output.status.check();
    }

    /// execute and ensure command has been executed ok
    fn wait_and_check(&mut self) {
        self.print();

        let output = self.output().expect("execution failed");

        io::stdout().write_all(&output.stdout).unwrap();
        io::stderr().write_all(&output.stderr).unwrap();

        output.status.check();
    }

    /// execute and wait, ignore error
    fn wait(&mut self) {
        self.print();
        let output = self.output().expect("execution failed");

        io::stdout().write_all(&output.stdout).unwrap();
        io::stderr().write_all(&output.stderr).unwrap();
    }

    fn print(&mut self) -> &mut Self {
        use std::env;

        if env::var_os("FLV_CMD").is_some() {
            println!(">> {}", format!("{:?}", self).replace("\"", ""));
        }

        self
    }

    fn rust_log(&mut self, log_option: Option<&str>) -> &mut Self {
        if let Some(log) = log_option {
            println!("setting rust log: {}", log);
            self.env("RUST_LOG", log);
        }

        self
    }
}

trait StatusExt {
    fn check(&self);
}

impl StatusExt for ExitStatus {
    fn check(&self) {
        if !self.success() {
            match self.code() {
                Some(code) => println!("Exited with status code: {}", code),
                None => println!("Process terminated by signal"),
            }
            unreachable!()
        }
    }
}