summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorlurchi <lurchi@strangeplace.net>2016-08-14 12:46:51 +0200
committerlurchi <lurchi@strangeplace.net>2016-08-14 12:46:51 +0200
commit8604a7336f8c3957458e6e15740189b173b9966e (patch)
tree33e93b8424ece15b5c03bfad57ef0b3e7867b5b6
parent17321bfb3c7ef6a05073f9656460c00547e89ed8 (diff)
downloadsecushare-8604a7336f8c3957458e6e15740189b173b9966e.tar.gz
secushare-8604a7336f8c3957458e6e15740189b173b9966e.zip
add pkg-config-rs subtree
-rw-r--r--third_party/pkg-config-rs/.gitignore2
-rw-r--r--third_party/pkg-config-rs/.travis.yml25
-rw-r--r--third_party/pkg-config-rs/Cargo.toml16
-rw-r--r--third_party/pkg-config-rs/LICENSE-APACHE201
-rw-r--r--third_party/pkg-config-rs/LICENSE-MIT25
-rw-r--r--third_party/pkg-config-rs/README.md25
-rw-r--r--third_party/pkg-config-rs/src/lib.rs471
-rw-r--r--third_party/pkg-config-rs/tests/foo.pc16
-rw-r--r--third_party/pkg-config-rs/tests/framework.pc16
-rw-r--r--third_party/pkg-config-rs/tests/test.rs99
10 files changed, 896 insertions, 0 deletions
diff --git a/third_party/pkg-config-rs/.gitignore b/third_party/pkg-config-rs/.gitignore
new file mode 100644
index 0000000..4fffb2f
--- /dev/null
+++ b/third_party/pkg-config-rs/.gitignore
@@ -0,0 +1,2 @@
1/target
2/Cargo.lock
diff --git a/third_party/pkg-config-rs/.travis.yml b/third_party/pkg-config-rs/.travis.yml
new file mode 100644
index 0000000..f02def7
--- /dev/null
+++ b/third_party/pkg-config-rs/.travis.yml
@@ -0,0 +1,25 @@
1language: rust
2rust:
3 - stable
4 - beta
5 - nightly
6sudo: false
7script:
8 - cargo build --verbose
9 - |
10 [ $TRAVIS_RUST_VERSION != nightly ] || cargo test --verbose
11 - cargo doc
12after_success: |
13 [ $TRAVIS_BRANCH = master ] &&
14 [ $TRAVIS_PULL_REQUEST = false ] &&
15 [ $TRAVIS_RUST_VERSION = nightly ] &&
16 echo '<meta http-equiv=refresh content=0;url=pkg_config/index.html>' > target/doc/index.html &&
17 pip install ghp-import --user $USER &&
18 $HOME/.local/bin/ghp-import -n target/doc &&
19 git push -qf https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
20env:
21 global:
22 secure: XlfwiQ+fPgRWqFwHbyPTma2FAVtgN+IXFpkiIdh1sKxWEeHMqABrTtOKf/NugDYCGsOJfr2vb5qFL6teBV2lTXOffUIWj+1hMd0N/FbVKWzABBV02XdxQi8w2ptPez5LPRTEfXJRRHmJpc8ww2aCTIrdT3AQE2oqZM/jHJTi/1U=
23notifications:
24 email:
25 on_success: never
diff --git a/third_party/pkg-config-rs/Cargo.toml b/third_party/pkg-config-rs/Cargo.toml
new file mode 100644
index 0000000..ba10f5d
--- /dev/null
+++ b/third_party/pkg-config-rs/Cargo.toml
@@ -0,0 +1,16 @@
1[package]
2
3name = "pkg-config"
4version = "0.3.8"
5authors = ["Alex Crichton <alex@alexcrichton.com>"]
6license = "MIT/Apache-2.0"
7repository = "https://github.com/alexcrichton/pkg-config-rs"
8documentation = "http://alexcrichton.com/pkg-config-rs"
9description = """
10A library to run the pkg-config system tool at build time in order to be used in
11Cargo build scripts.
12"""
13keywords = ["build-dependencies"]
14
15[dev-dependencies]
16lazy_static = "0.2"
diff --git a/third_party/pkg-config-rs/LICENSE-APACHE b/third_party/pkg-config-rs/LICENSE-APACHE
new file mode 100644
index 0000000..16fe87b
--- /dev/null
+++ b/third_party/pkg-config-rs/LICENSE-APACHE
@@ -0,0 +1,201 @@
1 Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
71. Definitions.
8
9 "License" shall mean the terms and conditions for use, reproduction,
10 and distribution as defined by Sections 1 through 9 of this document.
11
12 "Licensor" shall mean the copyright owner or entity authorized by
13 the copyright owner that is granting the License.
14
15 "Legal Entity" shall mean the union of the acting entity and all
16 other entities that control, are controlled by, or are under common
17 control with that entity. For the purposes of this definition,
18 "control" means (i) the power, direct or indirect, to cause the
19 direction or management of such entity, whether by contract or
20 otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 outstanding shares, or (iii) beneficial ownership of such entity.
22
23 "You" (or "Your") shall mean an individual or Legal Entity
24 exercising permissions granted by this License.
25
26 "Source" form shall mean the preferred form for making modifications,
27 including but not limited to software source code, documentation
28 source, and configuration files.
29
30 "Object" form shall mean any form resulting from mechanical
31 transformation or translation of a Source form, including but
32 not limited to compiled object code, generated documentation,
33 and conversions to other media types.
34
35 "Work" shall mean the work of authorship, whether in Source or
36 Object form, made available under the License, as indicated by a
37 copyright notice that is included in or attached to the work
38 (an example is provided in the Appendix below).
39
40 "Derivative Works" shall mean any work, whether in Source or Object
41 form, that is based on (or derived from) the Work and for which the
42 editorial revisions, annotations, elaborations, or other modifications
43 represent, as a whole, an original work of authorship. For the purposes
44 of this License, Derivative Works shall not include works that remain
45 separable from, or merely link (or bind by name) to the interfaces of,
46 the Work and Derivative Works thereof.
47
48 "Contribution" shall mean any work of authorship, including
49 the original version of the Work and any modifications or additions
50 to that Work or Derivative Works thereof, that is intentionally
51 submitted to Licensor for inclusion in the Work by the copyright owner
52 or by an individual or Legal Entity authorized to submit on behalf of
53 the copyright owner. For the purposes of this definition, "submitted"
54 means any form of electronic, verbal, or written communication sent
55 to the Licensor or its representatives, including but not limited to
56 communication on electronic mailing lists, source code control systems,
57 and issue tracking systems that are managed by, or on behalf of, the
58 Licensor for the purpose of discussing and improving the Work, but
59 excluding communication that is conspicuously marked or otherwise
60 designated in writing by the copyright owner as "Not a Contribution."
61
62 "Contributor" shall mean Licensor and any individual or Legal Entity
63 on behalf of whom a Contribution has been received by Licensor and
64 subsequently incorporated within the Work.
65
662. Grant of Copyright License. Subject to the terms and conditions of
67 this License, each Contributor hereby grants to You a perpetual,
68 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 copyright license to reproduce, prepare Derivative Works of,
70 publicly display, publicly perform, sublicense, and distribute the
71 Work and such Derivative Works in Source or Object form.
72
733. Grant of Patent License. Subject to the terms and conditions of
74 this License, each Contributor hereby grants to You a perpetual,
75 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 (except as stated in this section) patent license to make, have made,
77 use, offer to sell, sell, import, and otherwise transfer the Work,
78 where such license applies only to those patent claims licensable
79 by such Contributor that are necessarily infringed by their
80 Contribution(s) alone or by combination of their Contribution(s)
81 with the Work to which such Contribution(s) was submitted. If You
82 institute patent litigation against any entity (including a
83 cross-claim or counterclaim in a lawsuit) alleging that the Work
84 or a Contribution incorporated within the Work constitutes direct
85 or contributory patent infringement, then any patent licenses
86 granted to You under this License for that Work shall terminate
87 as of the date such litigation is filed.
88
894. Redistribution. You may reproduce and distribute copies of the
90 Work or Derivative Works thereof in any medium, with or without
91 modifications, and in Source or Object form, provided that You
92 meet the following conditions:
93
94 (a) You must give any other recipients of the Work or
95 Derivative Works a copy of this License; and
96
97 (b) You must cause any modified files to carry prominent notices
98 stating that You changed the files; and
99
100 (c) You must retain, in the Source form of any Derivative Works
101 that You distribute, all copyright, patent, trademark, and
102 attribution notices from the Source form of the Work,
103 excluding those notices that do not pertain to any part of
104 the Derivative Works; and
105
106 (d) If the Work includes a "NOTICE" text file as part of its
107 distribution, then any Derivative Works that You distribute must
108 include a readable copy of the attribution notices contained
109 within such NOTICE file, excluding those notices that do not
110 pertain to any part of the Derivative Works, in at least one
111 of the following places: within a NOTICE text file distributed
112 as part of the Derivative Works; within the Source form or
113 documentation, if provided along with the Derivative Works; or,
114 within a display generated by the Derivative Works, if and
115 wherever such third-party notices normally appear. The contents
116 of the NOTICE file are for informational purposes only and
117 do not modify the License. You may add Your own attribution
118 notices within Derivative Works that You distribute, alongside
119 or as an addendum to the NOTICE text from the Work, provided
120 that such additional attribution notices cannot be construed
121 as modifying the License.
122
123 You may add Your own copyright statement to Your modifications and
124 may provide additional or different license terms and conditions
125 for use, reproduction, or distribution of Your modifications, or
126 for any such Derivative Works as a whole, provided Your use,
127 reproduction, and distribution of the Work otherwise complies with
128 the conditions stated in this License.
129
1305. Submission of Contributions. Unless You explicitly state otherwise,
131 any Contribution intentionally submitted for inclusion in the Work
132 by You to the Licensor shall be under the terms and conditions of
133 this License, without any additional terms or conditions.
134 Notwithstanding the above, nothing herein shall supersede or modify
135 the terms of any separate license agreement you may have executed
136 with Licensor regarding such Contributions.
137
1386. Trademarks. This License does not grant permission to use the trade
139 names, trademarks, service marks, or product names of the Licensor,
140 except as required for reasonable and customary use in describing the
141 origin of the Work and reproducing the content of the NOTICE file.
142
1437. Disclaimer of Warranty. Unless required by applicable law or
144 agreed to in writing, Licensor provides the Work (and each
145 Contributor provides its Contributions) on an "AS IS" BASIS,
146 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 implied, including, without limitation, any warranties or conditions
148 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 PARTICULAR PURPOSE. You are solely responsible for determining the
150 appropriateness of using or redistributing the Work and assume any
151 risks associated with Your exercise of permissions under this License.
152
1538. Limitation of Liability. In no event and under no legal theory,
154 whether in tort (including negligence), contract, or otherwise,
155 unless required by applicable law (such as deliberate and grossly
156 negligent acts) or agreed to in writing, shall any Contributor be
157 liable to You for damages, including any direct, indirect, special,
158 incidental, or consequential damages of any character arising as a
159 result of this License or out of the use or inability to use the
160 Work (including but not limited to damages for loss of goodwill,
161 work stoppage, computer failure or malfunction, or any and all
162 other commercial damages or losses), even if such Contributor
163 has been advised of the possibility of such damages.
164
1659. Accepting Warranty or Additional Liability. While redistributing
166 the Work or Derivative Works thereof, You may choose to offer,
167 and charge a fee for, acceptance of support, warranty, indemnity,
168 or other liability obligations and/or rights consistent with this
169 License. However, in accepting such obligations, You may act only
170 on Your own behalf and on Your sole responsibility, not on behalf
171 of any other Contributor, and only if You agree to indemnify,
172 defend, and hold each Contributor harmless for any liability
173 incurred by, or claims asserted against, such Contributor by reason
174 of your accepting any such warranty or additional liability.
175
176END OF TERMS AND CONDITIONS
177
178APPENDIX: How to apply the Apache License to your work.
179
180 To apply the Apache License to your work, attach the following
181 boilerplate notice, with the fields enclosed by brackets "[]"
182 replaced with your own identifying information. (Don't include
183 the brackets!) The text should be enclosed in the appropriate
184 comment syntax for the file format. We also recommend that a
185 file or class name and description of purpose be included on the
186 same "printed page" as the copyright notice for easier
187 identification within third-party archives.
188
189Copyright [yyyy] [name of copyright owner]
190
191Licensed under the Apache License, Version 2.0 (the "License");
192you may not use this file except in compliance with the License.
193You may obtain a copy of the License at
194
195 http://www.apache.org/licenses/LICENSE-2.0
196
197Unless required by applicable law or agreed to in writing, software
198distributed under the License is distributed on an "AS IS" BASIS,
199WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200See the License for the specific language governing permissions and
201limitations under the License.
diff --git a/third_party/pkg-config-rs/LICENSE-MIT b/third_party/pkg-config-rs/LICENSE-MIT
new file mode 100644
index 0000000..39e0ed6
--- /dev/null
+++ b/third_party/pkg-config-rs/LICENSE-MIT
@@ -0,0 +1,25 @@
1Copyright (c) 2014 Alex Crichton
2
3Permission is hereby granted, free of charge, to any
4person obtaining a copy of this software and associated
5documentation files (the "Software"), to deal in the
6Software without restriction, including without
7limitation the rights to use, copy, modify, merge,
8publish, distribute, sublicense, and/or sell copies of
9the Software, and to permit persons to whom the Software
10is furnished to do so, subject to the following
11conditions:
12
13The above copyright notice and this permission notice
14shall be included in all copies or substantial portions
15of the Software.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25DEALINGS IN THE SOFTWARE.
diff --git a/third_party/pkg-config-rs/README.md b/third_party/pkg-config-rs/README.md
new file mode 100644
index 0000000..4db41e2
--- /dev/null
+++ b/third_party/pkg-config-rs/README.md
@@ -0,0 +1,25 @@
1# pkg-config-rs
2
3[![Build Status](https://travis-ci.org/alexcrichton/pkg-config-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/pkg-config-rs)
4
5[Documentation](http://alexcrichton.com/pkg-config-rs)
6
7A simple library meant to be used as a build dependency with Cargo packages in
8order to use the system `pkg-config` tool (if available) to determine where a
9library is located.
10
11```rust
12extern crate pkg_config;
13
14fn main() {
15 pkg_config::find_library("foo").unwrap();
16}
17```
18
19# License
20
21`pkg-config-rs` is primarily distributed under the terms of both the MIT
22license and the Apache License (Version 2.0), with portions covered by various
23BSD-like licenses.
24
25See LICENSE-APACHE, and LICENSE-MIT for details.
diff --git a/third_party/pkg-config-rs/src/lib.rs b/third_party/pkg-config-rs/src/lib.rs
new file mode 100644
index 0000000..5c25917
--- /dev/null
+++ b/third_party/pkg-config-rs/src/lib.rs
@@ -0,0 +1,471 @@
1//! A build dependency for Cargo libraries to find system artifacts through the
2//! `pkg-config` utility.
3//!
4//! This library will shell out to `pkg-config` as part of build scripts and
5//! probe the system to determine how to link to a specified library. The
6//! `Config` structure serves as a method of configuring how `pkg-config` is
7//! invoked in a builder style.
8//!
9//! A number of environment variables are available to globally configure how
10//! this crate will invoke `pkg-config`:
11//!
12//! * `PKG_CONFIG_ALLOW_CROSS` - if this variable is not set, then `pkg-config`
13//! will automatically be disabled for all cross compiles.
14//! * `FOO_NO_PKG_CONFIG` - if set, this will disable running `pkg-config` when
15//! probing for the library named `foo`.
16//!
17//! There are also a number of environment variables which can configure how a
18//! library is linked to (dynamically vs statically). These variables control
19//! whether the `--static` flag is passed. Note that this behavior can be
20//! overridden by configuring explicitly on `Config`. The variables are checked
21//! in the following order:
22//!
23//! * `FOO_STATIC` - pass `--static` for the library `foo`
24//! * `FOO_DYNAMIC` - do not pass `--static` for the library `foo`
25//! * `PKG_CONFIG_ALL_STATIC` - pass `--static` for all libraries
26//! * `PKG_CONFIG_ALL_DYNAMIC` - do not pass `--static` for all libraries
27//!
28//! After running `pkg-config` all appropriate Cargo metadata will be printed on
29//! stdout if the search was successful.
30//!
31//! # Example
32//!
33//! Find the system library named `foo`.
34//!
35//! ```no_run
36//! extern crate pkg_config;
37//!
38//! fn main() {
39//! pkg_config::probe_library("foo").unwrap();
40//! }
41//! ```
42//!
43//! Configure how library `foo` is linked to.
44//!
45//! ```no_run
46//! extern crate pkg_config;
47//!
48//! fn main() {
49//! pkg_config::Config::new().statik(true).probe("foo").unwrap();
50//! }
51//! ```
52
53#![doc(html_root_url = "http://alexcrichton.com/pkg-config-rs")]
54#![cfg_attr(test, deny(warnings))]
55
56use std::ascii::AsciiExt;
57use std::env;
58use std::error;
59use std::ffi::{OsStr, OsString};
60use std::fmt;
61use std::fs;
62use std::io;
63use std::path::{PathBuf, Path};
64use std::process::{Command, Output};
65use std::str;
66
67pub fn target_supported() -> bool {
68 let target = env::var("TARGET").unwrap_or(String::new());
69 let host = env::var("HOST").unwrap_or(String::new());
70
71 // Only use pkg-config in host == target situations by default (allowing an
72 // override) and then also don't use pkg-config on MSVC as it's really not
73 // meant to work there but when building MSVC code in a MSYS shell we may be
74 // able to run pkg-config anyway.
75 (host == target || env::var_os("PKG_CONFIG_ALLOW_CROSS").is_some()) &&
76 !target.contains("msvc")
77}
78
79#[derive(Clone)]
80pub struct Config {
81 statik: Option<bool>,
82 atleast_version: Option<String>,
83 extra_args: Vec<OsString>,
84 cargo_metadata: bool,
85}
86
87#[derive(Debug)]
88pub struct Library {
89 pub libs: Vec<String>,
90 pub link_paths: Vec<PathBuf>,
91 pub frameworks: Vec<String>,
92 pub framework_paths: Vec<PathBuf>,
93 pub include_paths: Vec<PathBuf>,
94 pub version: String,
95 _priv: (),
96}
97
98/// Represents all reasons `pkg-config` might not succeed or be run at all.
99pub enum Error {
100 /// Aborted because of `*_NO_PKG_CONFIG` environment variable.
101 ///
102 /// Contains the name of the responsible environment variable.
103 EnvNoPkgConfig(String),
104
105 /// Cross compilation detected.
106 ///
107 /// Override with `PKG_CONFIG_ALLOW_CROSS=1`.
108 CrossCompilation,
109
110 /// Failed to run `pkg-config`.
111 ///
112 /// Contains the command and the cause.
113 Command { command: String, cause: io::Error },
114
115 /// `pkg-config` did not exit sucessfully.
116 ///
117 /// Contains the command and output.
118 Failure { command: String, output: Output },
119
120 #[doc(hidden)]
121 // please don't match on this, we're likely to add more variants over time
122 __Nonexhaustive,
123}
124
125impl error::Error for Error {
126 fn description(&self) -> &str {
127 match *self {
128 Error::EnvNoPkgConfig(_) => "pkg-config requested to be aborted",
129 Error::CrossCompilation => {
130 "pkg-config doesn't handle cross compilation. \
131 Use PKG_CONFIG_ALLOW_CROSS=1 to override"
132 }
133 Error::Command { .. } => "failed to run pkg-config",
134 Error::Failure { .. } => "pkg-config did not exit sucessfully",
135 Error::__Nonexhaustive => panic!(),
136 }
137 }
138
139 fn cause(&self) -> Option<&error::Error> {
140 match *self {
141 Error::Command { ref cause, .. } => Some(cause),
142 _ => None,
143 }
144 }
145}
146
147// Workaround for temporary lack of impl Debug for Output in stable std
148struct OutputDebugger<'a>(&'a Output);
149
150// Lifted from 1.7 std
151impl<'a> fmt::Debug for OutputDebugger<'a> {
152 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
153 let stdout_utf8 = str::from_utf8(&self.0.stdout);
154 let stdout_debug: &fmt::Debug = match stdout_utf8 {
155 Ok(ref str) => str,
156 Err(_) => &self.0.stdout
157 };
158
159 let stderr_utf8 = str::from_utf8(&self.0.stderr);
160 let stderr_debug: &fmt::Debug = match stderr_utf8 {
161 Ok(ref str) => str,
162 Err(_) => &self.0.stderr
163 };
164
165 fmt.debug_struct("Output")
166 .field("status", &self.0.status)
167 .field("stdout", stdout_debug)
168 .field("stderr", stderr_debug)
169 .finish()
170 }
171}
172
173// Workaround for temporary lack of impl Debug for Output in stable std, continued
174impl fmt::Debug for Error {
175 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
176 match *self {
177 Error::EnvNoPkgConfig(ref name) => {
178 f.debug_tuple("EnvNoPkgConfig")
179 .field(name)
180 .finish()
181 }
182 Error::CrossCompilation => write!(f, "CrossCompilation"),
183 Error::Command { ref command, ref cause } => {
184 f.debug_struct("Command")
185 .field("command", command)
186 .field("cause", cause)
187 .finish()
188 }
189 Error::Failure { ref command, ref output } => {
190 f.debug_struct("Failure")
191 .field("command", command)
192 .field("output", &OutputDebugger(output))
193 .finish()
194 }
195 Error::__Nonexhaustive => panic!(),
196 }
197 }
198}
199
200impl fmt::Display for Error {
201 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
202 match *self {
203 Error::EnvNoPkgConfig(ref name) => {
204 write!(f, "Aborted because {} is set", name)
205 }
206 Error::CrossCompilation => {
207 write!(f, "Cross compilation detected. \
208 Use PKG_CONFIG_ALLOW_CROSS=1 to override")
209 }
210 Error::Command { ref command, ref cause } => {
211 write!(f, "Failed to run `{}`: {}", command, cause)
212 }
213 Error::Failure { ref command, ref output } => {
214 let stdout = str::from_utf8(&output.stdout).unwrap();
215 let stderr = str::from_utf8(&output.stderr).unwrap();
216 try!(write!(f, "`{}` did not exit successfully: {}", command, output.status));
217 if !stdout.is_empty() {
218 try!(write!(f, "\n--- stdout\n{}", stdout));
219 }
220 if !stderr.is_empty() {
221 try!(write!(f, "\n--- stderr\n{}", stderr));
222 }
223 Ok(())
224 }
225 Error::__Nonexhaustive => panic!(),
226 }
227 }
228}
229
230/// Deprecated in favor of the probe_library function
231#[doc(hidden)]
232pub fn find_library(name: &str) -> Result<Library, String> {
233 probe_library(name).map_err(|e| e.to_string())
234}
235
236/// Simple shortcut for using all default options for finding a library.
237pub fn probe_library(name: &str) -> Result<Library, Error> {
238 Config::new().probe(name)
239}
240
241/// Run `pkg-config` to get the value of a variable from a package using
242/// --variable.
243pub fn get_variable(package: &str, variable: &str) -> Result<String, Error> {
244 let arg = format!("--variable={}", variable);
245 let cfg = Config::new();
246 Ok(try!(run(cfg.command(package, &[&arg]))).trim_right().to_owned())
247}
248
249impl Config {
250 /// Creates a new set of configuration options which are all initially set
251 /// to "blank".
252 pub fn new() -> Config {
253 Config {
254 statik: None,
255 atleast_version: None,
256 extra_args: vec![],
257 cargo_metadata: true,
258 }
259 }
260
261 /// Indicate whether the `--static` flag should be passed.
262 ///
263 /// This will override the inference from environment variables described in
264 /// the crate documentation.
265 pub fn statik(&mut self, statik: bool) -> &mut Config {
266 self.statik = Some(statik);
267 self
268 }
269
270 /// Indicate that the library must be at least version `vers`.
271 pub fn atleast_version(&mut self, vers: &str) -> &mut Config {
272 self.atleast_version = Some(vers.to_string());
273 self
274 }
275
276 /// Add an argument to pass to pkg-config.
277 ///
278 /// It's placed after all of the arguments generated by this library.
279 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Config {
280 self.extra_args.push(arg.as_ref().to_os_string());
281 self
282 }
283
284 /// Define whether metadata should be emitted for cargo allowing it to
285 /// automatically link the binary. Defaults to `true`.
286 pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
287 self.cargo_metadata = cargo_metadata;
288 self
289 }
290
291 /// Deprecated in favor fo the `probe` function
292 #[doc(hidden)]
293 pub fn find(&self, name: &str) -> Result<Library, String> {
294 self.probe(name).map_err(|e| e.to_string())
295 }
296
297 /// Run `pkg-config` to find the library `name`.
298 ///
299 /// This will use all configuration previously set to specify how
300 /// `pkg-config` is run.
301 pub fn probe(&self, name: &str) -> Result<Library, Error> {
302 let abort_var_name = format!("{}_NO_PKG_CONFIG", envify(name));
303 if env::var_os(&abort_var_name).is_some() {
304 return Err(Error::EnvNoPkgConfig(abort_var_name))
305 } else if !target_supported() {
306 return Err(Error::CrossCompilation);
307 }
308
309 let mut library = Library::new();
310
311 let output = try!(run(self.command(name, &["--libs", "--cflags"])));
312 library.parse_libs_cflags(name, &output, self);
313
314 let output = try!(run(self.command(name, &["--modversion"])));
315 library.parse_modversion(&output);
316
317 Ok(library)
318 }
319
320 /// Deprecated in favor of the top level `get_variable` function
321 #[doc(hidden)]
322 pub fn get_variable(package: &str, variable: &str) -> Result<String, String> {
323 get_variable(package, variable).map_err(|e| e.to_string())
324 }
325
326 fn is_static(&self, name: &str) -> bool {
327 self.statik.unwrap_or_else(|| infer_static(name))
328 }
329
330 fn command(&self, name: &str, args: &[&str]) -> Command {
331 let exe = env::var("PKG_CONFIG").unwrap_or(String::from("pkg-config"));
332 let mut cmd = Command::new(exe);
333 if self.is_static(name) {
334 cmd.arg("--static");
335 }
336 cmd.args(args)
337 .args(&self.extra_args)
338 .env("PKG_CONFIG_ALLOW_SYSTEM_LIBS", "1");
339 if let Some(ref version) = self.atleast_version {
340 cmd.arg(&format!("{} >= {}", name, version));
341 } else {
342 cmd.arg(name);
343 }
344 cmd
345 }
346
347 fn print_metadata(&self, s: &str) {
348 if self.cargo_metadata {
349 println!("cargo:{}", s);
350 }
351 }
352}
353
354impl Library {
355 fn new() -> Library {
356 Library {
357 libs: Vec::new(),
358 link_paths: Vec::new(),
359 include_paths: Vec::new(),
360 frameworks: Vec::new(),
361 framework_paths: Vec::new(),
362 version: String::new(),
363 _priv: (),
364 }
365 }
366
367 fn parse_libs_cflags(&mut self, name: &str, output: &str, config: &Config) {
368 let parts = output.trim_right()
369 .split(' ')
370 .filter(|l| l.len() > 2)
371 .map(|arg| (&arg[0..2], &arg[2..]))
372 .collect::<Vec<_>>();
373
374 let mut dirs = Vec::new();
375 let statik = config.is_static(name);
376 for &(flag, val) in parts.iter() {
377 match flag {
378 "-L" => {
379 let meta = format!("rustc-link-search=native={}", val);
380 config.print_metadata(&meta);
381 dirs.push(PathBuf::from(val));
382 self.link_paths.push(PathBuf::from(val));
383 }
384 "-F" => {
385 let meta = format!("rustc-link-search=framework={}", val);
386 config.print_metadata(&meta);
387 self.framework_paths.push(PathBuf::from(val));
388 }
389 "-I" => {
390 self.include_paths.push(PathBuf::from(val));
391 }
392 "-l" => {
393 self.libs.push(val.to_string());
394 if statik && !is_system(val, &dirs) {
395 let meta = format!("rustc-link-lib=static={}", val);
396 config.print_metadata(&meta);
397 } else {
398 let meta = format!("rustc-link-lib={}", val);
399 config.print_metadata(&meta);
400 }
401 }
402 _ => {}
403 }
404 }
405
406 let mut iter = output.trim_right().split(' ');
407 while let Some(part) = iter.next() {
408 if part != "-framework" {
409 continue
410 }
411 if let Some(lib) = iter.next() {
412 let meta = format!("rustc-link-lib=framework={}", lib);
413 config.print_metadata(&meta);
414 self.frameworks.push(lib.to_string());
415 }
416 }
417 }
418
419 fn parse_modversion(&mut self, output: &str) {
420 self.version.push_str(output.trim());
421 }
422}
423
424fn infer_static(name: &str) -> bool {
425 let name = envify(name);
426 if env::var_os(&format!("{}_STATIC", name)).is_some() {
427 true
428 } else if env::var_os(&format!("{}_DYNAMIC", name)).is_some() {
429 false
430 } else if env::var_os("PKG_CONFIG_ALL_STATIC").is_some() {
431 true
432 } else if env::var_os("PKG_CONFIG_ALL_DYNAMIC").is_some() {
433 false
434 } else {
435 false
436 }
437}
438
439fn envify(name: &str) -> String {
440 name.chars().map(|c| c.to_ascii_uppercase()).map(|c| {
441 if c == '-' {'_'} else {c}
442 }).collect()
443}
444
445fn is_system(name: &str, dirs: &[PathBuf]) -> bool {
446 let libname = format!("lib{}.a", name);
447 let root = Path::new("/usr");
448 !dirs.iter().any(|d| {
449 !d.starts_with(root) && fs::metadata(&d.join(&libname)).is_ok()
450 })
451}
452
453fn run(mut cmd: Command) -> Result<String, Error> {
454 match cmd.output() {
455 Ok(output) => {
456 if output.status.success() {
457 let stdout = String::from_utf8(output.stdout).unwrap();
458 Ok(stdout)
459 } else {
460 Err(Error::Failure {
461 command: format!("{:?}", cmd),
462 output: output,
463 })
464 }
465 }
466 Err(cause) => Err(Error::Command {
467 command: format!("{:?}", cmd),
468 cause: cause,
469 }),
470 }
471}
diff --git a/third_party/pkg-config-rs/tests/foo.pc b/third_party/pkg-config-rs/tests/foo.pc
new file mode 100644
index 0000000..b1ae3d8
--- /dev/null
+++ b/third_party/pkg-config-rs/tests/foo.pc
@@ -0,0 +1,16 @@
1prefix=/usr
2exec_prefix=${prefix}
3libdir=${exec_prefix}/lib
4includedir=${prefix}/include/valgrind
5arch=amd64
6os=linux
7platform=amd64-linux
8valt_load_address=0x38000000
9
10Name: Valgrind
11Description: A dynamic binary instrumentation framework
12Version: 3.10.0.SVN
13Requires:
14Libs: -L${libdir}/valgrind -lcoregrind-amd64-linux -lvex-amd64-linux -lgcc
15Cflags: -I${includedir}
16
diff --git a/third_party/pkg-config-rs/tests/framework.pc b/third_party/pkg-config-rs/tests/framework.pc
new file mode 100644
index 0000000..57c0447
--- /dev/null
+++ b/third_party/pkg-config-rs/tests/framework.pc
@@ -0,0 +1,16 @@
1prefix=/usr
2exec_prefix=${prefix}
3libdir=${exec_prefix}/lib
4includedir=${prefix}/include/valgrind
5arch=amd64
6os=linux
7platform=amd64-linux
8valt_load_address=0x38000000
9
10Name: Valgrind
11Description: A dynamic binary instrumentation framework
12Version: 3.10.0.SVN
13Requires:
14Libs: -F${libdir} -framework foo
15Cflags: -I${includedir}
16
diff --git a/third_party/pkg-config-rs/tests/test.rs b/third_party/pkg-config-rs/tests/test.rs
new file mode 100644
index 0000000..ee8613c
--- /dev/null
+++ b/third_party/pkg-config-rs/tests/test.rs
@@ -0,0 +1,99 @@
1extern crate pkg_config;
2#[macro_use]
3extern crate lazy_static;
4
5use pkg_config::Error;
6use std::env;
7use std::sync::Mutex;
8use std::path::PathBuf;
9
10lazy_static! {
11 static ref LOCK: Mutex<()> = Mutex::new(());
12}
13
14fn reset() {
15 for (k, _) in env::vars() {
16 if k.contains("DYNAMIC") ||
17 k.contains("STATIC") ||
18 k.contains("PKG_CONFIG_ALLOW_CROSS") ||
19 k.contains("FOO_NO_PKG_CONFIG") {
20 env::remove_var(&k);
21 }
22 }
23 env::remove_var("TARGET");
24 env::remove_var("HOST");
25 env::set_var("PKG_CONFIG_PATH", &env::current_dir().unwrap().join("tests"));
26}
27
28fn find(name: &str) -> Result<pkg_config::Library, Error> {
29 pkg_config::probe_library(name)
30}
31
32#[test]
33fn cross_disabled() {
34 let _g = LOCK.lock();
35 reset();
36 env::set_var("TARGET", "foo");
37 env::set_var("HOST", "bar");
38 match find("foo") {
39 Err(Error::CrossCompilation) => {},
40 x => panic!("Error::CrossCompilation expected, found `{:?}`", x),
41 }
42}
43
44#[test]
45fn cross_enabled() {
46 let _g = LOCK.lock();
47 reset();
48 env::set_var("TARGET", "foo");
49 env::set_var("HOST", "bar");
50 env::set_var("PKG_CONFIG_ALLOW_CROSS", "1");
51 find("foo").unwrap();
52}
53
54#[test]
55fn package_disabled() {
56 let _g = LOCK.lock();
57 reset();
58 env::set_var("FOO_NO_PKG_CONFIG", "1");
59 match find("foo") {
60 Err(Error::EnvNoPkgConfig(name)) => {
61 assert_eq!(name, "FOO_NO_PKG_CONFIG")
62 }
63 x => panic!("Error::EnvNoPkgConfig expected, found `{:?}`", x),
64 }
65}
66
67#[test]
68fn output_ok() {
69 let _g = LOCK.lock();
70 reset();
71 let lib = find("foo").unwrap();
72 assert!(lib.libs.contains(&"gcc".to_string()));
73 assert!(lib.libs.contains(&"coregrind-amd64-linux".to_string()));
74 assert!(lib.link_paths.contains(&PathBuf::from("/usr/lib/valgrind")));
75}
76
77#[test]
78fn framework() {
79 let _g = LOCK.lock();
80 reset();
81 let lib = find("framework").unwrap();
82 assert!(lib.frameworks.contains(&"foo".to_string()));
83 assert!(lib.framework_paths.contains(&PathBuf::from("/usr/lib")));
84}
85
86#[test]
87fn get_variable() {
88 let _g = LOCK.lock();
89 reset();
90 let prefix = pkg_config::get_variable("foo", "prefix").unwrap();
91 assert_eq!(prefix, "/usr");
92}
93
94#[test]
95fn version() {
96 let _g = LOCK.lock();
97 reset();
98 assert_eq!(&find("foo").unwrap().version[..], "3.10.0.SVN");
99}