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,
21};
22use crate::core::{EitherManifest, Package, SourceId, VirtualManifest};
23use crate::ops;
24use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY, PathSource, SourceConfigMap};
25use crate::util::context::FeatureUnification;
26use crate::util::edit_distance;
27use crate::util::errors::{CargoResult, ManifestError};
28use crate::util::interning::InternedString;
29use crate::util::lints::{
30 analyze_cargo_lints_table, blanket_hint_mostly_unused, check_im_a_teapot,
31};
32use crate::util::toml::{InheritableFields, read_manifest};
33use crate::util::{
34 Filesystem, GlobalContext, IntoUrl, context::CargoResolverConfig, context::ConfigRelativePath,
35 context::IncompatibleRustVersions,
36};
37use cargo_util::paths;
38use cargo_util::paths::normalize_path;
39use cargo_util_schemas::manifest;
40use cargo_util_schemas::manifest::RustVersion;
41use cargo_util_schemas::manifest::{TomlDependency, TomlProfiles};
42use pathdiff::diff_paths;
43
44#[derive(Debug)]
50pub struct Workspace<'gctx> {
51 gctx: &'gctx GlobalContext,
53
54 current_manifest: PathBuf,
58
59 packages: Packages<'gctx>,
62
63 root_manifest: Option<PathBuf>,
68
69 target_dir: Option<Filesystem>,
72
73 build_dir: Option<Filesystem>,
76
77 members: Vec<PathBuf>,
81 member_ids: HashSet<PackageId>,
83
84 default_members: Vec<PathBuf>,
95
96 is_ephemeral: bool,
99
100 require_optional_deps: bool,
105
106 loaded_packages: RefCell<HashMap<PathBuf, Package>>,
109
110 ignore_lock: bool,
113
114 requested_lockfile_path: Option<PathBuf>,
116
117 resolve_behavior: ResolveBehavior,
119 resolve_honors_rust_version: bool,
123 resolve_feature_unification: FeatureUnification,
125 custom_metadata: Option<toml::Value>,
127
128 local_overlays: HashMap<SourceId, PathBuf>,
130}
131
132#[derive(Debug)]
135struct Packages<'gctx> {
136 gctx: &'gctx GlobalContext,
137 packages: HashMap<PathBuf, MaybePackage>,
138}
139
140#[derive(Debug)]
141pub enum MaybePackage {
142 Package(Package),
143 Virtual(VirtualManifest),
144}
145
146#[derive(Debug, Clone)]
148pub enum WorkspaceConfig {
149 Root(WorkspaceRootConfig),
152
153 Member { root: Option<String> },
156}
157
158impl WorkspaceConfig {
159 pub fn inheritable(&self) -> Option<&InheritableFields> {
160 match self {
161 WorkspaceConfig::Root(root) => Some(&root.inheritable_fields),
162 WorkspaceConfig::Member { .. } => None,
163 }
164 }
165
166 fn get_ws_root(&self, self_path: &Path, look_from: &Path) -> Option<PathBuf> {
174 match self {
175 WorkspaceConfig::Root(ances_root_config) => {
176 debug!("find_root - found a root checking exclusion");
177 if !ances_root_config.is_excluded(look_from) {
178 debug!("find_root - found!");
179 Some(self_path.to_owned())
180 } else {
181 None
182 }
183 }
184 WorkspaceConfig::Member {
185 root: Some(path_to_root),
186 } => {
187 debug!("find_root - found pointer");
188 Some(read_root_pointer(self_path, path_to_root))
189 }
190 WorkspaceConfig::Member { .. } => None,
191 }
192 }
193}
194
195#[derive(Debug, Clone)]
200pub struct WorkspaceRootConfig {
201 root_dir: PathBuf,
202 members: Option<Vec<String>>,
203 default_members: Option<Vec<String>>,
204 exclude: Vec<String>,
205 inheritable_fields: InheritableFields,
206 custom_metadata: Option<toml::Value>,
207}
208
209impl<'gctx> Workspace<'gctx> {
210 pub fn new(manifest_path: &Path, gctx: &'gctx GlobalContext) -> CargoResult<Workspace<'gctx>> {
217 let mut ws = Workspace::new_default(manifest_path.to_path_buf(), gctx);
218 ws.target_dir = gctx.target_dir()?;
219
220 if manifest_path.is_relative() {
221 bail!(
222 "manifest_path:{:?} is not an absolute path. Please provide an absolute path.",
223 manifest_path
224 )
225 } else {
226 ws.root_manifest = ws.find_root(manifest_path)?;
227 }
228
229 ws.build_dir = gctx.build_dir(
230 ws.root_manifest
231 .as_ref()
232 .unwrap_or(&manifest_path.to_path_buf()),
233 )?;
234
235 ws.custom_metadata = ws
236 .load_workspace_config()?
237 .and_then(|cfg| cfg.custom_metadata);
238 ws.find_members()?;
239 ws.set_resolve_behavior()?;
240 ws.validate()?;
241 Ok(ws)
242 }
243
244 fn new_default(current_manifest: PathBuf, gctx: &'gctx GlobalContext) -> Workspace<'gctx> {
245 Workspace {
246 gctx,
247 current_manifest,
248 packages: Packages {
249 gctx,
250 packages: HashMap::new(),
251 },
252 root_manifest: None,
253 target_dir: None,
254 build_dir: None,
255 members: Vec::new(),
256 member_ids: HashSet::new(),
257 default_members: Vec::new(),
258 is_ephemeral: false,
259 require_optional_deps: true,
260 loaded_packages: RefCell::new(HashMap::new()),
261 ignore_lock: false,
262 requested_lockfile_path: None,
263 resolve_behavior: ResolveBehavior::V1,
264 resolve_honors_rust_version: false,
265 resolve_feature_unification: FeatureUnification::Selected,
266 custom_metadata: None,
267 local_overlays: HashMap::new(),
268 }
269 }
270
271 pub fn ephemeral(
281 package: Package,
282 gctx: &'gctx GlobalContext,
283 target_dir: Option<Filesystem>,
284 require_optional_deps: bool,
285 ) -> CargoResult<Workspace<'gctx>> {
286 let mut ws = Workspace::new_default(package.manifest_path().to_path_buf(), gctx);
287 ws.is_ephemeral = true;
288 ws.require_optional_deps = require_optional_deps;
289 let id = package.package_id();
290 let package = MaybePackage::Package(package);
291 ws.packages
292 .packages
293 .insert(ws.current_manifest.clone(), package);
294 ws.target_dir = if let Some(dir) = target_dir {
295 Some(dir)
296 } else {
297 ws.gctx.target_dir()?
298 };
299 ws.build_dir = ws.target_dir.clone();
300 ws.members.push(ws.current_manifest.clone());
301 ws.member_ids.insert(id);
302 ws.default_members.push(ws.current_manifest.clone());
303 ws.set_resolve_behavior()?;
304 Ok(ws)
305 }
306
307 pub fn reload(&self, gctx: &'gctx GlobalContext) -> CargoResult<Workspace<'gctx>> {
312 let mut ws = Workspace::new(&self.current_manifest, gctx)?;
313 ws.set_resolve_honors_rust_version(Some(self.resolve_honors_rust_version));
314 ws.set_resolve_feature_unification(self.resolve_feature_unification);
315 ws.set_requested_lockfile_path(self.requested_lockfile_path.clone());
316 Ok(ws)
317 }
318
319 fn set_resolve_behavior(&mut self) -> CargoResult<()> {
320 self.resolve_behavior = match self.root_maybe() {
325 MaybePackage::Package(p) => p
326 .manifest()
327 .resolve_behavior()
328 .unwrap_or_else(|| p.manifest().edition().default_resolve_behavior()),
329 MaybePackage::Virtual(vm) => vm.resolve_behavior().unwrap_or(ResolveBehavior::V1),
330 };
331
332 match self.resolve_behavior() {
333 ResolveBehavior::V1 | ResolveBehavior::V2 => {}
334 ResolveBehavior::V3 => {
335 if self.resolve_behavior == ResolveBehavior::V3 {
336 self.resolve_honors_rust_version = true;
337 }
338 }
339 }
340 let config = self.gctx().get::<CargoResolverConfig>("resolver")?;
341 if let Some(incompatible_rust_versions) = config.incompatible_rust_versions {
342 self.resolve_honors_rust_version =
343 incompatible_rust_versions == IncompatibleRustVersions::Fallback;
344 }
345 if self.gctx().cli_unstable().feature_unification {
346 self.resolve_feature_unification = config
347 .feature_unification
348 .unwrap_or(FeatureUnification::Selected);
349 } else if config.feature_unification.is_some() {
350 self.gctx()
351 .shell()
352 .warn("ignoring `resolver.feature-unification` without `-Zfeature-unification`")?;
353 };
354
355 Ok(())
356 }
357
358 pub fn current(&self) -> CargoResult<&Package> {
364 let pkg = self.current_opt().ok_or_else(|| {
365 anyhow::format_err!(
366 "manifest path `{}` is a virtual manifest, but this \
367 command requires running against an actual package in \
368 this workspace",
369 self.current_manifest.display()
370 )
371 })?;
372 Ok(pkg)
373 }
374
375 pub fn current_mut(&mut self) -> CargoResult<&mut Package> {
376 let cm = self.current_manifest.clone();
377 let pkg = self.current_opt_mut().ok_or_else(|| {
378 anyhow::format_err!(
379 "manifest path `{}` is a virtual manifest, but this \
380 command requires running against an actual package in \
381 this workspace",
382 cm.display()
383 )
384 })?;
385 Ok(pkg)
386 }
387
388 pub fn current_opt(&self) -> Option<&Package> {
389 match *self.packages.get(&self.current_manifest) {
390 MaybePackage::Package(ref p) => Some(p),
391 MaybePackage::Virtual(..) => None,
392 }
393 }
394
395 pub fn current_opt_mut(&mut self) -> Option<&mut Package> {
396 match *self.packages.get_mut(&self.current_manifest) {
397 MaybePackage::Package(ref mut p) => Some(p),
398 MaybePackage::Virtual(..) => None,
399 }
400 }
401
402 pub fn is_virtual(&self) -> bool {
403 match *self.packages.get(&self.current_manifest) {
404 MaybePackage::Package(..) => false,
405 MaybePackage::Virtual(..) => true,
406 }
407 }
408
409 pub fn gctx(&self) -> &'gctx GlobalContext {
411 self.gctx
412 }
413
414 pub fn profiles(&self) -> Option<&TomlProfiles> {
415 self.root_maybe().profiles()
416 }
417
418 pub fn root(&self) -> &Path {
423 self.root_manifest().parent().unwrap()
424 }
425
426 pub fn root_manifest(&self) -> &Path {
429 self.root_manifest
430 .as_ref()
431 .unwrap_or(&self.current_manifest)
432 }
433
434 pub fn root_maybe(&self) -> &MaybePackage {
436 self.packages.get(self.root_manifest())
437 }
438
439 pub fn target_dir(&self) -> Filesystem {
440 self.target_dir
441 .clone()
442 .unwrap_or_else(|| self.default_target_dir())
443 }
444
445 pub fn build_dir(&self) -> Filesystem {
446 self.build_dir.clone().unwrap_or_else(|| self.target_dir())
447 }
448
449 fn default_target_dir(&self) -> Filesystem {
450 if self.root_maybe().is_embedded() {
451 let hash = crate::util::hex::short_hash(&self.root_manifest().to_string_lossy());
452 let mut rel_path = PathBuf::new();
453 rel_path.push("target");
454 rel_path.push(&hash[0..2]);
455 rel_path.push(&hash[2..]);
456
457 self.gctx().home().join(rel_path)
458 } else {
459 Filesystem::new(self.root().join("target"))
460 }
461 }
462
463 pub fn root_replace(&self) -> &[(PackageIdSpec, Dependency)] {
467 match self.root_maybe() {
468 MaybePackage::Package(p) => p.manifest().replace(),
469 MaybePackage::Virtual(vm) => vm.replace(),
470 }
471 }
472
473 fn config_patch(&self) -> CargoResult<HashMap<Url, Vec<Dependency>>> {
474 let config_patch: Option<
475 BTreeMap<String, BTreeMap<String, TomlDependency<ConfigRelativePath>>>,
476 > = self.gctx.get("patch")?;
477
478 let source = SourceId::for_manifest_path(self.root_manifest())?;
479
480 let mut warnings = Vec::new();
481
482 let mut patch = HashMap::new();
483 for (url, deps) in config_patch.into_iter().flatten() {
484 let url = match &url[..] {
485 CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
486 url => self
487 .gctx
488 .get_registry_index(url)
489 .or_else(|_| url.into_url())
490 .with_context(|| {
491 format!("[patch] entry `{}` should be a URL or registry name", url)
492 })?,
493 };
494 patch.insert(
495 url,
496 deps.iter()
497 .map(|(name, dep)| {
498 crate::util::toml::to_dependency(
499 dep,
500 name,
501 source,
502 self.gctx,
503 &mut warnings,
504 None,
505 Path::new("unused-relative-path"),
508 None,
509 )
510 })
511 .collect::<CargoResult<Vec<_>>>()?,
512 );
513 }
514
515 for message in warnings {
516 self.gctx
517 .shell()
518 .warn(format!("[patch] in cargo config: {}", message))?
519 }
520
521 Ok(patch)
522 }
523
524 pub fn root_patch(&self) -> CargoResult<HashMap<Url, Vec<Dependency>>> {
528 let from_manifest = match self.root_maybe() {
529 MaybePackage::Package(p) => p.manifest().patch(),
530 MaybePackage::Virtual(vm) => vm.patch(),
531 };
532
533 let from_config = self.config_patch()?;
534 if from_config.is_empty() {
535 return Ok(from_manifest.clone());
536 }
537 if from_manifest.is_empty() {
538 return Ok(from_config);
539 }
540
541 let mut combined = from_config;
544 for (url, deps_from_manifest) in from_manifest {
545 if let Some(deps_from_config) = combined.get_mut(url) {
546 let mut from_manifest_pruned = deps_from_manifest.clone();
549 for dep_from_config in &mut *deps_from_config {
550 if let Some(i) = from_manifest_pruned.iter().position(|dep_from_manifest| {
551 dep_from_config.name_in_toml() == dep_from_manifest.name_in_toml()
553 }) {
554 from_manifest_pruned.swap_remove(i);
555 }
556 }
557 deps_from_config.extend(from_manifest_pruned);
559 } else {
560 combined.insert(url.clone(), deps_from_manifest.clone());
561 }
562 }
563 Ok(combined)
564 }
565
566 pub fn members(&self) -> impl Iterator<Item = &Package> {
568 let packages = &self.packages;
569 self.members
570 .iter()
571 .filter_map(move |path| match packages.get(path) {
572 MaybePackage::Package(p) => Some(p),
573 _ => None,
574 })
575 }
576
577 pub fn members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
579 let packages = &mut self.packages.packages;
580 let members: HashSet<_> = self.members.iter().map(|path| path).collect();
581
582 packages.iter_mut().filter_map(move |(path, package)| {
583 if members.contains(path) {
584 if let MaybePackage::Package(p) = package {
585 return Some(p);
586 }
587 }
588
589 None
590 })
591 }
592
593 pub fn default_members<'a>(&'a self) -> impl Iterator<Item = &'a Package> {
595 let packages = &self.packages;
596 self.default_members
597 .iter()
598 .filter_map(move |path| match packages.get(path) {
599 MaybePackage::Package(p) => Some(p),
600 _ => None,
601 })
602 }
603
604 pub fn default_members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
606 let packages = &mut self.packages.packages;
607 let members: HashSet<_> = self
608 .default_members
609 .iter()
610 .map(|path| path.parent().unwrap().to_owned())
611 .collect();
612
613 packages.iter_mut().filter_map(move |(path, package)| {
614 if members.contains(path) {
615 if let MaybePackage::Package(p) = package {
616 return Some(p);
617 }
618 }
619
620 None
621 })
622 }
623
624 pub fn is_member(&self, pkg: &Package) -> bool {
626 self.member_ids.contains(&pkg.package_id())
627 }
628
629 pub fn is_member_id(&self, package_id: PackageId) -> bool {
631 self.member_ids.contains(&package_id)
632 }
633
634 pub fn is_ephemeral(&self) -> bool {
635 self.is_ephemeral
636 }
637
638 pub fn require_optional_deps(&self) -> bool {
639 self.require_optional_deps
640 }
641
642 pub fn set_require_optional_deps(
643 &mut self,
644 require_optional_deps: bool,
645 ) -> &mut Workspace<'gctx> {
646 self.require_optional_deps = require_optional_deps;
647 self
648 }
649
650 pub fn ignore_lock(&self) -> bool {
651 self.ignore_lock
652 }
653
654 pub fn set_ignore_lock(&mut self, ignore_lock: bool) -> &mut Workspace<'gctx> {
655 self.ignore_lock = ignore_lock;
656 self
657 }
658
659 pub fn lock_root(&self) -> Filesystem {
661 if let Some(requested) = self.requested_lockfile_path.as_ref() {
662 return Filesystem::new(
663 requested
664 .parent()
665 .expect("Lockfile path can't be root")
666 .to_owned(),
667 );
668 }
669 self.default_lock_root()
670 }
671
672 fn default_lock_root(&self) -> Filesystem {
673 if self.root_maybe().is_embedded() {
674 self.target_dir()
675 } else {
676 Filesystem::new(self.root().to_owned())
677 }
678 }
679
680 pub fn set_requested_lockfile_path(&mut self, path: Option<PathBuf>) {
681 self.requested_lockfile_path = path;
682 }
683
684 pub fn requested_lockfile_path(&self) -> Option<&Path> {
685 self.requested_lockfile_path.as_deref()
686 }
687
688 pub fn lowest_rust_version(&self) -> Option<&RustVersion> {
691 self.members().filter_map(|pkg| pkg.rust_version()).min()
692 }
693
694 pub fn set_resolve_honors_rust_version(&mut self, honor_rust_version: Option<bool>) {
695 if let Some(honor_rust_version) = honor_rust_version {
696 self.resolve_honors_rust_version = honor_rust_version;
697 }
698 }
699
700 pub fn resolve_honors_rust_version(&self) -> bool {
701 self.resolve_honors_rust_version
702 }
703
704 pub fn set_resolve_feature_unification(&mut self, feature_unification: FeatureUnification) {
705 self.resolve_feature_unification = feature_unification;
706 }
707
708 pub fn resolve_feature_unification(&self) -> FeatureUnification {
709 self.resolve_feature_unification
710 }
711
712 pub fn custom_metadata(&self) -> Option<&toml::Value> {
713 self.custom_metadata.as_ref()
714 }
715
716 pub fn load_workspace_config(&mut self) -> CargoResult<Option<WorkspaceRootConfig>> {
717 if let Some(root_path) = &self.root_manifest {
720 let root_package = self.packages.load(root_path)?;
721 match root_package.workspace_config() {
722 WorkspaceConfig::Root(root_config) => {
723 return Ok(Some(root_config.clone()));
724 }
725
726 _ => bail!(
727 "root of a workspace inferred but wasn't a root: {}",
728 root_path.display()
729 ),
730 }
731 }
732
733 Ok(None)
734 }
735
736 fn find_root(&mut self, manifest_path: &Path) -> CargoResult<Option<PathBuf>> {
746 let current = self.packages.load(manifest_path)?;
747 match current
748 .workspace_config()
749 .get_ws_root(manifest_path, manifest_path)
750 {
751 Some(root_path) => {
752 debug!("find_root - is root {}", manifest_path.display());
753 Ok(Some(root_path))
754 }
755 None => find_workspace_root_with_loader(manifest_path, self.gctx, |self_path| {
756 Ok(self
757 .packages
758 .load(self_path)?
759 .workspace_config()
760 .get_ws_root(self_path, manifest_path))
761 }),
762 }
763 }
764
765 #[tracing::instrument(skip_all)]
773 fn find_members(&mut self) -> CargoResult<()> {
774 let Some(workspace_config) = self.load_workspace_config()? else {
775 debug!("find_members - only me as a member");
776 self.members.push(self.current_manifest.clone());
777 self.default_members.push(self.current_manifest.clone());
778 if let Ok(pkg) = self.current() {
779 let id = pkg.package_id();
780 self.member_ids.insert(id);
781 }
782 return Ok(());
783 };
784
785 let root_manifest_path = self.root_manifest.clone().unwrap();
787
788 let members_paths = workspace_config
789 .members_paths(workspace_config.members.as_deref().unwrap_or_default())?;
790 let default_members_paths = if root_manifest_path == self.current_manifest {
791 if let Some(ref default) = workspace_config.default_members {
792 Some(workspace_config.members_paths(default)?)
793 } else {
794 None
795 }
796 } else {
797 None
798 };
799
800 for (path, glob) in &members_paths {
801 self.find_path_deps(&path.join("Cargo.toml"), &root_manifest_path, false)
802 .with_context(|| {
803 format!(
804 "failed to load manifest for workspace member `{}`\n\
805 referenced{} by workspace at `{}`",
806 path.display(),
807 glob.map(|g| format!(" via `{g}`")).unwrap_or_default(),
808 root_manifest_path.display(),
809 )
810 })?;
811 }
812
813 self.find_path_deps(&root_manifest_path, &root_manifest_path, false)?;
814
815 if let Some(default) = default_members_paths {
816 for (path, default_member_glob) in default {
817 let normalized_path = paths::normalize_path(&path);
818 let manifest_path = normalized_path.join("Cargo.toml");
819 if !self.members.contains(&manifest_path) {
820 let exclude = members_paths.iter().any(|(m, _)| *m == normalized_path)
827 && workspace_config.is_excluded(&normalized_path);
828 if exclude {
829 continue;
830 }
831 bail!(
832 "package `{}` is listed in default-members{} but is not a member\n\
833 for workspace at `{}`.",
834 path.display(),
835 default_member_glob
836 .map(|g| format!(" via `{g}`"))
837 .unwrap_or_default(),
838 root_manifest_path.display(),
839 )
840 }
841 self.default_members.push(manifest_path)
842 }
843 } else if self.is_virtual() {
844 self.default_members = self.members.clone()
845 } else {
846 self.default_members.push(self.current_manifest.clone())
847 }
848
849 Ok(())
850 }
851
852 fn find_path_deps(
853 &mut self,
854 manifest_path: &Path,
855 root_manifest: &Path,
856 is_path_dep: bool,
857 ) -> CargoResult<()> {
858 let manifest_path = paths::normalize_path(manifest_path);
859 if self.members.contains(&manifest_path) {
860 return Ok(());
861 }
862 if is_path_dep && self.root_maybe().is_embedded() {
863 return Ok(());
865 }
866 if is_path_dep
867 && !manifest_path.parent().unwrap().starts_with(self.root())
868 && self.find_root(&manifest_path)? != self.root_manifest
869 {
870 return Ok(());
873 }
874
875 if let WorkspaceConfig::Root(ref root_config) =
876 *self.packages.load(root_manifest)?.workspace_config()
877 {
878 if root_config.is_excluded(&manifest_path) {
879 return Ok(());
880 }
881 }
882
883 debug!("find_path_deps - {}", manifest_path.display());
884 self.members.push(manifest_path.clone());
885
886 let candidates = {
887 let pkg = match *self.packages.load(&manifest_path)? {
888 MaybePackage::Package(ref p) => p,
889 MaybePackage::Virtual(_) => return Ok(()),
890 };
891 self.member_ids.insert(pkg.package_id());
892 pkg.dependencies()
893 .iter()
894 .map(|d| (d.source_id(), d.package_name()))
895 .filter(|(s, _)| s.is_path())
896 .filter_map(|(s, n)| s.url().to_file_path().ok().map(|p| (p, n)))
897 .map(|(p, n)| (p.join("Cargo.toml"), n))
898 .collect::<Vec<_>>()
899 };
900 for (path, name) in candidates {
901 self.find_path_deps(&path, root_manifest, true)
902 .with_context(|| format!("failed to load manifest for dependency `{}`", name))
903 .map_err(|err| ManifestError::new(err, manifest_path.clone()))?;
904 }
905 Ok(())
906 }
907
908 pub fn unstable_features(&self) -> &Features {
910 self.root_maybe().unstable_features()
911 }
912
913 pub fn resolve_behavior(&self) -> ResolveBehavior {
914 self.resolve_behavior
915 }
916
917 pub fn allows_new_cli_feature_behavior(&self) -> bool {
925 self.is_virtual()
926 || match self.resolve_behavior() {
927 ResolveBehavior::V1 => false,
928 ResolveBehavior::V2 | ResolveBehavior::V3 => true,
929 }
930 }
931
932 #[tracing::instrument(skip_all)]
938 fn validate(&mut self) -> CargoResult<()> {
939 if self.root_manifest.is_none() {
941 return Ok(());
942 }
943
944 self.validate_unique_names()?;
945 self.validate_workspace_roots()?;
946 self.validate_members()?;
947 self.error_if_manifest_not_in_members()?;
948 self.validate_manifest()
949 }
950
951 fn validate_unique_names(&self) -> CargoResult<()> {
952 let mut names = BTreeMap::new();
953 for member in self.members.iter() {
954 let package = self.packages.get(member);
955 let name = match *package {
956 MaybePackage::Package(ref p) => p.name(),
957 MaybePackage::Virtual(_) => continue,
958 };
959 if let Some(prev) = names.insert(name, member) {
960 bail!(
961 "two packages named `{}` in this workspace:\n\
962 - {}\n\
963 - {}",
964 name,
965 prev.display(),
966 member.display()
967 );
968 }
969 }
970 Ok(())
971 }
972
973 fn validate_workspace_roots(&self) -> CargoResult<()> {
974 let roots: Vec<PathBuf> = self
975 .members
976 .iter()
977 .filter(|&member| {
978 let config = self.packages.get(member).workspace_config();
979 matches!(config, WorkspaceConfig::Root(_))
980 })
981 .map(|member| member.parent().unwrap().to_path_buf())
982 .collect();
983 match roots.len() {
984 1 => Ok(()),
985 0 => bail!(
986 "`package.workspace` configuration points to a crate \
987 which is not configured with [workspace]: \n\
988 configuration at: {}\n\
989 points to: {}",
990 self.current_manifest.display(),
991 self.root_manifest.as_ref().unwrap().display()
992 ),
993 _ => {
994 bail!(
995 "multiple workspace roots found in the same workspace:\n{}",
996 roots
997 .iter()
998 .map(|r| format!(" {}", r.display()))
999 .collect::<Vec<_>>()
1000 .join("\n")
1001 );
1002 }
1003 }
1004 }
1005
1006 #[tracing::instrument(skip_all)]
1007 fn validate_members(&mut self) -> CargoResult<()> {
1008 for member in self.members.clone() {
1009 let root = self.find_root(&member)?;
1010 if root == self.root_manifest {
1011 continue;
1012 }
1013
1014 match root {
1015 Some(root) => {
1016 bail!(
1017 "package `{}` is a member of the wrong workspace\n\
1018 expected: {}\n\
1019 actual: {}",
1020 member.display(),
1021 self.root_manifest.as_ref().unwrap().display(),
1022 root.display()
1023 );
1024 }
1025 None => {
1026 bail!(
1027 "workspace member `{}` is not hierarchically below \
1028 the workspace root `{}`",
1029 member.display(),
1030 self.root_manifest.as_ref().unwrap().display()
1031 );
1032 }
1033 }
1034 }
1035 Ok(())
1036 }
1037
1038 fn error_if_manifest_not_in_members(&mut self) -> CargoResult<()> {
1039 if self.members.contains(&self.current_manifest) {
1040 return Ok(());
1041 }
1042
1043 let root = self.root_manifest.as_ref().unwrap();
1044 let root_dir = root.parent().unwrap();
1045 let current_dir = self.current_manifest.parent().unwrap();
1046 let root_pkg = self.packages.get(root);
1047
1048 let members_msg = match current_dir.strip_prefix(root_dir) {
1050 Ok(rel) => format!(
1051 "this may be fixable by adding `{}` to the \
1052 `workspace.members` array of the manifest \
1053 located at: {}",
1054 rel.display(),
1055 root.display()
1056 ),
1057 Err(_) => format!(
1058 "this may be fixable by adding a member to \
1059 the `workspace.members` array of the \
1060 manifest located at: {}",
1061 root.display()
1062 ),
1063 };
1064 let extra = match *root_pkg {
1065 MaybePackage::Virtual(_) => members_msg,
1066 MaybePackage::Package(ref p) => {
1067 let has_members_list = match *p.manifest().workspace_config() {
1068 WorkspaceConfig::Root(ref root_config) => root_config.has_members_list(),
1069 WorkspaceConfig::Member { .. } => unreachable!(),
1070 };
1071 if !has_members_list {
1072 format!(
1073 "this may be fixable by ensuring that this \
1074 crate is depended on by the workspace \
1075 root: {}",
1076 root.display()
1077 )
1078 } else {
1079 members_msg
1080 }
1081 }
1082 };
1083 bail!(
1084 "current package believes it's in a workspace when it's not:\n\
1085 current: {}\n\
1086 workspace: {}\n\n{}\n\
1087 Alternatively, to keep it out of the workspace, add the package \
1088 to the `workspace.exclude` array, or add an empty `[workspace]` \
1089 table to the package's manifest.",
1090 self.current_manifest.display(),
1091 root.display(),
1092 extra
1093 );
1094 }
1095
1096 fn validate_manifest(&mut self) -> CargoResult<()> {
1097 if let Some(ref root_manifest) = self.root_manifest {
1098 for pkg in self
1099 .members()
1100 .filter(|p| p.manifest_path() != root_manifest)
1101 {
1102 let manifest = pkg.manifest();
1103 let emit_warning = |what| -> CargoResult<()> {
1104 let msg = format!(
1105 "{} for the non root package will be ignored, \
1106 specify {} at the workspace root:\n\
1107 package: {}\n\
1108 workspace: {}",
1109 what,
1110 what,
1111 pkg.manifest_path().display(),
1112 root_manifest.display(),
1113 );
1114 self.gctx.shell().warn(&msg)
1115 };
1116 if manifest.normalized_toml().has_profiles() {
1117 emit_warning("profiles")?;
1118 }
1119 if !manifest.replace().is_empty() {
1120 emit_warning("replace")?;
1121 }
1122 if !manifest.patch().is_empty() {
1123 emit_warning("patch")?;
1124 }
1125 if let Some(behavior) = manifest.resolve_behavior() {
1126 if behavior != self.resolve_behavior {
1127 emit_warning("resolver")?;
1129 }
1130 }
1131 }
1132 if let MaybePackage::Virtual(vm) = self.root_maybe() {
1133 if vm.resolve_behavior().is_none() {
1134 if let Some(edition) = self
1135 .members()
1136 .filter(|p| p.manifest_path() != root_manifest)
1137 .map(|p| p.manifest().edition())
1138 .filter(|&e| e >= Edition::Edition2021)
1139 .max()
1140 {
1141 let resolver = edition.default_resolve_behavior().to_manifest();
1142 let report = &[Level::WARNING
1143 .primary_title(format!(
1144 "virtual workspace defaulting to `resolver = \"1\"` despite one or more workspace members being on edition {edition} which implies `resolver = \"{resolver}\"`"
1145 ))
1146 .elements([
1147 Level::NOTE.message("to keep the current resolver, specify `workspace.resolver = \"1\"` in the workspace root's manifest"),
1148 Level::NOTE.message(
1149 format!("to use the edition {edition} resolver, specify `workspace.resolver = \"{resolver}\"` in the workspace root's manifest"),
1150 ),
1151 Level::NOTE.message("for more details see https://doc.rust-lang.org/cargo/reference/resolver.html#resolver-versions"),
1152 ])];
1153 self.gctx.shell().print_report(report, false)?;
1154 }
1155 }
1156 }
1157 }
1158 Ok(())
1159 }
1160
1161 pub fn load(&self, manifest_path: &Path) -> CargoResult<Package> {
1162 match self.packages.maybe_get(manifest_path) {
1163 Some(MaybePackage::Package(p)) => return Ok(p.clone()),
1164 Some(&MaybePackage::Virtual(_)) => bail!("cannot load workspace root"),
1165 None => {}
1166 }
1167
1168 let mut loaded = self.loaded_packages.borrow_mut();
1169 if let Some(p) = loaded.get(manifest_path).cloned() {
1170 return Ok(p);
1171 }
1172 let source_id = SourceId::for_manifest_path(manifest_path)?;
1173 let package = ops::read_package(manifest_path, source_id, self.gctx)?;
1174 loaded.insert(manifest_path.to_path_buf(), package.clone());
1175 Ok(package)
1176 }
1177
1178 pub fn preload(&self, registry: &mut PackageRegistry<'gctx>) {
1185 if self.is_ephemeral {
1191 return;
1192 }
1193
1194 for pkg in self.packages.packages.values() {
1195 let pkg = match *pkg {
1196 MaybePackage::Package(ref p) => p.clone(),
1197 MaybePackage::Virtual(_) => continue,
1198 };
1199 let src = PathSource::preload_with(pkg, self.gctx);
1200 registry.add_preloaded(Box::new(src));
1201 }
1202 }
1203
1204 pub fn emit_warnings(&self) -> CargoResult<()> {
1205 let mut first_emitted_error = None;
1206
1207 if let Err(e) = self.emit_ws_lints() {
1208 first_emitted_error = Some(e);
1209 }
1210
1211 for (path, maybe_pkg) in &self.packages.packages {
1212 if let MaybePackage::Package(pkg) = maybe_pkg {
1213 if let Err(e) = self.emit_pkg_lints(pkg, &path)
1214 && first_emitted_error.is_none()
1215 {
1216 first_emitted_error = Some(e);
1217 }
1218 }
1219 let warnings = match maybe_pkg {
1220 MaybePackage::Package(pkg) => pkg.manifest().warnings().warnings(),
1221 MaybePackage::Virtual(vm) => vm.warnings().warnings(),
1222 };
1223 for warning in warnings {
1224 if warning.is_critical {
1225 let err = anyhow::format_err!("{}", warning.message);
1226 let cx =
1227 anyhow::format_err!("failed to parse manifest at `{}`", path.display());
1228 if first_emitted_error.is_none() {
1229 first_emitted_error = Some(err.context(cx));
1230 }
1231 } else {
1232 let msg = if self.root_manifest.is_none() {
1233 warning.message.to_string()
1234 } else {
1235 format!("{}: {}", path.display(), warning.message)
1238 };
1239 self.gctx.shell().warn(msg)?
1240 }
1241 }
1242 }
1243
1244 if let Some(error) = first_emitted_error {
1245 Err(error)
1246 } else {
1247 Ok(())
1248 }
1249 }
1250
1251 pub fn emit_pkg_lints(&self, pkg: &Package, path: &Path) -> CargoResult<()> {
1252 let mut error_count = 0;
1253 let toml_lints = pkg
1254 .manifest()
1255 .normalized_toml()
1256 .lints
1257 .clone()
1258 .map(|lints| lints.lints)
1259 .unwrap_or(manifest::TomlLints::default());
1260 let cargo_lints = toml_lints
1261 .get("cargo")
1262 .cloned()
1263 .unwrap_or(manifest::TomlToolLints::default());
1264
1265 let ws_contents = self.root_maybe().contents();
1266
1267 let ws_document = self.root_maybe().document();
1268
1269 if self.gctx.cli_unstable().cargo_lints {
1270 analyze_cargo_lints_table(
1271 pkg,
1272 &path,
1273 &cargo_lints,
1274 ws_contents,
1275 ws_document,
1276 self.root_manifest(),
1277 self.gctx,
1278 )?;
1279 check_im_a_teapot(pkg, &path, &cargo_lints, &mut error_count, self.gctx)?;
1280 }
1281
1282 if error_count > 0 {
1283 Err(crate::util::errors::AlreadyPrintedError::new(anyhow!(
1284 "encountered {error_count} errors(s) while running lints"
1285 ))
1286 .into())
1287 } else {
1288 Ok(())
1289 }
1290 }
1291
1292 pub fn emit_ws_lints(&self) -> CargoResult<()> {
1293 let mut error_count = 0;
1294
1295 let cargo_lints = match self.root_maybe() {
1296 MaybePackage::Package(pkg) => {
1297 let toml = pkg.manifest().normalized_toml();
1298 if let Some(ws) = &toml.workspace {
1299 ws.lints.as_ref()
1300 } else {
1301 toml.lints.as_ref().map(|l| &l.lints)
1302 }
1303 }
1304 MaybePackage::Virtual(vm) => vm
1305 .normalized_toml()
1306 .workspace
1307 .as_ref()
1308 .unwrap()
1309 .lints
1310 .as_ref(),
1311 }
1312 .and_then(|t| t.get("cargo"))
1313 .cloned()
1314 .unwrap_or(manifest::TomlToolLints::default());
1315
1316 if self.gctx.cli_unstable().cargo_lints {
1317 }
1319
1320 if self.gctx.cli_unstable().profile_hint_mostly_unused {
1324 blanket_hint_mostly_unused(
1325 self.root_maybe(),
1326 self.root_manifest(),
1327 &cargo_lints,
1328 &mut error_count,
1329 self.gctx,
1330 )?;
1331 }
1332
1333 if error_count > 0 {
1334 Err(crate::util::errors::AlreadyPrintedError::new(anyhow!(
1335 "encountered {error_count} errors(s) while running lints"
1336 ))
1337 .into())
1338 } else {
1339 Ok(())
1340 }
1341 }
1342
1343 pub fn set_target_dir(&mut self, target_dir: Filesystem) {
1344 self.target_dir = Some(target_dir);
1345 }
1346
1347 pub fn members_with_features(
1355 &self,
1356 specs: &[PackageIdSpec],
1357 cli_features: &CliFeatures,
1358 ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1359 assert!(
1360 !specs.is_empty() || cli_features.all_features,
1361 "no specs requires all_features"
1362 );
1363 if specs.is_empty() {
1364 return Ok(self
1367 .members()
1368 .map(|m| (m, CliFeatures::new_all(true)))
1369 .collect());
1370 }
1371 if self.allows_new_cli_feature_behavior() {
1372 self.members_with_features_new(specs, cli_features)
1373 } else {
1374 Ok(self.members_with_features_old(specs, cli_features))
1375 }
1376 }
1377
1378 fn collect_matching_features(
1381 member: &Package,
1382 cli_features: &CliFeatures,
1383 found_features: &mut BTreeSet<FeatureValue>,
1384 ) -> CliFeatures {
1385 if cli_features.features.is_empty() {
1386 return cli_features.clone();
1387 }
1388
1389 let summary = member.summary();
1391
1392 let summary_features = summary.features();
1394
1395 let dependencies: BTreeMap<InternedString, &Dependency> = summary
1397 .dependencies()
1398 .iter()
1399 .map(|dep| (dep.name_in_toml(), dep))
1400 .collect();
1401
1402 let optional_dependency_names: BTreeSet<_> = dependencies
1404 .iter()
1405 .filter(|(_, dep)| dep.is_optional())
1406 .map(|(name, _)| name)
1407 .copied()
1408 .collect();
1409
1410 let mut features = BTreeSet::new();
1411
1412 let summary_or_opt_dependency_feature = |feature: &InternedString| -> bool {
1414 summary_features.contains_key(feature) || optional_dependency_names.contains(feature)
1415 };
1416
1417 for feature in cli_features.features.iter() {
1418 match feature {
1419 FeatureValue::Feature(f) => {
1420 if summary_or_opt_dependency_feature(f) {
1421 features.insert(feature.clone());
1423 found_features.insert(feature.clone());
1424 }
1425 }
1426 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1428 FeatureValue::DepFeature {
1429 dep_name,
1430 dep_feature,
1431 weak: _,
1432 } => {
1433 if dependencies.contains_key(dep_name) {
1434 features.insert(feature.clone());
1437 found_features.insert(feature.clone());
1438 } else if *dep_name == member.name()
1439 && summary_or_opt_dependency_feature(dep_feature)
1440 {
1441 features.insert(FeatureValue::Feature(*dep_feature));
1446 found_features.insert(feature.clone());
1447 }
1448 }
1449 }
1450 }
1451 CliFeatures {
1452 features: Rc::new(features),
1453 all_features: cli_features.all_features,
1454 uses_default_features: cli_features.uses_default_features,
1455 }
1456 }
1457
1458 fn missing_feature_spelling_suggestions(
1459 &self,
1460 selected_members: &[&Package],
1461 cli_features: &CliFeatures,
1462 found_features: &BTreeSet<FeatureValue>,
1463 ) -> Vec<String> {
1464 let mut summary_features: Vec<InternedString> = Default::default();
1466
1467 let mut dependencies_features: BTreeMap<InternedString, &[InternedString]> =
1469 Default::default();
1470
1471 let mut optional_dependency_names: Vec<InternedString> = Default::default();
1473
1474 let mut summary_features_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1476 Default::default();
1477
1478 let mut optional_dependency_names_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1480 Default::default();
1481
1482 for &member in selected_members {
1483 let summary = member.summary();
1485
1486 summary_features.extend(summary.features().keys());
1488 summary_features_per_member
1489 .insert(member, summary.features().keys().copied().collect());
1490
1491 let dependencies: BTreeMap<InternedString, &Dependency> = summary
1493 .dependencies()
1494 .iter()
1495 .map(|dep| (dep.name_in_toml(), dep))
1496 .collect();
1497
1498 dependencies_features.extend(
1499 dependencies
1500 .iter()
1501 .map(|(name, dep)| (*name, dep.features())),
1502 );
1503
1504 let optional_dependency_names_raw: BTreeSet<_> = dependencies
1506 .iter()
1507 .filter(|(_, dep)| dep.is_optional())
1508 .map(|(name, _)| name)
1509 .copied()
1510 .collect();
1511
1512 optional_dependency_names.extend(optional_dependency_names_raw.iter());
1513 optional_dependency_names_per_member.insert(member, optional_dependency_names_raw);
1514 }
1515
1516 let edit_distance_test = |a: InternedString, b: InternedString| {
1517 edit_distance(a.as_str(), b.as_str(), 3).is_some()
1518 };
1519
1520 cli_features
1521 .features
1522 .difference(found_features)
1523 .map(|feature| match feature {
1524 FeatureValue::Feature(typo) => {
1526 let summary_features = summary_features
1528 .iter()
1529 .filter(move |feature| edit_distance_test(**feature, *typo));
1530
1531 let optional_dependency_features = optional_dependency_names
1533 .iter()
1534 .filter(move |feature| edit_distance_test(**feature, *typo));
1535
1536 summary_features
1537 .chain(optional_dependency_features)
1538 .map(|s| s.to_string())
1539 .collect::<Vec<_>>()
1540 }
1541 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1542 FeatureValue::DepFeature {
1543 dep_name,
1544 dep_feature,
1545 weak: _,
1546 } => {
1547 let pkg_feat_similar = dependencies_features
1549 .iter()
1550 .filter(|(name, _)| edit_distance_test(**name, *dep_name))
1551 .map(|(name, features)| {
1552 (
1553 name,
1554 features
1555 .iter()
1556 .filter(|feature| edit_distance_test(**feature, *dep_feature))
1557 .collect::<Vec<_>>(),
1558 )
1559 })
1560 .map(|(name, features)| {
1561 features
1562 .into_iter()
1563 .map(move |feature| format!("{}/{}", name, feature))
1564 })
1565 .flatten();
1566
1567 let optional_dependency_features = optional_dependency_names_per_member
1569 .iter()
1570 .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1571 .map(|(package, optional_dependencies)| {
1572 optional_dependencies
1573 .into_iter()
1574 .filter(|optional_dependency| {
1575 edit_distance_test(**optional_dependency, *dep_name)
1576 })
1577 .map(move |optional_dependency| {
1578 format!("{}/{}", package.name(), optional_dependency)
1579 })
1580 })
1581 .flatten();
1582
1583 let summary_features = summary_features_per_member
1585 .iter()
1586 .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1587 .map(|(package, summary_features)| {
1588 summary_features
1589 .into_iter()
1590 .filter(|summary_feature| {
1591 edit_distance_test(**summary_feature, *dep_feature)
1592 })
1593 .map(move |summary_feature| {
1594 format!("{}/{}", package.name(), summary_feature)
1595 })
1596 })
1597 .flatten();
1598
1599 pkg_feat_similar
1600 .chain(optional_dependency_features)
1601 .chain(summary_features)
1602 .collect::<Vec<_>>()
1603 }
1604 })
1605 .map(|v| v.into_iter())
1606 .flatten()
1607 .unique()
1608 .filter(|element| {
1609 let feature = FeatureValue::new(element.into());
1610 !cli_features.features.contains(&feature) && !found_features.contains(&feature)
1611 })
1612 .sorted()
1613 .take(5)
1614 .collect()
1615 }
1616
1617 fn report_unknown_features_error(
1618 &self,
1619 specs: &[PackageIdSpec],
1620 cli_features: &CliFeatures,
1621 found_features: &BTreeSet<FeatureValue>,
1622 ) -> CargoResult<()> {
1623 let unknown: Vec<_> = cli_features
1624 .features
1625 .difference(found_features)
1626 .map(|feature| feature.to_string())
1627 .sorted()
1628 .collect();
1629
1630 let (selected_members, unselected_members): (Vec<_>, Vec<_>) = self
1631 .members()
1632 .partition(|member| specs.iter().any(|spec| spec.matches(member.package_id())));
1633
1634 let missing_packages_with_the_features = unselected_members
1635 .into_iter()
1636 .filter(|member| {
1637 unknown
1638 .iter()
1639 .any(|feature| member.summary().features().contains_key(&**feature))
1640 })
1641 .map(|m| m.name())
1642 .collect_vec();
1643
1644 let these_features = if unknown.len() == 1 {
1645 "this feature"
1646 } else {
1647 "these features"
1648 };
1649 let mut msg = if let [singular] = &selected_members[..] {
1650 format!(
1651 "the package '{}' does not contain {these_features}: {}",
1652 singular.name(),
1653 unknown.join(", ")
1654 )
1655 } else {
1656 let names = selected_members.iter().map(|m| m.name()).join(", ");
1657 format!(
1658 "none of the selected packages contains {these_features}: {}\nselected packages: {names}",
1659 unknown.join(", ")
1660 )
1661 };
1662
1663 use std::fmt::Write;
1664 if !missing_packages_with_the_features.is_empty() {
1665 write!(
1666 &mut msg,
1667 "\nhelp: package{} with the missing feature{}: {}",
1668 if missing_packages_with_the_features.len() != 1 {
1669 "s"
1670 } else {
1671 ""
1672 },
1673 if unknown.len() != 1 { "s" } else { "" },
1674 missing_packages_with_the_features.join(", ")
1675 )?;
1676 } else {
1677 let suggestions = self.missing_feature_spelling_suggestions(
1678 &selected_members,
1679 cli_features,
1680 found_features,
1681 );
1682 if !suggestions.is_empty() {
1683 write!(
1684 &mut msg,
1685 "\nhelp: there {}: {}",
1686 if suggestions.len() == 1 {
1687 "is a similarly named feature"
1688 } else {
1689 "are similarly named features"
1690 },
1691 suggestions.join(", ")
1692 )?;
1693 }
1694 }
1695
1696 bail!("{msg}")
1697 }
1698
1699 fn members_with_features_new(
1702 &self,
1703 specs: &[PackageIdSpec],
1704 cli_features: &CliFeatures,
1705 ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1706 let mut found_features = Default::default();
1709
1710 let members: Vec<(&Package, CliFeatures)> = self
1711 .members()
1712 .filter(|m| specs.iter().any(|spec| spec.matches(m.package_id())))
1713 .map(|m| {
1714 (
1715 m,
1716 Workspace::collect_matching_features(m, cli_features, &mut found_features),
1717 )
1718 })
1719 .collect();
1720
1721 if members.is_empty() {
1722 if !(cli_features.features.is_empty()
1725 && !cli_features.all_features
1726 && cli_features.uses_default_features)
1727 {
1728 bail!("cannot specify features for packages outside of workspace");
1729 }
1730 return Ok(self
1733 .members()
1734 .map(|m| (m, CliFeatures::new_all(false)))
1735 .collect());
1736 }
1737 if *cli_features.features != found_features {
1738 self.report_unknown_features_error(specs, cli_features, &found_features)?;
1739 }
1740 Ok(members)
1741 }
1742
1743 fn members_with_features_old(
1746 &self,
1747 specs: &[PackageIdSpec],
1748 cli_features: &CliFeatures,
1749 ) -> Vec<(&Package, CliFeatures)> {
1750 let mut member_specific_features: HashMap<InternedString, BTreeSet<FeatureValue>> =
1753 HashMap::new();
1754 let mut cwd_features = BTreeSet::new();
1756 for feature in cli_features.features.iter() {
1757 match feature {
1758 FeatureValue::Feature(_) => {
1759 cwd_features.insert(feature.clone());
1760 }
1761 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1763 FeatureValue::DepFeature {
1764 dep_name,
1765 dep_feature,
1766 weak: _,
1767 } => {
1768 let is_member = self.members().any(|member| {
1774 self.current_opt() != Some(member) && member.name() == *dep_name
1776 });
1777 if is_member && specs.iter().any(|spec| spec.name() == dep_name.as_str()) {
1778 member_specific_features
1779 .entry(*dep_name)
1780 .or_default()
1781 .insert(FeatureValue::Feature(*dep_feature));
1782 } else {
1783 cwd_features.insert(feature.clone());
1784 }
1785 }
1786 }
1787 }
1788
1789 let ms: Vec<_> = self
1790 .members()
1791 .filter_map(|member| {
1792 let member_id = member.package_id();
1793 match self.current_opt() {
1794 Some(current) if member_id == current.package_id() => {
1797 let feats = CliFeatures {
1798 features: Rc::new(cwd_features.clone()),
1799 all_features: cli_features.all_features,
1800 uses_default_features: cli_features.uses_default_features,
1801 };
1802 Some((member, feats))
1803 }
1804 _ => {
1805 if specs.iter().any(|spec| spec.matches(member_id)) {
1807 let feats = CliFeatures {
1817 features: Rc::new(
1818 member_specific_features
1819 .remove(member.name().as_str())
1820 .unwrap_or_default(),
1821 ),
1822 uses_default_features: true,
1823 all_features: cli_features.all_features,
1824 };
1825 Some((member, feats))
1826 } else {
1827 None
1829 }
1830 }
1831 }
1832 })
1833 .collect();
1834
1835 assert!(member_specific_features.is_empty());
1838
1839 ms
1840 }
1841
1842 pub fn unit_needs_doc_scrape(&self, unit: &Unit) -> bool {
1844 self.is_member(&unit.pkg) && !(unit.target.for_host() || unit.pkg.proc_macro())
1849 }
1850
1851 pub fn add_local_overlay(&mut self, id: SourceId, registry_path: PathBuf) {
1855 self.local_overlays.insert(id, registry_path);
1856 }
1857
1858 pub fn package_registry(&self) -> CargoResult<PackageRegistry<'gctx>> {
1860 let source_config =
1861 SourceConfigMap::new_with_overlays(self.gctx(), self.local_overlays()?)?;
1862 PackageRegistry::new_with_source_config(self.gctx(), source_config)
1863 }
1864
1865 fn local_overlays(&self) -> CargoResult<impl Iterator<Item = (SourceId, SourceId)>> {
1867 let mut ret = self
1868 .local_overlays
1869 .iter()
1870 .map(|(id, path)| Ok((*id, SourceId::for_local_registry(path)?)))
1871 .collect::<CargoResult<Vec<_>>>()?;
1872
1873 if let Ok(overlay) = self
1874 .gctx
1875 .get_env("__CARGO_TEST_DEPENDENCY_CONFUSION_VULNERABILITY_DO_NOT_USE_THIS")
1876 {
1877 let (url, path) = overlay.split_once('=').ok_or(anyhow::anyhow!(
1878 "invalid overlay format. I won't tell you why; you shouldn't be using it anyway"
1879 ))?;
1880 ret.push((
1881 SourceId::from_url(url)?,
1882 SourceId::for_local_registry(path.as_ref())?,
1883 ));
1884 }
1885
1886 Ok(ret.into_iter())
1887 }
1888}
1889
1890impl<'gctx> Packages<'gctx> {
1891 fn get(&self, manifest_path: &Path) -> &MaybePackage {
1892 self.maybe_get(manifest_path).unwrap()
1893 }
1894
1895 fn get_mut(&mut self, manifest_path: &Path) -> &mut MaybePackage {
1896 self.maybe_get_mut(manifest_path).unwrap()
1897 }
1898
1899 fn maybe_get(&self, manifest_path: &Path) -> Option<&MaybePackage> {
1900 self.packages.get(manifest_path)
1901 }
1902
1903 fn maybe_get_mut(&mut self, manifest_path: &Path) -> Option<&mut MaybePackage> {
1904 self.packages.get_mut(manifest_path)
1905 }
1906
1907 fn load(&mut self, manifest_path: &Path) -> CargoResult<&MaybePackage> {
1908 match self.packages.entry(manifest_path.to_path_buf()) {
1909 Entry::Occupied(e) => Ok(e.into_mut()),
1910 Entry::Vacant(v) => {
1911 let source_id = SourceId::for_manifest_path(manifest_path)?;
1912 let manifest = read_manifest(manifest_path, source_id, self.gctx)?;
1913 Ok(v.insert(match manifest {
1914 EitherManifest::Real(manifest) => {
1915 MaybePackage::Package(Package::new(manifest, manifest_path))
1916 }
1917 EitherManifest::Virtual(vm) => MaybePackage::Virtual(vm),
1918 }))
1919 }
1920 }
1921 }
1922}
1923
1924impl MaybePackage {
1925 fn workspace_config(&self) -> &WorkspaceConfig {
1926 match *self {
1927 MaybePackage::Package(ref p) => p.manifest().workspace_config(),
1928 MaybePackage::Virtual(ref vm) => vm.workspace_config(),
1929 }
1930 }
1931
1932 pub fn is_embedded(&self) -> bool {
1934 match self {
1935 MaybePackage::Package(p) => p.manifest().is_embedded(),
1936 MaybePackage::Virtual(_) => false,
1937 }
1938 }
1939
1940 pub fn contents(&self) -> &str {
1941 match self {
1942 MaybePackage::Package(p) => p.manifest().contents(),
1943 MaybePackage::Virtual(v) => v.contents(),
1944 }
1945 }
1946
1947 pub fn document(&self) -> &toml::Spanned<toml::de::DeTable<'static>> {
1948 match self {
1949 MaybePackage::Package(p) => p.manifest().document(),
1950 MaybePackage::Virtual(v) => v.document(),
1951 }
1952 }
1953
1954 pub fn edition(&self) -> Edition {
1955 match self {
1956 MaybePackage::Package(p) => p.manifest().edition(),
1957 MaybePackage::Virtual(_) => Edition::default(),
1958 }
1959 }
1960
1961 pub fn profiles(&self) -> Option<&TomlProfiles> {
1962 match self {
1963 MaybePackage::Package(p) => p.manifest().profiles(),
1964 MaybePackage::Virtual(v) => v.profiles(),
1965 }
1966 }
1967
1968 pub fn unstable_features(&self) -> &Features {
1969 match self {
1970 MaybePackage::Package(p) => p.manifest().unstable_features(),
1971 MaybePackage::Virtual(vm) => vm.unstable_features(),
1972 }
1973 }
1974}
1975
1976impl WorkspaceRootConfig {
1977 pub fn new(
1979 root_dir: &Path,
1980 members: &Option<Vec<String>>,
1981 default_members: &Option<Vec<String>>,
1982 exclude: &Option<Vec<String>>,
1983 inheritable: &Option<InheritableFields>,
1984 custom_metadata: &Option<toml::Value>,
1985 ) -> WorkspaceRootConfig {
1986 WorkspaceRootConfig {
1987 root_dir: root_dir.to_path_buf(),
1988 members: members.clone(),
1989 default_members: default_members.clone(),
1990 exclude: exclude.clone().unwrap_or_default(),
1991 inheritable_fields: inheritable.clone().unwrap_or_default(),
1992 custom_metadata: custom_metadata.clone(),
1993 }
1994 }
1995 fn is_excluded(&self, manifest_path: &Path) -> bool {
1999 let excluded = self
2000 .exclude
2001 .iter()
2002 .any(|ex| manifest_path.starts_with(self.root_dir.join(ex)));
2003
2004 let explicit_member = match self.members {
2005 Some(ref members) => members
2006 .iter()
2007 .any(|mem| manifest_path.starts_with(self.root_dir.join(mem))),
2008 None => false,
2009 };
2010
2011 !explicit_member && excluded
2012 }
2013
2014 fn has_members_list(&self) -> bool {
2015 self.members.is_some()
2016 }
2017
2018 #[tracing::instrument(skip_all)]
2021 fn members_paths<'g>(
2022 &self,
2023 globs: &'g [String],
2024 ) -> CargoResult<Vec<(PathBuf, Option<&'g str>)>> {
2025 let mut expanded_list = Vec::new();
2026
2027 for glob in globs {
2028 let pathbuf = self.root_dir.join(glob);
2029 let expanded_paths = Self::expand_member_path(&pathbuf)?;
2030
2031 if expanded_paths.is_empty() {
2034 expanded_list.push((pathbuf, None));
2035 } else {
2036 let used_glob_pattern = expanded_paths.len() > 1 || expanded_paths[0] != pathbuf;
2037 let glob = used_glob_pattern.then_some(glob.as_str());
2038
2039 for expanded_path in expanded_paths {
2045 if expanded_path.is_dir() {
2046 expanded_list.push((expanded_path, glob));
2047 }
2048 }
2049 }
2050 }
2051
2052 Ok(expanded_list)
2053 }
2054
2055 fn expand_member_path(path: &Path) -> CargoResult<Vec<PathBuf>> {
2056 let Some(path) = path.to_str() else {
2057 return Ok(Vec::new());
2058 };
2059 let res = glob(path).with_context(|| format!("could not parse pattern `{}`", &path))?;
2060 let res = res
2061 .map(|p| p.with_context(|| format!("unable to match path to pattern `{}`", &path)))
2062 .collect::<Result<Vec<_>, _>>()?;
2063 Ok(res)
2064 }
2065
2066 pub fn inheritable(&self) -> &InheritableFields {
2067 &self.inheritable_fields
2068 }
2069}
2070
2071pub fn resolve_relative_path(
2072 label: &str,
2073 old_root: &Path,
2074 new_root: &Path,
2075 rel_path: &str,
2076) -> CargoResult<String> {
2077 let joined_path = normalize_path(&old_root.join(rel_path));
2078 match diff_paths(joined_path, new_root) {
2079 None => Err(anyhow!(
2080 "`{}` was defined in {} but could not be resolved with {}",
2081 label,
2082 old_root.display(),
2083 new_root.display()
2084 )),
2085 Some(path) => Ok(path
2086 .to_str()
2087 .ok_or_else(|| {
2088 anyhow!(
2089 "`{}` resolved to non-UTF value (`{}`)",
2090 label,
2091 path.display()
2092 )
2093 })?
2094 .to_owned()),
2095 }
2096}
2097
2098pub fn find_workspace_root(
2100 manifest_path: &Path,
2101 gctx: &GlobalContext,
2102) -> CargoResult<Option<PathBuf>> {
2103 find_workspace_root_with_loader(manifest_path, gctx, |self_path| {
2104 let source_id = SourceId::for_manifest_path(self_path)?;
2105 let manifest = read_manifest(self_path, source_id, gctx)?;
2106 Ok(manifest
2107 .workspace_config()
2108 .get_ws_root(self_path, manifest_path))
2109 })
2110}
2111
2112fn find_workspace_root_with_loader(
2117 manifest_path: &Path,
2118 gctx: &GlobalContext,
2119 mut loader: impl FnMut(&Path) -> CargoResult<Option<PathBuf>>,
2120) -> CargoResult<Option<PathBuf>> {
2121 {
2123 let roots = gctx.ws_roots();
2124 for current in manifest_path.ancestors().skip(1) {
2127 if let Some(ws_config) = roots.get(current) {
2128 if !ws_config.is_excluded(manifest_path) {
2129 return Ok(Some(current.join("Cargo.toml")));
2131 }
2132 }
2133 }
2134 }
2135
2136 for ances_manifest_path in find_root_iter(manifest_path, gctx) {
2137 debug!("find_root - trying {}", ances_manifest_path.display());
2138 if let Some(ws_root_path) = loader(&ances_manifest_path)? {
2139 return Ok(Some(ws_root_path));
2140 }
2141 }
2142 Ok(None)
2143}
2144
2145fn read_root_pointer(member_manifest: &Path, root_link: &str) -> PathBuf {
2146 let path = member_manifest
2147 .parent()
2148 .unwrap()
2149 .join(root_link)
2150 .join("Cargo.toml");
2151 debug!("find_root - pointer {}", path.display());
2152 paths::normalize_path(&path)
2153}
2154
2155fn find_root_iter<'a>(
2156 manifest_path: &'a Path,
2157 gctx: &'a GlobalContext,
2158) -> impl Iterator<Item = PathBuf> + 'a {
2159 LookBehind::new(paths::ancestors(manifest_path, None).skip(2))
2160 .take_while(|path| !path.curr.ends_with("target/package"))
2161 .take_while(|path| {
2167 if let Some(last) = path.last {
2168 gctx.home() != last
2169 } else {
2170 true
2171 }
2172 })
2173 .map(|path| path.curr.join("Cargo.toml"))
2174 .filter(|ances_manifest_path| ances_manifest_path.exists())
2175}
2176
2177struct LookBehindWindow<'a, T: ?Sized> {
2178 curr: &'a T,
2179 last: Option<&'a T>,
2180}
2181
2182struct LookBehind<'a, T: ?Sized, K: Iterator<Item = &'a T>> {
2183 iter: K,
2184 last: Option<&'a T>,
2185}
2186
2187impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> LookBehind<'a, T, K> {
2188 fn new(items: K) -> Self {
2189 Self {
2190 iter: items,
2191 last: None,
2192 }
2193 }
2194}
2195
2196impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> Iterator for LookBehind<'a, T, K> {
2197 type Item = LookBehindWindow<'a, T>;
2198
2199 fn next(&mut self) -> Option<Self::Item> {
2200 match self.iter.next() {
2201 None => None,
2202 Some(next) => {
2203 let last = self.last;
2204 self.last = Some(next);
2205 Some(LookBehindWindow { curr: next, last })
2206 }
2207 }
2208 }
2209}