Skip to main content

cargo/workspace/
workspace.rs

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