1use crate::util::data_structures::{HashMap, HashSet, IndexSet};
2use std::cell::RefCell;
3use std::collections::hash_map::Entry;
4use std::collections::{BTreeMap, BTreeSet};
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8use anyhow::{Context as _, anyhow, bail};
9use cargo_util_terminal::report::Level;
10use glob::glob;
11use itertools::Itertools;
12use tracing::debug;
13use url::Url;
14
15use crate::compiler::Unit;
16use crate::context;
17use crate::context::{
18 CargoResolverConfig, ConfigRelativePath, FeatureUnification, IncompatibleRustVersions, Value,
19};
20use crate::ops;
21use crate::ops::lockfile::LOCKFILE_NAME;
22use crate::resolver::ResolveBehavior;
23use crate::resolver::features::CliFeatures;
24use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY, PathSource, SourceConfigMap};
25use crate::util::edit_distance;
26use crate::util::errors::{CargoResult, ManifestError};
27use crate::util::interning::InternedString;
28use crate::util::{Filesystem, GlobalContext, IntoUrl, closest_msg};
29use crate::workspace::features::Features;
30use crate::workspace::parser::{InheritableFields, read_manifest};
31use crate::workspace::registry::PackageRegistry;
32use crate::workspace::{
33 Dependency, Edition, Feature, FeatureValue, PackageId, PackageIdSpec, PackageIdSpecQuery,
34 Patch, PatchLocation,
35};
36use crate::workspace::{EitherManifest, Package, SourceId, VirtualManifest};
37
38use cargo_util::paths;
39use cargo_util::paths::normalize_path;
40use cargo_util_schemas::manifest::RustVersion;
41use cargo_util_schemas::manifest::{TomlDependency, TomlManifest, TomlProfiles};
42use pathdiff::diff_paths;
43
44#[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: IndexSet<PathBuf>,
85 member_ids: HashSet<PackageId>,
87
88 default_members: Vec<PathBuf>,
99
100 is_ephemeral: bool,
103
104 require_optional_deps: bool,
109
110 loaded_packages: RefCell<HashMap<PathBuf, Package>>,
113
114 requested_lockfile_path: Option<PathBuf>,
116
117 resolve_behavior: ResolveBehavior,
119 resolve_honors_rust_version: bool,
123 resolve_feature_unification: FeatureUnification,
125 resolve_honors_publish_age: bool,
127 resolve_publish_time: Option<jiff::Timestamp>,
129 custom_metadata: Option<toml::Value>,
131
132 local_overlays: HashMap<SourceId, PathBuf>,
134}
135
136#[derive(Debug)]
139struct Packages<'gctx> {
140 gctx: &'gctx GlobalContext,
141 packages: HashMap<PathBuf, MaybePackage>,
142}
143
144#[derive(Debug)]
145pub enum MaybePackage {
146 Package(Package),
147 Virtual(VirtualManifest),
148}
149
150#[derive(Debug, Clone)]
152pub enum WorkspaceConfig {
153 Root(WorkspaceRootConfig),
156
157 Member { root: Option<String> },
160}
161
162impl WorkspaceConfig {
163 pub fn inheritable(&self) -> Option<&InheritableFields> {
164 match self {
165 WorkspaceConfig::Root(root) => Some(&root.inheritable_fields),
166 WorkspaceConfig::Member { .. } => None,
167 }
168 }
169
170 fn get_ws_root(&self, self_path: &Path, look_from: &Path) -> Option<PathBuf> {
178 match self {
179 WorkspaceConfig::Root(ances_root_config) => {
180 debug!("find_root - found a root checking exclusion");
181 if !ances_root_config.is_excluded(look_from) {
182 debug!("find_root - found!");
183 Some(self_path.to_owned())
184 } else {
185 None
186 }
187 }
188 WorkspaceConfig::Member {
189 root: Some(path_to_root),
190 } => {
191 debug!("find_root - found pointer");
192 Some(read_root_pointer(self_path, path_to_root))
193 }
194 WorkspaceConfig::Member { .. } => None,
195 }
196 }
197}
198
199#[derive(Debug, Clone)]
204pub struct WorkspaceRootConfig {
205 root_dir: PathBuf,
206 members: Option<Vec<String>>,
207 default_members: Option<Vec<String>>,
208 exclude: Vec<String>,
209 inheritable_fields: InheritableFields,
210 custom_metadata: Option<toml::Value>,
211}
212
213impl<'gctx> Workspace<'gctx> {
214 pub fn new(manifest_path: &Path, gctx: &'gctx GlobalContext) -> CargoResult<Workspace<'gctx>> {
221 let mut ws = Workspace::new_default(manifest_path.to_path_buf(), gctx);
222
223 if manifest_path.is_relative() {
224 bail!(
225 "manifest_path:{:?} is not an absolute path. Please provide an absolute path.",
226 manifest_path
227 )
228 } else {
229 ws.root_manifest = ws.find_root(manifest_path)?;
230 }
231
232 ws.target_dir = gctx.target_dir()?;
233 ws.build_dir = gctx.build_dir(ws.root_manifest())?;
234
235 ws.custom_metadata = ws
236 .load_workspace_config()?
237 .and_then(|cfg| cfg.custom_metadata);
238 ws.find_members()?;
239 ws.set_resolve_behavior()?;
240 ws.validate()?;
241 Ok(ws)
242 }
243
244 fn new_default(current_manifest: PathBuf, gctx: &'gctx GlobalContext) -> Workspace<'gctx> {
245 Workspace {
246 gctx,
247 current_manifest,
248 packages: Packages {
249 gctx,
250 packages: HashMap::default(),
251 },
252 root_manifest: None,
253 target_dir: None,
254 build_dir: None,
255 members: IndexSet::default(),
256 member_ids: HashSet::default(),
257 default_members: Vec::new(),
258 is_ephemeral: false,
259 require_optional_deps: true,
260 loaded_packages: RefCell::new(HashMap::default()),
261 requested_lockfile_path: None,
262 resolve_behavior: ResolveBehavior::V1,
263 resolve_honors_rust_version: false,
264 resolve_feature_unification: FeatureUnification::Selected,
265 resolve_honors_publish_age: true,
266 resolve_publish_time: None,
267 custom_metadata: None,
268 local_overlays: HashMap::default(),
269 }
270 }
271
272 pub fn ephemeral(
282 package: Package,
283 gctx: &'gctx GlobalContext,
284 target_dir: Option<Filesystem>,
285 require_optional_deps: bool,
286 ) -> CargoResult<Workspace<'gctx>> {
287 let mut ws = Workspace::new_default(package.manifest_path().to_path_buf(), gctx);
288 ws.is_ephemeral = true;
289 ws.require_optional_deps = require_optional_deps;
290 let id = package.package_id();
291 let package = MaybePackage::Package(package);
292 ws.packages
293 .packages
294 .insert(ws.current_manifest.clone(), package);
295 ws.target_dir = if let Some(dir) = target_dir {
296 Some(dir)
297 } else {
298 ws.gctx.target_dir()?
299 };
300 ws.build_dir = ws.target_dir.clone();
301 ws.members.insert(ws.current_manifest.clone());
302 ws.member_ids.insert(id);
303 ws.default_members.push(ws.current_manifest.clone());
304 ws.set_resolve_behavior()?;
305 Ok(ws)
306 }
307
308 pub fn reload(&self, gctx: &'gctx GlobalContext) -> CargoResult<Workspace<'gctx>> {
313 let mut ws = Workspace::new(&self.current_manifest, gctx)?;
314 ws.set_resolve_honors_rust_version(Some(self.resolve_honors_rust_version));
315 ws.set_resolve_feature_unification(self.resolve_feature_unification);
316 ws.set_requested_lockfile_path(self.requested_lockfile_path.clone());
317 Ok(ws)
318 }
319
320 fn set_resolve_behavior(&mut self) -> CargoResult<()> {
321 self.resolve_behavior = match self.root_maybe() {
326 MaybePackage::Package(p) => p
327 .manifest()
328 .resolve_behavior()
329 .unwrap_or_else(|| p.manifest().edition().default_resolve_behavior()),
330 MaybePackage::Virtual(vm) => vm.resolve_behavior().unwrap_or(ResolveBehavior::V1),
331 };
332
333 match self.resolve_behavior() {
334 ResolveBehavior::V1 | ResolveBehavior::V2 => {}
335 ResolveBehavior::V3 => {
336 if self.resolve_behavior == ResolveBehavior::V3 {
337 self.resolve_honors_rust_version = true;
338 }
339 }
340 }
341 let config = self.gctx().get::<CargoResolverConfig>(["resolver"])?;
342 if let Some(incompatible_rust_versions) = config.incompatible_rust_versions {
343 self.resolve_honors_rust_version =
344 incompatible_rust_versions == IncompatibleRustVersions::Fallback;
345 }
346 if self.gctx().cli_unstable().feature_unification {
347 self.resolve_feature_unification = config
348 .feature_unification
349 .unwrap_or(FeatureUnification::Selected);
350 } else if config.feature_unification.is_some() {
351 self.gctx()
352 .shell()
353 .warn("ignoring `resolver.feature-unification` without `-Zfeature-unification`")?;
354 };
355
356 if let Some(lockfile_path) = config.lockfile_path {
357 let replacements: [(&str, &str); 0] = [];
359 let path = lockfile_path
360 .resolve_templated_path(self.gctx(), replacements)
361 .map_err(|e| match e {
362 context::ResolveTemplateError::UnexpectedVariable {
363 variable,
364 raw_template,
365 } => {
366 anyhow!(
367 "unexpected variable `{variable}` in resolver.lockfile-path `{raw_template}`"
368 )
369 }
370 context::ResolveTemplateError::UnexpectedBracket { bracket_type, raw_template } => {
371 let (btype, literal) = match bracket_type {
372 context::BracketType::Opening => ("opening", "{"),
373 context::BracketType::Closing => ("closing", "}"),
374 };
375
376 anyhow!(
377 "unexpected {btype} bracket `{literal}` in build.build-dir path `{raw_template}`"
378 )
379 }
380 })?;
381 if !path.ends_with(LOCKFILE_NAME) {
382 bail!("the `resolver.lockfile-path` must be a path to a {LOCKFILE_NAME} file");
383 }
384 if path.is_dir() {
385 bail!(
386 "`resolver.lockfile-path` `{}` is a directory but expected a file",
387 path.display()
388 );
389 }
390 self.requested_lockfile_path = Some(path);
391 }
392
393 Ok(())
394 }
395
396 pub fn current(&self) -> CargoResult<&Package> {
402 let pkg = self.current_opt().ok_or_else(|| {
403 anyhow::format_err!(
404 "manifest path `{}` is a virtual manifest, but this \
405 command requires running against an actual package in \
406 this workspace",
407 self.current_manifest.display()
408 )
409 })?;
410 Ok(pkg)
411 }
412
413 pub fn current_mut(&mut self) -> CargoResult<&mut Package> {
414 let cm = self.current_manifest.clone();
415 let pkg = self.current_opt_mut().ok_or_else(|| {
416 anyhow::format_err!(
417 "manifest path `{}` is a virtual manifest, but this \
418 command requires running against an actual package in \
419 this workspace",
420 cm.display()
421 )
422 })?;
423 Ok(pkg)
424 }
425
426 pub fn current_opt(&self) -> Option<&Package> {
427 match *self.packages.get(&self.current_manifest) {
428 MaybePackage::Package(ref p) => Some(p),
429 MaybePackage::Virtual(..) => None,
430 }
431 }
432
433 pub fn current_opt_mut(&mut self) -> Option<&mut Package> {
434 match *self.packages.get_mut(&self.current_manifest) {
435 MaybePackage::Package(ref mut p) => Some(p),
436 MaybePackage::Virtual(..) => None,
437 }
438 }
439
440 pub fn is_virtual(&self) -> bool {
441 match *self.packages.get(&self.current_manifest) {
442 MaybePackage::Package(..) => false,
443 MaybePackage::Virtual(..) => true,
444 }
445 }
446
447 pub fn gctx(&self) -> &'gctx GlobalContext {
449 self.gctx
450 }
451
452 pub fn profiles(&self) -> Option<&TomlProfiles> {
453 self.root_maybe().profiles()
454 }
455
456 pub fn root(&self) -> &Path {
461 self.root_manifest().parent().unwrap()
462 }
463
464 pub fn root_manifest(&self) -> &Path {
467 self.root_manifest
468 .as_ref()
469 .unwrap_or(&self.current_manifest)
470 }
471
472 pub fn root_maybe(&self) -> &MaybePackage {
474 self.packages.get(self.root_manifest())
475 }
476
477 pub fn target_dir(&self) -> Filesystem {
478 self.target_dir
479 .clone()
480 .unwrap_or_else(|| self.default_target_dir())
481 }
482
483 pub fn build_dir(&self) -> Filesystem {
484 self.build_dir
485 .clone()
486 .or_else(|| self.target_dir.clone())
487 .unwrap_or_else(|| self.default_build_dir())
488 }
489
490 fn default_target_dir(&self) -> Filesystem {
491 if self.root_maybe().is_embedded() {
492 self.build_dir().join("target")
493 } else {
494 Filesystem::new(self.root().join("target"))
495 }
496 }
497
498 fn default_build_dir(&self) -> Filesystem {
499 if self.root_maybe().is_embedded() {
500 let default = ConfigRelativePath::new(
501 "{cargo-cache-home}/build/{workspace-path-hash}"
502 .to_owned()
503 .into(),
504 );
505 self.gctx()
506 .custom_build_dir(&default, self.root_manifest())
507 .expect("template is correct")
508 } else {
509 self.default_target_dir()
510 }
511 }
512
513 pub fn root_replace(&self) -> &[(PackageIdSpec, Dependency)] {
517 match self.root_maybe() {
518 MaybePackage::Package(p) => p.manifest().replace(),
519 MaybePackage::Virtual(vm) => vm.replace(),
520 }
521 }
522
523 fn config_patch(&self) -> CargoResult<HashMap<Url, Vec<Patch>>> {
524 let config_patch: Option<
525 BTreeMap<String, BTreeMap<String, Value<TomlDependency<ConfigRelativePath>>>>,
526 > = self.gctx.get(["patch"])?;
527
528 let source = SourceId::for_manifest_path(self.root_manifest())?;
529
530 let mut warnings = Vec::new();
531
532 let mut patch = HashMap::default();
533 for (url, deps) in config_patch.into_iter().flatten() {
534 let url = match &url[..] {
535 CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
536 url => self
537 .gctx
538 .get_registry_index(url)
539 .or_else(|_| url.into_url())
540 .with_context(|| {
541 format!("[patch] entry `{}` should be a URL or registry name", url)
542 })?,
543 };
544 patch.insert(
545 url,
546 deps.iter()
547 .map(|(name, dependency_cv)| {
548 if let TomlDependency::Detailed(d) = &dependency_cv.val {
549 if d.builtin {
550 self.unstable_features()
551 .require(Feature::builtin_dependencies())
552 .with_context(|| format!("invalid patch for `{name}`"))?;
553 }
554 }
555 crate::workspace::parser::config_patch_to_dependency(
556 &dependency_cv.val,
557 name,
558 source,
559 self.gctx,
560 &mut warnings,
561 )
562 .map(|dep| Patch {
563 dep,
564 loc: PatchLocation::Config(dependency_cv.definition.clone()),
565 })
566 })
567 .collect::<CargoResult<Vec<_>>>()?,
568 );
569 }
570
571 for message in warnings {
572 self.gctx
573 .shell()
574 .warn(format!("[patch] in cargo config: {}", message))?
575 }
576
577 Ok(patch)
578 }
579
580 pub fn root_patch(&self) -> CargoResult<HashMap<Url, Vec<Patch>>> {
584 let from_manifest = match self.root_maybe() {
585 MaybePackage::Package(p) => p.manifest().patch(),
586 MaybePackage::Virtual(vm) => vm.patch(),
587 };
588
589 let from_config = self.config_patch()?;
590 if from_config.is_empty() {
591 return Ok(from_manifest.clone());
592 }
593 if from_manifest.is_empty() {
594 return Ok(from_config);
595 }
596
597 let mut combined = from_config;
600 for (url, deps_from_manifest) in from_manifest {
601 if let Some(deps_from_config) = combined.get_mut(url) {
602 let mut from_manifest_pruned = deps_from_manifest.clone();
605 for dep_from_config in &mut *deps_from_config {
606 if let Some(i) = from_manifest_pruned.iter().position(|dep_from_manifest| {
607 dep_from_config.dep.name_in_toml() == dep_from_manifest.dep.name_in_toml()
609 }) {
610 from_manifest_pruned.swap_remove(i);
611 }
612 }
613 deps_from_config.extend(from_manifest_pruned);
615 } else {
616 combined.insert(url.clone(), deps_from_manifest.clone());
617 }
618 }
619 Ok(combined)
620 }
621
622 pub fn loaded_maybe(&self) -> impl Iterator<Item = &MaybePackage> {
624 self.packages.packages.values()
625 }
626
627 pub fn members(&self) -> impl Iterator<Item = &Package> {
629 let packages = &self.packages;
630 self.members
631 .iter()
632 .filter_map(move |path| match packages.get(path) {
633 MaybePackage::Package(p) => Some(p),
634 _ => None,
635 })
636 }
637
638 pub fn members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
640 let packages = &mut self.packages.packages;
641 let members: HashSet<_> = self.members.iter().map(|path| path).collect();
642
643 packages.iter_mut().filter_map(move |(path, package)| {
644 if members.contains(path) {
645 if let MaybePackage::Package(p) = package {
646 return Some(p);
647 }
648 }
649
650 None
651 })
652 }
653
654 pub fn default_members<'a>(&'a self) -> impl Iterator<Item = &'a Package> {
656 let packages = &self.packages;
657 self.default_members
658 .iter()
659 .filter_map(move |path| match packages.get(path) {
660 MaybePackage::Package(p) => Some(p),
661 _ => None,
662 })
663 }
664
665 pub fn default_members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
667 let packages = &mut self.packages.packages;
668 let members: HashSet<_> = self
669 .default_members
670 .iter()
671 .map(|path| path.parent().unwrap().to_owned())
672 .collect();
673
674 packages.iter_mut().filter_map(move |(path, package)| {
675 if members.contains(path) {
676 if let MaybePackage::Package(p) = package {
677 return Some(p);
678 }
679 }
680
681 None
682 })
683 }
684
685 pub fn is_member(&self, pkg: &Package) -> bool {
687 self.member_ids.contains(&pkg.package_id())
688 }
689
690 pub fn is_member_id(&self, package_id: PackageId) -> bool {
692 self.member_ids.contains(&package_id)
693 }
694
695 pub fn is_ephemeral(&self) -> bool {
696 self.is_ephemeral
697 }
698
699 pub fn require_optional_deps(&self) -> bool {
700 self.require_optional_deps
701 }
702
703 pub fn set_require_optional_deps(
704 &mut self,
705 require_optional_deps: bool,
706 ) -> &mut Workspace<'gctx> {
707 self.require_optional_deps = require_optional_deps;
708 self
709 }
710
711 pub fn lock_root(&self) -> Filesystem {
713 if let Some(requested) = self.requested_lockfile_path.as_ref() {
714 return Filesystem::new(
715 requested
716 .parent()
717 .expect("Lockfile path can't be root")
718 .to_owned(),
719 );
720 }
721 self.default_lock_root()
722 }
723
724 fn default_lock_root(&self) -> Filesystem {
725 if self.root_maybe().is_embedded() {
726 let workspace_manifest_path = self.root_manifest();
729 let real_path = std::fs::canonicalize(workspace_manifest_path)
730 .unwrap_or_else(|_err| workspace_manifest_path.to_owned());
731 let hash = crate::util::hex::short_hash(&real_path);
732 self.build_dir().join(hash)
733 } else {
734 Filesystem::new(self.root().to_owned())
735 }
736 }
737
738 pub fn set_requested_lockfile_path(&mut self, path: Option<PathBuf>) {
740 self.requested_lockfile_path = path;
741 }
742
743 pub fn requested_lockfile_path(&self) -> Option<&Path> {
744 self.requested_lockfile_path.as_deref()
745 }
746
747 pub fn lowest_rust_version(&self) -> Option<&RustVersion> {
750 self.members().filter_map(|pkg| pkg.rust_version()).min()
751 }
752
753 pub fn set_resolve_honors_rust_version(&mut self, honor_rust_version: Option<bool>) {
754 if let Some(honor_rust_version) = honor_rust_version {
755 self.resolve_honors_rust_version = honor_rust_version;
756 }
757 }
758
759 pub fn resolve_honors_rust_version(&self) -> bool {
760 self.resolve_honors_rust_version
761 }
762
763 pub fn set_resolve_honors_publish_age(&mut self, honor_publish_age: bool) {
764 self.resolve_honors_publish_age = honor_publish_age;
765 }
766
767 pub fn resolve_honors_publish_age(&self) -> bool {
768 self.resolve_honors_publish_age
769 }
770
771 pub fn set_resolve_feature_unification(&mut self, feature_unification: FeatureUnification) {
772 self.resolve_feature_unification = feature_unification;
773 }
774
775 pub fn resolve_feature_unification(&self) -> FeatureUnification {
776 self.resolve_feature_unification
777 }
778
779 pub fn set_resolve_publish_time(&mut self, publish_time: jiff::Timestamp) {
780 self.resolve_publish_time = Some(publish_time);
781 }
782
783 pub fn resolve_publish_time(&self) -> Option<jiff::Timestamp> {
784 self.resolve_publish_time
785 }
786
787 pub fn custom_metadata(&self) -> Option<&toml::Value> {
788 self.custom_metadata.as_ref()
789 }
790
791 pub fn load_workspace_config(&mut self) -> CargoResult<Option<WorkspaceRootConfig>> {
792 if let Some(root_path) = &self.root_manifest {
795 let root_package = self.packages.load(root_path)?;
796 match root_package.workspace_config() {
797 WorkspaceConfig::Root(root_config) => {
798 return Ok(Some(root_config.clone()));
799 }
800
801 _ => bail!(
802 "root of a workspace inferred but wasn't a root: {}",
803 root_path.display()
804 ),
805 }
806 }
807
808 Ok(None)
809 }
810
811 fn find_root(&mut self, manifest_path: &Path) -> CargoResult<Option<PathBuf>> {
821 let current = self.packages.load(manifest_path)?;
822 match current
823 .workspace_config()
824 .get_ws_root(manifest_path, manifest_path)
825 {
826 Some(root_path) => {
827 debug!("find_root - is root {}", manifest_path.display());
828 Ok(Some(root_path))
829 }
830 None => find_workspace_root_with_loader(manifest_path, self.gctx, |self_path| {
831 Ok(self
832 .packages
833 .load(self_path)?
834 .workspace_config()
835 .get_ws_root(self_path, manifest_path))
836 }),
837 }
838 }
839
840 #[tracing::instrument(skip_all)]
848 fn find_members(&mut self) -> CargoResult<()> {
849 let Some(workspace_config) = self.load_workspace_config()? else {
850 debug!("find_members - only me as a member");
851 self.members.insert(self.current_manifest.clone());
852 self.default_members.push(self.current_manifest.clone());
853 if let Ok(pkg) = self.current() {
854 let id = pkg.package_id();
855 self.member_ids.insert(id);
856 }
857 return Ok(());
858 };
859
860 let root_manifest_path = self.root_manifest.clone().unwrap();
862
863 let members_paths = workspace_config
864 .members_paths(workspace_config.members.as_deref().unwrap_or_default())?;
865 let default_members_paths = if root_manifest_path == self.current_manifest {
866 if let Some(ref default) = workspace_config.default_members {
867 Some(workspace_config.members_paths(default)?)
868 } else {
869 None
870 }
871 } else {
872 None
873 };
874
875 for (path, glob) in &members_paths {
876 self.find_path_deps(&path.join("Cargo.toml"), &root_manifest_path, false)
877 .with_context(|| {
878 format!(
879 "failed to load manifest for workspace member `{}`\n\
880 referenced{} by workspace at `{}`",
881 path.display(),
882 glob.map(|g| format!(" via `{g}`")).unwrap_or_default(),
883 root_manifest_path.display(),
884 )
885 })?;
886 }
887
888 self.find_path_deps(&root_manifest_path, &root_manifest_path, false)?;
889
890 if let Some(default) = default_members_paths {
891 for (path, default_member_glob) in default {
892 let normalized_path = paths::normalize_path(&path);
893 let manifest_path = normalized_path.join("Cargo.toml");
894 if !self.members.contains(&manifest_path) {
895 let exclude = members_paths.iter().any(|(m, _)| *m == normalized_path)
902 && workspace_config.is_excluded(&normalized_path);
903 if exclude {
904 continue;
905 }
906 bail!(
907 "package `{}` is listed in default-members{} but is not a member\n\
908 for workspace at `{}`.",
909 path.display(),
910 default_member_glob
911 .map(|g| format!(" via `{g}`"))
912 .unwrap_or_default(),
913 root_manifest_path.display(),
914 )
915 }
916 self.default_members.push(manifest_path)
917 }
918 } else if self.is_virtual() {
919 self.default_members = self.members.iter().cloned().collect();
920 } else {
921 self.default_members.push(self.current_manifest.clone())
922 }
923
924 Ok(())
925 }
926
927 fn find_path_deps(
928 &mut self,
929 manifest_path: &Path,
930 root_manifest: &Path,
931 is_path_dep: bool,
932 ) -> CargoResult<()> {
933 let manifest_path = paths::normalize_path(manifest_path);
934 if self.members.contains(&manifest_path) {
935 return Ok(());
936 }
937 if is_path_dep && self.root_maybe().is_embedded() {
938 return Ok(());
940 }
941 if is_path_dep
942 && !manifest_path.parent().unwrap().starts_with(self.root())
943 && self.find_root(&manifest_path)? != self.root_manifest
944 {
945 return Ok(());
948 }
949
950 if let WorkspaceConfig::Root(ref root_config) =
951 *self.packages.load(root_manifest)?.workspace_config()
952 {
953 if root_config.is_excluded(&manifest_path) {
954 return Ok(());
955 }
956 }
957
958 debug!("find_path_deps - {}", manifest_path.display());
959 self.members.insert(manifest_path.clone());
960
961 let candidates = {
962 let pkg = match *self.packages.load(&manifest_path)? {
963 MaybePackage::Package(ref p) => p,
964 MaybePackage::Virtual(_) => return Ok(()),
965 };
966 self.member_ids.insert(pkg.package_id());
967 pkg.dependencies()
968 .iter()
969 .map(|d| (d.source_id(), d.package_name()))
970 .filter(|(s, _)| s.is_path())
971 .filter_map(|(s, n)| s.url().to_file_path().ok().map(|p| (p, n)))
972 .map(|(p, n)| (p.join("Cargo.toml"), n))
973 .collect::<Vec<_>>()
974 };
975 for (path, name) in candidates {
976 self.find_path_deps(&path, root_manifest, true)
977 .with_context(|| format!("failed to load manifest for dependency `{}`", name))
978 .map_err(|err| ManifestError::new(err, manifest_path.clone()))?;
979 }
980 Ok(())
981 }
982
983 pub fn unstable_features(&self) -> &Features {
985 self.root_maybe().unstable_features()
986 }
987
988 pub fn resolve_behavior(&self) -> ResolveBehavior {
989 self.resolve_behavior
990 }
991
992 pub fn allows_new_cli_feature_behavior(&self) -> bool {
1000 self.is_virtual()
1001 || match self.resolve_behavior() {
1002 ResolveBehavior::V1 => false,
1003 ResolveBehavior::V2 | ResolveBehavior::V3 => true,
1004 }
1005 }
1006
1007 #[tracing::instrument(skip_all)]
1013 fn validate(&mut self) -> CargoResult<()> {
1014 if self.root_manifest.is_none() {
1016 return Ok(());
1017 }
1018
1019 self.validate_unique_names()?;
1020 self.validate_workspace_roots()?;
1021 self.validate_members()?;
1022 self.error_if_manifest_not_in_members()?;
1023 self.validate_manifest()
1024 }
1025
1026 fn validate_unique_names(&self) -> CargoResult<()> {
1027 let mut names = BTreeMap::new();
1028 for member in self.members.iter() {
1029 let package = self.packages.get(member);
1030 let name = match *package {
1031 MaybePackage::Package(ref p) => p.name(),
1032 MaybePackage::Virtual(_) => continue,
1033 };
1034 if let Some(prev) = names.insert(name, member) {
1035 bail!(
1036 "two packages named `{}` in this workspace:\n\
1037 - {}\n\
1038 - {}",
1039 name,
1040 prev.display(),
1041 member.display()
1042 );
1043 }
1044 }
1045 Ok(())
1046 }
1047
1048 fn validate_workspace_roots(&self) -> CargoResult<()> {
1049 let roots: Vec<PathBuf> = self
1050 .members
1051 .iter()
1052 .filter(|&member| {
1053 let config = self.packages.get(member).workspace_config();
1054 matches!(config, WorkspaceConfig::Root(_))
1055 })
1056 .map(|member| member.parent().unwrap().to_path_buf())
1057 .collect();
1058 match roots.len() {
1059 1 => Ok(()),
1060 0 => bail!(
1061 "`package.workspace` configuration points to a crate \
1062 which is not configured with [workspace]: \n\
1063 configuration at: {}\n\
1064 points to: {}",
1065 self.current_manifest.display(),
1066 self.root_manifest.as_ref().unwrap().display()
1067 ),
1068 _ => {
1069 bail!(
1070 "multiple workspace roots found in the same workspace:\n{}",
1071 roots
1072 .iter()
1073 .map(|r| format!(" {}", r.display()))
1074 .collect::<Vec<_>>()
1075 .join("\n")
1076 );
1077 }
1078 }
1079 }
1080
1081 #[tracing::instrument(skip_all)]
1082 fn validate_members(&mut self) -> CargoResult<()> {
1083 for member in self.members.clone() {
1084 let root = self.find_root(&member)?;
1085 if root == self.root_manifest {
1086 continue;
1087 }
1088
1089 match root {
1090 Some(root) => {
1091 bail!(
1092 "package `{}` is a member of the wrong workspace\n\
1093 expected: {}\n\
1094 actual: {}",
1095 member.display(),
1096 self.root_manifest.as_ref().unwrap().display(),
1097 root.display()
1098 );
1099 }
1100 None => {
1101 bail!(
1102 "workspace member `{}` is not hierarchically below \
1103 the workspace root `{}`",
1104 member.display(),
1105 self.root_manifest.as_ref().unwrap().display()
1106 );
1107 }
1108 }
1109 }
1110 Ok(())
1111 }
1112
1113 fn error_if_manifest_not_in_members(&mut self) -> CargoResult<()> {
1114 if self.members.contains(&self.current_manifest) {
1115 return Ok(());
1116 }
1117
1118 let root = self.root_manifest.as_ref().unwrap();
1119 let root_dir = root.parent().unwrap();
1120 let current_dir = self.current_manifest.parent().unwrap();
1121 let root_pkg = self.packages.get(root);
1122
1123 let current_dir = paths::normalize_path(current_dir);
1129 let root_dir = paths::normalize_path(root_dir);
1130 let members_msg = match pathdiff::diff_paths(¤t_dir, &root_dir) {
1131 Some(rel) => format!(
1132 "this may be fixable by adding `{}` to the \
1133 `workspace.members` array of the manifest \
1134 located at: {}",
1135 rel.display(),
1136 root.display()
1137 ),
1138 None => format!(
1139 "this may be fixable by adding a member to \
1140 the `workspace.members` array of the \
1141 manifest located at: {}",
1142 root.display()
1143 ),
1144 };
1145 let extra = match *root_pkg {
1146 MaybePackage::Virtual(_) => members_msg,
1147 MaybePackage::Package(ref p) => {
1148 let has_members_list = match *p.manifest().workspace_config() {
1149 WorkspaceConfig::Root(ref root_config) => root_config.has_members_list(),
1150 WorkspaceConfig::Member { .. } => unreachable!(),
1151 };
1152 if !has_members_list {
1153 format!(
1154 "this may be fixable by ensuring that this \
1155 crate is depended on by the workspace \
1156 root: {}",
1157 root.display()
1158 )
1159 } else {
1160 members_msg
1161 }
1162 }
1163 };
1164 bail!(
1165 "current package believes it's in a workspace when it's not:\n\
1166 current: {}\n\
1167 workspace: {}\n\n{}\n\
1168 Alternatively, to keep it out of the workspace, add the package \
1169 to the `workspace.exclude` array, or add an empty `[workspace]` \
1170 table to the package's manifest.",
1171 self.current_manifest.display(),
1172 root.display(),
1173 extra
1174 );
1175 }
1176
1177 fn validate_manifest(&mut self) -> CargoResult<()> {
1178 if let Some(ref root_manifest) = self.root_manifest {
1179 for pkg in self
1180 .members()
1181 .filter(|p| p.manifest_path() != root_manifest)
1182 {
1183 let manifest = pkg.manifest();
1184 let emit_warning = |what| -> CargoResult<()> {
1185 let msg = format!(
1186 "{} for the non root package will be ignored, \
1187 specify {} at the workspace root:\n\
1188 package: {}\n\
1189 workspace: {}",
1190 what,
1191 what,
1192 pkg.manifest_path().display(),
1193 root_manifest.display(),
1194 );
1195 self.gctx.shell().warn(&msg)
1196 };
1197 if manifest.normalized_toml().has_profiles() {
1198 emit_warning("profiles")?;
1199 }
1200 if !manifest.replace().is_empty() {
1201 emit_warning("replace")?;
1202 }
1203 if !manifest.patch().is_empty() {
1204 emit_warning("patch")?;
1205 }
1206 if let Some(behavior) = manifest.resolve_behavior() {
1207 if behavior != self.resolve_behavior {
1208 emit_warning("resolver")?;
1210 }
1211 }
1212 }
1213 if let MaybePackage::Virtual(vm) = self.root_maybe() {
1214 if vm.resolve_behavior().is_none() {
1215 if let Some(edition) = self
1216 .members()
1217 .filter(|p| p.manifest_path() != root_manifest)
1218 .map(|p| p.manifest().edition())
1219 .filter(|&e| e >= Edition::Edition2021)
1220 .max()
1221 {
1222 let resolver = edition.default_resolve_behavior().to_manifest();
1223 let report = &[Level::WARNING
1224 .primary_title(format!(
1225 "virtual workspace defaulting to `resolver = \"1\"` despite one or more workspace members being on edition {edition} which implies `resolver = \"{resolver}\"`"
1226 ))
1227 .elements([
1228 Level::NOTE.message("to keep the current resolver, specify `workspace.resolver = \"1\"` in the workspace root's manifest"),
1229 Level::NOTE.message(
1230 format!("to use the edition {edition} resolver, specify `workspace.resolver = \"{resolver}\"` in the workspace root's manifest"),
1231 ),
1232 Level::NOTE.message("for more details see https://doc.rust-lang.org/cargo/reference/resolver.html#resolver-versions"),
1233 ])];
1234 self.gctx.shell().print_report(report, false)?;
1235 }
1236 }
1237 }
1238 }
1239 Ok(())
1240 }
1241
1242 pub fn load(&self, manifest_path: &Path) -> CargoResult<Package> {
1243 match self.packages.maybe_get(manifest_path) {
1244 Some(MaybePackage::Package(p)) => return Ok(p.clone()),
1245 Some(&MaybePackage::Virtual(_)) => bail!("cannot load workspace root"),
1246 None => {}
1247 }
1248
1249 let mut loaded = self.loaded_packages.borrow_mut();
1250 if let Some(p) = loaded.get(manifest_path).cloned() {
1251 return Ok(p);
1252 }
1253 let source_id = SourceId::for_manifest_path(manifest_path)?;
1254 let package = ops::read_package(manifest_path, source_id, self.gctx)?;
1255 loaded.insert(manifest_path.to_path_buf(), package.clone());
1256 Ok(package)
1257 }
1258
1259 pub fn preload(&self, registry: &mut PackageRegistry<'gctx>) {
1266 if self.is_ephemeral {
1272 return;
1273 }
1274
1275 for pkg in self.packages.packages.values() {
1276 let pkg = match *pkg {
1277 MaybePackage::Package(ref p) => p.clone(),
1278 MaybePackage::Virtual(_) => continue,
1279 };
1280 let src = PathSource::preload_with(pkg, self.gctx);
1281 registry.add_preloaded(Box::new(src));
1282 }
1283 }
1284
1285 pub fn set_target_dir(&mut self, target_dir: Filesystem) {
1286 self.target_dir = Some(target_dir);
1287 }
1288
1289 pub fn members_with_features(
1297 &self,
1298 specs: &[PackageIdSpec],
1299 cli_features: &CliFeatures,
1300 ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1301 assert!(
1302 !specs.is_empty() || cli_features.all_features,
1303 "no specs requires all_features"
1304 );
1305 if specs.is_empty() {
1306 return Ok(self
1309 .members()
1310 .map(|m| (m, CliFeatures::new_all(true)))
1311 .collect());
1312 }
1313 if self.allows_new_cli_feature_behavior() {
1314 self.members_with_features_new(specs, cli_features)
1315 } else {
1316 Ok(self.members_with_features_old(specs, cli_features))
1317 }
1318 }
1319
1320 fn collect_matching_features(
1323 member: &Package,
1324 cli_features: &CliFeatures,
1325 found_features: &mut BTreeSet<FeatureValue>,
1326 ) -> CliFeatures {
1327 if cli_features.features.is_empty() {
1328 return cli_features.clone();
1329 }
1330
1331 let summary = member.summary();
1333
1334 let summary_features = summary.features();
1336
1337 let dependencies: BTreeMap<InternedString, &Dependency> = summary
1339 .dependencies()
1340 .iter()
1341 .map(|dep| (dep.name_in_toml(), dep))
1342 .collect();
1343
1344 let optional_dependency_names: BTreeSet<_> = dependencies
1346 .iter()
1347 .filter(|(_, dep)| dep.is_optional())
1348 .map(|(name, _)| name)
1349 .copied()
1350 .collect();
1351
1352 let mut features = BTreeSet::new();
1353
1354 let summary_or_opt_dependency_feature = |feature: &InternedString| -> bool {
1356 summary_features.contains_key(feature) || optional_dependency_names.contains(feature)
1357 };
1358
1359 for feature in cli_features.features.iter() {
1360 match feature {
1361 FeatureValue::Feature(f) => {
1362 if summary_or_opt_dependency_feature(f) {
1363 features.insert(feature.clone());
1365 found_features.insert(feature.clone());
1366 }
1367 }
1368 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1370 FeatureValue::DepFeature {
1371 dep_name,
1372 dep_feature,
1373 weak: _,
1374 } => {
1375 if dependencies.contains_key(dep_name) {
1376 features.insert(feature.clone());
1379 found_features.insert(feature.clone());
1380 } else if *dep_name == member.name()
1381 && summary_or_opt_dependency_feature(dep_feature)
1382 {
1383 features.insert(FeatureValue::Feature(*dep_feature));
1388 found_features.insert(feature.clone());
1389 }
1390 }
1391 }
1392 }
1393 CliFeatures {
1394 features: Rc::new(features),
1395 all_features: cli_features.all_features,
1396 uses_default_features: cli_features.uses_default_features,
1397 }
1398 }
1399
1400 fn missing_feature_spelling_suggestions(
1401 &self,
1402 selected_members: &[&Package],
1403 cli_features: &CliFeatures,
1404 found_features: &BTreeSet<FeatureValue>,
1405 ) -> Vec<String> {
1406 let mut summary_features: Vec<InternedString> = Default::default();
1408
1409 let mut dependencies_features: BTreeMap<InternedString, &[InternedString]> =
1411 Default::default();
1412
1413 let mut optional_dependency_names: Vec<InternedString> = Default::default();
1415
1416 let mut summary_features_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1418 Default::default();
1419
1420 let mut optional_dependency_names_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1422 Default::default();
1423
1424 for &member in selected_members {
1425 let summary = member.summary();
1427
1428 summary_features.extend(summary.features().keys());
1430 summary_features_per_member
1431 .insert(member, summary.features().keys().copied().collect());
1432
1433 let dependencies: BTreeMap<InternedString, &Dependency> = summary
1435 .dependencies()
1436 .iter()
1437 .map(|dep| (dep.name_in_toml(), dep))
1438 .collect();
1439
1440 dependencies_features.extend(
1441 dependencies
1442 .iter()
1443 .map(|(name, dep)| (*name, dep.features())),
1444 );
1445
1446 let optional_dependency_names_raw: BTreeSet<_> = dependencies
1448 .iter()
1449 .filter(|(_, dep)| dep.is_optional())
1450 .map(|(name, _)| name)
1451 .copied()
1452 .collect();
1453
1454 optional_dependency_names.extend(optional_dependency_names_raw.iter());
1455 optional_dependency_names_per_member.insert(member, optional_dependency_names_raw);
1456 }
1457
1458 let edit_distance_test = |a: InternedString, b: InternedString| {
1459 edit_distance(a.as_str(), b.as_str(), 3).is_some()
1460 };
1461
1462 cli_features
1463 .features
1464 .difference(found_features)
1465 .map(|feature| match feature {
1466 FeatureValue::Feature(typo) => {
1468 let summary_features = summary_features
1470 .iter()
1471 .filter(move |feature| edit_distance_test(**feature, *typo));
1472
1473 let optional_dependency_features = optional_dependency_names
1475 .iter()
1476 .filter(move |feature| edit_distance_test(**feature, *typo));
1477
1478 summary_features
1479 .chain(optional_dependency_features)
1480 .map(|s| s.to_string())
1481 .collect::<Vec<_>>()
1482 }
1483 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1484 FeatureValue::DepFeature {
1485 dep_name,
1486 dep_feature,
1487 weak: _,
1488 } => {
1489 let pkg_feat_similar = dependencies_features
1491 .iter()
1492 .filter(|(name, _)| edit_distance_test(**name, *dep_name))
1493 .map(|(name, features)| {
1494 (
1495 name,
1496 features
1497 .iter()
1498 .filter(|feature| edit_distance_test(**feature, *dep_feature))
1499 .collect::<Vec<_>>(),
1500 )
1501 })
1502 .map(|(name, features)| {
1503 features
1504 .into_iter()
1505 .map(move |feature| format!("{}/{}", name, feature))
1506 })
1507 .flatten();
1508
1509 let optional_dependency_features = optional_dependency_names_per_member
1511 .iter()
1512 .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1513 .map(|(package, optional_dependencies)| {
1514 optional_dependencies
1515 .into_iter()
1516 .filter(|optional_dependency| {
1517 edit_distance_test(**optional_dependency, *dep_name)
1518 })
1519 .map(move |optional_dependency| {
1520 format!("{}/{}", package.name(), optional_dependency)
1521 })
1522 })
1523 .flatten();
1524
1525 let summary_features = summary_features_per_member
1527 .iter()
1528 .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1529 .map(|(package, summary_features)| {
1530 summary_features
1531 .into_iter()
1532 .filter(|summary_feature| {
1533 edit_distance_test(**summary_feature, *dep_feature)
1534 })
1535 .map(move |summary_feature| {
1536 format!("{}/{}", package.name(), summary_feature)
1537 })
1538 })
1539 .flatten();
1540
1541 pkg_feat_similar
1542 .chain(optional_dependency_features)
1543 .chain(summary_features)
1544 .collect::<Vec<_>>()
1545 }
1546 })
1547 .map(|v| v.into_iter())
1548 .flatten()
1549 .unique()
1550 .filter(|element| {
1551 let feature = FeatureValue::new(element.into());
1552 !cli_features.features.contains(&feature) && !found_features.contains(&feature)
1553 })
1554 .sorted()
1555 .take(5)
1556 .collect()
1557 }
1558
1559 fn report_unknown_features_error(
1560 &self,
1561 specs: &[PackageIdSpec],
1562 cli_features: &CliFeatures,
1563 found_features: &BTreeSet<FeatureValue>,
1564 ) -> CargoResult<()> {
1565 let unknown: Vec<_> = cli_features
1566 .features
1567 .difference(found_features)
1568 .map(|feature| feature.to_string())
1569 .sorted()
1570 .collect();
1571
1572 let (selected_members, unselected_members): (Vec<_>, Vec<_>) = self
1573 .members()
1574 .partition(|member| specs.iter().any(|spec| spec.matches(member.package_id())));
1575
1576 let missing_packages_with_the_features = unselected_members
1577 .into_iter()
1578 .filter(|member| {
1579 unknown
1580 .iter()
1581 .any(|feature| member.summary().features().contains_key(&**feature))
1582 })
1583 .map(|m| m.name())
1584 .collect_vec();
1585
1586 let these_features = if unknown.len() == 1 {
1587 "this feature"
1588 } else {
1589 "these features"
1590 };
1591 let mut msg = if let [singular] = &selected_members[..] {
1592 format!(
1593 "the package '{}' does not contain {these_features}: {}",
1594 singular.name(),
1595 unknown.join(", ")
1596 )
1597 } else {
1598 let names = selected_members.iter().map(|m| m.name()).join(", ");
1599 format!(
1600 "none of the selected packages contains {these_features}: {}\nselected packages: {names}",
1601 unknown.join(", ")
1602 )
1603 };
1604
1605 use std::fmt::Write;
1606 if !missing_packages_with_the_features.is_empty() {
1607 write!(
1608 &mut msg,
1609 "\nhelp: package{} with the missing feature{}: {}",
1610 if missing_packages_with_the_features.len() != 1 {
1611 "s"
1612 } else {
1613 ""
1614 },
1615 if unknown.len() != 1 { "s" } else { "" },
1616 missing_packages_with_the_features.join(", ")
1617 )?;
1618 } else {
1619 let suggestions = self.missing_feature_spelling_suggestions(
1620 &selected_members,
1621 cli_features,
1622 found_features,
1623 );
1624 if !suggestions.is_empty() {
1625 write!(
1626 &mut msg,
1627 "\nhelp: there {}: {}",
1628 if suggestions.len() == 1 {
1629 "is a similarly named feature"
1630 } else {
1631 "are similarly named features"
1632 },
1633 suggestions.join(", ")
1634 )?;
1635 }
1636 }
1637
1638 bail!("{msg}")
1639 }
1640
1641 fn members_with_features_new(
1644 &self,
1645 specs: &[PackageIdSpec],
1646 cli_features: &CliFeatures,
1647 ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1648 let mut found_features = Default::default();
1651
1652 let members: Vec<(&Package, CliFeatures)> = self
1653 .members()
1654 .filter(|m| specs.iter().any(|spec| spec.matches(m.package_id())))
1655 .map(|m| {
1656 (
1657 m,
1658 Workspace::collect_matching_features(m, cli_features, &mut found_features),
1659 )
1660 })
1661 .collect();
1662
1663 if members.is_empty() {
1664 if !(cli_features.features.is_empty()
1667 && !cli_features.all_features
1668 && cli_features.uses_default_features)
1669 {
1670 let hint = specs
1671 .iter()
1672 .map(|spec| {
1673 closest_msg(
1674 spec.name(),
1675 self.members(),
1676 |m| m.name().as_str(),
1677 "workspace member",
1678 )
1679 })
1680 .find(|msg| !msg.is_empty())
1681 .unwrap_or_default();
1682 bail!("cannot specify features for packages outside of workspace{hint}");
1683 }
1684 return Ok(self
1687 .members()
1688 .map(|m| (m, CliFeatures::new_all(false)))
1689 .collect());
1690 }
1691 if *cli_features.features != found_features {
1692 self.report_unknown_features_error(specs, cli_features, &found_features)?;
1693 }
1694 Ok(members)
1695 }
1696
1697 fn members_with_features_old(
1700 &self,
1701 specs: &[PackageIdSpec],
1702 cli_features: &CliFeatures,
1703 ) -> Vec<(&Package, CliFeatures)> {
1704 let mut member_specific_features: HashMap<InternedString, BTreeSet<FeatureValue>> =
1707 HashMap::default();
1708 let mut cwd_features = BTreeSet::new();
1710 for feature in cli_features.features.iter() {
1711 match feature {
1712 FeatureValue::Feature(_) => {
1713 cwd_features.insert(feature.clone());
1714 }
1715 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1717 FeatureValue::DepFeature {
1718 dep_name,
1719 dep_feature,
1720 weak: _,
1721 } => {
1722 let is_member = self.members().any(|member| {
1728 self.current_opt() != Some(member) && member.name() == *dep_name
1730 });
1731 if is_member && specs.iter().any(|spec| spec.name() == dep_name.as_str()) {
1732 member_specific_features
1733 .entry(*dep_name)
1734 .or_default()
1735 .insert(FeatureValue::Feature(*dep_feature));
1736 } else {
1737 cwd_features.insert(feature.clone());
1738 }
1739 }
1740 }
1741 }
1742
1743 let ms: Vec<_> = self
1744 .members()
1745 .filter_map(|member| {
1746 let member_id = member.package_id();
1747 match self.current_opt() {
1748 Some(current) if member_id == current.package_id() => {
1751 let feats = CliFeatures {
1752 features: Rc::new(cwd_features.clone()),
1753 all_features: cli_features.all_features,
1754 uses_default_features: cli_features.uses_default_features,
1755 };
1756 Some((member, feats))
1757 }
1758 _ => {
1759 if specs.iter().any(|spec| spec.matches(member_id)) {
1761 let feats = CliFeatures {
1771 features: Rc::new(
1772 member_specific_features
1773 .remove(member.name().as_str())
1774 .unwrap_or_default(),
1775 ),
1776 uses_default_features: true,
1777 all_features: cli_features.all_features,
1778 };
1779 Some((member, feats))
1780 } else {
1781 None
1783 }
1784 }
1785 }
1786 })
1787 .collect();
1788
1789 assert!(member_specific_features.is_empty());
1792
1793 ms
1794 }
1795
1796 pub fn unit_needs_doc_scrape(&self, unit: &Unit) -> bool {
1798 self.is_member(&unit.pkg) && !(unit.target.for_host() || unit.pkg.proc_macro())
1803 }
1804
1805 pub fn add_local_overlay(&mut self, id: SourceId, registry_path: PathBuf) {
1809 self.local_overlays.insert(id, registry_path);
1810 }
1811
1812 pub fn package_registry(&self) -> CargoResult<PackageRegistry<'gctx>> {
1814 let source_config =
1815 SourceConfigMap::new_with_overlays(self.gctx(), self.local_overlays()?)?;
1816 PackageRegistry::new_with_source_config(self.gctx(), source_config)
1817 }
1818
1819 fn local_overlays(&self) -> CargoResult<impl Iterator<Item = (SourceId, SourceId)>> {
1821 let mut ret = self
1822 .local_overlays
1823 .iter()
1824 .map(|(id, path)| Ok((*id, SourceId::for_local_registry(path)?)))
1825 .collect::<CargoResult<Vec<_>>>()?;
1826
1827 if let Ok(overlay) = self
1828 .gctx
1829 .get_env("__CARGO_TEST_DEPENDENCY_CONFUSION_VULNERABILITY_DO_NOT_USE_THIS")
1830 {
1831 let (url, path) = overlay.split_once('=').ok_or(anyhow::anyhow!(
1832 "invalid overlay format. I won't tell you why; you shouldn't be using it anyway"
1833 ))?;
1834 ret.push((
1835 SourceId::from_url(url)?,
1836 SourceId::for_local_registry(path.as_ref())?,
1837 ));
1838 }
1839
1840 Ok(ret.into_iter())
1841 }
1842}
1843
1844impl<'gctx> Packages<'gctx> {
1845 fn get(&self, manifest_path: &Path) -> &MaybePackage {
1846 self.maybe_get(manifest_path).unwrap()
1847 }
1848
1849 fn get_mut(&mut self, manifest_path: &Path) -> &mut MaybePackage {
1850 self.maybe_get_mut(manifest_path).unwrap()
1851 }
1852
1853 fn maybe_get(&self, manifest_path: &Path) -> Option<&MaybePackage> {
1854 self.packages.get(manifest_path)
1855 }
1856
1857 fn maybe_get_mut(&mut self, manifest_path: &Path) -> Option<&mut MaybePackage> {
1858 self.packages.get_mut(manifest_path)
1859 }
1860
1861 fn load(&mut self, manifest_path: &Path) -> CargoResult<&MaybePackage> {
1862 match self.packages.entry(manifest_path.to_path_buf()) {
1863 Entry::Occupied(e) => Ok(e.into_mut()),
1864 Entry::Vacant(v) => {
1865 let source_id = SourceId::for_manifest_path(manifest_path)?;
1866 let manifest = read_manifest(manifest_path, source_id, self.gctx)?;
1867 Ok(v.insert(match manifest {
1868 EitherManifest::Real(manifest) => {
1869 MaybePackage::Package(Package::new(manifest, manifest_path))
1870 }
1871 EitherManifest::Virtual(vm) => MaybePackage::Virtual(vm),
1872 }))
1873 }
1874 }
1875 }
1876}
1877
1878impl MaybePackage {
1879 fn workspace_config(&self) -> &WorkspaceConfig {
1880 match *self {
1881 MaybePackage::Package(ref p) => p.manifest().workspace_config(),
1882 MaybePackage::Virtual(ref vm) => vm.workspace_config(),
1883 }
1884 }
1885
1886 pub fn as_package(&self) -> Option<&Package> {
1887 match self {
1888 MaybePackage::Package(p) => Some(p),
1889 MaybePackage::Virtual(_) => None,
1890 }
1891 }
1892
1893 pub fn is_embedded(&self) -> bool {
1895 match self {
1896 MaybePackage::Package(p) => p.manifest().is_embedded(),
1897 MaybePackage::Virtual(_) => false,
1898 }
1899 }
1900
1901 pub fn contents(&self) -> Option<&str> {
1902 match self {
1903 MaybePackage::Package(p) => p.manifest().contents(),
1904 MaybePackage::Virtual(v) => v.contents(),
1905 }
1906 }
1907
1908 pub fn document(&self) -> Option<&toml::Spanned<toml::de::DeTable<'static>>> {
1909 match self {
1910 MaybePackage::Package(p) => p.manifest().document(),
1911 MaybePackage::Virtual(v) => v.document(),
1912 }
1913 }
1914
1915 pub fn original_toml(&self) -> Option<&TomlManifest> {
1916 match self {
1917 MaybePackage::Package(p) => p.manifest().original_toml(),
1918 MaybePackage::Virtual(v) => v.original_toml(),
1919 }
1920 }
1921
1922 pub fn normalized_toml(&self) -> &TomlManifest {
1923 match self {
1924 MaybePackage::Package(p) => p.manifest().normalized_toml(),
1925 MaybePackage::Virtual(v) => v.normalized_toml(),
1926 }
1927 }
1928
1929 pub fn edition(&self) -> Edition {
1930 match self {
1931 MaybePackage::Package(p) => p.manifest().edition(),
1932 MaybePackage::Virtual(_) => Edition::default(),
1933 }
1934 }
1935
1936 pub fn profiles(&self) -> Option<&TomlProfiles> {
1937 match self {
1938 MaybePackage::Package(p) => p.manifest().profiles(),
1939 MaybePackage::Virtual(v) => v.profiles(),
1940 }
1941 }
1942
1943 pub fn unstable_features(&self) -> &Features {
1944 match self {
1945 MaybePackage::Package(p) => p.manifest().unstable_features(),
1946 MaybePackage::Virtual(vm) => vm.unstable_features(),
1947 }
1948 }
1949}
1950
1951impl WorkspaceRootConfig {
1952 pub fn new(
1954 root_dir: &Path,
1955 members: &Option<Vec<String>>,
1956 default_members: &Option<Vec<String>>,
1957 exclude: &Option<Vec<String>>,
1958 inheritable: &Option<InheritableFields>,
1959 custom_metadata: &Option<toml::Value>,
1960 ) -> WorkspaceRootConfig {
1961 WorkspaceRootConfig {
1962 root_dir: root_dir.to_path_buf(),
1963 members: members.clone(),
1964 default_members: default_members.clone(),
1965 exclude: exclude.clone().unwrap_or_default(),
1966 inheritable_fields: inheritable.clone().unwrap_or_default(),
1967 custom_metadata: custom_metadata.clone(),
1968 }
1969 }
1970 fn is_excluded(&self, manifest_path: &Path) -> bool {
1974 let excluded = self
1975 .exclude
1976 .iter()
1977 .any(|ex| manifest_path.starts_with(self.root_dir.join(ex)));
1978
1979 let explicit_member = match self.members {
1980 Some(ref members) => members
1981 .iter()
1982 .any(|mem| manifest_path.starts_with(self.root_dir.join(mem))),
1983 None => false,
1984 };
1985
1986 !explicit_member && excluded
1987 }
1988
1989 fn is_explicitly_listed_member(&self, manifest_path: &Path) -> bool {
2000 let root_manifest = self.root_dir.join("Cargo.toml");
2001 if manifest_path == root_manifest {
2002 return true;
2003 }
2004 match self.members {
2005 Some(ref members) => {
2006 let Ok(expanded_members) = self.members_paths(members) else {
2008 return false;
2009 };
2010 let normalized_manifest = paths::normalize_path(manifest_path);
2012 expanded_members.iter().any(|(member_path, _)| {
2013 let normalized_member = paths::normalize_path(member_path);
2015 normalized_manifest.parent() == Some(normalized_member.as_path())
2018 })
2019 }
2020 None => false,
2021 }
2022 }
2023
2024 fn has_members_list(&self) -> bool {
2025 self.members.is_some()
2026 }
2027
2028 fn has_default_members(&self) -> bool {
2030 self.default_members.is_some()
2031 }
2032
2033 #[tracing::instrument(skip_all)]
2036 fn members_paths<'g>(
2037 &self,
2038 globs: &'g [String],
2039 ) -> CargoResult<Vec<(PathBuf, Option<&'g str>)>> {
2040 let mut expanded_list = Vec::new();
2041
2042 for glob in globs {
2043 let pathbuf = self.root_dir.join(glob);
2044 let expanded_paths = Self::expand_member_path(&pathbuf)?;
2045
2046 if expanded_paths.is_empty() {
2049 expanded_list.push((pathbuf, None));
2050 } else {
2051 let used_glob_pattern = expanded_paths.len() > 1 || expanded_paths[0] != pathbuf;
2052 let glob = used_glob_pattern.then_some(glob.as_str());
2053
2054 for expanded_path in expanded_paths {
2060 if expanded_path.is_dir() {
2061 expanded_list.push((expanded_path, glob));
2062 }
2063 }
2064 }
2065 }
2066
2067 Ok(expanded_list)
2068 }
2069
2070 fn expand_member_path(path: &Path) -> CargoResult<Vec<PathBuf>> {
2071 let Some(path) = path.to_str() else {
2072 return Ok(Vec::new());
2073 };
2074 let res = glob(path).with_context(|| format!("could not parse pattern `{}`", &path))?;
2075 let res = res
2076 .map(|p| p.with_context(|| format!("unable to match path to pattern `{}`", &path)))
2077 .collect::<Result<Vec<_>, _>>()?;
2078 Ok(res)
2079 }
2080
2081 pub fn inheritable(&self) -> &InheritableFields {
2082 &self.inheritable_fields
2083 }
2084}
2085
2086pub fn resolve_relative_path(
2087 label: &str,
2088 old_root: &Path,
2089 new_root: &Path,
2090 rel_path: &str,
2091) -> CargoResult<String> {
2092 let joined_path = normalize_path(&old_root.join(rel_path));
2093 match diff_paths(joined_path, new_root) {
2094 None => Err(anyhow!(
2095 "`{}` was defined in {} but could not be resolved with {}",
2096 label,
2097 old_root.display(),
2098 new_root.display()
2099 )),
2100 Some(path) => Ok(path
2101 .to_str()
2102 .ok_or_else(|| {
2103 anyhow!(
2104 "`{}` resolved to non-UTF value (`{}`)",
2105 label,
2106 path.display()
2107 )
2108 })?
2109 .to_owned()),
2110 }
2111}
2112
2113pub fn find_workspace_root(
2115 manifest_path: &Path,
2116 gctx: &GlobalContext,
2117) -> CargoResult<Option<PathBuf>> {
2118 find_workspace_root_with_loader(manifest_path, gctx, |self_path| {
2119 let source_id = SourceId::for_manifest_path(self_path)?;
2120 let manifest = read_manifest(self_path, source_id, gctx)?;
2121 Ok(manifest
2122 .workspace_config()
2123 .get_ws_root(self_path, manifest_path))
2124 })
2125}
2126
2127pub fn find_workspace_root_with_membership_check(
2134 manifest_path: &Path,
2135 gctx: &GlobalContext,
2136) -> CargoResult<Option<PathBuf>> {
2137 let source_id = SourceId::for_manifest_path(manifest_path)?;
2138 let current_manifest = read_manifest(manifest_path, source_id, gctx)?;
2139
2140 match current_manifest.workspace_config() {
2141 WorkspaceConfig::Root(root_config) => {
2142 if root_config.has_default_members() {
2145 Ok(None)
2146 } else {
2147 Ok(Some(manifest_path.to_path_buf()))
2148 }
2149 }
2150 WorkspaceConfig::Member {
2151 root: Some(path_to_root),
2152 } => {
2153 let ws_manifest_path = read_root_pointer(manifest_path, path_to_root);
2155 let ws_source_id = SourceId::for_manifest_path(&ws_manifest_path)?;
2156 let ws_manifest = read_manifest(&ws_manifest_path, ws_source_id, gctx)?;
2157
2158 if let WorkspaceConfig::Root(ref root_config) = *ws_manifest.workspace_config() {
2160 if root_config.is_explicitly_listed_member(manifest_path)
2161 && !root_config.is_excluded(manifest_path)
2162 {
2163 return Ok(Some(ws_manifest_path));
2164 }
2165 }
2166 Ok(None)
2168 }
2169 WorkspaceConfig::Member { root: None } => {
2170 find_workspace_root_with_loader(manifest_path, gctx, |candidate_manifest_path| {
2172 let source_id = SourceId::for_manifest_path(candidate_manifest_path)?;
2173 let manifest = read_manifest(candidate_manifest_path, source_id, gctx)?;
2174 if let WorkspaceConfig::Root(ref root_config) = *manifest.workspace_config() {
2175 if root_config.is_explicitly_listed_member(manifest_path)
2176 && !root_config.is_excluded(manifest_path)
2177 {
2178 return Ok(Some(candidate_manifest_path.to_path_buf()));
2179 }
2180 }
2181 Ok(None)
2182 })
2183 }
2184 }
2185}
2186
2187fn find_workspace_root_with_loader(
2192 manifest_path: &Path,
2193 gctx: &GlobalContext,
2194 mut loader: impl FnMut(&Path) -> CargoResult<Option<PathBuf>>,
2195) -> CargoResult<Option<PathBuf>> {
2196 {
2198 let roots = gctx.ws_roots();
2199 for current in manifest_path.ancestors().skip(1) {
2202 if let Some(ws_config) = roots.get(current) {
2203 if !ws_config.is_excluded(manifest_path) {
2204 return Ok(Some(current.join("Cargo.toml")));
2206 }
2207 }
2208 }
2209 }
2210
2211 for ances_manifest_path in find_root_iter(manifest_path, gctx) {
2212 debug!("find_root - trying {}", ances_manifest_path.display());
2213 let ws_root_path = loader(&ances_manifest_path).with_context(|| {
2214 format!(
2215 "failed searching for potential workspace\n\
2216 package manifest: `{}`\n\
2217 invalid potential workspace manifest: `{}`\n\
2218 \n\
2219 help: to avoid searching for a non-existent workspace, add \
2220 `[workspace]` to the package manifest",
2221 manifest_path.display(),
2222 ances_manifest_path.display(),
2223 )
2224 })?;
2225 if let Some(ws_root_path) = ws_root_path {
2226 return Ok(Some(ws_root_path));
2227 }
2228 }
2229 Ok(None)
2230}
2231
2232fn read_root_pointer(member_manifest: &Path, root_link: &str) -> PathBuf {
2233 let path = member_manifest
2234 .parent()
2235 .unwrap()
2236 .join(root_link)
2237 .join("Cargo.toml");
2238 debug!("find_root - pointer {}", path.display());
2239 paths::normalize_path(&path)
2240}
2241
2242fn find_root_iter<'a>(
2243 manifest_path: &'a Path,
2244 gctx: &'a GlobalContext,
2245) -> impl Iterator<Item = PathBuf> + 'a {
2246 LookBehind::new(paths::ancestors(manifest_path, None).skip(2))
2247 .take_while(|path| !path.curr.ends_with("target/package"))
2248 .take_while(|path| {
2254 if let Some(last) = path.last {
2255 gctx.home() != last
2256 } else {
2257 true
2258 }
2259 })
2260 .map(|path| path.curr.join("Cargo.toml"))
2261 .filter(|ances_manifest_path| ances_manifest_path.exists())
2262}
2263
2264struct LookBehindWindow<'a, T: ?Sized> {
2265 curr: &'a T,
2266 last: Option<&'a T>,
2267}
2268
2269struct LookBehind<'a, T: ?Sized, K: Iterator<Item = &'a T>> {
2270 iter: K,
2271 last: Option<&'a T>,
2272}
2273
2274impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> LookBehind<'a, T, K> {
2275 fn new(items: K) -> Self {
2276 Self {
2277 iter: items,
2278 last: None,
2279 }
2280 }
2281}
2282
2283impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> Iterator for LookBehind<'a, T, K> {
2284 type Item = LookBehindWindow<'a, T>;
2285
2286 fn next(&mut self) -> Option<Self::Item> {
2287 match self.iter.next() {
2288 None => None,
2289 Some(next) => {
2290 let last = self.last;
2291 self.last = Some(next);
2292 Some(LookBehindWindow { curr: next, last })
2293 }
2294 }
2295 }
2296}