Skip to main content

project_model/
cargo_workspace.rs

1//! See [`CargoWorkspace`].
2
3use std::{borrow::Cow, ops, str::from_utf8};
4
5use anyhow::Context;
6use base_db::{Env, TargetKind};
7use cargo_metadata::{CargoOpt, MetadataCommand, PackageId};
8use la_arena::{Arena, Idx};
9use paths::{AbsPath, AbsPathBuf, Utf8Path, Utf8PathBuf};
10use rustc_hash::{FxHashMap, FxHashSet};
11use serde_derive::Deserialize;
12use serde_json::from_value;
13use span::Edition;
14use stdx::process::spawn_with_streaming_output;
15use toolchain::{NO_RUSTUP_AUTO_INSTALL_ENV, Tool};
16use triomphe::Arc;
17
18use crate::{
19    CfgOverrides, InvocationStrategy, ManifestPath, Sysroot,
20    cargo_config_file::{LockfileCopy, LockfileUsage, make_lockfile_copy},
21};
22
23/// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
24/// workspace. It pretty closely mirrors `cargo metadata` output.
25///
26/// Note that internally, rust-analyzer uses a different structure:
27/// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
28/// while this knows about `Packages` & `Targets`: purely cargo-related
29/// concepts.
30///
31/// We use absolute paths here, `cargo metadata` guarantees to always produce
32/// abs paths.
33#[derive(Debug, Clone, Eq, PartialEq)]
34pub struct CargoWorkspace {
35    packages: Arena<PackageData>,
36    targets: Arena<TargetData>,
37    workspace_root: AbsPathBuf,
38    target_directory: AbsPathBuf,
39    build_directory: Option<AbsPathBuf>,
40    manifest_path: ManifestPath,
41    is_virtual_workspace: bool,
42    /// Whether this workspace represents the sysroot workspace.
43    is_sysroot: bool,
44    /// Environment variables set in the `.cargo/config` file and the extraEnv
45    /// configuration option.
46    env: Env,
47    requires_rustc_private: bool,
48}
49
50impl ops::Index<Package> for CargoWorkspace {
51    type Output = PackageData;
52    fn index(&self, index: Package) -> &PackageData {
53        &self.packages[index]
54    }
55}
56
57impl ops::Index<Target> for CargoWorkspace {
58    type Output = TargetData;
59    fn index(&self, index: Target) -> &TargetData {
60        &self.targets[index]
61    }
62}
63
64/// Describes how to set the rustc source directory.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub enum RustLibSource {
67    /// Explicit path for the rustc source directory.
68    Path(AbsPathBuf),
69    /// Try to automatically detect where the rustc source directory is.
70    Discover,
71}
72
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub enum CargoFeatures {
75    All,
76    Selected {
77        /// List of features to activate.
78        features: Vec<String>,
79        /// Do not activate the `default` feature.
80        no_default_features: bool,
81    },
82}
83
84impl Default for CargoFeatures {
85    fn default() -> Self {
86        CargoFeatures::Selected { features: vec![], no_default_features: false }
87    }
88}
89
90#[derive(Clone, Debug, Default, PartialEq, Eq)]
91pub enum TargetDirectoryConfig {
92    #[default]
93    None,
94    UseSubdirectory,
95    Directory(Utf8PathBuf),
96}
97
98impl TargetDirectoryConfig {
99    pub fn target_dir<'a>(
100        &'a self,
101        ws_target_dir: Option<&'a Utf8Path>,
102    ) -> Option<Cow<'a, Utf8Path>> {
103        match self {
104            TargetDirectoryConfig::None => None,
105            TargetDirectoryConfig::UseSubdirectory => {
106                Some(Cow::Owned(ws_target_dir?.join("rust-analyzer")))
107            }
108            TargetDirectoryConfig::Directory(dir) => Some(Cow::Borrowed(dir)),
109        }
110    }
111}
112
113#[derive(Default, Clone, Debug, PartialEq, Eq)]
114pub struct CargoConfig {
115    /// Whether to pass `--all-targets` to cargo invocations.
116    pub all_targets: bool,
117    /// List of features to activate.
118    pub features: CargoFeatures,
119    /// rustc target
120    pub target: Option<String>,
121    /// Sysroot loading behavior
122    pub sysroot: Option<RustLibSource>,
123    pub sysroot_src: Option<AbsPathBuf>,
124    /// rustc private crate source
125    pub rustc_source: Option<RustLibSource>,
126    /// Extra includes to add to the VFS.
127    pub extra_includes: Vec<AbsPathBuf>,
128    pub cfg_overrides: CfgOverrides,
129    /// Invoke `cargo check` through the RUSTC_WRAPPER.
130    pub wrap_rustc_in_build_scripts: bool,
131    /// The command to run instead of `cargo check` for building build scripts.
132    pub run_build_script_command: Option<Vec<String>>,
133    /// Extra args to pass to the cargo command.
134    pub extra_args: Vec<String>,
135    /// Extra args passed only to `cargo metadata`, not other cargo commands.
136    pub metadata_extra_args: Vec<String>,
137    /// Path to an extra config file passed to every cargo invocation via `--config`.
138    pub config_path: Option<AbsPathBuf>,
139    /// Extra env vars to set when invoking the cargo command
140    pub extra_env: FxHashMap<String, Option<String>>,
141    pub invocation_strategy: InvocationStrategy,
142    /// Optional path to use instead of `target` when building
143    pub target_dir_config: TargetDirectoryConfig,
144    /// Gate `#[test]` behind `#[cfg(test)]`
145    pub set_test: bool,
146    /// Load the project without any dependencies
147    pub no_deps: bool,
148}
149
150pub type Package = Idx<PackageData>;
151
152pub type Target = Idx<TargetData>;
153
154/// Information associated with a cargo crate
155#[derive(Debug, Clone, Eq, PartialEq)]
156pub struct PackageData {
157    /// Version given in the `Cargo.toml`
158    pub version: semver::Version,
159    /// Name as given in the `Cargo.toml`
160    pub name: String,
161    /// Repository as given in the `Cargo.toml`
162    pub repository: Option<String>,
163    /// Path containing the `Cargo.toml`
164    pub manifest: ManifestPath,
165    /// Targets provided by the crate (lib, bin, example, test, ...)
166    pub targets: Vec<Target>,
167    /// Does this package come from the local filesystem (and is editable)?
168    pub is_local: bool,
169    /// Whether this package is a member of the workspace
170    pub is_member: bool,
171    /// List of packages this package depends on
172    pub dependencies: Vec<PackageDependency>,
173    /// Rust edition for this package
174    pub edition: Edition,
175    /// Features provided by the crate, mapped to the features required by that feature.
176    pub features: FxHashMap<String, Vec<String>>,
177    /// List of features enabled on this package
178    pub active_features: Vec<String>,
179    /// Package id
180    pub id: Arc<PackageId>,
181    /// Authors as given in the `Cargo.toml`
182    pub authors: Vec<String>,
183    /// Description as given in the `Cargo.toml`
184    pub description: Option<String>,
185    /// Homepage as given in the `Cargo.toml`
186    pub homepage: Option<String>,
187    /// License as given in the `Cargo.toml`
188    pub license: Option<String>,
189    /// License file as given in the `Cargo.toml`
190    pub license_file: Option<Utf8PathBuf>,
191    /// Readme file as given in the `Cargo.toml`
192    pub readme: Option<Utf8PathBuf>,
193    /// Rust version as given in the `Cargo.toml`
194    pub rust_version: Option<semver::Version>,
195    /// The contents of [package.metadata.rust-analyzer]
196    pub metadata: RustAnalyzerPackageMetaData,
197    /// If this package is a member of the workspace, store all direct and transitive
198    /// dependencies as long as they are workspace members, to track dependency relationships
199    /// between members.
200    pub all_member_deps: Option<FxHashSet<Package>>,
201}
202
203#[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
204pub struct RustAnalyzerPackageMetaData {
205    pub rustc_private: bool,
206}
207
208#[derive(Debug, Clone, Eq, PartialEq)]
209pub struct PackageDependency {
210    pub pkg: Package,
211    pub name: String,
212    pub kind: DepKind,
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub enum DepKind {
217    /// Available to the library, binary, and dev targets in the package (but not the build script).
218    Normal,
219    /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
220    Dev,
221    /// Available only to the build script target.
222    Build,
223}
224
225impl DepKind {
226    fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> {
227        let mut dep_kinds = [None; 3];
228        if list.is_empty() {
229            dep_kinds[0] = Some(Self::Normal);
230        }
231        for info in list {
232            match info.kind {
233                cargo_metadata::DependencyKind::Normal => dep_kinds[0] = Some(Self::Normal),
234                cargo_metadata::DependencyKind::Development => dep_kinds[1] = Some(Self::Dev),
235                cargo_metadata::DependencyKind::Build => dep_kinds[2] = Some(Self::Build),
236                cargo_metadata::DependencyKind::Unknown => continue,
237            }
238        }
239        dep_kinds.into_iter().flatten()
240    }
241}
242
243/// Information associated with a package's target
244#[derive(Debug, Clone, Eq, PartialEq)]
245pub struct TargetData {
246    /// Package that provided this target
247    pub package: Package,
248    /// Name as given in the `Cargo.toml` or generated from the file name
249    pub name: String,
250    /// Path to the main source file of the target
251    pub root: AbsPathBuf,
252    /// Kind of target
253    pub kind: TargetKind,
254    /// Required features of the target without which it won't build
255    pub required_features: Vec<String>,
256}
257
258fn convert_target_kind(kinds: &[cargo_metadata::TargetKind]) -> TargetKind {
259    for kind in kinds {
260        return match kind {
261            cargo_metadata::TargetKind::Bin => TargetKind::Bin,
262            cargo_metadata::TargetKind::Test => TargetKind::Test,
263            cargo_metadata::TargetKind::Bench => TargetKind::Bench,
264            cargo_metadata::TargetKind::Example => TargetKind::Example,
265            cargo_metadata::TargetKind::CustomBuild => TargetKind::BuildScript,
266            cargo_metadata::TargetKind::ProcMacro => TargetKind::Lib { is_proc_macro: true },
267            cargo_metadata::TargetKind::Lib
268            | cargo_metadata::TargetKind::DyLib
269            | cargo_metadata::TargetKind::CDyLib
270            | cargo_metadata::TargetKind::StaticLib
271            | cargo_metadata::TargetKind::RLib => TargetKind::Lib { is_proc_macro: false },
272            _ => continue,
273        };
274    }
275    TargetKind::Other
276}
277
278#[derive(Default, Clone, Debug, PartialEq, Eq)]
279pub struct CargoMetadataConfig {
280    /// List of features to activate.
281    pub features: CargoFeatures,
282    /// rustc targets
283    pub targets: Vec<String>,
284    /// Extra args to pass to the cargo command.
285    pub extra_args: Vec<String>,
286    /// Extra args passed directly to `cargo metadata` without filtering.
287    pub metadata_extra_args: Vec<String>,
288    /// Path to an extra config file passed to `cargo metadata` via `--config`.
289    pub config_path: Option<AbsPathBuf>,
290    /// Extra env vars to set when invoking the cargo command
291    pub extra_env: FxHashMap<String, Option<String>>,
292    /// What kind of metadata are we fetching: workspace, rustc, or sysroot.
293    pub kind: CargoMetadataKind,
294    /// The toolchain version, if known.
295    /// Used to conditionally enable unstable cargo features.
296    pub toolchain_version: Option<semver::Version>,
297}
298
299#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
300pub enum CargoMetadataKind {
301    #[default]
302    Workspace,
303    DetachedFile,
304    Rustc,
305    Sysroot,
306}
307
308// Deserialize helper for the cargo metadata
309#[derive(Deserialize, Default)]
310struct PackageMetadata {
311    #[serde(rename = "rust-analyzer")]
312    rust_analyzer: Option<RustAnalyzerPackageMetaData>,
313}
314
315impl CargoWorkspace {
316    pub fn new(
317        mut meta: cargo_metadata::Metadata,
318        ws_manifest_path: ManifestPath,
319        cargo_env: Env,
320        is_sysroot: bool,
321    ) -> CargoWorkspace {
322        let mut pkg_by_id = FxHashMap::default();
323        let mut packages = Arena::default();
324        let mut targets = Arena::default();
325
326        let ws_members = &meta.workspace_members;
327
328        let workspace_root = AbsPathBuf::assert(meta.workspace_root);
329        let target_directory = AbsPathBuf::assert(meta.target_directory);
330        let build_directory = meta.build_directory.map(AbsPathBuf::assert);
331        let mut is_virtual_workspace = true;
332        let mut requires_rustc_private = false;
333
334        let mut members = FxHashSet::default();
335
336        meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
337        for meta_pkg in meta.packages {
338            let cargo_metadata::Package {
339                name,
340                version,
341                id,
342                source,
343                targets: meta_targets,
344                features,
345                manifest_path,
346                repository,
347                edition,
348                metadata,
349                authors,
350                description,
351                homepage,
352                license,
353                license_file,
354                readme,
355                rust_version,
356                ..
357            } = meta_pkg;
358            let id = Arc::new(id);
359            let meta = from_value::<PackageMetadata>(metadata).unwrap_or_default();
360            let edition = match edition {
361                cargo_metadata::Edition::E2015 => Edition::Edition2015,
362                cargo_metadata::Edition::E2018 => Edition::Edition2018,
363                cargo_metadata::Edition::E2021 => Edition::Edition2021,
364                cargo_metadata::Edition::E2024 => Edition::Edition2024,
365                _ => {
366                    tracing::error!("Unsupported edition `{:?}`", edition);
367                    Edition::CURRENT
368                }
369            };
370            // We treat packages without source as "local" packages. That includes all members of
371            // the current workspace, as well as any path dependency outside the workspace.
372            let is_local = source.is_none();
373            let is_member = ws_members.contains(&id);
374
375            let manifest = ManifestPath::try_from(AbsPathBuf::assert(manifest_path)).unwrap();
376            is_virtual_workspace &= manifest != ws_manifest_path;
377            let pkg = packages.alloc(PackageData {
378                id: id.clone(),
379                name: name.to_string(),
380                version,
381                manifest: manifest.clone(),
382                targets: Vec::new(),
383                is_local,
384                is_member,
385                edition,
386                repository,
387                authors,
388                description,
389                homepage,
390                license,
391                license_file,
392                readme,
393                rust_version,
394                dependencies: Vec::new(),
395                features: features.into_iter().collect(),
396                active_features: Vec::new(),
397                metadata: meta.rust_analyzer.unwrap_or_default(),
398                all_member_deps: None,
399            });
400            if is_member {
401                members.insert(pkg);
402            }
403            let pkg_data = &mut packages[pkg];
404            requires_rustc_private |= pkg_data.metadata.rustc_private;
405            pkg_by_id.insert(id, pkg);
406            for meta_tgt in meta_targets {
407                let cargo_metadata::Target { name, kind, required_features, src_path, .. } =
408                    meta_tgt;
409                let kind = convert_target_kind(&kind);
410                let tgt = targets.alloc(TargetData {
411                    package: pkg,
412                    name,
413                    root: if kind == TargetKind::Bin
414                        && manifest.extension().is_some_and(|ext| ext == "rs")
415                    {
416                        // cargo strips the script part of a cargo script away and places the
417                        // modified manifest file into a special target dir which is then used as
418                        // the source path. We don't want that, we want the original here so map it
419                        // back
420                        manifest.clone().into()
421                    } else {
422                        AbsPathBuf::assert(src_path)
423                    },
424                    kind,
425                    required_features,
426                });
427                pkg_data.targets.push(tgt);
428            }
429        }
430        for mut node in meta.resolve.map_or_else(Vec::new, |it| it.nodes) {
431            let &source = pkg_by_id.get(&node.id).unwrap();
432            node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
433            let dependencies = node
434                .deps
435                .iter()
436                .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)));
437            for (dep_node, kind) in dependencies {
438                let &pkg = pkg_by_id.get(&dep_node.pkg).unwrap();
439                let dep = PackageDependency { name: dep_node.name.to_string(), pkg, kind };
440                packages[source].dependencies.push(dep);
441            }
442            packages[source]
443                .active_features
444                .extend(node.features.into_iter().map(|it| it.to_string()));
445        }
446
447        fn saturate_all_member_deps(
448            packages: &mut Arena<PackageData>,
449            to_visit: Package,
450            visited: &mut FxHashSet<Package>,
451            members: &FxHashSet<Package>,
452        ) {
453            let pkg_data = &mut packages[to_visit];
454
455            if !visited.insert(to_visit) {
456                return;
457            }
458
459            let deps: Vec<_> = pkg_data
460                .dependencies
461                .iter()
462                .filter_map(|dep| {
463                    let pkg = dep.pkg;
464                    if members.contains(&pkg) { Some(pkg) } else { None }
465                })
466                .collect();
467
468            let mut all_member_deps = FxHashSet::from_iter(deps.iter().copied());
469            for dep in deps {
470                saturate_all_member_deps(packages, dep, visited, members);
471                if let Some(transitives) = &packages[dep].all_member_deps {
472                    all_member_deps.extend(transitives);
473                }
474            }
475
476            packages[to_visit].all_member_deps = Some(all_member_deps);
477        }
478
479        let mut visited = FxHashSet::default();
480        for member in members.iter() {
481            saturate_all_member_deps(&mut packages, *member, &mut visited, &members);
482        }
483
484        CargoWorkspace {
485            packages,
486            targets,
487            workspace_root,
488            target_directory,
489            build_directory,
490            manifest_path: ws_manifest_path,
491            is_virtual_workspace,
492            requires_rustc_private,
493            is_sysroot,
494            env: cargo_env,
495        }
496    }
497
498    pub fn packages(&self) -> impl ExactSizeIterator<Item = Package> + '_ {
499        self.packages.iter().map(|(id, _pkg)| id)
500    }
501
502    pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
503        self.packages()
504            .filter(|&pkg| self[pkg].is_member)
505            .find_map(|pkg| self[pkg].targets.iter().find(|&&it| self[it].root == root))
506            .copied()
507    }
508
509    pub fn workspace_root(&self) -> &AbsPath {
510        &self.workspace_root
511    }
512
513    pub fn manifest_path(&self) -> &ManifestPath {
514        &self.manifest_path
515    }
516
517    pub fn target_directory(&self) -> &AbsPath {
518        &self.target_directory
519    }
520
521    pub fn build_directory(&self) -> Option<&AbsPath> {
522        self.build_directory.as_deref()
523    }
524
525    pub fn package_flag(&self, package: &PackageData) -> String {
526        if self.is_unique(&package.name) {
527            package.name.clone()
528        } else {
529            format!("{}:{}", package.name, package.version)
530        }
531    }
532
533    pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
534        let mut found = false;
535        let parent_manifests = self
536            .packages()
537            .filter_map(|pkg| {
538                if !found && &self[pkg].manifest == manifest_path {
539                    found = true
540                }
541                self[pkg].dependencies.iter().find_map(|dep| {
542                    (&self[dep.pkg].manifest == manifest_path).then(|| self[pkg].manifest.clone())
543                })
544            })
545            .collect::<Vec<ManifestPath>>();
546
547        // some packages has this pkg as dep. return their manifests
548        if !parent_manifests.is_empty() {
549            return Some(parent_manifests);
550        }
551
552        // this pkg is inside this cargo workspace, fallback to workspace root
553        if found {
554            return Some(vec![
555                ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?,
556            ]);
557        }
558
559        // not in this workspace
560        None
561    }
562
563    /// Returns the union of the features of all member crates in this workspace.
564    pub fn workspace_features(&self) -> FxHashSet<String> {
565        self.packages()
566            .filter_map(|package| {
567                let package = &self[package];
568                if package.is_member {
569                    Some(package.features.keys().cloned().chain(
570                        package.features.keys().map(|key| format!("{}/{key}", package.name)),
571                    ))
572                } else {
573                    None
574                }
575            })
576            .flatten()
577            .collect()
578    }
579
580    fn is_unique(&self, name: &str) -> bool {
581        self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
582    }
583
584    pub fn is_virtual_workspace(&self) -> bool {
585        self.is_virtual_workspace
586    }
587
588    pub fn env(&self) -> &Env {
589        &self.env
590    }
591
592    pub fn is_sysroot(&self) -> bool {
593        self.is_sysroot
594    }
595
596    pub fn requires_rustc_private(&self) -> bool {
597        self.requires_rustc_private
598    }
599}
600
601pub(crate) struct FetchMetadata {
602    command: cargo_metadata::MetadataCommand,
603    #[expect(dead_code)]
604    manifest_path: ManifestPath,
605    lockfile_copy: Option<LockfileCopy>,
606    #[expect(dead_code)]
607    kind: CargoMetadataKind,
608    no_deps: bool,
609    no_deps_result: anyhow::Result<cargo_metadata::Metadata>,
610    other_options: Vec<String>,
611}
612
613impl FetchMetadata {
614    /// Builds a command to fetch metadata for the given `cargo_toml` manifest.
615    ///
616    /// Performs a lightweight pre-fetch using the `--no-deps` option,
617    /// available via `FetchMetadata::no_deps_metadata`, to gather basic
618    /// information such as the `target-dir`.
619    ///
620    /// The provided sysroot is used to set the `RUSTUP_TOOLCHAIN`
621    /// environment variable when invoking Cargo, ensuring that the
622    /// rustup proxy selects the correct toolchain.
623    pub(crate) fn new(
624        cargo_toml: &ManifestPath,
625        current_dir: &AbsPath,
626        config: &CargoMetadataConfig,
627        sysroot: &Sysroot,
628        no_deps: bool,
629    ) -> Self {
630        let cargo = sysroot.tool(Tool::Cargo, current_dir, &config.extra_env);
631        let mut command = MetadataCommand::new();
632        command.env(NO_RUSTUP_AUTO_INSTALL_ENV.0, NO_RUSTUP_AUTO_INSTALL_ENV.1);
633        command.cargo_path(cargo.get_program());
634        cargo.get_envs().for_each(|(var, val)| _ = command.env(var, val.unwrap_or_default()));
635        command.manifest_path(cargo_toml.to_path_buf());
636        match &config.features {
637            CargoFeatures::All => {
638                command.features(CargoOpt::AllFeatures);
639            }
640            CargoFeatures::Selected { features, no_default_features } => {
641                if *no_default_features {
642                    command.features(CargoOpt::NoDefaultFeatures);
643                }
644                if !features.is_empty() {
645                    command.features(CargoOpt::SomeFeatures(features.clone()));
646                }
647            }
648        }
649        command.current_dir(current_dir);
650
651        let mut other_options = vec![];
652        // cargo metadata only supports a subset of flags of what cargo usually accepts, and usually
653        // the only relevant flags for metadata here are unstable ones, so we pass those along
654        // but nothing else
655        let mut extra_args = config.extra_args.iter();
656        while let Some(arg) = extra_args.next() {
657            if arg == "-Z"
658                && let Some(arg) = extra_args.next()
659            {
660                other_options.push("-Z".to_owned());
661                other_options.push(arg.to_owned());
662            }
663        }
664        other_options.extend(config.metadata_extra_args.iter().cloned());
665        if let Some(config_path) = &config.config_path {
666            other_options.push("--config".to_owned());
667            other_options.push(config_path.to_string());
668        }
669
670        let mut lockfile_copy = None;
671        if cargo_toml.is_rust_manifest() {
672            other_options.push("-Zscript".to_owned());
673        } else if let Some(v) = config.toolchain_version.as_ref() {
674            let manifest: &Utf8Path = cargo_toml.as_ref();
675            let lockfile_path = if config.kind == CargoMetadataKind::Rustc {
676                // The `rustc-dev` component ships `rustc-src/rust/compiler/rustc/Cargo.toml`
677                // without the workspace root manifest, so the lockfile at
678                // `rustc-src/rust/Cargo.lock` is neither next to the manifest nor discoverable
679                // by cargo. Without a copy of it, `cargo metadata --locked` fails and we degrade
680                // to `--no-deps` metadata, losing all rustc crates (e.g. `rustc_middle`).
681                manifest.ancestors().nth(3).map(|dir| dir.join("Cargo.lock"))
682            } else {
683                Some(manifest.with_extension("lock"))
684            };
685            lockfile_copy = lockfile_path.and_then(|path| make_lockfile_copy(v, &path));
686        }
687
688        if !config.targets.is_empty() {
689            let mut has_json_target = false;
690            other_options.extend(config.targets.iter().flat_map(|target| {
691                has_json_target |= target.ends_with(".json");
692                ["--filter-platform".to_owned(), target.clone()]
693            }));
694            if has_json_target
695                && config.toolchain_version.as_ref().is_some_and(|version| {
696                    *version >= toolchain::MINIMUM_TOOLCHAIN_VERSION_REQUIRING_JSON_TARGET_SPEC_FLAG
697                })
698            {
699                other_options.push("-Zjson-target-spec".to_owned());
700            }
701        }
702
703        command.other_options(other_options.clone());
704
705        // Pre-fetch basic metadata using `--no-deps`, which:
706        // - avoids fetching registries like crates.io,
707        // - skips dependency resolution and does not modify lockfiles,
708        // - and thus doesn't require progress reporting or copying lockfiles.
709        //
710        // Useful as a fast fallback to extract info like `target-dir`.
711        let cargo_command;
712        let no_deps_result = if no_deps {
713            command.no_deps();
714            cargo_command = command.cargo_command();
715            command.exec()
716        } else {
717            let mut no_deps_command = command.clone();
718            no_deps_command.no_deps();
719            cargo_command = no_deps_command.cargo_command();
720            no_deps_command.exec()
721        }
722        .with_context(|| format!("Failed to run `{cargo_command:?}`"));
723
724        Self {
725            manifest_path: cargo_toml.clone(),
726            command,
727            lockfile_copy,
728            kind: config.kind,
729            no_deps,
730            no_deps_result,
731            other_options,
732        }
733    }
734
735    /// Executes the metadata-fetching command.
736    ///
737    /// A successful result may still contain a metadata error if the full fetch failed,
738    /// but the fallback `--no-deps` pre-fetch succeeded during command construction.
739    pub(crate) fn exec(
740        self,
741        locked: bool,
742        progress: &dyn Fn(String),
743    ) -> anyhow::Result<(cargo_metadata::Metadata, Option<anyhow::Error>)> {
744        let Self {
745            mut command,
746            manifest_path: _,
747            lockfile_copy,
748            kind: _,
749            no_deps,
750            no_deps_result,
751            mut other_options,
752        } = self;
753
754        if no_deps {
755            return no_deps_result.map(|m| (m, None));
756        }
757
758        let mut using_lockfile_copy = false;
759        if let Some(lockfile_copy) = &lockfile_copy {
760            match lockfile_copy.usage {
761                LockfileUsage::WithFlag => {
762                    other_options.push("--lockfile-path".to_owned());
763                    other_options.push(lockfile_copy.path.to_string());
764                }
765                LockfileUsage::WithEnvVarUnstable => {
766                    other_options.push("-Zlockfile-path".to_owned());
767                    command.env("CARGO_RESOLVER_LOCKFILE_PATH", lockfile_copy.path.as_os_str());
768                }
769                LockfileUsage::WithEnvVar => {
770                    command.env("CARGO_RESOLVER_LOCKFILE_PATH", lockfile_copy.path.as_os_str());
771                }
772            }
773            using_lockfile_copy = true;
774        }
775        if using_lockfile_copy || other_options.iter().any(|it| it.starts_with("-Z")) {
776            command.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
777            other_options.push("-Zunstable-options".to_owned());
778        }
779        // No need to lock it if we copied the lockfile, we won't modify the original after all/
780        // This way cargo cannot error out on us if the lockfile requires updating.
781        if !using_lockfile_copy && locked {
782            other_options.push("--locked".to_owned());
783        }
784        command.other_options(other_options);
785
786        progress("cargo metadata: started".to_owned());
787
788        let res = (|| -> anyhow::Result<(_, _)> {
789            let mut errored = false;
790            tracing::debug!("Running `{:?}`", command.cargo_command());
791            let output =
792                spawn_with_streaming_output(command.cargo_command(), &mut |_| (), &mut |line| {
793                    errored = errored || line.starts_with("error") || line.starts_with("warning");
794                    if errored {
795                        progress("cargo metadata: ?".to_owned());
796                        return;
797                    }
798                    progress(format!("cargo metadata: {line}"));
799                })?;
800            if !output.status.success() {
801                progress(format!("cargo metadata: failed {}", output.status));
802                let error = cargo_metadata::Error::CargoMetadata {
803                    stderr: String::from_utf8(output.stderr)?,
804                }
805                .into();
806                if !no_deps {
807                    // If we failed to fetch metadata with deps, return pre-fetched result without them.
808                    // This makes r-a still work partially when offline.
809                    if let Ok(metadata) = no_deps_result {
810                        tracing::warn!(
811                            ?error,
812                            "`cargo metadata` failed and returning succeeded result with `--no-deps`"
813                        );
814                        return Ok((metadata, Some(error)));
815                    }
816                }
817                return Err(error);
818            }
819            let stdout = from_utf8(&output.stdout)?
820                .lines()
821                .find(|line| line.starts_with('{'))
822                .ok_or(cargo_metadata::Error::NoJson)?;
823            Ok((cargo_metadata::MetadataCommand::parse(stdout)?, None))
824        })()
825        .with_context(|| format!("Failed to run `{:?}`", command.cargo_command()));
826        progress("cargo metadata: finished".to_owned());
827        res
828    }
829}