Skip to main content

cargo/compiler/
output_depinfo.rs

1//! dep-info files for external build system integration.
2//! See [`output_depinfo`] for more.
3
4use crate::util::data_structures::HashSet;
5use cargo_util::paths::normalize_path;
6use std::collections::BTreeSet;
7use std::io::{BufWriter, Write};
8use std::path::{Path, PathBuf};
9
10use super::{BuildRunner, FileFlavor, Unit, fingerprint};
11use crate::util::{CargoResult, internal};
12use cargo_util::paths;
13use tracing::debug;
14
15/// Basically just normalizes a given path and converts it to a string.
16fn render_filename<P: AsRef<Path>>(path: P, basedir: Option<&str>) -> CargoResult<String> {
17    fn wrap_path(path: &Path) -> CargoResult<String> {
18        path.to_str()
19            .ok_or_else(|| internal(format!("path `{:?}` not utf-8", path)))
20            .map(|f| f.replace(" ", "\\ "))
21    }
22
23    let path = path.as_ref();
24    if let Some(basedir) = basedir {
25        let norm_path = normalize_path(path);
26        let norm_basedir = normalize_path(basedir.as_ref());
27        match norm_path.strip_prefix(norm_basedir) {
28            Ok(relpath) => wrap_path(relpath),
29            _ => wrap_path(path),
30        }
31    } else {
32        wrap_path(path)
33    }
34}
35
36/// Collects all dependencies of the `unit` for the output dep info file.
37///
38/// Dependencies will be stored in `deps`, including:
39///
40/// * dependencies from [fingerprint dep-info]
41/// * paths from `rerun-if-changed` build script instruction
42/// * ...and traverse transitive dependencies recursively
43///
44/// [fingerprint dep-info]: super::fingerprint#fingerprint-dep-info-files
45fn add_deps_for_unit(
46    deps: &mut BTreeSet<PathBuf>,
47    build_runner: &mut BuildRunner<'_, '_>,
48    unit: &Unit,
49    visited: &mut HashSet<Unit>,
50) -> CargoResult<()> {
51    if !visited.insert(unit.clone()) {
52        return Ok(());
53    }
54
55    // units representing the execution of a build script don't actually
56    // generate a dep info file, so we just keep on going below
57    if !unit.mode.is_run_custom_build() {
58        // Add dependencies from rustc dep-info output (stored in fingerprint directory)
59        let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
60        if let Some(paths) = fingerprint::parse_dep_info(
61            unit.pkg.root(),
62            build_runner.files().host_build_root(),
63            &dep_info_loc,
64        )? {
65            for path in paths.files.into_keys() {
66                deps.insert(path);
67            }
68        } else {
69            debug!(
70                "can't find dep_info for {:?} {}",
71                unit.pkg.package_id(),
72                unit.target
73            );
74            return Err(internal("dep_info missing"));
75        }
76    }
77
78    // Add rerun-if-changed dependencies
79    if let Some(metadata_vec) = build_runner.find_build_script_metadatas(unit) {
80        for metadata in metadata_vec {
81            if let Some(output) = build_runner
82                .build_script_outputs
83                .lock()
84                .unwrap()
85                .get(metadata)
86            {
87                for path in &output.rerun_if_changed {
88                    let package_root = unit.pkg.root();
89
90                    let path = if path.as_os_str().is_empty() {
91                        // Joining with an empty path causes Rust to add a trailing path separator.
92                        // On Windows, this would add an invalid trailing backslash to the .d file.
93                        package_root.to_path_buf()
94                    } else {
95                        // The paths we have saved from the unit are of arbitrary relativeness and
96                        // may be relative to the crate root of the dependency.
97                        package_root.join(path)
98                    };
99
100                    deps.insert(path);
101                }
102            }
103        }
104    }
105
106    // Recursively traverse all transitive dependencies
107    let unit_deps = Vec::from(build_runner.unit_deps(unit)); // Create vec due to mutable borrow.
108    for dep in unit_deps {
109        if dep.unit.is_local() {
110            add_deps_for_unit(deps, build_runner, &dep.unit, visited)?;
111        }
112    }
113    Ok(())
114}
115
116/// Save a `.d` dep-info file for the given unit. This is the third kind of
117/// dep-info mentioned in [`fingerprint`] module.
118///
119/// Argument `unit` is expected to be the root unit, which will be uplifted.
120///
121/// Cargo emits its own dep-info files in the output directory. This is
122/// only done for every "uplifted" artifact. These are intended to be used
123/// with external build systems so that they can detect if Cargo needs to be
124/// re-executed.
125///
126/// It includes all the entries from the `rustc` dep-info file, and extends it
127/// with any `rerun-if-changed` entries from build scripts. It also includes
128/// sources from any path dependencies. Registry dependencies are not included
129/// under the assumption that changes to them can be detected via changes to
130/// `Cargo.lock`.
131///
132/// [`fingerprint`]: super::fingerprint#dep-info-files
133pub fn output_depinfo(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<()> {
134    let bcx = build_runner.bcx;
135    let mut deps = BTreeSet::new();
136    let mut visited = HashSet::default();
137    let success = add_deps_for_unit(&mut deps, build_runner, unit, &mut visited).is_ok();
138    let basedir_string;
139    let basedir = match bcx.gctx.build_config()?.dep_info_basedir.clone() {
140        Some(value) => {
141            basedir_string = value
142                .resolve_path(bcx.gctx)
143                .as_os_str()
144                .to_str()
145                .ok_or_else(|| anyhow::format_err!("build.dep-info-basedir path not utf-8"))?
146                .to_string();
147            Some(basedir_string.as_str())
148        }
149        None => None,
150    };
151    let deps = deps
152        .iter()
153        .map(|f| render_filename(f, basedir))
154        .collect::<CargoResult<Vec<_>>>()?;
155
156    for output in build_runner.outputs(unit)?.iter().filter(|o| {
157        !matches!(
158            o.flavor,
159            FileFlavor::DebugInfo | FileFlavor::Auxiliary | FileFlavor::Sbom
160        )
161    }) {
162        if let Some(ref link_dst) = output.hardlink {
163            let output_path = link_dst.with_extension("d");
164            if success {
165                let target_fn = render_filename(link_dst, basedir)?;
166
167                // If nothing changed don't recreate the file which could alter
168                // its mtime
169                if let Ok(previous) = fingerprint::parse_rustc_dep_info(&output_path) {
170                    if previous
171                        .files
172                        .iter()
173                        .map(|(path, _checksum)| path)
174                        .eq(deps.iter().map(Path::new))
175                    {
176                        continue;
177                    }
178                }
179
180                // Otherwise write it all out
181                let mut outfile = BufWriter::new(paths::create(output_path)?);
182                write!(outfile, "{}:", target_fn)?;
183                for dep in &deps {
184                    write!(outfile, " {}", dep)?;
185                }
186                writeln!(outfile)?;
187
188            // dep-info generation failed, so delete output file. This will
189            // usually cause the build system to always rerun the build
190            // rule, which is correct if inefficient.
191            } else if output_path.exists() {
192                paths::remove_file(output_path)?;
193            }
194        }
195    }
196    Ok(())
197}