Skip to main content

cargo/workspace/
workspace.rs

1use crate::util::data_structures::{HashMap, HashSet, IndexSet};
2use std::cell::RefCell;
3use std::collections::hash_map::Entry;
4use std::collections::{BTreeMap, BTreeSet};
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8use anyhow::{Context as _, anyhow, bail};
9use cargo_util_terminal::report::Level;
10use glob::glob;
11use itertools::Itertools;
12use tracing::debug;
13use url::Url;
14
15use crate::compiler::Unit;
16use crate::context;
17use crate::context::{
18    CargoResolverConfig, ConfigRelativePath, FeatureUnification, IncompatibleRustVersions, Value,
19};
20use crate::ops;
21use crate::ops::lockfile::LOCKFILE_NAME;
22use crate::resolver::ResolveBehavior;
23use crate::resolver::features::CliFeatures;
24use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY, PathSource, SourceConfigMap};
25use crate::util::edit_distance;
26use crate::util::errors::{CargoResult, ManifestError};
27use crate::util::interning::InternedString;
28use crate::util::{Filesystem, GlobalContext, IntoUrl, closest_msg};
29use crate::workspace::features::Features;
30use crate::workspace::parser::{InheritableFields, read_manifest};
31use crate::workspace::registry::PackageRegistry;
32use crate::workspace::{
33    Dependency, Edition, FeatureValue, PackageId, PackageIdSpec, PackageIdSpecQuery, Patch,
34    PatchLocation,
35};
36use crate::workspace::{EitherManifest, Package, SourceId, VirtualManifest};
37
38use cargo_util::paths;
39use cargo_util::paths::normalize_path;
40use cargo_util_schemas::manifest::RustVersion;
41use cargo_util_schemas::manifest::{TomlDependency, TomlManifest, TomlProfiles};
42use pathdiff::diff_paths;
43
44/// The core abstraction in Cargo for working with a workspace of crates.
45///
46/// A workspace is often created very early on and then threaded through all
47/// other functions. It's typically through this object that the current
48/// package is loaded and/or learned about.
49#[derive(Debug)]
50pub struct Workspace<'gctx> {
51    /// Cargo configuration information. See [`GlobalContext`].
52    gctx: &'gctx GlobalContext,
53
54    /// This path is a path to where the current cargo subcommand was invoked
55    /// from. That is the `--manifest-path` argument to Cargo, and
56    /// points to the "main crate" that we're going to worry about.
57    current_manifest: PathBuf,
58
59    /// A list of packages found in this workspace. Always includes at least the
60    /// package mentioned by `current_manifest`.
61    packages: Packages<'gctx>,
62
63    /// If this workspace includes more than one crate, this points to the root
64    /// of the workspace. This is `None` in the case that `[workspace]` is
65    /// missing, `package.workspace` is missing, and no `Cargo.toml` above
66    /// `current_manifest` was found on the filesystem with `[workspace]`.
67    root_manifest: Option<PathBuf>,
68
69    /// Shared target directory for all the packages of this workspace.
70    /// `None` if the default path of `root/target` should be used.
71    target_dir: Option<Filesystem>,
72
73    /// Shared build directory for intermediate build artifacts.
74    /// This directory may be shared between multiple workspaces.
75    build_dir: Option<Filesystem>,
76
77    /// List of members in this workspace with a listing of all their manifest
78    /// paths. The packages themselves can be looked up through the `packages`
79    /// set above.
80    ///
81    /// Note: this uses a set because we query it using `contains`, which is
82    /// faster with a set, partly because running `PartialEq` on a bunch of paths
83    /// isn't very fast.
84    members: IndexSet<PathBuf>,
85    /// Set of ids of workspace members
86    member_ids: HashSet<PackageId>,
87
88    /// The subset of `members` that are used by the
89    /// `build`, `check`, `test`, and `bench` subcommands
90    /// when no package is selected with `--package` / `-p` and `--workspace`
91    /// is not used.
92    ///
93    /// This is set by the `default-members` config
94    /// in the `[workspace]` section.
95    /// When unset, this is the same as `members` for virtual workspaces
96    /// (`--workspace` is implied)
97    /// or only the root package for non-virtual workspaces.
98    default_members: Vec<PathBuf>,
99
100    /// `true` if this is a temporary workspace created for the purposes of the
101    /// `cargo install` or `cargo package` commands.
102    is_ephemeral: bool,
103
104    /// `true` if this workspace should enforce optional dependencies even when
105    /// not needed; false if this workspace should only enforce dependencies
106    /// needed by the current configuration (such as in cargo install). In some
107    /// cases `false` also results in the non-enforcement of dev-dependencies.
108    require_optional_deps: bool,
109
110    /// A cache of loaded packages for particular paths which is disjoint from
111    /// `packages` up above, used in the `load` method down below.
112    loaded_packages: RefCell<HashMap<PathBuf, Package>>,
113
114    /// If `true`, then the resolver will ignore any existing `Cargo.lock`
115    /// file. This is set for `cargo install` without `--locked`.
116    ignore_lock: bool,
117
118    /// Requested path of the lockfile (i.e. passed as the cli flag)
119    requested_lockfile_path: Option<PathBuf>,
120
121    /// The resolver behavior specified with the `resolver` field.
122    resolve_behavior: ResolveBehavior,
123    /// If `true`, then workspace `rust_version` would be used in `cargo resolve`
124    /// and other places that use rust version.
125    /// This is set based on the resolver version, config settings, and CLI flags.
126    resolve_honors_rust_version: bool,
127    /// The feature unification mode used when building packages.
128    resolve_feature_unification: FeatureUnification,
129    /// Whether resolution enforces `min-publish-age`.
130    resolve_honors_publish_age: bool,
131    /// Latest publish time allowed for packages
132    resolve_publish_time: Option<jiff::Timestamp>,
133    /// Workspace-level custom metadata
134    custom_metadata: Option<toml::Value>,
135
136    /// Local overlay configuration. See [`crate::sources::overlay`].
137    local_overlays: HashMap<SourceId, PathBuf>,
138}
139
140// Separate structure for tracking loaded packages (to avoid loading anything
141// twice), and this is separate to help appease the borrow checker.
142#[derive(Debug)]
143struct Packages<'gctx> {
144    gctx: &'gctx GlobalContext,
145    packages: HashMap<PathBuf, MaybePackage>,
146}
147
148#[derive(Debug)]
149pub enum MaybePackage {
150    Package(Package),
151    Virtual(VirtualManifest),
152}
153
154/// Configuration of a workspace in a manifest.
155#[derive(Debug, Clone)]
156pub enum WorkspaceConfig {
157    /// Indicates that `[workspace]` was present and the members were
158    /// optionally specified as well.
159    Root(WorkspaceRootConfig),
160
161    /// Indicates that `[workspace]` was present and the `root` field is the
162    /// optional value of `package.workspace`, if present.
163    Member { root: Option<String> },
164}
165
166impl WorkspaceConfig {
167    pub fn inheritable(&self) -> Option<&InheritableFields> {
168        match self {
169            WorkspaceConfig::Root(root) => Some(&root.inheritable_fields),
170            WorkspaceConfig::Member { .. } => None,
171        }
172    }
173
174    /// Returns the path of the workspace root based on this `[workspace]` configuration.
175    ///
176    /// Returns `None` if the root is not explicitly known.
177    ///
178    /// * `self_path` is the path of the manifest this `WorkspaceConfig` is located.
179    /// * `look_from` is the path where discovery started (usually the current
180    ///   working directory), used for `workspace.exclude` checking.
181    fn get_ws_root(&self, self_path: &Path, look_from: &Path) -> Option<PathBuf> {
182        match self {
183            WorkspaceConfig::Root(ances_root_config) => {
184                debug!("find_root - found a root checking exclusion");
185                if !ances_root_config.is_excluded(look_from) {
186                    debug!("find_root - found!");
187                    Some(self_path.to_owned())
188                } else {
189                    None
190                }
191            }
192            WorkspaceConfig::Member {
193                root: Some(path_to_root),
194            } => {
195                debug!("find_root - found pointer");
196                Some(read_root_pointer(self_path, path_to_root))
197            }
198            WorkspaceConfig::Member { .. } => None,
199        }
200    }
201}
202
203/// Intermediate configuration of a workspace root in a manifest.
204///
205/// Knows the Workspace Root path, as well as `members` and `exclude` lists of path patterns, which
206/// together tell if some path is recognized as a member by this root or not.
207#[derive(Debug, Clone)]
208pub struct WorkspaceRootConfig {
209    root_dir: PathBuf,
210    members: Option<Vec<String>>,
211    default_members: Option<Vec<String>>,
212    exclude: Vec<String>,
213    inheritable_fields: InheritableFields,
214    custom_metadata: Option<toml::Value>,
215}
216
217impl<'gctx> Workspace<'gctx> {
218    /// Creates a new workspace given the target manifest pointed to by
219    /// `manifest_path`.
220    ///
221    /// This function will construct the entire workspace by determining the
222    /// root and all member packages. It will then validate the workspace
223    /// before returning it, so `Ok` is only returned for valid workspaces.
224    pub fn new(manifest_path: &Path, gctx: &'gctx GlobalContext) -> CargoResult<Workspace<'gctx>> {
225        let mut ws = Workspace::new_default(manifest_path.to_path_buf(), gctx);
226
227        if manifest_path.is_relative() {
228            bail!(
229                "manifest_path:{:?} is not an absolute path. Please provide an absolute path.",
230                manifest_path
231            )
232        } else {
233            ws.root_manifest = ws.find_root(manifest_path)?;
234        }
235
236        ws.target_dir = gctx.target_dir()?;
237        ws.build_dir = gctx.build_dir(ws.root_manifest())?;
238
239        ws.custom_metadata = ws
240            .load_workspace_config()?
241            .and_then(|cfg| cfg.custom_metadata);
242        ws.find_members()?;
243        ws.set_resolve_behavior()?;
244        ws.validate()?;
245        Ok(ws)
246    }
247
248    fn new_default(current_manifest: PathBuf, gctx: &'gctx GlobalContext) -> Workspace<'gctx> {
249        Workspace {
250            gctx,
251            current_manifest,
252            packages: Packages {
253                gctx,
254                packages: HashMap::default(),
255            },
256            root_manifest: None,
257            target_dir: None,
258            build_dir: None,
259            members: IndexSet::default(),
260            member_ids: HashSet::default(),
261            default_members: Vec::new(),
262            is_ephemeral: false,
263            require_optional_deps: true,
264            loaded_packages: RefCell::new(HashMap::default()),
265            ignore_lock: false,
266            requested_lockfile_path: None,
267            resolve_behavior: ResolveBehavior::V1,
268            resolve_honors_rust_version: false,
269            resolve_feature_unification: FeatureUnification::Selected,
270            resolve_honors_publish_age: true,
271            resolve_publish_time: None,
272            custom_metadata: None,
273            local_overlays: HashMap::default(),
274        }
275    }
276
277    /// Creates a "temporary workspace" from one package which only contains
278    /// that package.
279    ///
280    /// This constructor will not touch the filesystem and only creates an
281    /// in-memory workspace. That is, all configuration is ignored, it's just
282    /// intended for that one package.
283    ///
284    /// This is currently only used in niche situations like `cargo install` or
285    /// `cargo package`.
286    pub fn ephemeral(
287        package: Package,
288        gctx: &'gctx GlobalContext,
289        target_dir: Option<Filesystem>,
290        require_optional_deps: bool,
291    ) -> CargoResult<Workspace<'gctx>> {
292        let mut ws = Workspace::new_default(package.manifest_path().to_path_buf(), gctx);
293        ws.is_ephemeral = true;
294        ws.require_optional_deps = require_optional_deps;
295        let id = package.package_id();
296        let package = MaybePackage::Package(package);
297        ws.packages
298            .packages
299            .insert(ws.current_manifest.clone(), package);
300        ws.target_dir = if let Some(dir) = target_dir {
301            Some(dir)
302        } else {
303            ws.gctx.target_dir()?
304        };
305        ws.build_dir = ws.target_dir.clone();
306        ws.members.insert(ws.current_manifest.clone());
307        ws.member_ids.insert(id);
308        ws.default_members.push(ws.current_manifest.clone());
309        ws.set_resolve_behavior()?;
310        Ok(ws)
311    }
312
313    /// Reloads the workspace.
314    ///
315    /// This is useful if the workspace has been updated, such as with `cargo
316    /// fix` modifying the `Cargo.toml` file.
317    pub fn reload(&self, gctx: &'gctx GlobalContext) -> CargoResult<Workspace<'gctx>> {
318        let mut ws = Workspace::new(&self.current_manifest, gctx)?;
319        ws.set_resolve_honors_rust_version(Some(self.resolve_honors_rust_version));
320        ws.set_resolve_feature_unification(self.resolve_feature_unification);
321        ws.set_requested_lockfile_path(self.requested_lockfile_path.clone());
322        Ok(ws)
323    }
324
325    fn set_resolve_behavior(&mut self) -> CargoResult<()> {
326        // - If resolver is specified in the workspace definition, use that.
327        // - If the root package specifies the resolver, use that.
328        // - If the root package specifies edition 2021, use v2.
329        // - Otherwise, use the default v1.
330        self.resolve_behavior = match self.root_maybe() {
331            MaybePackage::Package(p) => p
332                .manifest()
333                .resolve_behavior()
334                .unwrap_or_else(|| p.manifest().edition().default_resolve_behavior()),
335            MaybePackage::Virtual(vm) => vm.resolve_behavior().unwrap_or(ResolveBehavior::V1),
336        };
337
338        match self.resolve_behavior() {
339            ResolveBehavior::V1 | ResolveBehavior::V2 => {}
340            ResolveBehavior::V3 => {
341                if self.resolve_behavior == ResolveBehavior::V3 {
342                    self.resolve_honors_rust_version = true;
343                }
344            }
345        }
346        let config = self.gctx().get::<CargoResolverConfig>("resolver")?;
347        if let Some(incompatible_rust_versions) = config.incompatible_rust_versions {
348            self.resolve_honors_rust_version =
349                incompatible_rust_versions == IncompatibleRustVersions::Fallback;
350        }
351        if self.gctx().cli_unstable().feature_unification {
352            self.resolve_feature_unification = config
353                .feature_unification
354                .unwrap_or(FeatureUnification::Selected);
355        } else if config.feature_unification.is_some() {
356            self.gctx()
357                .shell()
358                .warn("ignoring `resolver.feature-unification` without `-Zfeature-unification`")?;
359        };
360
361        if let Some(lockfile_path) = config.lockfile_path {
362            // Reserve the ability to add templates in the future.
363            let replacements: [(&str, &str); 0] = [];
364            let path = lockfile_path
365                    .resolve_templated_path(self.gctx(), replacements)
366                    .map_err(|e| match e {
367                        context::ResolveTemplateError::UnexpectedVariable {
368                            variable,
369                            raw_template,
370                        } => {
371                            anyhow!(
372                                "unexpected variable `{variable}` in resolver.lockfile-path `{raw_template}`"
373                            )
374                        }
375                        context::ResolveTemplateError::UnexpectedBracket { bracket_type, raw_template } => {
376                            let (btype, literal) = match bracket_type {
377                                context::BracketType::Opening => ("opening", "{"),
378                                context::BracketType::Closing => ("closing", "}"),
379                            };
380
381                            anyhow!(
382                                "unexpected {btype} bracket `{literal}` in build.build-dir path `{raw_template}`"
383                            )
384                        }
385                    })?;
386            if !path.ends_with(LOCKFILE_NAME) {
387                bail!("the `resolver.lockfile-path` must be a path to a {LOCKFILE_NAME} file");
388            }
389            if path.is_dir() {
390                bail!(
391                    "`resolver.lockfile-path` `{}` is a directory but expected a file",
392                    path.display()
393                );
394            }
395            self.requested_lockfile_path = Some(path);
396        }
397
398        Ok(())
399    }
400
401    /// Returns the current package of this workspace.
402    ///
403    /// Note that this can return an error if it the current manifest is
404    /// actually a "virtual Cargo.toml", in which case an error is returned
405    /// indicating that something else should be passed.
406    pub fn current(&self) -> CargoResult<&Package> {
407        let pkg = self.current_opt().ok_or_else(|| {
408            anyhow::format_err!(
409                "manifest path `{}` is a virtual manifest, but this \
410                 command requires running against an actual package in \
411                 this workspace",
412                self.current_manifest.display()
413            )
414        })?;
415        Ok(pkg)
416    }
417
418    pub fn current_mut(&mut self) -> CargoResult<&mut Package> {
419        let cm = self.current_manifest.clone();
420        let pkg = self.current_opt_mut().ok_or_else(|| {
421            anyhow::format_err!(
422                "manifest path `{}` is a virtual manifest, but this \
423                 command requires running against an actual package in \
424                 this workspace",
425                cm.display()
426            )
427        })?;
428        Ok(pkg)
429    }
430
431    pub fn current_opt(&self) -> Option<&Package> {
432        match *self.packages.get(&self.current_manifest) {
433            MaybePackage::Package(ref p) => Some(p),
434            MaybePackage::Virtual(..) => None,
435        }
436    }
437
438    pub fn current_opt_mut(&mut self) -> Option<&mut Package> {
439        match *self.packages.get_mut(&self.current_manifest) {
440            MaybePackage::Package(ref mut p) => Some(p),
441            MaybePackage::Virtual(..) => None,
442        }
443    }
444
445    pub fn is_virtual(&self) -> bool {
446        match *self.packages.get(&self.current_manifest) {
447            MaybePackage::Package(..) => false,
448            MaybePackage::Virtual(..) => true,
449        }
450    }
451
452    /// Returns the `GlobalContext` this workspace is associated with.
453    pub fn gctx(&self) -> &'gctx GlobalContext {
454        self.gctx
455    }
456
457    pub fn profiles(&self) -> Option<&TomlProfiles> {
458        self.root_maybe().profiles()
459    }
460
461    /// Returns the root path of this workspace.
462    ///
463    /// That is, this returns the path of the directory containing the
464    /// `Cargo.toml` which is the root of this workspace.
465    pub fn root(&self) -> &Path {
466        self.root_manifest().parent().unwrap()
467    }
468
469    /// Returns the path of the `Cargo.toml` which is the root of this
470    /// workspace.
471    pub fn root_manifest(&self) -> &Path {
472        self.root_manifest
473            .as_ref()
474            .unwrap_or(&self.current_manifest)
475    }
476
477    /// Returns the root Package or `VirtualManifest`.
478    pub fn root_maybe(&self) -> &MaybePackage {
479        self.packages.get(self.root_manifest())
480    }
481
482    pub fn target_dir(&self) -> Filesystem {
483        self.target_dir
484            .clone()
485            .unwrap_or_else(|| self.default_target_dir())
486    }
487
488    pub fn build_dir(&self) -> Filesystem {
489        self.build_dir
490            .clone()
491            .or_else(|| self.target_dir.clone())
492            .unwrap_or_else(|| self.default_build_dir())
493    }
494
495    fn default_target_dir(&self) -> Filesystem {
496        if self.root_maybe().is_embedded() {
497            self.build_dir().join("target")
498        } else {
499            Filesystem::new(self.root().join("target"))
500        }
501    }
502
503    fn default_build_dir(&self) -> Filesystem {
504        if self.root_maybe().is_embedded() {
505            let default = ConfigRelativePath::new(
506                "{cargo-cache-home}/build/{workspace-path-hash}"
507                    .to_owned()
508                    .into(),
509            );
510            self.gctx()
511                .custom_build_dir(&default, self.root_manifest())
512                .expect("template is correct")
513        } else {
514            self.default_target_dir()
515        }
516    }
517
518    /// Returns the root `[replace]` section of this workspace.
519    ///
520    /// This may be from a virtual crate or an actual crate.
521    pub fn root_replace(&self) -> &[(PackageIdSpec, Dependency)] {
522        match self.root_maybe() {
523            MaybePackage::Package(p) => p.manifest().replace(),
524            MaybePackage::Virtual(vm) => vm.replace(),
525        }
526    }
527
528    fn config_patch(&self) -> CargoResult<HashMap<Url, Vec<Patch>>> {
529        let config_patch: Option<
530            BTreeMap<String, BTreeMap<String, Value<TomlDependency<ConfigRelativePath>>>>,
531        > = self.gctx.get("patch")?;
532
533        let source = SourceId::for_manifest_path(self.root_manifest())?;
534
535        let mut warnings = Vec::new();
536
537        let mut patch = HashMap::default();
538        for (url, deps) in config_patch.into_iter().flatten() {
539            let url = match &url[..] {
540                CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
541                url => self
542                    .gctx
543                    .get_registry_index(url)
544                    .or_else(|_| url.into_url())
545                    .with_context(|| {
546                        format!("[patch] entry `{}` should be a URL or registry name", url)
547                    })?,
548            };
549            patch.insert(
550                url,
551                deps.iter()
552                    .map(|(name, dependency_cv)| {
553                        crate::workspace::parser::config_patch_to_dependency(
554                            &dependency_cv.val,
555                            name,
556                            source,
557                            self.gctx,
558                            &mut warnings,
559                        )
560                        .map(|dep| Patch {
561                            dep,
562                            loc: PatchLocation::Config(dependency_cv.definition.clone()),
563                        })
564                    })
565                    .collect::<CargoResult<Vec<_>>>()?,
566            );
567        }
568
569        for message in warnings {
570            self.gctx
571                .shell()
572                .warn(format!("[patch] in cargo config: {}", message))?
573        }
574
575        Ok(patch)
576    }
577
578    /// Returns the root `[patch]` section of this workspace.
579    ///
580    /// This may be from a virtual crate or an actual crate.
581    pub fn root_patch(&self) -> CargoResult<HashMap<Url, Vec<Patch>>> {
582        let from_manifest = match self.root_maybe() {
583            MaybePackage::Package(p) => p.manifest().patch(),
584            MaybePackage::Virtual(vm) => vm.patch(),
585        };
586
587        let from_config = self.config_patch()?;
588        if from_config.is_empty() {
589            return Ok(from_manifest.clone());
590        }
591        if from_manifest.is_empty() {
592            return Ok(from_config);
593        }
594
595        // We could just chain from_manifest and from_config,
596        // but that's not quite right as it won't deal with overlaps.
597        let mut combined = from_config;
598        for (url, deps_from_manifest) in from_manifest {
599            if let Some(deps_from_config) = combined.get_mut(url) {
600                // We want from_config to take precedence for each patched name.
601                // NOTE: This is inefficient if the number of patches is large!
602                let mut from_manifest_pruned = deps_from_manifest.clone();
603                for dep_from_config in &mut *deps_from_config {
604                    if let Some(i) = from_manifest_pruned.iter().position(|dep_from_manifest| {
605                        // XXX: should this also take into account version numbers?
606                        dep_from_config.dep.name_in_toml() == dep_from_manifest.dep.name_in_toml()
607                    }) {
608                        from_manifest_pruned.swap_remove(i);
609                    }
610                }
611                // Whatever is left does not exist in manifest dependencies.
612                deps_from_config.extend(from_manifest_pruned);
613            } else {
614                combined.insert(url.clone(), deps_from_manifest.clone());
615            }
616        }
617        Ok(combined)
618    }
619
620    /// Returns an iterator over all loaded manifests
621    pub fn loaded_maybe(&self) -> impl Iterator<Item = &MaybePackage> {
622        self.packages.packages.values()
623    }
624
625    /// Returns an iterator over all packages in this workspace
626    pub fn members(&self) -> impl Iterator<Item = &Package> {
627        let packages = &self.packages;
628        self.members
629            .iter()
630            .filter_map(move |path| match packages.get(path) {
631                MaybePackage::Package(p) => Some(p),
632                _ => None,
633            })
634    }
635
636    /// Returns a mutable iterator over all packages in this workspace
637    pub fn members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
638        let packages = &mut self.packages.packages;
639        let members: HashSet<_> = self.members.iter().map(|path| path).collect();
640
641        packages.iter_mut().filter_map(move |(path, package)| {
642            if members.contains(path) {
643                if let MaybePackage::Package(p) = package {
644                    return Some(p);
645                }
646            }
647
648            None
649        })
650    }
651
652    /// Returns an iterator over default packages in this workspace
653    pub fn default_members<'a>(&'a self) -> impl Iterator<Item = &'a Package> {
654        let packages = &self.packages;
655        self.default_members
656            .iter()
657            .filter_map(move |path| match packages.get(path) {
658                MaybePackage::Package(p) => Some(p),
659                _ => None,
660            })
661    }
662
663    /// Returns an iterator over default packages in this workspace
664    pub fn default_members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
665        let packages = &mut self.packages.packages;
666        let members: HashSet<_> = self
667            .default_members
668            .iter()
669            .map(|path| path.parent().unwrap().to_owned())
670            .collect();
671
672        packages.iter_mut().filter_map(move |(path, package)| {
673            if members.contains(path) {
674                if let MaybePackage::Package(p) = package {
675                    return Some(p);
676                }
677            }
678
679            None
680        })
681    }
682
683    /// Returns true if the package is a member of the workspace.
684    pub fn is_member(&self, pkg: &Package) -> bool {
685        self.member_ids.contains(&pkg.package_id())
686    }
687
688    /// Returns true if the given package_id is a member of the workspace.
689    pub fn is_member_id(&self, package_id: PackageId) -> bool {
690        self.member_ids.contains(&package_id)
691    }
692
693    pub fn is_ephemeral(&self) -> bool {
694        self.is_ephemeral
695    }
696
697    pub fn require_optional_deps(&self) -> bool {
698        self.require_optional_deps
699    }
700
701    pub fn set_require_optional_deps(
702        &mut self,
703        require_optional_deps: bool,
704    ) -> &mut Workspace<'gctx> {
705        self.require_optional_deps = require_optional_deps;
706        self
707    }
708
709    pub fn ignore_lock(&self) -> bool {
710        self.ignore_lock
711    }
712
713    pub fn set_ignore_lock(&mut self, ignore_lock: bool) -> &mut Workspace<'gctx> {
714        self.ignore_lock = ignore_lock;
715        self
716    }
717
718    /// Returns the directory where the lockfile is in.
719    pub fn lock_root(&self) -> Filesystem {
720        if let Some(requested) = self.requested_lockfile_path.as_ref() {
721            return Filesystem::new(
722                requested
723                    .parent()
724                    .expect("Lockfile path can't be root")
725                    .to_owned(),
726            );
727        }
728        self.default_lock_root()
729    }
730
731    fn default_lock_root(&self) -> Filesystem {
732        if self.root_maybe().is_embedded() {
733            // Include a workspace hash in case the user requests a shared build-dir so that
734            // scripts don't fight over the `Cargo.lock` content
735            let workspace_manifest_path = self.root_manifest();
736            let real_path = std::fs::canonicalize(workspace_manifest_path)
737                .unwrap_or_else(|_err| workspace_manifest_path.to_owned());
738            let hash = crate::util::hex::short_hash(&real_path);
739            self.build_dir().join(hash)
740        } else {
741            Filesystem::new(self.root().to_owned())
742        }
743    }
744
745    // NOTE: may be removed once the deprecated `--lockfile-path` CLI flag is removed
746    pub fn set_requested_lockfile_path(&mut self, path: Option<PathBuf>) {
747        self.requested_lockfile_path = path;
748    }
749
750    pub fn requested_lockfile_path(&self) -> Option<&Path> {
751        self.requested_lockfile_path.as_deref()
752    }
753
754    /// Get the lowest-common denominator `package.rust-version` within the workspace, if specified
755    /// anywhere
756    pub fn lowest_rust_version(&self) -> Option<&RustVersion> {
757        self.members().filter_map(|pkg| pkg.rust_version()).min()
758    }
759
760    pub fn set_resolve_honors_rust_version(&mut self, honor_rust_version: Option<bool>) {
761        if let Some(honor_rust_version) = honor_rust_version {
762            self.resolve_honors_rust_version = honor_rust_version;
763        }
764    }
765
766    pub fn resolve_honors_rust_version(&self) -> bool {
767        self.resolve_honors_rust_version
768    }
769
770    pub fn set_resolve_honors_publish_age(&mut self, honor_publish_age: bool) {
771        self.resolve_honors_publish_age = honor_publish_age;
772    }
773
774    pub fn resolve_honors_publish_age(&self) -> bool {
775        self.resolve_honors_publish_age
776    }
777
778    pub fn set_resolve_feature_unification(&mut self, feature_unification: FeatureUnification) {
779        self.resolve_feature_unification = feature_unification;
780    }
781
782    pub fn resolve_feature_unification(&self) -> FeatureUnification {
783        self.resolve_feature_unification
784    }
785
786    pub fn set_resolve_publish_time(&mut self, publish_time: jiff::Timestamp) {
787        self.resolve_publish_time = Some(publish_time);
788    }
789
790    pub fn resolve_publish_time(&self) -> Option<jiff::Timestamp> {
791        self.resolve_publish_time
792    }
793
794    pub fn custom_metadata(&self) -> Option<&toml::Value> {
795        self.custom_metadata.as_ref()
796    }
797
798    pub fn load_workspace_config(&mut self) -> CargoResult<Option<WorkspaceRootConfig>> {
799        // If we didn't find a root, it must mean there is no [workspace] section, and thus no
800        // metadata.
801        if let Some(root_path) = &self.root_manifest {
802            let root_package = self.packages.load(root_path)?;
803            match root_package.workspace_config() {
804                WorkspaceConfig::Root(root_config) => {
805                    return Ok(Some(root_config.clone()));
806                }
807
808                _ => bail!(
809                    "root of a workspace inferred but wasn't a root: {}",
810                    root_path.display()
811                ),
812            }
813        }
814
815        Ok(None)
816    }
817
818    /// Finds the root of a workspace for the crate whose manifest is located
819    /// at `manifest_path`.
820    ///
821    /// This will parse the `Cargo.toml` at `manifest_path` and then interpret
822    /// the workspace configuration, optionally walking up the filesystem
823    /// looking for other workspace roots.
824    ///
825    /// Returns an error if `manifest_path` isn't actually a valid manifest or
826    /// if some other transient error happens.
827    fn find_root(&mut self, manifest_path: &Path) -> CargoResult<Option<PathBuf>> {
828        let current = self.packages.load(manifest_path)?;
829        match current
830            .workspace_config()
831            .get_ws_root(manifest_path, manifest_path)
832        {
833            Some(root_path) => {
834                debug!("find_root - is root {}", manifest_path.display());
835                Ok(Some(root_path))
836            }
837            None => find_workspace_root_with_loader(manifest_path, self.gctx, |self_path| {
838                Ok(self
839                    .packages
840                    .load(self_path)?
841                    .workspace_config()
842                    .get_ws_root(self_path, manifest_path))
843            }),
844        }
845    }
846
847    /// After the root of a workspace has been located, probes for all members
848    /// of a workspace.
849    ///
850    /// If the `workspace.members` configuration is present, then this just
851    /// verifies that those are all valid packages to point to. Otherwise, this
852    /// will transitively follow all `path` dependencies looking for members of
853    /// the workspace.
854    #[tracing::instrument(skip_all)]
855    fn find_members(&mut self) -> CargoResult<()> {
856        let Some(workspace_config) = self.load_workspace_config()? else {
857            debug!("find_members - only me as a member");
858            self.members.insert(self.current_manifest.clone());
859            self.default_members.push(self.current_manifest.clone());
860            if let Ok(pkg) = self.current() {
861                let id = pkg.package_id();
862                self.member_ids.insert(id);
863            }
864            return Ok(());
865        };
866
867        // self.root_manifest must be Some to have retrieved workspace_config
868        let root_manifest_path = self.root_manifest.clone().unwrap();
869
870        let members_paths = workspace_config
871            .members_paths(workspace_config.members.as_deref().unwrap_or_default())?;
872        let default_members_paths = if root_manifest_path == self.current_manifest {
873            if let Some(ref default) = workspace_config.default_members {
874                Some(workspace_config.members_paths(default)?)
875            } else {
876                None
877            }
878        } else {
879            None
880        };
881
882        for (path, glob) in &members_paths {
883            self.find_path_deps(&path.join("Cargo.toml"), &root_manifest_path, false)
884                .with_context(|| {
885                    format!(
886                        "failed to load manifest for workspace member `{}`\n\
887                        referenced{} by workspace at `{}`",
888                        path.display(),
889                        glob.map(|g| format!(" via `{g}`")).unwrap_or_default(),
890                        root_manifest_path.display(),
891                    )
892                })?;
893        }
894
895        self.find_path_deps(&root_manifest_path, &root_manifest_path, false)?;
896
897        if let Some(default) = default_members_paths {
898            for (path, default_member_glob) in default {
899                let normalized_path = paths::normalize_path(&path);
900                let manifest_path = normalized_path.join("Cargo.toml");
901                if !self.members.contains(&manifest_path) {
902                    // default-members are allowed to be excluded, but they
903                    // still must be referred to by the original (unfiltered)
904                    // members list. Note that we aren't testing against the
905                    // manifest path, both because `members_paths` doesn't
906                    // include `/Cargo.toml`, and because excluded paths may not
907                    // be crates.
908                    let exclude = members_paths.iter().any(|(m, _)| *m == normalized_path)
909                        && workspace_config.is_excluded(&normalized_path);
910                    if exclude {
911                        continue;
912                    }
913                    bail!(
914                        "package `{}` is listed in default-members{} but is not a member\n\
915                        for workspace at `{}`.",
916                        path.display(),
917                        default_member_glob
918                            .map(|g| format!(" via `{g}`"))
919                            .unwrap_or_default(),
920                        root_manifest_path.display(),
921                    )
922                }
923                self.default_members.push(manifest_path)
924            }
925        } else if self.is_virtual() {
926            self.default_members = self.members.iter().cloned().collect();
927        } else {
928            self.default_members.push(self.current_manifest.clone())
929        }
930
931        Ok(())
932    }
933
934    fn find_path_deps(
935        &mut self,
936        manifest_path: &Path,
937        root_manifest: &Path,
938        is_path_dep: bool,
939    ) -> CargoResult<()> {
940        let manifest_path = paths::normalize_path(manifest_path);
941        if self.members.contains(&manifest_path) {
942            return Ok(());
943        }
944        if is_path_dep && self.root_maybe().is_embedded() {
945            // Embedded manifests cannot have workspace members
946            return Ok(());
947        }
948        if is_path_dep
949            && !manifest_path.parent().unwrap().starts_with(self.root())
950            && self.find_root(&manifest_path)? != self.root_manifest
951        {
952            // If `manifest_path` is a path dependency outside of the workspace,
953            // don't add it, or any of its dependencies, as a members.
954            return Ok(());
955        }
956
957        if let WorkspaceConfig::Root(ref root_config) =
958            *self.packages.load(root_manifest)?.workspace_config()
959        {
960            if root_config.is_excluded(&manifest_path) {
961                return Ok(());
962            }
963        }
964
965        debug!("find_path_deps - {}", manifest_path.display());
966        self.members.insert(manifest_path.clone());
967
968        let candidates = {
969            let pkg = match *self.packages.load(&manifest_path)? {
970                MaybePackage::Package(ref p) => p,
971                MaybePackage::Virtual(_) => return Ok(()),
972            };
973            self.member_ids.insert(pkg.package_id());
974            pkg.dependencies()
975                .iter()
976                .map(|d| (d.source_id(), d.package_name()))
977                .filter(|(s, _)| s.is_path())
978                .filter_map(|(s, n)| s.url().to_file_path().ok().map(|p| (p, n)))
979                .map(|(p, n)| (p.join("Cargo.toml"), n))
980                .collect::<Vec<_>>()
981        };
982        for (path, name) in candidates {
983            self.find_path_deps(&path, root_manifest, true)
984                .with_context(|| format!("failed to load manifest for dependency `{}`", name))
985                .map_err(|err| ManifestError::new(err, manifest_path.clone()))?;
986        }
987        Ok(())
988    }
989
990    /// Returns the unstable nightly-only features enabled via `cargo-features` in the manifest.
991    pub fn unstable_features(&self) -> &Features {
992        self.root_maybe().unstable_features()
993    }
994
995    pub fn resolve_behavior(&self) -> ResolveBehavior {
996        self.resolve_behavior
997    }
998
999    /// Returns `true` if this workspace uses the new CLI features behavior.
1000    ///
1001    /// The old behavior only allowed choosing the features from the package
1002    /// in the current directory, regardless of which packages were chosen
1003    /// with the -p flags. The new behavior allows selecting features from the
1004    /// packages chosen on the command line (with -p or --workspace flags),
1005    /// ignoring whatever is in the current directory.
1006    pub fn allows_new_cli_feature_behavior(&self) -> bool {
1007        self.is_virtual()
1008            || match self.resolve_behavior() {
1009                ResolveBehavior::V1 => false,
1010                ResolveBehavior::V2 | ResolveBehavior::V3 => true,
1011            }
1012    }
1013
1014    /// Validates a workspace, ensuring that a number of invariants are upheld:
1015    ///
1016    /// 1. A workspace only has one root.
1017    /// 2. All workspace members agree on this one root as the root.
1018    /// 3. The current crate is a member of this workspace.
1019    #[tracing::instrument(skip_all)]
1020    fn validate(&mut self) -> CargoResult<()> {
1021        // The rest of the checks require a VirtualManifest or multiple members.
1022        if self.root_manifest.is_none() {
1023            return Ok(());
1024        }
1025
1026        self.validate_unique_names()?;
1027        self.validate_workspace_roots()?;
1028        self.validate_members()?;
1029        self.error_if_manifest_not_in_members()?;
1030        self.validate_manifest()
1031    }
1032
1033    fn validate_unique_names(&self) -> CargoResult<()> {
1034        let mut names = BTreeMap::new();
1035        for member in self.members.iter() {
1036            let package = self.packages.get(member);
1037            let name = match *package {
1038                MaybePackage::Package(ref p) => p.name(),
1039                MaybePackage::Virtual(_) => continue,
1040            };
1041            if let Some(prev) = names.insert(name, member) {
1042                bail!(
1043                    "two packages named `{}` in this workspace:\n\
1044                         - {}\n\
1045                         - {}",
1046                    name,
1047                    prev.display(),
1048                    member.display()
1049                );
1050            }
1051        }
1052        Ok(())
1053    }
1054
1055    fn validate_workspace_roots(&self) -> CargoResult<()> {
1056        let roots: Vec<PathBuf> = self
1057            .members
1058            .iter()
1059            .filter(|&member| {
1060                let config = self.packages.get(member).workspace_config();
1061                matches!(config, WorkspaceConfig::Root(_))
1062            })
1063            .map(|member| member.parent().unwrap().to_path_buf())
1064            .collect();
1065        match roots.len() {
1066            1 => Ok(()),
1067            0 => bail!(
1068                "`package.workspace` configuration points to a crate \
1069                 which is not configured with [workspace]: \n\
1070                 configuration at: {}\n\
1071                 points to: {}",
1072                self.current_manifest.display(),
1073                self.root_manifest.as_ref().unwrap().display()
1074            ),
1075            _ => {
1076                bail!(
1077                    "multiple workspace roots found in the same workspace:\n{}",
1078                    roots
1079                        .iter()
1080                        .map(|r| format!("  {}", r.display()))
1081                        .collect::<Vec<_>>()
1082                        .join("\n")
1083                );
1084            }
1085        }
1086    }
1087
1088    #[tracing::instrument(skip_all)]
1089    fn validate_members(&mut self) -> CargoResult<()> {
1090        for member in self.members.clone() {
1091            let root = self.find_root(&member)?;
1092            if root == self.root_manifest {
1093                continue;
1094            }
1095
1096            match root {
1097                Some(root) => {
1098                    bail!(
1099                        "package `{}` is a member of the wrong workspace\n\
1100                         expected: {}\n\
1101                         actual:   {}",
1102                        member.display(),
1103                        self.root_manifest.as_ref().unwrap().display(),
1104                        root.display()
1105                    );
1106                }
1107                None => {
1108                    bail!(
1109                        "workspace member `{}` is not hierarchically below \
1110                         the workspace root `{}`",
1111                        member.display(),
1112                        self.root_manifest.as_ref().unwrap().display()
1113                    );
1114                }
1115            }
1116        }
1117        Ok(())
1118    }
1119
1120    fn error_if_manifest_not_in_members(&mut self) -> CargoResult<()> {
1121        if self.members.contains(&self.current_manifest) {
1122            return Ok(());
1123        }
1124
1125        let root = self.root_manifest.as_ref().unwrap();
1126        let root_dir = root.parent().unwrap();
1127        let current_dir = self.current_manifest.parent().unwrap();
1128        let root_pkg = self.packages.get(root);
1129
1130        // Use pathdiff to handle finding the relative path between the current package
1131        // and the workspace root. This usually does a good job of handling `..` and
1132        // other weird things.
1133        // Normalize paths first to ensure `../` components are resolved if possible,
1134        // which helps `diff_paths` find the most direct relative path.
1135        let current_dir = paths::normalize_path(current_dir);
1136        let root_dir = paths::normalize_path(root_dir);
1137        let members_msg = match pathdiff::diff_paths(&current_dir, &root_dir) {
1138            Some(rel) => format!(
1139                "this may be fixable by adding `{}` to the \
1140                     `workspace.members` array of the manifest \
1141                     located at: {}",
1142                rel.display(),
1143                root.display()
1144            ),
1145            None => format!(
1146                "this may be fixable by adding a member to \
1147                     the `workspace.members` array of the \
1148                     manifest located at: {}",
1149                root.display()
1150            ),
1151        };
1152        let extra = match *root_pkg {
1153            MaybePackage::Virtual(_) => members_msg,
1154            MaybePackage::Package(ref p) => {
1155                let has_members_list = match *p.manifest().workspace_config() {
1156                    WorkspaceConfig::Root(ref root_config) => root_config.has_members_list(),
1157                    WorkspaceConfig::Member { .. } => unreachable!(),
1158                };
1159                if !has_members_list {
1160                    format!(
1161                        "this may be fixable by ensuring that this \
1162                             crate is depended on by the workspace \
1163                             root: {}",
1164                        root.display()
1165                    )
1166                } else {
1167                    members_msg
1168                }
1169            }
1170        };
1171        bail!(
1172            "current package believes it's in a workspace when it's not:\n\
1173                 current:   {}\n\
1174                 workspace: {}\n\n{}\n\
1175                 Alternatively, to keep it out of the workspace, add the package \
1176                 to the `workspace.exclude` array, or add an empty `[workspace]` \
1177                 table to the package's manifest.",
1178            self.current_manifest.display(),
1179            root.display(),
1180            extra
1181        );
1182    }
1183
1184    fn validate_manifest(&mut self) -> CargoResult<()> {
1185        if let Some(ref root_manifest) = self.root_manifest {
1186            for pkg in self
1187                .members()
1188                .filter(|p| p.manifest_path() != root_manifest)
1189            {
1190                let manifest = pkg.manifest();
1191                let emit_warning = |what| -> CargoResult<()> {
1192                    let msg = format!(
1193                        "{} for the non root package will be ignored, \
1194                         specify {} at the workspace root:\n\
1195                         package:   {}\n\
1196                         workspace: {}",
1197                        what,
1198                        what,
1199                        pkg.manifest_path().display(),
1200                        root_manifest.display(),
1201                    );
1202                    self.gctx.shell().warn(&msg)
1203                };
1204                if manifest.normalized_toml().has_profiles() {
1205                    emit_warning("profiles")?;
1206                }
1207                if !manifest.replace().is_empty() {
1208                    emit_warning("replace")?;
1209                }
1210                if !manifest.patch().is_empty() {
1211                    emit_warning("patch")?;
1212                }
1213                if let Some(behavior) = manifest.resolve_behavior() {
1214                    if behavior != self.resolve_behavior {
1215                        // Only warn if they don't match.
1216                        emit_warning("resolver")?;
1217                    }
1218                }
1219            }
1220            if let MaybePackage::Virtual(vm) = self.root_maybe() {
1221                if vm.resolve_behavior().is_none() {
1222                    if let Some(edition) = self
1223                        .members()
1224                        .filter(|p| p.manifest_path() != root_manifest)
1225                        .map(|p| p.manifest().edition())
1226                        .filter(|&e| e >= Edition::Edition2021)
1227                        .max()
1228                    {
1229                        let resolver = edition.default_resolve_behavior().to_manifest();
1230                        let report = &[Level::WARNING
1231                            .primary_title(format!(
1232                                "virtual workspace defaulting to `resolver = \"1\"` despite one or more workspace members being on edition {edition} which implies `resolver = \"{resolver}\"`"
1233                            ))
1234                            .elements([
1235                                Level::NOTE.message("to keep the current resolver, specify `workspace.resolver = \"1\"` in the workspace root's manifest"),
1236                                Level::NOTE.message(
1237                                    format!("to use the edition {edition} resolver, specify `workspace.resolver = \"{resolver}\"` in the workspace root's manifest"),
1238                                ),
1239                                Level::NOTE.message("for more details see https://doc.rust-lang.org/cargo/reference/resolver.html#resolver-versions"),
1240                            ])];
1241                        self.gctx.shell().print_report(report, false)?;
1242                    }
1243                }
1244            }
1245        }
1246        Ok(())
1247    }
1248
1249    pub fn load(&self, manifest_path: &Path) -> CargoResult<Package> {
1250        match self.packages.maybe_get(manifest_path) {
1251            Some(MaybePackage::Package(p)) => return Ok(p.clone()),
1252            Some(&MaybePackage::Virtual(_)) => bail!("cannot load workspace root"),
1253            None => {}
1254        }
1255
1256        let mut loaded = self.loaded_packages.borrow_mut();
1257        if let Some(p) = loaded.get(manifest_path).cloned() {
1258            return Ok(p);
1259        }
1260        let source_id = SourceId::for_manifest_path(manifest_path)?;
1261        let package = ops::read_package(manifest_path, source_id, self.gctx)?;
1262        loaded.insert(manifest_path.to_path_buf(), package.clone());
1263        Ok(package)
1264    }
1265
1266    /// Preload the provided registry with already loaded packages.
1267    ///
1268    /// A workspace may load packages during construction/parsing/early phases
1269    /// for various operations, and this preload step avoids doubly-loading and
1270    /// parsing crates on the filesystem by inserting them all into the registry
1271    /// with their in-memory formats.
1272    pub fn preload(&self, registry: &mut PackageRegistry<'gctx>) {
1273        // These can get weird as this generally represents a workspace during
1274        // `cargo install`. Things like git repositories will actually have a
1275        // `PathSource` with multiple entries in it, so the logic below is
1276        // mostly just an optimization for normal `cargo build` in workspaces
1277        // during development.
1278        if self.is_ephemeral {
1279            return;
1280        }
1281
1282        for pkg in self.packages.packages.values() {
1283            let pkg = match *pkg {
1284                MaybePackage::Package(ref p) => p.clone(),
1285                MaybePackage::Virtual(_) => continue,
1286            };
1287            let src = PathSource::preload_with(pkg, self.gctx);
1288            registry.add_preloaded(Box::new(src));
1289        }
1290    }
1291
1292    pub fn set_target_dir(&mut self, target_dir: Filesystem) {
1293        self.target_dir = Some(target_dir);
1294    }
1295
1296    /// Returns a Vec of `(&Package, CliFeatures)` tuples that
1297    /// represent the workspace members that were requested on the command-line.
1298    ///
1299    /// `specs` may be empty, which indicates it should return all workspace
1300    /// members. In this case, `requested_features.all_features` must be
1301    /// `true`. This is used for generating `Cargo.lock`, which must include
1302    /// all members with all features enabled.
1303    pub fn members_with_features(
1304        &self,
1305        specs: &[PackageIdSpec],
1306        cli_features: &CliFeatures,
1307    ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1308        assert!(
1309            !specs.is_empty() || cli_features.all_features,
1310            "no specs requires all_features"
1311        );
1312        if specs.is_empty() {
1313            // When resolving the entire workspace, resolve each member with
1314            // all features enabled.
1315            return Ok(self
1316                .members()
1317                .map(|m| (m, CliFeatures::new_all(true)))
1318                .collect());
1319        }
1320        if self.allows_new_cli_feature_behavior() {
1321            self.members_with_features_new(specs, cli_features)
1322        } else {
1323            Ok(self.members_with_features_old(specs, cli_features))
1324        }
1325    }
1326
1327    /// Returns the requested features for the given member.
1328    /// This filters out any named features that the member does not have.
1329    fn collect_matching_features(
1330        member: &Package,
1331        cli_features: &CliFeatures,
1332        found_features: &mut BTreeSet<FeatureValue>,
1333    ) -> CliFeatures {
1334        if cli_features.features.is_empty() {
1335            return cli_features.clone();
1336        }
1337
1338        // Only include features this member defines.
1339        let summary = member.summary();
1340
1341        // Features defined in the manifest
1342        let summary_features = summary.features();
1343
1344        // Dependency name -> dependency
1345        let dependencies: BTreeMap<InternedString, &Dependency> = summary
1346            .dependencies()
1347            .iter()
1348            .map(|dep| (dep.name_in_toml(), dep))
1349            .collect();
1350
1351        // Features that enable optional dependencies
1352        let optional_dependency_names: BTreeSet<_> = dependencies
1353            .iter()
1354            .filter(|(_, dep)| dep.is_optional())
1355            .map(|(name, _)| name)
1356            .copied()
1357            .collect();
1358
1359        let mut features = BTreeSet::new();
1360
1361        // Checks if a member contains the given feature.
1362        let summary_or_opt_dependency_feature = |feature: &InternedString| -> bool {
1363            summary_features.contains_key(feature) || optional_dependency_names.contains(feature)
1364        };
1365
1366        for feature in cli_features.features.iter() {
1367            match feature {
1368                FeatureValue::Feature(f) => {
1369                    if summary_or_opt_dependency_feature(f) {
1370                        // feature exists in this member.
1371                        features.insert(feature.clone());
1372                        found_features.insert(feature.clone());
1373                    }
1374                }
1375                // This should be enforced by CliFeatures.
1376                FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1377                FeatureValue::DepFeature {
1378                    dep_name,
1379                    dep_feature,
1380                    weak: _,
1381                } => {
1382                    if dependencies.contains_key(dep_name) {
1383                        // pkg/feat for a dependency.
1384                        // Will rely on the dependency resolver to validate `dep_feature`.
1385                        features.insert(feature.clone());
1386                        found_features.insert(feature.clone());
1387                    } else if *dep_name == member.name()
1388                        && summary_or_opt_dependency_feature(dep_feature)
1389                    {
1390                        // member/feat where "feat" is a feature in member.
1391                        //
1392                        // `weak` can be ignored here, because the member
1393                        // either is or isn't being built.
1394                        features.insert(FeatureValue::Feature(*dep_feature));
1395                        found_features.insert(feature.clone());
1396                    }
1397                }
1398            }
1399        }
1400        CliFeatures {
1401            features: Rc::new(features),
1402            all_features: cli_features.all_features,
1403            uses_default_features: cli_features.uses_default_features,
1404        }
1405    }
1406
1407    fn missing_feature_spelling_suggestions(
1408        &self,
1409        selected_members: &[&Package],
1410        cli_features: &CliFeatures,
1411        found_features: &BTreeSet<FeatureValue>,
1412    ) -> Vec<String> {
1413        // Keeps track of which features were contained in summary of `member` to suggest similar features in errors
1414        let mut summary_features: Vec<InternedString> = Default::default();
1415
1416        // Keeps track of `member` dependencies (`dep/feature`) and their features names to suggest similar features in error
1417        let mut dependencies_features: BTreeMap<InternedString, &[InternedString]> =
1418            Default::default();
1419
1420        // Keeps track of `member` optional dependencies names (which can be enabled with feature) to suggest similar features in error
1421        let mut optional_dependency_names: Vec<InternedString> = Default::default();
1422
1423        // Keeps track of which features were contained in summary of `member` to suggest similar features in errors
1424        let mut summary_features_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1425            Default::default();
1426
1427        // Keeps track of `member` optional dependencies (which can be enabled with feature) to suggest similar features in error
1428        let mut optional_dependency_names_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1429            Default::default();
1430
1431        for &member in selected_members {
1432            // Only include features this member defines.
1433            let summary = member.summary();
1434
1435            // Features defined in the manifest
1436            summary_features.extend(summary.features().keys());
1437            summary_features_per_member
1438                .insert(member, summary.features().keys().copied().collect());
1439
1440            // Dependency name -> dependency
1441            let dependencies: BTreeMap<InternedString, &Dependency> = summary
1442                .dependencies()
1443                .iter()
1444                .map(|dep| (dep.name_in_toml(), dep))
1445                .collect();
1446
1447            dependencies_features.extend(
1448                dependencies
1449                    .iter()
1450                    .map(|(name, dep)| (*name, dep.features())),
1451            );
1452
1453            // Features that enable optional dependencies
1454            let optional_dependency_names_raw: BTreeSet<_> = dependencies
1455                .iter()
1456                .filter(|(_, dep)| dep.is_optional())
1457                .map(|(name, _)| name)
1458                .copied()
1459                .collect();
1460
1461            optional_dependency_names.extend(optional_dependency_names_raw.iter());
1462            optional_dependency_names_per_member.insert(member, optional_dependency_names_raw);
1463        }
1464
1465        let edit_distance_test = |a: InternedString, b: InternedString| {
1466            edit_distance(a.as_str(), b.as_str(), 3).is_some()
1467        };
1468
1469        cli_features
1470            .features
1471            .difference(found_features)
1472            .map(|feature| match feature {
1473                // Simple feature, check if any of the optional dependency features or member features are close enough
1474                FeatureValue::Feature(typo) => {
1475                    // Finds member features which are similar to the requested feature.
1476                    let summary_features = summary_features
1477                        .iter()
1478                        .filter(move |feature| edit_distance_test(**feature, *typo));
1479
1480                    // Finds optional dependencies which name is similar to the feature
1481                    let optional_dependency_features = optional_dependency_names
1482                        .iter()
1483                        .filter(move |feature| edit_distance_test(**feature, *typo));
1484
1485                    summary_features
1486                        .chain(optional_dependency_features)
1487                        .map(|s| s.to_string())
1488                        .collect::<Vec<_>>()
1489                }
1490                FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1491                FeatureValue::DepFeature {
1492                    dep_name,
1493                    dep_feature,
1494                    weak: _,
1495                } => {
1496                    // Finds set of `pkg/feat` that are very similar to current `pkg/feat`.
1497                    let pkg_feat_similar = dependencies_features
1498                        .iter()
1499                        .filter(|(name, _)| edit_distance_test(**name, *dep_name))
1500                        .map(|(name, features)| {
1501                            (
1502                                name,
1503                                features
1504                                    .iter()
1505                                    .filter(|feature| edit_distance_test(**feature, *dep_feature))
1506                                    .collect::<Vec<_>>(),
1507                            )
1508                        })
1509                        .map(|(name, features)| {
1510                            features
1511                                .into_iter()
1512                                .map(move |feature| format!("{}/{}", name, feature))
1513                        })
1514                        .flatten();
1515
1516                    // Finds set of `member/optional_dep` features which name is similar to current `pkg/feat`.
1517                    let optional_dependency_features = optional_dependency_names_per_member
1518                        .iter()
1519                        .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1520                        .map(|(package, optional_dependencies)| {
1521                            optional_dependencies
1522                                .into_iter()
1523                                .filter(|optional_dependency| {
1524                                    edit_distance_test(**optional_dependency, *dep_name)
1525                                })
1526                                .map(move |optional_dependency| {
1527                                    format!("{}/{}", package.name(), optional_dependency)
1528                                })
1529                        })
1530                        .flatten();
1531
1532                    // Finds set of `member/feat` features which name is similar to current `pkg/feat`.
1533                    let summary_features = summary_features_per_member
1534                        .iter()
1535                        .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1536                        .map(|(package, summary_features)| {
1537                            summary_features
1538                                .into_iter()
1539                                .filter(|summary_feature| {
1540                                    edit_distance_test(**summary_feature, *dep_feature)
1541                                })
1542                                .map(move |summary_feature| {
1543                                    format!("{}/{}", package.name(), summary_feature)
1544                                })
1545                        })
1546                        .flatten();
1547
1548                    pkg_feat_similar
1549                        .chain(optional_dependency_features)
1550                        .chain(summary_features)
1551                        .collect::<Vec<_>>()
1552                }
1553            })
1554            .map(|v| v.into_iter())
1555            .flatten()
1556            .unique()
1557            .filter(|element| {
1558                let feature = FeatureValue::new(element.into());
1559                !cli_features.features.contains(&feature) && !found_features.contains(&feature)
1560            })
1561            .sorted()
1562            .take(5)
1563            .collect()
1564    }
1565
1566    fn report_unknown_features_error(
1567        &self,
1568        specs: &[PackageIdSpec],
1569        cli_features: &CliFeatures,
1570        found_features: &BTreeSet<FeatureValue>,
1571    ) -> CargoResult<()> {
1572        let unknown: Vec<_> = cli_features
1573            .features
1574            .difference(found_features)
1575            .map(|feature| feature.to_string())
1576            .sorted()
1577            .collect();
1578
1579        let (selected_members, unselected_members): (Vec<_>, Vec<_>) = self
1580            .members()
1581            .partition(|member| specs.iter().any(|spec| spec.matches(member.package_id())));
1582
1583        let missing_packages_with_the_features = unselected_members
1584            .into_iter()
1585            .filter(|member| {
1586                unknown
1587                    .iter()
1588                    .any(|feature| member.summary().features().contains_key(&**feature))
1589            })
1590            .map(|m| m.name())
1591            .collect_vec();
1592
1593        let these_features = if unknown.len() == 1 {
1594            "this feature"
1595        } else {
1596            "these features"
1597        };
1598        let mut msg = if let [singular] = &selected_members[..] {
1599            format!(
1600                "the package '{}' does not contain {these_features}: {}",
1601                singular.name(),
1602                unknown.join(", ")
1603            )
1604        } else {
1605            let names = selected_members.iter().map(|m| m.name()).join(", ");
1606            format!(
1607                "none of the selected packages contains {these_features}: {}\nselected packages: {names}",
1608                unknown.join(", ")
1609            )
1610        };
1611
1612        use std::fmt::Write;
1613        if !missing_packages_with_the_features.is_empty() {
1614            write!(
1615                &mut msg,
1616                "\nhelp: package{} with the missing feature{}: {}",
1617                if missing_packages_with_the_features.len() != 1 {
1618                    "s"
1619                } else {
1620                    ""
1621                },
1622                if unknown.len() != 1 { "s" } else { "" },
1623                missing_packages_with_the_features.join(", ")
1624            )?;
1625        } else {
1626            let suggestions = self.missing_feature_spelling_suggestions(
1627                &selected_members,
1628                cli_features,
1629                found_features,
1630            );
1631            if !suggestions.is_empty() {
1632                write!(
1633                    &mut msg,
1634                    "\nhelp: there {}: {}",
1635                    if suggestions.len() == 1 {
1636                        "is a similarly named feature"
1637                    } else {
1638                        "are similarly named features"
1639                    },
1640                    suggestions.join(", ")
1641                )?;
1642            }
1643        }
1644
1645        bail!("{msg}")
1646    }
1647
1648    /// New command-line feature selection behavior with resolver = "2" or the
1649    /// root of a virtual workspace. See `allows_new_cli_feature_behavior`.
1650    fn members_with_features_new(
1651        &self,
1652        specs: &[PackageIdSpec],
1653        cli_features: &CliFeatures,
1654    ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1655        // Keeps track of which features matched `member` to produce an error
1656        // if any of them did not match anywhere.
1657        let mut found_features = Default::default();
1658
1659        let members: Vec<(&Package, CliFeatures)> = self
1660            .members()
1661            .filter(|m| specs.iter().any(|spec| spec.matches(m.package_id())))
1662            .map(|m| {
1663                (
1664                    m,
1665                    Workspace::collect_matching_features(m, cli_features, &mut found_features),
1666                )
1667            })
1668            .collect();
1669
1670        if members.is_empty() {
1671            // `cargo build -p foo`, where `foo` is not a member.
1672            // Do not allow any command-line flags (defaults only).
1673            if !(cli_features.features.is_empty()
1674                && !cli_features.all_features
1675                && cli_features.uses_default_features)
1676            {
1677                let hint = specs
1678                    .iter()
1679                    .map(|spec| {
1680                        closest_msg(
1681                            spec.name(),
1682                            self.members(),
1683                            |m| m.name().as_str(),
1684                            "workspace member",
1685                        )
1686                    })
1687                    .find(|msg| !msg.is_empty())
1688                    .unwrap_or_default();
1689                bail!("cannot specify features for packages outside of workspace{hint}");
1690            }
1691            // Add all members from the workspace so we can ensure `-p nonmember`
1692            // is in the resolve graph.
1693            return Ok(self
1694                .members()
1695                .map(|m| (m, CliFeatures::new_all(false)))
1696                .collect());
1697        }
1698        if *cli_features.features != found_features {
1699            self.report_unknown_features_error(specs, cli_features, &found_features)?;
1700        }
1701        Ok(members)
1702    }
1703
1704    /// This is the "old" behavior for command-line feature selection.
1705    /// See `allows_new_cli_feature_behavior`.
1706    fn members_with_features_old(
1707        &self,
1708        specs: &[PackageIdSpec],
1709        cli_features: &CliFeatures,
1710    ) -> Vec<(&Package, CliFeatures)> {
1711        // Split off any features with the syntax `member-name/feature-name` into a map
1712        // so that those features can be applied directly to those workspace-members.
1713        let mut member_specific_features: HashMap<InternedString, BTreeSet<FeatureValue>> =
1714            HashMap::default();
1715        // Features for the member in the current directory.
1716        let mut cwd_features = BTreeSet::new();
1717        for feature in cli_features.features.iter() {
1718            match feature {
1719                FeatureValue::Feature(_) => {
1720                    cwd_features.insert(feature.clone());
1721                }
1722                // This should be enforced by CliFeatures.
1723                FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1724                FeatureValue::DepFeature {
1725                    dep_name,
1726                    dep_feature,
1727                    weak: _,
1728                } => {
1729                    // I think weak can be ignored here.
1730                    // * With `--features member?/feat -p member`, the ? doesn't
1731                    //   really mean anything (either the member is built or it isn't).
1732                    // * With `--features nonmember?/feat`, cwd_features will
1733                    //   handle processing it correctly.
1734                    let is_member = self.members().any(|member| {
1735                        // Check if `dep_name` is member of the workspace, but isn't associated with current package.
1736                        self.current_opt() != Some(member) && member.name() == *dep_name
1737                    });
1738                    if is_member && specs.iter().any(|spec| spec.name() == dep_name.as_str()) {
1739                        member_specific_features
1740                            .entry(*dep_name)
1741                            .or_default()
1742                            .insert(FeatureValue::Feature(*dep_feature));
1743                    } else {
1744                        cwd_features.insert(feature.clone());
1745                    }
1746                }
1747            }
1748        }
1749
1750        let ms: Vec<_> = self
1751            .members()
1752            .filter_map(|member| {
1753                let member_id = member.package_id();
1754                match self.current_opt() {
1755                    // The features passed on the command-line only apply to
1756                    // the "current" package (determined by the cwd).
1757                    Some(current) if member_id == current.package_id() => {
1758                        let feats = CliFeatures {
1759                            features: Rc::new(cwd_features.clone()),
1760                            all_features: cli_features.all_features,
1761                            uses_default_features: cli_features.uses_default_features,
1762                        };
1763                        Some((member, feats))
1764                    }
1765                    _ => {
1766                        // Ignore members that are not enabled on the command-line.
1767                        if specs.iter().any(|spec| spec.matches(member_id)) {
1768                            // -p for a workspace member that is not the "current"
1769                            // one.
1770                            //
1771                            // The odd behavior here is due to backwards
1772                            // compatibility. `--features` and
1773                            // `--no-default-features` used to only apply to the
1774                            // "current" package. As an extension, this allows
1775                            // member-name/feature-name to set member-specific
1776                            // features, which should be backwards-compatible.
1777                            let feats = CliFeatures {
1778                                features: Rc::new(
1779                                    member_specific_features
1780                                        .remove(member.name().as_str())
1781                                        .unwrap_or_default(),
1782                                ),
1783                                uses_default_features: true,
1784                                all_features: cli_features.all_features,
1785                            };
1786                            Some((member, feats))
1787                        } else {
1788                            // This member was not requested on the command-line, skip.
1789                            None
1790                        }
1791                    }
1792                }
1793            })
1794            .collect();
1795
1796        // If any member specific features were not removed while iterating over members
1797        // some features will be ignored.
1798        assert!(member_specific_features.is_empty());
1799
1800        ms
1801    }
1802
1803    /// Returns true if `unit` should depend on the output of Docscrape units.
1804    pub fn unit_needs_doc_scrape(&self, unit: &Unit) -> bool {
1805        // We do not add scraped units for Host units, as they're either build scripts
1806        // (not documented) or proc macros (have no scrape-able exports). Additionally,
1807        // naively passing a proc macro's unit_for to new_unit_dep will currently cause
1808        // Cargo to panic, see issue #10545.
1809        self.is_member(&unit.pkg) && !(unit.target.for_host() || unit.pkg.proc_macro())
1810    }
1811
1812    /// Adds a local package registry overlaying a `SourceId`.
1813    ///
1814    /// See [`crate::sources::overlay::DependencyConfusionThreatOverlaySource`] for why you shouldn't use this.
1815    pub fn add_local_overlay(&mut self, id: SourceId, registry_path: PathBuf) {
1816        self.local_overlays.insert(id, registry_path);
1817    }
1818
1819    /// Builds a package registry that reflects this workspace configuration.
1820    pub fn package_registry(&self) -> CargoResult<PackageRegistry<'gctx>> {
1821        let source_config =
1822            SourceConfigMap::new_with_overlays(self.gctx(), self.local_overlays()?)?;
1823        PackageRegistry::new_with_source_config(self.gctx(), source_config)
1824    }
1825
1826    /// Returns all the configured local overlays, including the ones from our secret environment variable.
1827    fn local_overlays(&self) -> CargoResult<impl Iterator<Item = (SourceId, SourceId)>> {
1828        let mut ret = self
1829            .local_overlays
1830            .iter()
1831            .map(|(id, path)| Ok((*id, SourceId::for_local_registry(path)?)))
1832            .collect::<CargoResult<Vec<_>>>()?;
1833
1834        if let Ok(overlay) = self
1835            .gctx
1836            .get_env("__CARGO_TEST_DEPENDENCY_CONFUSION_VULNERABILITY_DO_NOT_USE_THIS")
1837        {
1838            let (url, path) = overlay.split_once('=').ok_or(anyhow::anyhow!(
1839                "invalid overlay format. I won't tell you why; you shouldn't be using it anyway"
1840            ))?;
1841            ret.push((
1842                SourceId::from_url(url)?,
1843                SourceId::for_local_registry(path.as_ref())?,
1844            ));
1845        }
1846
1847        Ok(ret.into_iter())
1848    }
1849}
1850
1851impl<'gctx> Packages<'gctx> {
1852    fn get(&self, manifest_path: &Path) -> &MaybePackage {
1853        self.maybe_get(manifest_path).unwrap()
1854    }
1855
1856    fn get_mut(&mut self, manifest_path: &Path) -> &mut MaybePackage {
1857        self.maybe_get_mut(manifest_path).unwrap()
1858    }
1859
1860    fn maybe_get(&self, manifest_path: &Path) -> Option<&MaybePackage> {
1861        self.packages.get(manifest_path)
1862    }
1863
1864    fn maybe_get_mut(&mut self, manifest_path: &Path) -> Option<&mut MaybePackage> {
1865        self.packages.get_mut(manifest_path)
1866    }
1867
1868    fn load(&mut self, manifest_path: &Path) -> CargoResult<&MaybePackage> {
1869        match self.packages.entry(manifest_path.to_path_buf()) {
1870            Entry::Occupied(e) => Ok(e.into_mut()),
1871            Entry::Vacant(v) => {
1872                let source_id = SourceId::for_manifest_path(manifest_path)?;
1873                let manifest = read_manifest(manifest_path, source_id, self.gctx)?;
1874                Ok(v.insert(match manifest {
1875                    EitherManifest::Real(manifest) => {
1876                        MaybePackage::Package(Package::new(manifest, manifest_path))
1877                    }
1878                    EitherManifest::Virtual(vm) => MaybePackage::Virtual(vm),
1879                }))
1880            }
1881        }
1882    }
1883}
1884
1885impl MaybePackage {
1886    fn workspace_config(&self) -> &WorkspaceConfig {
1887        match *self {
1888            MaybePackage::Package(ref p) => p.manifest().workspace_config(),
1889            MaybePackage::Virtual(ref vm) => vm.workspace_config(),
1890        }
1891    }
1892
1893    pub fn as_package(&self) -> Option<&Package> {
1894        match self {
1895            MaybePackage::Package(p) => Some(p),
1896            MaybePackage::Virtual(_) => None,
1897        }
1898    }
1899
1900    /// Has an embedded manifest (single-file package)
1901    pub fn is_embedded(&self) -> bool {
1902        match self {
1903            MaybePackage::Package(p) => p.manifest().is_embedded(),
1904            MaybePackage::Virtual(_) => false,
1905        }
1906    }
1907
1908    pub fn contents(&self) -> Option<&str> {
1909        match self {
1910            MaybePackage::Package(p) => p.manifest().contents(),
1911            MaybePackage::Virtual(v) => v.contents(),
1912        }
1913    }
1914
1915    pub fn document(&self) -> Option<&toml::Spanned<toml::de::DeTable<'static>>> {
1916        match self {
1917            MaybePackage::Package(p) => p.manifest().document(),
1918            MaybePackage::Virtual(v) => v.document(),
1919        }
1920    }
1921
1922    pub fn original_toml(&self) -> Option<&TomlManifest> {
1923        match self {
1924            MaybePackage::Package(p) => p.manifest().original_toml(),
1925            MaybePackage::Virtual(v) => v.original_toml(),
1926        }
1927    }
1928
1929    pub fn normalized_toml(&self) -> &TomlManifest {
1930        match self {
1931            MaybePackage::Package(p) => p.manifest().normalized_toml(),
1932            MaybePackage::Virtual(v) => v.normalized_toml(),
1933        }
1934    }
1935
1936    pub fn edition(&self) -> Edition {
1937        match self {
1938            MaybePackage::Package(p) => p.manifest().edition(),
1939            MaybePackage::Virtual(_) => Edition::default(),
1940        }
1941    }
1942
1943    pub fn profiles(&self) -> Option<&TomlProfiles> {
1944        match self {
1945            MaybePackage::Package(p) => p.manifest().profiles(),
1946            MaybePackage::Virtual(v) => v.profiles(),
1947        }
1948    }
1949
1950    pub fn unstable_features(&self) -> &Features {
1951        match self {
1952            MaybePackage::Package(p) => p.manifest().unstable_features(),
1953            MaybePackage::Virtual(vm) => vm.unstable_features(),
1954        }
1955    }
1956}
1957
1958impl WorkspaceRootConfig {
1959    /// Creates a new Intermediate Workspace Root configuration.
1960    pub fn new(
1961        root_dir: &Path,
1962        members: &Option<Vec<String>>,
1963        default_members: &Option<Vec<String>>,
1964        exclude: &Option<Vec<String>>,
1965        inheritable: &Option<InheritableFields>,
1966        custom_metadata: &Option<toml::Value>,
1967    ) -> WorkspaceRootConfig {
1968        WorkspaceRootConfig {
1969            root_dir: root_dir.to_path_buf(),
1970            members: members.clone(),
1971            default_members: default_members.clone(),
1972            exclude: exclude.clone().unwrap_or_default(),
1973            inheritable_fields: inheritable.clone().unwrap_or_default(),
1974            custom_metadata: custom_metadata.clone(),
1975        }
1976    }
1977    /// Checks the path against the `excluded` list.
1978    ///
1979    /// This method does **not** consider the `members` list.
1980    fn is_excluded(&self, manifest_path: &Path) -> bool {
1981        let excluded = self
1982            .exclude
1983            .iter()
1984            .any(|ex| manifest_path.starts_with(self.root_dir.join(ex)));
1985
1986        let explicit_member = match self.members {
1987            Some(ref members) => members
1988                .iter()
1989                .any(|mem| manifest_path.starts_with(self.root_dir.join(mem))),
1990            None => false,
1991        };
1992
1993        !explicit_member && excluded
1994    }
1995
1996    /// Checks if the path is explicitly listed as a workspace member.
1997    ///
1998    /// Returns `true` ONLY if:
1999    /// - The path is the workspace root manifest itself, or
2000    /// - The path matches one of the explicit `members` patterns
2001    ///
2002    /// NOTE: This does NOT check for implicit path dependency membership.
2003    /// A `false` return does NOT mean the package is definitely not a member -
2004    /// it could still be a member via path dependencies. Callers should fallback
2005    /// to full workspace loading when this returns `false`.
2006    fn is_explicitly_listed_member(&self, manifest_path: &Path) -> bool {
2007        let root_manifest = self.root_dir.join("Cargo.toml");
2008        if manifest_path == root_manifest {
2009            return true;
2010        }
2011        match self.members {
2012            Some(ref members) => {
2013                // Use members_paths to properly expand glob patterns
2014                let Ok(expanded_members) = self.members_paths(members) else {
2015                    return false;
2016                };
2017                // Normalize the manifest path for comparison
2018                let normalized_manifest = paths::normalize_path(manifest_path);
2019                expanded_members.iter().any(|(member_path, _)| {
2020                    // Normalize the member path as glob expansion may leave ".." components
2021                    let normalized_member = paths::normalize_path(member_path);
2022                    // Compare the manifest's parent directory with the member path exactly
2023                    // instead of using starts_with to avoid matching nested directories
2024                    normalized_manifest.parent() == Some(normalized_member.as_path())
2025                })
2026            }
2027            None => false,
2028        }
2029    }
2030
2031    fn has_members_list(&self) -> bool {
2032        self.members.is_some()
2033    }
2034
2035    /// Returns true if this workspace config has default-members defined.
2036    fn has_default_members(&self) -> bool {
2037        self.default_members.is_some()
2038    }
2039
2040    /// Returns expanded paths along with the glob that they were expanded from.
2041    /// The glob is `None` if the path matched exactly.
2042    #[tracing::instrument(skip_all)]
2043    fn members_paths<'g>(
2044        &self,
2045        globs: &'g [String],
2046    ) -> CargoResult<Vec<(PathBuf, Option<&'g str>)>> {
2047        let mut expanded_list = Vec::new();
2048
2049        for glob in globs {
2050            let pathbuf = self.root_dir.join(glob);
2051            let expanded_paths = Self::expand_member_path(&pathbuf)?;
2052
2053            // If glob does not find any valid paths, then put the original
2054            // path in the expanded list to maintain backwards compatibility.
2055            if expanded_paths.is_empty() {
2056                expanded_list.push((pathbuf, None));
2057            } else {
2058                let used_glob_pattern = expanded_paths.len() > 1 || expanded_paths[0] != pathbuf;
2059                let glob = used_glob_pattern.then_some(glob.as_str());
2060
2061                // Some OS can create system support files anywhere.
2062                // (e.g. macOS creates `.DS_Store` file if you visit a directory using Finder.)
2063                // Such files can be reported as a member path unexpectedly.
2064                // Check and filter out non-directory paths to prevent pushing such accidental unwanted path
2065                // as a member.
2066                for expanded_path in expanded_paths {
2067                    if expanded_path.is_dir() {
2068                        expanded_list.push((expanded_path, glob));
2069                    }
2070                }
2071            }
2072        }
2073
2074        Ok(expanded_list)
2075    }
2076
2077    fn expand_member_path(path: &Path) -> CargoResult<Vec<PathBuf>> {
2078        let Some(path) = path.to_str() else {
2079            return Ok(Vec::new());
2080        };
2081        let res = glob(path).with_context(|| format!("could not parse pattern `{}`", &path))?;
2082        let res = res
2083            .map(|p| p.with_context(|| format!("unable to match path to pattern `{}`", &path)))
2084            .collect::<Result<Vec<_>, _>>()?;
2085        Ok(res)
2086    }
2087
2088    pub fn inheritable(&self) -> &InheritableFields {
2089        &self.inheritable_fields
2090    }
2091}
2092
2093pub fn resolve_relative_path(
2094    label: &str,
2095    old_root: &Path,
2096    new_root: &Path,
2097    rel_path: &str,
2098) -> CargoResult<String> {
2099    let joined_path = normalize_path(&old_root.join(rel_path));
2100    match diff_paths(joined_path, new_root) {
2101        None => Err(anyhow!(
2102            "`{}` was defined in {} but could not be resolved with {}",
2103            label,
2104            old_root.display(),
2105            new_root.display()
2106        )),
2107        Some(path) => Ok(path
2108            .to_str()
2109            .ok_or_else(|| {
2110                anyhow!(
2111                    "`{}` resolved to non-UTF value (`{}`)",
2112                    label,
2113                    path.display()
2114                )
2115            })?
2116            .to_owned()),
2117    }
2118}
2119
2120/// Finds the path of the root of the workspace.
2121pub fn find_workspace_root(
2122    manifest_path: &Path,
2123    gctx: &GlobalContext,
2124) -> CargoResult<Option<PathBuf>> {
2125    find_workspace_root_with_loader(manifest_path, gctx, |self_path| {
2126        let source_id = SourceId::for_manifest_path(self_path)?;
2127        let manifest = read_manifest(self_path, source_id, gctx)?;
2128        Ok(manifest
2129            .workspace_config()
2130            .get_ws_root(self_path, manifest_path))
2131    })
2132}
2133
2134/// Finds the workspace root for a manifest, with minimal verification.
2135///
2136/// This is similar to `find_workspace_root`, but additionally verifies that the
2137/// package and workspace agree on each other:
2138/// - If the package has an explicit `package.workspace` pointer, it is trusted
2139/// - Otherwise, the workspace must include the package in its `members` list
2140pub fn find_workspace_root_with_membership_check(
2141    manifest_path: &Path,
2142    gctx: &GlobalContext,
2143) -> CargoResult<Option<PathBuf>> {
2144    let source_id = SourceId::for_manifest_path(manifest_path)?;
2145    let current_manifest = read_manifest(manifest_path, source_id, gctx)?;
2146
2147    match current_manifest.workspace_config() {
2148        WorkspaceConfig::Root(root_config) => {
2149            // This manifest is a workspace root itself
2150            // If default-members are defined, fall back to full loading for proper validation
2151            if root_config.has_default_members() {
2152                Ok(None)
2153            } else {
2154                Ok(Some(manifest_path.to_path_buf()))
2155            }
2156        }
2157        WorkspaceConfig::Member {
2158            root: Some(path_to_root),
2159        } => {
2160            // Has explicit `package.workspace` pointer - verify the workspace agrees
2161            let ws_manifest_path = read_root_pointer(manifest_path, path_to_root);
2162            let ws_source_id = SourceId::for_manifest_path(&ws_manifest_path)?;
2163            let ws_manifest = read_manifest(&ws_manifest_path, ws_source_id, gctx)?;
2164
2165            // Verify the workspace includes this package in its members
2166            if let WorkspaceConfig::Root(ref root_config) = *ws_manifest.workspace_config() {
2167                if root_config.is_explicitly_listed_member(manifest_path)
2168                    && !root_config.is_excluded(manifest_path)
2169                {
2170                    return Ok(Some(ws_manifest_path));
2171                }
2172            }
2173            // Workspace doesn't agree with the pointer - not a valid workspace root
2174            Ok(None)
2175        }
2176        WorkspaceConfig::Member { root: None } => {
2177            // No explicit pointer, walk up with membership validation
2178            find_workspace_root_with_loader(manifest_path, gctx, |candidate_manifest_path| {
2179                let source_id = SourceId::for_manifest_path(candidate_manifest_path)?;
2180                let manifest = read_manifest(candidate_manifest_path, source_id, gctx)?;
2181                if let WorkspaceConfig::Root(ref root_config) = *manifest.workspace_config() {
2182                    if root_config.is_explicitly_listed_member(manifest_path)
2183                        && !root_config.is_excluded(manifest_path)
2184                    {
2185                        return Ok(Some(candidate_manifest_path.to_path_buf()));
2186                    }
2187                }
2188                Ok(None)
2189            })
2190        }
2191    }
2192}
2193
2194/// Finds the path of the root of the workspace.
2195///
2196/// This uses a callback to determine if the given path tells us what the
2197/// workspace root is.
2198fn find_workspace_root_with_loader(
2199    manifest_path: &Path,
2200    gctx: &GlobalContext,
2201    mut loader: impl FnMut(&Path) -> CargoResult<Option<PathBuf>>,
2202) -> CargoResult<Option<PathBuf>> {
2203    // Check if there are any workspace roots that have already been found that would work
2204    {
2205        let roots = gctx.ws_roots();
2206        // Iterate through the manifests parent directories until we find a workspace
2207        // root. Note we skip the first item since that is just the path itself
2208        for current in manifest_path.ancestors().skip(1) {
2209            if let Some(ws_config) = roots.get(current) {
2210                if !ws_config.is_excluded(manifest_path) {
2211                    // Add `Cargo.toml` since ws_root is the root and not the file
2212                    return Ok(Some(current.join("Cargo.toml")));
2213                }
2214            }
2215        }
2216    }
2217
2218    for ances_manifest_path in find_root_iter(manifest_path, gctx) {
2219        debug!("find_root - trying {}", ances_manifest_path.display());
2220        let ws_root_path = loader(&ances_manifest_path).with_context(|| {
2221            format!(
2222                "failed searching for potential workspace\n\
2223                 package manifest: `{}`\n\
2224                 invalid potential workspace manifest: `{}`\n\
2225                 \n\
2226                 help: to avoid searching for a non-existent workspace, add \
2227                 `[workspace]` to the package manifest",
2228                manifest_path.display(),
2229                ances_manifest_path.display(),
2230            )
2231        })?;
2232        if let Some(ws_root_path) = ws_root_path {
2233            return Ok(Some(ws_root_path));
2234        }
2235    }
2236    Ok(None)
2237}
2238
2239fn read_root_pointer(member_manifest: &Path, root_link: &str) -> PathBuf {
2240    let path = member_manifest
2241        .parent()
2242        .unwrap()
2243        .join(root_link)
2244        .join("Cargo.toml");
2245    debug!("find_root - pointer {}", path.display());
2246    paths::normalize_path(&path)
2247}
2248
2249fn find_root_iter<'a>(
2250    manifest_path: &'a Path,
2251    gctx: &'a GlobalContext,
2252) -> impl Iterator<Item = PathBuf> + 'a {
2253    LookBehind::new(paths::ancestors(manifest_path, None).skip(2))
2254        .take_while(|path| !path.curr.ends_with("target/package"))
2255        // Don't walk across `CARGO_HOME` when we're looking for the
2256        // workspace root. Sometimes a package will be organized with
2257        // `CARGO_HOME` pointing inside of the workspace root or in the
2258        // current package, but we don't want to mistakenly try to put
2259        // crates.io crates into the workspace by accident.
2260        .take_while(|path| {
2261            if let Some(last) = path.last {
2262                gctx.home() != last
2263            } else {
2264                true
2265            }
2266        })
2267        .map(|path| path.curr.join("Cargo.toml"))
2268        .filter(|ances_manifest_path| ances_manifest_path.exists())
2269}
2270
2271struct LookBehindWindow<'a, T: ?Sized> {
2272    curr: &'a T,
2273    last: Option<&'a T>,
2274}
2275
2276struct LookBehind<'a, T: ?Sized, K: Iterator<Item = &'a T>> {
2277    iter: K,
2278    last: Option<&'a T>,
2279}
2280
2281impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> LookBehind<'a, T, K> {
2282    fn new(items: K) -> Self {
2283        Self {
2284            iter: items,
2285            last: None,
2286        }
2287    }
2288}
2289
2290impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> Iterator for LookBehind<'a, T, K> {
2291    type Item = LookBehindWindow<'a, T>;
2292
2293    fn next(&mut self) -> Option<Self::Item> {
2294        match self.iter.next() {
2295            None => None,
2296            Some(next) => {
2297                let last = self.last;
2298                self.last = Some(next);
2299                Some(LookBehindWindow { curr: next, last })
2300            }
2301        }
2302    }
2303}