robuild 0.0.4

Tool for writing build recipes in Rust
Documentation
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
use std::{
    fs::{
        metadata,
        create_dir_all,
        read_dir,
        remove_dir_all,
        remove_file,
        rename
    },
    time::SystemTime,
    collections::VecDeque,
    path::{Path, PathBuf},
    io::{ErrorKind, Result as ioResult},
    process::{exit, Command, Output, Stdio, Child},
};

const CMD_ARG: &str = if cfg!(windows) {"cmd"} else {"sh"};
const CMD_ARG2: &str = if cfg!(windows) {"/C"} else {"-c"};

#[macro_export]
macro_rules! go_rebuild_yourself {
    () => {{
        let source_path = file!();
        let args = std::env::args().collect::<Vec::<_>>();
        Rob::go_rebuild_yourself(&args, &source_path).unwrap();
    }}
}

macro_rules! colored {
    (r.$str: expr)  => { format!("\x1b[91m{}\x1b[0m", $str) };
    (y.$str: expr)  => { format!("\x1b[93m{}\x1b[0m", $str) };
    (br.$str: expr) => { format!("\x1b[31m{}\x1b[0m", $str) };
}

#[macro_export]
macro_rules! log {
    ($log_level: tt, $($args: expr), *) => {{
        use LogLevel::*;
        let out = format!($($args), *);
        match $log_level {
            PANIC => {
                let out = format!("{lvl} {f}:{l}:{c}: {out}",
                                  lvl = LogLevel::$log_level, f = file!(),
                                  l = line!(), c = column!());
                Rob::panic(&out)
            }
            _ => Rob::log($log_level, &out, file!(), line!(), column!())
        }
    }}
}

#[macro_export]
macro_rules! pathbuf {
    ($($p: expr), *) => {{
        let mut path = std::path::PathBuf::new();
        $(path.push($p);)*
        path
    }}
}

#[macro_export]
macro_rules! mkdirs {
    ($($dir: expr), *) => {{
        let p = pathbuf![$($dir), *];
        Rob::mkdir(p)
    }}
}

pub struct Dir {
    stack: VecDeque::<PathBuf>,
}

impl Dir {
    /// Takes path to a directory and returns
    /// instance of the iterable struct `Dir`.
    ///
    /// `Dir` iterates using the BFS algorithm,
    ///
    /// if current element is file `Dir` returns it,
    /// otherwise it iterates that directory and checkes for other files.
    pub fn new<P>(root: P) -> Dir
    where
        P: Into::<PathBuf>
    {
        let mut stack = VecDeque::new();
        stack.push_back(root.into());
        Dir { stack }
    }
}

impl Iterator for Dir {
    type Item = PathBuf;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(p) = self.stack.pop_front() {
            if p.is_file() { return Some(p) }

            match read_dir(&p) {
                Ok(es) => es.filter_map(Result::ok).for_each(|e| {
                    self.stack.push_back(e.path())
                }),
                Err(e) => eprintln!("ERROR: {e}")
            }
        } None
    }
}

pub struct RobCommand {
    lines: Vec::<String>,
}

pub enum LogLevel {
    CMD,
    INFO,
    WARN,
    ERROR,
    PANIC
}

impl std::fmt::Display for LogLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use self::LogLevel::*;
        match self {
            CMD   => write!(f, "[CMD]")?,
            INFO  => write!(f, "[INFO]")?,
            WARN  => write!(f, "[WARN]")?,
            ERROR => write!(f, "[ERROR]")?,
            PANIC => write!(f, "[PANIC]")?
        } Ok(())
    }
}

impl RobCommand {
    #[inline]
    pub fn new() -> RobCommand {
        Self { lines: Vec::new() }
    }
}

pub struct Rob(RobCommand);

impl Rob {
    #[inline]
    pub fn new() -> Rob {
        Rob(RobCommand::new())
    }

    fn needs_rebuild(bin: &str, srcs: &Vec::<&str>) -> ioResult::<bool> {
        if !Rob::path_exists(bin) { return Ok(true) }

        let bin_mod_time = Rob::get_last_modification_time(bin)?;
        for src in srcs {
            let src_mod_time = Rob::get_last_modification_time(src)?;
            if src_mod_time > bin_mod_time {
                return Ok(true)
            }
        } Ok(false)
    }

    // The implementation idea is stolen from https://github.com/tsoding/nobuild,
    // which is also stolen from https://github.com/zhiayang/nabs
    pub fn go_rebuild_yourself(args: &Vec::<String>, source_path: &str) -> ioResult::<()> {
        assert!(args.len() >= 1);
        let binary_path = &args[0];
        let rebuild_is_needed = Rob::needs_rebuild(&binary_path, &vec![source_path])?;
        if rebuild_is_needed {
            let old_bin_path = format!("{binary_path}.old");
            log!(INFO, "RENAMING: {binary_path} -> {old_bin_path}");
            Rob::rename(binary_path, &old_bin_path)?;

            if let Err(err) = Rob::new()
                .append(&["rustc -o", binary_path, source_path])
                .execute_sync()
            {
                log!(ERROR, "FAILED TO RENAME FILE: {old_bin_path}: {err}");
                Rob::rename(&old_bin_path, binary_path)?;
                exit(1);
            }

            match Rob::new()
                .append(args)
                .execute_sync()
            {
                Ok(_) => {
                    log!(INFO, "REMOVING: {old_bin_path}");
                    Rob::rm_if_exists(old_bin_path);
                    exit(0);
                }
                Err(err) => {
                    log!(ERROR, "FAILED TO RESTART ROB FROM FILE: {binary_path}: {err}");
                    exit(1);
                }
            }
        } Ok(())
    }

    #[inline]
    pub fn get_last_modification_time<P>(p: P) -> ioResult::<SystemTime>
    where
        P: AsRef::<Path>
    {
        metadata(p)?.modified()
    }

    #[inline]
    pub fn is_file<P>(p: P) -> bool
    where
        P: Into::<PathBuf>
    {
        p.into().is_file()
    }

    #[inline]
    pub fn is_dir<P>(p: P) -> bool
    where
        P: Into::<PathBuf>
    {
        p.into().is_dir()
    }

    #[inline]
    pub fn path_exists<P>(p: P) -> bool
    where
        P: Into::<PathBuf>
    {
        p.into().exists()
    }

    #[inline]
    pub fn rename<P>(from: P, to: P) -> ioResult<()>
    where
        P: AsRef::<Path>
    {
        rename(from, to)
    }

    #[inline]
    pub fn mkdir<P>(p: P) -> ioResult::<()>
    where
        P: Into::<PathBuf>
    {
        create_dir_all(p.into())
    }

    pub fn rm_if_exists<P>(p: P)
    where
        P: Into::<PathBuf> + ToOwned::<Owned = String>
    {
        if Rob::is_dir(p.to_owned()) {
            remove_dir_all(p.into()).expect("Failed to remove directory")
        } else if Rob::is_file(p.to_owned()) {
            remove_file(p.into()).expect("Failed to remove file")
        }
    }

    pub fn rm<P>(p: P) -> ioResult::<()>
    where
        P: Into::<PathBuf> + ToOwned::<Owned = String>
    {
        if !Rob::path_exists(p.to_owned()) {
            return Err(ErrorKind::NotFound.into())
        } else if Rob::is_dir(p.to_owned()) {
            remove_dir_all(p.into())
        } else if Rob::is_file(p.to_owned()) {
            remove_file(p.into())
        } else {
            Err(ErrorKind::InvalidData.into())
        }
    }

    #[inline]
    fn panic(out: &str) -> ! {
        panic!("{out}", out = out.to_owned())
    }

    fn log(lvl: LogLevel, out: &str, f: &str, l: u32, c: u32) {
        use self::LogLevel::*;
        let out_with_info = format!("{f}:{l}:{c}: {out}");
        match lvl {
            CMD   => println!("{lvl} {out}"),
            INFO  => println!("{lvl} {out}"),
            WARN  => println!("{lvl} {out_with_info}", lvl = colored!(y."[WARN]")),
            ERROR => println!("{lvl} {out_with_info}", lvl = colored!(r."[ERROR]")),
            PANIC => panic!("UNREACHABLE")
        }
    }

    /// Takes path and returns it without the file extension
    #[inline]
    pub fn noext(p: &str) -> String {
        p.chars().take_while(|x| *x != '.').collect()
    }

    /* TODO:
    Change the way how we treating lines, i think we should introduce
    some new function like `execute_last_sync` or something, that just moves command pointer
    therefore following input will be treated as next line and so on, if ykwim
    */
    /// Takes all of the args and pushes them to self.lines,
    /// Each call of the append function will be treated as one line of arguments, as in here:
    /// ```
    /// let p = pathbuf!["dummy", "rakivo", "dummy.cpp"];
    /// let handle = Rob::new()
    ///     .append(&["clang++", "-o", "output", p.to_str().unwrap()])
    ///     .execute_sync();
    /// ```
    /// It Outputs:
    /// ```
    /// [CMD] clang++ -o output test/test1/test.cpp
    /// [INFO] [EMPTY]
    /// ```
    ///
    /// Output is [EMPTY] because the program compiled successfully.
    #[inline]
    pub fn append<'a, I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator::<Item = S>,
        S: AsRef<str>
    {
        let line = args.into_iter()
            .map(|arg| arg.as_ref().to_owned())
            .collect::<Vec<_>>()
            .join(" ");

        self.0.lines.push(line);
        self
    }

    fn format_out(out: &str) -> &str {
        if out.ends_with('\n') {
            &out[0..out.len() - 1]
        } else {
            out
        }
    }

    fn process_output(out: &Output) {
        if out.status.success() {
            let stdout = String::from_utf8_lossy(&out.stdout);
            if !stdout.is_empty() {
                let formatted = Rob::format_out(&stdout);
                log!(INFO, "{formatted}");
            }
        } else {
            let stderr = String::from_utf8_lossy(&out.stderr);
            if !stderr.is_empty() {
                let formatted = Rob::format_out(&stderr);
                log!(ERROR, "{formatted}");
            }
        }
    }

    /// Blocking operation.
    ///
    /// Simply creates `Command` for each line in self.lines and executes them.
    /// More about that: https://doc.rust-lang.org/std/process/struct.Command.html
    pub fn execute_sync(&mut self) -> ioResult::<Vec::<Output>> {
        let mut ret = Vec::new();

        for line in self.0.lines.iter() {
            log!(CMD, "{line}");
            let out = Command::new(CMD_ARG)
                .arg(CMD_ARG2)
                .arg(&line)
                .output()?;

            Self::process_output(&out);
            ret.push(out);
        } Ok(ret)
    }

    /// Non-blocking operation.
    ///
    /// Created `Command` for each line in self.lines.
    /// More about that: https://doc.rust-lang.org/std/process/struct.Command.html
    ///
    /// Stdout and stderr are piped to manage all of the outputs properly.
    /// Returns vector of child which you can turn into vector of the outputs using Rob::wait_for_children.
    pub fn execute_async(&mut self) -> ioResult::<Vec::<Child>> {
        let mut children = Vec::new();
        for line in self.0.lines.iter() {
            log!(CMD, "{line}");
            let out = Command::new(CMD_ARG)
                .arg(CMD_ARG2)
                .arg(&line)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()?;

            children.push(out);
        }

        Ok(children)
    }

    /// Blocks the main thread and waits for all of the children.
    pub fn wait_for_children(children: Vec::<Child>) -> ioResult::<Vec::<Output>> {
        let mut ret = Vec::new();
        for child in children {
            ret.push(child.wait_with_output()?);
        } Ok(ret)
    }
}

/* TODO:
    Examples,
    Other Nob features,
    Documentation,
*/