Skip to main content

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