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