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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
#![deny(missing_docs)]
extern crate gcc;
use std::env;
use std::ffi::{OsString, OsStr};
use std::fs::{self, File};
use std::io::ErrorKind;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::Command;
pub struct Config {
path: PathBuf,
generator: Option<OsString>,
cflags: OsString,
cxxflags: OsString,
defines: Vec<(OsString, OsString)>,
deps: Vec<String>,
target: Option<String>,
host: Option<String>,
out_dir: Option<PathBuf>,
profile: Option<String>,
build_args: Vec<OsString>,
cmake_target: Option<String>,
env: Vec<(OsString, OsString)>,
static_crt: Option<bool>,
}
pub fn build<P: AsRef<Path>>(path: P) -> PathBuf {
Config::new(path.as_ref()).build()
}
impl Config {
pub fn new<P: AsRef<Path>>(path: P) -> Config {
Config {
path: env::current_dir().unwrap().join(path),
generator: None,
cflags: OsString::new(),
cxxflags: OsString::new(),
defines: Vec::new(),
deps: Vec::new(),
profile: None,
out_dir: None,
target: None,
host: None,
build_args: Vec::new(),
cmake_target: None,
env: Vec::new(),
static_crt: None,
}
}
pub fn generator<T: AsRef<OsStr>>(&mut self, generator: T) -> &mut Config {
self.generator = Some(generator.as_ref().to_owned());
self
}
pub fn cflag<P: AsRef<OsStr>>(&mut self, flag: P) -> &mut Config {
self.cflags.push(" ");
self.cflags.push(flag.as_ref());
self
}
pub fn cxxflag<P: AsRef<OsStr>>(&mut self, flag: P) -> &mut Config {
self.cxxflags.push(" ");
self.cxxflags.push(flag.as_ref());
self
}
pub fn define<K, V>(&mut self, k: K, v: V) -> &mut Config
where K: AsRef<OsStr>, V: AsRef<OsStr>
{
self.defines.push((k.as_ref().to_owned(), v.as_ref().to_owned()));
self
}
pub fn register_dep(&mut self, dep: &str) -> &mut Config {
self.deps.push(dep.to_string());
self
}
pub fn target(&mut self, target: &str) -> &mut Config {
self.target = Some(target.to_string());
self
}
pub fn host(&mut self, host: &str) -> &mut Config {
self.host = Some(host.to_string());
self
}
pub fn out_dir<P: AsRef<Path>>(&mut self, out: P) -> &mut Config {
self.out_dir = Some(out.as_ref().to_path_buf());
self
}
pub fn profile(&mut self, profile: &str) -> &mut Config {
self.profile = Some(profile.to_string());
self
}
pub fn static_crt(&mut self, static_crt: bool) -> &mut Config {
self.static_crt = Some(static_crt);
self
}
pub fn build_arg<A: AsRef<OsStr>>(&mut self, arg: A) -> &mut Config {
self.build_args.push(arg.as_ref().to_owned());
self
}
pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Config
where K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.env.push((key.as_ref().to_owned(), value.as_ref().to_owned()));
self
}
pub fn build_target(&mut self, target: &str) -> &mut Config {
self.cmake_target = Some(target.to_string());
self
}
pub fn build(&mut self) -> PathBuf {
let target = self.target.clone().unwrap_or_else(|| {
getenv_unwrap("TARGET")
});
let host = self.host.clone().unwrap_or_else(|| {
getenv_unwrap("HOST")
});
let msvc = target.contains("msvc");
let mut c_cfg = gcc::Build::new();
c_cfg.cargo_metadata(false)
.opt_level(0)
.debug(false)
.target(&target)
.warnings(false)
.host(&host);
let mut cxx_cfg = gcc::Build::new();
cxx_cfg.cargo_metadata(false)
.cpp(true)
.opt_level(0)
.debug(false)
.target(&target)
.warnings(false)
.host(&host);
if let Some(static_crt) = self.static_crt {
c_cfg.static_crt(static_crt);
cxx_cfg.static_crt(static_crt);
}
let c_compiler = c_cfg.get_compiler();
let cxx_compiler = cxx_cfg.get_compiler();
let dst = self.out_dir.clone().unwrap_or_else(|| {
PathBuf::from(getenv_unwrap("OUT_DIR"))
});
let build = dst.join("build");
self.maybe_clear(&build);
let _ = fs::create_dir(&build);
let mut cmake_prefix_path = Vec::new();
for dep in &self.deps {
if let Some(root) = env::var_os(&format!("DEP_{}_ROOT", dep)) {
cmake_prefix_path.push(PathBuf::from(root));
}
}
let system_prefix = env::var_os("CMAKE_PREFIX_PATH")
.unwrap_or(OsString::new());
cmake_prefix_path.extend(env::split_paths(&system_prefix)
.map(|s| s.to_owned()));
let cmake_prefix_path = env::join_paths(&cmake_prefix_path).unwrap();
let mut cmd = Command::new("cmake");
cmd.arg(&self.path)
.current_dir(&build);
if target.contains("windows-gnu") {
if host.contains("windows") {
if self.generator.is_none() {
cmd.arg("-G").arg("MSYS Makefiles");
}
} else {
if !self.defined("CMAKE_SYSTEM_NAME") {
cmd.arg("-DCMAKE_SYSTEM_NAME=Windows");
}
if !self.defined("CMAKE_RC_COMPILER") {
let exe = find_exe(c_compiler.path());
if let Some(name) = exe.file_name().unwrap().to_str() {
let name = name.replace("gcc", "windres");
let windres = exe.with_file_name(name);
if windres.is_file() {
let mut arg = OsString::from("-DCMAKE_RC_COMPILER=");
arg.push(&windres);
cmd.arg(arg);
}
}
}
}
} else if msvc {
if self.generator.is_none() {
cmd.arg("-G").arg(self.visual_studio_generator(&target));
}
} else if target.contains("redox") {
if !self.defined("CMAKE_SYSTEM_NAME") {
cmd.arg("-DCMAKE_SYSTEM_NAME=Generic");
}
}
let mut is_ninja = false;
if let Some(ref generator) = self.generator {
cmd.arg("-G").arg(generator);
is_ninja = generator.to_string_lossy().contains("Ninja");
}
let profile = self.profile.clone().unwrap_or_else(|| {
match &getenv_unwrap("PROFILE")[..] {
"bench" | "release" => "Release",
_ => "Debug",
}.to_string()
});
for &(ref k, ref v) in &self.defines {
let mut os = OsString::from("-D");
os.push(k);
os.push("=");
os.push(v);
cmd.arg(os);
}
if !self.defined("CMAKE_INSTALL_PREFIX") {
let mut dstflag = OsString::from("-DCMAKE_INSTALL_PREFIX=");
dstflag.push(&dst);
cmd.arg(dstflag);
}
let build_type = self.defines.iter().find(|&&(ref a, _)| {
a == "CMAKE_BUILD_TYPE"
}).map(|x| x.1.to_str().unwrap()).unwrap_or(&profile);
let build_type_upcase = build_type.chars()
.flat_map(|c| c.to_uppercase())
.collect::<String>();
{
let skip_arg = |arg: &OsStr| {
match arg.to_str() {
Some(s) => {
s.starts_with("-O") || s.starts_with("/O") || s == "-g"
}
None => false,
}
};
let mut set_compiler = |kind: &str,
compiler: &gcc::Tool,
extra: &OsString| {
let flag_var = format!("CMAKE_{}_FLAGS", kind);
let tool_var = format!("CMAKE_{}_COMPILER", kind);
if !self.defined(&flag_var) {
let mut flagsflag = OsString::from("-D");
flagsflag.push(&flag_var);
flagsflag.push("=");
flagsflag.push(extra);
for arg in compiler.args() {
if skip_arg(arg) {
continue
}
flagsflag.push(" ");
flagsflag.push(arg);
}
cmd.arg(flagsflag);
}
if self.generator.is_none() && msvc {
let flag_var_alt = format!("CMAKE_{}_FLAGS_{}", kind,
build_type_upcase);
if !self.defined(&flag_var_alt) {
let mut flagsflag = OsString::from("-D");
flagsflag.push(&flag_var_alt);
flagsflag.push("=");
flagsflag.push(extra);
for arg in compiler.args() {
if skip_arg(arg) {
continue
}
flagsflag.push(" ");
flagsflag.push(arg);
}
cmd.arg(flagsflag);
}
}
if !self.defined("CMAKE_TOOLCHAIN_FILE")
&& !self.defined(&tool_var)
&& (env::consts::FAMILY != "windows" || (msvc && is_ninja)) {
let mut ccompiler = OsString::from("-D");
ccompiler.push(&tool_var);
ccompiler.push("=");
ccompiler.push(find_exe(compiler.path()));
#[cfg(windows)] {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
let wchars = ccompiler.encode_wide().map(|wchar| {
if wchar == b'\\' as u16 { '/' as u16 } else { wchar }
}).collect::<Vec<_>>();
ccompiler = OsString::from_wide(&wchars);
}
cmd.arg(ccompiler);
}
};
set_compiler("C", &c_compiler, &self.cflags);
set_compiler("CXX", &cxx_compiler, &self.cxxflags);
}
if !self.defined("CMAKE_BUILD_TYPE") {
cmd.arg(&format!("-DCMAKE_BUILD_TYPE={}", profile));
}
if !self.defined("CMAKE_TOOLCHAIN_FILE") {
if let Ok(s) = env::var("CMAKE_TOOLCHAIN_FILE") {
cmd.arg(&format!("-DCMAKE_TOOLCHAIN_FILE={}", s));
}
}
for &(ref k, ref v) in c_compiler.env().iter().chain(&self.env) {
cmd.env(k, v);
}
run(cmd.env("CMAKE_PREFIX_PATH", cmake_prefix_path), "cmake");
let mut parallel_args = Vec::new();
if let Ok(s) = env::var("NUM_JOBS") {
match self.generator.as_ref().map(|g| g.to_string_lossy()) {
Some(ref g) if g.contains("Ninja") => {
parallel_args.push(format!("-j{}", s));
}
Some(ref g) if g.contains("Visual Studio") => {
parallel_args.push(format!("/m:{}", s));
}
Some(ref g) if g.contains("NMake") => {
}
_ => if fs::metadata(&dst.join("build/Makefile")).is_ok() {
parallel_args.push(format!("-j{}", s));
}
}
}
let target = self.cmake_target.clone().unwrap_or("install".to_string());
let mut cmd = Command::new("cmake");
for &(ref k, ref v) in c_compiler.env().iter().chain(&self.env) {
cmd.env(k, v);
}
run(cmd.arg("--build").arg(".")
.arg("--target").arg(target)
.arg("--config").arg(&profile)
.arg("--").args(&self.build_args)
.args(¶llel_args)
.current_dir(&build), "cmake");
println!("cargo:root={}", dst.display());
return dst
}
fn visual_studio_generator(&self, target: &str) -> String {
use gcc::windows_registry::{find_vs_version, VsVers};
let base = match find_vs_version() {
Ok(VsVers::Vs15) => "Visual Studio 15 2017",
Ok(VsVers::Vs14) => "Visual Studio 14 2015",
Ok(VsVers::Vs12) => "Visual Studio 12 2013",
Ok(_) => panic!("Visual studio version detected but this crate \
doesn't know how to generate cmake files for it, \
can the `cmake` crate be updated?"),
Err(msg) => panic!(msg),
};
if target.contains("i686") {
base.to_string()
} else if target.contains("x86_64") {
format!("{} Win64", base)
} else {
panic!("unsupported msvc target: {}", target);
}
}
fn defined(&self, var: &str) -> bool {
self.defines.iter().any(|&(ref a, _)| a == var)
}
fn maybe_clear(&self, dir: &Path) {
let path = fs::canonicalize(&self.path).unwrap_or(self.path.clone());
let mut f = match File::open(dir.join("CMakeCache.txt")) {
Ok(f) => f,
Err(..) => return,
};
let mut u8contents = Vec::new();
match f.read_to_end(&mut u8contents) {
Ok(f) => f,
Err(..) => return,
};
let contents = String::from_utf8_lossy(&u8contents);
drop(f);
for line in contents.lines() {
if line.starts_with("CMAKE_HOME_DIRECTORY") {
let needs_cleanup = match line.split('=').next_back() {
Some(cmake_home) => {
fs::canonicalize(cmake_home)
.ok()
.map(|cmake_home| cmake_home != path)
.unwrap_or(true)
},
None => true
};
if needs_cleanup {
println!("detected home dir change, cleaning out entire build \
directory");
fs::remove_dir_all(dir).unwrap();
}
break
}
}
}
}
fn run(cmd: &mut Command, program: &str) {
println!("running: {:?}", cmd);
let status = match cmd.status() {
Ok(status) => status,
Err(ref e) if e.kind() == ErrorKind::NotFound => {
fail(&format!("failed to execute command: {}\nis `{}` not installed?",
e, program));
}
Err(e) => fail(&format!("failed to execute command: {}", e)),
};
if !status.success() {
fail(&format!("command did not execute successfully, got: {}", status));
}
}
fn find_exe(path: &Path) -> PathBuf {
env::split_paths(&env::var_os("PATH").unwrap_or(OsString::new()))
.map(|p| p.join(path))
.find(|p| fs::metadata(p).is_ok())
.unwrap_or(path.to_owned())
}
fn getenv_unwrap(v: &str) -> String {
match env::var(v) {
Ok(s) => s,
Err(..) => fail(&format!("environment variable `{}` not defined", v)),
}
}
fn fail(s: &str) -> ! {
panic!("\n{}\n\nbuild script failed, must exit now", s)
}