Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! A build dependency for Cargo libraries to find libraries in a
2 //! [Vcpkg](https://github.com/Microsoft/vcpkg) tree. From a Vcpkg package name
3 //! this build helper will emit cargo metadata to link it and it's dependencies
4 //! (excluding system libraries, which it cannot derive).
5 //!
6 //! **Note:** You must set one of `RUSTFLAGS=-Ctarget-feature=+crt-static` or
7 //! `VCPKGRS_DYNAMIC=1` in your environment or the vcpkg-rs helper
8 //! will not find any libraries. If `VCPKGRS_DYNAMIC` is set, `cargo install` will
9 //! generate dynamically linked binaries, in which case you will have to arrange for
10 //! dlls from your Vcpkg installation to be available in your path.
11 //!
12 //! The simplest possible usage looks like this :-
13 //!
14 //! ```rust,no_run
15 //! vcpkg::find_package("libssh2").unwrap();
16 //! ```
17 //!
18 //! The cargo metadata that is emitted can be changed like this :-
19 //!
20 //! ```rust,no_run
21 //! vcpkg::Config::new()
22 //! .emit_includes(true)
23 //! .find_package("zlib").unwrap();
24 //! ```
25 //!
26 //! If the search was successful all appropriate Cargo metadata will be printed
27 //! to stdout.
28 //!
29 //! The decision to choose static variants of libraries is driven by adding
30 //! `RUSTFLAGS=-Ctarget-feature=+crt-static` to the environment. This requires
31 //! at least Rust 1.19.
32 //!
33 //! A number of environment variables are available to globally configure which
34 //! libraries are selected.
35 //!
36 //! * `VCPKG_ROOT` - Set the directory to look in for a vcpkg installation. If
37 //! it is not set, vcpkg will use the user-wide installation if one has been
38 //! set up with `vcpkg integrate install`
39 //!
40 //! * `VCPKGRS_NO_FOO` - if set, vcpkg-rs will not attempt to find the
41 //! library named `foo`.
42 //!
43 //! * `VCPKGRS_DISABLE` - if set, vcpkg-rs will not attempt to find any libraries.
44 //!
45 //! * `VCPKGRS_DYNAMIC` - if set, vcpkg-rs will link to DLL builds of ports.
46 //!
47 //! There is a companion crate `vcpkg_cli` that allows testing of environment
48 //! and flag combinations.
49 //!
50 //! ```Batchfile
51 //! C:\src> vcpkg_cli probe -l static mysqlclient
52 //! Found library mysqlclient
53 //! Include paths:
54 //! C:\src\[..]\vcpkg\installed\x64-windows-static\include
55 //! Library paths:
56 //! C:\src\[..]\vcpkg\installed\x64-windows-static\lib
57 //! Cargo metadata:
58 //! cargo:rustc-link-search=native=C:\src\[..]\vcpkg\installed\x64-windows-static\lib
59 //! cargo:rustc-link-lib=static=mysqlclient
60 //! ```
61
62 // The CI will test vcpkg-rs on 1.10 because at this point rust-openssl's
63 // openssl-sys is backward compatible that far. (Actually, the oldest release
64 // crate openssl version 0.10 seems to build against is now Rust 1.24.1?)
65 #![allow(deprecated)]
66
67 #[cfg(test)]
68 #[macro_use]
69 extern crate lazy_static;
70
71 #[allow(unused_imports)]
72 use std::ascii::AsciiExt;
73
74 use std::collections::BTreeMap;
75 use std::env;
76 use std::error;
77 use std::ffi::OsStr;
78 use std::fmt;
79 use std::fs::{self, File};
80 use std::io::{BufRead, BufReader};
81 use std::path::{Path, PathBuf};
82
83 #[derive(Default)]
84 pub struct Config {
85 /// should the cargo metadata actually be emitted
86 cargo_metadata: bool,
87
88 /// should cargo:include= metadata be emitted (defaults to false)
89 emit_includes: bool,
90
91 /// .lib/.a files that must be be found for probing to be considered successful
92 required_libs: Vec<String>,
93
94 /// .dlls that must be be found for probing to be considered successful
95 required_dlls: Vec<String>,
96
97 /// should DLLs be copies to OUT_DIR?
98 copy_dlls: bool,
99
100 /// override VCPKG_ROOT environment variable
101 vcpkg_root: Option<PathBuf>,
102 }
103
104 /// Details of a package that was found
105 #[derive(Debug)]
106 pub struct Library {
107 /// Paths for the linker to search for static or import libraries
108 pub link_paths: Vec<PathBuf>,
109
110 /// Paths to search at runtme to find DLLs
111 pub dll_paths: Vec<PathBuf>,
112
113 /// Paths to search for
114 pub include_paths: Vec<PathBuf>,
115
116 /// cargo: metadata lines
117 pub cargo_metadata: Vec<String>,
118
119 /// libraries found are static
120 pub is_static: bool,
121
122 /// DLLs found
123 pub found_dlls: Vec<PathBuf>,
124
125 /// static libs or import libs found
126 pub found_libs: Vec<PathBuf>,
127
128 /// link name of libraries found, this is useful to emit linker commands
129 pub found_names: Vec<String>,
130
131 /// ports that are providing the libraries to link to, in port link order
132 pub ports: Vec<String>,
133 }
134
135 enum MSVCTarget {
136 X86Windows,
137 X64Windows,
138 X64Linux,
139 X64MacOS,
140 }
141
142 impl fmt::Display for MSVCTarget {
143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144 match *self {
145 MSVCTarget::X86Windows => write!(f, "x86-windows"),
146 MSVCTarget::X64Windows => write!(f, "x64-windows"),
147 MSVCTarget::X64Linux => write!(f, "x64-linux"),
148 MSVCTarget::X64MacOS => write!(f, "x64-osx"),
149 }
150 }
151 }
152
153 #[derive(Debug)] // need Display?
154 pub enum Error {
155 /// Aborted because of a `VCPKGRS_NO_*` environment variable.
156 ///
157 /// Contains the name of the responsible environment variable.
158 DisabledByEnv(String),
159
160 /// Aborted because a required environment variable was not set.
161 RequiredEnvMissing(String),
162
163 /// On Windows, only MSVC ABI is supported
164 NotMSVC,
165
166 /// Can't find a vcpkg tree
167 VcpkgNotFound(String),
168
169 /// Library not found in vcpkg tree
170 LibNotFound(String),
171
172 /// Could not understand vcpkg installation
173 VcpkgInstallation(String),
174
175 #[doc(hidden)]
176 __Nonexhaustive,
177 }
178
179 impl error::Error for Error {
180 fn description(&self) -> &str {
181 match *self {
182 Error::DisabledByEnv(_) => "vcpkg-rs requested to be aborted",
183 Error::RequiredEnvMissing(_) => "a required env setting is missing",
184 Error::NotMSVC => "vcpkg-rs only can only find libraries for MSVC ABI 64 bit builds",
185 Error::VcpkgNotFound(_) => "could not find Vcpkg tree",
186 Error::LibNotFound(_) => "could not find library in Vcpkg tree",
187 Error::VcpkgInstallation(_) => "could not look up details of packages in vcpkg tree",
188 Error::__Nonexhaustive => panic!(),
189 }
190 }
191
192 fn cause(&self) -> Option<&error::Error> {
193 match *self {
194 // Error::Command { ref cause, .. } => Some(cause),
195 _ => None,
196 }
197 }
198 }
199
200 impl fmt::Display for Error {
201 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
202 match *self {
203 Error::DisabledByEnv(ref name) => write!(f, "Aborted because {} is set", name),
204 Error::RequiredEnvMissing(ref name) => write!(f, "Aborted because {} is not set", name),
205 Error::NotMSVC => write!(
206 f,
207 "the vcpkg-rs Vcpkg build helper can only find libraries built for the MSVC ABI."
208 ),
209 Error::VcpkgNotFound(ref detail) => write!(f, "Could not find Vcpkg tree: {}", detail),
210 Error::LibNotFound(ref detail) => {
211 write!(f, "Could not find library in Vcpkg tree {}", detail)
212 }
213 Error::VcpkgInstallation(ref detail) => write!(
214 f,
215 "Could not look up details of packages in vcpkg tree {}",
216 detail
217 ),
218 Error::__Nonexhaustive => panic!(),
219 }
220 }
221 }
222
223 /// Deprecated in favor of the find_package function
224 #[doc(hidden)]
225 pub fn probe_package(name: &str) -> Result<Library, Error> {
226 Config::new().probe(name)
227 }
228
229 /// Find the package `package` in a Vcpkg tree.
230 ///
231 /// Emits cargo metadata to link to libraries provided by the Vcpkg package/port
232 /// named, and any (non-system) libraries that they depend on.
233 ///
234 /// This will select the architecture and linkage based on environment
235 /// variables and build flags as described in the module docs.
236 pub fn find_package(package: &str) -> Result<Library, Error> {
237 Config::new().find_package(package)
238 }
239
240 fn find_vcpkg_root(cfg: &Config) -> Result<PathBuf, Error> {
241 // prefer the setting from the use if there is one
242 if let &Some(ref path) = &cfg.vcpkg_root {
243 return Ok(path.clone());
244 }
245
246 // otherwise, use the setting from the environment
247 if let Some(path) = env::var_os("VCPKG_ROOT") {
248 return Ok(PathBuf::from(path));
249 }
250
251 // see if there is a per-user vcpkg tree that has been integrated into msbuild
252 // using `vcpkg integrate install`
253 let local_app_data = try!(env::var("LOCALAPPDATA").map_err(|_| Error::VcpkgNotFound(
254 "Failed to read either VCPKG_ROOT or LOCALAPPDATA environment variables".to_string()
255 ))); // not present or can't utf8
256 let vcpkg_user_targets_path = Path::new(local_app_data.as_str())
257 .join("vcpkg")
258 .join("vcpkg.user.targets");
259
260 let file = try!(File::open(vcpkg_user_targets_path.clone()).map_err(|_| {
261 Error::VcpkgNotFound(
262 "No vcpkg.user.targets found. Set the VCPKG_ROOT environment \
263 variable or run 'vcpkg integrate install'"
264 .to_string(),
265 )
266 }));
267 let file = BufReader::new(&file);
268
269 for line in file.lines() {
270 let line = try!(line.map_err(|_| Error::VcpkgNotFound(format!(
271 "Parsing of {} failed.",
272 vcpkg_user_targets_path.to_string_lossy().to_owned()
273 ))));
274 let mut split = line.split("Project=\"");
275 split.next(); // eat anything before Project="
276 if let Some(found) = split.next() {
277 // " is illegal in a Windows pathname
278 if let Some(found) = found.split_terminator('"').next() {
279 let mut vcpkg_root = PathBuf::from(found);
280 if !(vcpkg_root.pop() && vcpkg_root.pop() && vcpkg_root.pop() && vcpkg_root.pop()) {
281 return Err(Error::VcpkgNotFound(format!(
282 "Could not find vcpkg root above {}",
283 found
284 )));
285 }
286 return Ok(vcpkg_root);
287 }
288 }
289 }
290
291 Err(Error::VcpkgNotFound(format!(
292 "Project location not found parsing {}.",
293 vcpkg_user_targets_path.to_string_lossy().to_owned()
294 )))
295 }
296
297 fn validate_vcpkg_root(path: &PathBuf) -> Result<(), Error> {
298 let mut vcpkg_root_path = path.clone();
299 vcpkg_root_path.push(".vcpkg-root");
300
301 if vcpkg_root_path.exists() {
302 Ok(())
303 } else {
304 Err(Error::VcpkgNotFound(format!(
305 "Could not find Vcpkg root at {}",
306 vcpkg_root_path.to_string_lossy()
307 )))
308 }
309 }
310
311 fn find_vcpkg_target(cfg: &Config, msvc_target: &MSVCTarget) -> Result<VcpkgTarget, Error> {
312 let vcpkg_root = try!(find_vcpkg_root(&cfg));
313 try!(validate_vcpkg_root(&vcpkg_root));
314
315 let (static_lib, static_appendage, lib_suffix, strip_lib_prefix) = match msvc_target {
316 &MSVCTarget::X64Windows | &MSVCTarget::X86Windows => {
317 let static_lib = env::var("CARGO_CFG_TARGET_FEATURE")
318 .unwrap_or(String::new()) // rustc 1.10
319 .contains("crt-static");
320 let static_appendage = if static_lib { "-static" } else { "" };
321 (static_lib, static_appendage, "lib", false)
322 }
323 _ => (true, "", "a", true),
324 };
325
326 let mut base = vcpkg_root;
327 base.push("installed");
328 let status_path = base.join("vcpkg");
329
330 let vcpkg_triple = format!("{}{}", msvc_target.to_string(), static_appendage);
331 base.push(&vcpkg_triple);
332
333 let lib_path = base.join("lib");
334 let bin_path = base.join("bin");
335 let include_path = base.join("include");
336
337 Ok(VcpkgTarget {
338 vcpkg_triple: vcpkg_triple,
339 lib_path: lib_path,
340 bin_path: bin_path,
341 include_path: include_path,
342 is_static: static_lib,
343 status_path: status_path,
344 lib_suffix: lib_suffix.to_owned(),
345 strip_lib_prefix: strip_lib_prefix,
346 })
347 }
348
349 #[derive(Clone, Debug)]
350 struct Port {
351 // dlls if any
352 dlls: Vec<String>,
353
354 // libs (static or import)
355 libs: Vec<String>,
356
357 // ports that this port depends on
358 deps: Vec<String>,
359 }
360
361 fn load_port_manifest(
362 path: &PathBuf,
363 port: &str,
364 version: &str,
365 vcpkg_target: &VcpkgTarget,
366 ) -> Result<(Vec<String>, Vec<String>), Error> {
367 let manifest_file = path.join("info").join(format!(
368 "{}_{}_{}.list",
369 port, version, vcpkg_target.vcpkg_triple
370 ));
371
372 let mut dlls = Vec::new();
373 let mut libs = Vec::new();
374
375 let f = try!(
376 File::open(&manifest_file).map_err(|_| Error::VcpkgInstallation(format!(
377 "Could not open port manifest file {}",
378 manifest_file.display()
379 )))
380 );
381
382 let file = BufReader::new(&f);
383
384 let dll_prefix = Path::new(&vcpkg_target.vcpkg_triple).join("bin");
385 let lib_prefix = Path::new(&vcpkg_target.vcpkg_triple).join("lib");
386
387 for line in file.lines() {
388 let line = line.unwrap();
389
390 let file_path = Path::new(&line);
391
392 if let Ok(dll) = file_path.strip_prefix(&dll_prefix) {
393 if dll.extension() == Some(OsStr::new("dll"))
394 && dll.components().collect::<Vec<_>>().len() == 1
395 {
396 // match "mylib.dll" but not "debug/mylib.dll" or "manual_link/mylib.dll"
397
398 dll.to_str().map(|s| dlls.push(s.to_owned()));
399 }
400 } else if let Ok(lib) = file_path.strip_prefix(&lib_prefix) {
401 if lib.extension() == Some(OsStr::new(&vcpkg_target.lib_suffix))
402 && lib.components().collect::<Vec<_>>().len() == 1
403 {
404 if let Some(lib) = vcpkg_target.link_name_for_lib(lib) {
405 libs.push(lib);
406 }
407 }
408 }
409 }
410
411 Ok((dlls, libs))
412 }
413
414 // load ports from the status file or one of the incremental updates
415 fn load_port_file(
416 filename: &PathBuf,
417 port_info: &mut Vec<BTreeMap<String, String>>,
418 ) -> Result<(), Error> {
419 let f = try!(
420 File::open(&filename).map_err(|e| Error::VcpkgInstallation(format!(
421 "Could not open status file at {}: {}",
422 filename.display(),
423 e
424 )))
425 );
426 let file = BufReader::new(&f);
427 let mut current: BTreeMap<String, String> = BTreeMap::new();
428 for line in file.lines() {
429 let line = line.unwrap();
430 let parts = line.splitn(2, ": ").clone().collect::<Vec<_>>();
431 if parts.len() == 2 {
432 // a key: value line
433 current.insert(parts[0].trim().into(), parts[1].trim().into());
434 } else if line.len() == 0 {
435 // end of section
436 port_info.push(current.clone());
437 current.clear();
438 } else {
439 // ignore all extension lines of the form
440 //
441 // Description: a package with a
442 // very long description
443 //
444 // the description key is not used so this is harmless but
445 // this will eat extension lines for any multiline key which
446 // could become an issue in future
447 }
448 }
449
450 if !current.is_empty() {
451 port_info.push(current);
452 }
453
454 Ok(())
455 }
456
457 fn load_ports(target: &VcpkgTarget) -> Result<BTreeMap<String, Port>, Error> {
458 let mut ports: BTreeMap<String, Port> = BTreeMap::new();
459
460 let mut port_info: Vec<BTreeMap<String, String>> = Vec::new();
461
462 // load the main status file. It is not an error if this file does not
463 // exist. If the only command that has been run in a Vcpkg installation
464 // is a single `vcpkg install package` then there will likely be no
465 // status file, only incremental updates. This is the typical case when
466 // running in a CI environment.
467 let status_filename = target.status_path.join("status");
468 load_port_file(&status_filename, &mut port_info).ok();
469
470 // load updates to the status file that have yet to be normalized
471 let status_update_dir = target.status_path.join("updates");
472
473 let paths = try!(
474 fs::read_dir(status_update_dir).map_err(|e| Error::VcpkgInstallation(format!(
475 "could not read status file updates dir: {}",
476 e
477 )))
478 );
479
480 // get all of the paths of the update files into a Vec<PathBuf>
481 let mut paths = try!(paths
482 .map(|rde| rde.map(|de| de.path())) // Result<DirEntry, io::Error> -> Result<PathBuf, io::Error>
483 .collect::<Result<Vec<_>, _>>() // collect into Result<Vec<PathBuf>, io::Error>
484 .map_err(|e| {
485 Error::VcpkgInstallation(format!(
486 "could not read status file update filenames: {}",
487 e
488 ))
489 }));
490
491 // Sort the paths and read them. This could be done directly from the iterator if
492 // read_dir() guarantees that the files will be read in alpha order but that appears
493 // to be unspecified as the underlying operating system calls used are unspecified
494 // https://doc.rust-lang.org/nightly/std/fs/fn.read_dir.html#platform-specific-behavior
495 paths.sort();
496 for path in paths {
497 // println!("Name: {}", path.display());
498 try!(load_port_file(&path, &mut port_info));
499 }
500 //println!("{:#?}", port_info);
501
502 let mut seen_names = BTreeMap::new();
503 for current in &port_info {
504 // store them by name and arch, clobbering older details
505 match (
506 current.get("Package"),
507 current.get("Architecture"),
508 current.get("Feature"),
509 ) {
510 (Some(pkg), Some(arch), feature) => {
511 seen_names.insert((pkg, arch, feature), current);
512 }
513 _ => {}
514 }
515 }
516
517 for (&(name, arch, feature), current) in &seen_names {
518 if **arch == target.vcpkg_triple {
519 let mut deps = if let Some(deps) = current.get("Depends") {
520 deps.split(", ").map(|x| x.to_owned()).collect()
521 } else {
522 Vec::new()
523 };
524
525 if current
526 .get("Status")
527 .unwrap_or(&String::new())
528 .ends_with(" installed")
529 {
530 match (current.get("Version"), feature) {
531 (Some(version), _) => {
532 // this failing here and bailing out causes everything to fail
533 let lib_info = try!(load_port_manifest(
534 &target.status_path,
535 &name,
536 version,
537 &target
538 ));
539 let port = Port {
540 dlls: lib_info.0,
541 libs: lib_info.1,
542 deps: deps,
543 };
544
545 ports.insert(name.to_string(), port);
546 }
547 (_, Some(_feature)) => match ports.get_mut(name) {
548 Some(ref mut port) => {
549 port.deps.append(&mut deps);
550 }
551 _ => {
552 println!("found a feature that had no corresponding port :-");
553 println!("current {:+?}", current);
554 continue;
555 }
556 },
557 (_, _) => {
558 println!("didn't know how to deal with status file entry :-");
559 println!("{:+?}", current);
560 continue;
561 }
562 }
563 }
564 }
565 }
566
567 Ok(ports)
568 }
569
570 /// paths and triple for the chosen target
571 struct VcpkgTarget {
572 vcpkg_triple: String,
573 lib_path: PathBuf,
574 bin_path: PathBuf,
575 include_path: PathBuf,
576
577 // directory containing the status file
578 status_path: PathBuf,
579
580 is_static: bool,
581 lib_suffix: String,
582
583 /// strip 'lib' from library names in linker args?
584 strip_lib_prefix: bool,
585 }
586
587 impl VcpkgTarget {
588 fn link_name_for_lib(&self, filename: &std::path::Path) -> Option<String> {
589 if self.strip_lib_prefix {
590 filename.to_str().map(|s| s.to_owned())
591 // filename
592 // .to_str()
593 // .map(|s| s.trim_left_matches("lib").to_owned())
594 } else {
595 filename.to_str().map(|s| s.to_owned())
596 }
597 }
598 }
599
600 impl Config {
601 pub fn new() -> Config {
602 Config {
603 cargo_metadata: true,
604 copy_dlls: true,
605 ..Default::default()
606 // emit_includes: false,
607 // required_libs: Vec::new(),
608 }
609 }
610
611 /// Override the name of the library to look for if it differs from the package name.
612 ///
613 /// This may be called more than once if multiple libs are required.
614 /// All libs must be found for the probe to succeed. `.probe()` must
615 /// be run with a different configuration to look for libraries under one of several names.
616 /// `.libname("ssleay32")` will look for ssleay32.lib and also ssleay32.dll if
617 /// dynamic linking is selected.
618 pub fn lib_name(&mut self, lib_stem: &str) -> &mut Config {
619 self.required_libs.push(lib_stem.to_owned());
620 self.required_dlls.push(lib_stem.to_owned());
621 self
622 }
623
624 /// Override the name of the library to look for if it differs from the package name.
625 ///
626 /// This may be called more than once if multiple libs are required.
627 /// All libs must be found for the probe to succeed. `.probe()` must
628 /// be run with a different configuration to look for libraries under one of several names.
629 /// `.lib_names("libcurl_imp","curl")` will look for libcurl_imp.lib and also curl.dll if
630 /// dynamic linking is selected.
631 pub fn lib_names(&mut self, lib_stem: &str, dll_stem: &str) -> &mut Config {
632 self.required_libs.push(lib_stem.to_owned());
633 self.required_dlls.push(dll_stem.to_owned());
634 self
635 }
636
637 /// Define whether metadata should be emitted for cargo allowing it to
638 /// automatically link the binary. Defaults to `true`.
639 pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
640 self.cargo_metadata = cargo_metadata;
641 self
642 }
643
644 /// Define cargo:include= metadata should be emitted. Defaults to `false`.
645 pub fn emit_includes(&mut self, emit_includes: bool) -> &mut Config {
646 self.emit_includes = emit_includes;
647 self
648 }
649
650 /// Should DLLs be copied to OUT_DIR?
651 /// Defaults to `true`.
652 pub fn copy_dlls(&mut self, copy_dlls: bool) -> &mut Config {
653 self.copy_dlls = copy_dlls;
654 self
655 }
656
657 /// Define which path to use as vcpkg root overriding the VCPKG_ROOT environment variable
658 /// Default to `None`, which means use VCPKG_ROOT or try to find out automatically
659 pub fn vcpkg_root(&mut self, vcpkg_root: PathBuf) -> &mut Config {
660 self.vcpkg_root = Some(vcpkg_root);
661 self
662 }
663
664 /// Find the library `port_name` in a Vcpkg tree.
665 ///
666 /// This will use all configuration previously set to select the
667 /// architecture and linkage.
668 /// Deprecated in favor of the find_package function
669 #[doc(hidden)]
670 pub fn probe(&mut self, port_name: &str) -> Result<Library, Error> {
671 // determine the target type, bailing out if it is not some
672 // kind of msvc
673 let msvc_target = try!(msvc_target());
674
675 // bail out if requested to not try at all
676 if env::var_os("VCPKGRS_DISABLE").is_some() {
677 return Err(Error::DisabledByEnv("VCPKGRS_DISABLE".to_owned()));
678 }
679
680 // bail out if requested to not try at all (old)
681 if env::var_os("NO_VCPKG").is_some() {
682 return Err(Error::DisabledByEnv("NO_VCPKG".to_owned()));
683 }
684
685 // bail out if requested to skip this package
686 let abort_var_name = format!("VCPKGRS_NO_{}", envify(port_name));
687 if env::var_os(&abort_var_name).is_some() {
688 return Err(Error::DisabledByEnv(abort_var_name));
689 }
690
691 // bail out if requested to skip this package (old)
692 let abort_var_name = format!("{}_NO_VCPKG", envify(port_name));
693 if env::var_os(&abort_var_name).is_some() {
694 return Err(Error::DisabledByEnv(abort_var_name));
695 }
696
697 // if no overrides have been selected, then the Vcpkg port name
698 // is the the .lib name and the .dll name
699 if self.required_libs.is_empty() {
700 self.required_libs.push(port_name.to_owned());
701 self.required_dlls.push(port_name.to_owned());
702 }
703
704 let vcpkg_target = try!(find_vcpkg_target(&self, &msvc_target));
705
706 // require explicit opt-in before using dynamically linked
707 // variants, otherwise cargo install of various things will
708 // stop working if Vcpkg is installed.
709 if !vcpkg_target.is_static && !env::var_os("VCPKGRS_DYNAMIC").is_some() {
710 return Err(Error::RequiredEnvMissing("VCPKGRS_DYNAMIC".to_owned()));
711 }
712
713 let mut lib = Library::new(vcpkg_target.is_static);
714
715 if self.emit_includes {
716 lib.cargo_metadata.push(format!(
717 "cargo:include={}",
718 vcpkg_target.include_path.display()
719 ));
720 }
721 lib.include_paths.push(vcpkg_target.include_path.clone());
722
723 lib.cargo_metadata.push(format!(
724 "cargo:rustc-link-search=native={}",
725 vcpkg_target
726 .lib_path
727 .to_str()
728 .expect("failed to convert string type")
729 ));
730 lib.link_paths.push(vcpkg_target.lib_path.clone());
731 if !vcpkg_target.is_static {
732 lib.cargo_metadata.push(format!(
733 "cargo:rustc-link-search=native={}",
734 vcpkg_target
735 .bin_path
736 .to_str()
737 .expect("failed to convert string type")
738 ));
739 // this path is dropped by recent versions of cargo hence the copies to OUT_DIR below
740 lib.dll_paths.push(vcpkg_target.bin_path.clone());
741 }
742
743 try!(self.emit_libs(&mut lib, &vcpkg_target));
744
745 if self.copy_dlls {
746 try!(self.do_dll_copy(&mut lib));
747 }
748
749 if self.cargo_metadata {
750 for line in &lib.cargo_metadata {
751 println!("{}", line);
752 }
753 }
754 Ok(lib)
755 }
756
757 fn emit_libs(&mut self, lib: &mut Library, vcpkg_target: &VcpkgTarget) -> Result<(), Error> {
758 for required_lib in &self.required_libs {
759 // this could use static-nobundle= for static libraries but it is apparently
760 // not necessary to make the distinction for windows-msvc.
761
762 let link_name = match vcpkg_target.strip_lib_prefix {
763 true => required_lib.trim_left_matches("lib"),
764 false => required_lib,
765 };
766
767 lib.cargo_metadata
768 .push(format!("cargo:rustc-link-lib={}", link_name));
769
770 lib.found_names.push(String::from(link_name));
771
772 // verify that the library exists
773 let mut lib_location = vcpkg_target.lib_path.clone();
774 lib_location.push(required_lib.clone() + "." + &vcpkg_target.lib_suffix);
775
776 if !lib_location.exists() {
777 return Err(Error::LibNotFound(lib_location.display().to_string()));
778 }
779 lib.found_libs.push(lib_location);
780 }
781
782 if !vcpkg_target.is_static {
783 for required_dll in &self.required_dlls {
784 let mut dll_location = vcpkg_target.bin_path.clone();
785 dll_location.push(required_dll.clone() + ".dll");
786
787 // verify that the DLL exists
788 if !dll_location.exists() {
789 return Err(Error::LibNotFound(dll_location.display().to_string()));
790 }
791 lib.found_dlls.push(dll_location);
792 }
793 }
794
795 Ok(())
796 }
797
798 fn do_dll_copy(&mut self, lib: &mut Library) -> Result<(), Error> {
799 if let Some(target_dir) = env::var_os("OUT_DIR") {
800 if !lib.found_dlls.is_empty() {
801 for file in &lib.found_dlls {
802 let mut dest_path = Path::new(target_dir.as_os_str()).to_path_buf();
803 dest_path.push(Path::new(file.file_name().unwrap()));
804 try!(
805 fs::copy(file, &dest_path).map_err(|_| Error::LibNotFound(format!(
806 "Can't copy file {} to {}",
807 file.to_string_lossy(),
808 dest_path.to_string_lossy()
809 )))
810 );
811 println!(
812 "vcpkg build helper copied {} to {}",
813 file.to_string_lossy(),
814 dest_path.to_string_lossy()
815 );
816 }
817 lib.cargo_metadata.push(format!(
818 "cargo:rustc-link-search=native={}",
819 env::var("OUT_DIR").unwrap()
820 ));
821 // work around https://github.com/rust-lang/cargo/issues/3957
822 lib.cargo_metadata.push(format!(
823 "cargo:rustc-link-search={}",
824 env::var("OUT_DIR").unwrap()
825 ));
826 }
827 } else {
828 return Err(Error::LibNotFound("Unable to get OUT_DIR".to_owned()));
829 }
830 Ok(())
831 }
832
833 /// Find the package `port_name` in a Vcpkg tree.
834 ///
835 /// Emits cargo metadata to link to libraries provided by the Vcpkg package/port
836 /// named, and any (non-system) libraries that they depend on.
837 ///
838 /// This will select the architecture and linkage based on environment
839 /// variables and build flags as described in the module docs, and any configuration
840 /// set on the builder.
841 pub fn find_package(&mut self, port_name: &str) -> Result<Library, Error> {
842 // determine the target type, bailing out if it is not some
843 // kind of msvc
844 let msvc_target = try!(msvc_target());
845
846 // bail out if requested to not try at all
847 if env::var_os("VCPKGRS_DISABLE").is_some() {
848 return Err(Error::DisabledByEnv("VCPKGRS_DISABLE".to_owned()));
849 }
850
851 // bail out if requested to not try at all (old)
852 if env::var_os("NO_VCPKG").is_some() {
853 return Err(Error::DisabledByEnv("NO_VCPKG".to_owned()));
854 }
855
856 // bail out if requested to skip this package
857 let abort_var_name = format!("VCPKGRS_NO_{}", envify(port_name));
858 if env::var_os(&abort_var_name).is_some() {
859 return Err(Error::DisabledByEnv(abort_var_name));
860 }
861
862 // bail out if requested to skip this package (old)
863 let abort_var_name = format!("{}_NO_VCPKG", envify(port_name));
864 if env::var_os(&abort_var_name).is_some() {
865 return Err(Error::DisabledByEnv(abort_var_name));
866 }
867
868 let vcpkg_target = try!(find_vcpkg_target(&self, &msvc_target));
869 let mut required_port_order = Vec::new();
870
871 // if no overrides have been selected, then the Vcpkg port name
872 // is the the .lib name and the .dll name
873 if self.required_libs.is_empty() {
874 let ports = try!(load_ports(&vcpkg_target));
875
876 if ports.get(&port_name.to_owned()).is_none() {
877 return Err(Error::LibNotFound(port_name.to_owned()));
878 }
879
880 // the complete set of ports required
881 let mut required_ports: BTreeMap<String, Port> = BTreeMap::new();
882 // working of ports that we need to include
883 // let mut ports_to_scan: BTreeSet<String> = BTreeSet::new();
884 // ports_to_scan.insert(port_name.to_owned());
885 let mut ports_to_scan = vec![port_name.to_owned()]; //: Vec<String> = BTreeSet::new();
886
887 while !ports_to_scan.is_empty() {
888 let port_name = ports_to_scan.pop().unwrap();
889
890 if required_ports.contains_key(&port_name) {
891 continue;
892 }
893
894 if let Some(port) = ports.get(&port_name) {
895 for dep in &port.deps {
896 ports_to_scan.push(dep.clone());
897 }
898 required_ports.insert(port_name.clone(), (*port).clone());
899 remove_item(&mut required_port_order, &port_name);
900 required_port_order.push(port_name);
901 } else {
902 // what?
903 }
904 }
905
906 // for port in ports {
907 // println!("port {:?}", port);
908 // }
909 // println!("== Looking for port {}", port_name);
910 // for port in &required_port_order {
911 // println!("ordered required port {:?}", port);
912 // }
913 // println!("=============================");
914 // for port in &required_ports {
915 // println!("required port {:?}", port);
916 // }
917
918 // if no overrides have been selected, then the Vcpkg port name
919 // is the the .lib name and the .dll name
920 if self.required_libs.is_empty() {
921 for port_name in &required_port_order {
922 let port = required_ports.get(port_name).unwrap();
923 self.required_libs.extend(port.libs.iter().map(|s| {
924 Path::new(&s)
925 .file_stem()
926 .unwrap()
927 .to_string_lossy()
928 .into_owned()
929 }));
930 self.required_dlls
931 .extend(port.dlls.iter().cloned().map(|s| {
932 Path::new(&s)
933 .file_stem()
934 .unwrap()
935 .to_string_lossy()
936 .into_owned()
937 }));
938 }
939 }
940 }
941 // require explicit opt-in before using dynamically linked
942 // variants, otherwise cargo install of various things will
943 // stop working if Vcpkg is installed.
944 if !vcpkg_target.is_static && !env::var_os("VCPKGRS_DYNAMIC").is_some() {
945 return Err(Error::RequiredEnvMissing("VCPKGRS_DYNAMIC".to_owned()));
946 }
947
948 let mut lib = Library::new(vcpkg_target.is_static);
949
950 if self.emit_includes {
951 lib.cargo_metadata.push(format!(
952 "cargo:include={}",
953 vcpkg_target.include_path.display()
954 ));
955 }
956 lib.include_paths.push(vcpkg_target.include_path.clone());
957
958 lib.cargo_metadata.push(format!(
959 "cargo:rustc-link-search=native={}",
960 vcpkg_target
961 .lib_path
962 .to_str()
963 .expect("failed to convert string type")
964 ));
965 lib.link_paths.push(vcpkg_target.lib_path.clone());
966 if !vcpkg_target.is_static {
967 lib.cargo_metadata.push(format!(
968 "cargo:rustc-link-search=native={}",
969 vcpkg_target
970 .bin_path
971 .to_str()
972 .expect("failed to convert string type")
973 ));
974 // this path is dropped by recent versions of cargo hence the copies to OUT_DIR below
975 lib.dll_paths.push(vcpkg_target.bin_path.clone());
976 }
977
978 lib.ports = required_port_order;
979
980 try!(self.emit_libs(&mut lib, &vcpkg_target));
981
982 if self.copy_dlls {
983 try!(self.do_dll_copy(&mut lib));
984 }
985
986 if self.cargo_metadata {
987 for line in &lib.cargo_metadata {
988 println!("{}", line);
989 }
990 }
991 Ok(lib)
992 }
993 }
994
995 fn remove_item(cont: &mut Vec<String>, item: &String) -> Option<String> {
996 match cont.iter().position(|x| *x == *item) {
997 Some(pos) => Some(cont.remove(pos)),
998 None => None,
999 }
1000 }
1001
1002 impl Library {
1003 fn new(is_static: bool) -> Library {
1004 Library {
1005 link_paths: Vec::new(),
1006 dll_paths: Vec::new(),
1007 include_paths: Vec::new(),
1008 cargo_metadata: Vec::new(),
1009 is_static: is_static,
1010 found_dlls: Vec::new(),
1011 found_libs: Vec::new(),
1012 found_names: Vec::new(),
1013 ports: Vec::new(),
1014 }
1015 }
1016 }
1017
1018 fn envify(name: &str) -> String {
1019 name.chars()
1020 .map(|c| c.to_ascii_uppercase())
1021 .map(|c| if c == '-' { '_' } else { c })
1022 .collect()
1023 }
1024
1025 fn msvc_target() -> Result<MSVCTarget, Error> {
1026 let target = env::var("TARGET").unwrap_or(String::new());
1027 if target == "x86_64-apple-darwin" {
1028 Ok(MSVCTarget::X64MacOS)
1029 } else if target == "x86_64-unknown-linux-gnu" {
1030 Ok(MSVCTarget::X64Linux)
1031 } else if !target.contains("-pc-windows-msvc") {
1032 Err(Error::NotMSVC)
1033 } else if target.starts_with("x86_64-") {
1034 Ok(MSVCTarget::X64Windows)
1035 } else {
1036 // everything else is x86
1037 Ok(MSVCTarget::X86Windows)
1038 }
1039 }
1040
1041 #[cfg(test)]
1042 mod tests {
1043
1044 extern crate tempdir;
1045
1046 use super::*;
1047 use std::env;
1048 use std::sync::Mutex;
1049
1050 lazy_static! {
1051 static ref LOCK: Mutex<()> = Mutex::new(());
1052 }
1053
1054 #[test]
1055 fn do_nothing_for_unsupported_target() {
1056 let _g = LOCK.lock();
1057 env::set_var("VCPKG_ROOT", "/");
1058 env::set_var("TARGET", "x86_64-pc-windows-gnu");
1059 assert!(match ::probe_package("foo") {
1060 Err(Error::NotMSVC) => true,
1061 _ => false,
1062 });
1063
1064 env::set_var("TARGET", "x86_64-pc-windows-gnu");
1065 assert_eq!(env::var("TARGET"), Ok("x86_64-pc-windows-gnu".to_string()));
1066 assert!(match ::probe_package("foo") {
1067 Err(Error::NotMSVC) => true,
1068 _ => false,
1069 });
1070 env::remove_var("TARGET");
1071 env::remove_var("VCPKG_ROOT");
1072 }
1073
1074 #[test]
1075 fn do_nothing_for_bailout_variables_set() {
1076 let _g = LOCK.lock();
1077 env::set_var("VCPKG_ROOT", "/");
1078 env::set_var("TARGET", "x86_64-pc-windows-msvc");
1079
1080 for &var in &[
1081 "VCPKGRS_DISABLE",
1082 "VCPKGRS_NO_FOO",
1083 "FOO_NO_VCPKG",
1084 "NO_VCPKG",
1085 ] {
1086 env::set_var(var, "1");
1087 assert!(match ::probe_package("foo") {
1088 Err(Error::DisabledByEnv(ref v)) if v == var => true,
1089 _ => false,
1090 });
1091 env::remove_var(var);
1092 }
1093 env::remove_var("TARGET");
1094 env::remove_var("VCPKG_ROOT");
1095 }
1096
1097 // these tests are good but are leaning on a real vcpkg installation
1098
1099 #[test]
1100 fn default_build_refuses_dynamic() {
1101 let _g = LOCK.lock();
1102 clean_env();
1103 env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("no-status"));
1104 env::set_var("TARGET", "x86_64-pc-windows-msvc");
1105 println!("Result is {:?}", ::find_package("libmysql"));
1106 assert!(match ::find_package("libmysql") {
1107 Err(Error::RequiredEnvMissing(ref v)) if v == "VCPKGRS_DYNAMIC" => true,
1108 _ => false,
1109 });
1110 clean_env();
1111 }
1112
1113 #[test]
1114 fn static_build_finds_lib() {
1115 let _g = LOCK.lock();
1116 clean_env();
1117 env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
1118 env::set_var("TARGET", "x86_64-pc-windows-msvc");
1119 let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
1120 env::set_var("OUT_DIR", tmp_dir.path());
1121
1122 // CARGO_CFG_TARGET_FEATURE is set in response to
1123 // RUSTFLAGS=-Ctarget-feature=+crt-static. It would
1124 // be nice to test that also.
1125 env::set_var("CARGO_CFG_TARGET_FEATURE", "crt-static");
1126 println!("Result is {:?}", ::find_package("libmysql"));
1127 assert!(match ::find_package("libmysql") {
1128 Ok(_) => true,
1129 _ => false,
1130 });
1131 clean_env();
1132 }
1133
1134 #[test]
1135 fn dynamic_build_finds_lib() {
1136 let _g = LOCK.lock();
1137 clean_env();
1138 env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("no-status"));
1139 env::set_var("TARGET", "x86_64-pc-windows-msvc");
1140 env::set_var("VCPKGRS_DYNAMIC", "1");
1141 let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
1142 env::set_var("OUT_DIR", tmp_dir.path());
1143
1144 println!("Result is {:?}", ::find_package("libmysql"));
1145 assert!(match ::find_package("libmysql") {
1146 Ok(_) => true,
1147 _ => false,
1148 });
1149 clean_env();
1150 }
1151
1152 #[test]
1153 fn handle_multiline_description() {
1154 let _g = LOCK.lock();
1155 clean_env();
1156 env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("multiline-description"));
1157 env::set_var("TARGET", "i686-pc-windows-msvc");
1158 env::set_var("VCPKGRS_DYNAMIC", "1");
1159 let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
1160 env::set_var("OUT_DIR", tmp_dir.path());
1161
1162 println!("Result is {:?}", ::find_package("graphite2"));
1163 assert!(match ::find_package("graphite2") {
1164 Ok(_) => true,
1165 _ => false,
1166 });
1167 clean_env();
1168 }
1169
1170 #[test]
1171 fn link_libs_required_by_optional_features() {
1172 let _g = LOCK.lock();
1173 clean_env();
1174 env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
1175 env::set_var("TARGET", "i686-pc-windows-msvc");
1176 env::set_var("VCPKGRS_DYNAMIC", "1");
1177 let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
1178 env::set_var("OUT_DIR", tmp_dir.path());
1179
1180 println!("Result is {:?}", ::find_package("harfbuzz"));
1181 assert!(match ::find_package("harfbuzz") {
1182 Ok(lib) => lib
1183 .cargo_metadata
1184 .iter()
1185 .find(|&x| x == "cargo:rustc-link-lib=icuuc")
1186 .is_some(),
1187 _ => false,
1188 });
1189 clean_env();
1190 }
1191
1192 #[test]
1193 fn link_lib_name_is_correct() {
1194 let _g = LOCK.lock();
1195
1196 for target in &[
1197 "x86_64-apple-darwin",
1198 "i686-pc-windows-msvc",
1199 // "x86_64-pc-windows-msvc",
1200 // "x86_64-unknown-linux-gnu",
1201 ] {
1202 clean_env();
1203 env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
1204 env::set_var("TARGET", target);
1205 env::set_var("VCPKGRS_DYNAMIC", "1");
1206 let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
1207 env::set_var("OUT_DIR", tmp_dir.path());
1208
1209 println!("Result is {:?}", ::find_package("harfbuzz"));
1210 assert!(match ::find_package("harfbuzz") {
1211 Ok(lib) => lib
1212 .cargo_metadata
1213 .iter()
1214 .find(|&x| x == "cargo:rustc-link-lib=harfbuzz")
1215 .is_some(),
1216 _ => false,
1217 });
1218 clean_env();
1219 }
1220 }
1221
1222 #[test]
1223 fn link_dependencies_after_port() {
1224 let _g = LOCK.lock();
1225 clean_env();
1226 env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("normalized"));
1227 env::set_var("TARGET", "i686-pc-windows-msvc");
1228 env::set_var("VCPKGRS_DYNAMIC", "1");
1229 let tmp_dir = tempdir::TempDir::new("vcpkg_tests").unwrap();
1230 env::set_var("OUT_DIR", tmp_dir.path());
1231
1232 let lib = ::find_package("harfbuzz").unwrap();
1233
1234 check_before(&lib, "freetype", "zlib");
1235 check_before(&lib, "freetype", "bzip2");
1236 check_before(&lib, "freetype", "libpng");
1237 check_before(&lib, "harfbuzz", "freetype");
1238 check_before(&lib, "harfbuzz", "ragel");
1239 check_before(&lib, "libpng", "zlib");
1240
1241 clean_env();
1242
1243 fn check_before(lib: &Library, earlier: &str, later: &str) {
1244 match (
1245 lib.ports.iter().position(|x| *x == *earlier),
1246 lib.ports.iter().position(|x| *x == *later),
1247 ) {
1248 (Some(earlier_pos), Some(later_pos)) if earlier_pos < later_pos => {
1249 // ok
1250 }
1251 _ => {
1252 println!(
1253 "earlier: {}, later: {}\nLibrary found: {:#?}",
1254 earlier, later, lib
1255 );
1256 panic!();
1257 }
1258 }
1259 }
1260 }
1261 // #[test]
1262 // fn dynamic_build_package_specific_bailout() {
1263 // clean_env();
1264 // env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("no-status"));
1265 // env::set_var("TARGET", "x86_64-pc-windows-msvc");
1266 // env::set_var("VCPKGRS_DYNAMIC", "1");
1267 // env::set_var("VCPKGRS_NO_LIBMYSQL", "1");
1268
1269 // println!("Result is {:?}", ::find_package("libmysql"));
1270 // assert!(match ::find_package("libmysql") {
1271 // Err(Error::DisabledByEnv(ref v)) if v == "VCPKGRS_NO_LIBMYSQL" => true,
1272 // _ => false,
1273 // });
1274 // clean_env();
1275 // }
1276
1277 // #[test]
1278 // fn dynamic_build_global_bailout() {
1279 // clean_env();
1280 // env::set_var("VCPKG_ROOT", vcpkg_test_tree_loc("no-status"));
1281 // env::set_var("TARGET", "x86_64-pc-windows-msvc");
1282 // env::set_var("VCPKGRS_DYNAMIC", "1");
1283 // env::set_var("VCPKGRS_DISABLE", "1");
1284
1285 // println!("Result is {:?}", ::find_package("libmysql"));
1286 // assert!(match ::find_package("libmysql") {
1287 // Err(Error::DisabledByEnv(ref v)) if v == "VCPKGRS_DISABLE" => true,
1288 // _ => false,
1289 // });
1290 // clean_env();
1291 // }
1292
1293 fn clean_env() {
1294 env::remove_var("TARGET");
1295 env::remove_var("VCPKG_ROOT");
1296 env::remove_var("VCPKGRS_DYNAMIC");
1297 env::remove_var("RUSTFLAGS");
1298 env::remove_var("CARGO_CFG_TARGET_FEATURE");
1299 env::remove_var("VCPKGRS_DISABLE");
1300 env::remove_var("VCPKGRS_NO_LIBMYSQL");
1301 }
1302
1303 // path to a to vcpkg installation to test against
1304 fn vcpkg_test_tree_loc(name: &str) -> PathBuf {
1305 let mut path = PathBuf::new();
1306 path.push(env::var("CARGO_MANIFEST_DIR").unwrap());
1307 path.pop();
1308 path.push("test-data");
1309 path.push(name);
1310 path
1311 }
1312 }