1use annotate_snippets::{Level, Snippet};
2use std::borrow::Cow;
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::ffi::OsStr;
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7use std::str::{self, FromStr};
8
9use crate::core::summary::MissingDependencyError;
10use crate::AlreadyPrintedError;
11use anyhow::{anyhow, bail, Context as _};
12use cargo_platform::Platform;
13use cargo_util::paths;
14use cargo_util_schemas::manifest::{
15 self, PackageName, PathBaseName, TomlDependency, TomlDetailedDependency, TomlManifest,
16};
17use cargo_util_schemas::manifest::{RustVersion, StringOrBool};
18use itertools::Itertools;
19use lazycell::LazyCell;
20use pathdiff::diff_paths;
21use toml_edit::ImDocument;
22use url::Url;
23
24use crate::core::compiler::{CompileKind, CompileTarget};
25use crate::core::dependency::{Artifact, ArtifactTarget, DepKind};
26use crate::core::manifest::{ManifestMetadata, TargetSourcePath};
27use crate::core::resolver::ResolveBehavior;
28use crate::core::{find_workspace_root, resolve_relative_path, CliUnstable, FeatureValue};
29use crate::core::{Dependency, Manifest, Package, PackageId, Summary, Target};
30use crate::core::{Edition, EitherManifest, Feature, Features, VirtualManifest, Workspace};
31use crate::core::{GitReference, PackageIdSpec, SourceId, WorkspaceConfig, WorkspaceRootConfig};
32use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY};
33use crate::util::errors::{CargoResult, ManifestError};
34use crate::util::interning::InternedString;
35use crate::util::lints::{get_span, rel_cwd_manifest_path};
36use crate::util::{self, context::ConfigRelativePath, GlobalContext, IntoUrl, OptVersionReq};
37
38mod embedded;
39mod targets;
40
41use self::targets::to_targets;
42
43pub use embedded::ScriptSource;
44
45pub fn is_embedded(path: &Path) -> bool {
47 let ext = path.extension();
48 ext == Some(OsStr::new("rs")) ||
49 (ext.is_none() && path.is_file())
51}
52
53#[tracing::instrument(skip(gctx))]
62pub fn read_manifest(
63 path: &Path,
64 source_id: SourceId,
65 gctx: &GlobalContext,
66) -> CargoResult<EitherManifest> {
67 let mut warnings = Default::default();
68 let mut errors = Default::default();
69
70 let is_embedded = is_embedded(path);
71 let contents = read_toml_string(path, is_embedded, gctx)
72 .map_err(|err| ManifestError::new(err, path.into()))?;
73 let document =
74 parse_document(&contents).map_err(|e| emit_diagnostic(e.into(), &contents, path, gctx))?;
75 let original_toml = deserialize_toml(&document)
76 .map_err(|e| emit_diagnostic(e.into(), &contents, path, gctx))?;
77
78 let mut manifest = (|| {
79 let empty = Vec::new();
80 let cargo_features = original_toml.cargo_features.as_ref().unwrap_or(&empty);
81 let features = Features::new(cargo_features, gctx, &mut warnings, source_id.is_path())?;
82 let workspace_config = to_workspace_config(&original_toml, path, gctx, &mut warnings)?;
83 if let WorkspaceConfig::Root(ws_root_config) = &workspace_config {
84 let package_root = path.parent().unwrap();
85 gctx.ws_roots
86 .borrow_mut()
87 .insert(package_root.to_owned(), ws_root_config.clone());
88 }
89 let normalized_toml = normalize_toml(
90 &original_toml,
91 &features,
92 &workspace_config,
93 path,
94 is_embedded,
95 gctx,
96 &mut warnings,
97 &mut errors,
98 )?;
99
100 if normalized_toml.package().is_some() {
101 to_real_manifest(
102 contents,
103 document,
104 original_toml,
105 normalized_toml,
106 features,
107 workspace_config,
108 source_id,
109 path,
110 is_embedded,
111 gctx,
112 &mut warnings,
113 &mut errors,
114 )
115 .map(EitherManifest::Real)
116 } else if normalized_toml.workspace.is_some() {
117 assert!(!is_embedded);
118 to_virtual_manifest(
119 contents,
120 document,
121 original_toml,
122 normalized_toml,
123 features,
124 workspace_config,
125 source_id,
126 path,
127 gctx,
128 &mut warnings,
129 &mut errors,
130 )
131 .map(EitherManifest::Virtual)
132 } else {
133 anyhow::bail!("manifest is missing either a `[package]` or a `[workspace]`")
134 }
135 })()
136 .map_err(|err| {
137 ManifestError::new(
138 err.context(format!("failed to parse manifest at `{}`", path.display())),
139 path.into(),
140 )
141 })?;
142
143 for warning in warnings {
144 manifest.warnings_mut().add_warning(warning);
145 }
146 for error in errors {
147 manifest.warnings_mut().add_critical_warning(error);
148 }
149
150 Ok(manifest)
151}
152
153#[tracing::instrument(skip_all)]
154fn read_toml_string(path: &Path, is_embedded: bool, gctx: &GlobalContext) -> CargoResult<String> {
155 let mut contents = paths::read(path)?;
156 if is_embedded {
157 if !gctx.cli_unstable().script {
158 anyhow::bail!("parsing `{}` requires `-Zscript`", path.display());
159 }
160 contents = embedded::expand_manifest(&contents, path, gctx)?;
161 }
162 Ok(contents)
163}
164
165#[tracing::instrument(skip_all)]
166fn parse_document(contents: &str) -> Result<toml_edit::ImDocument<String>, toml_edit::de::Error> {
167 toml_edit::ImDocument::parse(contents.to_owned()).map_err(Into::into)
168}
169
170#[tracing::instrument(skip_all)]
171fn deserialize_toml(
172 document: &toml_edit::ImDocument<String>,
173) -> Result<manifest::TomlManifest, toml_edit::de::Error> {
174 let mut unused = BTreeSet::new();
175 let deserializer = toml_edit::de::Deserializer::from(document.clone());
176 let mut document: manifest::TomlManifest = serde_ignored::deserialize(deserializer, |path| {
177 let mut key = String::new();
178 stringify(&mut key, &path);
179 unused.insert(key);
180 })?;
181 document._unused_keys = unused;
182 Ok(document)
183}
184
185fn stringify(dst: &mut String, path: &serde_ignored::Path<'_>) {
186 use serde_ignored::Path;
187
188 match *path {
189 Path::Root => {}
190 Path::Seq { parent, index } => {
191 stringify(dst, parent);
192 if !dst.is_empty() {
193 dst.push('.');
194 }
195 dst.push_str(&index.to_string());
196 }
197 Path::Map { parent, ref key } => {
198 stringify(dst, parent);
199 if !dst.is_empty() {
200 dst.push('.');
201 }
202 dst.push_str(key);
203 }
204 Path::Some { parent }
205 | Path::NewtypeVariant { parent }
206 | Path::NewtypeStruct { parent } => stringify(dst, parent),
207 }
208}
209
210fn to_workspace_config(
211 original_toml: &manifest::TomlManifest,
212 manifest_file: &Path,
213 gctx: &GlobalContext,
214 warnings: &mut Vec<String>,
215) -> CargoResult<WorkspaceConfig> {
216 let workspace_config = match (
217 original_toml.workspace.as_ref(),
218 original_toml.package().and_then(|p| p.workspace.as_ref()),
219 ) {
220 (Some(toml_config), None) => {
221 verify_lints(toml_config.lints.as_ref(), gctx, warnings)?;
222 if let Some(ws_deps) = &toml_config.dependencies {
223 for (name, dep) in ws_deps {
224 if dep.is_optional() {
225 bail!("{name} is optional, but workspace dependencies cannot be optional",);
226 }
227 if dep.is_public() {
228 bail!("{name} is public, but workspace dependencies cannot be public",);
229 }
230 }
231
232 for (name, dep) in ws_deps {
233 unused_dep_keys(name, "workspace.dependencies", dep.unused_keys(), warnings);
234 }
235 }
236 let ws_root_config = to_workspace_root_config(toml_config, manifest_file);
237 WorkspaceConfig::Root(ws_root_config)
238 }
239 (None, root) => WorkspaceConfig::Member {
240 root: root.cloned(),
241 },
242 (Some(..), Some(..)) => bail!(
243 "cannot configure both `package.workspace` and \
244 `[workspace]`, only one can be specified"
245 ),
246 };
247 Ok(workspace_config)
248}
249
250fn to_workspace_root_config(
251 normalized_toml: &manifest::TomlWorkspace,
252 manifest_file: &Path,
253) -> WorkspaceRootConfig {
254 let package_root = manifest_file.parent().unwrap();
255 let inheritable = InheritableFields {
256 package: normalized_toml.package.clone(),
257 dependencies: normalized_toml.dependencies.clone(),
258 lints: normalized_toml.lints.clone(),
259 _ws_root: package_root.to_owned(),
260 };
261 let ws_root_config = WorkspaceRootConfig::new(
262 package_root,
263 &normalized_toml.members,
264 &normalized_toml.default_members,
265 &normalized_toml.exclude,
266 &Some(inheritable),
267 &normalized_toml.metadata,
268 );
269 ws_root_config
270}
271
272#[tracing::instrument(skip_all)]
274fn normalize_toml(
275 original_toml: &manifest::TomlManifest,
276 features: &Features,
277 workspace_config: &WorkspaceConfig,
278 manifest_file: &Path,
279 is_embedded: bool,
280 gctx: &GlobalContext,
281 warnings: &mut Vec<String>,
282 errors: &mut Vec<String>,
283) -> CargoResult<manifest::TomlManifest> {
284 let package_root = manifest_file.parent().unwrap();
285
286 let inherit_cell: LazyCell<InheritableFields> = LazyCell::new();
287 let inherit = || {
288 inherit_cell
289 .try_borrow_with(|| load_inheritable_fields(gctx, manifest_file, &workspace_config))
290 };
291 let workspace_root = || inherit().map(|fields| fields.ws_root().as_path());
292
293 let mut normalized_toml = manifest::TomlManifest {
294 cargo_features: original_toml.cargo_features.clone(),
295 package: None,
296 project: None,
297 badges: None,
298 features: None,
299 lib: None,
300 bin: None,
301 example: None,
302 test: None,
303 bench: None,
304 dependencies: None,
305 dev_dependencies: None,
306 dev_dependencies2: None,
307 build_dependencies: None,
308 build_dependencies2: None,
309 target: None,
310 lints: None,
311 workspace: original_toml.workspace.clone().or_else(|| {
312 is_embedded.then(manifest::TomlWorkspace::default)
314 }),
315 profile: original_toml.profile.clone(),
316 patch: normalize_patch(
317 gctx,
318 original_toml.patch.as_ref(),
319 &workspace_root,
320 features,
321 )?,
322 replace: original_toml.replace.clone(),
323 _unused_keys: Default::default(),
324 };
325
326 if let Some(original_package) = original_toml.package().map(Cow::Borrowed).or_else(|| {
327 if is_embedded {
328 Some(Cow::Owned(Box::new(manifest::TomlPackage::default())))
329 } else {
330 None
331 }
332 }) {
333 let normalized_package = normalize_package_toml(
334 &original_package,
335 manifest_file,
336 is_embedded,
337 gctx,
338 &inherit,
339 )?;
340 let package_name = &normalized_package
341 .normalized_name()
342 .expect("previously normalized")
343 .clone();
344 let edition = normalized_package
345 .normalized_edition()
346 .expect("previously normalized")
347 .map_or(Edition::default(), |e| {
348 Edition::from_str(&e).unwrap_or_default()
349 });
350 normalized_toml.package = Some(normalized_package);
351
352 normalized_toml.features = normalize_features(original_toml.features.as_ref())?;
353
354 let auto_embedded = is_embedded.then_some(false);
355 normalized_toml.lib = targets::normalize_lib(
356 original_toml.lib.as_ref(),
357 package_root,
358 package_name,
359 edition,
360 original_package.autolib.or(auto_embedded),
361 warnings,
362 )?;
363 normalized_toml.bin = Some(targets::normalize_bins(
364 original_toml.bin.as_ref(),
365 package_root,
366 package_name,
367 edition,
368 original_package.autobins.or(auto_embedded),
369 warnings,
370 errors,
371 normalized_toml.lib.is_some(),
372 )?);
373 normalized_toml.example = Some(targets::normalize_examples(
374 original_toml.example.as_ref(),
375 package_root,
376 edition,
377 original_package.autoexamples.or(auto_embedded),
378 warnings,
379 errors,
380 )?);
381 normalized_toml.test = Some(targets::normalize_tests(
382 original_toml.test.as_ref(),
383 package_root,
384 edition,
385 original_package.autotests.or(auto_embedded),
386 warnings,
387 errors,
388 )?);
389 normalized_toml.bench = Some(targets::normalize_benches(
390 original_toml.bench.as_ref(),
391 package_root,
392 edition,
393 original_package.autobenches.or(auto_embedded),
394 warnings,
395 errors,
396 )?);
397
398 normalized_toml.dependencies = normalize_dependencies(
399 gctx,
400 edition,
401 &features,
402 original_toml.dependencies.as_ref(),
403 None,
404 &inherit,
405 &workspace_root,
406 package_root,
407 warnings,
408 )?;
409 deprecated_underscore(
410 &original_toml.dev_dependencies2,
411 &original_toml.dev_dependencies,
412 "dev-dependencies",
413 package_name,
414 "package",
415 edition,
416 warnings,
417 )?;
418 normalized_toml.dev_dependencies = normalize_dependencies(
419 gctx,
420 edition,
421 &features,
422 original_toml.dev_dependencies(),
423 Some(DepKind::Development),
424 &inherit,
425 &workspace_root,
426 package_root,
427 warnings,
428 )?;
429 deprecated_underscore(
430 &original_toml.build_dependencies2,
431 &original_toml.build_dependencies,
432 "build-dependencies",
433 package_name,
434 "package",
435 edition,
436 warnings,
437 )?;
438 normalized_toml.build_dependencies = normalize_dependencies(
439 gctx,
440 edition,
441 &features,
442 original_toml.build_dependencies(),
443 Some(DepKind::Build),
444 &inherit,
445 &workspace_root,
446 package_root,
447 warnings,
448 )?;
449 let mut normalized_target = BTreeMap::new();
450 for (name, platform) in original_toml.target.iter().flatten() {
451 let normalized_dependencies = normalize_dependencies(
452 gctx,
453 edition,
454 &features,
455 platform.dependencies.as_ref(),
456 None,
457 &inherit,
458 &workspace_root,
459 package_root,
460 warnings,
461 )?;
462 deprecated_underscore(
463 &platform.dev_dependencies2,
464 &platform.dev_dependencies,
465 "dev-dependencies",
466 name,
467 "platform target",
468 edition,
469 warnings,
470 )?;
471 let normalized_dev_dependencies = normalize_dependencies(
472 gctx,
473 edition,
474 &features,
475 platform.dev_dependencies(),
476 Some(DepKind::Development),
477 &inherit,
478 &workspace_root,
479 package_root,
480 warnings,
481 )?;
482 deprecated_underscore(
483 &platform.build_dependencies2,
484 &platform.build_dependencies,
485 "build-dependencies",
486 name,
487 "platform target",
488 edition,
489 warnings,
490 )?;
491 let normalized_build_dependencies = normalize_dependencies(
492 gctx,
493 edition,
494 &features,
495 platform.build_dependencies(),
496 Some(DepKind::Build),
497 &inherit,
498 &workspace_root,
499 package_root,
500 warnings,
501 )?;
502 normalized_target.insert(
503 name.clone(),
504 manifest::TomlPlatform {
505 dependencies: normalized_dependencies,
506 build_dependencies: normalized_build_dependencies,
507 build_dependencies2: None,
508 dev_dependencies: normalized_dev_dependencies,
509 dev_dependencies2: None,
510 },
511 );
512 }
513 normalized_toml.target = (!normalized_target.is_empty()).then_some(normalized_target);
514
515 let normalized_lints = original_toml
516 .lints
517 .clone()
518 .map(|value| lints_inherit_with(value, || inherit()?.lints()))
519 .transpose()?;
520 normalized_toml.lints = normalized_lints.map(|lints| manifest::InheritableLints {
521 workspace: false,
522 lints,
523 });
524
525 normalized_toml.badges = original_toml.badges.clone();
526 } else {
527 if let Some(field) = original_toml.requires_package().next() {
528 bail!("this virtual manifest specifies a `{field}` section, which is not allowed");
529 }
530 }
531
532 Ok(normalized_toml)
533}
534
535fn normalize_patch<'a>(
536 gctx: &GlobalContext,
537 original_patch: Option<&BTreeMap<String, BTreeMap<PackageName, TomlDependency>>>,
538 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
539 features: &Features,
540) -> CargoResult<Option<BTreeMap<String, BTreeMap<PackageName, TomlDependency>>>> {
541 if let Some(patch) = original_patch {
542 let mut normalized_patch = BTreeMap::new();
543 for (name, packages) in patch {
544 let mut normalized_packages = BTreeMap::new();
545 for (pkg, dep) in packages {
546 let dep = if let TomlDependency::Detailed(dep) = dep {
547 let mut dep = dep.clone();
548 normalize_path_dependency(gctx, &mut dep, workspace_root, features)
549 .with_context(|| {
550 format!("resolving path for patch of ({pkg}) for source ({name})")
551 })?;
552 TomlDependency::Detailed(dep)
553 } else {
554 dep.clone()
555 };
556 normalized_packages.insert(pkg.clone(), dep);
557 }
558 normalized_patch.insert(name.clone(), normalized_packages);
559 }
560 Ok(Some(normalized_patch))
561 } else {
562 Ok(None)
563 }
564}
565
566#[tracing::instrument(skip_all)]
567fn normalize_package_toml<'a>(
568 original_package: &manifest::TomlPackage,
569 manifest_file: &Path,
570 is_embedded: bool,
571 gctx: &GlobalContext,
572 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
573) -> CargoResult<Box<manifest::TomlPackage>> {
574 let package_root = manifest_file.parent().unwrap();
575
576 let edition = original_package
577 .edition
578 .clone()
579 .map(|value| field_inherit_with(value, "edition", || inherit()?.edition()))
580 .transpose()?
581 .map(manifest::InheritableField::Value)
582 .or_else(|| {
583 if is_embedded {
584 const DEFAULT_EDITION: crate::core::features::Edition =
585 crate::core::features::Edition::LATEST_STABLE;
586 let _ = gctx.shell().warn(format_args!(
587 "`package.edition` is unspecified, defaulting to `{}`",
588 DEFAULT_EDITION
589 ));
590 Some(manifest::InheritableField::Value(
591 DEFAULT_EDITION.to_string(),
592 ))
593 } else {
594 None
595 }
596 });
597 let rust_version = original_package
598 .rust_version
599 .clone()
600 .map(|value| field_inherit_with(value, "rust-version", || inherit()?.rust_version()))
601 .transpose()?
602 .map(manifest::InheritableField::Value);
603 let name = Some(
604 original_package
605 .name
606 .clone()
607 .or_else(|| {
608 if is_embedded {
609 let file_stem = manifest_file
610 .file_stem()
611 .expect("file name enforced previously")
612 .to_string_lossy();
613 let name = embedded::sanitize_name(file_stem.as_ref());
614 let name =
615 manifest::PackageName::new(name).expect("sanitize made the name valid");
616 Some(name)
617 } else {
618 None
619 }
620 })
621 .ok_or_else(|| anyhow::format_err!("missing field `package.name`"))?,
622 );
623 let version = original_package
624 .version
625 .clone()
626 .map(|value| field_inherit_with(value, "version", || inherit()?.version()))
627 .transpose()?
628 .map(manifest::InheritableField::Value);
629 let authors = original_package
630 .authors
631 .clone()
632 .map(|value| field_inherit_with(value, "authors", || inherit()?.authors()))
633 .transpose()?
634 .map(manifest::InheritableField::Value);
635 let build = if is_embedded {
636 Some(StringOrBool::Bool(false))
637 } else {
638 targets::normalize_build(original_package.build.as_ref(), package_root)
639 };
640 let metabuild = original_package.metabuild.clone();
641 let default_target = original_package.default_target.clone();
642 let forced_target = original_package.forced_target.clone();
643 let links = original_package.links.clone();
644 let exclude = original_package
645 .exclude
646 .clone()
647 .map(|value| field_inherit_with(value, "exclude", || inherit()?.exclude()))
648 .transpose()?
649 .map(manifest::InheritableField::Value);
650 let include = original_package
651 .include
652 .clone()
653 .map(|value| field_inherit_with(value, "include", || inherit()?.include()))
654 .transpose()?
655 .map(manifest::InheritableField::Value);
656 let publish = original_package
657 .publish
658 .clone()
659 .map(|value| field_inherit_with(value, "publish", || inherit()?.publish()))
660 .transpose()?
661 .map(manifest::InheritableField::Value);
662 let workspace = original_package.workspace.clone();
663 let im_a_teapot = original_package.im_a_teapot.clone();
664 let autolib = Some(false);
665 let autobins = Some(false);
666 let autoexamples = Some(false);
667 let autotests = Some(false);
668 let autobenches = Some(false);
669 let default_run = original_package.default_run.clone();
670 let description = original_package
671 .description
672 .clone()
673 .map(|value| field_inherit_with(value, "description", || inherit()?.description()))
674 .transpose()?
675 .map(manifest::InheritableField::Value);
676 let homepage = original_package
677 .homepage
678 .clone()
679 .map(|value| field_inherit_with(value, "homepage", || inherit()?.homepage()))
680 .transpose()?
681 .map(manifest::InheritableField::Value);
682 let documentation = original_package
683 .documentation
684 .clone()
685 .map(|value| field_inherit_with(value, "documentation", || inherit()?.documentation()))
686 .transpose()?
687 .map(manifest::InheritableField::Value);
688 let readme = normalize_package_readme(
689 package_root,
690 original_package
691 .readme
692 .clone()
693 .map(|value| field_inherit_with(value, "readme", || inherit()?.readme(package_root)))
694 .transpose()?
695 .as_ref(),
696 )
697 .map(|s| manifest::InheritableField::Value(StringOrBool::String(s)))
698 .or(Some(manifest::InheritableField::Value(StringOrBool::Bool(
699 false,
700 ))));
701 let keywords = original_package
702 .keywords
703 .clone()
704 .map(|value| field_inherit_with(value, "keywords", || inherit()?.keywords()))
705 .transpose()?
706 .map(manifest::InheritableField::Value);
707 let categories = original_package
708 .categories
709 .clone()
710 .map(|value| field_inherit_with(value, "categories", || inherit()?.categories()))
711 .transpose()?
712 .map(manifest::InheritableField::Value);
713 let license = original_package
714 .license
715 .clone()
716 .map(|value| field_inherit_with(value, "license", || inherit()?.license()))
717 .transpose()?
718 .map(manifest::InheritableField::Value);
719 let license_file = original_package
720 .license_file
721 .clone()
722 .map(|value| {
723 field_inherit_with(value, "license-file", || {
724 inherit()?.license_file(package_root)
725 })
726 })
727 .transpose()?
728 .map(manifest::InheritableField::Value);
729 let repository = original_package
730 .repository
731 .clone()
732 .map(|value| field_inherit_with(value, "repository", || inherit()?.repository()))
733 .transpose()?
734 .map(manifest::InheritableField::Value);
735 let resolver = original_package.resolver.clone();
736 let metadata = original_package.metadata.clone();
737
738 let normalized_package = manifest::TomlPackage {
739 edition,
740 rust_version,
741 name,
742 version,
743 authors,
744 build,
745 metabuild,
746 default_target,
747 forced_target,
748 links,
749 exclude,
750 include,
751 publish,
752 workspace,
753 im_a_teapot,
754 autolib,
755 autobins,
756 autoexamples,
757 autotests,
758 autobenches,
759 default_run,
760 description,
761 homepage,
762 documentation,
763 readme,
764 keywords,
765 categories,
766 license,
767 license_file,
768 repository,
769 resolver,
770 metadata,
771 _invalid_cargo_features: Default::default(),
772 };
773
774 Ok(Box::new(normalized_package))
775}
776
777fn normalize_package_readme(
779 package_root: &Path,
780 readme: Option<&manifest::StringOrBool>,
781) -> Option<String> {
782 match &readme {
783 None => default_readme_from_package_root(package_root),
784 Some(value) => match value {
785 manifest::StringOrBool::Bool(false) => None,
786 manifest::StringOrBool::Bool(true) => Some("README.md".to_string()),
787 manifest::StringOrBool::String(v) => Some(v.clone()),
788 },
789 }
790}
791
792const DEFAULT_README_FILES: [&str; 3] = ["README.md", "README.txt", "README"];
793
794fn default_readme_from_package_root(package_root: &Path) -> Option<String> {
797 for &readme_filename in DEFAULT_README_FILES.iter() {
798 if package_root.join(readme_filename).is_file() {
799 return Some(readme_filename.to_string());
800 }
801 }
802
803 None
804}
805
806#[tracing::instrument(skip_all)]
807fn normalize_features(
808 original_features: Option<&BTreeMap<manifest::FeatureName, Vec<String>>>,
809) -> CargoResult<Option<BTreeMap<manifest::FeatureName, Vec<String>>>> {
810 let Some(normalized_features) = original_features.cloned() else {
811 return Ok(None);
812 };
813
814 Ok(Some(normalized_features))
815}
816
817#[tracing::instrument(skip_all)]
818fn normalize_dependencies<'a>(
819 gctx: &GlobalContext,
820 edition: Edition,
821 features: &Features,
822 orig_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
823 kind: Option<DepKind>,
824 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
825 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
826 package_root: &Path,
827 warnings: &mut Vec<String>,
828) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
829 let Some(dependencies) = orig_deps else {
830 return Ok(None);
831 };
832
833 let mut deps = BTreeMap::new();
834 for (name_in_toml, v) in dependencies.iter() {
835 let mut resolved = dependency_inherit_with(
836 v.clone(),
837 name_in_toml,
838 inherit,
839 package_root,
840 edition,
841 warnings,
842 )?;
843 if let manifest::TomlDependency::Detailed(ref mut d) = resolved {
844 deprecated_underscore(
845 &d.default_features2,
846 &d.default_features,
847 "default-features",
848 name_in_toml,
849 "dependency",
850 edition,
851 warnings,
852 )?;
853 if d.public.is_some() {
854 let with_public_feature = features.require(Feature::public_dependency()).is_ok();
855 let with_z_public = gctx.cli_unstable().public_dependency;
856 if matches!(kind, None) {
857 if !with_public_feature && !with_z_public {
858 d.public = None;
859 warnings.push(format!(
860 "ignoring `public` on dependency {name_in_toml}, pass `-Zpublic-dependency` to enable support for it"
861 ))
862 }
863 } else {
864 let kind_name = match kind {
865 Some(k) => k.kind_table(),
866 None => "dependencies",
867 };
868 let hint = format!(
869 "'public' specifier can only be used on regular dependencies, not {kind_name}",
870 );
871 if with_public_feature || with_z_public {
872 bail!(hint)
873 } else {
874 warnings.push(hint);
876 d.public = None;
877 }
878 }
879 }
880 normalize_path_dependency(gctx, d, workspace_root, features)
881 .with_context(|| format!("resolving path dependency {name_in_toml}"))?;
882 }
883
884 deps.insert(
885 name_in_toml.clone(),
886 manifest::InheritableDependency::Value(resolved.clone()),
887 );
888 }
889 Ok(Some(deps))
890}
891
892fn normalize_path_dependency<'a>(
893 gctx: &GlobalContext,
894 detailed_dep: &mut TomlDetailedDependency,
895 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
896 features: &Features,
897) -> CargoResult<()> {
898 if let Some(base) = detailed_dep.base.take() {
899 if let Some(path) = detailed_dep.path.as_mut() {
900 let new_path = lookup_path_base(&base, gctx, workspace_root, features)?.join(&path);
901 *path = new_path.to_str().unwrap().to_string();
902 } else {
903 bail!("`base` can only be used with path dependencies");
904 }
905 }
906 Ok(())
907}
908
909fn load_inheritable_fields(
910 gctx: &GlobalContext,
911 normalized_path: &Path,
912 workspace_config: &WorkspaceConfig,
913) -> CargoResult<InheritableFields> {
914 match workspace_config {
915 WorkspaceConfig::Root(root) => Ok(root.inheritable().clone()),
916 WorkspaceConfig::Member {
917 root: Some(ref path_to_root),
918 } => {
919 let path = normalized_path
920 .parent()
921 .unwrap()
922 .join(path_to_root)
923 .join("Cargo.toml");
924 let root_path = paths::normalize_path(&path);
925 inheritable_from_path(gctx, root_path)
926 }
927 WorkspaceConfig::Member { root: None } => {
928 match find_workspace_root(&normalized_path, gctx)? {
929 Some(path_to_root) => inheritable_from_path(gctx, path_to_root),
930 None => Err(anyhow!("failed to find a workspace root")),
931 }
932 }
933 }
934}
935
936fn inheritable_from_path(
937 gctx: &GlobalContext,
938 workspace_path: PathBuf,
939) -> CargoResult<InheritableFields> {
940 let workspace_path_root = workspace_path.parent().unwrap();
942
943 if let Some(ws_root) = gctx.ws_roots.borrow().get(workspace_path_root) {
946 return Ok(ws_root.inheritable().clone());
947 };
948
949 let source_id = SourceId::for_manifest_path(&workspace_path)?;
950 let man = read_manifest(&workspace_path, source_id, gctx)?;
951 match man.workspace_config() {
952 WorkspaceConfig::Root(root) => {
953 gctx.ws_roots
954 .borrow_mut()
955 .insert(workspace_path, root.clone());
956 Ok(root.inheritable().clone())
957 }
958 _ => bail!(
959 "root of a workspace inferred but wasn't a root: {}",
960 workspace_path.display()
961 ),
962 }
963}
964
965macro_rules! package_field_getter {
967 ( $(($key:literal, $field:ident -> $ret:ty),)* ) => (
968 $(
969 #[doc = concat!("Gets the field `workspace.package.", $key, "`.")]
970 fn $field(&self) -> CargoResult<$ret> {
971 let Some(val) = self.package.as_ref().and_then(|p| p.$field.as_ref()) else {
972 bail!("`workspace.package.{}` was not defined", $key);
973 };
974 Ok(val.clone())
975 }
976 )*
977 )
978}
979
980#[derive(Clone, Debug, Default)]
982pub struct InheritableFields {
983 package: Option<manifest::InheritablePackage>,
984 dependencies: Option<BTreeMap<manifest::PackageName, manifest::TomlDependency>>,
985 lints: Option<manifest::TomlLints>,
986
987 _ws_root: PathBuf,
989}
990
991impl InheritableFields {
992 package_field_getter! {
993 ("authors", authors -> Vec<String>),
995 ("categories", categories -> Vec<String>),
996 ("description", description -> String),
997 ("documentation", documentation -> String),
998 ("edition", edition -> String),
999 ("exclude", exclude -> Vec<String>),
1000 ("homepage", homepage -> String),
1001 ("include", include -> Vec<String>),
1002 ("keywords", keywords -> Vec<String>),
1003 ("license", license -> String),
1004 ("publish", publish -> manifest::VecStringOrBool),
1005 ("repository", repository -> String),
1006 ("rust-version", rust_version -> RustVersion),
1007 ("version", version -> semver::Version),
1008 }
1009
1010 fn get_dependency(
1012 &self,
1013 name: &str,
1014 package_root: &Path,
1015 ) -> CargoResult<manifest::TomlDependency> {
1016 let Some(deps) = &self.dependencies else {
1017 bail!("`workspace.dependencies` was not defined");
1018 };
1019 let Some(dep) = deps.get(name) else {
1020 bail!("`dependency.{name}` was not found in `workspace.dependencies`");
1021 };
1022 let mut dep = dep.clone();
1023 if let manifest::TomlDependency::Detailed(detailed) = &mut dep {
1024 if detailed.base.is_none() {
1025 if let Some(rel_path) = &detailed.path {
1028 detailed.path = Some(resolve_relative_path(
1029 name,
1030 self.ws_root(),
1031 package_root,
1032 rel_path,
1033 )?);
1034 }
1035 }
1036 }
1037 Ok(dep)
1038 }
1039
1040 pub fn lints(&self) -> CargoResult<manifest::TomlLints> {
1042 let Some(val) = &self.lints else {
1043 bail!("`workspace.lints` was not defined");
1044 };
1045 Ok(val.clone())
1046 }
1047
1048 fn license_file(&self, package_root: &Path) -> CargoResult<String> {
1050 let Some(license_file) = self.package.as_ref().and_then(|p| p.license_file.as_ref()) else {
1051 bail!("`workspace.package.license-file` was not defined");
1052 };
1053 resolve_relative_path("license-file", &self._ws_root, package_root, license_file)
1054 }
1055
1056 fn readme(&self, package_root: &Path) -> CargoResult<manifest::StringOrBool> {
1058 let Some(readme) = normalize_package_readme(
1059 self._ws_root.as_path(),
1060 self.package.as_ref().and_then(|p| p.readme.as_ref()),
1061 ) else {
1062 bail!("`workspace.package.readme` was not defined");
1063 };
1064 resolve_relative_path("readme", &self._ws_root, package_root, &readme)
1065 .map(manifest::StringOrBool::String)
1066 }
1067
1068 fn ws_root(&self) -> &PathBuf {
1069 &self._ws_root
1070 }
1071}
1072
1073fn field_inherit_with<'a, T>(
1074 field: manifest::InheritableField<T>,
1075 label: &str,
1076 get_ws_inheritable: impl FnOnce() -> CargoResult<T>,
1077) -> CargoResult<T> {
1078 match field {
1079 manifest::InheritableField::Value(value) => Ok(value),
1080 manifest::InheritableField::Inherit(_) => get_ws_inheritable().with_context(|| {
1081 format!(
1082 "error inheriting `{label}` from workspace root manifest's `workspace.package.{label}`",
1083 )
1084 }),
1085 }
1086}
1087
1088fn lints_inherit_with(
1089 lints: manifest::InheritableLints,
1090 get_ws_inheritable: impl FnOnce() -> CargoResult<manifest::TomlLints>,
1091) -> CargoResult<manifest::TomlLints> {
1092 if lints.workspace {
1093 if !lints.lints.is_empty() {
1094 anyhow::bail!("cannot override `workspace.lints` in `lints`, either remove the overrides or `lints.workspace = true` and manually specify the lints");
1095 }
1096 get_ws_inheritable().with_context(|| {
1097 "error inheriting `lints` from workspace root manifest's `workspace.lints`"
1098 })
1099 } else {
1100 Ok(lints.lints)
1101 }
1102}
1103
1104fn dependency_inherit_with<'a>(
1105 dependency: manifest::InheritableDependency,
1106 name: &str,
1107 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
1108 package_root: &Path,
1109 edition: Edition,
1110 warnings: &mut Vec<String>,
1111) -> CargoResult<manifest::TomlDependency> {
1112 match dependency {
1113 manifest::InheritableDependency::Value(value) => Ok(value),
1114 manifest::InheritableDependency::Inherit(w) => {
1115 inner_dependency_inherit_with(w, name, inherit, package_root, edition, warnings).with_context(|| {
1116 format!(
1117 "error inheriting `{name}` from workspace root manifest's `workspace.dependencies.{name}`",
1118 )
1119 })
1120 }
1121 }
1122}
1123
1124fn inner_dependency_inherit_with<'a>(
1125 pkg_dep: manifest::TomlInheritedDependency,
1126 name: &str,
1127 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
1128 package_root: &Path,
1129 edition: Edition,
1130 warnings: &mut Vec<String>,
1131) -> CargoResult<manifest::TomlDependency> {
1132 let ws_dep = inherit()?.get_dependency(name, package_root)?;
1133 let mut merged_dep = match ws_dep {
1134 manifest::TomlDependency::Simple(ws_version) => manifest::TomlDetailedDependency {
1135 version: Some(ws_version),
1136 ..Default::default()
1137 },
1138 manifest::TomlDependency::Detailed(ws_dep) => ws_dep.clone(),
1139 };
1140 let manifest::TomlInheritedDependency {
1141 workspace: _,
1142
1143 features,
1144 optional,
1145 default_features,
1146 default_features2,
1147 public,
1148
1149 _unused_keys: _,
1150 } = &pkg_dep;
1151 let default_features = default_features.or(*default_features2);
1152
1153 match (default_features, merged_dep.default_features()) {
1154 (Some(true), Some(false)) => {
1158 merged_dep.default_features = Some(true);
1159 }
1160 (Some(false), Some(true)) => {
1164 deprecated_ws_default_features(name, Some(true), edition, warnings)?;
1165 }
1166 (Some(false), None) => {
1169 deprecated_ws_default_features(name, None, edition, warnings)?;
1170 }
1171 _ => {}
1172 }
1173 merged_dep.features = match (merged_dep.features.clone(), features.clone()) {
1174 (Some(dep_feat), Some(inherit_feat)) => Some(
1175 dep_feat
1176 .into_iter()
1177 .chain(inherit_feat)
1178 .collect::<Vec<String>>(),
1179 ),
1180 (Some(dep_fet), None) => Some(dep_fet),
1181 (None, Some(inherit_feat)) => Some(inherit_feat),
1182 (None, None) => None,
1183 };
1184 merged_dep.optional = *optional;
1185 merged_dep.public = *public;
1186 Ok(manifest::TomlDependency::Detailed(merged_dep))
1187}
1188
1189fn deprecated_ws_default_features(
1190 label: &str,
1191 ws_def_feat: Option<bool>,
1192 edition: Edition,
1193 warnings: &mut Vec<String>,
1194) -> CargoResult<()> {
1195 let ws_def_feat = match ws_def_feat {
1196 Some(true) => "true",
1197 Some(false) => "false",
1198 None => "not specified",
1199 };
1200 if Edition::Edition2024 <= edition {
1201 anyhow::bail!("`default-features = false` cannot override workspace's `default-features`");
1202 } else {
1203 warnings.push(format!(
1204 "`default-features` is ignored for {label}, since `default-features` was \
1205 {ws_def_feat} for `workspace.dependencies.{label}`, \
1206 this could become a hard error in the future"
1207 ));
1208 }
1209 Ok(())
1210}
1211
1212#[tracing::instrument(skip_all)]
1213pub fn to_real_manifest(
1214 contents: String,
1215 document: toml_edit::ImDocument<String>,
1216 original_toml: manifest::TomlManifest,
1217 normalized_toml: manifest::TomlManifest,
1218 features: Features,
1219 workspace_config: WorkspaceConfig,
1220 source_id: SourceId,
1221 manifest_file: &Path,
1222 is_embedded: bool,
1223 gctx: &GlobalContext,
1224 warnings: &mut Vec<String>,
1225 _errors: &mut Vec<String>,
1226) -> CargoResult<Manifest> {
1227 let package_root = manifest_file.parent().unwrap();
1228 if !package_root.is_dir() {
1229 bail!(
1230 "package root '{}' is not a directory",
1231 package_root.display()
1232 );
1233 };
1234
1235 let normalized_package = normalized_toml
1236 .package()
1237 .expect("previously verified to have a `[package]`");
1238 let package_name = normalized_package
1239 .normalized_name()
1240 .expect("previously normalized");
1241 if package_name.contains(':') {
1242 features.require(Feature::open_namespaces())?;
1243 }
1244 let rust_version = normalized_package
1245 .normalized_rust_version()
1246 .expect("previously normalized")
1247 .cloned();
1248
1249 let edition = if let Some(edition) = normalized_package
1250 .normalized_edition()
1251 .expect("previously normalized")
1252 {
1253 let edition: Edition = edition
1254 .parse()
1255 .context("failed to parse the `edition` key")?;
1256 if let Some(pkg_msrv) = &rust_version {
1257 if let Some(edition_msrv) = edition.first_version() {
1258 let edition_msrv = RustVersion::try_from(edition_msrv).unwrap();
1259 if !edition_msrv.is_compatible_with(pkg_msrv.as_partial()) {
1260 bail!(
1261 "rust-version {} is older than first version ({}) required by \
1262 the specified edition ({})",
1263 pkg_msrv,
1264 edition_msrv,
1265 edition,
1266 )
1267 }
1268 }
1269 }
1270 edition
1271 } else {
1272 let msrv_edition = if let Some(pkg_msrv) = &rust_version {
1273 Edition::ALL
1274 .iter()
1275 .filter(|e| {
1276 e.first_version()
1277 .map(|e| {
1278 let e = RustVersion::try_from(e).unwrap();
1279 e.is_compatible_with(pkg_msrv.as_partial())
1280 })
1281 .unwrap_or_default()
1282 })
1283 .max()
1284 .copied()
1285 } else {
1286 None
1287 }
1288 .unwrap_or_default();
1289 let default_edition = Edition::default();
1290 let latest_edition = Edition::LATEST_STABLE;
1291
1292 if msrv_edition != default_edition || rust_version.is_none() {
1297 let tip = if msrv_edition == latest_edition || rust_version.is_none() {
1298 format!(" while the latest is {latest_edition}")
1299 } else {
1300 format!(" while {msrv_edition} is compatible with `rust-version`")
1301 };
1302 warnings.push(format!(
1303 "no edition set: defaulting to the {default_edition} edition{tip}",
1304 ));
1305 }
1306 default_edition
1307 };
1308 if !edition.is_stable() {
1315 return Err(util::errors::internal(format!(
1317 "edition {} should be gated",
1318 edition
1319 )));
1320 }
1321
1322 if original_toml.project.is_some() {
1323 if Edition::Edition2024 <= edition {
1324 anyhow::bail!(
1325 "`[project]` is not supported as of the 2024 Edition, please use `[package]`"
1326 );
1327 } else {
1328 warnings.push(format!("`[project]` is deprecated in favor of `[package]`"));
1329 }
1330 }
1331
1332 if normalized_package.metabuild.is_some() {
1333 features.require(Feature::metabuild())?;
1334 }
1335
1336 if is_embedded {
1337 let invalid_fields = [
1338 ("`workspace`", original_toml.workspace.is_some()),
1339 ("`lib`", original_toml.lib.is_some()),
1340 (
1341 "`bin`",
1342 original_toml.bin.as_ref().map(|b| b.len()).unwrap_or(0) != 1,
1343 ),
1344 ("`example`", original_toml.example.is_some()),
1345 ("`test`", original_toml.test.is_some()),
1346 ("`bench`", original_toml.bench.is_some()),
1347 (
1348 "`package.workspace`",
1349 original_toml
1350 .package()
1351 .map(|p| p.workspace.is_some())
1352 .unwrap_or(false),
1353 ),
1354 (
1355 "`package.build`",
1356 original_toml
1357 .package()
1358 .map(|p| p.build.is_some())
1359 .unwrap_or(false),
1360 ),
1361 (
1362 "`package.links`",
1363 original_toml
1364 .package()
1365 .map(|p| p.links.is_some())
1366 .unwrap_or(false),
1367 ),
1368 (
1369 "`package.autolib`",
1370 original_toml
1371 .package()
1372 .map(|p| p.autolib.is_some())
1373 .unwrap_or(false),
1374 ),
1375 (
1376 "`package.autobins`",
1377 original_toml
1378 .package()
1379 .map(|p| p.autobins.is_some())
1380 .unwrap_or(false),
1381 ),
1382 (
1383 "`package.autoexamples`",
1384 original_toml
1385 .package()
1386 .map(|p| p.autoexamples.is_some())
1387 .unwrap_or(false),
1388 ),
1389 (
1390 "`package.autotests`",
1391 original_toml
1392 .package()
1393 .map(|p| p.autotests.is_some())
1394 .unwrap_or(false),
1395 ),
1396 (
1397 "`package.autobenches`",
1398 original_toml
1399 .package()
1400 .map(|p| p.autobenches.is_some())
1401 .unwrap_or(false),
1402 ),
1403 ];
1404 let invalid_fields = invalid_fields
1405 .into_iter()
1406 .filter_map(|(name, invalid)| invalid.then_some(name))
1407 .collect::<Vec<_>>();
1408 if !invalid_fields.is_empty() {
1409 let fields = invalid_fields.join(", ");
1410 let are = if invalid_fields.len() == 1 {
1411 "is"
1412 } else {
1413 "are"
1414 };
1415 anyhow::bail!("{fields} {are} not allowed in embedded manifests")
1416 }
1417 }
1418
1419 let resolve_behavior = match (
1420 normalized_package.resolver.as_ref(),
1421 normalized_toml
1422 .workspace
1423 .as_ref()
1424 .and_then(|ws| ws.resolver.as_ref()),
1425 ) {
1426 (None, None) => None,
1427 (Some(s), None) | (None, Some(s)) => Some(ResolveBehavior::from_manifest(s)?),
1428 (Some(_), Some(_)) => {
1429 bail!("cannot specify `resolver` field in both `[workspace]` and `[package]`")
1430 }
1431 };
1432
1433 let targets = to_targets(
1437 &features,
1438 &original_toml,
1439 &normalized_toml,
1440 package_root,
1441 edition,
1442 &normalized_package.metabuild,
1443 warnings,
1444 )?;
1445
1446 if targets.iter().all(|t| t.is_custom_build()) {
1447 bail!(
1448 "no targets specified in the manifest\n\
1449 either src/lib.rs, src/main.rs, a [lib] section, or \
1450 [[bin]] section must be present"
1451 )
1452 }
1453
1454 if let Err(conflict_targets) = unique_build_targets(&targets, package_root) {
1455 conflict_targets
1456 .iter()
1457 .for_each(|(target_path, conflicts)| {
1458 warnings.push(format!(
1459 "file `{}` found to be present in multiple \
1460 build targets:\n{}",
1461 target_path.display().to_string(),
1462 conflicts
1463 .iter()
1464 .map(|t| format!(" * `{}` target `{}`", t.kind().description(), t.name(),))
1465 .join("\n")
1466 ));
1467 })
1468 }
1469
1470 if let Some(links) = &normalized_package.links {
1471 if !targets.iter().any(|t| t.is_custom_build()) {
1472 bail!("package specifies that it links to `{links}` but does not have a custom build script")
1473 }
1474 }
1475
1476 validate_dependencies(original_toml.dependencies.as_ref(), None, None, warnings)?;
1477 validate_dependencies(
1478 original_toml.dev_dependencies(),
1479 None,
1480 Some(DepKind::Development),
1481 warnings,
1482 )?;
1483 validate_dependencies(
1484 original_toml.build_dependencies(),
1485 None,
1486 Some(DepKind::Build),
1487 warnings,
1488 )?;
1489 for (name, platform) in original_toml.target.iter().flatten() {
1490 let platform_kind: Platform = name.parse()?;
1491 platform_kind.check_cfg_attributes(warnings);
1492 platform_kind.check_cfg_keywords(warnings, manifest_file);
1493 let platform_kind = Some(platform_kind);
1494 validate_dependencies(
1495 platform.dependencies.as_ref(),
1496 platform_kind.as_ref(),
1497 None,
1498 warnings,
1499 )?;
1500 validate_dependencies(
1501 platform.build_dependencies(),
1502 platform_kind.as_ref(),
1503 Some(DepKind::Build),
1504 warnings,
1505 )?;
1506 validate_dependencies(
1507 platform.dev_dependencies(),
1508 platform_kind.as_ref(),
1509 Some(DepKind::Development),
1510 warnings,
1511 )?;
1512 }
1513
1514 let mut deps = Vec::new();
1516 let mut manifest_ctx = ManifestContext {
1517 deps: &mut deps,
1518 source_id,
1519 gctx,
1520 warnings,
1521 platform: None,
1522 root: package_root,
1523 };
1524 gather_dependencies(
1525 &mut manifest_ctx,
1526 normalized_toml.dependencies.as_ref(),
1527 None,
1528 )?;
1529 gather_dependencies(
1530 &mut manifest_ctx,
1531 normalized_toml.dev_dependencies(),
1532 Some(DepKind::Development),
1533 )?;
1534 gather_dependencies(
1535 &mut manifest_ctx,
1536 normalized_toml.build_dependencies(),
1537 Some(DepKind::Build),
1538 )?;
1539 for (name, platform) in normalized_toml.target.iter().flatten() {
1540 manifest_ctx.platform = Some(name.parse()?);
1541 gather_dependencies(&mut manifest_ctx, platform.dependencies.as_ref(), None)?;
1542 gather_dependencies(
1543 &mut manifest_ctx,
1544 platform.build_dependencies(),
1545 Some(DepKind::Build),
1546 )?;
1547 gather_dependencies(
1548 &mut manifest_ctx,
1549 platform.dev_dependencies(),
1550 Some(DepKind::Development),
1551 )?;
1552 }
1553 let replace = replace(&normalized_toml, &mut manifest_ctx)?;
1554 let patch = patch(&normalized_toml, &mut manifest_ctx)?;
1555
1556 {
1557 let mut names_sources = BTreeMap::new();
1558 for dep in &deps {
1559 let name = dep.name_in_toml();
1560 let prev = names_sources.insert(name, dep.source_id());
1561 if prev.is_some() && prev != Some(dep.source_id()) {
1562 bail!(
1563 "Dependency '{}' has different source paths depending on the build \
1564 target. Each dependency must have a single canonical source path \
1565 irrespective of build target.",
1566 name
1567 );
1568 }
1569 }
1570 }
1571
1572 verify_lints(
1573 normalized_toml
1574 .normalized_lints()
1575 .expect("previously normalized"),
1576 gctx,
1577 warnings,
1578 )?;
1579 let default = manifest::TomlLints::default();
1580 let rustflags = lints_to_rustflags(
1581 normalized_toml
1582 .normalized_lints()
1583 .expect("previously normalized")
1584 .unwrap_or(&default),
1585 )?;
1586
1587 let metadata = ManifestMetadata {
1588 description: normalized_package
1589 .normalized_description()
1590 .expect("previously normalized")
1591 .cloned(),
1592 homepage: normalized_package
1593 .normalized_homepage()
1594 .expect("previously normalized")
1595 .cloned(),
1596 documentation: normalized_package
1597 .normalized_documentation()
1598 .expect("previously normalized")
1599 .cloned(),
1600 readme: normalized_package
1601 .normalized_readme()
1602 .expect("previously normalized")
1603 .cloned(),
1604 authors: normalized_package
1605 .normalized_authors()
1606 .expect("previously normalized")
1607 .cloned()
1608 .unwrap_or_default(),
1609 license: normalized_package
1610 .normalized_license()
1611 .expect("previously normalized")
1612 .cloned(),
1613 license_file: normalized_package
1614 .normalized_license_file()
1615 .expect("previously normalized")
1616 .cloned(),
1617 repository: normalized_package
1618 .normalized_repository()
1619 .expect("previously normalized")
1620 .cloned(),
1621 keywords: normalized_package
1622 .normalized_keywords()
1623 .expect("previously normalized")
1624 .cloned()
1625 .unwrap_or_default(),
1626 categories: normalized_package
1627 .normalized_categories()
1628 .expect("previously normalized")
1629 .cloned()
1630 .unwrap_or_default(),
1631 badges: normalized_toml.badges.clone().unwrap_or_default(),
1632 links: normalized_package.links.clone(),
1633 rust_version: rust_version.clone(),
1634 };
1635
1636 if let Some(profiles) = &normalized_toml.profile {
1637 let cli_unstable = gctx.cli_unstable();
1638 validate_profiles(profiles, cli_unstable, &features, warnings)?;
1639 }
1640
1641 let version = normalized_package
1642 .normalized_version()
1643 .expect("previously normalized");
1644 let publish = match normalized_package
1645 .normalized_publish()
1646 .expect("previously normalized")
1647 {
1648 Some(manifest::VecStringOrBool::VecString(ref vecstring)) => Some(vecstring.clone()),
1649 Some(manifest::VecStringOrBool::Bool(false)) => Some(vec![]),
1650 Some(manifest::VecStringOrBool::Bool(true)) => None,
1651 None => version.is_none().then_some(vec![]),
1652 };
1653
1654 if version.is_none() && publish != Some(vec![]) {
1655 bail!("`package.publish` requires `package.version` be specified");
1656 }
1657
1658 let pkgid = PackageId::new(
1659 package_name.as_str().into(),
1660 version
1661 .cloned()
1662 .unwrap_or_else(|| semver::Version::new(0, 0, 0)),
1663 source_id,
1664 );
1665 let summary = {
1666 let summary = Summary::new(
1667 pkgid,
1668 deps,
1669 &normalized_toml
1670 .features
1671 .as_ref()
1672 .unwrap_or(&Default::default())
1673 .iter()
1674 .map(|(k, v)| {
1675 (
1676 InternedString::new(k),
1677 v.iter().map(InternedString::from).collect(),
1678 )
1679 })
1680 .collect(),
1681 normalized_package.links.as_deref(),
1682 rust_version.clone(),
1683 );
1684 if let Err(ref err) = summary {
1687 if let Some(missing_dep) = err.downcast_ref::<MissingDependencyError>() {
1688 missing_dep_diagnostic(
1689 missing_dep,
1690 &original_toml,
1691 &document,
1692 &contents,
1693 manifest_file,
1694 gctx,
1695 )?;
1696 }
1697 }
1698 summary?
1699 };
1700
1701 if summary.features().contains_key("default-features") {
1702 warnings.push(
1703 "`default-features = [\"..\"]` was found in [features]. \
1704 Did you mean to use `default = [\"..\"]`?"
1705 .to_string(),
1706 )
1707 }
1708
1709 if let Some(run) = &normalized_package.default_run {
1710 if !targets
1711 .iter()
1712 .filter(|t| t.is_bin())
1713 .any(|t| t.name() == run)
1714 {
1715 let suggestion = util::closest_msg(
1716 run,
1717 targets.iter().filter(|t| t.is_bin()),
1718 |t| t.name(),
1719 "target",
1720 );
1721 bail!("default-run target `{}` not found{}", run, suggestion);
1722 }
1723 }
1724
1725 let default_kind = normalized_package
1726 .default_target
1727 .as_ref()
1728 .map(|t| CompileTarget::new(&*t))
1729 .transpose()?
1730 .map(CompileKind::Target);
1731 let forced_kind = normalized_package
1732 .forced_target
1733 .as_ref()
1734 .map(|t| CompileTarget::new(&*t))
1735 .transpose()?
1736 .map(CompileKind::Target);
1737 let include = normalized_package
1738 .normalized_include()
1739 .expect("previously normalized")
1740 .cloned()
1741 .unwrap_or_default();
1742 let exclude = normalized_package
1743 .normalized_exclude()
1744 .expect("previously normalized")
1745 .cloned()
1746 .unwrap_or_default();
1747 let links = normalized_package.links.clone();
1748 let custom_metadata = normalized_package.metadata.clone();
1749 let im_a_teapot = normalized_package.im_a_teapot;
1750 let default_run = normalized_package.default_run.clone();
1751 let metabuild = normalized_package.metabuild.clone().map(|sov| sov.0);
1752 let manifest = Manifest::new(
1753 Rc::new(contents),
1754 Rc::new(document),
1755 Rc::new(original_toml),
1756 Rc::new(normalized_toml),
1757 summary,
1758 default_kind,
1759 forced_kind,
1760 targets,
1761 exclude,
1762 include,
1763 links,
1764 metadata,
1765 custom_metadata,
1766 publish,
1767 replace,
1768 patch,
1769 workspace_config,
1770 features,
1771 edition,
1772 rust_version,
1773 im_a_teapot,
1774 default_run,
1775 metabuild,
1776 resolve_behavior,
1777 rustflags,
1778 is_embedded,
1779 );
1780 if manifest
1781 .normalized_toml()
1782 .package()
1783 .unwrap()
1784 .license_file
1785 .is_some()
1786 && manifest
1787 .normalized_toml()
1788 .package()
1789 .unwrap()
1790 .license
1791 .is_some()
1792 {
1793 warnings.push(
1794 "only one of `license` or `license-file` is necessary\n\
1795 `license` should be used if the package license can be expressed \
1796 with a standard SPDX expression.\n\
1797 `license-file` should be used if the package uses a non-standard license.\n\
1798 See https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields \
1799 for more information."
1800 .to_owned(),
1801 );
1802 }
1803 warn_on_unused(&manifest.original_toml()._unused_keys, warnings);
1804
1805 manifest.feature_gate()?;
1806
1807 Ok(manifest)
1808}
1809
1810fn missing_dep_diagnostic(
1811 missing_dep: &MissingDependencyError,
1812 orig_toml: &TomlManifest,
1813 document: &ImDocument<String>,
1814 contents: &str,
1815 manifest_file: &Path,
1816 gctx: &GlobalContext,
1817) -> CargoResult<()> {
1818 let dep_name = missing_dep.dep_name;
1819 let manifest_path = rel_cwd_manifest_path(manifest_file, gctx);
1820 let feature_value_span =
1821 get_span(&document, &["features", missing_dep.feature.as_str()], true).unwrap();
1822
1823 let title = format!(
1824 "feature `{}` includes `{}`, but `{}` is not a dependency",
1825 missing_dep.feature, missing_dep.feature_value, &dep_name
1826 );
1827 let help = format!("enable the dependency with `dep:{dep_name}`");
1828 let info_label = format!(
1829 "`{}` is an unused optional dependency since no feature enables it",
1830 &dep_name
1831 );
1832 let message = Level::Error.title(&title);
1833 let snippet = Snippet::source(&contents)
1834 .origin(&manifest_path)
1835 .fold(true)
1836 .annotation(Level::Error.span(feature_value_span.start..feature_value_span.end));
1837 let message = if missing_dep.weak_optional {
1838 let mut orig_deps = vec![
1839 (
1840 orig_toml.dependencies.as_ref(),
1841 vec![DepKind::Normal.kind_table()],
1842 ),
1843 (
1844 orig_toml.build_dependencies.as_ref(),
1845 vec![DepKind::Build.kind_table()],
1846 ),
1847 ];
1848 for (name, platform) in orig_toml.target.iter().flatten() {
1849 orig_deps.push((
1850 platform.dependencies.as_ref(),
1851 vec!["target", name, DepKind::Normal.kind_table()],
1852 ));
1853 orig_deps.push((
1854 platform.build_dependencies.as_ref(),
1855 vec!["target", name, DepKind::Normal.kind_table()],
1856 ));
1857 }
1858
1859 if let Some((_, toml_path)) = orig_deps.iter().find(|(deps, _)| {
1860 if let Some(deps) = deps {
1861 deps.keys().any(|p| *p.as_str() == *dep_name)
1862 } else {
1863 false
1864 }
1865 }) {
1866 let toml_path = toml_path
1867 .iter()
1868 .map(|s| *s)
1869 .chain(std::iter::once(dep_name.as_str()))
1870 .collect::<Vec<_>>();
1871 let dep_span = get_span(&document, &toml_path, false).unwrap();
1872
1873 message
1874 .snippet(snippet.annotation(Level::Warning.span(dep_span).label(&info_label)))
1875 .footer(Level::Help.title(&help))
1876 } else {
1877 message.snippet(snippet)
1878 }
1879 } else {
1880 message.snippet(snippet)
1881 };
1882
1883 if let Err(err) = gctx.shell().print_message(message) {
1884 return Err(err.into());
1885 }
1886 Err(AlreadyPrintedError::new(anyhow!("").into()).into())
1887}
1888
1889fn to_virtual_manifest(
1890 contents: String,
1891 document: toml_edit::ImDocument<String>,
1892 original_toml: manifest::TomlManifest,
1893 normalized_toml: manifest::TomlManifest,
1894 features: Features,
1895 workspace_config: WorkspaceConfig,
1896 source_id: SourceId,
1897 manifest_file: &Path,
1898 gctx: &GlobalContext,
1899 warnings: &mut Vec<String>,
1900 _errors: &mut Vec<String>,
1901) -> CargoResult<VirtualManifest> {
1902 let root = manifest_file.parent().unwrap();
1903
1904 let mut deps = Vec::new();
1905 let (replace, patch) = {
1906 let mut manifest_ctx = ManifestContext {
1907 deps: &mut deps,
1908 source_id,
1909 gctx,
1910 warnings,
1911 platform: None,
1912 root,
1913 };
1914 (
1915 replace(&normalized_toml, &mut manifest_ctx)?,
1916 patch(&normalized_toml, &mut manifest_ctx)?,
1917 )
1918 };
1919 if let Some(profiles) = &normalized_toml.profile {
1920 validate_profiles(profiles, gctx.cli_unstable(), &features, warnings)?;
1921 }
1922 let resolve_behavior = normalized_toml
1923 .workspace
1924 .as_ref()
1925 .and_then(|ws| ws.resolver.as_deref())
1926 .map(|r| ResolveBehavior::from_manifest(r))
1927 .transpose()?;
1928 if let WorkspaceConfig::Member { .. } = &workspace_config {
1929 bail!("virtual manifests must be configured with [workspace]");
1930 }
1931 let manifest = VirtualManifest::new(
1932 Rc::new(contents),
1933 Rc::new(document),
1934 Rc::new(original_toml),
1935 Rc::new(normalized_toml),
1936 replace,
1937 patch,
1938 workspace_config,
1939 features,
1940 resolve_behavior,
1941 );
1942
1943 warn_on_unused(&manifest.original_toml()._unused_keys, warnings);
1944
1945 Ok(manifest)
1946}
1947
1948#[tracing::instrument(skip_all)]
1949fn validate_dependencies(
1950 original_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
1951 platform: Option<&Platform>,
1952 kind: Option<DepKind>,
1953 warnings: &mut Vec<String>,
1954) -> CargoResult<()> {
1955 let Some(dependencies) = original_deps else {
1956 return Ok(());
1957 };
1958
1959 for (name_in_toml, v) in dependencies.iter() {
1960 let kind_name = match kind {
1961 Some(k) => k.kind_table(),
1962 None => "dependencies",
1963 };
1964 let table_in_toml = if let Some(platform) = platform {
1965 format!("target.{}.{kind_name}", platform.to_string())
1966 } else {
1967 kind_name.to_string()
1968 };
1969 unused_dep_keys(name_in_toml, &table_in_toml, v.unused_keys(), warnings);
1970 }
1971 Ok(())
1972}
1973
1974struct ManifestContext<'a, 'b> {
1975 deps: &'a mut Vec<Dependency>,
1976 source_id: SourceId,
1977 gctx: &'b GlobalContext,
1978 warnings: &'a mut Vec<String>,
1979 platform: Option<Platform>,
1980 root: &'a Path,
1981}
1982
1983#[tracing::instrument(skip_all)]
1984fn gather_dependencies(
1985 manifest_ctx: &mut ManifestContext<'_, '_>,
1986 normalized_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
1987 kind: Option<DepKind>,
1988) -> CargoResult<()> {
1989 let Some(dependencies) = normalized_deps else {
1990 return Ok(());
1991 };
1992
1993 for (n, v) in dependencies.iter() {
1994 let resolved = v.normalized().expect("previously normalized");
1995 let dep = dep_to_dependency(&resolved, n, manifest_ctx, kind)?;
1996 manifest_ctx.deps.push(dep);
1997 }
1998 Ok(())
1999}
2000
2001fn replace(
2002 me: &manifest::TomlManifest,
2003 manifest_ctx: &mut ManifestContext<'_, '_>,
2004) -> CargoResult<Vec<(PackageIdSpec, Dependency)>> {
2005 if me.patch.is_some() && me.replace.is_some() {
2006 bail!("cannot specify both [replace] and [patch]");
2007 }
2008 let mut replace = Vec::new();
2009 for (spec, replacement) in me.replace.iter().flatten() {
2010 let mut spec = PackageIdSpec::parse(spec).with_context(|| {
2011 format!(
2012 "replacements must specify a valid semver \
2013 version to replace, but `{}` does not",
2014 spec
2015 )
2016 })?;
2017 if spec.url().is_none() {
2018 spec.set_url(CRATES_IO_INDEX.parse().unwrap());
2019 }
2020
2021 if replacement.is_version_specified() {
2022 bail!(
2023 "replacements cannot specify a version \
2024 requirement, but found one for `{}`",
2025 spec
2026 );
2027 }
2028
2029 let mut dep = dep_to_dependency(replacement, spec.name(), manifest_ctx, None)?;
2030 let version = spec.version().ok_or_else(|| {
2031 anyhow!(
2032 "replacements must specify a version \
2033 to replace, but `{}` does not",
2034 spec
2035 )
2036 })?;
2037 unused_dep_keys(
2038 dep.name_in_toml().as_str(),
2039 "replace",
2040 replacement.unused_keys(),
2041 &mut manifest_ctx.warnings,
2042 );
2043 dep.set_version_req(OptVersionReq::exact(&version));
2044 replace.push((spec, dep));
2045 }
2046 Ok(replace)
2047}
2048
2049fn patch(
2050 me: &manifest::TomlManifest,
2051 manifest_ctx: &mut ManifestContext<'_, '_>,
2052) -> CargoResult<HashMap<Url, Vec<Dependency>>> {
2053 let mut patch = HashMap::new();
2054 for (toml_url, deps) in me.patch.iter().flatten() {
2055 let url = match &toml_url[..] {
2056 CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
2057 _ => manifest_ctx
2058 .gctx
2059 .get_registry_index(toml_url)
2060 .or_else(|_| toml_url.into_url())
2061 .with_context(|| {
2062 format!(
2063 "[patch] entry `{}` should be a URL or registry name{}",
2064 toml_url,
2065 if toml_url == "crates" {
2066 "\nFor crates.io, use [patch.crates-io] (with a dash)"
2067 } else {
2068 ""
2069 }
2070 )
2071 })?,
2072 };
2073 patch.insert(
2074 url,
2075 deps.iter()
2076 .map(|(name, dep)| {
2077 unused_dep_keys(
2078 name,
2079 &format!("patch.{toml_url}",),
2080 dep.unused_keys(),
2081 &mut manifest_ctx.warnings,
2082 );
2083 dep_to_dependency(dep, name, manifest_ctx, None)
2084 })
2085 .collect::<CargoResult<Vec<_>>>()?,
2086 );
2087 }
2088 Ok(patch)
2089}
2090
2091pub(crate) fn to_dependency<P: ResolveToPath + Clone>(
2092 dep: &manifest::TomlDependency<P>,
2093 name: &str,
2094 source_id: SourceId,
2095 gctx: &GlobalContext,
2096 warnings: &mut Vec<String>,
2097 platform: Option<Platform>,
2098 root: &Path,
2099 kind: Option<DepKind>,
2100) -> CargoResult<Dependency> {
2101 dep_to_dependency(
2102 dep,
2103 name,
2104 &mut ManifestContext {
2105 deps: &mut Vec::new(),
2106 source_id,
2107 gctx,
2108 warnings,
2109 platform,
2110 root,
2111 },
2112 kind,
2113 )
2114}
2115
2116fn dep_to_dependency<P: ResolveToPath + Clone>(
2117 orig: &manifest::TomlDependency<P>,
2118 name: &str,
2119 manifest_ctx: &mut ManifestContext<'_, '_>,
2120 kind: Option<DepKind>,
2121) -> CargoResult<Dependency> {
2122 match *orig {
2123 manifest::TomlDependency::Simple(ref version) => detailed_dep_to_dependency(
2124 &manifest::TomlDetailedDependency::<P> {
2125 version: Some(version.clone()),
2126 ..Default::default()
2127 },
2128 name,
2129 manifest_ctx,
2130 kind,
2131 ),
2132 manifest::TomlDependency::Detailed(ref details) => {
2133 detailed_dep_to_dependency(details, name, manifest_ctx, kind)
2134 }
2135 }
2136}
2137
2138fn detailed_dep_to_dependency<P: ResolveToPath + Clone>(
2139 orig: &manifest::TomlDetailedDependency<P>,
2140 name_in_toml: &str,
2141 manifest_ctx: &mut ManifestContext<'_, '_>,
2142 kind: Option<DepKind>,
2143) -> CargoResult<Dependency> {
2144 if orig.version.is_none() && orig.path.is_none() && orig.git.is_none() {
2145 anyhow::bail!(
2146 "dependency ({name_in_toml}) specified without \
2147 providing a local path, Git repository, version, or \
2148 workspace dependency to use"
2149 );
2150 }
2151
2152 if let Some(version) = &orig.version {
2153 if version.contains('+') {
2154 manifest_ctx.warnings.push(format!(
2155 "version requirement `{}` for dependency `{}` \
2156 includes semver metadata which will be ignored, removing the \
2157 metadata is recommended to avoid confusion",
2158 version, name_in_toml
2159 ));
2160 }
2161 }
2162
2163 if orig.git.is_none() {
2164 let git_only_keys = [
2165 (&orig.branch, "branch"),
2166 (&orig.tag, "tag"),
2167 (&orig.rev, "rev"),
2168 ];
2169
2170 for &(key, key_name) in &git_only_keys {
2171 if key.is_some() {
2172 bail!(
2173 "key `{}` is ignored for dependency ({}).",
2174 key_name,
2175 name_in_toml
2176 );
2177 }
2178 }
2179 }
2180
2181 if let Some(features) = &orig.features {
2184 for feature in features {
2185 if feature.contains('/') {
2186 bail!(
2187 "feature `{}` in dependency `{}` is not allowed to contain slashes\n\
2188 If you want to enable features of a transitive dependency, \
2189 the direct dependency needs to re-export those features from \
2190 the `[features]` table.",
2191 feature,
2192 name_in_toml
2193 );
2194 }
2195 if feature.starts_with("dep:") {
2196 bail!(
2197 "feature `{}` in dependency `{}` is not allowed to use explicit \
2198 `dep:` syntax\n\
2199 If you want to enable an optional dependency, specify the name \
2200 of the optional dependency without the `dep:` prefix, or specify \
2201 a feature from the dependency's `[features]` table that enables \
2202 the optional dependency.",
2203 feature,
2204 name_in_toml
2205 );
2206 }
2207 }
2208 }
2209
2210 let new_source_id = to_dependency_source_id(orig, name_in_toml, manifest_ctx)?;
2211
2212 let (pkg_name, explicit_name_in_toml) = match orig.package {
2213 Some(ref s) => (&s[..], Some(name_in_toml)),
2214 None => (name_in_toml, None),
2215 };
2216
2217 let version = orig.version.as_deref();
2218 let mut dep = Dependency::parse(pkg_name, version, new_source_id)?;
2219 dep.set_features(orig.features.iter().flatten())
2220 .set_default_features(orig.default_features().unwrap_or(true))
2221 .set_optional(orig.optional.unwrap_or(false))
2222 .set_platform(manifest_ctx.platform.clone());
2223 if let Some(registry) = &orig.registry {
2224 let registry_id = SourceId::alt_registry(manifest_ctx.gctx, registry)?;
2225 dep.set_registry_id(registry_id);
2226 }
2227 if let Some(registry_index) = &orig.registry_index {
2228 let url = registry_index.into_url()?;
2229 let registry_id = SourceId::for_registry(&url)?;
2230 dep.set_registry_id(registry_id);
2231 }
2232
2233 if let Some(kind) = kind {
2234 dep.set_kind(kind);
2235 }
2236 if let Some(name_in_toml) = explicit_name_in_toml {
2237 dep.set_explicit_name_in_toml(name_in_toml);
2238 }
2239
2240 if let Some(p) = orig.public {
2241 dep.set_public(p);
2242 }
2243
2244 if let (Some(artifact), is_lib, target) = (
2245 orig.artifact.as_ref(),
2246 orig.lib.unwrap_or(false),
2247 orig.target.as_deref(),
2248 ) {
2249 if manifest_ctx.gctx.cli_unstable().bindeps {
2250 let artifact = Artifact::parse(&artifact.0, is_lib, target)?;
2251 if dep.kind() != DepKind::Build
2252 && artifact.target() == Some(ArtifactTarget::BuildDependencyAssumeTarget)
2253 {
2254 bail!(
2255 r#"`target = "target"` in normal- or dev-dependencies has no effect ({})"#,
2256 name_in_toml
2257 );
2258 }
2259 dep.set_artifact(artifact)
2260 } else {
2261 bail!("`artifact = …` requires `-Z bindeps` ({})", name_in_toml);
2262 }
2263 } else if orig.lib.is_some() || orig.target.is_some() {
2264 for (is_set, specifier) in [
2265 (orig.lib.is_some(), "lib"),
2266 (orig.target.is_some(), "target"),
2267 ] {
2268 if !is_set {
2269 continue;
2270 }
2271 bail!(
2272 "'{}' specifier cannot be used without an 'artifact = …' value ({})",
2273 specifier,
2274 name_in_toml
2275 )
2276 }
2277 }
2278 Ok(dep)
2279}
2280
2281fn to_dependency_source_id<P: ResolveToPath + Clone>(
2282 orig: &manifest::TomlDetailedDependency<P>,
2283 name_in_toml: &str,
2284 manifest_ctx: &mut ManifestContext<'_, '_>,
2285) -> CargoResult<SourceId> {
2286 match (
2287 orig.git.as_ref(),
2288 orig.path.as_ref(),
2289 orig.registry.as_deref(),
2290 orig.registry_index.as_ref(),
2291 ) {
2292 (Some(_git), _, Some(_registry), _) | (Some(_git), _, _, Some(_registry)) => bail!(
2293 "dependency ({name_in_toml}) specification is ambiguous. \
2294 Only one of `git` or `registry` is allowed.",
2295 ),
2296 (_, _, Some(_registry), Some(_registry_index)) => bail!(
2297 "dependency ({name_in_toml}) specification is ambiguous. \
2298 Only one of `registry` or `registry-index` is allowed.",
2299 ),
2300 (Some(_git), Some(_path), None, None) => {
2301 bail!(
2302 "dependency ({name_in_toml}) specification is ambiguous. \
2303 Only one of `git` or `path` is allowed.",
2304 );
2305 }
2306 (Some(git), None, None, None) => {
2307 let n_details = [&orig.branch, &orig.tag, &orig.rev]
2308 .iter()
2309 .filter(|d| d.is_some())
2310 .count();
2311
2312 if n_details > 1 {
2313 bail!(
2314 "dependency ({name_in_toml}) specification is ambiguous. \
2315 Only one of `branch`, `tag` or `rev` is allowed.",
2316 );
2317 }
2318
2319 let reference = orig
2320 .branch
2321 .clone()
2322 .map(GitReference::Branch)
2323 .or_else(|| orig.tag.clone().map(GitReference::Tag))
2324 .or_else(|| orig.rev.clone().map(GitReference::Rev))
2325 .unwrap_or(GitReference::DefaultBranch);
2326 let loc = git.into_url()?;
2327
2328 if let Some(fragment) = loc.fragment() {
2329 let msg = format!(
2330 "URL fragment `#{fragment}` in git URL is ignored for dependency ({name_in_toml}). \
2331 If you were trying to specify a specific git revision, \
2332 use `rev = \"{fragment}\"` in the dependency declaration.",
2333 );
2334 manifest_ctx.warnings.push(msg);
2335 }
2336
2337 SourceId::for_git(&loc, reference)
2338 }
2339 (None, Some(path), _, _) => {
2340 let path = path.resolve(manifest_ctx.gctx);
2341 if manifest_ctx.source_id.is_path() {
2350 let path = manifest_ctx.root.join(path);
2351 let path = paths::normalize_path(&path);
2352 SourceId::for_path(&path)
2353 } else {
2354 Ok(manifest_ctx.source_id)
2355 }
2356 }
2357 (None, None, Some(registry), None) => SourceId::alt_registry(manifest_ctx.gctx, registry),
2358 (None, None, None, Some(registry_index)) => {
2359 let url = registry_index.into_url()?;
2360 SourceId::for_registry(&url)
2361 }
2362 (None, None, None, None) => SourceId::crates_io(manifest_ctx.gctx),
2363 }
2364}
2365
2366pub(crate) fn lookup_path_base<'a>(
2367 base: &PathBaseName,
2368 gctx: &GlobalContext,
2369 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
2370 features: &Features,
2371) -> CargoResult<PathBuf> {
2372 features.require(Feature::path_bases())?;
2373
2374 let base_key = format!("path-bases.{base}");
2377
2378 if let Some(path_bases) = gctx.get::<Option<ConfigRelativePath>>(&base_key)? {
2380 Ok(path_bases.resolve_path(gctx))
2381 } else {
2382 match base.as_str() {
2384 "workspace" => Ok(workspace_root()?.to_path_buf()),
2385 _ => bail!(
2386 "path base `{base}` is undefined. \
2387 You must add an entry for `{base}` in the Cargo configuration [path-bases] table."
2388 ),
2389 }
2390 }
2391}
2392
2393pub trait ResolveToPath {
2394 fn resolve(&self, gctx: &GlobalContext) -> PathBuf;
2395}
2396
2397impl ResolveToPath for String {
2398 fn resolve(&self, _: &GlobalContext) -> PathBuf {
2399 self.into()
2400 }
2401}
2402
2403impl ResolveToPath for ConfigRelativePath {
2404 fn resolve(&self, gctx: &GlobalContext) -> PathBuf {
2405 self.resolve_path(gctx)
2406 }
2407}
2408
2409#[tracing::instrument(skip_all)]
2412fn unique_build_targets(
2413 targets: &[Target],
2414 package_root: &Path,
2415) -> Result<(), HashMap<PathBuf, Vec<Target>>> {
2416 let mut source_targets = HashMap::<_, Vec<_>>::new();
2417 for target in targets {
2418 if let TargetSourcePath::Path(path) = target.src_path() {
2419 let full = package_root.join(path);
2420 source_targets.entry(full).or_default().push(target.clone());
2421 }
2422 }
2423
2424 let conflict_targets = source_targets
2425 .into_iter()
2426 .filter(|(_, targets)| targets.len() > 1)
2427 .collect::<HashMap<_, _>>();
2428
2429 if !conflict_targets.is_empty() {
2430 return Err(conflict_targets);
2431 }
2432
2433 Ok(())
2434}
2435
2436fn validate_profiles(
2441 profiles: &manifest::TomlProfiles,
2442 cli_unstable: &CliUnstable,
2443 features: &Features,
2444 warnings: &mut Vec<String>,
2445) -> CargoResult<()> {
2446 for (name, profile) in &profiles.0 {
2447 validate_profile(profile, name, cli_unstable, features, warnings)?;
2448 }
2449 Ok(())
2450}
2451
2452pub fn validate_profile(
2454 root: &manifest::TomlProfile,
2455 name: &str,
2456 cli_unstable: &CliUnstable,
2457 features: &Features,
2458 warnings: &mut Vec<String>,
2459) -> CargoResult<()> {
2460 validate_profile_layer(root, name, cli_unstable, features)?;
2461 if let Some(ref profile) = root.build_override {
2462 validate_profile_override(profile, "build-override")?;
2463 validate_profile_layer(
2464 profile,
2465 &format!("{name}.build-override"),
2466 cli_unstable,
2467 features,
2468 )?;
2469 }
2470 if let Some(ref packages) = root.package {
2471 for (override_name, profile) in packages {
2472 validate_profile_override(profile, "package")?;
2473 validate_profile_layer(
2474 profile,
2475 &format!("{name}.package.{override_name}"),
2476 cli_unstable,
2477 features,
2478 )?;
2479 }
2480 }
2481
2482 if let Some(dir_name) = &root.dir_name {
2483 bail!(
2487 "dir-name=\"{}\" in profile `{}` is not currently allowed, \
2488 directory names are tied to the profile name for custom profiles",
2489 dir_name,
2490 name
2491 );
2492 }
2493
2494 if matches!(root.inherits.as_deref(), Some("debug")) {
2496 bail!(
2497 "profile.{}.inherits=\"debug\" should be profile.{}.inherits=\"dev\"",
2498 name,
2499 name
2500 );
2501 }
2502
2503 match name {
2504 "doc" => {
2505 warnings.push("profile `doc` is deprecated and has no effect".to_string());
2506 }
2507 "test" | "bench" => {
2508 if root.panic.is_some() {
2509 warnings.push(format!("`panic` setting is ignored for `{}` profile", name))
2510 }
2511 }
2512 _ => {}
2513 }
2514
2515 if let Some(panic) = &root.panic {
2516 if panic != "unwind" && panic != "abort" {
2517 bail!(
2518 "`panic` setting of `{}` is not a valid setting, \
2519 must be `unwind` or `abort`",
2520 panic
2521 );
2522 }
2523 }
2524
2525 if let Some(manifest::StringOrBool::String(arg)) = &root.lto {
2526 if arg == "true" || arg == "false" {
2527 bail!(
2528 "`lto` setting of string `\"{arg}\"` for `{name}` profile is not \
2529 a valid setting, must be a boolean (`true`/`false`) or a string \
2530 (`\"thin\"`/`\"fat\"`/`\"off\"`) or omitted.",
2531 );
2532 }
2533 }
2534
2535 Ok(())
2536}
2537
2538fn validate_profile_layer(
2542 profile: &manifest::TomlProfile,
2543 name: &str,
2544 cli_unstable: &CliUnstable,
2545 features: &Features,
2546) -> CargoResult<()> {
2547 if let Some(codegen_backend) = &profile.codegen_backend {
2548 match (
2549 features.require(Feature::codegen_backend()),
2550 cli_unstable.codegen_backend,
2551 ) {
2552 (Err(e), false) => return Err(e),
2553 _ => {}
2554 }
2555
2556 if codegen_backend.contains(|c: char| !c.is_ascii_alphanumeric() && c != '_') {
2557 bail!(
2558 "`profile.{}.codegen-backend` setting of `{}` is not a valid backend name.",
2559 name,
2560 codegen_backend,
2561 );
2562 }
2563 }
2564 if profile.rustflags.is_some() {
2565 match (
2566 features.require(Feature::profile_rustflags()),
2567 cli_unstable.profile_rustflags,
2568 ) {
2569 (Err(e), false) => return Err(e),
2570 _ => {}
2571 }
2572 }
2573 if profile.trim_paths.is_some() {
2574 match (
2575 features.require(Feature::trim_paths()),
2576 cli_unstable.trim_paths,
2577 ) {
2578 (Err(e), false) => return Err(e),
2579 _ => {}
2580 }
2581 }
2582 Ok(())
2583}
2584
2585fn validate_profile_override(profile: &manifest::TomlProfile, which: &str) -> CargoResult<()> {
2587 if profile.package.is_some() {
2588 bail!("package-specific profiles cannot be nested");
2589 }
2590 if profile.build_override.is_some() {
2591 bail!("build-override profiles cannot be nested");
2592 }
2593 if profile.panic.is_some() {
2594 bail!("`panic` may not be specified in a `{}` profile", which)
2595 }
2596 if profile.lto.is_some() {
2597 bail!("`lto` may not be specified in a `{}` profile", which)
2598 }
2599 if profile.rpath.is_some() {
2600 bail!("`rpath` may not be specified in a `{}` profile", which)
2601 }
2602 Ok(())
2603}
2604
2605fn verify_lints(
2606 lints: Option<&manifest::TomlLints>,
2607 gctx: &GlobalContext,
2608 warnings: &mut Vec<String>,
2609) -> CargoResult<()> {
2610 let Some(lints) = lints else {
2611 return Ok(());
2612 };
2613
2614 for (tool, lints) in lints {
2615 let supported = ["cargo", "clippy", "rust", "rustdoc"];
2616 if !supported.contains(&tool.as_str()) {
2617 let message = format!(
2618 "unrecognized lint tool `lints.{tool}`, specifying unrecognized tools may break in the future.
2619supported tools: {}",
2620 supported.join(", "),
2621 );
2622 warnings.push(message);
2623 continue;
2624 }
2625 if tool == "cargo" && !gctx.cli_unstable().cargo_lints {
2626 warn_for_cargo_lint_feature(gctx, warnings);
2627 }
2628 for (name, config) in lints {
2629 if let Some((prefix, suffix)) = name.split_once("::") {
2630 if tool == prefix {
2631 anyhow::bail!(
2632 "`lints.{tool}.{name}` is not valid lint name; try `lints.{prefix}.{suffix}`"
2633 )
2634 } else if tool == "rust" && supported.contains(&prefix) {
2635 anyhow::bail!(
2636 "`lints.{tool}.{name}` is not valid lint name; try `lints.{prefix}.{suffix}`"
2637 )
2638 } else {
2639 anyhow::bail!("`lints.{tool}.{name}` is not a valid lint name")
2640 }
2641 } else if let Some(config) = config.config() {
2642 for config_name in config.keys() {
2643 if !(tool == "rust" && name == "unexpected_cfgs" && config_name == "check-cfg")
2648 {
2649 let message =
2650 format!("unused manifest key: `lints.{tool}.{name}.{config_name}`");
2651 warnings.push(message);
2652 }
2653 }
2654 }
2655 }
2656 }
2657
2658 Ok(())
2659}
2660
2661fn warn_for_cargo_lint_feature(gctx: &GlobalContext, warnings: &mut Vec<String>) {
2662 use std::fmt::Write as _;
2663
2664 let key_name = "lints.cargo";
2665 let feature_name = "cargo-lints";
2666
2667 let mut message = String::new();
2668
2669 let _ = write!(
2670 message,
2671 "unused manifest key `{key_name}` (may be supported in a future version)"
2672 );
2673 if gctx.nightly_features_allowed {
2674 let _ = write!(
2675 message,
2676 "
2677
2678consider passing `-Z{feature_name}` to enable this feature."
2679 );
2680 } else {
2681 let _ = write!(
2682 message,
2683 "
2684
2685this Cargo does not support nightly features, but if you
2686switch to nightly channel you can pass
2687`-Z{feature_name}` to enable this feature.",
2688 );
2689 }
2690 warnings.push(message);
2691}
2692
2693fn lints_to_rustflags(lints: &manifest::TomlLints) -> CargoResult<Vec<String>> {
2694 let mut rustflags = lints
2695 .iter()
2696 .filter(|(tool, _)| tool != &"cargo")
2698 .flat_map(|(tool, lints)| {
2699 lints.iter().map(move |(name, config)| {
2700 let flag = match config.level() {
2701 manifest::TomlLintLevel::Forbid => "--forbid",
2702 manifest::TomlLintLevel::Deny => "--deny",
2703 manifest::TomlLintLevel::Warn => "--warn",
2704 manifest::TomlLintLevel::Allow => "--allow",
2705 };
2706
2707 let option = if tool == "rust" {
2708 format!("{flag}={name}")
2709 } else {
2710 format!("{flag}={tool}::{name}")
2711 };
2712 (
2713 config.priority(),
2714 std::cmp::Reverse(name),
2717 option,
2718 )
2719 })
2720 })
2721 .collect::<Vec<_>>();
2722 rustflags.sort();
2723
2724 let mut rustflags: Vec<_> = rustflags.into_iter().map(|(_, _, option)| option).collect();
2725
2726 if let Some(rust_lints) = lints.get("rust") {
2728 if let Some(unexpected_cfgs) = rust_lints.get("unexpected_cfgs") {
2729 if let Some(config) = unexpected_cfgs.config() {
2730 if let Some(check_cfg) = config.get("check-cfg") {
2731 if let Ok(check_cfgs) = toml::Value::try_into::<Vec<String>>(check_cfg.clone())
2732 {
2733 for check_cfg in check_cfgs {
2734 rustflags.push("--check-cfg".to_string());
2735 rustflags.push(check_cfg);
2736 }
2737 } else {
2739 bail!("`lints.rust.unexpected_cfgs.check-cfg` must be a list of string");
2740 }
2741 }
2742 }
2743 }
2744 }
2745
2746 Ok(rustflags)
2747}
2748
2749fn emit_diagnostic(
2750 e: toml_edit::de::Error,
2751 contents: &str,
2752 manifest_file: &Path,
2753 gctx: &GlobalContext,
2754) -> anyhow::Error {
2755 let Some(span) = e.span() else {
2756 return e.into();
2757 };
2758
2759 let manifest_path = diff_paths(manifest_file, gctx.cwd())
2761 .unwrap_or_else(|| manifest_file.to_path_buf())
2762 .display()
2763 .to_string();
2764 let message = Level::Error.title(e.message()).snippet(
2765 Snippet::source(contents)
2766 .origin(&manifest_path)
2767 .fold(true)
2768 .annotation(Level::Error.span(span)),
2769 );
2770 if let Err(err) = gctx.shell().print_message(message) {
2771 return err.into();
2772 }
2773 return AlreadyPrintedError::new(e.into()).into();
2774}
2775
2776fn deprecated_underscore<T>(
2778 old: &Option<T>,
2779 new: &Option<T>,
2780 new_path: &str,
2781 name: &str,
2782 kind: &str,
2783 edition: Edition,
2784 warnings: &mut Vec<String>,
2785) -> CargoResult<()> {
2786 let old_path = new_path.replace("-", "_");
2787 if old.is_some() && Edition::Edition2024 <= edition {
2788 anyhow::bail!("`{old_path}` is unsupported as of the 2024 edition; instead use `{new_path}`\n(in the `{name}` {kind})");
2789 } else if old.is_some() && new.is_some() {
2790 warnings.push(format!(
2791 "`{old_path}` is redundant with `{new_path}`, preferring `{new_path}` in the `{name}` {kind}"
2792 ))
2793 } else if old.is_some() {
2794 warnings.push(format!(
2795 "`{old_path}` is deprecated in favor of `{new_path}` and will not work in the 2024 edition\n(in the `{name}` {kind})"
2796 ))
2797 }
2798 Ok(())
2799}
2800
2801fn warn_on_unused(unused: &BTreeSet<String>, warnings: &mut Vec<String>) {
2802 for key in unused {
2803 warnings.push(format!("unused manifest key: {}", key));
2804 if key == "profiles.debug" {
2805 warnings.push("use `[profile.dev]` to configure debug builds".to_string());
2806 }
2807 }
2808}
2809
2810fn unused_dep_keys(
2811 dep_name: &str,
2812 kind: &str,
2813 unused_keys: Vec<String>,
2814 warnings: &mut Vec<String>,
2815) {
2816 for unused in unused_keys {
2817 let key = format!("unused manifest key: {kind}.{dep_name}.{unused}");
2818 warnings.push(key);
2819 }
2820}
2821
2822pub fn prepare_for_publish(
2824 me: &Package,
2825 ws: &Workspace<'_>,
2826 packaged_files: Option<&[PathBuf]>,
2827) -> CargoResult<Package> {
2828 let contents = me.manifest().contents();
2829 let document = me.manifest().document();
2830 let original_toml = prepare_toml_for_publish(
2831 me.manifest().normalized_toml(),
2832 ws,
2833 me.root(),
2834 packaged_files,
2835 )?;
2836 let normalized_toml = original_toml.clone();
2837 let features = me.manifest().unstable_features().clone();
2838 let workspace_config = me.manifest().workspace_config().clone();
2839 let source_id = me.package_id().source_id();
2840 let mut warnings = Default::default();
2841 let mut errors = Default::default();
2842 let gctx = ws.gctx();
2843 let manifest = to_real_manifest(
2844 contents.to_owned(),
2845 document.clone(),
2846 original_toml,
2847 normalized_toml,
2848 features,
2849 workspace_config,
2850 source_id,
2851 me.manifest_path(),
2852 me.manifest().is_embedded(),
2853 gctx,
2854 &mut warnings,
2855 &mut errors,
2856 )?;
2857 let new_pkg = Package::new(manifest, me.manifest_path());
2858 Ok(new_pkg)
2859}
2860
2861fn prepare_toml_for_publish(
2865 me: &manifest::TomlManifest,
2866 ws: &Workspace<'_>,
2867 package_root: &Path,
2868 packaged_files: Option<&[PathBuf]>,
2869) -> CargoResult<manifest::TomlManifest> {
2870 let gctx = ws.gctx();
2871
2872 if me
2873 .cargo_features
2874 .iter()
2875 .flat_map(|f| f.iter())
2876 .any(|f| f == "open-namespaces")
2877 {
2878 anyhow::bail!("cannot publish with `open-namespaces`")
2879 }
2880
2881 let mut package = me.package().unwrap().clone();
2882 package.workspace = None;
2883 if let Some(StringOrBool::String(path)) = &package.build {
2884 let path = Path::new(path).to_path_buf();
2885 let included = packaged_files.map(|i| i.contains(&path)).unwrap_or(true);
2886 let build = if included {
2887 let path = path
2888 .into_os_string()
2889 .into_string()
2890 .map_err(|_err| anyhow::format_err!("non-UTF8 `package.build`"))?;
2891 let path = normalize_path_string_sep(path);
2892 StringOrBool::String(path)
2893 } else {
2894 ws.gctx().shell().warn(format!(
2895 "ignoring `package.build` as `{}` is not included in the published package",
2896 path.display()
2897 ))?;
2898 StringOrBool::Bool(false)
2899 };
2900 package.build = Some(build);
2901 }
2902 let current_resolver = package
2903 .resolver
2904 .as_ref()
2905 .map(|r| ResolveBehavior::from_manifest(r))
2906 .unwrap_or_else(|| {
2907 package
2908 .edition
2909 .as_ref()
2910 .and_then(|e| e.as_value())
2911 .map(|e| Edition::from_str(e))
2912 .unwrap_or(Ok(Edition::Edition2015))
2913 .map(|e| e.default_resolve_behavior())
2914 })?;
2915 if ws.resolve_behavior() != current_resolver {
2916 package.resolver = Some(ws.resolve_behavior().to_manifest());
2921 }
2922 if let Some(license_file) = &package.license_file {
2923 let license_file = license_file
2924 .as_value()
2925 .context("license file should have been resolved before `prepare_for_publish()`")?;
2926 let license_path = Path::new(&license_file);
2927 let abs_license_path = paths::normalize_path(&package_root.join(license_path));
2928 if let Ok(license_file) = abs_license_path.strip_prefix(package_root) {
2929 package.license_file = Some(manifest::InheritableField::Value(
2930 normalize_path_string_sep(
2931 license_file
2932 .to_str()
2933 .ok_or_else(|| anyhow::format_err!("non-UTF8 `package.license-file`"))?
2934 .to_owned(),
2935 ),
2936 ));
2937 } else {
2938 package.license_file = Some(manifest::InheritableField::Value(
2941 license_path
2942 .file_name()
2943 .unwrap()
2944 .to_str()
2945 .unwrap()
2946 .to_string(),
2947 ));
2948 }
2949 }
2950
2951 if let Some(readme) = &package.readme {
2952 let readme = readme
2953 .as_value()
2954 .context("readme should have been resolved before `prepare_for_publish()`")?;
2955 match readme {
2956 manifest::StringOrBool::String(readme) => {
2957 let readme_path = Path::new(&readme);
2958 let abs_readme_path = paths::normalize_path(&package_root.join(readme_path));
2959 if let Ok(readme_path) = abs_readme_path.strip_prefix(package_root) {
2960 package.readme = Some(manifest::InheritableField::Value(StringOrBool::String(
2961 normalize_path_string_sep(
2962 readme_path
2963 .to_str()
2964 .ok_or_else(|| {
2965 anyhow::format_err!("non-UTF8 `package.license-file`")
2966 })?
2967 .to_owned(),
2968 ),
2969 )));
2970 } else {
2971 package.readme = Some(manifest::InheritableField::Value(
2974 manifest::StringOrBool::String(
2975 readme_path
2976 .file_name()
2977 .unwrap()
2978 .to_str()
2979 .unwrap()
2980 .to_string(),
2981 ),
2982 ));
2983 }
2984 }
2985 manifest::StringOrBool::Bool(_) => {}
2986 }
2987 }
2988
2989 let lib = if let Some(target) = &me.lib {
2990 prepare_target_for_publish(target, packaged_files, "library", ws.gctx())?
2991 } else {
2992 None
2993 };
2994 let bin = prepare_targets_for_publish(me.bin.as_ref(), packaged_files, "binary", ws.gctx())?;
2995 let example =
2996 prepare_targets_for_publish(me.example.as_ref(), packaged_files, "example", ws.gctx())?;
2997 let test = prepare_targets_for_publish(me.test.as_ref(), packaged_files, "test", ws.gctx())?;
2998 let bench =
2999 prepare_targets_for_publish(me.bench.as_ref(), packaged_files, "benchmark", ws.gctx())?;
3000
3001 let all = |_d: &manifest::TomlDependency| true;
3002 let mut manifest = manifest::TomlManifest {
3003 cargo_features: me.cargo_features.clone(),
3004 package: Some(package),
3005 project: None,
3006 badges: me.badges.clone(),
3007 features: me.features.clone(),
3008 lib,
3009 bin,
3010 example,
3011 test,
3012 bench,
3013 dependencies: map_deps(gctx, me.dependencies.as_ref(), all)?,
3014 dev_dependencies: map_deps(
3015 gctx,
3016 me.dev_dependencies(),
3017 manifest::TomlDependency::is_version_specified,
3018 )?,
3019 dev_dependencies2: None,
3020 build_dependencies: map_deps(gctx, me.build_dependencies(), all)?,
3021 build_dependencies2: None,
3022 target: match me.target.as_ref().map(|target_map| {
3023 target_map
3024 .iter()
3025 .map(|(k, v)| {
3026 Ok((
3027 k.clone(),
3028 manifest::TomlPlatform {
3029 dependencies: map_deps(gctx, v.dependencies.as_ref(), all)?,
3030 dev_dependencies: map_deps(
3031 gctx,
3032 v.dev_dependencies(),
3033 manifest::TomlDependency::is_version_specified,
3034 )?,
3035 dev_dependencies2: None,
3036 build_dependencies: map_deps(gctx, v.build_dependencies(), all)?,
3037 build_dependencies2: None,
3038 },
3039 ))
3040 })
3041 .collect()
3042 }) {
3043 Some(Ok(v)) => Some(v),
3044 Some(Err(e)) => return Err(e),
3045 None => None,
3046 },
3047 lints: me.lints.clone(),
3048 workspace: None,
3049 profile: me.profile.clone(),
3050 patch: None,
3051 replace: None,
3052 _unused_keys: Default::default(),
3053 };
3054 strip_features(&mut manifest);
3055 return Ok(manifest);
3056
3057 fn strip_features(manifest: &mut TomlManifest) {
3058 fn insert_dep_name(
3059 dep_name_set: &mut BTreeSet<manifest::PackageName>,
3060 deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
3061 ) {
3062 let Some(deps) = deps else {
3063 return;
3064 };
3065 deps.iter().for_each(|(k, _v)| {
3066 dep_name_set.insert(k.clone());
3067 });
3068 }
3069 let mut dep_name_set = BTreeSet::new();
3070 insert_dep_name(&mut dep_name_set, manifest.dependencies.as_ref());
3071 insert_dep_name(&mut dep_name_set, manifest.dev_dependencies());
3072 insert_dep_name(&mut dep_name_set, manifest.build_dependencies());
3073 if let Some(target_map) = manifest.target.as_ref() {
3074 target_map.iter().for_each(|(_k, v)| {
3075 insert_dep_name(&mut dep_name_set, v.dependencies.as_ref());
3076 insert_dep_name(&mut dep_name_set, v.dev_dependencies());
3077 insert_dep_name(&mut dep_name_set, v.build_dependencies());
3078 });
3079 }
3080 let features = manifest.features.as_mut();
3081
3082 let Some(features) = features else {
3083 return;
3084 };
3085
3086 features.values_mut().for_each(|feature_deps| {
3087 feature_deps.retain(|feature_dep| {
3088 let feature_value = FeatureValue::new(InternedString::new(feature_dep));
3089 match feature_value {
3090 FeatureValue::Dep { dep_name } | FeatureValue::DepFeature { dep_name, .. } => {
3091 let k = &manifest::PackageName::new(dep_name.to_string()).unwrap();
3092 dep_name_set.contains(k)
3093 }
3094 _ => true,
3095 }
3096 });
3097 });
3098 }
3099
3100 fn map_deps(
3101 gctx: &GlobalContext,
3102 deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
3103 filter: impl Fn(&manifest::TomlDependency) -> bool,
3104 ) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
3105 let Some(deps) = deps else {
3106 return Ok(None);
3107 };
3108 let deps = deps
3109 .iter()
3110 .filter(|(_k, v)| {
3111 if let manifest::InheritableDependency::Value(def) = v {
3112 filter(def)
3113 } else {
3114 false
3115 }
3116 })
3117 .map(|(k, v)| Ok((k.clone(), map_dependency(gctx, v)?)))
3118 .collect::<CargoResult<BTreeMap<_, _>>>()?;
3119 Ok(Some(deps))
3120 }
3121
3122 fn map_dependency(
3123 gctx: &GlobalContext,
3124 dep: &manifest::InheritableDependency,
3125 ) -> CargoResult<manifest::InheritableDependency> {
3126 let dep = match dep {
3127 manifest::InheritableDependency::Value(manifest::TomlDependency::Detailed(d)) => {
3128 let mut d = d.clone();
3129 d.path.take();
3131 d.base.take();
3132 d.git.take();
3134 d.branch.take();
3135 d.tag.take();
3136 d.rev.take();
3137 if let Some(registry) = d.registry.take() {
3139 d.registry_index = Some(gctx.get_registry_index(®istry)?.to_string());
3140 }
3141 Ok(d)
3142 }
3143 manifest::InheritableDependency::Value(manifest::TomlDependency::Simple(s)) => {
3144 Ok(manifest::TomlDetailedDependency {
3145 version: Some(s.clone()),
3146 ..Default::default()
3147 })
3148 }
3149 _ => unreachable!(),
3150 };
3151 dep.map(manifest::TomlDependency::Detailed)
3152 .map(manifest::InheritableDependency::Value)
3153 }
3154}
3155
3156pub fn prepare_targets_for_publish(
3157 targets: Option<&Vec<manifest::TomlTarget>>,
3158 packaged_files: Option<&[PathBuf]>,
3159 context: &str,
3160 gctx: &GlobalContext,
3161) -> CargoResult<Option<Vec<manifest::TomlTarget>>> {
3162 let Some(targets) = targets else {
3163 return Ok(None);
3164 };
3165
3166 let mut prepared = Vec::with_capacity(targets.len());
3167 for target in targets {
3168 let Some(target) = prepare_target_for_publish(target, packaged_files, context, gctx)?
3169 else {
3170 continue;
3171 };
3172 prepared.push(target);
3173 }
3174
3175 if prepared.is_empty() {
3176 Ok(None)
3177 } else {
3178 Ok(Some(prepared))
3179 }
3180}
3181
3182pub fn prepare_target_for_publish(
3183 target: &manifest::TomlTarget,
3184 packaged_files: Option<&[PathBuf]>,
3185 context: &str,
3186 gctx: &GlobalContext,
3187) -> CargoResult<Option<manifest::TomlTarget>> {
3188 let path = target.path.as_ref().expect("previously normalized");
3189 let path = &path.0;
3190 if let Some(packaged_files) = packaged_files {
3191 if !packaged_files.contains(&path) {
3192 let name = target.name.as_ref().expect("previously normalized");
3193 gctx.shell().warn(format!(
3194 "ignoring {context} `{name}` as `{}` is not included in the published package",
3195 path.display()
3196 ))?;
3197 return Ok(None);
3198 }
3199 }
3200
3201 let mut target = target.clone();
3202 let path = normalize_path_sep(path.to_path_buf(), context)?;
3203 target.path = Some(manifest::PathValue(path.into()));
3204
3205 Ok(Some(target))
3206}
3207
3208fn normalize_path_sep(path: PathBuf, context: &str) -> CargoResult<PathBuf> {
3209 let path = path
3210 .into_os_string()
3211 .into_string()
3212 .map_err(|_err| anyhow::format_err!("non-UTF8 path for {context}"))?;
3213 let path = normalize_path_string_sep(path);
3214 Ok(path.into())
3215}
3216
3217pub fn normalize_path_string_sep(path: String) -> String {
3218 if std::path::MAIN_SEPARATOR != '/' {
3219 path.replace(std::path::MAIN_SEPARATOR, "/")
3220 } else {
3221 path
3222 }
3223}