system-deps-6.2.0/.cargo_vcs_info.json0000644000000001360000000000100133160ustar { "git": { "sha1": "7d10f40e6cd29c007d5ed1e9358b0e0a7c43fcb3" }, "path_in_vcs": "" }system-deps-6.2.0/.github/release-drafter.yml000064400000000000000000000003451046102023000172400ustar 00000000000000template: | ## Whatโ€™s Changed $CHANGES categories: - title: '๐Ÿš€ Features' label: 'feature' - title: '๐Ÿ› Bug Fixes' labels: - 'fix' - 'bugfix' - 'bug' exclude-labels: - 'skip-changelog'system-deps-6.2.0/.github/workflows/ci.yml000064400000000000000000000036051046102023000166250ustar 00000000000000on: [push, pull_request] name: CI jobs: check: name: Check runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - uses: actions-rs/cargo@v1 with: command: check test: name: Test Suite runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macOS-latest] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - uses: actions-rs/cargo@v1 with: command: test test-Windows: name: Test Suite (Windows) runs-on: windows-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - uses: crazy-max/ghaction-chocolatey@v3 with: args: install pkgconfiglite --allow-empty-checksums - uses: actions-rs/cargo@v1 with: command: test fmt: name: Rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - run: rustup component add rustfmt - uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check clippy: name: Clippy runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - run: rustup component add clippy - uses: actions-rs/cargo@v1 with: command: clippy args: -- -D warnings system-deps-6.2.0/.github/workflows/release-drafter.yml000064400000000000000000000006121046102023000212720ustar 00000000000000name: Release Drafter on: push: # branches to consider in the event; optional, defaults to all branches: - master jobs: update_release_draft: runs-on: ubuntu-latest steps: # Drafts your next Release notes as Pull Requests are merged into "master" - uses: release-drafter/release-drafter@v5 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}system-deps-6.2.0/.gitignore000064400000000000000000000000241046102023000140720ustar 00000000000000/Cargo.lock /target system-deps-6.2.0/Cargo.toml0000644000000026500000000000100113170ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "system-deps" version = "6.2.0" authors = [ "Guillaume Desmottes ", "Josh Triplett ", ] description = "Discover and configure system dependencies from declarative dependencies in Cargo.toml" documentation = "https://docs.rs/system-deps/" readme = "README.md" keywords = [ "pkg-config", "build-dependencies", "build-depends", "manifest", "metadata", ] license = "MIT OR Apache-2.0" repository = "https://github.com/gdesmott/system-deps" [dependencies.cfg-expr] version = "0.15.5" features = ["targets"] [dependencies.heck] version = "0.4" [dependencies.pkg-config] version = "0.3.23" [dependencies.toml] version = "0.8" features = ["parse"] default-features = false [dependencies.version-compare] version = "0.1" [dev-dependencies.assert_matches] version = "1.5" [dev-dependencies.itertools] version = "0.11" [dev-dependencies.lazy_static] version = "1" system-deps-6.2.0/Cargo.toml.orig0000644000000014520000000000100122550ustar [package] name = "system-deps" version = "6.2.0" authors = ["Guillaume Desmottes ", "Josh Triplett "] license = "MIT OR Apache-2.0" repository = "https://github.com/gdesmott/system-deps" description = "Discover and configure system dependencies from declarative dependencies in Cargo.toml" keywords = ["pkg-config", "build-dependencies", "build-depends", "manifest", "metadata"] edition = "2018" documentation = "https://docs.rs/system-deps/" readme = "README.md" [dependencies] pkg-config = "0.3.23" toml = { version = "0.8", default-features = false, features = ["parse"] } version-compare = "0.1" heck = "0.4" cfg-expr = { version = "0.15.5", features = ["targets"] } [dev-dependencies] lazy_static = "1" itertools = "0.11" assert_matches = "1.5" system-deps-6.2.0/Cargo.toml.orig000064400000000000000000000014521046102023000147770ustar 00000000000000[package] name = "system-deps" version = "6.2.0" authors = ["Guillaume Desmottes ", "Josh Triplett "] license = "MIT OR Apache-2.0" repository = "https://github.com/gdesmott/system-deps" description = "Discover and configure system dependencies from declarative dependencies in Cargo.toml" keywords = ["pkg-config", "build-dependencies", "build-depends", "manifest", "metadata"] edition = "2018" documentation = "https://docs.rs/system-deps/" readme = "README.md" [dependencies] pkg-config = "0.3.23" toml = { version = "0.8", default-features = false, features = ["parse"] } version-compare = "0.1" heck = "0.4" cfg-expr = { version = "0.15.5", features = ["targets"] } [dev-dependencies] lazy_static = "1" itertools = "0.11" assert_matches = "1.5" system-deps-6.2.0/LICENSE-APACHE000064400000000000000000000251371046102023000140420ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. system-deps-6.2.0/LICENSE-MIT000064400000000000000000000017771046102023000135560ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. system-deps-6.2.0/README.md000064400000000000000000000031161046102023000133660ustar 00000000000000# system-deps [![](https://img.shields.io/crates/v/system-deps.svg)](https://crates.io/crates/system-deps) [![](https://docs.rs/system-deps/badge.svg)](https://docs.rs/system-deps) [![codecov](https://codecov.io/gh/gdesmott/system-deps/branch/master/graph/badge.svg?token=13DAFV8M8G)](https://codecov.io/gh/gdesmott/system-deps) [![CI](https://github.com/gdesmott/system-deps/workflows/CI/badge.svg)](https://github.com/gdesmott/system-deps/actions) `system-deps` lets you write system dependencies in `Cargo.toml` metadata, rather than programmatically in `build.rs`. This makes those dependencies declarative, so other tools can read them as well. For now only `pkg-config` dependencies are supported, but we are planning to [expand it](https://github.com/gdesmott/system-deps/issues/3) at some point. Users can override dependency flags using environment variables if needed. `system-deps` also allows `-sys` crates to optionally internally build and static link the required system library. `system-deps` has been started as a fork of the [metadeps](https://github.com/joshtriplett/metadeps) project. ## Documentation See the [crate documentation](https://docs.rs/system-deps/). ## Usage In your `Cargo.toml`: ```toml [build-dependencies] system-deps = "2.0" ``` Then, to declare a dependency on `testlib >= 1.2` add the following section: ```toml [package.metadata.system-deps] testlib = "1.2" ``` Finally, in your `build.rs`, add: ```rust fn main() { system_deps::Config::new().probe().unwrap(); } ``` See the [crate documentation](https://docs.rs/system-deps/) for more advanced features. system-deps-6.2.0/src/lib.rs000064400000000000000000001253071046102023000140210ustar 00000000000000#![allow(clippy::needless_doctest_main)] #![allow(clippy::result_large_err)] //!`system-deps` lets you write system dependencies in `Cargo.toml` metadata, //! rather than programmatically in `build.rs`. This makes those dependencies //! declarative, so other tools can read them as well. //! //! # Usage //! In your `Cargo.toml`: //! //! ```toml //! [build-dependencies] //! system-deps = "2.0" //! ``` //! //! Then, to declare a dependency on `testlib >= 1.2` //! add the following section: //! //! ```toml //! [package.metadata.system-deps] //! testlib = "1.2" //! ``` //! //! Finally, in your `build.rs`, add: //! //! ```should_panic //! fn main() { //! system_deps::Config::new().probe().unwrap(); //! } //! ``` //! //! # Version format //! //! Versions can be expressed in the following formats //! //! * "1.2" or ">= 1.2": At least version 1.2 //! * ">= 1.2, < 2.0": At least version 1.2 but less than version 2.0 //! //! In the future more complicated version expressions might be supported. //! //! Note that these versions are not interpreted according to the semver rules, but based on the //! rules defined by pkg-config. //! //! # Feature-specific dependency //! You can easily declare an optional system dependency by associating it with a feature: //! //! ```toml //! [package.metadata.system-deps] //! testdata = { version = "4.5", feature = "use-testdata" } //! ``` //! //! `system-deps` will check for `testdata` only if the `use-testdata` feature has been enabled. //! //! # Optional dependency //! //! Another option is to use the `optional` setting, which can also be used using [features versions](#feature-versions): //! //! ```toml //! [package.metadata.system-deps] //! test-data = { version = "4.5", optional = true } //! testmore = { version = "2", v3 = { version = "3.0", optional = true }} //! ``` //! //! `system-deps` will automatically export for each dependency a feature `system_deps_have_$DEP` where `$DEP` //! is the `toml` key defining the dependency in [snake_case](https://en.wikipedia.org/wiki/Snake_case). //! This can be used to check if an optional dependency has been found or not: //! //! ``` //! #[cfg(system_deps_have_testdata)] //! println!("found test-data"); //! ``` //! //! # Overriding library name //! `toml` keys cannot contain dot characters so if your library name does, you can define it using the `name` field: //! //! ```toml //! [package.metadata.system-deps] //! glib = { name = "glib-2.0", version = "2.64" } //! ``` //! //! # Fallback library names //! Some libraries may be available under different names on different platforms or distributions. //! To allow for this, you can define fallback names to search for if the main library name does not work. //! //! ```toml //! [package.metadata.system-deps] //! aravis = { fallback-names = ["aravis-0.8"] } //! ``` //! //! You may also specify different fallback names for different versions: //! //! [package.metadata.system-deps.libfoo] //! version = "0.1" //! fallback-names = ["libfoo-0.1"] //! v1 = { version = "1.0", fallback-names = ["libfoo1"] } //! v2 = { version = "2.0", fallback-names = ["libfoo2"] } //! //! # Feature versions //! `-sys` crates willing to support various versions of their underlying system libraries //! can use features to control the version of the dependency required. //! `system-deps` will pick the highest version among enabled features. //! Such version features must use the pattern `v1_0`, `v1_2`, etc. //! //! ```toml //! [features] //! v1_2 = [] //! v1_4 = ["v1_2"] //! v1_6 = ["v1_4"] //! //! [package.metadata.system-deps.gstreamer_1_0] //! name = "gstreamer-1.0" //! version = "1.0" //! v1_2 = { version = "1.2" } //! v1_4 = { version = "1.4" } //! v1_6 = { version = "1.6" } //! ``` //! //! The same mechanism can be used to require a different library name depending on the version: //! //! ```toml //! [package.metadata.system-deps.gst_gl] //! name = "gstreamer-gl-1.0" //! version = "1.14" //! v1_18 = { version = "1.18", name = "gstreamer-gl-egl-1.0" } //! ``` //! //! # Target specific dependencies //! //! You can define target specific dependencies: //! //! ```toml //! [package.metadata.system-deps.'cfg(target_os = "linux")'] //! testdata = "1" //! [package.metadata.system-deps.'cfg(not(target_os = "macos"))'] //! testlib = "1" //! [package.metadata.system-deps.'cfg(unix)'] //! testanotherlib = { version = "1", optional = true } //! ``` //! //! See [the Rust documentation](https://doc.rust-lang.org/reference/conditional-compilation.html) //! for the exact syntax. //! Currently, those keys are supported: //! - `target_arch` //! - `target_endian` //! - `target_env` //! - `target_family` //! - `target_os` //! - `target_pointer_width` //! - `target_vendor` //! - `unix` and `windows` //! //! # Overriding build flags //! By default `system-deps` automatically defines the required build flags for each dependency using the information fetched from `pkg-config`. //! These flags can be overridden using environment variables if needed: //! - `SYSTEM_DEPS_$NAME_SEARCH_NATIVE` to override the [`cargo:rustc-link-search=native`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-searchkindpath) flag; //! - `SYSTEM_DEPS_$NAME_SEARCH_FRAMEWORK` to override the [`cargo:rustc-link-search=framework`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-searchkindpath) flag; //! - `SYSTEM_DEPS_$NAME_LIB` to override the [`cargo:rustc-link-lib`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib) flag; //! - `SYSTEM_DEPS_$NAME_LIB_FRAMEWORK` to override the [`cargo:rustc-link-lib=framework`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib) flag; //! - `SYSTEM_DEPS_$NAME_INCLUDE` to override the [`cargo:include`](https://kornel.ski/rust-sys-crate#headers) flag. //! //! With `$NAME` being the upper case name of the key defining the dependency in `Cargo.toml`. //! For example `SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE=/opt/lib` could be used to override a dependency named `testlib`. //! //! One can also define the environment variable `SYSTEM_DEPS_$NAME_NO_PKG_CONFIG` to fully disable `pkg-config` lookup //! for the given dependency. In this case at least SYSTEM_DEPS_$NAME_LIB or SYSTEM_DEPS_$NAME_LIB_FRAMEWORK should be defined as well. //! //! # Internally build system libraries //! //! `-sys` crates can provide support for building and statically link their underlying system library as part of their build process. //! Here is how to do this in your `build.rs`: //! ```should_panic //! fn main() { //! system_deps::Config::new() //! .add_build_internal("testlib", |lib, version| { //! // Actually build the library here that fulfills the passed in version requirements //! system_deps::Library::from_internal_pkg_config("build/path-to-pc-file", lib, "1.2.4") //! }) //! .probe() //! .unwrap(); //! } //! ``` //! //! This feature can be controlled using the `SYSTEM_DEPS_$NAME_BUILD_INTERNAL` environment variable //! which can have the following values: //! - `auto`: build the dependency only if the required version has not been found by `pkg-config`; //! - `always`: always build the dependency, ignoring any version which may be installed on the system; //! - `never`: (default) never build the dependency, `system-deps` will fail if the required version is not found on the system. //! //! You can also use the `SYSTEM_DEPS_BUILD_INTERNAL` environment variable with the same values //! defining the behavior for all the dependencies which don't have `SYSTEM_DEPS_$NAME_BUILD_INTERNAL` defined. //! //! # Static linking //! //! By default all libraries are dynamically linked, except when build internally as [described above](#internally-build-system-libraries). //! Libraries can be statically linked by defining the environment variable `SYSTEM_DEPS_$NAME_LINK=static`. //! You can also use `SYSTEM_DEPS_LINK=static` to statically link all the libraries. #![deny(missing_docs)] #[cfg(test)] #[macro_use] extern crate lazy_static; #[cfg(test)] mod test; use heck::{ToShoutySnakeCase, ToSnakeCase}; use std::collections::HashMap; use std::env; use std::fmt; use std::ops::RangeBounds; use std::path::{Path, PathBuf}; use std::str::FromStr; mod metadata; use metadata::MetaData; /// system-deps errors #[derive(Debug)] pub enum Error { /// pkg-config error PkgConfig(pkg_config::Error), /// One of the `Config::add_build_internal` closures failed BuildInternalClosureError(String, BuildInternalClosureError), /// Failed to read `Cargo.toml` FailToRead(String, std::io::Error), /// Raised when an error is detected in the metadata defined in `Cargo.toml` InvalidMetadata(String), /// Raised when dependency defined manually using `SYSTEM_DEPS_$NAME_NO_PKG_CONFIG` /// did not define at least one lib using `SYSTEM_DEPS_$NAME_LIB` or /// `SYSTEM_DEPS_$NAME_LIB_FRAMEWORK` MissingLib(String), /// An environment variable in the form of `SYSTEM_DEPS_$NAME_BUILD_INTERNAL` /// contained an invalid value (allowed: `auto`, `always`, `never`) BuildInternalInvalid(String), /// system-deps has been asked to internally build a lib, through /// `SYSTEM_DEPS_$NAME_BUILD_INTERNAL=always' or `SYSTEM_DEPS_$NAME_BUILD_INTERNAL=auto', /// but not closure has been defined using `Config::add_build_internal` to build /// this lib BuildInternalNoClosure(String, String), /// The library which has been build internally does not match the /// required version defined in `Cargo.toml` BuildInternalWrongVersion(String, String, String), /// The `cfg()` expression used in `Cargo.toml` is currently not supported UnsupportedCfg(String), } impl From for Error { fn from(err: pkg_config::Error) -> Self { Self::PkgConfig(err) } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::PkgConfig(e) => Some(e), Self::BuildInternalClosureError(_, e) => Some(e), Self::FailToRead(_, e) => Some(e), _ => None, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PkgConfig(e) => write!(f, "{}", e), Self::BuildInternalClosureError(s, e) => write!(f, "Failed to build {}: {}", s, e), Self::FailToRead(s, _) => write!(f, "{}", s), Self::InvalidMetadata(s) => write!(f, "{}", s), Self::MissingLib(s) => write!( f, "You should define at least one lib using {} or {}", EnvVariable::new_lib(s), EnvVariable::new_lib_framework(s), ), Self::BuildInternalInvalid(s) => write!(f, "{}", s), Self::BuildInternalNoClosure(s1, s2) => write!( f, "Missing build internal closure for {} (version {})", s1, s2 ), Self::BuildInternalWrongVersion(s1, s2, s3) => write!( f, "Internally built {} {} but minimum required version is {}", s1, s2, s3 ), Self::UnsupportedCfg(s) => write!(f, "Unsupported cfg() expression: {}", s), } } } #[derive(Debug, Default)] /// All the system dependencies retrieved by [Config::probe]. pub struct Dependencies { libs: HashMap, } impl Dependencies { /// Retrieve details about a system dependency. /// /// # Arguments /// /// * `name`: the name of the `toml` key defining the dependency in `Cargo.toml` pub fn get_by_name(&self, name: &str) -> Option<&Library> { self.libs.get(name) } /// A vector listing all system dependencies in sorted (for build reproducibility) order. /// The first element of the tuple is the name of the `toml` key defining the /// dependency in `Cargo.toml`. pub fn iter(&self) -> Vec<(&str, &Library)> { let mut v = self .libs .iter() .map(|(k, v)| (k.as_str(), v)) .collect::>(); v.sort_by_key(|x| x.0); v } fn aggregate_str &Vec>(&self, getter: F) -> Vec<&str> { let mut v = self .libs .values() .flat_map(getter) .map(|s| s.as_str()) .collect::>(); v.sort_unstable(); v.dedup(); v } fn aggregate_path_buf &Vec>(&self, getter: F) -> Vec<&PathBuf> { let mut v = self.libs.values().flat_map(getter).collect::>(); v.sort(); v.dedup(); v } /// Returns a vector of [Library::libs] of each library, removing duplicates. pub fn all_libs(&self) -> Vec<&str> { let mut v = self .libs .values() .flat_map(|l| l.libs.iter().map(|lib| lib.name.as_str())) .collect::>(); v.sort_unstable(); v.dedup(); v } /// Returns a vector of [Library::link_paths] of each library, removing duplicates. pub fn all_link_paths(&self) -> Vec<&PathBuf> { self.aggregate_path_buf(|l| &l.link_paths) } /// Returns a vector of [Library::frameworks] of each library, removing duplicates. pub fn all_frameworks(&self) -> Vec<&str> { self.aggregate_str(|l| &l.frameworks) } /// Returns a vector of [Library::framework_paths] of each library, removing duplicates. pub fn all_framework_paths(&self) -> Vec<&PathBuf> { self.aggregate_path_buf(|l| &l.framework_paths) } /// Returns a vector of [Library::include_paths] of each library, removing duplicates. pub fn all_include_paths(&self) -> Vec<&PathBuf> { self.aggregate_path_buf(|l| &l.include_paths) } /// Returns a vector of [Library::defines] of each library, removing duplicates. pub fn all_defines(&self) -> Vec<(&str, &Option)> { let mut v = self .libs .values() .flat_map(|l| l.defines.iter()) .map(|(k, v)| (k.as_str(), v)) .collect::>(); v.sort(); v.dedup(); v } fn add(&mut self, name: &str, lib: Library) { self.libs.insert(name.to_string(), lib); } fn override_from_flags(&mut self, env: &EnvVariables) { for (name, lib) in self.libs.iter_mut() { if let Some(value) = env.get(&EnvVariable::new_search_native(name)) { lib.link_paths = split_paths(&value); } if let Some(value) = env.get(&EnvVariable::new_search_framework(name)) { lib.framework_paths = split_paths(&value); } if let Some(value) = env.get(&EnvVariable::new_lib(name)) { let should_be_linked_statically = env .has_value(&EnvVariable::new_link(Some(name)), "static") || env.has_value(&EnvVariable::new_link(None), "static"); // If somebody manually mandates static linking, that is a // clear intent. Let's just assume that a static lib is // available and let the linking fail if the user is wrong. let is_static_lib_available = should_be_linked_statically; lib.libs = split_string(&value) .into_iter() .map(|l| InternalLib::new(l, is_static_lib_available)) .collect(); } if let Some(value) = env.get(&EnvVariable::new_lib_framework(name)) { lib.frameworks = split_string(&value); } if let Some(value) = env.get(&EnvVariable::new_include(name)) { lib.include_paths = split_paths(&value); } } } fn gen_flags(&self) -> Result { let mut flags = BuildFlags::new(); let mut include_paths = Vec::new(); for (name, lib) in self.iter() { include_paths.extend(lib.include_paths.clone()); if lib.source == Source::EnvVariables && lib.libs.is_empty() && lib.frameworks.is_empty() { return Err(Error::MissingLib(name.to_string())); } lib.link_paths .iter() .for_each(|l| flags.add(BuildFlag::SearchNative(l.to_string_lossy().to_string()))); lib.framework_paths.iter().for_each(|f| { flags.add(BuildFlag::SearchFramework(f.to_string_lossy().to_string())) }); lib.libs.iter().for_each(|l| { flags.add(BuildFlag::Lib( l.name.clone(), lib.statik && l.is_static_available, )) }); lib.frameworks .iter() .for_each(|f| flags.add(BuildFlag::LibFramework(f.clone()))); } // Export DEP_$CRATE_INCLUDE env variable with the headers paths, // see https://kornel.ski/rust-sys-crate#headers if !include_paths.is_empty() { if let Ok(paths) = std::env::join_paths(include_paths) { flags.add(BuildFlag::Include(paths.to_string_lossy().to_string())); } } // Export cargo:rerun-if-env-changed instructions for all env variables affecting system-deps behaviour flags.add(BuildFlag::RerunIfEnvChanged( EnvVariable::new_build_internal(None), )); flags.add(BuildFlag::RerunIfEnvChanged(EnvVariable::new_link(None))); for (name, _lib) in self.libs.iter() { EnvVariable::set_rerun_if_changed_for_all_variants(&mut flags, name); } Ok(flags) } } #[derive(Debug)] /// Error used in return value of `Config::add_build_internal` closures pub enum BuildInternalClosureError { /// `pkg-config` error PkgConfig(pkg_config::Error), /// General failure Failed(String), } impl From for BuildInternalClosureError { fn from(err: pkg_config::Error) -> Self { Self::PkgConfig(err) } } impl BuildInternalClosureError { /// Create a new `BuildInternalClosureError::Failed` representing a general /// failure. /// /// # Arguments /// /// * `details`: human-readable details about the failure pub fn failed(details: &str) -> Self { Self::Failed(details.to_string()) } } impl std::error::Error for BuildInternalClosureError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::PkgConfig(e) => Some(e), _ => None, } } } impl fmt::Display for BuildInternalClosureError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PkgConfig(e) => write!(f, "{}", e), Self::Failed(s) => write!(f, "{}", s), } } } // Enum representing the environment variables user can define to tune system-deps. #[derive(Debug, PartialEq)] enum EnvVariable { Lib(String), LibFramework(String), SearchNative(String), SearchFramework(String), Include(String), NoPkgConfig(String), BuildInternal(Option), Link(Option), } impl EnvVariable { fn new_lib(lib: &str) -> Self { Self::Lib(lib.to_string()) } fn new_lib_framework(lib: &str) -> Self { Self::LibFramework(lib.to_string()) } fn new_search_native(lib: &str) -> Self { Self::SearchNative(lib.to_string()) } fn new_search_framework(lib: &str) -> Self { Self::SearchFramework(lib.to_string()) } fn new_include(lib: &str) -> Self { Self::Include(lib.to_string()) } fn new_no_pkg_config(lib: &str) -> Self { Self::NoPkgConfig(lib.to_string()) } fn new_build_internal(lib: Option<&str>) -> Self { Self::BuildInternal(lib.map(|l| l.to_string())) } fn new_link(lib: Option<&str>) -> Self { Self::Link(lib.map(|l| l.to_string())) } fn suffix(&self) -> &'static str { match self { EnvVariable::Lib(_) => "LIB", EnvVariable::LibFramework(_) => "LIB_FRAMEWORK", EnvVariable::SearchNative(_) => "SEARCH_NATIVE", EnvVariable::SearchFramework(_) => "SEARCH_FRAMEWORK", EnvVariable::Include(_) => "INCLUDE", EnvVariable::NoPkgConfig(_) => "NO_PKG_CONFIG", EnvVariable::BuildInternal(_) => "BUILD_INTERNAL", EnvVariable::Link(_) => "LINK", } } fn set_rerun_if_changed_for_all_variants(flags: &mut BuildFlags, name: &str) { #[inline] fn add_to_flags(flags: &mut BuildFlags, var: EnvVariable) { flags.add(BuildFlag::RerunIfEnvChanged(var)); } add_to_flags(flags, EnvVariable::new_lib(name)); add_to_flags(flags, EnvVariable::new_lib_framework(name)); add_to_flags(flags, EnvVariable::new_search_native(name)); add_to_flags(flags, EnvVariable::new_search_framework(name)); add_to_flags(flags, EnvVariable::new_include(name)); add_to_flags(flags, EnvVariable::new_no_pkg_config(name)); add_to_flags(flags, EnvVariable::new_build_internal(Some(name))); add_to_flags(flags, EnvVariable::new_link(Some(name))); } } impl fmt::Display for EnvVariable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let suffix = match self { EnvVariable::Lib(lib) | EnvVariable::LibFramework(lib) | EnvVariable::SearchNative(lib) | EnvVariable::SearchFramework(lib) | EnvVariable::Include(lib) | EnvVariable::NoPkgConfig(lib) | EnvVariable::BuildInternal(Some(lib)) | EnvVariable::Link(Some(lib)) => { format!("{}_{}", lib.to_shouty_snake_case(), self.suffix()) } EnvVariable::BuildInternal(None) | EnvVariable::Link(None) => self.suffix().to_string(), }; write!(f, "SYSTEM_DEPS_{}", suffix) } } type FnBuildInternal = dyn FnOnce(&str, &str) -> std::result::Result; /// Structure used to configure `metadata` before starting to probe for dependencies pub struct Config { env: EnvVariables, build_internals: HashMap>, } impl Default for Config { fn default() -> Self { Self::new_with_env(EnvVariables::Environment) } } impl Config { /// Create a new set of configuration pub fn new() -> Self { Self::default() } fn new_with_env(env: EnvVariables) -> Self { Self { env, build_internals: HashMap::new(), } } /// Probe all libraries configured in the Cargo.toml /// `[package.metadata.system-deps]` section. /// /// The returned hash is using the `toml` key defining the dependency as key. pub fn probe(self) -> Result { let libraries = self.probe_full()?; let flags = libraries.gen_flags()?; // Output cargo flags println!("{}", flags); for (name, _) in libraries.iter() { println!("cargo:rustc-cfg=system_deps_have_{}", name.to_snake_case()); } Ok(libraries) } /// Add hook so system-deps can internally build library `name` if requested by user. /// /// It will only be triggered if the environment variable /// `SYSTEM_DEPS_$NAME_BUILD_INTERNAL` is defined with either `always` or /// `auto` as value. In the latter case, `func` is called only if the requested /// version of the library was not found on the system. /// /// # Arguments /// * `name`: the name of the library, as defined in `Cargo.toml` /// * `func`: closure called when internally building the library. /// It receives as argument the library name, and the minimum version required. pub fn add_build_internal(self, name: &str, func: F) -> Self where F: 'static + FnOnce(&str, &str) -> std::result::Result, { let mut build_internals = self.build_internals; build_internals.insert(name.to_string(), Box::new(func)); Self { env: self.env, build_internals, } } fn probe_full(mut self) -> Result { let mut libraries = self.probe_pkg_config()?; libraries.override_from_flags(&self.env); Ok(libraries) } fn probe_pkg_config(&mut self) -> Result { let dir = self .env .get("CARGO_MANIFEST_DIR") .ok_or_else(|| Error::InvalidMetadata("$CARGO_MANIFEST_DIR not set".into()))?; let mut path = PathBuf::from(dir); path.push("Cargo.toml"); let metadata = MetaData::from_file(&path)?; let mut libraries = Dependencies::default(); for dep in metadata.deps.iter() { if let Some(cfg) = &dep.cfg { // Check if `cfg()` expression matches the target settings if !self.check_cfg(cfg)? { continue; } } let mut enabled_feature_overrides = Vec::new(); for o in dep.version_overrides.iter() { if self.has_feature(&o.key) { enabled_feature_overrides.push(o); } } if let Some(feature) = dep.feature.as_ref() { if !self.has_feature(feature) { continue; } } // Pick the highest feature enabled version let version; let lib_name; let fallback_lib_names; let optional; if enabled_feature_overrides.is_empty() { version = dep.version.as_deref(); lib_name = dep.lib_name(); fallback_lib_names = dep.fallback_names.as_deref().unwrap_or(&[]); optional = dep.optional; } else { enabled_feature_overrides.sort_by(|a, b| { fn min_version(r: metadata::VersionRange) -> &str { match r.start_bound() { std::ops::Bound::Unbounded => unreachable!(), std::ops::Bound::Excluded(_) => unreachable!(), std::ops::Bound::Included(b) => b, } } let a = min_version(metadata::parse_version(&a.version)); let b = min_version(metadata::parse_version(&b.version)); version_compare::compare(a, b) .expect("failed to compare versions") .ord() .expect("invalid version") }); let highest = enabled_feature_overrides.into_iter().last().unwrap(); version = Some(highest.version.as_str()); lib_name = highest.name.as_deref().unwrap_or(dep.lib_name()); fallback_lib_names = highest .fallback_names .as_deref() .or(dep.fallback_names.as_deref()) .unwrap_or(&[]); optional = highest.optional.unwrap_or(dep.optional); }; let version = version.ok_or_else(|| { Error::InvalidMetadata(format!("No version defined for {}", dep.key)) })?; let name = &dep.key; let build_internal = self.get_build_internal_status(name)?; // should the lib be statically linked? let statik = self .env .has_value(&EnvVariable::new_link(Some(name)), "static") || self.env.has_value(&EnvVariable::new_link(None), "static"); let mut library = if self.env.contains(&EnvVariable::new_no_pkg_config(name)) { Library::from_env_variables(name) } else if build_internal == BuildInternal::Always { self.call_build_internal(lib_name, version)? } else { let mut config = pkg_config::Config::new(); config .print_system_libs(false) .cargo_metadata(false) .range_version(metadata::parse_version(version)) .statik(statik); match Self::probe_with_fallback(config, lib_name, fallback_lib_names) { Ok((lib_name, lib)) => Library::from_pkg_config(lib_name, lib), Err(e) => { if build_internal == BuildInternal::Auto { // Try building the lib internally as a fallback self.call_build_internal(name, version)? } else if optional { // If the dep is optional just skip it continue; } else { return Err(e.into()); } } } }; library.statik = statik; libraries.add(name, library); } Ok(libraries) } fn probe_with_fallback<'a>( config: pkg_config::Config, name: &'a str, fallback_names: &'a [String], ) -> Result<(&'a str, pkg_config::Library), pkg_config::Error> { let error = match config.probe(name) { Ok(x) => return Ok((name, x)), Err(e) => e, }; for name in fallback_names { if let Ok(library) = config.probe(name) { return Ok((name, library)); } } Err(error) } fn get_build_internal_env_var(&self, var: EnvVariable) -> Result, Error> { match self.env.get(&var).as_deref() { Some(s) => { let b = BuildInternal::from_str(s).map_err(|_| { Error::BuildInternalInvalid(format!( "Invalid value in {}: {} (allowed: 'auto', 'always', 'never')", var, s )) })?; Ok(Some(b)) } None => Ok(None), } } fn get_build_internal_status(&self, name: &str) -> Result { match self.get_build_internal_env_var(EnvVariable::new_build_internal(Some(name)))? { Some(b) => Ok(b), None => Ok(self .get_build_internal_env_var(EnvVariable::new_build_internal(None))? .unwrap_or_default()), } } fn call_build_internal(&mut self, name: &str, version_str: &str) -> Result { let lib = match self.build_internals.remove(name) { Some(f) => f(name, version_str) .map_err(|e| Error::BuildInternalClosureError(name.into(), e))?, None => { return Err(Error::BuildInternalNoClosure( name.into(), version_str.into(), )) } }; // Check that the lib built internally matches the required version let version = metadata::parse_version(version_str); fn min_version(r: metadata::VersionRange) -> &str { match r.start_bound() { std::ops::Bound::Unbounded => unreachable!(), std::ops::Bound::Excluded(_) => unreachable!(), std::ops::Bound::Included(b) => b, } } fn max_version(r: metadata::VersionRange) -> Option<&str> { match r.end_bound() { std::ops::Bound::Included(_) => unreachable!(), std::ops::Bound::Unbounded => None, std::ops::Bound::Excluded(b) => Some(*b), } } let min = min_version(version.clone()); if version_compare::compare(&lib.version, min) == Ok(version_compare::Cmp::Lt) { return Err(Error::BuildInternalWrongVersion( name.into(), lib.version, version_str.into(), )); } if let Some(max) = max_version(version) { if version_compare::compare(&lib.version, max) == Ok(version_compare::Cmp::Ge) { return Err(Error::BuildInternalWrongVersion( name.into(), lib.version, version_str.into(), )); } } Ok(lib) } fn has_feature(&self, feature: &str) -> bool { let var: &str = &format!("CARGO_FEATURE_{}", feature.to_uppercase().replace('-', "_")); self.env.contains(var) } fn check_cfg(&self, cfg: &cfg_expr::Expression) -> Result { use cfg_expr::{targets::get_builtin_target_by_triple, Predicate}; let target = self .env .get("TARGET") .expect("no TARGET env variable defined"); let res = if let Some(target) = get_builtin_target_by_triple(&target) { cfg.eval(|pred| match pred { Predicate::Target(tp) => Some(tp.matches(target)), _ => None, }) } else { // Attempt to parse the triple, the target is not an official builtin let triple: cfg_expr::target_lexicon::Triple = target.parse().unwrap_or_else(|e| panic!("TARGET {} is not a builtin target, and it could not be parsed as a valid triplet: {}", target, e)); cfg.eval(|pred| match pred { Predicate::Target(tp) => Some(tp.matches(&triple)), _ => None, }) }; res.ok_or_else(|| Error::UnsupportedCfg(cfg.original().to_string())) } } #[derive(Debug, PartialEq, Eq)] /// From where the library settings have been retrieved pub enum Source { /// Settings have been retrieved from `pkg-config` PkgConfig, /// Settings have been defined using user defined environment variables EnvVariables, } #[derive(Debug, PartialEq, Eq)] /// Internal library name and if a static library is available on the system pub struct InternalLib { /// Name of the library pub name: String, /// Indicates if a static library is available on the system pub is_static_available: bool, } impl InternalLib { fn new(name: String, is_static_available: bool) -> Self { InternalLib { name, is_static_available, } } } #[derive(Debug)] /// A system dependency pub struct Library { /// Name of the library pub name: String, /// From where the library settings have been retrieved pub source: Source, /// libraries the linker should link on pub libs: Vec, /// directories where the compiler should look for libraries pub link_paths: Vec, /// frameworks the linker should link on pub frameworks: Vec, /// directories where the compiler should look for frameworks pub framework_paths: Vec, /// directories where the compiler should look for header files pub include_paths: Vec, /// macros that should be defined by the compiler pub defines: HashMap>, /// library version pub version: String, /// library is statically linked pub statik: bool, } impl Library { fn from_pkg_config(name: &str, l: pkg_config::Library) -> Self { // taken from: https://github.com/rust-lang/pkg-config-rs/blob/54325785816695df031cef3b26b6a9a203bbc01b/src/lib.rs#L502 let system_roots = if cfg!(target_os = "macos") { vec![PathBuf::from("/Library"), PathBuf::from("/System")] } else { let sysroot = env::var_os("PKG_CONFIG_SYSROOT_DIR") .or_else(|| env::var_os("SYSROOT")) .map(PathBuf::from); if cfg!(target_os = "windows") { if let Some(sysroot) = sysroot { vec![sysroot] } else { vec![] } } else { vec![sysroot.unwrap_or_else(|| PathBuf::from("/usr"))] } }; let is_static_available = |name: &String| -> bool { let libname = format!("lib{}.a", name); l.link_paths.iter().any(|dir| { !system_roots.iter().any(|sys| dir.starts_with(sys)) && dir.join(&libname).exists() }) }; Self { name: name.to_string(), source: Source::PkgConfig, libs: l .libs .iter() .map(|lib| InternalLib::new(lib.to_owned(), is_static_available(lib))) .collect(), link_paths: l.link_paths, include_paths: l.include_paths, frameworks: l.frameworks, framework_paths: l.framework_paths, defines: l.defines, version: l.version, statik: false, } } fn from_env_variables(name: &str) -> Self { Self { name: name.to_string(), source: Source::EnvVariables, libs: Vec::new(), link_paths: Vec::new(), include_paths: Vec::new(), frameworks: Vec::new(), framework_paths: Vec::new(), defines: HashMap::new(), version: String::new(), statik: false, } } /// Create a `Library` by probing `pkg-config` on an internal directory. /// This helper is meant to be used by `Config::add_build_internal` closures /// after having built the lib to return the library information to system-deps. /// /// This library will be statically linked. /// /// # Arguments /// /// * `pkg_config_dir`: the directory where the library `.pc` file is located /// * `lib`: the name of the library to look for /// * `version`: the minimum version of `lib` required /// /// # Examples /// /// ``` /// let mut config = system_deps::Config::new(); /// config.add_build_internal("mylib", |lib, version| { /// // Actually build the library here that fulfills the passed in version requirements /// system_deps::Library::from_internal_pkg_config("build-dir", /// lib, "1.2.4") /// }); /// ``` pub fn from_internal_pkg_config

( pkg_config_dir: P, lib: &str, version: &str, ) -> Result where P: AsRef, { // save current PKG_CONFIG_PATH, so we can restore it let old = env::var("PKG_CONFIG_PATH"); match old { Ok(ref s) => { let mut paths = env::split_paths(s).collect::>(); paths.push(PathBuf::from(pkg_config_dir.as_ref())); let paths = env::join_paths(paths).unwrap(); env::set_var("PKG_CONFIG_PATH", paths) } Err(_) => env::set_var("PKG_CONFIG_PATH", pkg_config_dir.as_ref()), } let pkg_lib = pkg_config::Config::new() .atleast_version(version) .print_system_libs(false) .cargo_metadata(false) .statik(true) .probe(lib); env::set_var("PKG_CONFIG_PATH", old.unwrap_or_else(|_| "".into())); match pkg_lib { Ok(pkg_lib) => { let mut lib = Self::from_pkg_config(lib, pkg_lib); lib.statik = true; Ok(lib) } Err(e) => Err(e.into()), } } } #[derive(Debug)] enum EnvVariables { Environment, #[cfg(test)] Mock(HashMap<&'static str, String>), } trait EnvVariablesExt { fn contains(&self, var: T) -> bool { self.get(var).is_some() } fn get(&self, var: T) -> Option; fn has_value(&self, var: T, val: &str) -> bool { match self.get(var) { Some(v) => v == val, None => false, } } } impl EnvVariablesExt<&str> for EnvVariables { fn get(&self, var: &str) -> Option { match self { EnvVariables::Environment => env::var(var).ok(), #[cfg(test)] EnvVariables::Mock(vars) => vars.get(var).cloned(), } } } impl EnvVariablesExt<&EnvVariable> for EnvVariables { fn get(&self, var: &EnvVariable) -> Option { let s = var.to_string(); let var: &str = s.as_ref(); self.get(var) } } #[derive(Debug, PartialEq)] enum BuildFlag { Include(String), SearchNative(String), SearchFramework(String), Lib(String, bool), // true if static LibFramework(String), RerunIfEnvChanged(EnvVariable), } impl fmt::Display for BuildFlag { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { BuildFlag::Include(paths) => write!(f, "include={}", paths), BuildFlag::SearchNative(lib) => write!(f, "rustc-link-search=native={}", lib), BuildFlag::SearchFramework(lib) => write!(f, "rustc-link-search=framework={}", lib), BuildFlag::Lib(lib, statik) => { if *statik { write!(f, "rustc-link-lib=static={}", lib) } else { write!(f, "rustc-link-lib={}", lib) } } BuildFlag::LibFramework(lib) => write!(f, "rustc-link-lib=framework={}", lib), BuildFlag::RerunIfEnvChanged(env) => write!(f, "rerun-if-env-changed={}", env), } } } #[derive(Debug, PartialEq)] struct BuildFlags(Vec); impl BuildFlags { fn new() -> Self { Self(Vec::new()) } fn add(&mut self, flag: BuildFlag) { self.0.push(flag); } } impl fmt::Display for BuildFlags { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for flag in self.0.iter() { writeln!(f, "cargo:{}", flag)?; } Ok(()) } } fn split_paths(value: &str) -> Vec { if !value.is_empty() { let paths = env::split_paths(&value); paths.map(|p| Path::new(&p).into()).collect() } else { Vec::new() } } fn split_string(value: &str) -> Vec { if !value.is_empty() { value.split(' ').map(|s| s.to_string()).collect() } else { Vec::new() } } #[derive(Debug, PartialEq)] enum BuildInternal { Auto, Always, Never, } impl Default for BuildInternal { fn default() -> Self { Self::Never } } impl FromStr for BuildInternal { type Err = ParseError; fn from_str(s: &str) -> Result { match s { "auto" => Ok(Self::Auto), "always" => Ok(Self::Always), "never" => Ok(Self::Never), v => Err(ParseError::VariantNotFound(v.to_owned())), } } } #[derive(Debug, PartialEq)] enum ParseError { VariantNotFound(String), } impl std::error::Error for ParseError {} impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::VariantNotFound(v) => write!(f, "Unknown variant: `{}`", v), } } } system-deps-6.2.0/src/metadata.rs000064400000000000000000000527071046102023000150360ustar 00000000000000// Parse system-deps metadata from Cargo.toml use std::{fmt, fs, io::Read, path::Path}; use toml::{map::Map, Value}; #[derive(Debug, PartialEq)] pub(crate) struct MetaData { pub(crate) deps: Vec, } #[derive(Debug, Clone, PartialEq)] pub(crate) struct Dependency { pub(crate) key: String, pub(crate) version: Option, pub(crate) name: Option, pub(crate) fallback_names: Option>, pub(crate) feature: Option, pub(crate) optional: bool, pub(crate) cfg: Option, pub(crate) version_overrides: Vec, } impl Dependency { fn new(name: &str) -> Self { Self { key: name.to_string(), ..Default::default() } } pub(crate) fn lib_name(&self) -> &str { self.name.as_ref().unwrap_or(&self.key) } } impl Default for Dependency { fn default() -> Self { Self { key: "".to_string(), version: None, name: None, fallback_names: None, feature: None, optional: false, cfg: None, version_overrides: Vec::new(), } } } #[derive(Debug, PartialEq)] enum VersionOverrideBuilderError { MissingVersionField, } impl fmt::Display for VersionOverrideBuilderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::MissingVersionField => write!(f, "missing version field"), } } } impl std::error::Error for VersionOverrideBuilderError {} #[derive(Debug, PartialEq)] enum MetadataError { MissingKey(String), NotATable(String), NestedCfg(String), NotStringOrTable(String), NotString(String), CfgExpr(cfg_expr::ParseError), Toml(toml::de::Error), UnexpectedVersionSetting(String, String, String), UnexpectedKey(String, String, String), VersionOverrideBuilder(VersionOverrideBuilderError), } impl fmt::Display for MetadataError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingKey(k) => write!(f, "missing key `{}`", k), Self::NotATable(k) => write!(f, "`{}` is not a table", k), Self::NestedCfg(k) => write!(f, "`{}`: cfg() cannot be nested", k), Self::NotString(k) => write!(f, "`{}`: not a string", k), Self::NotStringOrTable(k) => write!(f, "`{}`: not a string or a table", k), Self::CfgExpr(e) => write!(f, "{}", e), Self::Toml(e) => write!(f, "error parsing TOML: {}", e), Self::UnexpectedVersionSetting(n, k, t) => { write!( f, "{}: unexpected version settings key: {} type: {}", n, k, t ) } Self::UnexpectedKey(n, k, t) => write!(f, "{}: unexpected key {} type {}", n, k, t), Self::VersionOverrideBuilder(e) => write!(f, "{}", e), } } } impl std::error::Error for MetadataError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::CfgExpr(e) => Some(e), Self::Toml(e) => Some(e), Self::VersionOverrideBuilder(e) => Some(e), _ => None, } } } impl From for MetadataError { fn from(err: cfg_expr::ParseError) -> Self { Self::CfgExpr(err) } } impl From for MetadataError { fn from(err: toml::de::Error) -> Self { Self::Toml(err) } } impl From for MetadataError { fn from(err: VersionOverrideBuilderError) -> Self { Self::VersionOverrideBuilder(err) } } #[derive(Debug, Clone, PartialEq)] pub(crate) struct VersionOverride { pub(crate) key: String, pub(crate) version: String, pub(crate) name: Option, pub(crate) fallback_names: Option>, pub(crate) optional: Option, } struct VersionOverrideBuilder { version_id: String, version: Option, full_name: Option, fallback_names: Option>, optional: Option, } impl VersionOverrideBuilder { fn new(version_id: &str) -> Self { Self { version_id: version_id.to_string(), version: None, full_name: None, fallback_names: None, optional: None, } } fn build(self) -> Result { let version = self .version .ok_or(VersionOverrideBuilderError::MissingVersionField)?; Ok(VersionOverride { key: self.version_id, version, name: self.full_name, fallback_names: self.fallback_names, optional: self.optional, }) } } impl MetaData { pub(crate) fn from_file(path: &Path) -> Result { let mut manifest = fs::File::open(path).map_err(|e| { crate::Error::FailToRead(format!("error opening {}", path.display()), e) })?; let mut manifest_str = String::new(); manifest.read_to_string(&mut manifest_str).map_err(|e| { crate::Error::FailToRead(format!("error reading {}", path.display()), e) })?; Self::from_str(manifest_str) .map_err(|e| crate::Error::InvalidMetadata(format!("{}: {}", path.display(), e))) } fn from_str(manifest_str: String) -> Result { let toml = manifest_str.parse::()?; let key = "package.metadata.system-deps"; let meta = toml .get("package") .and_then(|v| v.get("metadata")) .and_then(|v| v.get("system-deps")) .ok_or_else(|| MetadataError::MissingKey(key.to_owned()))?; let deps = Self::parse_deps_table(meta, key, true)?; Ok(MetaData { deps }) } fn parse_deps_table( table: &Value, key: &str, allow_cfg: bool, ) -> Result, MetadataError> { let table = table .as_table() .ok_or_else(|| MetadataError::NotATable(key.to_owned()))?; let mut deps = Vec::new(); for (name, value) in table { if name.starts_with("cfg(") { if allow_cfg { let cfg_exp = cfg_expr::Expression::parse(name)?; for mut dep in Self::parse_deps_table(value, &format!("{}.{}", key, name), false)? { dep.cfg = Some(cfg_exp.clone()); deps.push(dep); } } else { return Err(MetadataError::NestedCfg(format!("{}.{}", key, name))); } } else { let dep = Self::parse_dep(key, name, value)?; deps.push(dep); } } Ok(deps) } fn parse_dep(key: &str, name: &str, value: &Value) -> Result { let mut dep = Dependency::new(name); match value { // somelib = "1.0" toml::Value::String(ref s) => { if !validate_version(s) { return Err(MetadataError::UnexpectedVersionSetting( key.into(), name.into(), value.type_str().to_owned(), )); } dep.version = Some(s.clone()); } toml::Value::Table(ref t) => { Self::parse_dep_table(key, name, &mut dep, t)?; } _ => { return Err(MetadataError::NotStringOrTable(format!("{}.{}", key, name))); } } Ok(dep) } fn parse_dep_table( p_key: &str, name: &str, dep: &mut Dependency, t: &Map, ) -> Result<(), MetadataError> { for (key, value) in t { match (key.as_str(), value) { ("feature", toml::Value::String(s)) => { dep.feature = Some(s.clone()); } ("version", toml::Value::String(s)) => { if !validate_version(s) { return Err(MetadataError::UnexpectedVersionSetting( format!("{}.{}", p_key, name), key.into(), value.type_str().to_owned(), )); } dep.version = Some(s.clone()); } ("name", toml::Value::String(s)) => { dep.name = Some(s.clone()); } ("fallback-names", toml::Value::Array(values)) => { let key = format!("{}.{}", p_key, name); dep.fallback_names = Some(Self::parse_name_list(&key, values)?); } ("optional", &toml::Value::Boolean(optional)) => { dep.optional = optional; } (version_feature, toml::Value::Table(version_settings)) if version_feature.starts_with('v') => { let mut builder = VersionOverrideBuilder::new(version_feature); for (k, v) in version_settings { match (k.as_str(), v) { ("version", toml::Value::String(feat_vers)) => { if !validate_version(feat_vers) { return Err(MetadataError::UnexpectedVersionSetting( format!("{}.{}", p_key, name), k.into(), v.type_str().to_owned(), )); } builder.version = Some(feat_vers.into()); } ("name", toml::Value::String(feat_name)) => { builder.full_name = Some(feat_name.into()); } ("fallback-names", toml::Value::Array(values)) => { let key = format!("{}.{}.{}", p_key, name, version_feature); builder.fallback_names = Some(Self::parse_name_list(&key, values)?); } ("optional", &toml::Value::Boolean(optional)) => { builder.optional = Some(optional); } _ => { return Err(MetadataError::UnexpectedVersionSetting( format!("{}.{}", p_key, name), k.to_owned(), v.type_str().to_owned(), )); } } } dep.version_overrides.push(builder.build()?); } _ => { return Err(MetadataError::UnexpectedKey( format!("{}.{}", p_key, name), key.to_owned(), value.type_str().to_owned(), )); } } } Ok(()) } fn parse_name_list(key: &str, values: &[Value]) -> Result, MetadataError> { values .iter() .enumerate() .map(|(i, value)| { value .as_str() .map(|x| x.to_owned()) .ok_or_else(|| MetadataError::NotString(format!("{}[{}]", key, i))) }) .collect() } } fn validate_version(version: &str) -> bool { if let Some((min, max)) = version.split_once(',') { if !min.trim_start().starts_with(">=") || !max.trim_start().starts_with('<') { return false; } true } else { true } } #[derive(Debug, Clone)] pub(crate) enum VersionRange<'a> { Range(std::ops::Range<&'a str>), RangeFrom(std::ops::RangeFrom<&'a str>), } impl<'a> std::ops::RangeBounds<&'a str> for VersionRange<'a> { fn start_bound(&self) -> std::ops::Bound<&&'a str> { match self { VersionRange::Range(r) => r.start_bound(), VersionRange::RangeFrom(r) => r.start_bound(), } } fn end_bound(&self) -> std::ops::Bound<&&'a str> { match self { VersionRange::Range(r) => r.end_bound(), VersionRange::RangeFrom(r) => r.end_bound(), } } } pub(crate) fn parse_version(version: &str) -> VersionRange { if let Some((min, max)) = version.split_once(',') { // Format checked when parsing let min = min.trim_start().strip_prefix(">=").unwrap().trim(); let max = max.trim_start().strip_prefix('<').unwrap().trim(); VersionRange::Range(min..max) } else if let Some(min) = version.trim_start().strip_prefix(">=") { VersionRange::RangeFrom(min..) } else { VersionRange::RangeFrom(version..) } } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; use cfg_expr::Expression; use std::{env, path::PathBuf}; fn parse_file(dir: &str) -> Result { let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let mut p: PathBuf = manifest_dir.into(); p.push("src"); p.push("tests"); p.push(dir); p.push("Cargo.toml"); assert!(p.exists()); MetaData::from_file(&p) } #[test] fn parse_good() { let m = parse_file("toml-good").unwrap(); assert_eq!( m, MetaData { deps: vec![ Dependency { key: "testdata".into(), version: Some("4".into()), ..Default::default() }, Dependency { key: "testlib".into(), version: Some("1".into()), feature: Some("test-feature".into()), ..Default::default() }, Dependency { key: "testmore".into(), version: Some("2".into()), feature: Some("another-test-feature".into()), ..Default::default() } ] } ) } #[test] fn parse_feature_not_string() { assert_matches!( parse_file("toml-feature-not-string"), Err(crate::Error::InvalidMetadata(_)) ); } #[test] fn parse_override_name() { let m = parse_file("toml-override-name").unwrap(); assert_eq!( m, MetaData { deps: vec![Dependency { key: "test_lib".into(), version: Some("1.0".into()), name: Some("testlib".into()), version_overrides: vec![VersionOverride { key: "v1_2".into(), version: "1.2".into(), name: None, fallback_names: None, optional: None, }], ..Default::default() },] } ) } #[test] fn parse_feature_versions() { let m = parse_file("toml-feature-versions").unwrap(); assert_eq!( m, MetaData { deps: vec![Dependency { key: "testdata".into(), version: Some("4".into()), version_overrides: vec![ VersionOverride { key: "v5".into(), version: "5".into(), name: None, fallback_names: None, optional: None, }, VersionOverride { key: "v6".into(), version: "6".into(), name: None, fallback_names: None, optional: None, }, ], ..Default::default() },] } ) } #[test] fn parse_fallback_names() { let m = parse_file("toml-fallback-names").unwrap(); assert_eq!( m, MetaData { deps: vec![Dependency { key: "test_lib".into(), version: Some("1.0".into()), name: Some("nosuchlib".into()), fallback_names: Some(vec![ "also-no-such-lib".into(), "testlib".into(), "should-not-get-here".into(), ]), version_overrides: vec![], ..Default::default() }] } ) } #[test] fn parse_version_fallback_names() { let m = parse_file("toml-version-fallback-names").unwrap(); assert_eq!( m, MetaData { deps: vec![Dependency { key: "test_lib".into(), version: Some("0.1".into()), name: Some("nosuchlib".into()), fallback_names: Some(vec![ "also-no-such-lib".into(), "testlib".into(), "should-not-get-here".into(), ]), version_overrides: vec![ VersionOverride { key: "v1".into(), version: "1.0".into(), name: None, fallback_names: None, optional: None, }, VersionOverride { key: "v2".into(), version: "2.0".into(), name: None, fallback_names: Some(vec!["testlib-2.0".into()]), optional: None, }, VersionOverride { key: "v99".into(), version: "99.0".into(), name: None, fallback_names: Some(vec![]), optional: None, }, ], ..Default::default() }] } ) } #[test] fn parse_optional() { let m = parse_file("toml-optional").unwrap(); assert_eq!( m, MetaData { deps: vec![ Dependency { key: "testbadger".into(), version: Some("1".into()), optional: true, ..Default::default() }, Dependency { key: "testlib".into(), version: Some("1.0".into()), optional: true, version_overrides: vec![VersionOverride { key: "v5".into(), version: "5.0".into(), name: Some("testlib-5.0".into()), fallback_names: None, optional: Some(false), },], ..Default::default() }, Dependency { key: "testmore".into(), version: Some("2".into()), version_overrides: vec![VersionOverride { key: "v3".into(), version: "3.0".into(), name: None, fallback_names: None, optional: Some(true), },], ..Default::default() }, ] } ) } #[test] fn parse_os_specific() { let m = parse_file("toml-os-specific").unwrap(); assert_eq!( m, MetaData { deps: vec![ Dependency { key: "testlib".into(), version: Some("1".into()), cfg: Some(Expression::parse("not(target_os = \"macos\")").unwrap()), ..Default::default() }, Dependency { key: "testdata".into(), version: Some("1".into()), cfg: Some(Expression::parse("target_os = \"linux\"").unwrap()), ..Default::default() }, Dependency { key: "testanotherlib".into(), version: Some("1".into()), cfg: Some(Expression::parse("unix").unwrap()), optional: true, ..Default::default() }, ] } ) } } system-deps-6.2.0/src/test.rs000064400000000000000000001216431046102023000142310ustar 00000000000000use itertools::Itertools; use std::cell::Cell; use std::collections::HashMap; use std::env; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::sync::Mutex; use assert_matches::assert_matches; use crate::Dependencies; use super::{ BuildFlags, BuildInternalClosureError, Config, EnvVariables, Error, InternalLib, Library, }; lazy_static! { static ref LOCK: Mutex<()> = Mutex::new(()); } fn create_config(path: &str, env: Vec<(&'static str, &'static str)>) -> Config { { // PKG_CONFIG_PATH is read by pkg-config, so we need to actually change the env let _l = LOCK.lock(); env::set_var( "PKG_CONFIG_PATH", env::current_dir().unwrap().join("src").join("tests"), ); } let mut hash = HashMap::new(); hash.insert( "CARGO_MANIFEST_DIR", env::current_dir() .unwrap() .join("src") .join("tests") .join(path) .to_string_lossy() .to_string(), ); hash.insert("CARGO_FEATURE_TEST_FEATURE", "".to_string()); env.iter().for_each(|(k, v)| { hash.insert(k, v.to_string()); }); Config::new_with_env(EnvVariables::Mock(hash)) } fn toml( path: &str, env: Vec<(&'static str, &'static str)>, ) -> Result<(Dependencies, BuildFlags), Error> { let libs = create_config(path, env).probe_full()?; let flags = libs.gen_flags()?; Ok((libs, flags)) } fn assert_flags(flags: BuildFlags, expected: &str) { // flags ordering isn't guaranteed so sort them out before comparing let flags = flags.to_string().split('\n').sorted().join("\n"); let expected = expected.to_string().split('\n').sorted().join("\n"); assert_eq!(flags, expected); } #[test] fn good() { let (libraries, flags) = toml("toml-good", vec![]).unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.version, "1.2.3"); assert_eq!( testlib.defines.get("BADGER").unwrap().as_deref(), Some("yes") ); assert!(testlib.defines.get("AWESOME").unwrap().is_none()); let testdata = libraries.get_by_name("testdata").unwrap(); assert_eq!(testdata.version, "4.5.6"); assert!(libraries.get_by_name("testmore").is_none()); assert_eq!(libraries.iter().len(), 2); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=someframework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK "#, ); } #[test] fn version_range() { let (libraries, _flags) = toml("toml-version-range", vec![]).unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.version, "1.2.3"); assert_eq!( testlib.defines.get("BADGER").unwrap().as_deref(), Some("yes") ); assert!(testlib.defines.get("AWESOME").unwrap().is_none()); let testdata = libraries.get_by_name("testdata").unwrap(); assert_eq!(testdata.version, "4.5.6"); assert_eq!(libraries.iter().len(), 2); } #[test] fn version_range_unsatisfied() { let err = toml_err("toml-version-range-unsatisfied"); assert_matches!(err, Error::PkgConfig(_)); let err_msg = err.to_string(); // pkgconf and pkg-config give different error messages if !err_msg.contains("Package 'testlib' has version '1.2.3', required version is '< 1.2'") && !err_msg.contains("Requested 'testlib < 1.2' but version of Test Library is 1.2.3") { panic!("Error not as expected: {:?}", err); } } fn toml_err(path: &str) -> Error { toml(path, vec![]).unwrap_err() } fn toml_err_invalid(path: &str, err_ends_with: &str) { let err = toml_err(path); assert_matches!(err, Error::InvalidMetadata(_)); if !err.to_string().ends_with(err_ends_with) { panic!( "Expected error to end with: {:?}\nGot error: {:?}", err_ends_with, err ); } } // Assert a PkgConfig error because requested lib version cannot be found fn toml_pkg_config_err_version( path: &str, expected_version: &str, env_vars: Vec<(&'static str, &'static str)>, ) { let err = toml(path, env_vars).unwrap_err(); match err { Error::PkgConfig(e) => match e { pkg_config::Error::ProbeFailure { command: cmd, output: _, name: _, } => { let s = format!(">= {}\"", expected_version); assert!(cmd.ends_with(&s)); } _ => panic!("Wrong pkg-config error type"), }, _ => panic!("Wrong error type"), } } #[test] fn missing_file() { assert_matches!(toml_err("toml-missing-file"), Error::FailToRead(_, _)); } #[test] fn missing_key() { toml_err_invalid( "toml-missing-key", "missing key `package.metadata.system-deps`", ); } #[test] fn not_table() { toml_err_invalid( "toml-not-table", "`package.metadata.system-deps` is not a table", ); } #[test] fn version_missing() { toml_err_invalid("toml-version-missing", "No version defined for testlib"); } #[test] fn version_not_string() { toml_err_invalid( "toml-version-not-string", "`package.metadata.system-deps.testlib`: not a string or a table", ); } #[test] fn version_in_table_not_string() { toml_err_invalid( "toml-version-in-table-not-string", "metadata.system-deps.testlib: unexpected key version type integer", ); } #[test] fn feature_not_string() { toml_err_invalid( "toml-feature-not-string", "metadata.system-deps.testlib: unexpected key feature type integer", ); } #[test] fn unexpected_key() { toml_err_invalid( "toml-unexpected-key", "metadata.system-deps.testlib: unexpected key color type string", ); } #[test] fn override_name() { let (libraries, _) = toml("toml-override-name", vec![]).unwrap(); let testlib = libraries.get_by_name("test_lib").unwrap(); assert_eq!(testlib.name, "testlib"); assert_eq!(testlib.version, "1.2.3"); // Enable feature 1.2 let (libraries, _) = toml("toml-override-name", vec![("CARGO_FEATURE_V1_2", "")]).unwrap(); let testlib = libraries.get_by_name("test_lib").unwrap(); assert_eq!(testlib.name, "testlib"); assert_eq!(testlib.version, "1.2.3"); } #[test] fn fallback_names() { let (libraries, flags) = toml("toml-fallback-names", vec![]).unwrap(); let testlib = libraries.get_by_name("test_lib").unwrap(); assert_eq!(testlib.name, "testlib"); assert_eq!(testlib.version, "1.2.3"); eprintln!(); eprintln!("{flags}"); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=someframework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LINK "#, ); } #[test] fn version_fallback_names() { let (libraries, flags) = toml("toml-version-fallback-names", vec![]).unwrap(); let testlib = libraries.get_by_name("test_lib").unwrap(); assert_eq!(testlib.name, "testlib"); assert_eq!(testlib.version, "1.2.3"); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=someframework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LINK "#, ); // Now try with v2 feature enabled. let (libraries, flags) = toml( "toml-version-fallback-names", vec![("CARGO_FEATURE_V2", "")], ) .unwrap(); let testlib = libraries.get_by_name("test_lib").unwrap(); assert_eq!(testlib.name, "testlib-2.0"); assert_eq!(testlib.version, "2.0.0"); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-lib=test cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TEST_LIB_LINK "#, ); } #[test] fn feature_versions() { let (libraries, _) = toml("toml-feature-versions", vec![]).unwrap(); let testdata = libraries.get_by_name("testdata").unwrap(); assert_eq!(testdata.name, "testdata"); assert_eq!(testdata.version, "4.5.6"); // version 5 is not available toml_pkg_config_err_version("toml-feature-versions", "5", vec![("CARGO_FEATURE_V5", "")]); // We check the highest version enabled by features toml_pkg_config_err_version("toml-feature-versions", "6", vec![("CARGO_FEATURE_V6", "")]); let (libraries, _) = toml("toml-version-names", vec![]).unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.name, "testlib"); assert_eq!(testlib.version, "1.2.3"); // Enable feature v2 let (libraries, _) = toml("toml-version-names", vec![("CARGO_FEATURE_V2", "")]).unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.name, "testlib-2.0"); assert_eq!(testlib.version, "2.0.0"); // Takes the higher feature let (libraries, _) = toml( "toml-version-names", vec![("CARGO_FEATURE_V2", ""), ("CARGO_FEATURE_V3", "")], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.name, "testlib-3.0"); } #[test] fn override_search_native() { #[cfg(target_os = "windows")] let paths_env = "/custom/path;/other/path"; #[cfg(not(target_os = "windows"))] let paths_env = "/custom/path:/other/path"; let (libraries, flags) = toml( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE", paths_env)], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!( testlib.link_paths, vec![Path::new("/custom/path"), Path::new("/other/path")] ); assert_flags( flags, r#"cargo:rustc-link-search=native=/custom/path cargo:rustc-link-search=native=/other/path cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=someframework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK "#, ); } #[test] fn override_search_framework() { let (libraries, flags) = toml( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK", "/custom/path")], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.framework_paths, vec![Path::new("/custom/path")]); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/custom/path cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=someframework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK "#, ); } #[test] fn override_lib() { let (libraries, flags) = toml( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_LIB", "overridden-test other-test")], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!( testlib.libs, vec!["overridden-test", "other-test"] .into_iter() .map(|name| InternalLib::new(name.to_string(), false)) .collect::>() ); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=overridden-test cargo:rustc-link-lib=other-test cargo:rustc-link-lib=framework=someframework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK "#, ); } #[test] fn override_framework() { let (libraries, flags) = toml( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK", "overridden-framework")], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.frameworks, vec!["overridden-framework"]); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=overridden-framework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK "#, ); } #[test] fn override_include() { let (libraries, flags) = toml( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_INCLUDE", "/other/include")], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.include_paths, vec![Path::new("/other/include")]); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=someframework cargo:include=/other/include cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK "#, ); } #[test] fn override_unset() { let (libraries, flags) = toml( "toml-good", vec![ ("SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE", ""), ("SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK", ""), ("SYSTEM_DEPS_TESTLIB_LIB", ""), ("SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK", ""), ("SYSTEM_DEPS_TESTLIB_INCLUDE", ""), ], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.link_paths, Vec::::new()); assert_eq!(testlib.framework_paths, Vec::::new()); assert_eq!(testlib.libs, Vec::::new()); assert_eq!(testlib.frameworks, Vec::::new()); assert_eq!(testlib.include_paths, Vec::::new()); assert_flags( flags, r"cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK ", ); } #[test] fn override_no_pkg_config() { let (libraries, flags) = toml( "toml-good", vec![ ("SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG", "1"), ("SYSTEM_DEPS_TESTLIB_LIB", "custom-lib"), ], ) .unwrap(); let testlib = libraries.get_by_name("testlib").unwrap(); assert_eq!(testlib.link_paths, Vec::::new()); assert_eq!(testlib.framework_paths, Vec::::new()); assert_eq!( testlib.libs, vec![InternalLib::new("custom-lib".to_string(), false)] ); assert_eq!(testlib.frameworks, Vec::::new()); assert_eq!(testlib.include_paths, Vec::::new()); assert_flags( flags, r"cargo:rustc-link-lib=custom-lib cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK ", ); } #[test] fn override_no_pkg_config_error() { let err = toml( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG", "1")], ) .unwrap_err(); assert_eq!( err.to_string(), "You should define at least one lib using SYSTEM_DEPS_TESTLIB_LIB or SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK" ); } fn test_build_internal( path: &'static str, env: Vec<(&'static str, &'static str)>, expected_lib: &'static str, ) -> Result<(Dependencies, bool), (Error, bool)> { let called = Rc::new(Cell::new(false)); let called_clone = called.clone(); let config = create_config(path, env).add_build_internal(expected_lib, move |lib, version| { called_clone.replace(true); assert_eq!(lib, expected_lib); let mut pkg_lib = pkg_config::Config::new() .print_system_libs(false) .cargo_metadata(false) .probe(lib) .unwrap(); pkg_lib.version = version.to_string(); Ok(Library::from_pkg_config(lib, pkg_lib)) }); match config.probe_full() { Ok(libraries) => Ok((libraries, called.get())), Err(e) => Err((e, called.get())), } } #[test] fn build_internal_always() { let (libraries, called) = test_build_internal( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL", "always")], "testlib", ) .unwrap(); assert!(called); assert!(libraries.get_by_name("testlib").is_some()); } #[test] fn build_internal_auto_not_called() { // No need to build the lib as the existing version is new enough let (libraries, called) = test_build_internal( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL", "auto")], "testlib", ) .unwrap(); assert!(!called); assert!(libraries.get_by_name("testlib").is_some()); } #[test] fn build_internal_auto_called() { // Version 5 is not available, so we should try building let (libraries, called) = test_build_internal( "toml-feature-versions", vec![ ("SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL", "auto"), ("CARGO_FEATURE_V5", ""), ], "testdata", ) .unwrap(); assert!(called); assert!(libraries.get_by_name("testdata").is_some()); } #[test] fn build_internal_auto_never() { // Version 5 is not available, but we forbid to build the lib let (err, called) = test_build_internal( "toml-feature-versions", vec![ ("SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL", "never"), ("CARGO_FEATURE_V5", ""), ], "testdata", ) .unwrap_err(); assert!(matches!(err, Error::PkgConfig(..))); assert!(!called); } #[test] fn build_internal_always_no_closure() { let config = create_config( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL", "always")], ); let err = config.probe_full().unwrap_err(); assert!(matches!(err, Error::BuildInternalNoClosure(..))); } #[test] fn build_internal_invalid() { let config = create_config( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL", "badger")], ); let err = config.probe_full().unwrap_err(); assert!(matches!(err, Error::BuildInternalInvalid(..))); } #[test] fn build_internal_wrong_version() { // Require version 5 let called = Rc::new(Cell::new(false)); let called_clone = called.clone(); let config = create_config( "toml-feature-versions", vec![ ("SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL", "auto"), ("CARGO_FEATURE_V5", ""), ], ) .add_build_internal("testdata", move |lib, _version| { called_clone.replace(true); assert_eq!(lib, "testdata"); let pkg_lib = pkg_config::Config::new() .print_system_libs(false) .cargo_metadata(false) .probe(lib) .unwrap(); Ok(Library::from_pkg_config(lib, pkg_lib)) }); let err = config.probe_full().unwrap_err(); assert!(matches!(err, Error::BuildInternalWrongVersion(..))); assert!(called.get()); } #[test] fn build_internal_fail() { let called = Rc::new(Cell::new(false)); let called_clone = called.clone(); let config = create_config( "toml-good", vec![("SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL", "always")], ) .add_build_internal("testlib", move |lib, _version| { called_clone.replace(true); assert_eq!(lib, "testlib"); Err(BuildInternalClosureError::failed("Something went wrong")) }); let err = config.probe_full().unwrap_err(); assert!(matches!(err, Error::BuildInternalClosureError(..))); assert!(called.get()); } #[test] fn build_internal_always_global() { let called = Rc::new(Cell::new((false, false))); let called_clone = called.clone(); let called_clone2 = called.clone(); let config = create_config("toml-good", vec![("SYSTEM_DEPS_BUILD_INTERNAL", "always")]) .add_build_internal("testlib", move |lib, version| { let (_, b) = called_clone.get(); called_clone.replace((true, b)); let mut pkg_lib = pkg_config::Config::new() .print_system_libs(false) .cargo_metadata(false) .probe(lib) .unwrap(); pkg_lib.version = version.to_string(); Ok(Library::from_pkg_config(lib, pkg_lib)) }) .add_build_internal("testdata", move |lib, version| { let (a, _) = called_clone2.get(); called_clone2.replace((a, true)); let mut pkg_lib = pkg_config::Config::new() .print_system_libs(false) .cargo_metadata(false) .probe(lib) .unwrap(); pkg_lib.version = version.to_string(); Ok(Library::from_pkg_config(lib, pkg_lib)) }); let libraries = config.probe_full().unwrap(); assert_eq!(called.get(), (true, true)); assert!(libraries.get_by_name("testlib").is_some()); assert!(libraries.get_by_name("testdata").is_some()); } #[test] fn build_internal_global_override() { // Request to build all libs using global var but disable it for a specific one let called = Rc::new(Cell::new((false, false))); let called_clone = called.clone(); let called_clone2 = called.clone(); let config = create_config( "toml-good", vec![ ("SYSTEM_DEPS_BUILD_INTERNAL", "always"), ("SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL", "never"), ], ) .add_build_internal("testlib", move |lib, version| { let (_, b) = called_clone.get(); called_clone.replace((true, b)); let mut pkg_lib = pkg_config::Config::new() .print_system_libs(false) .cargo_metadata(false) .probe(lib) .unwrap(); pkg_lib.version = version.to_string(); Ok(Library::from_pkg_config(lib, pkg_lib)) }) .add_build_internal("testdata", move |lib, version| { let (a, _) = called_clone2.get(); called_clone2.replace((a, true)); let mut pkg_lib = pkg_config::Config::new() .print_system_libs(false) .cargo_metadata(false) .probe(lib) .unwrap(); pkg_lib.version = version.to_string(); Ok(Library::from_pkg_config(lib, pkg_lib)) }); let libraries = config.probe_full().unwrap(); assert_eq!(called.get(), (false, true)); assert!(libraries.get_by_name("testlib").is_some()); assert!(libraries.get_by_name("testdata").is_some()); } #[test] fn build_internal_override_name() { let (libraries, called) = test_build_internal( "toml-override-name", vec![("SYSTEM_DEPS_BUILD_INTERNAL", "always")], "testlib", ) .unwrap(); assert!(called); assert!(libraries.get_by_name("test_lib").is_some()); } #[test] fn optional() { // without any feature, testmore is not optional toml_pkg_config_err_version("toml-optional", "2", vec![]); // when enabling v3 testmore is now optional let config = create_config("toml-optional", vec![("CARGO_FEATURE_V3", "")]); let libs = config.probe_full().unwrap(); assert!(libs.get_by_name("testlib").is_some()); assert!(libs.get_by_name("testmore").is_none()); assert!(libs.get_by_name("testbadger").is_none()); // testlib is no longer optional if enabling v5 toml_pkg_config_err_version("toml-optional", "5.0", vec![("CARGO_FEATURE_V5", "")]); } #[test] fn aggregate() { let (libraries, _) = toml("toml-two-libs", vec![]).unwrap(); assert_eq!(libraries.all_libs(), vec!["test", "test2"]); assert_eq!( libraries.all_link_paths(), vec![Path::new("/usr/lib"), Path::new("/usr/lib64")] ); assert_eq!( libraries.all_frameworks(), vec!["someframework", "someotherframework"] ); assert_eq!( libraries.all_framework_paths(), vec![Path::new("/usr/lib"), Path::new("/usr/lib64")] ); assert_eq!( libraries.all_include_paths(), vec![ Path::new("/usr/include/testanotherlib"), Path::new("/usr/include/testlib") ] ); assert_eq!( libraries.all_defines(), vec![ ("AWESOME", &None), ("BADGER", &Some("yes".into())), ("GREAT", &None) ] ); } #[test] fn os_specific() { let (libraries, _) = toml( "toml-os-specific", vec![("TARGET", "x86_64-alpine-linux-musl")], ) .unwrap(); assert!(libraries.get_by_name("testdata").is_some()); assert!(libraries.get_by_name("testlib").is_some()); assert!(libraries.get_by_name("testanotherlib").is_some()); let (libraries, _) = toml("toml-os-specific", vec![("TARGET", "x86_64-apple-darwin")]).unwrap(); assert!(libraries.get_by_name("testdata").is_none()); assert!(libraries.get_by_name("testlib").is_none()); assert!(libraries.get_by_name("testanotherlib").is_some()); let (libraries, _) = toml( "toml-os-specific", vec![("TARGET", "x86_64-pc-windows-gnu")], ) .unwrap(); assert!(libraries.get_by_name("testdata").is_none()); assert!(libraries.get_by_name("testlib").is_some()); assert!(libraries.get_by_name("testanotherlib").is_none()); } #[test] fn invalid_cfg() { let err = toml( "toml-invalid-cfg", vec![("TARGET", "x86_64-unknown-linux-gnu")], ) .unwrap_err(); assert_matches!(err, Error::UnsupportedCfg(_)); } #[test] fn static_one_lib() { let (libraries, flags) = toml( "toml-static", vec![("SYSTEM_DEPS_TESTSTATICLIB_LINK", "static")], ) .unwrap(); let testdata = libraries.get_by_name("testdata").unwrap(); assert!(!testdata.statik); let testlib = libraries.get_by_name("teststaticlib").unwrap(); assert!(testlib.statik); assert_flags( flags, r#"cargo:rustc-link-search=native=./src/tests/lib/ cargo:rustc-link-search=framework=./src/tests/lib/ cargo:rustc-link-lib=static=teststatic cargo:rustc-link-lib=framework=someframework cargo:include=./src/tests/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK "# .to_string() .as_str(), ); } #[test] fn override_static_no_pkg_config() { let (libraries, flags) = toml( "toml-static", vec![ ("SYSTEM_DEPS_TESTSTATICLIB_NO_PKG_CONFIG", "1"), ("SYSTEM_DEPS_TESTSTATICLIB_LIB", "custom-lib"), ("SYSTEM_DEPS_TESTSTATICLIB_LINK", "static"), ], ) .unwrap(); let testlib = libraries.get_by_name("teststaticlib").unwrap(); assert_eq!(testlib.link_paths, Vec::::new()); assert!(testlib.statik); assert_eq!(testlib.framework_paths, Vec::::new()); assert_eq!( testlib.libs, vec![InternalLib::new("custom-lib".to_string(), true)] ); assert_eq!(testlib.frameworks, Vec::::new()); assert_eq!(testlib.include_paths, Vec::::new()); assert_flags( flags, r"cargo:rustc-link-lib=static=custom-lib cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK ", ); } #[test] fn static_all_libs() { let (libraries, flags) = toml("toml-static", vec![("SYSTEM_DEPS_LINK", "static")]).unwrap(); let testdata = libraries.get_by_name("testdata").unwrap(); assert!(testdata.statik); let testlib = libraries.get_by_name("teststaticlib").unwrap(); assert!(testlib.statik); assert_flags( flags, r#"cargo:rustc-link-search=native=./src/tests/lib/ cargo:rustc-link-search=framework=./src/tests/lib/ cargo:rustc-link-lib=static=teststatic cargo:rustc-link-lib=framework=someframework cargo:include=./src/tests/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTSTATICLIB_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK "#, ); } #[test] fn static_lib_not_available() { let (libraries, flags) = toml("toml-good", vec![("SYSTEM_DEPS_LINK", "static")]).unwrap(); let testdata = libraries.get_by_name("testdata").unwrap(); assert!(testdata.statik); // testlib is not available as static library, which is why it is linked dynamically, // as seen below let testlib = libraries.get_by_name("testlib").unwrap(); assert!(testlib.statik); assert_flags( flags, r#"cargo:rustc-link-search=native=/usr/lib/ cargo:rustc-link-search=framework=/usr/lib/ cargo:rustc-link-lib=test cargo:rustc-link-lib=framework=someframework cargo:include=/usr/include/testlib cargo:rerun-if-env-changed=SYSTEM_DEPS_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTDATA_LINK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LIB_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_NATIVE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_SEARCH_FRAMEWORK cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_INCLUDE cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_NO_PKG_CONFIG cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_BUILD_INTERNAL cargo:rerun-if-env-changed=SYSTEM_DEPS_TESTLIB_LINK "#, ); } system-deps-6.2.0/src/tests/testanotherlib.pc000064400000000000000000000007241046102023000174150ustar 00000000000000prefix=/usr exec_prefix=${prefix} libdir=${exec_prefix}/lib/ libdir2=${exec_prefix}/lib64/ includedir=${prefix}/include/testlib includedir2=${prefix}/include/testanotherlib Name: Test Another Library Description: Another fake library to test pkg-config. Version: 1.2.3 Libs: -L${libdir} -ltest -L${libdir2} -ltest2 -F${libdir} -framework someframework -F${libdir2} -framework someotherframework Cflags: -I${includedir} -I${includedir2} -DBADGER=yes -DAWESOME -DGREAT system-deps-6.2.0/src/tests/testdata.pc000064400000000000000000000002601046102023000161720ustar 00000000000000Name: Test Data Description: Fake data to test pkg-config. Version: 4.5.6 prefix=/usr datarootdir=${prefix}/share datadir=${datarootdir} testdata=${datadir}/testdata/test.dat system-deps-6.2.0/src/tests/testlib-2.0.pc000064400000000000000000000003461046102023000163310ustar 00000000000000prefix=/usr exec_prefix=${prefix} libdir=${exec_prefix}/lib/ includedir=${prefix}/include/testlib Name: Test Library Description: A fake library to test pkg-config. Version: 2.0.0 Libs: -L${libdir} -ltest Cflags: -I${includedir} system-deps-6.2.0/src/tests/testlib-3.0.pc000064400000000000000000000003461046102023000163320ustar 00000000000000prefix=/usr exec_prefix=${prefix} libdir=${exec_prefix}/lib/ includedir=${prefix}/include/testlib Name: Test Library Description: A fake library to test pkg-config. Version: 3.0.0 Libs: -L${libdir} -ltest Cflags: -I${includedir} system-deps-6.2.0/src/tests/testlib.pc000064400000000000000000000004421046102023000160310ustar 00000000000000prefix=/usr exec_prefix=${prefix} libdir=${exec_prefix}/lib/ includedir=${prefix}/include/testlib Name: Test Library Description: A fake library to test pkg-config. Version: 1.2.3 Libs: -L${libdir} -ltest -F${libdir} -framework someframework Cflags: -I${includedir} -DBADGER=yes -DAWESOME system-deps-6.2.0/src/tests/teststaticlib.pc000064400000000000000000000004571046102023000172470ustar 00000000000000prefix=./src/tests exec_prefix=${prefix} libdir=${exec_prefix}/lib/ includedir=${prefix}/include/testlib Name: Test Library Description: A fake library to test pkg-config. Version: 1.2.3 Libs: -L${libdir} -lteststatic -F${libdir} -framework someframework Cflags: -I${includedir} -DBADGER=yes -DAWESOME system-deps-6.2.0/src/tests/toml-missing-file/no-cargo-toml-here000064400000000000000000000000231046102023000227130ustar 00000000000000No Cargo.toml here