#![allow(deprecated)]
#![allow(warnings)]
#[cfg(test)]
#[macro_use]
extern crate lazy_static;
#[allow(unused_imports)]
use std::ascii::AsciiExt;
use std::collections::BTreeMap;
use std::env;
use std::error;
use std::ffi::OsStr;
use std::fmt;
use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
#[derive(Default)]
pub struct Config {
cargo_metadata: bool,
emit_includes: bool,
required_libs: Vec<String>,
required_dlls: Vec<String>,
copy_dlls: bool,
vcpkg_root: Option<PathBuf>,
target: Option<TargetTriplet>,
}
#[derive(Debug)]
pub struct Library {
pub link_paths: Vec<PathBuf>,
pub dll_paths: Vec<PathBuf>,
pub include_paths: Vec<PathBuf>,
pub cargo_metadata: Vec<String>,
pub is_static: bool,
pub found_dlls: Vec<PathBuf>,
pub found_libs: Vec<PathBuf>,
pub found_names: Vec<String>,
pub ports: Vec<String>,
pub vcpkg_triplet: String,
}
#[derive(Clone)]
struct TargetTriplet {
triplet: String,
is_static: bool,
lib_suffix: String,
strip_lib_prefix: bool,
}
impl<S: AsRef<str>> From<S> for TargetTriplet {
fn from(triplet: S) -> TargetTriplet {
let triplet = triplet.as_ref();
if triplet.contains("windows") {
TargetTriplet {
triplet: triplet.into(),
is_static: triplet.contains("-static"),
lib_suffix: "lib".into(),
strip_lib_prefix: false,
}
} else {
TargetTriplet {
triplet: triplet.into(),
is_static: true,
lib_suffix: "a".into(),
strip_lib_prefix: true,
}
}
}
}
#[derive(Debug)]
pub enum Error {
DisabledByEnv(String),
RequiredEnvMissing(String),
NotMSVC,
VcpkgNotFound(String),
LibNotFound(String),
VcpkgInstallation(String),
#[doc(hidden)]
__Nonexhaustive,
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::DisabledByEnv(_) => "vcpkg-rs requested to be aborted",
Error::RequiredEnvMissing(_) => "a required env setting is missing",
Error::NotMSVC => "vcpkg-rs only can only find libraries for MSVC ABI builds",
Error::VcpkgNotFound(_) => "could not find Vcpkg tree",
Error::LibNotFound(_) => "could not find library in Vcpkg tree",
Error::VcpkgInstallation(_) => "could not look up details of packages in vcpkg tree",
Error::__Nonexhaustive => panic!(),
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Error::DisabledByEnv(ref name) => write!(f, "Aborted because {} is set", name),
Error::RequiredEnvMissing(ref name) => write!(f, "Aborted because {} is not set", name),
Error::NotMSVC => write!(
f,
"the vcpkg-rs Vcpkg build helper can only find libraries built for the MSVC ABI."
),
Error::VcpkgNotFound(ref detail) => write!(f, "Could not find Vcpkg tree: {}", detail),
Error::LibNotFound(ref detail) => {
write!(f, "Could not find library in Vcpkg tree {}", detail)
}
Error::VcpkgInstallation(ref detail) => write!(
f,
"Could not look up details of packages in vcpkg tree {}",
detail
),
Error::__Nonexhaustive => panic!(),
}
}
}
#[doc(hidden)]
pub fn probe_package(name: &str) -> Result<Library, Error> {
Config::new().probe(name)
}
pub fn find_package(package: &str) -> Result<Library, Error> {
Config::new().find_package(package)
}
#[doc(hidden)]
pub fn find_vcpkg_root(cfg: &Config) -> Result<PathBuf, Error> {
if let &Some(ref path) = &cfg.vcpkg_root {
return Ok(path.clone());
}
if let Some(path) = env::var_os("VCPKG_ROOT") {
return Ok(PathBuf::from(path));
}
if let Ok(ref local_app_data) = env::var("LOCALAPPDATA") {
let vcpkg_user_targets_path = Path::new(local_app_data.as_str())
.join("vcpkg")
.join("vcpkg.user.targets");
if let Ok(file) = File::open(vcpkg_user_targets_path.clone()) {
let file = BufReader::new(&file);
for line in file.lines() {
let line = try!(line.map_err(|_| Error::VcpkgNotFound(format!(
"Parsing of {} failed.",
vcpkg_user_targets_path.to_string_lossy().to_owned()
))));
let mut split = line.split("Project=\"");
split.next();
if let Some(found) = split.next() {
if let Some(found) = found.split_terminator('"').next() {
let mut vcpkg_root = PathBuf::from(found);
if !(vcpkg_root.pop()
&& vcpkg_root.pop()
&& vcpkg_root.pop()
&& vcpkg_root.pop())
{
return Err(Error::VcpkgNotFound(format!(
"Could not find vcpkg root above {}",
found
)));
}
return Ok(vcpkg_root);
}
}
}
}
}
if let Some(path) = env::var_os("OUT_DIR") {
let mut path = PathBuf::from(path);
while path.pop() {
let mut try_root = path.clone();
try_root.push("vcpkg");
try_root.push(".vcpkg-root");
if try_root.exists() {
try_root.pop();
let mut cv_cfg = try_root.clone();
cv_cfg.push("downloads");
cv_cfg.push("cargo-vcpkg.toml");
if cv_cfg.exists() {
return Ok(try_root);
}
}
}
}
Err(Error::VcpkgNotFound(
"No vcpkg installation found. Set the VCPKG_ROOT environment \
variable or run 'vcpkg integrate install'"
.to_string(),
))
}
fn validate_vcpkg_root(path: &PathBuf) -> Result<(), Error> {
let mut vcpkg_root_path = path.clone();
vcpkg_root_path.push(".vcpkg-root");
if vcpkg_root_path.exists() {
Ok(())
} else {
Err(Error::VcpkgNotFound(format!(
"Could not find Vcpkg root at {}",
vcpkg_root_path.to_string_lossy()
)))
}
}
fn find_vcpkg_target(cfg: &Config, target_triplet: &TargetTriplet) -> Result<VcpkgTarget, Error> {
let vcpkg_root = try!(find_vcpkg_root(&cfg));
try!(validate_vcpkg_root(&vcpkg_root));
let mut base = vcpkg_root;
base.push("installed");
let status_path = base.join("vcpkg");
base.push(&target_triplet.triplet);
let lib_path = base.join("lib");
let bin_path = base.join("bin");
let include_path = base.join("include");
Ok(VcpkgTarget {
vcpkg_triplet: target_triplet.triplet.to_owned(),
lib_path: lib_path,
bin_path: bin_path,
include_path: include_path,
is_static: target_triplet.is_static,
status_path: status_path,
lib_suffix: target_triplet.lib_suffix.to_owned(),
strip_lib_prefix: target_triplet.strip_lib_prefix,
})
}
#[derive(Clone, Debug)]
struct Port {
dlls: Vec<String>,
libs: Vec<String>,
deps: Vec<String>,
}
fn load_port_manifest(
path: &PathBuf,
port: &str,
version: &str,
vcpkg_target: &VcpkgTarget,
) -> Result<(Vec<String>, Vec<String>), Error> {
let manifest_file = path.join("info").join(format!(
"{}_{}_{}.list",
port, version, vcpkg_target.vcpkg_triplet
));
let mut dlls = Vec::new();
let mut libs = Vec::new();
let f = try!(
File::open(&manifest_file).map_err(|_| Error::VcpkgInstallation(format!(
"Could not open port manifest file {}",
manifest_file.display()
)))
);
let file = BufReader::new(&f);
let dll_prefix = Path::new(&vcpkg_target.vcpkg_triplet).join("bin");
let lib_prefix = Path::new(&vcpkg_target.vcpkg_triplet).join("lib");
for line in file.lines() {
let line = line.unwrap();
let file_path = Path::new(&line);
if let Ok(dll) = file_path.strip_prefix(&dll_prefix) {
if dll.extension() == Some(OsStr::new("dll"))
&& dll.components().collect::<Vec<_>>().len() == 1
{
dll.to_str().map(|s| dlls.push(s.to_owned()));
}
} else if let Ok(lib) = file_path.strip_prefix(&lib_prefix) {
if lib.extension() == Some(OsStr::new(&vcpkg_target.lib_suffix))
&& lib.components().collect::<Vec<_>>().len() == 1
{
if let Some(lib) = vcpkg_target.link_name_for_lib(lib) {
libs.push(lib);
}
}
}
}
Ok((dlls, libs))
}
fn load_port_file(
filename: &PathBuf,
port_info: &mut Vec<BTreeMap<String, String>>,
) -> Result<(), Error> {
let f = try!(
File::open(&filename).map_err(|e| Error::VcpkgInstallation(format!(
"Could not open status file at {}: {}",
filename.display(),
e
)))
);
let file = BufReader::new(&f);
let mut current: BTreeMap<String, String> = BTreeMap::new();
for line in file.lines() {
let line = line.unwrap();
let parts = line.splitn(2, ": ").clone().collect::<Vec<_>>();
if parts.len() == 2 {
current.insert(parts[0].trim().into(), parts[1].trim().into());
} else if line.len() == 0 {
port_info.push(current.clone());
current.clear();
} else {
}
}
if !current.is_empty() {
port_info.push(current);
}
Ok(())
}
fn load_ports(target: &VcpkgTarget) -> Result<BTreeMap<String, Port>, Error> {
let mut ports: BTreeMap<String, Port> = BTreeMap::new();
let mut port_info: Vec<BTreeMap<String, String>> = Vec::new();
let status_filename = target.status_path.join("status");
load_port_file(&status_filename, &mut port_info).ok();
let status_update_dir = target.status_path.join("updates");
let paths = try!(
fs::read_dir(status_update_dir).map_err(|e| Error::VcpkgInstallation(format!(
"could not read status file updates dir: {}",
e
)))
);
let mut paths = try!(paths
.map(|rde| rde.map(|de| de.path()))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| {
Error::VcpkgInstallation(format!(
"could not read status file update filenames: {}",
e
))
}));
paths.sort();
for path in paths {
try!(load_port_file(&path, &mut port_info));
}
let mut seen_names = BTreeMap::new();
for current in &port_info {
match (
current.get("Package"),
current.get("Architecture"),
current.get("Feature"),
) {
(Some(pkg), Some(arch), feature) => {
seen_names.insert((pkg, arch, feature), current);
}
_ => {}
}
}
for (&(name, arch, feature), current) in &seen_names {
if **arch == target.vcpkg_triplet {
let mut deps = if let Some(deps) = current.get("Depends") {
deps.split(", ").map(|x| x.to_owned()).collect()
} else {
Vec::new()
};
if current
.get("Status")
.unwrap_or(&String::new())
.ends_with(" installed")
{
match (current.get("Version"), feature) {
(Some(version), _) => {
let lib_info = try!(load_port_manifest(
&target.status_path,
&name,
version,
&target
));
let port = Port {
dlls: lib_info.0,
libs: lib_info.1,
deps: deps,
};
ports.insert(name.to_string(), port);
}
(_, Some(_feature)) => match ports.get_mut(name) {
Some(ref mut port) => {
port.deps.append(&mut deps);
}
_ => {
println!("found a feature that had no corresponding port :-");
println!("current {:+?}", current);
continue;
}
},
(_, _) => {
println!("didn't know how to deal with status file entry :-");
println!("{:+?}", current);
continue;
}
}
}
}
}
Ok(ports)
}
struct VcpkgTarget {
vcpkg_triplet: String,
lib_path: PathBuf,
bin_path: PathBuf,
include_path: PathBuf,
status_path: PathBuf,
is_static: bool,
lib_suffix: String,
strip_lib_prefix: bool,
}
impl VcpkgTarget {
fn link_name_for_lib(&self, filename: &std::path::Path) -> Option<String> {
if self.strip_lib_prefix {
filename.to_str().map(|s| s.to_owned())
} else {
filename.to_str().map(|s| s.to_owned())
}
}
}
impl Config {
pub fn new() -> Config {
Config {
cargo_metadata: true,
copy_dlls: true,
..Default::default()
}
}
fn get_target_triplet(&mut self) -> Result<TargetTriplet, Error> {
if self.target.is_none() {
let target = if let Ok(triplet_str) = env::var("VCPKGRS_TRIPLET") {
triplet_str.into()
} else {
try!(msvc_target())
};
self.target = Some(target);
}
Ok(self.target.as_ref().unwrap().clone())
}
pub fn find_package(&mut self, port_name: &str) -> Result<Library, Error> {
let msvc_target = try!(self.get_target_triplet());
if env::var_os("VCPKGRS_DISABLE").is_some() {
return Err(Error::DisabledByEnv("VCPKGRS_DISABLE".to_owned()));
}
if env::var_os("NO_VCPKG").is_some() {
return Err(Error::DisabledByEnv("NO_VCPKG".to_owned()));
}
let abort_var_name = format!("VCPKGRS_NO_{}", envify(port_name));
if env::var_os(&abort_var_name).is_some() {
return Err(Error::DisabledByEnv(abort_var_name));
}
let abort_var_name = format!("{}_NO_VCPKG", envify(port_name));
if env::var_os(&abort_var_name).is_some() {
return Err(Error::DisabledByEnv(abort_var_name));
}
let vcpkg_target = try!(find_vcpkg_target(&self, &msvc_target));
let mut required_port_order = Vec::new();
if self.required_libs.is_empty() {
let ports = try!(load_ports(&vcpkg_target));
if ports.get(&port_name.to_owned()).is_none() {
return Err(Error::LibNotFound(format!(
"package {} is not installed for vcpkg triplet {}",
port_name.to_owned(),
vcpkg_target.vcpkg_triplet
)));
}
let mut required_ports: BTreeMap<String, Port> = BTreeMap::new();
let mut ports_to_scan = vec![port_name.to_owned()];
while !ports_to_scan.is_empty() {
let port_name = ports_to_scan.pop().unwrap();
if required_ports.contains_key(&port_name) {
continue;
}
if let Some(port) = ports.get(&port_name) {
for dep in &port.deps {
ports_to_scan.push(dep.clone());
}
required_ports.insert(port_name.clone(), (*port).clone());
remove_item(&mut required_port_order, &port_name);
required_port_order.push(port_name);
} else {
}
}
if self.required_libs.is_empty() {
for port_name in &required_port_order {
let port = required_ports.get(port_name).unwrap();
self.required_libs.extend(port.libs.iter().map(|s| {
Path::new(&s)
.file_stem()
.unwrap()
.to_string_lossy()
.into_owned()
}));
self.required_dlls
.extend(port.dlls.iter().cloned().map(|s| {
Path::new(&s)
.file_stem()
.unwrap()
.to_string_lossy()
.into_owned()
}));
}
}
}
if !vcpkg_target.is_static && !env::var_os("VCPKGRS_DYNAMIC").is_some() {
return Err(Error::RequiredEnvMissing("VCPKGRS_DYNAMIC".to_owned()));
}
let mut lib = Library::new(vcpkg_target.is_static, &vcpkg_target.vcpkg_triplet);
if self.emit_includes {
lib.cargo_metadata.push(format!(
"cargo:include={}",
vcpkg_target.include_path.display()
));
}
lib.include_paths.push(vcpkg_target.include_path.clone());
lib.cargo_metadata.push(format!(
"cargo:rustc-link-search=native={}",
vcpkg_target
.lib_path
.to_str()
.expect("failed to convert string type")
));
lib.link_paths.push(vcpkg_target.lib_path.clone());
if !vcpkg_target.is_static {
lib.cargo_metadata.push(format!(
"cargo:rustc-link-search=native={}",
vcpkg_target
.bin_path
.to_str()
.expect("failed to convert string type")
));
lib.dll_paths.push(vcpkg_target.bin_path.clone());
}
lib.ports = required_port_order;
try!(self.emit_libs(&mut lib, &vcpkg_target));
if self.copy_dlls {
try!(self.do_dll_copy(&mut lib));
}
if self.cargo_metadata {
for line in &lib.cargo_metadata {
println!("{}", line);
}
}
Ok(lib)
}
pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
self.cargo_metadata = cargo_metadata;
self
}
pub fn emit_includes(&mut self, emit_includes: bool) -> &mut Config {
self.emit_includes = emit_includes;
self
}
pub fn copy_dlls(&mut self, copy_dlls: bool) -> &mut Config {
self.copy_dlls = copy_dlls;
self
}
pub fn vcpkg_root(&mut self, vcpkg_root: PathBuf) -> &mut Config {
self.vcpkg_root = Some(vcpkg_root);
self
}
pub fn target_triplet<S: AsRef<str>>(&mut self, triplet: S) -> &mut Config {
self.target = Some(triplet.into());
self
}
#[doc(hidden)]
pub fn probe(&mut self, port_name: &str) -> Result<Library, Error> {
let msvc_target = try!(self.get_target_triplet());
if env::var_os("VCPKGRS_DISABLE").is_some() {
return Err(Error::DisabledByEnv("VCPKGRS_DISABLE".to_owned()));
}
if env::var_os("NO_VCPKG").is_some() {
return Err(Error::DisabledByEnv("NO_VCPKG".to_owned()));
}
let abort_var_name = format!("VCPKGRS_NO_{}", envify(port_name));
if env::var_os(&abort_var_name).is_some() {
return Err(Error::DisabledByEnv(abort_var_name));
}
let abort_var_name = format!("{}_NO_VCPKG", envify(port_name));
if env::var_os(&abort_var_name).is_some() {
return Err(Error::DisabledByEnv(abort_var_name));
}
if self.required_libs.is_empty() {
self.required_libs.push(port_name.to_owned());
self.required_dlls.push(port_name.to_owned());
}
let vcpkg_target = try!(find_vcpkg_target(&self, &msvc_target));
if !vcpkg_target.is_static && !env::var_os("VCPKGRS_DYNAMIC").is_some() {
return Err(Error::RequiredEnvMissing("VCPKGRS_DYNAMIC".to_owned()));
}
let mut lib = Library::new(vcpkg_target.is_static, &vcpkg_target.vcpkg_triplet);
if self.emit_includes {
lib.cargo_metadata.push(format!(
"cargo:include={}",
vcpkg_target.include_path.display()
));
}
lib.include_paths.push(vcpkg_target.include_path.clone());
lib.cargo_metadata.push(format!(
"cargo:rustc-link-search=native={}",
vcpkg_target
.lib_path
.to_str()
.expect("failed to convert string type")
));
lib.link_paths.push(vcpkg_target.lib_path.clone());
if !vcpkg_target.is_static {
lib.cargo_metadata.push(format!(
"cargo:rustc-link-search=native={}",
vcpkg_target
.bin_path
.to_str()
.expect("failed to convert string type")
));
lib.dll_paths.push(vcpkg_target.bin_path.clone());
}
try!(self.emit_libs(&mut lib, &vcpkg_target));
if self.copy_dlls {
try!(self.do_dll_copy(&mut lib));
}
if self.cargo_metadata {
for line in &lib.cargo_metadata {
println!("{}", line);
}
}
Ok(lib)
}
fn emit_libs(&mut self, lib: &mut Library, vcpkg_target: &VcpkgTarget) -> Result<(), Error> {
for required_lib in &self.required_libs {
let link_name = match vcpkg_target.strip_lib_prefix {
true => required_lib.trim_left_matches("lib"),
false => required_lib,
};
lib.cargo_metadata
.push(format!("cargo:rustc-link-lib={}", link_name));
lib.found_names.push(String::from(link_name));
let mut lib_location = vcpkg_target.lib_path.clone();
lib_location.push(required_lib.clone() + "." + &vcpkg_target.lib_suffix);
if !lib_location.exists() {
return Err(Error::LibNotFound(lib_location.display().to_string()));
}
lib.found_libs.push(lib_location);
}
if !vcpkg_target.is_static {
for required_dll in &self.required_dlls {
let mut dll_location = vcpkg_target.bin_path.clone();
dll_location.push(required_dll.clone() + ".dll");
if !dll_location.exists() {
return Err(Error::LibNotFound(dll_location.display().to_string()));
}
lib.found_dlls.push(dll_location);
}
}
Ok(())
}
fn do_dll_copy(&mut self, lib: &mut Library) -> Result<(), Error> {
if let Some(target_dir) = env::var_os("OUT_DIR") {
if !lib.found_dlls.is_empty() {
for file in &lib.found_dlls {
let mut dest_path = Path::new(target_dir.as_os_str()).to_path_buf();
dest_path.push(Path::new(file.file_name().unwrap()));
try!(
fs::copy(file, &dest_path).map_err(|_| Error::LibNotFound(format!(
"Can't copy file {} to {}",
file.to_string_lossy(),
dest_path.to_string_lossy()
)))
);
println!(
"vcpkg build helper copied {} to {}",
file.to_string_lossy(),
dest_path.to_string_lossy()
);
}
lib.cargo_metadata.push(format!(
"cargo:rustc-link-search=native={}",
env::var("OUT_DIR").unwrap()
));
lib.cargo_metadata.push(format!(
"cargo:rustc-link-search={}",
env::var("OUT_DIR").unwrap()
));
}
} else {
return Err(Error::LibNotFound("Unable to get OUT_DIR".to_owned()));
}
Ok(())
}
pub fn lib_name(&mut self, lib_stem: &str) -> &mut Config {
self.required_libs.push(lib_stem.to_owned());
self.required_dlls.push(lib_stem.to_owned());
self
}
pub fn lib_names(&mut self, lib_stem: &str, dll_stem: &str) -> &mut Config {
self.required_libs.push(lib_stem.to_owned());
self.required_dlls.push(dll_stem.to_owned());
self
}
}
fn remove_item(cont: &mut Vec<String>, item: &String) -> Option<String> {
match cont.iter().position(|x| *x == *item) {
Some(pos) => Some(cont.remove(pos)),
None => None,
}
}
impl Library {
fn new(is_static: bool, vcpkg_triplet: &str) -> Library {
Library {
link_paths: Vec::new(),
dll_paths: Vec::new(),
include_paths: Vec::new(),
cargo_metadata: Vec::new(),
is_static: is_static,
found_dlls: Vec::new(),
found_libs: Vec::new(),
found_names: Vec::new(),
ports: Vec::new(),
vcpkg_triplet: vcpkg_triplet.to_string(),
}
}
}
fn envify(name: &str) -> String {
name.chars()
.map(|c| c.to_ascii_uppercase())
.map(|c| if c == '-' { '_' } else { c })
.collect()
}
fn msvc_target() -> Result<TargetTriplet, Error> {
let is_definitely_dynamic = env::var("VCPKGRS_DYNAMIC").is_ok();
let target = env::var("TARGET").unwrap_or(String::new());
let is_static = env::var("CARGO_CFG_TARGET_FEATURE")
.unwrap_or(String::new())
.contains("crt-static");
if target == "x86_64-apple-darwin" {
Ok(TargetTriplet {
triplet: "x64-osx".into(),
is_static: true,
lib_suffix: "a".into(),
strip_lib_prefix: true,
})
} else if target == "aarch64-apple-darwin" {
Ok(TargetTriplet {
triplet: "arm64-osx".into(),
is_static: true,
lib_suffix: "a".into(),
strip_lib_prefix: true,
})
} else if target == "x86_64-unknown-linux-gnu" {
Ok(TargetTriplet {
triplet: "x64-linux".into(),
is_static: true,
lib_suffix: "a".into(),
strip_lib_prefix: true,
})
} else if target == "aarch64-apple-ios" {
Ok(TargetTriplet {
triplet: "arm64-ios".into(),
is_static: true,
lib_suffix: "a".into(),
strip_lib_prefix: true,
})
} else if !target.contains("-pc-windows-msvc") {
Err(Error::NotMSVC)
} else if target.starts_with("x86_64-") {
if is_static {
Ok(TargetTriplet {
triplet: "x64-windows-static".into(),
is_static: true,
lib_suffix: "lib".into(),
strip_lib_prefix: false,
})
} else if is_definitely_dynamic {
Ok(TargetTriplet {
triplet: "x64-windows".into(),
is_static: false,
lib_suffix: "lib".into(),
strip_lib_prefix: false,
})
} else {
Ok(TargetTriplet {
triplet: "x64-windows-static-md".into(),
is_static: true,
lib_suffix: "lib".into(),
strip_lib_prefix: false,
})
}
} else {
if is_static {
Ok(TargetTriplet {
triplet: "x86-windows-static".into(),
is_static: true,
lib_suffix: "lib".into(),
strip_lib_prefix: false,
})
} else if is_definitely_dynamic {
Ok(TargetTriplet {
triplet: "x86-windows".into(),
is_static: false,
lib_suffix: "lib".into(),
strip_lib_prefix: false,
})
} else {
Ok(TargetTriplet {
triplet: "x86-windows-static-md".into(),
is_static: true,
lib_suffix: "lib".into(),
strip_lib_prefix: false,
})
}
}
}
#[cfg(test)]
mod tests {
extern crate tempdir;
use super::*;
use std::env;
use std::sync::Mutex;
lazy_static! {
static ref LOCK: Mutex<()> = Mutex::new(());
}
#[test]
fn do_nothing_for_unsupported_target() {
let _g = LOCK.lock();
env::set_var("VCPKG_ROOT", "/");
env::set_var("TARGET", "x86_64-pc-windows-gnu");
assert!(match ::probe_package("foo") {
Err(Error::NotMSVC) => true,
_ => false,
});
env::set_var("TARGET", "x86_64-pc-windows-gnu");
assert_eq!(env::var("TARGET"), Ok("x86_64-pc-windows-gnu".to_string()));
assert!(match ::probe_package("foo") {
Err(Error::NotMSVC) => true,
_ => false,
});
env::remove_var("TARGET");
env::remove_var("VCPKG_ROOT");
}
#[test]
fn do_nothing_for_bailout_variables_set() {
let _g = LOCK.lock();
env::set_var("VCPKG_ROOT", "/");
env::set_var("TARGET", "x86_64-pc-windows-msvc");
for &var in &[
"VCPKGRS_DISABLE",
"VCPKGRS_NO_FOO",
"FOO_NO_VCPKG",
"NO_VCPKG",
] {
env::set_var(var, "1");
assert!(match ::probe_package("foo") {
Err(Error::DisabledByEnv(ref v)) if v == var => true,
_ => false,
});
env::remove_var(var);
}
env::remove_var("TARGET");
env::remove_var("VCPKG_ROOT");
}
#[test]
fn static_build_finds_lib() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
env::set_var("TARGET", "x86_64-pc-windows-msvc");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
env::set_var("CARGO_CFG_TARGET_FEATURE", "crt-static");
println!("Result is {:?}", ::find_package("libmysql"));
assert!(match ::find_package("libmysql") {
Ok(_) => true,
_ => false,
});
clean_env();
}
#[test]
fn dynamic_build_finds_lib() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("no-status"));
env::set_var("TARGET", "x86_64-pc-windows-msvc");
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
println!("Result is {:?}", ::find_package("libmysql"));
assert!(match ::find_package("libmysql") {
Ok(_) => true,
_ => false,
});
clean_env();
}
#[test]
fn handle_multiline_description() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("multiline-description"));
env::set_var("TARGET", "i686-pc-windows-msvc");
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
println!("Result is {:?}", ::find_package("graphite2"));
assert!(match ::find_package("graphite2") {
Ok(_) => true,
_ => false,
});
clean_env();
}
#[test]
fn link_libs_required_by_optional_features() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
env::set_var("TARGET", "i686-pc-windows-msvc");
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
println!("Result is {:?}", ::find_package("harfbuzz"));
assert!(match ::find_package("harfbuzz") {
Ok(lib) => lib
.cargo_metadata
.iter()
.find(|&x| x == "cargo:rustc-link-lib=icuuc")
.is_some(),
_ => false,
});
clean_env();
}
#[test]
fn link_lib_name_is_correct() {
let _g = LOCK.lock();
for target in &[
"x86_64-apple-darwin",
"i686-pc-windows-msvc",
] {
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
env::set_var("TARGET", target);
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
println!("Result is {:?}", ::find_package("harfbuzz"));
assert!(match ::find_package("harfbuzz") {
Ok(lib) => lib
.cargo_metadata
.iter()
.find(|&x| x == "cargo:rustc-link-lib=harfbuzz")
.is_some(),
_ => false,
});
clean_env();
}
}
#[test]
fn link_dependencies_after_port() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
env::set_var("TARGET", "i686-pc-windows-msvc");
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
let lib = ::find_package("harfbuzz").unwrap();
check_before(&lib, "freetype", "zlib");
check_before(&lib, "freetype", "bzip2");
check_before(&lib, "freetype", "libpng");
check_before(&lib, "harfbuzz", "freetype");
check_before(&lib, "harfbuzz", "ragel");
check_before(&lib, "libpng", "zlib");
clean_env();
fn check_before(lib: &Library, earlier: &str, later: &str) {
match (
lib.ports.iter().position(|x| *x == *earlier),
lib.ports.iter().position(|x| *x == *later),
) {
(Some(earlier_pos), Some(later_pos)) if earlier_pos < later_pos => {
}
_ => {
println!(
"earlier: {}, later: {}\nLibrary found: {:#?}",
earlier, later, lib
);
panic!();
}
}
}
}
#[test]
fn custom_target_triplet_in_config() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
env::set_var("TARGET", "aarch64-apple-ios");
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
let harfbuzz = ::Config::new()
.target_triplet("x64-osx")
.find_package("harfbuzz");
println!("Result with specifying target triplet is {:?}", &harfbuzz);
let harfbuzz = harfbuzz.unwrap();
assert_eq!(harfbuzz.vcpkg_triplet, "x64-osx");
clean_env();
}
#[test]
fn custom_target_triplet_by_env_no_default() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
env::set_var("TARGET", "aarch64-apple-doesnotexist");
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
let harfbuzz = ::find_package("harfbuzz");
println!("Result with inference is {:?}", &harfbuzz);
assert!(harfbuzz.is_err());
env::set_var("VCPKGRS_TRIPLET", "x64-osx");
let harfbuzz = ::find_package("harfbuzz").unwrap();
println!("Result with setting VCPKGRS_TRIPLET is {:?}", &harfbuzz);
assert_eq!(harfbuzz.vcpkg_triplet, "x64-osx");
clean_env();
}
#[test]
fn custom_target_triplet_by_env_with_default() {
let _g = LOCK.lock();
clean_env();
env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
env::set_var("TARGET", "aarch64-apple-ios");
env::set_var("VCPKGRS_DYNAMIC", "1");
let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
env::set_var("OUT_DIR", tmp_dir.path());
let harfbuzz = ::find_package("harfbuzz").unwrap();
println!("Result with inference is {:?}", &harfbuzz);
assert_eq!(harfbuzz.vcpkg_triplet, "arm64-ios");
env::set_var("VCPKGRS_TRIPLET", "x64-osx");
let harfbuzz = ::find_package("harfbuzz").unwrap();
println!("Result with setting VCPKGRS_TRIPLET is {:?}", &harfbuzz);
assert_eq!(harfbuzz.vcpkg_triplet, "x64-osx");
clean_env();
}
fn clean_env() {
env::remove_var("TARGET");
env::remove_var("VCPKG_ROOT");
env::remove_var("VCPKGRS_DYNAMIC");
env::remove_var("RUSTFLAGS");
env::remove_var("CARGO_CFG_TARGET_FEATURE");
env::remove_var("VCPKGRS_DISABLE");
env::remove_var("VCPKGRS_NO_LIBMYSQL");
env::remove_var("VCPKGRS_TRIPLET");
}
fn vcpkg_test_tree_loc(name: &str) -> PathBuf {
let mut path = PathBuf::new();
path.push(env::var("CARGO_MANIFEST_DIR").unwrap());
path.pop();
path.push("test-data");
path.push(name);
path
}
}