Skip to main content

bootstrap/core/
metadata.rs

1//! This module interacts with Cargo metadata to collect and store information about
2//! the packages in the Rust workspace.
3//!
4//! It runs `cargo metadata` to gather details about each package, including its name,
5//! source, dependencies, targets, and available features. The collected metadata is then
6//! used to update the `Build` structure, ensuring proper dependency resolution and
7//! compilation flow.
8
9use std::collections::{BTreeMap, HashSet};
10use std::path::PathBuf;
11
12use serde_derive::Deserialize;
13
14use crate::Build;
15use crate::utils::exec::command;
16use crate::utils::helpers::t;
17
18#[derive(Debug, Clone)]
19pub(crate) struct Crate {
20    pub(crate) name: String,
21    pub(crate) deps: HashSet<String>,
22    pub(crate) path: PathBuf,
23    pub(crate) features: Vec<String>,
24}
25
26impl Crate {
27    pub(crate) fn local_path(&self, build: &Build) -> PathBuf {
28        self.path.strip_prefix(&build.config.src).unwrap().into()
29    }
30}
31
32/// For more information, see the output of
33/// <https://doc.rust-lang.org/nightly/cargo/commands/cargo-metadata.html>
34#[derive(Debug, Deserialize)]
35struct Output {
36    packages: Vec<Package>,
37}
38
39/// For more information, see the output of
40/// <https://doc.rust-lang.org/nightly/cargo/commands/cargo-metadata.html>
41#[derive(Debug, Deserialize)]
42struct Package {
43    name: String,
44    source: Option<String>,
45    manifest_path: String,
46    dependencies: Vec<Dependency>,
47    features: BTreeMap<String, Vec<String>>,
48}
49
50/// For more information, see the output of
51/// <https://doc.rust-lang.org/nightly/cargo/commands/cargo-metadata.html>
52#[derive(Debug, Deserialize)]
53struct Dependency {
54    name: String,
55    source: Option<String>,
56}
57
58/// Collects and stores package metadata of each workspace members into `build`,
59/// by executing `cargo metadata` commands.
60pub fn build(build: &mut Build) {
61    for package in workspace_members(build) {
62        if package.source.is_none() {
63            let name = package.name;
64            let mut path = PathBuf::from(package.manifest_path);
65            path.pop();
66            let deps = package
67                .dependencies
68                .into_iter()
69                .filter(|dep| dep.source.is_none())
70                .map(|dep| dep.name)
71                .collect();
72            let krate = Crate {
73                name: name.clone(),
74                deps,
75                path,
76                features: package.features.keys().cloned().collect(),
77            };
78            let relative_path = krate.local_path(build);
79            build.crates.insert(name.clone(), krate);
80            let existing_path = build.crate_paths.insert(relative_path, name);
81            assert!(
82                existing_path.is_none(),
83                "multiple crates with the same path: {}",
84                existing_path.unwrap()
85            );
86        }
87    }
88}
89
90/// Invokes `cargo metadata` to get package metadata of each workspace member.
91///
92/// This is used to resolve specific crate paths in `fn should_run` to compile
93/// particular crate (e.g., `x build sysroot` to build library/sysroot).
94fn workspace_members(build: &Build) -> Vec<Package> {
95    let collect_metadata = |manifest_path| {
96        let mut cargo = command(&build.initial_cargo);
97        cargo
98            // Will read the libstd Cargo.toml
99            // which uses the unstable `public-dependency` feature.
100            .env("RUSTC_BOOTSTRAP", "1")
101            .arg("metadata")
102            .arg("--format-version")
103            .arg("1")
104            .arg("--no-deps")
105            .arg("--manifest-path")
106            .arg(build.src.join(manifest_path));
107        let metadata_output = cargo.run_in_dry_run().run_capture_stdout(build).stdout();
108        let Output { packages, .. } = t!(serde_json::from_str(&metadata_output));
109        packages
110    };
111
112    // Collects `metadata.packages` from the root and library workspaces.
113    let mut packages = vec![];
114    packages.extend(collect_metadata("Cargo.toml"));
115    packages.extend(collect_metadata("library/Cargo.toml"));
116    packages
117}