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
150/// Describes a CMake target found in a CMake package.
151///
152/// The target can be obtained by calling the [`target()`][CMakePackage::target()] method on a [`CMakePackage`] instance.
153///
154/// Use [`link()`][Self::link()] method to instruct cargo to link the final binary against the target.
155/// There's currently no way to automatically apply compiler arguments or include directories, since
156/// that depends on how the C/C++ code in your project is compiled (e.g. using the [cc][cc_crate] crate).
157/// Optional support for this may be added in the future.
158///
159/// # Example
160/// ```no_run
161/// use cmake_package::find_package;
162///
163/// let package = find_package("OpenSSL").version("1.0").find().unwrap();
164/// let target = package.target("OpenSSL::SSL").unwrap();
165/// println!("Include directories: {:?}", target.include_directories);
166/// println!("Link libraries: {:?}", target.link_libraries);
167/// target.link();
168/// ```
169///
170/// [cc_crate]: https://crates.io/crates/cc
171#[derive(Debug, Default, Clone)]
172pub struct CMakeTarget {
173    /// Name of the CMake target
174    pub name: String,
175    /// List of public compile definitions requirements for a library.
176    ///
177    /// Contains preprocessor definitions provided by the target and all its transitive dependencies
178    /// via their [`INTERFACE_COMPILE_DEFINITIONS`][cmake_interface_compile_definitions] target properties.
179    ///
180    /// [cmake_interface_compile_definitions]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_COMPILE_DEFINITIONS.html
181    pub compile_definitions: Vec<String>,
182    /// List of options to pass to the compiler.
183    ///
184    /// Contains compiler options provided by the target and all its transitive dependencies via
185    /// their [`INTERFACE_COMPILE_OPTIONS`][cmake_interface_compile_options] target properties.
186    ///
187    /// [cmake_interface_compile_options]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_COMPILE_OPTIONS.html
188    pub compile_options: Vec<String>,
189    /// List of include directories required to build the target.
190    ///
191    /// Contains include directories provided by the target and all its transitive dependencies via
192    /// their [`INTERFACE_INCLUDE_DIRECTORIES`][cmake_interface_include_directories] target properties.
193    ///
194    /// [cmake_interface_include_directories]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_INCLUDE_DIRECTORIES.html
195    pub include_directories: Vec<String>,
196    /// List of directories to use for the link step of shared library, module and executable targets.
197    ///
198    /// Contains link directories provided by the target and all its transitive dependencies via
199    /// their [`INTERFACE_LINK_DIRECTORIES`][cmake_interface_link_directories] target properties.
200    ///
201    /// [cmake_interface_link_directories]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_LINK_DIRECTORIES.html
202    pub link_directories: Vec<String>,
203    /// List of target's direct link dependencies, followed by indirect dependencies from the transitive closure of the direct
204    /// dependencies' [`INTERFACE_LINK_LIBRARIES`][cmake_interface_link_libraries] properties
205    ///
206    /// [cmake_interface_link_libraries]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_LINK_LIBRARIES.html
207    pub link_libraries: Vec<String>,
208    /// List of options to use for the link step of shared library, module and executable targets as well as the device link step.
209    ///
210    /// Contains link options provided by the target and all its transitive dependencies via
211    /// their [`INTERFACE_LINK_OPTIONS`][cmake_interface_link_options] target properties.
212    ///
213    /// [cmake_interface_link_options]: https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_LINK_OPTIONS.html
214    pub link_options: Vec<String>,
215    /// The location of the target on disk.
216    ///
217    /// [cmake_interface_location]: https://cmake.org/cmake/help/latest/prop_tgt/LOCATION.html
218    pub location: Option<String>,
219}
220
221/// Turns /usr/lib/libfoo.so.5 into foo, so that -lfoo rather than -l/usr/lib/libfoo.so.5
222/// is passed to the linker. Leaves "foo" untouched.
223#[cfg(any(target_os = "linux", target_os = "macos"))]
224fn link_name(lib: &str) -> &str {
225    static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"lib([^/]+)\.(?:so|dylib|a).*").unwrap());
226    match RE.captures(lib) {
227        Some(captures) => captures.get(1).map(|f| f.as_str()).unwrap_or(lib),
228        None => lib,
229    }
230}
231
232#[cfg(target_os = "windows")]
233fn link_name(lib: &str) -> &str {
234    lib
235}
236
237#[cfg(any(target_os = "linux", target_os = "macos"))]
238fn link_dir(lib: &str) -> Option<&str> {
239    static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(.*)/lib[^/]+\.so.*").unwrap());
240    RE.captures(lib)?.get(1).map(|f| f.as_str())
241}
242
243#[cfg(target_os = "windows")]
244fn link_dir(_lib: &str) -> Option<&str> {
245    None
246}
247
248impl CMakeTarget {
249    /// Instructs cargo to link the final binary against the target.
250    ///
251    /// This method prints the necessary [`cargo:rustc-link-search=native={}`][cargo_rustc_link_search],
252    /// [`cargo:rustc-link-arg={}`][cargo_rustc_link_arg], and [`cargo:rustc-link-lib=dylib={}`][cargo_rustc_link_lib]
253    /// directives to the standard output for each of the target's [`link_directories`][Self::link_directories],
254    /// [`link_options`][Self::link_options], and [`link_libraries`][Self::link_libraries] respectively.
255    ///
256    /// [cargo_rustc_link_search]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-search
257    /// [cargo_rustc_link_arg]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-arg
258    /// [cargo_rustc_link_lib]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib]
259    pub fn link(&self) {
260        self.link_write(&mut std::io::stdout());
261    }
262
263    fn link_write<W: Write>(&self, io: &mut W) {
264        self.link_directories.iter().for_each(|dir| {
265            writeln!(io, "cargo:rustc-link-search=native={}", dir).unwrap();
266        });
267        self.link_options.iter().for_each(|opt| {
268            writeln!(io, "cargo:rustc-link-arg={}", opt).unwrap();
269        });
270        self.link_libraries.iter().for_each(|lib| {
271            if lib.starts_with("-") {
272                writeln!(io, "cargo:rustc-link-arg={}", lib).unwrap();
273            } else {
274                writeln!(io, "cargo:rustc-link-lib=dylib={}", link_name(lib)).unwrap();
275            }
276
277            if let Some(lib) = link_dir(lib) {
278                writeln!(io, "cargo:rustc-link-search=native={}", lib).unwrap();
279            }
280        });
281    }
282}
283
284/// A builder for creating a [`CMakePackage`] instance. An instance of the builder is created by calling
285/// the [`find_package()`] function. Once the package is configured, [`FindPackageBuilder::find()`] will actually
286/// try to find the CMake package and return a [`CMakePackage`] instance (or error if the package is not found
287/// or an error occurs during the search).
288#[derive(Debug, Clone)]
289pub struct FindPackageBuilder {
290    name: String,
291    version: Option<Version>,
292    components: Option<Vec<String>>,
293    verbose: bool,
294    prefix_paths: Option<Vec<PathBuf>>
295}
296
297impl FindPackageBuilder {
298    fn new(name: String) -> Self {
299        Self {
300            name,
301            version: None,
302            components: None,
303            verbose: false,
304            prefix_paths: None
305        }
306    }
307
308    /// Optionally specifies the minimum required version for the package to find.
309    /// If the package is not found or the version is too low, the `find()` method will return
310    /// [`Error::Version`] with the version of the package found on the system.
311    pub fn version(self, version: impl TryInto<Version>) -> Self {
312        Self {
313            version: Some(
314                version
315                    .try_into()
316                    .unwrap_or_else(|_| panic!("Invalid version specified!")),
317            ),
318            ..self
319        }
320    }
321
322    /// Optionally specifies the required components to locate in the package.
323    /// If the package is found, but any of the components is missing, the package is considered
324    /// as not found and the `find()` method will return [`Error::PackageNotFound`].
325    /// See the documentation on CMake's [`find_package()`][cmake_find_package] function and how it
326    /// treats the `COMPONENTS` argument.
327    ///
328    /// [cmake_find_package]: https://cmake.org/cmake/help/latest/command/find_package.html
329    pub fn components(self, components: impl Into<Vec<String>>) -> Self {
330        Self {
331            components: Some(components.into()),
332            ..self
333        }
334    }
335
336    /// Enable verbose output.
337    /// This will redirect output from actual execution of the `cmake` command to the standard output
338    /// and standard error of the build script.
339    pub fn verbose(self) -> Self {
340        Self {
341            verbose: true,
342            ..self
343        }
344    }
345
346    // Specify prefix paths.
347    // This sets directories to be searched for the package.
348    // [cmake_prefix_path]: https://cmake.org/cmake/help/latest/variable/CMAKE_PREFIX_PATH.html
349    pub fn prefix_paths(self, prefix_paths: Vec<PathBuf>) -> Self {
350        Self {
351            prefix_paths: Some(prefix_paths),
352            ..self
353        }
354    }
355
356    /// Tries to find the CMake package on the system.
357    /// Returns a [`CMakePackage`] instance if the package is found, otherwise an error.
358    pub fn find(self) -> Result<CMakePackage, cmake::Error> {
359        cmake::find_package(self.name, self.version, self.components, self.verbose, self.prefix_paths)
360    }
361}
362
363/// Find a CMake package on the system.
364///
365/// This function is the main entrypoint for the crate. It returns a builder object that you
366/// can use to specify further constraints on the package to find, such as the [version][FindPackageBuilder::version]
367/// or [components][FindPackageBuilder::components]. Once you call the [`find()`][FindPackageBuilder::find]
368/// method on the builder, the crate will try to find the package on the system or return an
369/// error if the package does not exist or does not satisfy some of the constraints. If the package
370/// is found, an instance of the [`CMakePackage`] struct is returned that can be used to further
371/// query the package for information about its individual CMake targets.
372///
373/// See the documentation for [`FindPackageBuilder`], [`CMakePackage`], and [`CMakeTarget`] for more
374/// information and the example in the crate documentation for a simple usage example.
375pub fn find_package(name: impl Into<String>) -> FindPackageBuilder {
376    FindPackageBuilder::new(name.into())
377}
378
379#[cfg(test)]
380mod testing {
381    use super::*;
382
383    // Note: requires cmake to be installed on the system
384    #[test]
385    fn test_find_package() {
386        let package = find_package("totallynonexistentpackage").find();
387        match package {
388            Ok(_) => panic!("Package should not be found"),
389            Err(cmake::Error::PackageNotFound) => (),
390            Err(err) => panic!("Unexpected error: {:?}", err),
391        }
392    }
393
394    // Note: requires cmake to be installed on the system
395    #[test]
396    fn test_find_package_with_version() {
397        let package = find_package("foo").version("1.0").find();
398        match package {
399            Ok(_) => panic!("Package should not be found"),
400            Err(cmake::Error::PackageNotFound) => (),
401            Err(err) => panic!("Unexpected error: {:?}", err),
402        }
403    }
404
405    #[test]
406    #[cfg(any(target_os = "linux", target_os = "macos"))]
407    fn test_link_to() {
408        let target = CMakeTarget {
409            name: "foo".into(),
410            compile_definitions: vec![],
411            compile_options: vec![],
412            include_directories: vec![],
413            link_directories: vec!["/usr/lib64".into()],
414            link_libraries: vec!["/usr/lib/libbar.so".into(), "/usr/lib64/libfoo.so.5".into()],
415            link_options: vec![],
416            location: None,
417        };
418
419        let mut buf = Vec::new();
420        target.link_write(&mut buf);
421        let output = String::from_utf8(buf).unwrap();
422        assert_eq!(
423            output.lines().collect::<Vec<&str>>(),
424            vec![
425                "cargo:rustc-link-search=native=/usr/lib64",
426                "cargo:rustc-link-lib=dylib=bar",
427                "cargo:rustc-link-search=native=/usr/lib",
428                "cargo:rustc-link-lib=dylib=foo",
429                "cargo:rustc-link-search=native=/usr/lib64"
430            ]
431        );
432    }
433}