extern crate pkg_config;
#[cfg(not(target_env = "msvc"))]
extern crate cmake;
use std::env;
use std::fmt;
enum LinkType {
Static,
Dynamic,
}
impl fmt::Display for LinkType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
&LinkType::Static => "static",
&LinkType::Dynamic => "dylib",
}
)
}
}
fn link_type_override() -> Option<LinkType> {
if env::var("CARGO_FEATURE_STATIC_ONIG").is_ok() {
return Some(LinkType::Static);
}
env::var("RUSTONIG_STATIC_LIBONIG").ok().map(|s| {
match &s.to_string().to_lowercase()[..] {
"0" | "no" | "false" => LinkType::Dynamic,
_ => LinkType::Static,
}
})
}
#[cfg(any(target_env = "musl", target_env = "msvc"))]
const DEFAULT_LINK_TYPE: LinkType = LinkType::Static;
#[cfg(not(any(target_env = "musl", target_env = "msvc")))]
const DEFAULT_LINK_TYPE: LinkType = LinkType::Dynamic;
#[cfg(not(target_env = "msvc"))]
fn compile(link_type: LinkType) {
use cmake::Config;
let mut c = Config::new("oniguruma");
let dst = match link_type {
LinkType::Static => c.define("BUILD_SHARED_LIBS", "OFF"),
LinkType::Dynamic => c.define("CMAKE_MACOSX_RPATH", "NO"),
}.build();
println!(
"cargo:rustc-link-search=native={}",
dst.join("build").to_string_lossy()
);
println!("cargo:rustc-link-lib={}=onig", link_type);
}
#[cfg(target_env = "msvc")]
fn compile(link_type: LinkType) {
use std::process::Command;
let onig_sys_dir = env::current_dir().unwrap();
let build_dir = env::var("OUT_DIR").unwrap();
let lib_name = match link_type {
LinkType::Static => "onig_s",
LinkType::Dynamic => "onig",
};
let bitness = if cfg!(target_pointer_width = "64") {
"64"
} else {
"32"
};
let cmd = format!("make_win{}.bat", bitness);
println!("{}", cmd);
let r = Command::new("cmd")
.args(&["/c", &(onig_sys_dir.join(cmd).to_string_lossy())])
.current_dir(&build_dir)
.env_remove("MFLAGS")
.env_remove("MAKEFLAGS")
.output()
.expect("error running build");
if !r.status.success() {
let err = String::from_utf8_lossy(&r.stderr);
let out = String::from_utf8_lossy(&r.stdout);
panic!("Build error:\nSTDERR:{}\nSTDOUT:{}", err, out);
}
println!("cargo:rustc-link-search=native={}", build_dir);
println!("cargo:rustc-link-lib={}={}", link_type, lib_name);
}
pub fn main() {
if let Ok(_) = pkg_config::find_library("oniguruma") {
return;
}
let link_type = link_type_override().unwrap_or(DEFAULT_LINK_TYPE);
compile(link_type);
}