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
use cargo_metadata::MetadataCommand;
use std::io::Result;
use std::path::{Path, PathBuf};
use std::process::Command;
use super::change_crate_type;
#[derive(Default)]
pub struct CargoBuild {
manifest_path: PathBuf,
crate_type: Option<String>,
target: Option<String>,
release: bool,
}
impl CargoBuild {
pub fn new(manifest_path: &Path) -> CargoBuild {
CargoBuild {
manifest_path: manifest_path.to_owned(),
..Default::default()
}
}
pub fn crate_type(mut self, crate_type: &str) -> CargoBuild {
self.crate_type = Some(crate_type.to_owned());
self
}
pub fn release(mut self, release: bool) -> CargoBuild {
self.release = release;
self
}
pub fn target(mut self, target: &str) -> CargoBuild {
self.target = Some(target.to_owned());
self
}
pub fn build(self) -> Result<String> {
let mut guard = None;
if let Some(crate_type) = self.crate_type.as_ref() {
guard.replace(change_crate_type(&self.manifest_path, crate_type)?);
}
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("build");
command.arg("--manifest-path");
command.arg(&self.manifest_path);
if let Some(target) = self.target.as_ref() {
command.arg("--target");
command.arg(target);
}
if self.release {
command.arg("--release");
}
match command.status()? {
status if status.success() => {}
status => {
std::process::exit(status.code().unwrap());
}
}
let mut targets = package.targets.iter();
let target = if let Some(crate_type) = self.crate_type.as_ref() {
targets.find(|target| target.kind == vec![crate_type.to_owned()])
} else {
targets.next()
};
Ok(target.unwrap().name.replace("-", "_"))
}
}