Skip to main content

cargo/core/
workspace.rs

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