Skip to main content

cmake_package/
lib.rs

1// SPDX-FileCopyrightText: 2024 Daniel Vrátil <dvratil@kde.org>
2//
3// SPDX-License-Identifier: MIT
4
5//! A simple CMake package finder.
6//!
7//! This crate is intended to be used in [cargo build scripts][cargo_build_script] to obtain
8//! information about and existing system [CMake package][cmake_package] and [CMake targets][cmake_target]
9//! defined in the package, such as include directories and link libraries for individual
10//! CMake targets defined in the package.
11//!
12//! The crate runs the `cmake` command in the background to query the system for the package
13//! and to extract the necessary information, which means that in order for this crate to work,
14//! the `cmake` executable must be located the system [`PATH`][wiki_path]. CMake version
15//! [3.19][CMAKE_MIN_VERSION] or newer is required for this crate to work.
16//!
17//! The entry point for the crate is the [`find_package()`] function that returns a builder,
18//! which you can use to specify further constraints on the package ([version][FindPackageBuilder::version]
19//! or [components][FindPackageBuilder::components]). Once you call the [`find()`][FindPackageBuilder::find]
20//! method on the builder, the crate will try to find the package on the system or return an
21//! error. If the package is found, an instance of the [`CMakePackage`] struct is returned that
22//! contains information about the package. Using its [`target()`][CMakePackage::target] method,
23//! you can query information about individual CMake targets defined in the package.
24//!
25//! If you want to make your dependency on CMake optional, you can use the [`find_cmake()`]
26//! function to check that a suitable version of CMake is found on the system and then decide
27//! how to proceed yourself. It is not necessary to call the function before using [`find_package()`].
28//!
29//! # Example
30//! ```no_run
31//! use cmake_package::find_package;
32//!
33//! let package = find_package("OpenSSL").version("1.0").find();
34//! let target = match package {
35//!     Err(_) => panic!("OpenSSL>=1.0 not found"),
36//!     Ok(package) => {
37//!         package.target("OpenSSL::SSL").unwrap()
38//!     }
39//! };
40//!
41//! println!("Include directories: {:?}", target.include_directories);
42//! target.link();
43//! ```
44//!
45//! # How Does it Work?
46//!
47//! When you call [`FindPackageBuilder::find()`], the crate will create a temporary directory
48//! with a `CMakeLists.txt` file that contains actual [`find_package()`][cmake_find_package]
49//! command to search for the package. The crate will then run actual `cmake` command in the
50//! temporary directory to let CMake find the package. The `CMakeLists.txt` then writes the
51//! information about the package into a JSON file that is then read by this crate to produce
52//! the [`CMakePackage`].
53//!
54//! When a target is queried using the [`CMakePackage::target()`] method, the crate runs the
55//! CMake command again the same directory, but this time the `CMakeLists.txt` attempts to locate
56//! the specified CMake target and list all its (relevant) properties and properties of all its
57//! transitive dependencies. The result is again written into a JSON file that is then processed
58//! by the crate to produce the [`CMakeTarget`] instance.
59//!
60//! # Known Limitations
61//!
62//! The crate currently supports primarily linking against shared libraries. Linking against
63//! static libraries is not tested and may not work as expected. The crate currently does not
64//! support linking against MacOS frameworks.
65//!
66//! [CMake generator expressions][cmake_generator_expr] are not supported in property values
67//! right now, because they are evaluated at later stage of the build, not during the "configure"
68//! phase of CMake, which is what this crate does. Some generator expressions could be supported
69//! by the crate in the future (e.g. by evaluating them ourselves).
70//!
71//! There's currently no way to customize the `CMakeLists.txt` file that is used to query the
72//! package or the target in order to extract non-standard properties or variables set by
73//! the CMake package. This may be addressed in the future.
74//!
75//! [wiki_path]: https://en.wikipedia.org/wiki/PATH_(variable)
76//! [cmake_package]: https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html
77//! [cmake_target]: https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#target-build-specification
78//! [cargo_build_script]: https://doc.rust-lang.org/cargo/reference/build-scripts.html
79//! [cmake_find_package]: https://cmake.org/cmake/help/latest/command/find_package.html
80//! [cmake_generator_expr]: https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html
81
82use std::io::Write;
83use std::path::PathBuf;
84
85#[cfg(any(target_os = "linux", target_os = "macos"))]
86use once_cell::sync::Lazy;
87#[cfg(any(target_os = "linux", target_os = "macos"))]
88use regex::Regex;
89use tempfile::TempDir;
90
91mod cmake;
92mod version;
93
94pub use cmake::{find_cmake, CMakeProgram, Error, CMAKE_MIN_VERSION};
95pub use version::{Version, VersionError};
96
97/// A CMake package found on the system.
98///
99/// Represents a CMake package found on the system. To find a package, use the [`find_package()`] function.
100/// The package can be queried for information about its individual CMake targets by [`CMakePackage::target()`].
101///
102/// # Example
103/// ```no_run
104/// use cmake_package::{CMakePackage, find_package};
105///
106/// let package: CMakePackage = find_package("OpenSSL").version("1.0").find().unwrap();
107/// ```
108#[derive(Debug)]
109pub struct CMakePackage {
110    cmake: CMakeProgram,
111    working_directory: TempDir,
112    verbose: bool,
113
114    /// Name of the CMake package
115    pub name: String,
116    /// Version of the package found on the system
117    pub version: Option<Version>,
118    /// Components of the package, as requested by the user in [`find_package()`]
119    pub components: Option<Vec<String>>,
120}
121
122impl CMakePackage {
123    fn new(
124        cmake: CMakeProgram,
125        working_directory: TempDir,
126        name: String,
127        version: Option<Version>,
128        components: Option<Vec<String>>,
129        verbose: bool,
130    ) -> Self {
131        Self {
132            cmake,
133            working_directory,
134            name,
135            version,
136            components,
137            verbose,
138        }
139    }
140
141    /// Queries the CMake package for information about a specific [CMake target][cmake_target].
142    /// Returns `None` if the target is not found in the package.
143    ///
144    /// [cmake_target]: https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#imported-targets
145    pub fn target(&self, target: impl Into<String>) -> Option<CMakeTarget> {
146        cmake::find_target(self, target)
147    }
148
149    /// Queries the CMake target for the value of a specific property.
150    ///
151    /// Returns `None` if the property is not defined on the target.
152    ///
153    /// This is equivalent to calling [`get_target_property()`][cmake_get_target_property] in CMake.
154    ///
155    /// [cmake_get_target_property]: https://cmake.org/cmake/help/latest/command/get_target_property.html
156    pub fn target_property(
157        &self,
158        target: &CMakeTarget,
159        property: impl Into<String>,
160    ) -> Option<String> {
161        cmake::target_property(self, target, property)
162    }
163}
164
165/// Describes a CMake target found in a CMake package.
166///
167/// The target can be obtained by calling the [`target()`][CMakePackage::target()] method on a [`CMakePackage`] instance.
168///
169/// Use [`link()`][Self::link()] method to instruct cargo to link the final binary against the target.
170/// There's currently no way to automatically apply compiler arguments or include directories, since
171/// that depends on how the C/C++ code in your project is compiled (e.g. using the [cc][cc_crate] crate).
172/// Optional support for this may be added in the future.
173///
174/// # Example
175/// ```no_run
176/// use cmake_package::find_package;
177///
178/// let package = find_package("OpenSSL").version("1.0").find().unwrap();
179/// let target = package.target("OpenSSL::SSL").unwrap();
180/// println!("Include directories: {:?}", target.include_directories);
181/// println!("Link libraries: {:?}", target.link_libraries);
182/// target.link();
183/// ```
184///
185/// [cc_crate]: https://crates.io/crates/cc
186#[derive(Debug, Default, Clone)]
187pub struct CMakeTarget {
188    /// Name of the CMake target
189    pub name: String,
190    /// List of public compile definitions requirements for a library.
191    ///
192    /// Contains preprocessor definitions provided by the target and all its transitive dependencies
193    /// via their [`INTERFACE_COMPILE_DEFINITIONS`][cmake_interface_compile_definitions] target properties.
194    ///
195    /// [cmake_interface_compile_definitions]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_COMPILE_DEFINITIONS.html
196    pub compile_definitions: Vec<String>,
197    /// List of options to pass to the compiler.
198    ///
199    /// Contains compiler options provided by the target and all its transitive dependencies via
200    /// their [`INTERFACE_COMPILE_OPTIONS`][cmake_interface_compile_options] target properties.
201    ///
202    /// [cmake_interface_compile_options]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_COMPILE_OPTIONS.html
203    pub compile_options: Vec<String>,
204    /// List of include directories required to build the target.
205    ///
206    /// Contains include directories provided by the target and all its transitive dependencies via
207    /// their [`INTERFACE_INCLUDE_DIRECTORIES`][cmake_interface_include_directories] target properties.
208    ///
209    /// [cmake_interface_include_directories]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_INCLUDE_DIRECTORIES.html
210    pub include_directories: Vec<String>,
211    /// List of directories to use for the link step of shared library, module and executable targets.
212    ///
213    /// Contains link directories provided by the target and all its transitive dependencies via
214    /// their [`INTERFACE_LINK_DIRECTORIES`][cmake_interface_link_directories] target properties.
215    ///
216    /// [cmake_interface_link_directories]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_LINK_DIRECTORIES.html
217    pub link_directories: Vec<String>,
218    /// List of target's direct link dependencies, followed by indirect dependencies from the transitive closure of the direct
219    /// dependencies' [`INTERFACE_LINK_LIBRARIES`][cmake_interface_link_libraries] properties
220    ///
221    /// [cmake_interface_link_libraries]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_LINK_LIBRARIES.html
222    pub link_libraries: Vec<String>,
223    /// List of options to use for the link step of shared library, module and executable targets as well as the device link step.
224    ///
225    /// Contains link options provided by the target and all its transitive dependencies via
226    /// their [`INTERFACE_LINK_OPTIONS`][cmake_interface_link_options] target properties.
227    ///
228    /// [cmake_interface_link_options]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_LINK_OPTIONS.html
229    pub link_options: Vec<String>,
230    /// The location of the target on disk.
231    ///
232    /// [cmake_interface_location]: https://cmake.org/cmake/help/latest/prop_tgt/LOCATION.html
233    pub location: Option<String>,
234}
235
236/// Turns /usr/lib/libfoo.so.5 into foo, so that -lfoo rather than -l/usr/lib/libfoo.so.5
237/// is passed to the linker. Leaves "foo" untouched.
238#[cfg(any(target_os = "linux", target_os = "macos"))]
239fn link_name(lib: &str) -> &str {
240    static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"lib([^/]+)\.(?:so|dylib|a).*").unwrap());
241    match RE.captures(lib) {
242        Some(captures) => captures.get(1).map(|f| f.as_str()).unwrap_or(lib),
243        None => lib,
244    }
245}
246
247#[cfg(target_os = "windows")]
248fn link_name(lib: &str) -> &str {
249    lib
250}
251
252#[cfg(any(target_os = "linux", target_os = "macos"))]
253fn link_dir(lib: &str) -> Option<&str> {
254    static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(.*)/lib[^/]+\.so.*").unwrap());
255    RE.captures(lib)?.get(1).map(|f| f.as_str())
256}
257
258#[cfg(target_os = "windows")]
259fn link_dir(_lib: &str) -> Option<&str> {
260    None
261}
262
263impl CMakeTarget {
264    /// Instructs cargo to link the final binary against the target.
265    ///
266    /// This method prints the necessary [`cargo:rustc-link-search=native={}`][cargo_rustc_link_search],
267    /// [`cargo:rustc-link-arg={}`][cargo_rustc_link_arg], and [`cargo:rustc-link-lib=dylib={}`][cargo_rustc_link_lib]
268    /// directives to the standard output for each of the target's [`link_directories`][Self::link_directories],
269    /// [`link_options`][Self::link_options], and [`link_libraries`][Self::link_libraries] respectively.
270    ///
271    /// [cargo_rustc_link_search]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-search
272    /// [cargo_rustc_link_arg]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-arg
273    /// [cargo_rustc_link_lib]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib]
274    pub fn link(&self) {
275        self.link_write(&mut std::io::stdout());
276    }
277
278    fn link_write<W: Write>(&self, io: &mut W) {
279        self.link_directories.iter().for_each(|dir| {
280            writeln!(io, "cargo:rustc-link-search=native={}", dir).unwrap();
281        });
282        self.link_options.iter().for_each(|opt| {
283            writeln!(io, "cargo:rustc-link-arg={}", opt).unwrap();
284        });
285        self.link_libraries.iter().for_each(|lib| {
286            if lib.starts_with("-") {
287                writeln!(io, "cargo:rustc-link-arg={}", lib).unwrap();
288            } else {
289                writeln!(io, "cargo:rustc-link-lib=dylib={}", link_name(lib)).unwrap();
290            }
291
292            if let Some(lib) = link_dir(lib) {
293                writeln!(io, "cargo:rustc-link-search=native={}", lib).unwrap();
294            }
295        });
296    }
297}
298
299/// A builder for creating a [`CMakePackage`] instance. An instance of the builder is created by calling
300/// the [`find_package()`] function. Once the package is configured, [`FindPackageBuilder::find()`] will actually
301/// try to find the CMake package and return a [`CMakePackage`] instance (or error if the package is not found
302/// or an error occurs during the search).
303#[derive(Debug, Clone)]
304pub struct FindPackageBuilder {
305    name: String,
306    version: Option<Version>,
307    components: Option<Vec<String>>,
308    verbose: bool,
309    prefix_paths: Option<Vec<PathBuf>>
310}
311
312impl FindPackageBuilder {
313    fn new(name: String) -> Self {
314        Self {
315            name,
316            version: None,
317            components: None,
318            verbose: false,
319            prefix_paths: None
320        }
321    }
322
323    /// Optionally specifies the minimum required version for the package to find.
324    /// If the package is not found or the version is too low, the `find()` method will return
325    /// [`Error::Version`] with the version of the package found on the system.
326    pub fn version(self, version: impl TryInto<Version>) -> Self {
327        Self {
328            version: Some(
329                version
330                    .try_into()
331                    .unwrap_or_else(|_| panic!("Invalid version specified!")),
332            ),
333            ..self
334        }
335    }
336
337    /// Optionally specifies the required components to locate in the package.
338    /// If the package is found, but any of the components is missing, the package is considered
339    /// as not found and the `find()` method will return [`Error::PackageNotFound`].
340    /// See the documentation on CMake's [`find_package()`][cmake_find_package] function and how it
341    /// treats the `COMPONENTS` argument.
342    ///
343    /// [cmake_find_package]: https://cmake.org/cmake/help/latest/command/find_package.html
344    pub fn components(self, components: impl Into<Vec<String>>) -> Self {
345        Self {
346            components: Some(components.into()),
347            ..self
348        }
349    }
350
351    /// Enable verbose output.
352    /// This will redirect output from actual execution of the `cmake` command to the standard output
353    /// and standard error of the build script.
354    pub fn verbose(self) -> Self {
355        Self {
356            verbose: true,
357            ..self
358        }
359    }
360
361    // Specify prefix paths.
362    // This sets directories to be searched for the package.
363    // [cmake_prefix_path]: https://cmake.org/cmake/help/latest/variable/CMAKE_PREFIX_PATH.html
364    pub fn prefix_paths(self, prefix_paths: Vec<PathBuf>) -> Self {
365        Self {
366            prefix_paths: Some(prefix_paths),
367            ..self
368        }
369    }
370
371    /// Tries to find the CMake package on the system.
372    /// Returns a [`CMakePackage`] instance if the package is found, otherwise an error.
373    pub fn find(self) -> Result<CMakePackage, cmake::Error> {
374        cmake::find_package(self.name, self.version, self.components, self.verbose, self.prefix_paths)
375    }
376}
377
378/// Find a CMake package on the system.
379///
380/// This function is the main entrypoint for the crate. It returns a builder object that you
381/// can use to specify further constraints on the package to find, such as the [version][FindPackageBuilder::version]
382/// or [components][FindPackageBuilder::components]. Once you call the [`find()`][FindPackageBuilder::find]
383/// method on the builder, the crate will try to find the package on the system or return an
384/// error if the package does not exist or does not satisfy some of the constraints. If the package
385/// is found, an instance of the [`CMakePackage`] struct is returned that can be used to further
386/// query the package for information about its individual CMake targets.
387///
388/// See the documentation for [`FindPackageBuilder`], [`CMakePackage`], and [`CMakeTarget`] for more
389/// information and the example in the crate documentation for a simple usage example.
390pub fn find_package(name: impl Into<String>) -> FindPackageBuilder {
391    FindPackageBuilder::new(name.into())
392}
393
394#[cfg(test)]
395mod testing {
396    use super::*;
397
398    // Note: requires cmake to be installed on the system
399    #[test]
400    fn test_find_package() {
401        let package = find_package("totallynonexistentpackage").find();
402        match package {
403            Ok(_) => panic!("Package should not be found"),
404            Err(cmake::Error::PackageNotFound) => (),
405            Err(err) => panic!("Unexpected error: {:?}", err),
406        }
407    }
408
409    // Note: requires cmake to be installed on the system
410    #[test]
411    fn test_find_package_with_version() {
412        let package = find_package("foo").version("1.0").find();
413        match package {
414            Ok(_) => panic!("Package should not be found"),
415            Err(cmake::Error::PackageNotFound) => (),
416            Err(err) => panic!("Unexpected error: {:?}", err),
417        }
418    }
419
420    #[test]
421    #[cfg(any(target_os = "linux", target_os = "macos"))]
422    fn test_link_to() {
423        let target = CMakeTarget {
424            name: "foo".into(),
425            compile_definitions: vec![],
426            compile_options: vec![],
427            include_directories: vec![],
428            link_directories: vec!["/usr/lib64".into()],
429            link_libraries: vec!["/usr/lib/libbar.so".into(), "/usr/lib64/libfoo.so.5".into()],
430            link_options: vec![],
431            location: None,
432        };
433
434        let mut buf = Vec::new();
435        target.link_write(&mut buf);
436        let output = String::from_utf8(buf).unwrap();
437        assert_eq!(
438            output.lines().collect::<Vec<&str>>(),
439            vec![
440                "cargo:rustc-link-search=native=/usr/lib64",
441                "cargo:rustc-link-lib=dylib=bar",
442                "cargo:rustc-link-search=native=/usr/lib",
443                "cargo:rustc-link-lib=dylib=foo",
444                "cargo:rustc-link-search=native=/usr/lib64"
445            ]
446        );
447    }
448}