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
pub extern crate rayon;

use std::slice;

/// Execute a command.
///
/// Each argument after the first, denoting the executable, represents a respective argument passed
/// to the executable.  Optionally, you can specify the working directory by prepending `; in
/// "blah" ` to the argument list. Any arbitrary number of environment variables can be declared
/// through `where VAR = VAL`, delimited by `;`.
///
/// An argument can be of any type implementing `AsSlice<T>` where `T: AsRef<OsStr>`, that is, it
/// can take both strings and arrays of strings.
///
/// Examples
/// ========
///
/// To run a command in the current working directory:
///
/// ```rust
/// cmd!("ls", "/"); // 'ls /'
/// ```
///
/// If we want to run this in a custom working directory, we can do:
///
/// ```rust
/// cmd!("ls", "."; in "/");
/// ```
///
/// In case we want to set environment variables, we do:
///
/// ```rust
/// cmd!("ls", "."; where BLAH = "/"; where BLUH = "!");
/// ```
#[macro_export]
macro_rules! cmd {
    ($cmd:expr $(, $arg:expr)*; in $cd:expr $(; where $var:ident = $val:expr)*) => {{
        use std::process;

        if process::Command::new($cmd)
            $(
                .args({
                    use $crate::ToSlice;
                    ($arg).to_slice()
                })
            )*
            $(
                .env(stringify!($var), $val)
            )*
            .current_dir($cd)
            .stdout(process::Stdio::inherit())
            .stderr(process::Stdio::inherit())
            .status().is_err() {
            return Err(());
        }
    }};
    ($cmd:expr $(, $arg:expr)* $(; where $var:ident = $val:expr)*) => {{
        use std::process;

        if process::Command::new($cmd)
            $(
                .args({
                    use $crate::ToSlice;
                    ($arg).to_slice()
                })
            )*
            $(
                .env(stringify!($var), $val)
            )*
            .stdout(process::Stdio::inherit())
            .stderr(process::Stdio::inherit())
            .status().is_err() {
            return Err(());
        }
    }};
}

/// Helper trait for converting types into slices.
pub trait ToSlice<T> {
    /// Convert this type into a slice.
    fn to_slice(&self) -> &[T];
}

impl<T> ToSlice<T> for T {
    fn to_slice(&self) -> &[T] {
        unsafe { slice::from_raw_parts(self as *const T, 1) }
    }
}

impl<T> ToSlice<T> for [T] {
    fn to_slice(&self) -> &[T] {
        self
    }
}

/// Evaluate N expressions in parallel.
///
/// This uses work-stealing as back end.
#[macro_export]
macro_rules! par {
    () => {
        Ok(())
    };
    ($a:expr) => {{
        try!($a);
        Ok(())
    }};
    ($a:expr, $($rest:expr),*) => {{
        let (a, b) = $crate::rayon::join(|| $a, || par!($($rest),*));
        try!(a);
        try!(b);
        Ok(())
    }};
}

/// Define a build.
///
/// This macro takes a block, which resembles the `match` syntax. Left to each of the arms are the
/// recipe's (compilation unit) name, which is followed by the names of the recipes it depends on,
/// delimited by `()`.  Right to the arm is the recipe's instructions are placed. This is simply
/// normal Rust code, defining the recipe.
///
/// Additionally, this expands to the main function, which handles arguments as well.
///
/// Examples
/// ========
///
/// ```rust
/// #[macro_use]
/// extern crate cake;
///
/// build! {
///     start(sodium, libstd) => cmd!("ls"),
///     sodium(libstd, libextra) => println!("yay"),
///     libstd() => println!("libstd"),
///     libextra() => println!("libextra"),
/// }
/// ```
#[macro_export]
macro_rules! build {
    { $($name:ident($($dep:ident),*) => $cont:expr,)* } => {
        use std::io::Write;
        use std::sync::Mutex;
        use std::{env, io, process};

        enum Error {
            Failed(&'static str),
            NotFound,
        }

        #[derive(Default)]
        struct CakeBuild {
            $(
                $name: Mutex<bool>
            ),*
        }

        fn unit(name: &str) {
            let mut stdout = io::stdout();
            writeln!(stdout, "== Running recipe {} ==", name).unwrap();
        }

        impl CakeBuild {
            $(
                fn $name(&self) -> Result<(), Error> {
                    fn inner() -> Result<(), ()> {
                        unit(stringify!($name));
                        $cont;
                        Ok(())
                    }

                    try!(par!(
                        $(
                            {
                                let mut lock = self.$dep.lock().unwrap();
                                if !*lock {
                                    try!(self.$dep());
                                }

                                *lock = true;

                                Ok(())
                            }
                        ),*
                    ));

                    inner().map_err(|_| Error::Failed(stringify!($name)))
                }
            )*

            fn run_recipe(&self, cmd: &str) -> Result<(), Error> {
                match cmd {
                    $(
                        stringify!($name) => {
                            let res = self.$name();
                            *self.$name.lock().unwrap() = true;
                            res
                        }
                    )*
                    _ => Err(Error::NotFound),
                }
            }
        }

        fn main() {
            let build = CakeBuild::default();
            let stderr = io::stderr();

            let mut run = false;
            for i in env::args().skip(1) {
                run = true;

                if let Err(x) = build.run_recipe(&i) {
                    let mut stderr = stderr.lock();
                    match x {
                        Error::NotFound => writeln!(stderr, "recipe, {}, not found.", i),
                        Error::Failed(name) => writeln!(stderr, "recipe, {}, failed.", name),
                    }.unwrap();
                    stderr.flush().unwrap();
                    process::exit(1);
                }
            }

            let mut stderr = stderr.lock();
            if !run {
                writeln!(stderr, "No argument given. Aborting.").unwrap();
            }
        }
    };
}