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
use cargo_metadata::{Message, MetadataCommand};
use std::io::{BufReader, Result};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// Builder for cargo build commands.
#[derive(Default)]
pub struct CargoRustc {
    manifest_path: PathBuf,
    cfg: Option<String>,
    crate_type: Option<String>,
    target: Option<String>,
    profile: Option<String>,
    flags: Vec<String>,
    release: bool,
}

impl CargoRustc {
    /// Returns a new builder for a cargo build command that operates on the
    /// manifest residing at the given path.
    pub fn new(manifest_path: &Path) -> CargoRustc {
        CargoRustc {
            manifest_path: manifest_path.to_owned(),
            ..Default::default()
        }
    }

    /// Builds a crate with the given cfg.
    pub fn cfg(mut self, cfg: &str) -> CargoRustc {
        self.cfg = Some(cfg.to_owned());
        self
    }

    /// Builds a crate with the given profile.
    pub fn profile(mut self, profile: &str) -> CargoRustc {
        self.profile = Some(profile.to_owned());
        self
    }

    /// Builds a crate of the given type, overriding the type that is written in
    /// the manifest.
    pub fn crate_type(mut self, crate_type: &str) -> CargoRustc {
        self.crate_type = Some(crate_type.to_owned());
        self
    }

    /// Changes the profile of this build.
    pub fn release(mut self, release: bool) -> CargoRustc {
        self.release = release;
        self
    }

    /// Changes the target of this build.
    pub fn target(mut self, target: &str) -> CargoRustc {
        self.target = Some(target.to_owned());
        self
    }

    /// Changes the flags that are passed to `rustc`.
    pub fn flags(mut self, flags: &[&str]) -> CargoRustc {
        self.flags = flags.into_iter().map(|flag| flag.to_string()).collect();
        self
    }

    /// Executes the build and returns the crate name of the first target that
    /// matches the requested crate type for this build.
    pub fn build(self) -> Result<PathBuf> {
        let metadata = MetadataCommand::new()
            .manifest_path(&self.manifest_path)
            .exec()
            .unwrap();
        let root_id = metadata.resolve.unwrap().root.unwrap();
        let package = metadata
            .packages
            .iter()
            .find(|package| package.id == root_id)
            .unwrap();

        let mut command = Command::new("cargo");
        command.arg("rustc");
        command.arg("--manifest-path");
        command.arg(&self.manifest_path);

        if let Some(target) = self.target.as_ref() {
            command.arg("--target");
            command.arg(target);
        }

        if let Some(profile) = self.profile.as_ref() {
            command.arg("--profile");
            command.arg(profile);
        }

        if self.release {
            command.arg("--release");
        }

        command.arg("--message-format=json-render-diagnostics");

        command.arg("--");

        if let Some(cfg) = self.cfg.as_ref() {
            command.arg("--cfg");
            command.arg(cfg);
        }

        if let Some(crate_type) = self.crate_type.as_ref() {
            command.arg("--crate-type");
            command.arg(crate_type);
        }

        command.args(&self.flags);

        command.stdout(Stdio::piped());
        command.stderr(Stdio::inherit());

        let mut process = command.spawn().unwrap();

        let reader = BufReader::new(process.stdout.take().unwrap());

        let mut path = None;

        for message in Message::parse_stream(reader) {
            match message.unwrap() {
                Message::CompilerArtifact(artifact) => {
                    if artifact.package_id == package.id {
                        path = artifact.filenames.first().cloned();
                    }
                }
                _ => {}
            }
        }

        match process.wait()? {
            status if status.success() => {}
            status => {
                std::process::exit(status.code().unwrap());
            }
        }

        Ok(path.unwrap())
    }
}