Skip to main content

cargo/workspace/
workspace.rs

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