Skip to content

Commit 037fe78

Browse files
authored
Merge pull request #64 from joelgallant/master
Tiny cleanliness improvement
2 parents 1e15ffa + 48dcb50 commit 037fe78

File tree

1 file changed

+118
-87
lines changed

1 file changed

+118
-87
lines changed

src/lib.rs

Lines changed: 118 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,10 @@
4747
extern crate cc;
4848

4949
use std::env;
50-
use std::ffi::{OsString, OsStr};
50+
use std::ffi::{OsStr, OsString};
5151
use std::fs::{self, File};
52-
use std::io::ErrorKind;
5352
use std::io::prelude::*;
53+
use std::io::ErrorKind;
5454
use std::path::{Path, PathBuf};
5555
use std::process::Command;
5656

@@ -148,9 +148,12 @@ impl Config {
148148

149149
/// Adds a new `-D` flag to pass to cmake during the generation step.
150150
pub fn define<K, V>(&mut self, k: K, v: V) -> &mut Config
151-
where K: AsRef<OsStr>, V: AsRef<OsStr>
151+
where
152+
K: AsRef<OsStr>,
153+
V: AsRef<OsStr>,
152154
{
153-
self.defines.push((k.as_ref().to_owned(), v.as_ref().to_owned()));
155+
self.defines
156+
.push((k.as_ref().to_owned(), v.as_ref().to_owned()));
154157
self
155158
}
156159

@@ -229,10 +232,12 @@ impl Config {
229232
/// Configure an environment variable for the `cmake` processes spawned by
230233
/// this crate in the `build` step.
231234
pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Config
232-
where K: AsRef<OsStr>,
233-
V: AsRef<OsStr>,
235+
where
236+
K: AsRef<OsStr>,
237+
V: AsRef<OsStr>,
234238
{
235-
self.env.push((key.as_ref().to_owned(), value.as_ref().to_owned()));
239+
self.env
240+
.push((key.as_ref().to_owned(), value.as_ref().to_owned()));
236241
self
237242
}
238243

@@ -286,19 +291,19 @@ impl Config {
286291
t
287292
}
288293
};
289-
let host = self.host.clone().unwrap_or_else(|| {
290-
getenv_unwrap("HOST")
291-
});
294+
let host = self.host.clone().unwrap_or_else(|| getenv_unwrap("HOST"));
292295
let msvc = target.contains("msvc");
293296
let mut c_cfg = cc::Build::new();
294-
c_cfg.cargo_metadata(false)
297+
c_cfg
298+
.cargo_metadata(false)
295299
.opt_level(0)
296300
.debug(false)
297301
.target(&target)
298302
.warnings(false)
299303
.host(&host);
300304
let mut cxx_cfg = cc::Build::new();
301-
cxx_cfg.cargo_metadata(false)
305+
cxx_cfg
306+
.cargo_metadata(false)
302307
.cpp(true)
303308
.opt_level(0)
304309
.debug(false)
@@ -312,9 +317,10 @@ impl Config {
312317
let c_compiler = c_cfg.get_compiler();
313318
let cxx_compiler = cxx_cfg.get_compiler();
314319

315-
let dst = self.out_dir.clone().unwrap_or_else(|| {
316-
PathBuf::from(getenv_unwrap("OUT_DIR"))
317-
});
320+
let dst = self
321+
.out_dir
322+
.clone()
323+
.unwrap_or_else(|| PathBuf::from(getenv_unwrap("OUT_DIR")));
318324
let build = dst.join("build");
319325
self.maybe_clear(&build);
320326
let _ = fs::create_dir(&build);
@@ -327,10 +333,8 @@ impl Config {
327333
cmake_prefix_path.push(PathBuf::from(root));
328334
}
329335
}
330-
let system_prefix = env::var_os("CMAKE_PREFIX_PATH")
331-
.unwrap_or(OsString::new());
332-
cmake_prefix_path.extend(env::split_paths(&system_prefix)
333-
.map(|s| s.to_owned()));
336+
let system_prefix = env::var_os("CMAKE_PREFIX_PATH").unwrap_or(OsString::new());
337+
cmake_prefix_path.extend(env::split_paths(&system_prefix).map(|s| s.to_owned()));
334338
let cmake_prefix_path = env::join_paths(&cmake_prefix_path).unwrap();
335339

336340
// Build up the first cmake command to build the build system.
@@ -342,8 +346,7 @@ impl Config {
342346
cmd.arg("--debug-output");
343347
}
344348

345-
cmd.arg(&self.path)
346-
.current_dir(&build);
349+
cmd.arg(&self.path).current_dir(&build);
347350
let mut is_ninja = false;
348351
if let Some(ref generator) = self.generator {
349352
is_ninja = generator.to_string_lossy().contains("Ninja");
@@ -357,10 +360,18 @@ impl Config {
357360
// If make.exe isn't found, that means we may be using a MinGW
358361
// toolchain instead of a MSYS2 toolchain. If neither is found,
359362
// the build cannot continue.
360-
let has_msys2 = Command::new("make").arg("--version").output().err()
361-
.map(|e| e.kind() != ErrorKind::NotFound).unwrap_or(true);
362-
let has_mingw32 = Command::new("mingw32-make").arg("--version").output().err()
363-
.map(|e| e.kind() != ErrorKind::NotFound).unwrap_or(true);
363+
let has_msys2 = Command::new("make")
364+
.arg("--version")
365+
.output()
366+
.err()
367+
.map(|e| e.kind() != ErrorKind::NotFound)
368+
.unwrap_or(true);
369+
let has_mingw32 = Command::new("mingw32-make")
370+
.arg("--version")
371+
.output()
372+
.err()
373+
.map(|e| e.kind() != ErrorKind::NotFound)
374+
.unwrap_or(true);
364375

365376
let generator = match (has_msys2, has_mingw32) {
366377
(true, _) => "MSYS Makefiles",
@@ -463,10 +474,7 @@ impl Config {
463474
"false" => false,
464475
"true" => true,
465476
unknown => {
466-
eprintln!(
467-
"Warning: unknown debug={}; defaulting to `true`.",
468-
unknown
469-
);
477+
eprintln!("Warning: unknown debug={}; defaulting to `true`.", unknown);
470478
true
471479
}
472480
};
@@ -492,26 +500,24 @@ impl Config {
492500
cmd.arg(dstflag);
493501
}
494502

495-
let build_type = self.defines.iter().find(|&&(ref a, _)| {
496-
a == "CMAKE_BUILD_TYPE"
497-
}).map(|x| x.1.to_str().unwrap()).unwrap_or(&profile);
498-
let build_type_upcase = build_type.chars()
499-
.flat_map(|c| c.to_uppercase())
500-
.collect::<String>();
503+
let build_type = self
504+
.defines
505+
.iter()
506+
.find(|&&(ref a, _)| a == "CMAKE_BUILD_TYPE")
507+
.map(|x| x.1.to_str().unwrap())
508+
.unwrap_or(&profile);
509+
let build_type_upcase = build_type
510+
.chars()
511+
.flat_map(|c| c.to_uppercase())
512+
.collect::<String>();
501513

502514
{
503515
// let cmake deal with optimization/debuginfo
504-
let skip_arg = |arg: &OsStr| {
505-
match arg.to_str() {
506-
Some(s) => {
507-
s.starts_with("-O") || s.starts_with("/O") || s == "-g"
508-
}
509-
None => false,
510-
}
516+
let skip_arg = |arg: &OsStr| match arg.to_str() {
517+
Some(s) => s.starts_with("-O") || s.starts_with("/O") || s == "-g",
518+
None => false,
511519
};
512-
let mut set_compiler = |kind: &str,
513-
compiler: &cc::Tool,
514-
extra: &OsString| {
520+
let mut set_compiler = |kind: &str, compiler: &cc::Tool, extra: &OsString| {
515521
let flag_var = format!("CMAKE_{}_FLAGS", kind);
516522
let tool_var = format!("CMAKE_{}_COMPILER", kind);
517523
if !self.defined(&flag_var) {
@@ -521,7 +527,7 @@ impl Config {
521527
flagsflag.push(extra);
522528
for arg in compiler.args() {
523529
if skip_arg(arg) {
524-
continue
530+
continue;
525531
}
526532
flagsflag.push(" ");
527533
flagsflag.push(arg);
@@ -537,16 +543,15 @@ impl Config {
537543
// Note that for other generators, though, this *overrides*
538544
// things like the optimization flags, which is bad.
539545
if self.generator.is_none() && msvc {
540-
let flag_var_alt = format!("CMAKE_{}_FLAGS_{}", kind,
541-
build_type_upcase);
546+
let flag_var_alt = format!("CMAKE_{}_FLAGS_{}", kind, build_type_upcase);
542547
if !self.defined(&flag_var_alt) {
543548
let mut flagsflag = OsString::from("-D");
544549
flagsflag.push(&flag_var_alt);
545550
flagsflag.push("=");
546551
flagsflag.push(extra);
547552
for arg in compiler.args() {
548553
if skip_arg(arg) {
549-
continue
554+
continue;
550555
}
551556
flagsflag.push(" ");
552557
flagsflag.push(arg);
@@ -566,19 +571,27 @@ impl Config {
566571
// as it's not needed for MSVC with Visual Studio generators and
567572
// for MinGW it doesn't really vary.
568573
if !self.defined("CMAKE_TOOLCHAIN_FILE")
569-
&& !self.defined(&tool_var)
570-
&& (env::consts::FAMILY != "windows" || (msvc && is_ninja)) {
574+
&& !self.defined(&tool_var)
575+
&& (env::consts::FAMILY != "windows" || (msvc && is_ninja))
576+
{
571577
let mut ccompiler = OsString::from("-D");
572578
ccompiler.push(&tool_var);
573579
ccompiler.push("=");
574580
ccompiler.push(find_exe(compiler.path()));
575-
#[cfg(windows)] {
581+
#[cfg(windows)]
582+
{
576583
// CMake doesn't like unescaped `\`s in compiler paths
577584
// so we either have to escape them or replace with `/`s.
578585
use std::os::windows::ffi::{OsStrExt, OsStringExt};
579-
let wchars = ccompiler.encode_wide().map(|wchar| {
580-
if wchar == b'\\' as u16 { '/' as u16 } else { wchar }
581-
}).collect::<Vec<_>>();
586+
let wchars = ccompiler
587+
.encode_wide()
588+
.map(|wchar| {
589+
if wchar == b'\\' as u16 {
590+
'/' as u16
591+
} else {
592+
wchar
593+
}
594+
}).collect::<Vec<_>>();
582595
ccompiler = OsString::from_wide(&wchars);
583596
}
584597
cmd.arg(ccompiler);
@@ -614,34 +627,38 @@ impl Config {
614627
}
615628

616629
let mut makeflags = None;
617-
let mut parallel_args = Vec::new();
630+
let mut parallel_flags = None;
631+
618632
if let Ok(s) = env::var("NUM_JOBS") {
619633
match self.generator.as_ref().map(|g| g.to_string_lossy()) {
620634
Some(ref g) if g.contains("Ninja") => {
621-
parallel_args.push(format!("-j{}", s));
635+
parallel_flags = Some(format!("-j{}", s));
622636
}
623637
Some(ref g) if g.contains("Visual Studio") => {
624-
parallel_args.push(format!("/m:{}", s));
638+
parallel_flags = Some(format!("/m:{}", s));
625639
}
626640
Some(ref g) if g.contains("NMake") => {
627641
// NMake creates `Makefile`s, but doesn't understand `-jN`.
628642
}
629-
_ if fs::metadata(&dst.join("build/Makefile")).is_ok() => {
643+
_ if fs::metadata(&build.join("Makefile")).is_ok() => {
630644
match env::var_os("CARGO_MAKEFLAGS") {
631645
// Only do this on non-windows and non-bsd
632646
// On Windows, we could be invoking make instead of
633647
// mingw32-make which doesn't work with our jobserver
634648
// bsdmake also does not work with our job server
635-
Some(ref s) if !(cfg!(windows) ||
636-
cfg!(target_os = "openbsd") ||
637-
cfg!(target_os = "netbsd") ||
638-
cfg!(target_os = "freebsd") ||
639-
cfg!(target_os = "bitrig") ||
640-
cfg!(target_os = "dragonflybsd")
641-
) => makeflags = Some(s.clone()),
649+
Some(ref s)
650+
if !(cfg!(windows)
651+
|| cfg!(target_os = "openbsd")
652+
|| cfg!(target_os = "netbsd")
653+
|| cfg!(target_os = "freebsd")
654+
|| cfg!(target_os = "bitrig")
655+
|| cfg!(target_os = "dragonflybsd")) =>
656+
{
657+
makeflags = Some(s.clone())
658+
}
642659

643660
// This looks like `make`, let's hope it understands `-jN`.
644-
_ => parallel_args.push(format!("-j{}", s)),
661+
_ => makeflags = Some(OsString::from(format!("-j{}", s))),
645662
}
646663
}
647664
_ => {}
@@ -654,24 +671,31 @@ impl Config {
654671
for &(ref k, ref v) in c_compiler.env().iter().chain(&self.env) {
655672
cmd.env(k, v);
656673
}
674+
657675
if let Some(flags) = makeflags {
658676
cmd.env("MAKEFLAGS", flags);
659677
}
660678

679+
if let Some(flags) = parallel_flags {
680+
cmd.arg(flags);
681+
}
682+
661683
cmd.arg("--build").arg(".");
662684

663685
if !self.no_build_target {
664686
cmd.arg("--target").arg(target);
665687
}
666-
cmd.arg("--config").arg(&profile)
667-
.arg("--").args(&self.build_args)
668-
.args(&parallel_args)
688+
689+
cmd.arg("--config")
690+
.arg(&profile)
691+
.arg("--")
692+
.args(&self.build_args)
669693
.current_dir(&build);
670694

671695
run(&mut cmd, "cmake");
672696

673697
println!("cargo:root={}", dst.display());
674-
return dst
698+
return dst;
675699
}
676700

677701
fn visual_studio_generator(&self, target: &str) -> String {
@@ -681,9 +705,11 @@ impl Config {
681705
Ok(VsVers::Vs15) => "Visual Studio 15 2017",
682706
Ok(VsVers::Vs14) => "Visual Studio 14 2015",
683707
Ok(VsVers::Vs12) => "Visual Studio 12 2013",
684-
Ok(_) => panic!("Visual studio version detected but this crate \
685-
doesn't know how to generate cmake files for it, \
686-
can the `cmake` crate be updated?"),
708+
Ok(_) => panic!(
709+
"Visual studio version detected but this crate \
710+
doesn't know how to generate cmake files for it, \
711+
can the `cmake` crate be updated?"
712+
),
687713
Err(msg) => panic!(msg),
688714
};
689715
if target.contains("i686") {
@@ -726,20 +752,20 @@ impl Config {
726752
for line in contents.lines() {
727753
if line.starts_with("CMAKE_HOME_DIRECTORY") {
728754
let needs_cleanup = match line.split('=').next_back() {
729-
Some(cmake_home) => {
730-
fs::canonicalize(cmake_home)
731-
.ok()
732-
.map(|cmake_home| cmake_home != path)
733-
.unwrap_or(true)
734-
},
735-
None => true
755+
Some(cmake_home) => fs::canonicalize(cmake_home)
756+
.ok()
757+
.map(|cmake_home| cmake_home != path)
758+
.unwrap_or(true),
759+
None => true,
736760
};
737761
if needs_cleanup {
738-
println!("detected home dir change, cleaning out entire build \
739-
directory");
762+
println!(
763+
"detected home dir change, cleaning out entire build \
764+
directory"
765+
);
740766
fs::remove_dir_all(dir).unwrap();
741767
}
742-
break
768+
break;
743769
}
744770
}
745771
}
@@ -750,13 +776,18 @@ fn run(cmd: &mut Command, program: &str) {
750776
let status = match cmd.status() {
751777
Ok(status) => status,
752778
Err(ref e) if e.kind() == ErrorKind::NotFound => {
753-
fail(&format!("failed to execute command: {}\nis `{}` not installed?",
754-
e, program));
779+
fail(&format!(
780+
"failed to execute command: {}\nis `{}` not installed?",
781+
e, program
782+
));
755783
}
756784
Err(e) => fail(&format!("failed to execute command: {}", e)),
757785
};
758786
if !status.success() {
759-
fail(&format!("command did not execute successfully, got: {}", status));
787+
fail(&format!(
788+
"command did not execute successfully, got: {}",
789+
status
790+
));
760791
}
761792
}
762793

0 commit comments

Comments
 (0)