Skip to main content

cargo/workspace/
workspace.rs

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