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            build_runner.bcx.ws.root(),
64            &dep_info_loc,
65        )? {
66            for path in paths.files.into_keys() {
67                deps.insert(path);
68            }
69        } else {
70            debug!(
71                "can't find dep_info for {:?} {}",
72                unit.pkg.package_id(),
73                unit.target
74            );
75            return Err(internal("dep_info missing"));
76        }
77    }
78
79    // Add rerun-if-changed dependencies
80    if let Some(metadata_vec) = build_runner.find_build_script_metadatas(unit) {
81        for metadata in metadata_vec {
82            if let Some(output) = build_runner
83                .build_script_outputs
84                .lock()
85                .unwrap()
86                .get(metadata)
87            {
88                for path in &output.rerun_if_changed {
89                    let package_root = unit.pkg.root();
90
91                    let path = if path.as_os_str().is_empty() {
92                        // Joining with an empty path causes Rust to add a trailing path separator.
93                        // On Windows, this would add an invalid trailing backslash to the .d file.
94                        package_root.to_path_buf()
95                    } else {
96                        // The paths we have saved from the unit are of arbitrary relativeness and
97                        // may be relative to the crate root of the dependency.
98                        package_root.join(path)
99                    };
100
101                    deps.insert(path);
102                }
103            }
104        }
105    }
106
107    // Recursively traverse all transitive dependencies
108    let unit_deps = Vec::from(build_runner.unit_deps(unit)); // Create vec due to mutable borrow.
109    for dep in unit_deps {
110        if dep.unit.is_local() {
111            add_deps_for_unit(deps, build_runner, &dep.unit, visited)?;
112        }
113    }
114    Ok(())
115}
116
117/// Save a `.d` dep-info file for the given unit. This is the third kind of
118/// dep-info mentioned in [`fingerprint`] module.
119///
120/// Argument `unit` is expected to be the root unit, which will be uplifted.
121///
122/// Cargo emits its own dep-info files in the output directory. This is
123/// only done for every "uplifted" artifact. These are intended to be used
124/// with external build systems so that they can detect if Cargo needs to be
125/// re-executed.
126///
127/// It includes all the entries from the `rustc` dep-info file, and extends it
128/// with any `rerun-if-changed` entries from build scripts. It also includes
129/// sources from any path dependencies. Registry dependencies are not included
130/// under the assumption that changes to them can be detected via changes to
131/// `Cargo.lock`.
132///
133/// [`fingerprint`]: super::fingerprint#dep-info-files
134pub fn output_depinfo(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<()> {
135    let bcx = build_runner.bcx;
136    let mut deps = BTreeSet::new();
137    let mut visited = HashSet::default();
138    let success = add_deps_for_unit(&mut deps, build_runner, unit, &mut visited).is_ok();
139    let basedir_string;
140    let basedir = match bcx.gctx.build_config()?.dep_info_basedir.clone() {
141        Some(value) => {
142            basedir_string = value
143                .resolve_path(bcx.gctx)
144                .as_os_str()
145                .to_str()
146                .ok_or_else(|| anyhow::format_err!("build.dep-info-basedir path not utf-8"))?
147                .to_string();
148            Some(basedir_string.as_str())
149        }
150        None => None,
151    };
152    let deps = deps
153        .iter()
154        .map(|f| render_filename(f, basedir))
155        .collect::<CargoResult<Vec<_>>>()?;
156
157    for output in build_runner.outputs(unit)?.iter().filter(|o| {
158        !matches!(
159            o.flavor,
160            FileFlavor::DebugInfo | FileFlavor::Auxiliary | FileFlavor::Sbom | FileFlavor::Unremap
161        )
162    }) {
163        if let Some(ref link_dst) = output.hardlink {
164            let output_path = link_dst.with_extension("d");
165            if success {
166                let target_fn = render_filename(link_dst, basedir)?;
167
168                // If nothing changed don't recreate the file which could alter
169                // its mtime
170                if let Ok(previous) = fingerprint::parse_rustc_dep_info(&output_path) {
171                    if previous
172                        .files
173                        .iter()
174                        .map(|(path, _checksum)| path)
175                        .eq(deps.iter().map(Path::new))
176                    {
177                        continue;
178                    }
179                }
180
181                // Otherwise write it all out
182                let mut outfile = BufWriter::new(paths::create(output_path)?);
183                write!(outfile, "{}:", target_fn)?;
184                for dep in &deps {
185                    write!(outfile, " {}", dep)?;
186                }
187                writeln!(outfile)?;
188
189            // dep-info generation failed, so delete output file. This will
190            // usually cause the build system to always rerun the build
191            // rule, which is correct if inefficient.
192            } else if output_path.exists() {
193                paths::remove_file(output_path)?;
194            }
195        }
196    }
197    Ok(())
198}