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