use std::fs::read_dir;
use std::path::Path;
use std::process::Command;
use std::io;
use std::str;
fn command_output(cmd: &mut Command) -> String {
str::from_utf8(&cmd.output().unwrap().stdout)
.unwrap()
.trim_right()
.to_string()
}
fn command_ok(cmd: &mut Command) -> bool {
cmd.status().ok().map_or(false, |s| s.success())
}
fn ghc(builder: &str, arg: &str) -> String {
command_output(Command::new(builder).args(&["exec", "--", "ghc", arg]))
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
const DYLIB_EXTENSION: &'static str = ".so";
#[cfg(target_os = "macos")]
const DYLIB_EXTENSION: &'static str = ".dylib";
#[cfg(target_os = "windows")]
const DYLIB_EXTENSION: &'static str = ".dll";
#[cfg(not(any(feature = "threaded", feature = "threaded_l", feature = "threaded_debug")))]
const RTS: &'static str = "libHSrts-g";
#[cfg(feature = "threaded")]
const RTS: &'static str = "libHSrts_thr-";
#[cfg(feature = "threaded_l")]
const RTS: &'static str = "libHSrts_thr_l-";
#[cfg(feature = "threaded_debug")]
const RTS: &'static str = "libHSrts_thr_debug-";
fn main() {
match link_ghc_libs() {
Err(e) => panic!("Unable to link ghc_libs: {}", e),
Ok(_) => println!("cargo:rustc-link-search=native=htest"),
}
}
fn link_ghc_libs() -> io::Result<()> {
let builder = if command_ok(Command::new("stack").arg("--version")) {
"stack"
} else {
"cabal"
};
for entry in try!(read_dir(Path::new(&ghc(builder, "--print-libdir")))) {
let entry = try!(entry);
if try!(entry.metadata()).is_dir() {
for item in try!(read_dir(entry.path())) {
match (entry.path().to_str(), try!(item).file_name().to_str()) {
(Some(e),Some(i)) => {
if i.starts_with("lib") && i.ends_with(DYLIB_EXTENSION) {
if i.starts_with(RTS) ||
i.starts_with("libHSghc-") && !i.starts_with("libHSghc-boot-") ||
i.starts_with("libHSbase") ||
i.starts_with("libHSinteger-gmp") {
println!("cargo:rustc-link-search=native={}", e);
let temp = i.split_at(3).1;
let trimmed = temp.split_at(temp.len() - DYLIB_EXTENSION.len()).0;
println!("cargo:rustc-link-lib=dylib={}", trimmed);
}
}
},
_ => panic!("Unable to link ghc libs"),
}
}
}
}
Ok(())
}