|
| 1 | +//! Rust project builder - wrapper for invoking Cargo |
| 2 | +
|
| 3 | +use std::{ |
| 4 | + ffi::OsString, |
| 5 | + process::{Child, Command, ExitStatus}, |
| 6 | +}; |
| 7 | + |
| 8 | +/// Name of the `cargo` executable |
| 9 | +const CARGO_EXE: &str = "cargo"; |
| 10 | + |
| 11 | +/// Rust project builder |
| 12 | +#[derive(Clone, Debug)] |
| 13 | +pub struct Builder { |
| 14 | + program: OsString, |
| 15 | + args: Vec<OsString>, |
| 16 | +} |
| 17 | + |
| 18 | +impl Default for Builder { |
| 19 | + fn default() -> Self { |
| 20 | + Self::new(CARGO_EXE) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +impl Builder { |
| 25 | + /// Create `Builder` that invokes the given command with the given arguments |
| 26 | + pub fn new<S>(program: S) -> Self |
| 27 | + where |
| 28 | + S: Into<OsString>, |
| 29 | + { |
| 30 | + Self { |
| 31 | + program: program.into(), |
| 32 | + args: vec![], |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /// Append an argument to the set of arguments to run |
| 37 | + pub fn arg<S>(&mut self, arg: S) -> &mut Self |
| 38 | + where |
| 39 | + S: Into<OsString>, |
| 40 | + { |
| 41 | + self.args.push(arg.into()); |
| 42 | + self |
| 43 | + } |
| 44 | + |
| 45 | + /// Append multiple arguments to the set of arguments to run |
| 46 | + pub fn args<I, S>(&mut self, args: I) -> &mut Self |
| 47 | + where |
| 48 | + I: IntoIterator<Item = S>, |
| 49 | + S: Into<OsString>, |
| 50 | + { |
| 51 | + self.args.extend(args.into_iter().map(|a| a.into())); |
| 52 | + self |
| 53 | + } |
| 54 | + |
| 55 | + /// Run the given subcommand |
| 56 | + pub fn run(&self) -> Process { |
| 57 | + let child = Command::new(&self.program) |
| 58 | + .args(&self.args) |
| 59 | + .spawn() |
| 60 | + .unwrap_or_else(|e| { |
| 61 | + panic!("error running command: {}", e); |
| 62 | + }); |
| 63 | + |
| 64 | + Process(child) |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +/// Wrapper for the builder subprocess |
| 69 | +pub struct Process(Child); |
| 70 | + |
| 71 | +impl Process { |
| 72 | + /// Wait for the child to finish |
| 73 | + pub fn wait(mut self) -> ExitStatus { |
| 74 | + self.0 |
| 75 | + .wait() |
| 76 | + .unwrap_or_else(|e| panic!("couldn't get child's exit status: {}", e)) |
| 77 | + } |
| 78 | +} |
0 commit comments