1 use std
::collections
::{BTreeMap, HashMap}
;
3 use std
::hash
::{Hash, Hasher}
;
4 use std
::path
::{Path, PathBuf}
;
12 use crate::core
::interning
::InternedString
;
13 use crate::core
::profiles
::Profiles
;
14 use crate::core
::{Dependency, PackageId, PackageIdSpec, SourceId, Summary}
;
15 use crate::core
::{Edition, Feature, Features, WorkspaceConfig}
;
16 use crate::util
::errors
::*;
17 use crate::util
::toml
::TomlManifest
;
18 use crate::util
::{short_hash, Config, Filesystem}
;
20 pub enum EitherManifest
{
22 Virtual(VirtualManifest
),
25 /// Contains all the information about a package, as loaded from a `Cargo.toml`.
26 #[derive(Clone, Debug)]
30 links
: Option
<String
>,
34 metadata
: ManifestMetadata
,
35 custom_metadata
: Option
<toml
::Value
>,
37 publish
: Option
<Vec
<String
>>,
38 publish_lockfile
: bool
,
39 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
40 patch
: HashMap
<Url
, Vec
<Dependency
>>,
41 workspace
: WorkspaceConfig
,
42 original
: Rc
<TomlManifest
>,
45 im_a_teapot
: Option
<bool
>,
46 default_run
: Option
<String
>,
47 metabuild
: Option
<Vec
<String
>>,
50 /// When parsing `Cargo.toml`, some warnings should silenced
51 /// if the manifest comes from a dependency. `ManifestWarning`
52 /// allows this delayed emission of warnings.
53 #[derive(Clone, Debug)]
54 pub struct DelayedWarning
{
56 pub is_critical
: bool
,
59 #[derive(Clone, Debug)]
60 pub struct Warnings(Vec
<DelayedWarning
>);
62 #[derive(Clone, Debug)]
63 pub struct VirtualManifest
{
64 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
65 patch
: HashMap
<Url
, Vec
<Dependency
>>,
66 workspace
: WorkspaceConfig
,
72 /// General metadata about a package which is just blindly uploaded to the
75 /// Note that many of these fields can contain invalid values such as the
76 /// homepage, repository, documentation, or license. These fields are not
77 /// validated by cargo itself, but rather it is up to the registry when uploaded
78 /// to validate these fields. Cargo will itself accept any valid TOML
79 /// specification for these values.
80 #[derive(PartialEq, Clone, Debug)]
81 pub struct ManifestMetadata
{
82 pub authors
: Vec
<String
>,
83 pub keywords
: Vec
<String
>,
84 pub categories
: Vec
<String
>,
85 pub license
: Option
<String
>,
86 pub license_file
: Option
<String
>,
87 pub description
: Option
<String
>, // Not in Markdown
88 pub readme
: Option
<String
>, // File, not contents
89 pub homepage
: Option
<String
>, // URL
90 pub repository
: Option
<String
>, // URL
91 pub documentation
: Option
<String
>, // URL
92 pub badges
: BTreeMap
<String
, BTreeMap
<String
, String
>>,
93 pub links
: Option
<String
>,
96 #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
106 /// Returns the argument suitable for `--crate-type` to pass to rustc.
107 pub fn crate_type(&self) -> &str {
109 LibKind
::Lib
=> "lib",
110 LibKind
::Rlib
=> "rlib",
111 LibKind
::Dylib
=> "dylib",
112 LibKind
::ProcMacro
=> "proc-macro",
113 LibKind
::Other(ref s
) => s
,
117 pub fn linkable(&self) -> bool
{
119 LibKind
::Lib
| LibKind
::Rlib
| LibKind
::Dylib
| LibKind
::ProcMacro
=> true,
120 LibKind
::Other(..) => false,
124 pub fn requires_upstream_objects(&self) -> bool
{
126 // "lib" == "rlib" and is a compilation that doesn't actually
127 // require upstream object files to exist, only upstream metadata
128 // files. As a result, it doesn't require upstream artifacts
129 LibKind
::Lib
| LibKind
::Rlib
=> false,
131 // Everything else, however, is some form of "linkable output" or
132 // something that requires upstream object files.
138 impl fmt
::Debug
for LibKind
{
139 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
140 self.crate_type().fmt(f
)
144 impl<'a
> From
<&'a String
> for LibKind
{
145 fn from(string
: &'a String
) -> Self {
146 match string
.as_ref() {
147 "lib" => LibKind
::Lib
,
148 "rlib" => LibKind
::Rlib
,
149 "dylib" => LibKind
::Dylib
,
150 "proc-macro" => LibKind
::ProcMacro
,
151 s
=> LibKind
::Other(s
.to_string()),
156 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
157 pub enum TargetKind
{
162 ExampleLib(Vec
<LibKind
>),
167 impl ser
::Serialize
for TargetKind
{
168 fn serialize
<S
>(&self, s
: S
) -> Result
<S
::Ok
, S
::Error
>
172 use self::TargetKind
::*;
174 Lib(ref kinds
) => s
.collect_seq(kinds
.iter().map(LibKind
::crate_type
)),
175 Bin
=> ["bin"].serialize(s
),
176 ExampleBin
| ExampleLib(_
) => ["example"].serialize(s
),
177 Test
=> ["test"].serialize(s
),
178 CustomBuild
=> ["custom-build"].serialize(s
),
179 Bench
=> ["bench"].serialize(s
),
184 impl fmt
::Debug
for TargetKind
{
185 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
186 use self::TargetKind
::*;
188 Lib(ref kinds
) => kinds
.fmt(f
),
190 ExampleBin
| ExampleLib(_
) => "example".fmt(f
),
191 Test
=> "test".fmt(f
),
192 CustomBuild
=> "custom-build".fmt(f
),
193 Bench
=> "bench".fmt(f
),
199 pub fn description(&self) -> &'
static str {
201 TargetKind
::Lib(..) => "lib",
202 TargetKind
::Bin
=> "bin",
203 TargetKind
::Test
=> "integration-test",
204 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => "example",
205 TargetKind
::Bench
=> "bench",
206 TargetKind
::CustomBuild
=> "build-script",
211 /// Information about a binary, a library, an example, etc. that is part of the
213 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
217 // Note that the `src_path` here is excluded from the `Hash` implementation
218 // as it's absolute currently and is otherwise a little too brittle for
219 // causing rebuilds. Instead the hash for the path that we send to the
220 // compiler is handled elsewhere.
221 src_path
: TargetSourcePath
,
222 required_features
: Option
<Vec
<String
>>,
227 harness
: bool
, // whether to use the test harness (--test)
233 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
234 pub enum TargetSourcePath
{
239 impl TargetSourcePath
{
240 pub fn path(&self) -> Option
<&Path
> {
242 TargetSourcePath
::Path(path
) => Some(path
.as_ref()),
243 TargetSourcePath
::Metabuild
=> None
,
247 pub fn is_path(&self) -> bool
{
249 TargetSourcePath
::Path(_
) => true,
255 impl Hash
for TargetSourcePath
{
256 fn hash
<H
: Hasher
>(&self, _
: &mut H
) {
261 impl fmt
::Debug
for TargetSourcePath
{
262 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
264 TargetSourcePath
::Path(path
) => path
.fmt(f
),
265 TargetSourcePath
::Metabuild
=> "metabuild".fmt(f
),
270 impl From
<PathBuf
> for TargetSourcePath
{
271 fn from(path
: PathBuf
) -> Self {
272 assert
!(path
.is_absolute(), "`{}` is not absolute", path
.display());
273 TargetSourcePath
::Path(path
)
278 struct SerializedTarget
<'a
> {
279 /// Is this a `--bin bin`, `--lib`, `--example ex`?
280 /// Serialized as a list of strings for historical reasons.
281 kind
: &'a TargetKind
,
282 /// Corresponds to `--crate-type` compiler attribute.
283 /// See https://doc.rust-lang.org/reference/linkage.html
284 crate_types
: Vec
<&'a
str>,
286 src_path
: Option
<&'a PathBuf
>,
288 #[serde(rename = "required-features", skip_serializing_if = "Option::is_none")]
289 required_features
: Option
<Vec
<&'a
str>>,
292 impl ser
::Serialize
for Target
{
293 fn serialize
<S
: ser
::Serializer
>(&self, s
: S
) -> Result
<S
::Ok
, S
::Error
> {
294 let src_path
= match &self.src_path
{
295 TargetSourcePath
::Path(p
) => Some(p
),
296 // Unfortunately getting the correct path would require access to
297 // target_dir, which is not available here.
298 TargetSourcePath
::Metabuild
=> None
,
302 crate_types
: self.rustc_crate_types(),
305 edition
: &self.edition
.to_string(),
306 required_features
: self
309 .map(|rf
| rf
.iter().map(|s
| &**s
).collect()),
316 impl fmt
::Debug
for Target
{
317 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
318 let (default, default_name
) = {
320 TargetKind
::Lib(kinds
) => {
325 self.src_path().path().unwrap().to_path_buf(),
328 format
!("lib_target({:?}, {:?}, {:?}, {:?})",
329 self.name
, kinds
, self.src_path
, self.edition
),
332 TargetKind
::CustomBuild
=> {
333 match self.src_path
{
334 TargetSourcePath
::Path(ref path
) => {
336 Target
::custom_build_target(
341 format
!("custom_build_target({:?}, {:?}, {:?})",
342 self.name
, path
, self.edition
),
345 TargetSourcePath
::Metabuild
=> {
347 Target
::metabuild_target(&self.name
),
348 format
!("metabuild_target({:?})", self.name
),
354 Target
::new(self.src_path
.clone(), self.edition
),
355 format
!("with_path({:?}, {:?})", self.src_path
, self.edition
),
380 targets
: Vec
<Target
>,
381 exclude
: Vec
<String
>,
382 include
: Vec
<String
>,
383 links
: Option
<String
>,
384 metadata
: ManifestMetadata
,
385 custom_metadata
: Option
<toml
::Value
>,
387 publish
: Option
<Vec
<String
>>,
388 publish_lockfile
: bool
,
389 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
390 patch
: HashMap
<Url
, Vec
<Dependency
>>,
391 workspace
: WorkspaceConfig
,
394 im_a_teapot
: Option
<bool
>,
395 default_run
: Option
<String
>,
396 original
: Rc
<TomlManifest
>,
397 metabuild
: Option
<Vec
<String
>>,
402 warnings
: Warnings
::new(),
423 pub fn dependencies(&self) -> &[Dependency
] {
424 self.summary
.dependencies()
426 pub fn exclude(&self) -> &[String
] {
429 pub fn include(&self) -> &[String
] {
432 pub fn metadata(&self) -> &ManifestMetadata
{
435 pub fn name(&self) -> InternedString
{
436 self.package_id().name()
438 pub fn package_id(&self) -> PackageId
{
439 self.summary
.package_id()
441 pub fn summary(&self) -> &Summary
{
444 pub fn summary_mut(&mut self) -> &mut Summary
{
447 pub fn targets(&self) -> &[Target
] {
450 pub fn version(&self) -> &Version
{
451 self.package_id().version()
453 pub fn warnings_mut(&mut self) -> &mut Warnings
{
456 pub fn warnings(&self) -> &Warnings
{
459 pub fn profiles(&self) -> &Profiles
{
462 pub fn publish(&self) -> &Option
<Vec
<String
>> {
465 pub fn publish_lockfile(&self) -> bool
{
466 self.publish_lockfile
468 pub fn replace(&self) -> &[(PackageIdSpec
, Dependency
)] {
471 pub fn original(&self) -> &TomlManifest
{
474 pub fn patch(&self) -> &HashMap
<Url
, Vec
<Dependency
>> {
477 pub fn links(&self) -> Option
<&str> {
478 self.links
.as_ref().map(|s
| &s
[..])
481 pub fn workspace_config(&self) -> &WorkspaceConfig
{
485 pub fn features(&self) -> &Features
{
489 pub fn map_source(self, to_replace
: SourceId
, replace_with
: SourceId
) -> Manifest
{
491 summary
: self.summary
.map_source(to_replace
, replace_with
),
496 pub fn feature_gate(&self) -> CargoResult
<()> {
497 if self.im_a_teapot
.is_some() {
499 .require(Feature
::test_dummy_unstable())
501 failure
::format_err
!(
502 "the `im-a-teapot` manifest key is unstable and may \
503 not work properly in England"
508 if self.default_run
.is_some() {
510 .require(Feature
::default_run())
511 .chain_err(|| failure
::format_err
!("the `default-run` manifest key is unstable"))?
;
517 // Just a helper function to test out `-Z` flags on Cargo
518 pub fn print_teapot(&self, config
: &Config
) {
519 if let Some(teapot
) = self.im_a_teapot
{
520 if config
.cli_unstable().print_im_a_teapot
{
521 println
!("im-a-teapot = {}", teapot
);
526 pub fn edition(&self) -> Edition
{
530 pub fn custom_metadata(&self) -> Option
<&toml
::Value
> {
531 self.custom_metadata
.as_ref()
534 pub fn default_run(&self) -> Option
<&str> {
535 self.default_run
.as_ref().map(|s
| &s
[..])
538 pub fn metabuild(&self) -> Option
<&Vec
<String
>> {
539 self.metabuild
.as_ref()
542 pub fn metabuild_path(&self, target_dir
: Filesystem
) -> PathBuf
{
543 let hash
= short_hash(&self.package_id());
545 .into_path_unlocked()
547 .join(format
!("metabuild-{}-{}.rs", self.name(), hash
))
551 impl VirtualManifest
{
553 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
554 patch
: HashMap
<Url
, Vec
<Dependency
>>,
555 workspace
: WorkspaceConfig
,
558 ) -> VirtualManifest
{
564 warnings
: Warnings
::new(),
569 pub fn replace(&self) -> &[(PackageIdSpec
, Dependency
)] {
573 pub fn patch(&self) -> &HashMap
<Url
, Vec
<Dependency
>> {
577 pub fn workspace_config(&self) -> &WorkspaceConfig
{
581 pub fn profiles(&self) -> &Profiles
{
585 pub fn warnings_mut(&mut self) -> &mut Warnings
{
589 pub fn warnings(&self) -> &Warnings
{
593 pub fn features(&self) -> &Features
{
599 fn new(src_path
: TargetSourcePath
, edition
: Edition
) -> Target
{
601 kind
: TargetKind
::Bin
,
604 required_features
: None
,
616 fn with_path(src_path
: PathBuf
, edition
: Edition
) -> Target
{
617 Target
::new(TargetSourcePath
::from(src_path
), edition
)
622 crate_targets
: Vec
<LibKind
>,
627 kind
: TargetKind
::Lib(crate_targets
),
628 name
: name
.to_string(),
631 ..Target
::with_path(src_path
, edition
)
638 required_features
: Option
<Vec
<String
>>,
642 kind
: TargetKind
::Bin
,
643 name
: name
.to_string(),
646 ..Target
::with_path(src_path
, edition
)
650 /// Builds a `Target` corresponding to the `build = "build.rs"` entry.
651 pub fn custom_build_target(name
: &str, src_path
: PathBuf
, edition
: Edition
) -> Target
{
653 kind
: TargetKind
::CustomBuild
,
654 name
: name
.to_string(),
658 ..Target
::with_path(src_path
, edition
)
662 pub fn metabuild_target(name
: &str) -> Target
{
664 kind
: TargetKind
::CustomBuild
,
665 name
: name
.to_string(),
669 ..Target
::new(TargetSourcePath
::Metabuild
, Edition
::Edition2018
)
673 pub fn example_target(
675 crate_targets
: Vec
<LibKind
>,
677 required_features
: Option
<Vec
<String
>>,
680 let kind
= if crate_targets
.is_empty()
683 .all(|t
| *t
== LibKind
::Other("bin".into()))
685 TargetKind
::ExampleBin
687 TargetKind
::ExampleLib(crate_targets
)
692 name
: name
.to_string(),
696 ..Target
::with_path(src_path
, edition
)
703 required_features
: Option
<Vec
<String
>>,
707 kind
: TargetKind
::Test
,
708 name
: name
.to_string(),
711 ..Target
::with_path(src_path
, edition
)
718 required_features
: Option
<Vec
<String
>>,
722 kind
: TargetKind
::Bench
,
723 name
: name
.to_string(),
726 ..Target
::with_path(src_path
, edition
)
730 pub fn name(&self) -> &str {
733 pub fn crate_name(&self) -> String
{
734 self.name
.replace("-", "_")
736 pub fn src_path(&self) -> &TargetSourcePath
{
739 pub fn set_src_path(&mut self, src_path
: TargetSourcePath
) {
740 self.src_path
= src_path
;
742 pub fn required_features(&self) -> Option
<&Vec
<String
>> {
743 self.required_features
.as_ref()
745 pub fn kind(&self) -> &TargetKind
{
748 pub fn tested(&self) -> bool
{
751 pub fn harness(&self) -> bool
{
754 pub fn documented(&self) -> bool
{
757 pub fn for_host(&self) -> bool
{
760 pub fn proc_macro(&self) -> bool
{
763 pub fn edition(&self) -> Edition
{
766 pub fn benched(&self) -> bool
{
769 pub fn doctested(&self) -> bool
{
773 pub fn doctestable(&self) -> bool
{
775 TargetKind
::Lib(ref kinds
) => kinds
777 .any(|k
| *k
== LibKind
::Rlib
|| *k
== LibKind
::Lib
|| *k
== LibKind
::ProcMacro
),
782 pub fn allows_underscores(&self) -> bool
{
783 self.is_bin() || self.is_example() || self.is_custom_build()
786 pub fn is_lib(&self) -> bool
{
788 TargetKind
::Lib(_
) => true,
793 pub fn is_dylib(&self) -> bool
{
795 TargetKind
::Lib(ref libs
) => libs
.iter().any(|l
| *l
== LibKind
::Dylib
),
800 pub fn is_cdylib(&self) -> bool
{
801 let libs
= match self.kind
{
802 TargetKind
::Lib(ref libs
) => libs
,
805 libs
.iter().any(|l
| match *l
{
806 LibKind
::Other(ref s
) => s
== "cdylib",
811 /// Returns whether this target produces an artifact which can be linked
812 /// into a Rust crate.
814 /// This only returns true for certain kinds of libraries.
815 pub fn linkable(&self) -> bool
{
817 TargetKind
::Lib(ref kinds
) => kinds
.iter().any(|k
| k
.linkable()),
822 /// Returns whether production of this artifact requires the object files
823 /// from dependencies to be available.
825 /// This only returns `false` when all we're producing is an rlib, otherwise
826 /// it will return `true`.
827 pub fn requires_upstream_objects(&self) -> bool
{
829 TargetKind
::Lib(kinds
) | TargetKind
::ExampleLib(kinds
) => {
830 kinds
.iter().any(|k
| k
.requires_upstream_objects())
836 pub fn is_bin(&self) -> bool
{
837 self.kind
== TargetKind
::Bin
840 pub fn is_example(&self) -> bool
{
842 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => true,
847 /// Returns `true` if it is a binary or executable example.
848 /// NOTE: Tests are `false`!
849 pub fn is_executable(&self) -> bool
{
850 self.is_bin() || self.is_exe_example()
853 /// Returns `true` if it is an executable example.
854 pub fn is_exe_example(&self) -> bool
{
855 // Needed for --all-examples in contexts where only runnable examples make sense
857 TargetKind
::ExampleBin
=> true,
862 pub fn is_test(&self) -> bool
{
863 self.kind
== TargetKind
::Test
865 pub fn is_bench(&self) -> bool
{
866 self.kind
== TargetKind
::Bench
868 pub fn is_custom_build(&self) -> bool
{
869 self.kind
== TargetKind
::CustomBuild
872 /// Returns the arguments suitable for `--crate-type` to pass to rustc.
873 pub fn rustc_crate_types(&self) -> Vec
<&str> {
875 TargetKind
::Lib(ref kinds
) | TargetKind
::ExampleLib(ref kinds
) => {
876 kinds
.iter().map(LibKind
::crate_type
).collect()
878 TargetKind
::CustomBuild
881 | TargetKind
::ExampleBin
882 | TargetKind
::Bin
=> vec
!["bin"],
886 pub fn can_lto(&self) -> bool
{
888 TargetKind
::Lib(ref v
) => {
889 !v
.contains(&LibKind
::Rlib
)
890 && !v
.contains(&LibKind
::Dylib
)
891 && !v
.contains(&LibKind
::Lib
)
897 pub fn set_tested(&mut self, tested
: bool
) -> &mut Target
{
898 self.tested
= tested
;
901 pub fn set_benched(&mut self, benched
: bool
) -> &mut Target
{
902 self.benched
= benched
;
905 pub fn set_doctest(&mut self, doctest
: bool
) -> &mut Target
{
906 self.doctest
= doctest
;
909 pub fn set_for_host(&mut self, for_host
: bool
) -> &mut Target
{
910 self.for_host
= for_host
;
913 pub fn set_proc_macro(&mut self, proc_macro
: bool
) -> &mut Target
{
914 self.proc_macro
= proc_macro
;
917 pub fn set_edition(&mut self, edition
: Edition
) -> &mut Target
{
918 self.edition
= edition
;
921 pub fn set_harness(&mut self, harness
: bool
) -> &mut Target
{
922 self.harness
= harness
;
925 pub fn set_doc(&mut self, doc
: bool
) -> &mut Target
{
931 impl fmt
::Display
for Target
{
932 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
934 TargetKind
::Lib(..) => write
!(f
, "Target(lib)"),
935 TargetKind
::Bin
=> write
!(f
, "Target(bin: {})", self.name
),
936 TargetKind
::Test
=> write
!(f
, "Target(test: {})", self.name
),
937 TargetKind
::Bench
=> write
!(f
, "Target(bench: {})", self.name
),
938 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => {
939 write
!(f
, "Target(example: {})", self.name
)
941 TargetKind
::CustomBuild
=> write
!(f
, "Target(script)"),
947 fn new() -> Warnings
{
951 pub fn add_warning(&mut self, s
: String
) {
952 self.0.push(DelayedWarning
{
958 pub fn add_critical_warning(&mut self, s
: String
) {
959 self.0.push(DelayedWarning
{
965 pub fn warnings(&self) -> &[DelayedWarning
] {