cargo/core/
workspace.rs

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