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,
125 impl fmt
::Debug
for LibKind
{
126 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
127 self.crate_type().fmt(f
)
131 impl<'a
> From
<&'a String
> for LibKind
{
132 fn from(string
: &'a String
) -> Self {
133 match string
.as_ref() {
134 "lib" => LibKind
::Lib
,
135 "rlib" => LibKind
::Rlib
,
136 "dylib" => LibKind
::Dylib
,
137 "proc-macro" => LibKind
::ProcMacro
,
138 s
=> LibKind
::Other(s
.to_string()),
143 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
144 pub enum TargetKind
{
149 ExampleLib(Vec
<LibKind
>),
154 impl ser
::Serialize
for TargetKind
{
155 fn serialize
<S
>(&self, s
: S
) -> Result
<S
::Ok
, S
::Error
>
159 use self::TargetKind
::*;
161 Lib(ref kinds
) => s
.collect_seq(kinds
.iter().map(LibKind
::crate_type
)),
162 Bin
=> ["bin"].serialize(s
),
163 ExampleBin
| ExampleLib(_
) => ["example"].serialize(s
),
164 Test
=> ["test"].serialize(s
),
165 CustomBuild
=> ["custom-build"].serialize(s
),
166 Bench
=> ["bench"].serialize(s
),
171 impl fmt
::Debug
for TargetKind
{
172 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
173 use self::TargetKind
::*;
175 Lib(ref kinds
) => kinds
.fmt(f
),
177 ExampleBin
| ExampleLib(_
) => "example".fmt(f
),
178 Test
=> "test".fmt(f
),
179 CustomBuild
=> "custom-build".fmt(f
),
180 Bench
=> "bench".fmt(f
),
186 pub fn description(&self) -> &'
static str {
188 TargetKind
::Lib(..) => "lib",
189 TargetKind
::Bin
=> "bin",
190 TargetKind
::Test
=> "integration-test",
191 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => "example",
192 TargetKind
::Bench
=> "bench",
193 TargetKind
::CustomBuild
=> "build-script",
198 /// Information about a binary, a library, an example, etc. that is part of the
200 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
204 // Note that the `src_path` here is excluded from the `Hash` implementation
205 // as it's absolute currently and is otherwise a little too brittle for
206 // causing rebuilds. Instead the hash for the path that we send to the
207 // compiler is handled elsewhere.
208 src_path
: TargetSourcePath
,
209 required_features
: Option
<Vec
<String
>>,
214 harness
: bool
, // whether to use the test harness (--test)
220 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
221 pub enum TargetSourcePath
{
226 impl TargetSourcePath
{
227 pub fn path(&self) -> Option
<&Path
> {
229 TargetSourcePath
::Path(path
) => Some(path
.as_ref()),
230 TargetSourcePath
::Metabuild
=> None
,
234 pub fn is_path(&self) -> bool
{
236 TargetSourcePath
::Path(_
) => true,
242 impl Hash
for TargetSourcePath
{
243 fn hash
<H
: Hasher
>(&self, _
: &mut H
) {
248 impl fmt
::Debug
for TargetSourcePath
{
249 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
251 TargetSourcePath
::Path(path
) => path
.fmt(f
),
252 TargetSourcePath
::Metabuild
=> "metabuild".fmt(f
),
257 impl From
<PathBuf
> for TargetSourcePath
{
258 fn from(path
: PathBuf
) -> Self {
259 assert
!(path
.is_absolute(), "`{}` is not absolute", path
.display());
260 TargetSourcePath
::Path(path
)
265 struct SerializedTarget
<'a
> {
266 /// Is this a `--bin bin`, `--lib`, `--example ex`?
267 /// Serialized as a list of strings for historical reasons.
268 kind
: &'a TargetKind
,
269 /// Corresponds to `--crate-type` compiler attribute.
270 /// See https://doc.rust-lang.org/reference/linkage.html
271 crate_types
: Vec
<&'a
str>,
273 src_path
: Option
<&'a PathBuf
>,
275 #[serde(rename = "required-features", skip_serializing_if = "Option::is_none")]
276 required_features
: Option
<Vec
<&'a
str>>,
279 impl ser
::Serialize
for Target
{
280 fn serialize
<S
: ser
::Serializer
>(&self, s
: S
) -> Result
<S
::Ok
, S
::Error
> {
281 let src_path
= match &self.src_path
{
282 TargetSourcePath
::Path(p
) => Some(p
),
283 // Unfortunately getting the correct path would require access to
284 // target_dir, which is not available here.
285 TargetSourcePath
::Metabuild
=> None
,
289 crate_types
: self.rustc_crate_types(),
292 edition
: &self.edition
.to_string(),
293 required_features
: self
296 .map(|rf
| rf
.iter().map(|s
| &**s
).collect()),
303 impl fmt
::Debug
for Target
{
304 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
305 let (default, default_name
) = {
307 TargetKind
::Lib(kinds
) => {
312 self.src_path().path().unwrap().to_path_buf(),
315 format
!("lib_target({:?}, {:?}, {:?}, {:?})",
316 self.name
, kinds
, self.src_path
, self.edition
),
319 TargetKind
::CustomBuild
=> {
320 match self.src_path
{
321 TargetSourcePath
::Path(ref path
) => {
323 Target
::custom_build_target(
328 format
!("custom_build_target({:?}, {:?}, {:?})",
329 self.name
, path
, self.edition
),
332 TargetSourcePath
::Metabuild
=> {
334 Target
::metabuild_target(&self.name
),
335 format
!("metabuild_target({:?})", self.name
),
341 Target
::new(self.src_path
.clone(), self.edition
),
342 format
!("with_path({:?}, {:?})", self.src_path
, self.edition
),
367 targets
: Vec
<Target
>,
368 exclude
: Vec
<String
>,
369 include
: Vec
<String
>,
370 links
: Option
<String
>,
371 metadata
: ManifestMetadata
,
372 custom_metadata
: Option
<toml
::Value
>,
374 publish
: Option
<Vec
<String
>>,
375 publish_lockfile
: bool
,
376 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
377 patch
: HashMap
<Url
, Vec
<Dependency
>>,
378 workspace
: WorkspaceConfig
,
381 im_a_teapot
: Option
<bool
>,
382 default_run
: Option
<String
>,
383 original
: Rc
<TomlManifest
>,
384 metabuild
: Option
<Vec
<String
>>,
389 warnings
: Warnings
::new(),
410 pub fn dependencies(&self) -> &[Dependency
] {
411 self.summary
.dependencies()
413 pub fn exclude(&self) -> &[String
] {
416 pub fn include(&self) -> &[String
] {
419 pub fn metadata(&self) -> &ManifestMetadata
{
422 pub fn name(&self) -> InternedString
{
423 self.package_id().name()
425 pub fn package_id(&self) -> PackageId
{
426 self.summary
.package_id()
428 pub fn summary(&self) -> &Summary
{
431 pub fn targets(&self) -> &[Target
] {
434 pub fn version(&self) -> &Version
{
435 self.package_id().version()
437 pub fn warnings_mut(&mut self) -> &mut Warnings
{
440 pub fn warnings(&self) -> &Warnings
{
443 pub fn profiles(&self) -> &Profiles
{
446 pub fn publish(&self) -> &Option
<Vec
<String
>> {
449 pub fn publish_lockfile(&self) -> bool
{
450 self.publish_lockfile
452 pub fn replace(&self) -> &[(PackageIdSpec
, Dependency
)] {
455 pub fn original(&self) -> &TomlManifest
{
458 pub fn patch(&self) -> &HashMap
<Url
, Vec
<Dependency
>> {
461 pub fn links(&self) -> Option
<&str> {
462 self.links
.as_ref().map(|s
| &s
[..])
465 pub fn workspace_config(&self) -> &WorkspaceConfig
{
469 pub fn features(&self) -> &Features
{
473 pub fn set_summary(&mut self, summary
: Summary
) {
474 self.summary
= summary
;
477 pub fn map_source(self, to_replace
: SourceId
, replace_with
: SourceId
) -> Manifest
{
479 summary
: self.summary
.map_source(to_replace
, replace_with
),
484 pub fn feature_gate(&self) -> CargoResult
<()> {
485 if self.im_a_teapot
.is_some() {
487 .require(Feature
::test_dummy_unstable())
489 failure
::format_err
!(
490 "the `im-a-teapot` manifest key is unstable and may \
491 not work properly in England"
496 if self.default_run
.is_some() {
498 .require(Feature
::default_run())
499 .chain_err(|| failure
::format_err
!("the `default-run` manifest key is unstable"))?
;
505 // Just a helper function to test out `-Z` flags on Cargo
506 pub fn print_teapot(&self, config
: &Config
) {
507 if let Some(teapot
) = self.im_a_teapot
{
508 if config
.cli_unstable().print_im_a_teapot
{
509 println
!("im-a-teapot = {}", teapot
);
514 pub fn edition(&self) -> Edition
{
518 pub fn custom_metadata(&self) -> Option
<&toml
::Value
> {
519 self.custom_metadata
.as_ref()
522 pub fn default_run(&self) -> Option
<&str> {
523 self.default_run
.as_ref().map(|s
| &s
[..])
526 pub fn metabuild(&self) -> Option
<&Vec
<String
>> {
527 self.metabuild
.as_ref()
530 pub fn metabuild_path(&self, target_dir
: Filesystem
) -> PathBuf
{
531 let hash
= short_hash(&self.package_id());
533 .into_path_unlocked()
535 .join(format
!("metabuild-{}-{}.rs", self.name(), hash
))
539 impl VirtualManifest
{
541 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
542 patch
: HashMap
<Url
, Vec
<Dependency
>>,
543 workspace
: WorkspaceConfig
,
546 ) -> VirtualManifest
{
552 warnings
: Warnings
::new(),
557 pub fn replace(&self) -> &[(PackageIdSpec
, Dependency
)] {
561 pub fn patch(&self) -> &HashMap
<Url
, Vec
<Dependency
>> {
565 pub fn workspace_config(&self) -> &WorkspaceConfig
{
569 pub fn profiles(&self) -> &Profiles
{
573 pub fn warnings_mut(&mut self) -> &mut Warnings
{
577 pub fn warnings(&self) -> &Warnings
{
581 pub fn features(&self) -> &Features
{
587 fn new(src_path
: TargetSourcePath
, edition
: Edition
) -> Target
{
589 kind
: TargetKind
::Bin
,
592 required_features
: None
,
604 fn with_path(src_path
: PathBuf
, edition
: Edition
) -> Target
{
605 Target
::new(TargetSourcePath
::from(src_path
), edition
)
610 crate_targets
: Vec
<LibKind
>,
615 kind
: TargetKind
::Lib(crate_targets
),
616 name
: name
.to_string(),
619 ..Target
::with_path(src_path
, edition
)
626 required_features
: Option
<Vec
<String
>>,
630 kind
: TargetKind
::Bin
,
631 name
: name
.to_string(),
634 ..Target
::with_path(src_path
, edition
)
638 /// Builds a `Target` corresponding to the `build = "build.rs"` entry.
639 pub fn custom_build_target(name
: &str, src_path
: PathBuf
, edition
: Edition
) -> Target
{
641 kind
: TargetKind
::CustomBuild
,
642 name
: name
.to_string(),
646 ..Target
::with_path(src_path
, edition
)
650 pub fn metabuild_target(name
: &str) -> Target
{
652 kind
: TargetKind
::CustomBuild
,
653 name
: name
.to_string(),
657 ..Target
::new(TargetSourcePath
::Metabuild
, Edition
::Edition2018
)
661 pub fn example_target(
663 crate_targets
: Vec
<LibKind
>,
665 required_features
: Option
<Vec
<String
>>,
668 let kind
= if crate_targets
.is_empty()
671 .all(|t
| *t
== LibKind
::Other("bin".into()))
673 TargetKind
::ExampleBin
675 TargetKind
::ExampleLib(crate_targets
)
680 name
: name
.to_string(),
684 ..Target
::with_path(src_path
, edition
)
691 required_features
: Option
<Vec
<String
>>,
695 kind
: TargetKind
::Test
,
696 name
: name
.to_string(),
699 ..Target
::with_path(src_path
, edition
)
706 required_features
: Option
<Vec
<String
>>,
710 kind
: TargetKind
::Bench
,
711 name
: name
.to_string(),
714 ..Target
::with_path(src_path
, edition
)
718 pub fn name(&self) -> &str {
721 pub fn crate_name(&self) -> String
{
722 self.name
.replace("-", "_")
724 pub fn src_path(&self) -> &TargetSourcePath
{
727 pub fn set_src_path(&mut self, src_path
: TargetSourcePath
) {
728 self.src_path
= src_path
;
730 pub fn required_features(&self) -> Option
<&Vec
<String
>> {
731 self.required_features
.as_ref()
733 pub fn kind(&self) -> &TargetKind
{
736 pub fn tested(&self) -> bool
{
739 pub fn harness(&self) -> bool
{
742 pub fn documented(&self) -> bool
{
745 pub fn for_host(&self) -> bool
{
748 pub fn proc_macro(&self) -> bool
{
751 pub fn edition(&self) -> Edition
{
754 pub fn benched(&self) -> bool
{
757 pub fn doctested(&self) -> bool
{
761 pub fn doctestable(&self) -> bool
{
763 TargetKind
::Lib(ref kinds
) => kinds
765 .any(|k
| *k
== LibKind
::Rlib
|| *k
== LibKind
::Lib
|| *k
== LibKind
::ProcMacro
),
770 pub fn allows_underscores(&self) -> bool
{
771 self.is_bin() || self.is_example() || self.is_custom_build()
774 pub fn is_lib(&self) -> bool
{
776 TargetKind
::Lib(_
) => true,
781 pub fn is_dylib(&self) -> bool
{
783 TargetKind
::Lib(ref libs
) => libs
.iter().any(|l
| *l
== LibKind
::Dylib
),
788 pub fn is_cdylib(&self) -> bool
{
789 let libs
= match self.kind
{
790 TargetKind
::Lib(ref libs
) => libs
,
793 libs
.iter().any(|l
| match *l
{
794 LibKind
::Other(ref s
) => s
== "cdylib",
799 pub fn linkable(&self) -> bool
{
801 TargetKind
::Lib(ref kinds
) => kinds
.iter().any(|k
| k
.linkable()),
806 pub fn is_bin(&self) -> bool
{
807 self.kind
== TargetKind
::Bin
810 pub fn is_example(&self) -> bool
{
812 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => true,
817 pub fn is_bin_example(&self) -> bool
{
818 // Needed for --all-examples in contexts where only runnable examples make sense
820 TargetKind
::ExampleBin
=> true,
825 pub fn is_test(&self) -> bool
{
826 self.kind
== TargetKind
::Test
828 pub fn is_bench(&self) -> bool
{
829 self.kind
== TargetKind
::Bench
831 pub fn is_custom_build(&self) -> bool
{
832 self.kind
== TargetKind
::CustomBuild
835 /// Returns the arguments suitable for `--crate-type` to pass to rustc.
836 pub fn rustc_crate_types(&self) -> Vec
<&str> {
838 TargetKind
::Lib(ref kinds
) | TargetKind
::ExampleLib(ref kinds
) => {
839 kinds
.iter().map(LibKind
::crate_type
).collect()
841 TargetKind
::CustomBuild
844 | TargetKind
::ExampleBin
845 | TargetKind
::Bin
=> vec
!["bin"],
849 pub fn can_lto(&self) -> bool
{
851 TargetKind
::Lib(ref v
) => {
852 !v
.contains(&LibKind
::Rlib
)
853 && !v
.contains(&LibKind
::Dylib
)
854 && !v
.contains(&LibKind
::Lib
)
860 pub fn set_tested(&mut self, tested
: bool
) -> &mut Target
{
861 self.tested
= tested
;
864 pub fn set_benched(&mut self, benched
: bool
) -> &mut Target
{
865 self.benched
= benched
;
868 pub fn set_doctest(&mut self, doctest
: bool
) -> &mut Target
{
869 self.doctest
= doctest
;
872 pub fn set_for_host(&mut self, for_host
: bool
) -> &mut Target
{
873 self.for_host
= for_host
;
876 pub fn set_proc_macro(&mut self, proc_macro
: bool
) -> &mut Target
{
877 self.proc_macro
= proc_macro
;
880 pub fn set_edition(&mut self, edition
: Edition
) -> &mut Target
{
881 self.edition
= edition
;
884 pub fn set_harness(&mut self, harness
: bool
) -> &mut Target
{
885 self.harness
= harness
;
888 pub fn set_doc(&mut self, doc
: bool
) -> &mut Target
{
894 impl fmt
::Display
for Target
{
895 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
897 TargetKind
::Lib(..) => write
!(f
, "Target(lib)"),
898 TargetKind
::Bin
=> write
!(f
, "Target(bin: {})", self.name
),
899 TargetKind
::Test
=> write
!(f
, "Target(test: {})", self.name
),
900 TargetKind
::Bench
=> write
!(f
, "Target(bench: {})", self.name
),
901 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => {
902 write
!(f
, "Target(example: {})", self.name
)
904 TargetKind
::CustomBuild
=> write
!(f
, "Target(script)"),
910 fn new() -> Warnings
{
914 pub fn add_warning(&mut self, s
: String
) {
915 self.0.push(DelayedWarning
{
921 pub fn add_critical_warning(&mut self, s
: String
) {
922 self.0.push(DelayedWarning
{
928 pub fn warnings(&self) -> &[DelayedWarning
] {