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 anyhow::{Context as _, anyhow, bail};
8use cargo_util_terminal::report::Level;
9use glob::glob;
10use itertools::Itertools;
11use tracing::debug;
12use url::Url;
13
14use crate::core::compiler::Unit;
15use crate::core::features::Features;
16use crate::core::registry::PackageRegistry;
17use crate::core::resolver::ResolveBehavior;
18use crate::core::resolver::features::CliFeatures;
19use crate::core::{
20 Dependency, Edition, FeatureValue, PackageId, PackageIdSpec, PackageIdSpecQuery, Patch,
21 PatchLocation,
22};
23use crate::core::{EitherManifest, Package, SourceId, VirtualManifest};
24use crate::ops;
25use crate::ops::lockfile::LOCKFILE_NAME;
26use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY, PathSource, SourceConfigMap};
27use crate::util::context;
28use crate::util::context::{FeatureUnification, Value};
29use crate::util::edit_distance;
30use crate::util::errors::{CargoResult, ManifestError};
31use crate::util::interning::InternedString;
32use crate::util::toml::{InheritableFields, read_manifest};
33use crate::util::{
34 Filesystem, GlobalContext, IntoUrl, closest_msg, context::CargoResolverConfig,
35 context::ConfigRelativePath, context::IncompatibleRustVersions,
36};
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: 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 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::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 resolve_honors_publish_age: true,
267 resolve_publish_time: None,
268 custom_metadata: None,
269 local_overlays: HashMap::new(),
270 }
271 }
272
273 pub fn ephemeral(
283 package: Package,
284 gctx: &'gctx GlobalContext,
285 target_dir: Option<Filesystem>,
286 require_optional_deps: bool,
287 ) -> CargoResult<Workspace<'gctx>> {
288 let mut ws = Workspace::new_default(package.manifest_path().to_path_buf(), gctx);
289 ws.is_ephemeral = true;
290 ws.require_optional_deps = require_optional_deps;
291 let id = package.package_id();
292 let package = MaybePackage::Package(package);
293 ws.packages
294 .packages
295 .insert(ws.current_manifest.clone(), package);
296 ws.target_dir = if let Some(dir) = target_dir {
297 Some(dir)
298 } else {
299 ws.gctx.target_dir()?
300 };
301 ws.build_dir = ws.target_dir.clone();
302 ws.members.push(ws.current_manifest.clone());
303 ws.member_ids.insert(id);
304 ws.default_members.push(ws.current_manifest.clone());
305 ws.set_resolve_behavior()?;
306 Ok(ws)
307 }
308
309 pub fn reload(&self, gctx: &'gctx GlobalContext) -> CargoResult<Workspace<'gctx>> {
314 let mut ws = Workspace::new(&self.current_manifest, gctx)?;
315 ws.set_resolve_honors_rust_version(Some(self.resolve_honors_rust_version));
316 ws.set_resolve_feature_unification(self.resolve_feature_unification);
317 ws.set_requested_lockfile_path(self.requested_lockfile_path.clone());
318 Ok(ws)
319 }
320
321 fn set_resolve_behavior(&mut self) -> CargoResult<()> {
322 self.resolve_behavior = match self.root_maybe() {
327 MaybePackage::Package(p) => p
328 .manifest()
329 .resolve_behavior()
330 .unwrap_or_else(|| p.manifest().edition().default_resolve_behavior()),
331 MaybePackage::Virtual(vm) => vm.resolve_behavior().unwrap_or(ResolveBehavior::V1),
332 };
333
334 match self.resolve_behavior() {
335 ResolveBehavior::V1 | ResolveBehavior::V2 => {}
336 ResolveBehavior::V3 => {
337 if self.resolve_behavior == ResolveBehavior::V3 {
338 self.resolve_honors_rust_version = true;
339 }
340 }
341 }
342 let config = self.gctx().get::<CargoResolverConfig>("resolver")?;
343 if let Some(incompatible_rust_versions) = config.incompatible_rust_versions {
344 self.resolve_honors_rust_version =
345 incompatible_rust_versions == IncompatibleRustVersions::Fallback;
346 }
347 if self.gctx().cli_unstable().feature_unification {
348 self.resolve_feature_unification = config
349 .feature_unification
350 .unwrap_or(FeatureUnification::Selected);
351 } else if config.feature_unification.is_some() {
352 self.gctx()
353 .shell()
354 .warn("ignoring `resolver.feature-unification` without `-Zfeature-unification`")?;
355 };
356
357 if !self.gctx().cli_unstable().min_publish_age {
358 if config.incompatible_publish_age.is_some() {
359 self.gctx().shell().warn(
360 "ignoring `resolver.incompatible-publish-age` without `-Zmin-publish-age`",
361 )?;
362 }
363 warn_unused_min_publish_age(self.gctx())?;
364 }
365
366 if let Some(lockfile_path) = config.lockfile_path {
367 let replacements: [(&str, &str); 0] = [];
369 let path = lockfile_path
370 .resolve_templated_path(self.gctx(), replacements)
371 .map_err(|e| match e {
372 context::ResolveTemplateError::UnexpectedVariable {
373 variable,
374 raw_template,
375 } => {
376 anyhow!(
377 "unexpected variable `{variable}` in resolver.lockfile-path `{raw_template}`"
378 )
379 }
380 context::ResolveTemplateError::UnexpectedBracket { bracket_type, raw_template } => {
381 let (btype, literal) = match bracket_type {
382 context::BracketType::Opening => ("opening", "{"),
383 context::BracketType::Closing => ("closing", "}"),
384 };
385
386 anyhow!(
387 "unexpected {btype} bracket `{literal}` in build.build-dir path `{raw_template}`"
388 )
389 }
390 })?;
391 if !path.ends_with(LOCKFILE_NAME) {
392 bail!("the `resolver.lockfile-path` must be a path to a {LOCKFILE_NAME} file");
393 }
394 if path.is_dir() {
395 bail!(
396 "`resolver.lockfile-path` `{}` is a directory but expected a file",
397 path.display()
398 );
399 }
400 self.requested_lockfile_path = Some(path);
401 }
402
403 Ok(())
404 }
405
406 pub fn current(&self) -> CargoResult<&Package> {
412 let pkg = self.current_opt().ok_or_else(|| {
413 anyhow::format_err!(
414 "manifest path `{}` is a virtual manifest, but this \
415 command requires running against an actual package in \
416 this workspace",
417 self.current_manifest.display()
418 )
419 })?;
420 Ok(pkg)
421 }
422
423 pub fn current_mut(&mut self) -> CargoResult<&mut Package> {
424 let cm = self.current_manifest.clone();
425 let pkg = self.current_opt_mut().ok_or_else(|| {
426 anyhow::format_err!(
427 "manifest path `{}` is a virtual manifest, but this \
428 command requires running against an actual package in \
429 this workspace",
430 cm.display()
431 )
432 })?;
433 Ok(pkg)
434 }
435
436 pub fn current_opt(&self) -> Option<&Package> {
437 match *self.packages.get(&self.current_manifest) {
438 MaybePackage::Package(ref p) => Some(p),
439 MaybePackage::Virtual(..) => None,
440 }
441 }
442
443 pub fn current_opt_mut(&mut self) -> Option<&mut Package> {
444 match *self.packages.get_mut(&self.current_manifest) {
445 MaybePackage::Package(ref mut p) => Some(p),
446 MaybePackage::Virtual(..) => None,
447 }
448 }
449
450 pub fn is_virtual(&self) -> bool {
451 match *self.packages.get(&self.current_manifest) {
452 MaybePackage::Package(..) => false,
453 MaybePackage::Virtual(..) => true,
454 }
455 }
456
457 pub fn gctx(&self) -> &'gctx GlobalContext {
459 self.gctx
460 }
461
462 pub fn profiles(&self) -> Option<&TomlProfiles> {
463 self.root_maybe().profiles()
464 }
465
466 pub fn root(&self) -> &Path {
471 self.root_manifest().parent().unwrap()
472 }
473
474 pub fn root_manifest(&self) -> &Path {
477 self.root_manifest
478 .as_ref()
479 .unwrap_or(&self.current_manifest)
480 }
481
482 pub fn root_maybe(&self) -> &MaybePackage {
484 self.packages.get(self.root_manifest())
485 }
486
487 pub fn target_dir(&self) -> Filesystem {
488 self.target_dir
489 .clone()
490 .unwrap_or_else(|| self.default_target_dir())
491 }
492
493 pub fn build_dir(&self) -> Filesystem {
494 self.build_dir
495 .clone()
496 .or_else(|| self.target_dir.clone())
497 .unwrap_or_else(|| self.default_build_dir())
498 }
499
500 fn default_target_dir(&self) -> Filesystem {
501 if self.root_maybe().is_embedded() {
502 self.build_dir().join("target")
503 } else {
504 Filesystem::new(self.root().join("target"))
505 }
506 }
507
508 fn default_build_dir(&self) -> Filesystem {
509 if self.root_maybe().is_embedded() {
510 let default = ConfigRelativePath::new(
511 "{cargo-cache-home}/build/{workspace-path-hash}"
512 .to_owned()
513 .into(),
514 );
515 self.gctx()
516 .custom_build_dir(&default, self.root_manifest())
517 .expect("template is correct")
518 } else {
519 self.default_target_dir()
520 }
521 }
522
523 pub fn root_replace(&self) -> &[(PackageIdSpec, Dependency)] {
527 match self.root_maybe() {
528 MaybePackage::Package(p) => p.manifest().replace(),
529 MaybePackage::Virtual(vm) => vm.replace(),
530 }
531 }
532
533 fn config_patch(&self) -> CargoResult<HashMap<Url, Vec<Patch>>> {
534 let config_patch: Option<
535 BTreeMap<String, BTreeMap<String, Value<TomlDependency<ConfigRelativePath>>>>,
536 > = self.gctx.get("patch")?;
537
538 let source = SourceId::for_manifest_path(self.root_manifest())?;
539
540 let mut warnings = Vec::new();
541
542 let mut patch = HashMap::new();
543 for (url, deps) in config_patch.into_iter().flatten() {
544 let url = match &url[..] {
545 CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
546 url => self
547 .gctx
548 .get_registry_index(url)
549 .or_else(|_| url.into_url())
550 .with_context(|| {
551 format!("[patch] entry `{}` should be a URL or registry name", url)
552 })?,
553 };
554 patch.insert(
555 url,
556 deps.iter()
557 .map(|(name, dependency_cv)| {
558 crate::util::toml::config_patch_to_dependency(
559 &dependency_cv.val,
560 name,
561 source,
562 self.gctx,
563 &mut warnings,
564 )
565 .map(|dep| Patch {
566 dep,
567 loc: PatchLocation::Config(dependency_cv.definition.clone()),
568 })
569 })
570 .collect::<CargoResult<Vec<_>>>()?,
571 );
572 }
573
574 for message in warnings {
575 self.gctx
576 .shell()
577 .warn(format!("[patch] in cargo config: {}", message))?
578 }
579
580 Ok(patch)
581 }
582
583 pub fn root_patch(&self) -> CargoResult<HashMap<Url, Vec<Patch>>> {
587 let from_manifest = match self.root_maybe() {
588 MaybePackage::Package(p) => p.manifest().patch(),
589 MaybePackage::Virtual(vm) => vm.patch(),
590 };
591
592 let from_config = self.config_patch()?;
593 if from_config.is_empty() {
594 return Ok(from_manifest.clone());
595 }
596 if from_manifest.is_empty() {
597 return Ok(from_config);
598 }
599
600 let mut combined = from_config;
603 for (url, deps_from_manifest) in from_manifest {
604 if let Some(deps_from_config) = combined.get_mut(url) {
605 let mut from_manifest_pruned = deps_from_manifest.clone();
608 for dep_from_config in &mut *deps_from_config {
609 if let Some(i) = from_manifest_pruned.iter().position(|dep_from_manifest| {
610 dep_from_config.dep.name_in_toml() == dep_from_manifest.dep.name_in_toml()
612 }) {
613 from_manifest_pruned.swap_remove(i);
614 }
615 }
616 deps_from_config.extend(from_manifest_pruned);
618 } else {
619 combined.insert(url.clone(), deps_from_manifest.clone());
620 }
621 }
622 Ok(combined)
623 }
624
625 pub fn loaded_maybe(&self) -> impl Iterator<Item = &MaybePackage> {
627 self.packages.packages.values()
628 }
629
630 pub fn members(&self) -> impl Iterator<Item = &Package> {
632 let packages = &self.packages;
633 self.members
634 .iter()
635 .filter_map(move |path| match packages.get(path) {
636 MaybePackage::Package(p) => Some(p),
637 _ => None,
638 })
639 }
640
641 pub fn members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
643 let packages = &mut self.packages.packages;
644 let members: HashSet<_> = self.members.iter().map(|path| path).collect();
645
646 packages.iter_mut().filter_map(move |(path, package)| {
647 if members.contains(path) {
648 if let MaybePackage::Package(p) = package {
649 return Some(p);
650 }
651 }
652
653 None
654 })
655 }
656
657 pub fn default_members<'a>(&'a self) -> impl Iterator<Item = &'a Package> {
659 let packages = &self.packages;
660 self.default_members
661 .iter()
662 .filter_map(move |path| match packages.get(path) {
663 MaybePackage::Package(p) => Some(p),
664 _ => None,
665 })
666 }
667
668 pub fn default_members_mut(&mut self) -> impl Iterator<Item = &mut Package> {
670 let packages = &mut self.packages.packages;
671 let members: HashSet<_> = self
672 .default_members
673 .iter()
674 .map(|path| path.parent().unwrap().to_owned())
675 .collect();
676
677 packages.iter_mut().filter_map(move |(path, package)| {
678 if members.contains(path) {
679 if let MaybePackage::Package(p) = package {
680 return Some(p);
681 }
682 }
683
684 None
685 })
686 }
687
688 pub fn is_member(&self, pkg: &Package) -> bool {
690 self.member_ids.contains(&pkg.package_id())
691 }
692
693 pub fn is_member_id(&self, package_id: PackageId) -> bool {
695 self.member_ids.contains(&package_id)
696 }
697
698 pub fn is_ephemeral(&self) -> bool {
699 self.is_ephemeral
700 }
701
702 pub fn require_optional_deps(&self) -> bool {
703 self.require_optional_deps
704 }
705
706 pub fn set_require_optional_deps(
707 &mut self,
708 require_optional_deps: bool,
709 ) -> &mut Workspace<'gctx> {
710 self.require_optional_deps = require_optional_deps;
711 self
712 }
713
714 pub fn ignore_lock(&self) -> bool {
715 self.ignore_lock
716 }
717
718 pub fn set_ignore_lock(&mut self, ignore_lock: bool) -> &mut Workspace<'gctx> {
719 self.ignore_lock = ignore_lock;
720 self
721 }
722
723 pub fn lock_root(&self) -> Filesystem {
725 if let Some(requested) = self.requested_lockfile_path.as_ref() {
726 return Filesystem::new(
727 requested
728 .parent()
729 .expect("Lockfile path can't be root")
730 .to_owned(),
731 );
732 }
733 self.default_lock_root()
734 }
735
736 fn default_lock_root(&self) -> Filesystem {
737 if self.root_maybe().is_embedded() {
738 let workspace_manifest_path = self.root_manifest();
741 let real_path = std::fs::canonicalize(workspace_manifest_path)
742 .unwrap_or_else(|_err| workspace_manifest_path.to_owned());
743 let hash = crate::util::hex::short_hash(&real_path);
744 self.build_dir().join(hash)
745 } else {
746 Filesystem::new(self.root().to_owned())
747 }
748 }
749
750 pub fn set_requested_lockfile_path(&mut self, path: Option<PathBuf>) {
752 self.requested_lockfile_path = path;
753 }
754
755 pub fn requested_lockfile_path(&self) -> Option<&Path> {
756 self.requested_lockfile_path.as_deref()
757 }
758
759 pub fn lowest_rust_version(&self) -> Option<&RustVersion> {
762 self.members().filter_map(|pkg| pkg.rust_version()).min()
763 }
764
765 pub fn set_resolve_honors_rust_version(&mut self, honor_rust_version: Option<bool>) {
766 if let Some(honor_rust_version) = honor_rust_version {
767 self.resolve_honors_rust_version = honor_rust_version;
768 }
769 }
770
771 pub fn resolve_honors_rust_version(&self) -> bool {
772 self.resolve_honors_rust_version
773 }
774
775 pub fn set_resolve_honors_publish_age(&mut self, honor_publish_age: bool) {
776 self.resolve_honors_publish_age = honor_publish_age;
777 }
778
779 pub fn resolve_honors_publish_age(&self) -> bool {
780 self.resolve_honors_publish_age
781 }
782
783 pub fn set_resolve_feature_unification(&mut self, feature_unification: FeatureUnification) {
784 self.resolve_feature_unification = feature_unification;
785 }
786
787 pub fn resolve_feature_unification(&self) -> FeatureUnification {
788 self.resolve_feature_unification
789 }
790
791 pub fn set_resolve_publish_time(&mut self, publish_time: jiff::Timestamp) {
792 self.resolve_publish_time = Some(publish_time);
793 }
794
795 pub fn resolve_publish_time(&self) -> Option<jiff::Timestamp> {
796 self.resolve_publish_time
797 }
798
799 pub fn custom_metadata(&self) -> Option<&toml::Value> {
800 self.custom_metadata.as_ref()
801 }
802
803 pub fn load_workspace_config(&mut self) -> CargoResult<Option<WorkspaceRootConfig>> {
804 if let Some(root_path) = &self.root_manifest {
807 let root_package = self.packages.load(root_path)?;
808 match root_package.workspace_config() {
809 WorkspaceConfig::Root(root_config) => {
810 return Ok(Some(root_config.clone()));
811 }
812
813 _ => bail!(
814 "root of a workspace inferred but wasn't a root: {}",
815 root_path.display()
816 ),
817 }
818 }
819
820 Ok(None)
821 }
822
823 fn find_root(&mut self, manifest_path: &Path) -> CargoResult<Option<PathBuf>> {
833 let current = self.packages.load(manifest_path)?;
834 match current
835 .workspace_config()
836 .get_ws_root(manifest_path, manifest_path)
837 {
838 Some(root_path) => {
839 debug!("find_root - is root {}", manifest_path.display());
840 Ok(Some(root_path))
841 }
842 None => find_workspace_root_with_loader(manifest_path, self.gctx, |self_path| {
843 Ok(self
844 .packages
845 .load(self_path)?
846 .workspace_config()
847 .get_ws_root(self_path, manifest_path))
848 }),
849 }
850 }
851
852 #[tracing::instrument(skip_all)]
860 fn find_members(&mut self) -> CargoResult<()> {
861 let Some(workspace_config) = self.load_workspace_config()? else {
862 debug!("find_members - only me as a member");
863 self.members.push(self.current_manifest.clone());
864 self.default_members.push(self.current_manifest.clone());
865 if let Ok(pkg) = self.current() {
866 let id = pkg.package_id();
867 self.member_ids.insert(id);
868 }
869 return Ok(());
870 };
871
872 let root_manifest_path = self.root_manifest.clone().unwrap();
874
875 let members_paths = workspace_config
876 .members_paths(workspace_config.members.as_deref().unwrap_or_default())?;
877 let default_members_paths = if root_manifest_path == self.current_manifest {
878 if let Some(ref default) = workspace_config.default_members {
879 Some(workspace_config.members_paths(default)?)
880 } else {
881 None
882 }
883 } else {
884 None
885 };
886
887 for (path, glob) in &members_paths {
888 self.find_path_deps(&path.join("Cargo.toml"), &root_manifest_path, false)
889 .with_context(|| {
890 format!(
891 "failed to load manifest for workspace member `{}`\n\
892 referenced{} by workspace at `{}`",
893 path.display(),
894 glob.map(|g| format!(" via `{g}`")).unwrap_or_default(),
895 root_manifest_path.display(),
896 )
897 })?;
898 }
899
900 self.find_path_deps(&root_manifest_path, &root_manifest_path, false)?;
901
902 if let Some(default) = default_members_paths {
903 for (path, default_member_glob) in default {
904 let normalized_path = paths::normalize_path(&path);
905 let manifest_path = normalized_path.join("Cargo.toml");
906 if !self.members.contains(&manifest_path) {
907 let exclude = members_paths.iter().any(|(m, _)| *m == normalized_path)
914 && workspace_config.is_excluded(&normalized_path);
915 if exclude {
916 continue;
917 }
918 bail!(
919 "package `{}` is listed in default-members{} but is not a member\n\
920 for workspace at `{}`.",
921 path.display(),
922 default_member_glob
923 .map(|g| format!(" via `{g}`"))
924 .unwrap_or_default(),
925 root_manifest_path.display(),
926 )
927 }
928 self.default_members.push(manifest_path)
929 }
930 } else if self.is_virtual() {
931 self.default_members = self.members.clone()
932 } else {
933 self.default_members.push(self.current_manifest.clone())
934 }
935
936 Ok(())
937 }
938
939 fn find_path_deps(
940 &mut self,
941 manifest_path: &Path,
942 root_manifest: &Path,
943 is_path_dep: bool,
944 ) -> CargoResult<()> {
945 let manifest_path = paths::normalize_path(manifest_path);
946 if self.members.contains(&manifest_path) {
947 return Ok(());
948 }
949 if is_path_dep && self.root_maybe().is_embedded() {
950 return Ok(());
952 }
953 if is_path_dep
954 && !manifest_path.parent().unwrap().starts_with(self.root())
955 && self.find_root(&manifest_path)? != self.root_manifest
956 {
957 return Ok(());
960 }
961
962 if let WorkspaceConfig::Root(ref root_config) =
963 *self.packages.load(root_manifest)?.workspace_config()
964 {
965 if root_config.is_excluded(&manifest_path) {
966 return Ok(());
967 }
968 }
969
970 debug!("find_path_deps - {}", manifest_path.display());
971 self.members.push(manifest_path.clone());
972
973 let candidates = {
974 let pkg = match *self.packages.load(&manifest_path)? {
975 MaybePackage::Package(ref p) => p,
976 MaybePackage::Virtual(_) => return Ok(()),
977 };
978 self.member_ids.insert(pkg.package_id());
979 pkg.dependencies()
980 .iter()
981 .map(|d| (d.source_id(), d.package_name()))
982 .filter(|(s, _)| s.is_path())
983 .filter_map(|(s, n)| s.url().to_file_path().ok().map(|p| (p, n)))
984 .map(|(p, n)| (p.join("Cargo.toml"), n))
985 .collect::<Vec<_>>()
986 };
987 for (path, name) in candidates {
988 self.find_path_deps(&path, root_manifest, true)
989 .with_context(|| format!("failed to load manifest for dependency `{}`", name))
990 .map_err(|err| ManifestError::new(err, manifest_path.clone()))?;
991 }
992 Ok(())
993 }
994
995 pub fn unstable_features(&self) -> &Features {
997 self.root_maybe().unstable_features()
998 }
999
1000 pub fn resolve_behavior(&self) -> ResolveBehavior {
1001 self.resolve_behavior
1002 }
1003
1004 pub fn allows_new_cli_feature_behavior(&self) -> bool {
1012 self.is_virtual()
1013 || match self.resolve_behavior() {
1014 ResolveBehavior::V1 => false,
1015 ResolveBehavior::V2 | ResolveBehavior::V3 => true,
1016 }
1017 }
1018
1019 #[tracing::instrument(skip_all)]
1025 fn validate(&mut self) -> CargoResult<()> {
1026 if self.root_manifest.is_none() {
1028 return Ok(());
1029 }
1030
1031 self.validate_unique_names()?;
1032 self.validate_workspace_roots()?;
1033 self.validate_members()?;
1034 self.error_if_manifest_not_in_members()?;
1035 self.validate_manifest()
1036 }
1037
1038 fn validate_unique_names(&self) -> CargoResult<()> {
1039 let mut names = BTreeMap::new();
1040 for member in self.members.iter() {
1041 let package = self.packages.get(member);
1042 let name = match *package {
1043 MaybePackage::Package(ref p) => p.name(),
1044 MaybePackage::Virtual(_) => continue,
1045 };
1046 if let Some(prev) = names.insert(name, member) {
1047 bail!(
1048 "two packages named `{}` in this workspace:\n\
1049 - {}\n\
1050 - {}",
1051 name,
1052 prev.display(),
1053 member.display()
1054 );
1055 }
1056 }
1057 Ok(())
1058 }
1059
1060 fn validate_workspace_roots(&self) -> CargoResult<()> {
1061 let roots: Vec<PathBuf> = self
1062 .members
1063 .iter()
1064 .filter(|&member| {
1065 let config = self.packages.get(member).workspace_config();
1066 matches!(config, WorkspaceConfig::Root(_))
1067 })
1068 .map(|member| member.parent().unwrap().to_path_buf())
1069 .collect();
1070 match roots.len() {
1071 1 => Ok(()),
1072 0 => bail!(
1073 "`package.workspace` configuration points to a crate \
1074 which is not configured with [workspace]: \n\
1075 configuration at: {}\n\
1076 points to: {}",
1077 self.current_manifest.display(),
1078 self.root_manifest.as_ref().unwrap().display()
1079 ),
1080 _ => {
1081 bail!(
1082 "multiple workspace roots found in the same workspace:\n{}",
1083 roots
1084 .iter()
1085 .map(|r| format!(" {}", r.display()))
1086 .collect::<Vec<_>>()
1087 .join("\n")
1088 );
1089 }
1090 }
1091 }
1092
1093 #[tracing::instrument(skip_all)]
1094 fn validate_members(&mut self) -> CargoResult<()> {
1095 for member in self.members.clone() {
1096 let root = self.find_root(&member)?;
1097 if root == self.root_manifest {
1098 continue;
1099 }
1100
1101 match root {
1102 Some(root) => {
1103 bail!(
1104 "package `{}` is a member of the wrong workspace\n\
1105 expected: {}\n\
1106 actual: {}",
1107 member.display(),
1108 self.root_manifest.as_ref().unwrap().display(),
1109 root.display()
1110 );
1111 }
1112 None => {
1113 bail!(
1114 "workspace member `{}` is not hierarchically below \
1115 the workspace root `{}`",
1116 member.display(),
1117 self.root_manifest.as_ref().unwrap().display()
1118 );
1119 }
1120 }
1121 }
1122 Ok(())
1123 }
1124
1125 fn error_if_manifest_not_in_members(&mut self) -> CargoResult<()> {
1126 if self.members.contains(&self.current_manifest) {
1127 return Ok(());
1128 }
1129
1130 let root = self.root_manifest.as_ref().unwrap();
1131 let root_dir = root.parent().unwrap();
1132 let current_dir = self.current_manifest.parent().unwrap();
1133 let root_pkg = self.packages.get(root);
1134
1135 let current_dir = paths::normalize_path(current_dir);
1141 let root_dir = paths::normalize_path(root_dir);
1142 let members_msg = match pathdiff::diff_paths(¤t_dir, &root_dir) {
1143 Some(rel) => format!(
1144 "this may be fixable by adding `{}` to the \
1145 `workspace.members` array of the manifest \
1146 located at: {}",
1147 rel.display(),
1148 root.display()
1149 ),
1150 None => format!(
1151 "this may be fixable by adding a member to \
1152 the `workspace.members` array of the \
1153 manifest located at: {}",
1154 root.display()
1155 ),
1156 };
1157 let extra = match *root_pkg {
1158 MaybePackage::Virtual(_) => members_msg,
1159 MaybePackage::Package(ref p) => {
1160 let has_members_list = match *p.manifest().workspace_config() {
1161 WorkspaceConfig::Root(ref root_config) => root_config.has_members_list(),
1162 WorkspaceConfig::Member { .. } => unreachable!(),
1163 };
1164 if !has_members_list {
1165 format!(
1166 "this may be fixable by ensuring that this \
1167 crate is depended on by the workspace \
1168 root: {}",
1169 root.display()
1170 )
1171 } else {
1172 members_msg
1173 }
1174 }
1175 };
1176 bail!(
1177 "current package believes it's in a workspace when it's not:\n\
1178 current: {}\n\
1179 workspace: {}\n\n{}\n\
1180 Alternatively, to keep it out of the workspace, add the package \
1181 to the `workspace.exclude` array, or add an empty `[workspace]` \
1182 table to the package's manifest.",
1183 self.current_manifest.display(),
1184 root.display(),
1185 extra
1186 );
1187 }
1188
1189 fn validate_manifest(&mut self) -> CargoResult<()> {
1190 if let Some(ref root_manifest) = self.root_manifest {
1191 for pkg in self
1192 .members()
1193 .filter(|p| p.manifest_path() != root_manifest)
1194 {
1195 let manifest = pkg.manifest();
1196 let emit_warning = |what| -> CargoResult<()> {
1197 let msg = format!(
1198 "{} for the non root package will be ignored, \
1199 specify {} at the workspace root:\n\
1200 package: {}\n\
1201 workspace: {}",
1202 what,
1203 what,
1204 pkg.manifest_path().display(),
1205 root_manifest.display(),
1206 );
1207 self.gctx.shell().warn(&msg)
1208 };
1209 if manifest.normalized_toml().has_profiles() {
1210 emit_warning("profiles")?;
1211 }
1212 if !manifest.replace().is_empty() {
1213 emit_warning("replace")?;
1214 }
1215 if !manifest.patch().is_empty() {
1216 emit_warning("patch")?;
1217 }
1218 if let Some(behavior) = manifest.resolve_behavior() {
1219 if behavior != self.resolve_behavior {
1220 emit_warning("resolver")?;
1222 }
1223 }
1224 }
1225 if let MaybePackage::Virtual(vm) = self.root_maybe() {
1226 if vm.resolve_behavior().is_none() {
1227 if let Some(edition) = self
1228 .members()
1229 .filter(|p| p.manifest_path() != root_manifest)
1230 .map(|p| p.manifest().edition())
1231 .filter(|&e| e >= Edition::Edition2021)
1232 .max()
1233 {
1234 let resolver = edition.default_resolve_behavior().to_manifest();
1235 let report = &[Level::WARNING
1236 .primary_title(format!(
1237 "virtual workspace defaulting to `resolver = \"1\"` despite one or more workspace members being on edition {edition} which implies `resolver = \"{resolver}\"`"
1238 ))
1239 .elements([
1240 Level::NOTE.message("to keep the current resolver, specify `workspace.resolver = \"1\"` in the workspace root's manifest"),
1241 Level::NOTE.message(
1242 format!("to use the edition {edition} resolver, specify `workspace.resolver = \"{resolver}\"` in the workspace root's manifest"),
1243 ),
1244 Level::NOTE.message("for more details see https://doc.rust-lang.org/cargo/reference/resolver.html#resolver-versions"),
1245 ])];
1246 self.gctx.shell().print_report(report, false)?;
1247 }
1248 }
1249 }
1250 }
1251 Ok(())
1252 }
1253
1254 pub fn load(&self, manifest_path: &Path) -> CargoResult<Package> {
1255 match self.packages.maybe_get(manifest_path) {
1256 Some(MaybePackage::Package(p)) => return Ok(p.clone()),
1257 Some(&MaybePackage::Virtual(_)) => bail!("cannot load workspace root"),
1258 None => {}
1259 }
1260
1261 let mut loaded = self.loaded_packages.borrow_mut();
1262 if let Some(p) = loaded.get(manifest_path).cloned() {
1263 return Ok(p);
1264 }
1265 let source_id = SourceId::for_manifest_path(manifest_path)?;
1266 let package = ops::read_package(manifest_path, source_id, self.gctx)?;
1267 loaded.insert(manifest_path.to_path_buf(), package.clone());
1268 Ok(package)
1269 }
1270
1271 pub fn preload(&self, registry: &mut PackageRegistry<'gctx>) {
1278 if self.is_ephemeral {
1284 return;
1285 }
1286
1287 for pkg in self.packages.packages.values() {
1288 let pkg = match *pkg {
1289 MaybePackage::Package(ref p) => p.clone(),
1290 MaybePackage::Virtual(_) => continue,
1291 };
1292 let src = PathSource::preload_with(pkg, self.gctx);
1293 registry.add_preloaded(Box::new(src));
1294 }
1295 }
1296
1297 pub fn set_target_dir(&mut self, target_dir: Filesystem) {
1298 self.target_dir = Some(target_dir);
1299 }
1300
1301 pub fn members_with_features(
1309 &self,
1310 specs: &[PackageIdSpec],
1311 cli_features: &CliFeatures,
1312 ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1313 assert!(
1314 !specs.is_empty() || cli_features.all_features,
1315 "no specs requires all_features"
1316 );
1317 if specs.is_empty() {
1318 return Ok(self
1321 .members()
1322 .map(|m| (m, CliFeatures::new_all(true)))
1323 .collect());
1324 }
1325 if self.allows_new_cli_feature_behavior() {
1326 self.members_with_features_new(specs, cli_features)
1327 } else {
1328 Ok(self.members_with_features_old(specs, cli_features))
1329 }
1330 }
1331
1332 fn collect_matching_features(
1335 member: &Package,
1336 cli_features: &CliFeatures,
1337 found_features: &mut BTreeSet<FeatureValue>,
1338 ) -> CliFeatures {
1339 if cli_features.features.is_empty() {
1340 return cli_features.clone();
1341 }
1342
1343 let summary = member.summary();
1345
1346 let summary_features = summary.features();
1348
1349 let dependencies: BTreeMap<InternedString, &Dependency> = summary
1351 .dependencies()
1352 .iter()
1353 .map(|dep| (dep.name_in_toml(), dep))
1354 .collect();
1355
1356 let optional_dependency_names: BTreeSet<_> = dependencies
1358 .iter()
1359 .filter(|(_, dep)| dep.is_optional())
1360 .map(|(name, _)| name)
1361 .copied()
1362 .collect();
1363
1364 let mut features = BTreeSet::new();
1365
1366 let summary_or_opt_dependency_feature = |feature: &InternedString| -> bool {
1368 summary_features.contains_key(feature) || optional_dependency_names.contains(feature)
1369 };
1370
1371 for feature in cli_features.features.iter() {
1372 match feature {
1373 FeatureValue::Feature(f) => {
1374 if summary_or_opt_dependency_feature(f) {
1375 features.insert(feature.clone());
1377 found_features.insert(feature.clone());
1378 }
1379 }
1380 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1382 FeatureValue::DepFeature {
1383 dep_name,
1384 dep_feature,
1385 weak: _,
1386 } => {
1387 if dependencies.contains_key(dep_name) {
1388 features.insert(feature.clone());
1391 found_features.insert(feature.clone());
1392 } else if *dep_name == member.name()
1393 && summary_or_opt_dependency_feature(dep_feature)
1394 {
1395 features.insert(FeatureValue::Feature(*dep_feature));
1400 found_features.insert(feature.clone());
1401 }
1402 }
1403 }
1404 }
1405 CliFeatures {
1406 features: Rc::new(features),
1407 all_features: cli_features.all_features,
1408 uses_default_features: cli_features.uses_default_features,
1409 }
1410 }
1411
1412 fn missing_feature_spelling_suggestions(
1413 &self,
1414 selected_members: &[&Package],
1415 cli_features: &CliFeatures,
1416 found_features: &BTreeSet<FeatureValue>,
1417 ) -> Vec<String> {
1418 let mut summary_features: Vec<InternedString> = Default::default();
1420
1421 let mut dependencies_features: BTreeMap<InternedString, &[InternedString]> =
1423 Default::default();
1424
1425 let mut optional_dependency_names: Vec<InternedString> = Default::default();
1427
1428 let mut summary_features_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1430 Default::default();
1431
1432 let mut optional_dependency_names_per_member: BTreeMap<&Package, BTreeSet<InternedString>> =
1434 Default::default();
1435
1436 for &member in selected_members {
1437 let summary = member.summary();
1439
1440 summary_features.extend(summary.features().keys());
1442 summary_features_per_member
1443 .insert(member, summary.features().keys().copied().collect());
1444
1445 let dependencies: BTreeMap<InternedString, &Dependency> = summary
1447 .dependencies()
1448 .iter()
1449 .map(|dep| (dep.name_in_toml(), dep))
1450 .collect();
1451
1452 dependencies_features.extend(
1453 dependencies
1454 .iter()
1455 .map(|(name, dep)| (*name, dep.features())),
1456 );
1457
1458 let optional_dependency_names_raw: BTreeSet<_> = dependencies
1460 .iter()
1461 .filter(|(_, dep)| dep.is_optional())
1462 .map(|(name, _)| name)
1463 .copied()
1464 .collect();
1465
1466 optional_dependency_names.extend(optional_dependency_names_raw.iter());
1467 optional_dependency_names_per_member.insert(member, optional_dependency_names_raw);
1468 }
1469
1470 let edit_distance_test = |a: InternedString, b: InternedString| {
1471 edit_distance(a.as_str(), b.as_str(), 3).is_some()
1472 };
1473
1474 cli_features
1475 .features
1476 .difference(found_features)
1477 .map(|feature| match feature {
1478 FeatureValue::Feature(typo) => {
1480 let summary_features = summary_features
1482 .iter()
1483 .filter(move |feature| edit_distance_test(**feature, *typo));
1484
1485 let optional_dependency_features = optional_dependency_names
1487 .iter()
1488 .filter(move |feature| edit_distance_test(**feature, *typo));
1489
1490 summary_features
1491 .chain(optional_dependency_features)
1492 .map(|s| s.to_string())
1493 .collect::<Vec<_>>()
1494 }
1495 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1496 FeatureValue::DepFeature {
1497 dep_name,
1498 dep_feature,
1499 weak: _,
1500 } => {
1501 let pkg_feat_similar = dependencies_features
1503 .iter()
1504 .filter(|(name, _)| edit_distance_test(**name, *dep_name))
1505 .map(|(name, features)| {
1506 (
1507 name,
1508 features
1509 .iter()
1510 .filter(|feature| edit_distance_test(**feature, *dep_feature))
1511 .collect::<Vec<_>>(),
1512 )
1513 })
1514 .map(|(name, features)| {
1515 features
1516 .into_iter()
1517 .map(move |feature| format!("{}/{}", name, feature))
1518 })
1519 .flatten();
1520
1521 let optional_dependency_features = optional_dependency_names_per_member
1523 .iter()
1524 .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1525 .map(|(package, optional_dependencies)| {
1526 optional_dependencies
1527 .into_iter()
1528 .filter(|optional_dependency| {
1529 edit_distance_test(**optional_dependency, *dep_name)
1530 })
1531 .map(move |optional_dependency| {
1532 format!("{}/{}", package.name(), optional_dependency)
1533 })
1534 })
1535 .flatten();
1536
1537 let summary_features = summary_features_per_member
1539 .iter()
1540 .filter(|(package, _)| edit_distance_test(package.name(), *dep_name))
1541 .map(|(package, summary_features)| {
1542 summary_features
1543 .into_iter()
1544 .filter(|summary_feature| {
1545 edit_distance_test(**summary_feature, *dep_feature)
1546 })
1547 .map(move |summary_feature| {
1548 format!("{}/{}", package.name(), summary_feature)
1549 })
1550 })
1551 .flatten();
1552
1553 pkg_feat_similar
1554 .chain(optional_dependency_features)
1555 .chain(summary_features)
1556 .collect::<Vec<_>>()
1557 }
1558 })
1559 .map(|v| v.into_iter())
1560 .flatten()
1561 .unique()
1562 .filter(|element| {
1563 let feature = FeatureValue::new(element.into());
1564 !cli_features.features.contains(&feature) && !found_features.contains(&feature)
1565 })
1566 .sorted()
1567 .take(5)
1568 .collect()
1569 }
1570
1571 fn report_unknown_features_error(
1572 &self,
1573 specs: &[PackageIdSpec],
1574 cli_features: &CliFeatures,
1575 found_features: &BTreeSet<FeatureValue>,
1576 ) -> CargoResult<()> {
1577 let unknown: Vec<_> = cli_features
1578 .features
1579 .difference(found_features)
1580 .map(|feature| feature.to_string())
1581 .sorted()
1582 .collect();
1583
1584 let (selected_members, unselected_members): (Vec<_>, Vec<_>) = self
1585 .members()
1586 .partition(|member| specs.iter().any(|spec| spec.matches(member.package_id())));
1587
1588 let missing_packages_with_the_features = unselected_members
1589 .into_iter()
1590 .filter(|member| {
1591 unknown
1592 .iter()
1593 .any(|feature| member.summary().features().contains_key(&**feature))
1594 })
1595 .map(|m| m.name())
1596 .collect_vec();
1597
1598 let these_features = if unknown.len() == 1 {
1599 "this feature"
1600 } else {
1601 "these features"
1602 };
1603 let mut msg = if let [singular] = &selected_members[..] {
1604 format!(
1605 "the package '{}' does not contain {these_features}: {}",
1606 singular.name(),
1607 unknown.join(", ")
1608 )
1609 } else {
1610 let names = selected_members.iter().map(|m| m.name()).join(", ");
1611 format!(
1612 "none of the selected packages contains {these_features}: {}\nselected packages: {names}",
1613 unknown.join(", ")
1614 )
1615 };
1616
1617 use std::fmt::Write;
1618 if !missing_packages_with_the_features.is_empty() {
1619 write!(
1620 &mut msg,
1621 "\nhelp: package{} with the missing feature{}: {}",
1622 if missing_packages_with_the_features.len() != 1 {
1623 "s"
1624 } else {
1625 ""
1626 },
1627 if unknown.len() != 1 { "s" } else { "" },
1628 missing_packages_with_the_features.join(", ")
1629 )?;
1630 } else {
1631 let suggestions = self.missing_feature_spelling_suggestions(
1632 &selected_members,
1633 cli_features,
1634 found_features,
1635 );
1636 if !suggestions.is_empty() {
1637 write!(
1638 &mut msg,
1639 "\nhelp: there {}: {}",
1640 if suggestions.len() == 1 {
1641 "is a similarly named feature"
1642 } else {
1643 "are similarly named features"
1644 },
1645 suggestions.join(", ")
1646 )?;
1647 }
1648 }
1649
1650 bail!("{msg}")
1651 }
1652
1653 fn members_with_features_new(
1656 &self,
1657 specs: &[PackageIdSpec],
1658 cli_features: &CliFeatures,
1659 ) -> CargoResult<Vec<(&Package, CliFeatures)>> {
1660 let mut found_features = Default::default();
1663
1664 let members: Vec<(&Package, CliFeatures)> = self
1665 .members()
1666 .filter(|m| specs.iter().any(|spec| spec.matches(m.package_id())))
1667 .map(|m| {
1668 (
1669 m,
1670 Workspace::collect_matching_features(m, cli_features, &mut found_features),
1671 )
1672 })
1673 .collect();
1674
1675 if members.is_empty() {
1676 if !(cli_features.features.is_empty()
1679 && !cli_features.all_features
1680 && cli_features.uses_default_features)
1681 {
1682 let hint = specs
1683 .iter()
1684 .map(|spec| {
1685 closest_msg(
1686 spec.name(),
1687 self.members(),
1688 |m| m.name().as_str(),
1689 "workspace member",
1690 )
1691 })
1692 .find(|msg| !msg.is_empty())
1693 .unwrap_or_default();
1694 bail!("cannot specify features for packages outside of workspace{hint}");
1695 }
1696 return Ok(self
1699 .members()
1700 .map(|m| (m, CliFeatures::new_all(false)))
1701 .collect());
1702 }
1703 if *cli_features.features != found_features {
1704 self.report_unknown_features_error(specs, cli_features, &found_features)?;
1705 }
1706 Ok(members)
1707 }
1708
1709 fn members_with_features_old(
1712 &self,
1713 specs: &[PackageIdSpec],
1714 cli_features: &CliFeatures,
1715 ) -> Vec<(&Package, CliFeatures)> {
1716 let mut member_specific_features: HashMap<InternedString, BTreeSet<FeatureValue>> =
1719 HashMap::new();
1720 let mut cwd_features = BTreeSet::new();
1722 for feature in cli_features.features.iter() {
1723 match feature {
1724 FeatureValue::Feature(_) => {
1725 cwd_features.insert(feature.clone());
1726 }
1727 FeatureValue::Dep { .. } => panic!("unexpected dep: syntax {}", feature),
1729 FeatureValue::DepFeature {
1730 dep_name,
1731 dep_feature,
1732 weak: _,
1733 } => {
1734 let is_member = self.members().any(|member| {
1740 self.current_opt() != Some(member) && member.name() == *dep_name
1742 });
1743 if is_member && specs.iter().any(|spec| spec.name() == dep_name.as_str()) {
1744 member_specific_features
1745 .entry(*dep_name)
1746 .or_default()
1747 .insert(FeatureValue::Feature(*dep_feature));
1748 } else {
1749 cwd_features.insert(feature.clone());
1750 }
1751 }
1752 }
1753 }
1754
1755 let ms: Vec<_> = self
1756 .members()
1757 .filter_map(|member| {
1758 let member_id = member.package_id();
1759 match self.current_opt() {
1760 Some(current) if member_id == current.package_id() => {
1763 let feats = CliFeatures {
1764 features: Rc::new(cwd_features.clone()),
1765 all_features: cli_features.all_features,
1766 uses_default_features: cli_features.uses_default_features,
1767 };
1768 Some((member, feats))
1769 }
1770 _ => {
1771 if specs.iter().any(|spec| spec.matches(member_id)) {
1773 let feats = CliFeatures {
1783 features: Rc::new(
1784 member_specific_features
1785 .remove(member.name().as_str())
1786 .unwrap_or_default(),
1787 ),
1788 uses_default_features: true,
1789 all_features: cli_features.all_features,
1790 };
1791 Some((member, feats))
1792 } else {
1793 None
1795 }
1796 }
1797 }
1798 })
1799 .collect();
1800
1801 assert!(member_specific_features.is_empty());
1804
1805 ms
1806 }
1807
1808 pub fn unit_needs_doc_scrape(&self, unit: &Unit) -> bool {
1810 self.is_member(&unit.pkg) && !(unit.target.for_host() || unit.pkg.proc_macro())
1815 }
1816
1817 pub fn add_local_overlay(&mut self, id: SourceId, registry_path: PathBuf) {
1821 self.local_overlays.insert(id, registry_path);
1822 }
1823
1824 pub fn package_registry(&self) -> CargoResult<PackageRegistry<'gctx>> {
1826 let source_config =
1827 SourceConfigMap::new_with_overlays(self.gctx(), self.local_overlays()?)?;
1828 PackageRegistry::new_with_source_config(self.gctx(), source_config)
1829 }
1830
1831 fn local_overlays(&self) -> CargoResult<impl Iterator<Item = (SourceId, SourceId)>> {
1833 let mut ret = self
1834 .local_overlays
1835 .iter()
1836 .map(|(id, path)| Ok((*id, SourceId::for_local_registry(path)?)))
1837 .collect::<CargoResult<Vec<_>>>()?;
1838
1839 if let Ok(overlay) = self
1840 .gctx
1841 .get_env("__CARGO_TEST_DEPENDENCY_CONFUSION_VULNERABILITY_DO_NOT_USE_THIS")
1842 {
1843 let (url, path) = overlay.split_once('=').ok_or(anyhow::anyhow!(
1844 "invalid overlay format. I won't tell you why; you shouldn't be using it anyway"
1845 ))?;
1846 ret.push((
1847 SourceId::from_url(url)?,
1848 SourceId::for_local_registry(path.as_ref())?,
1849 ));
1850 }
1851
1852 Ok(ret.into_iter())
1853 }
1854}
1855
1856impl<'gctx> Packages<'gctx> {
1857 fn get(&self, manifest_path: &Path) -> &MaybePackage {
1858 self.maybe_get(manifest_path).unwrap()
1859 }
1860
1861 fn get_mut(&mut self, manifest_path: &Path) -> &mut MaybePackage {
1862 self.maybe_get_mut(manifest_path).unwrap()
1863 }
1864
1865 fn maybe_get(&self, manifest_path: &Path) -> Option<&MaybePackage> {
1866 self.packages.get(manifest_path)
1867 }
1868
1869 fn maybe_get_mut(&mut self, manifest_path: &Path) -> Option<&mut MaybePackage> {
1870 self.packages.get_mut(manifest_path)
1871 }
1872
1873 fn load(&mut self, manifest_path: &Path) -> CargoResult<&MaybePackage> {
1874 match self.packages.entry(manifest_path.to_path_buf()) {
1875 Entry::Occupied(e) => Ok(e.into_mut()),
1876 Entry::Vacant(v) => {
1877 let source_id = SourceId::for_manifest_path(manifest_path)?;
1878 let manifest = read_manifest(manifest_path, source_id, self.gctx)?;
1879 Ok(v.insert(match manifest {
1880 EitherManifest::Real(manifest) => {
1881 MaybePackage::Package(Package::new(manifest, manifest_path))
1882 }
1883 EitherManifest::Virtual(vm) => MaybePackage::Virtual(vm),
1884 }))
1885 }
1886 }
1887 }
1888}
1889
1890impl MaybePackage {
1891 fn workspace_config(&self) -> &WorkspaceConfig {
1892 match *self {
1893 MaybePackage::Package(ref p) => p.manifest().workspace_config(),
1894 MaybePackage::Virtual(ref vm) => vm.workspace_config(),
1895 }
1896 }
1897
1898 pub fn as_package(&self) -> Option<&Package> {
1899 match self {
1900 MaybePackage::Package(p) => Some(p),
1901 MaybePackage::Virtual(_) => None,
1902 }
1903 }
1904
1905 pub fn is_embedded(&self) -> bool {
1907 match self {
1908 MaybePackage::Package(p) => p.manifest().is_embedded(),
1909 MaybePackage::Virtual(_) => false,
1910 }
1911 }
1912
1913 pub fn contents(&self) -> Option<&str> {
1914 match self {
1915 MaybePackage::Package(p) => p.manifest().contents(),
1916 MaybePackage::Virtual(v) => v.contents(),
1917 }
1918 }
1919
1920 pub fn document(&self) -> Option<&toml::Spanned<toml::de::DeTable<'static>>> {
1921 match self {
1922 MaybePackage::Package(p) => p.manifest().document(),
1923 MaybePackage::Virtual(v) => v.document(),
1924 }
1925 }
1926
1927 pub fn original_toml(&self) -> Option<&TomlManifest> {
1928 match self {
1929 MaybePackage::Package(p) => p.manifest().original_toml(),
1930 MaybePackage::Virtual(v) => v.original_toml(),
1931 }
1932 }
1933
1934 pub fn normalized_toml(&self) -> &TomlManifest {
1935 match self {
1936 MaybePackage::Package(p) => p.manifest().normalized_toml(),
1937 MaybePackage::Virtual(v) => v.normalized_toml(),
1938 }
1939 }
1940
1941 pub fn edition(&self) -> Edition {
1942 match self {
1943 MaybePackage::Package(p) => p.manifest().edition(),
1944 MaybePackage::Virtual(_) => Edition::default(),
1945 }
1946 }
1947
1948 pub fn profiles(&self) -> Option<&TomlProfiles> {
1949 match self {
1950 MaybePackage::Package(p) => p.manifest().profiles(),
1951 MaybePackage::Virtual(v) => v.profiles(),
1952 }
1953 }
1954
1955 pub fn unstable_features(&self) -> &Features {
1956 match self {
1957 MaybePackage::Package(p) => p.manifest().unstable_features(),
1958 MaybePackage::Virtual(vm) => vm.unstable_features(),
1959 }
1960 }
1961}
1962
1963impl WorkspaceRootConfig {
1964 pub fn new(
1966 root_dir: &Path,
1967 members: &Option<Vec<String>>,
1968 default_members: &Option<Vec<String>>,
1969 exclude: &Option<Vec<String>>,
1970 inheritable: &Option<InheritableFields>,
1971 custom_metadata: &Option<toml::Value>,
1972 ) -> WorkspaceRootConfig {
1973 WorkspaceRootConfig {
1974 root_dir: root_dir.to_path_buf(),
1975 members: members.clone(),
1976 default_members: default_members.clone(),
1977 exclude: exclude.clone().unwrap_or_default(),
1978 inheritable_fields: inheritable.clone().unwrap_or_default(),
1979 custom_metadata: custom_metadata.clone(),
1980 }
1981 }
1982 fn is_excluded(&self, manifest_path: &Path) -> bool {
1986 let excluded = self
1987 .exclude
1988 .iter()
1989 .any(|ex| manifest_path.starts_with(self.root_dir.join(ex)));
1990
1991 let explicit_member = match self.members {
1992 Some(ref members) => members
1993 .iter()
1994 .any(|mem| manifest_path.starts_with(self.root_dir.join(mem))),
1995 None => false,
1996 };
1997
1998 !explicit_member && excluded
1999 }
2000
2001 fn is_explicitly_listed_member(&self, manifest_path: &Path) -> bool {
2012 let root_manifest = self.root_dir.join("Cargo.toml");
2013 if manifest_path == root_manifest {
2014 return true;
2015 }
2016 match self.members {
2017 Some(ref members) => {
2018 let Ok(expanded_members) = self.members_paths(members) else {
2020 return false;
2021 };
2022 let normalized_manifest = paths::normalize_path(manifest_path);
2024 expanded_members.iter().any(|(member_path, _)| {
2025 let normalized_member = paths::normalize_path(member_path);
2027 normalized_manifest.parent() == Some(normalized_member.as_path())
2030 })
2031 }
2032 None => false,
2033 }
2034 }
2035
2036 fn has_members_list(&self) -> bool {
2037 self.members.is_some()
2038 }
2039
2040 fn has_default_members(&self) -> bool {
2042 self.default_members.is_some()
2043 }
2044
2045 #[tracing::instrument(skip_all)]
2048 fn members_paths<'g>(
2049 &self,
2050 globs: &'g [String],
2051 ) -> CargoResult<Vec<(PathBuf, Option<&'g str>)>> {
2052 let mut expanded_list = Vec::new();
2053
2054 for glob in globs {
2055 let pathbuf = self.root_dir.join(glob);
2056 let expanded_paths = Self::expand_member_path(&pathbuf)?;
2057
2058 if expanded_paths.is_empty() {
2061 expanded_list.push((pathbuf, None));
2062 } else {
2063 let used_glob_pattern = expanded_paths.len() > 1 || expanded_paths[0] != pathbuf;
2064 let glob = used_glob_pattern.then_some(glob.as_str());
2065
2066 for expanded_path in expanded_paths {
2072 if expanded_path.is_dir() {
2073 expanded_list.push((expanded_path, glob));
2074 }
2075 }
2076 }
2077 }
2078
2079 Ok(expanded_list)
2080 }
2081
2082 fn expand_member_path(path: &Path) -> CargoResult<Vec<PathBuf>> {
2083 let Some(path) = path.to_str() else {
2084 return Ok(Vec::new());
2085 };
2086 let res = glob(path).with_context(|| format!("could not parse pattern `{}`", &path))?;
2087 let res = res
2088 .map(|p| p.with_context(|| format!("unable to match path to pattern `{}`", &path)))
2089 .collect::<Result<Vec<_>, _>>()?;
2090 Ok(res)
2091 }
2092
2093 pub fn inheritable(&self) -> &InheritableFields {
2094 &self.inheritable_fields
2095 }
2096}
2097
2098fn warn_unused_min_publish_age(gctx: &GlobalContext) -> CargoResult<()> {
2099 if gctx
2100 .get::<Option<String>>("registry.global-min-publish-age")?
2101 .is_some()
2102 {
2103 gctx.shell()
2104 .warn("ignoring `registry.global-min-publish-age` without `-Zmin-publish-age`")?;
2105 }
2106
2107 if gctx
2108 .get::<Option<String>>("registry.min-publish-age")?
2109 .is_some()
2110 {
2111 gctx.shell()
2112 .warn("ignoring `registry.min-publish-age` without `-Zmin-publish-age`")?;
2113 }
2114
2115 if let Some(context::ConfigValue::Table(registries, _)) = gctx.values()?.get("registries") {
2116 for (name, val) in registries {
2117 if let context::ConfigValue::Table(val, _) = val {
2118 if val.contains_key("min-publish-age") {
2119 gctx.shell().warn(format!(
2120 "ignoring `registries.{name}.min-publish-age` without `-Zmin-publish-age`"
2121 ))?;
2122 }
2123 }
2124 }
2125 }
2126
2127 Ok(())
2128}
2129
2130pub fn resolve_relative_path(
2131 label: &str,
2132 old_root: &Path,
2133 new_root: &Path,
2134 rel_path: &str,
2135) -> CargoResult<String> {
2136 let joined_path = normalize_path(&old_root.join(rel_path));
2137 match diff_paths(joined_path, new_root) {
2138 None => Err(anyhow!(
2139 "`{}` was defined in {} but could not be resolved with {}",
2140 label,
2141 old_root.display(),
2142 new_root.display()
2143 )),
2144 Some(path) => Ok(path
2145 .to_str()
2146 .ok_or_else(|| {
2147 anyhow!(
2148 "`{}` resolved to non-UTF value (`{}`)",
2149 label,
2150 path.display()
2151 )
2152 })?
2153 .to_owned()),
2154 }
2155}
2156
2157pub fn find_workspace_root(
2159 manifest_path: &Path,
2160 gctx: &GlobalContext,
2161) -> CargoResult<Option<PathBuf>> {
2162 find_workspace_root_with_loader(manifest_path, gctx, |self_path| {
2163 let source_id = SourceId::for_manifest_path(self_path)?;
2164 let manifest = read_manifest(self_path, source_id, gctx)?;
2165 Ok(manifest
2166 .workspace_config()
2167 .get_ws_root(self_path, manifest_path))
2168 })
2169}
2170
2171pub fn find_workspace_root_with_membership_check(
2178 manifest_path: &Path,
2179 gctx: &GlobalContext,
2180) -> CargoResult<Option<PathBuf>> {
2181 let source_id = SourceId::for_manifest_path(manifest_path)?;
2182 let current_manifest = read_manifest(manifest_path, source_id, gctx)?;
2183
2184 match current_manifest.workspace_config() {
2185 WorkspaceConfig::Root(root_config) => {
2186 if root_config.has_default_members() {
2189 Ok(None)
2190 } else {
2191 Ok(Some(manifest_path.to_path_buf()))
2192 }
2193 }
2194 WorkspaceConfig::Member {
2195 root: Some(path_to_root),
2196 } => {
2197 let ws_manifest_path = read_root_pointer(manifest_path, path_to_root);
2199 let ws_source_id = SourceId::for_manifest_path(&ws_manifest_path)?;
2200 let ws_manifest = read_manifest(&ws_manifest_path, ws_source_id, gctx)?;
2201
2202 if let WorkspaceConfig::Root(ref root_config) = *ws_manifest.workspace_config() {
2204 if root_config.is_explicitly_listed_member(manifest_path)
2205 && !root_config.is_excluded(manifest_path)
2206 {
2207 return Ok(Some(ws_manifest_path));
2208 }
2209 }
2210 Ok(None)
2212 }
2213 WorkspaceConfig::Member { root: None } => {
2214 find_workspace_root_with_loader(manifest_path, gctx, |candidate_manifest_path| {
2216 let source_id = SourceId::for_manifest_path(candidate_manifest_path)?;
2217 let manifest = read_manifest(candidate_manifest_path, source_id, gctx)?;
2218 if let WorkspaceConfig::Root(ref root_config) = *manifest.workspace_config() {
2219 if root_config.is_explicitly_listed_member(manifest_path)
2220 && !root_config.is_excluded(manifest_path)
2221 {
2222 return Ok(Some(candidate_manifest_path.to_path_buf()));
2223 }
2224 }
2225 Ok(None)
2226 })
2227 }
2228 }
2229}
2230
2231fn find_workspace_root_with_loader(
2236 manifest_path: &Path,
2237 gctx: &GlobalContext,
2238 mut loader: impl FnMut(&Path) -> CargoResult<Option<PathBuf>>,
2239) -> CargoResult<Option<PathBuf>> {
2240 {
2242 let roots = gctx.ws_roots();
2243 for current in manifest_path.ancestors().skip(1) {
2246 if let Some(ws_config) = roots.get(current) {
2247 if !ws_config.is_excluded(manifest_path) {
2248 return Ok(Some(current.join("Cargo.toml")));
2250 }
2251 }
2252 }
2253 }
2254
2255 for ances_manifest_path in find_root_iter(manifest_path, gctx) {
2256 debug!("find_root - trying {}", ances_manifest_path.display());
2257 let ws_root_path = loader(&ances_manifest_path).with_context(|| {
2258 format!(
2259 "failed searching for potential workspace\n\
2260 package manifest: `{}`\n\
2261 invalid potential workspace manifest: `{}`\n\
2262 \n\
2263 help: to avoid searching for a non-existent workspace, add \
2264 `[workspace]` to the package manifest",
2265 manifest_path.display(),
2266 ances_manifest_path.display(),
2267 )
2268 })?;
2269 if let Some(ws_root_path) = ws_root_path {
2270 return Ok(Some(ws_root_path));
2271 }
2272 }
2273 Ok(None)
2274}
2275
2276fn read_root_pointer(member_manifest: &Path, root_link: &str) -> PathBuf {
2277 let path = member_manifest
2278 .parent()
2279 .unwrap()
2280 .join(root_link)
2281 .join("Cargo.toml");
2282 debug!("find_root - pointer {}", path.display());
2283 paths::normalize_path(&path)
2284}
2285
2286fn find_root_iter<'a>(
2287 manifest_path: &'a Path,
2288 gctx: &'a GlobalContext,
2289) -> impl Iterator<Item = PathBuf> + 'a {
2290 LookBehind::new(paths::ancestors(manifest_path, None).skip(2))
2291 .take_while(|path| !path.curr.ends_with("target/package"))
2292 .take_while(|path| {
2298 if let Some(last) = path.last {
2299 gctx.home() != last
2300 } else {
2301 true
2302 }
2303 })
2304 .map(|path| path.curr.join("Cargo.toml"))
2305 .filter(|ances_manifest_path| ances_manifest_path.exists())
2306}
2307
2308struct LookBehindWindow<'a, T: ?Sized> {
2309 curr: &'a T,
2310 last: Option<&'a T>,
2311}
2312
2313struct LookBehind<'a, T: ?Sized, K: Iterator<Item = &'a T>> {
2314 iter: K,
2315 last: Option<&'a T>,
2316}
2317
2318impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> LookBehind<'a, T, K> {
2319 fn new(items: K) -> Self {
2320 Self {
2321 iter: items,
2322 last: None,
2323 }
2324 }
2325}
2326
2327impl<'a, T: ?Sized, K: Iterator<Item = &'a T>> Iterator for LookBehind<'a, T, K> {
2328 type Item = LookBehindWindow<'a, T>;
2329
2330 fn next(&mut self) -> Option<Self::Item> {
2331 match self.iter.next() {
2332 None => None,
2333 Some(next) => {
2334 let last = self.last;
2335 self.last = Some(next);
2336 Some(LookBehindWindow { curr: next, last })
2337 }
2338 }
2339 }
2340}