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
,
71 /// General metadata about a package which is just blindly uploaded to the
74 /// Note that many of these fields can contain invalid values such as the
75 /// homepage, repository, documentation, or license. These fields are not
76 /// validated by cargo itself, but rather it is up to the registry when uploaded
77 /// to validate these fields. Cargo will itself accept any valid TOML
78 /// specification for these values.
79 #[derive(PartialEq, Clone, Debug)]
80 pub struct ManifestMetadata
{
81 pub authors
: Vec
<String
>,
82 pub keywords
: Vec
<String
>,
83 pub categories
: Vec
<String
>,
84 pub license
: Option
<String
>,
85 pub license_file
: Option
<String
>,
86 pub description
: Option
<String
>, // not markdown
87 pub readme
: Option
<String
>, // file, not contents
88 pub homepage
: Option
<String
>, // url
89 pub repository
: Option
<String
>, // url
90 pub documentation
: Option
<String
>, // url
91 pub badges
: BTreeMap
<String
, BTreeMap
<String
, String
>>,
92 pub links
: Option
<String
>,
95 #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
105 /// Returns the argument suitable for `--crate-type` to pass to rustc.
106 pub fn crate_type(&self) -> &str {
108 LibKind
::Lib
=> "lib",
109 LibKind
::Rlib
=> "rlib",
110 LibKind
::Dylib
=> "dylib",
111 LibKind
::ProcMacro
=> "proc-macro",
112 LibKind
::Other(ref s
) => s
,
116 pub fn linkable(&self) -> bool
{
118 LibKind
::Lib
| LibKind
::Rlib
| LibKind
::Dylib
| LibKind
::ProcMacro
=> true,
119 LibKind
::Other(..) => false,
124 impl fmt
::Debug
for LibKind
{
125 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
126 self.crate_type().fmt(f
)
130 impl<'a
> From
<&'a String
> for LibKind
{
131 fn from(string
: &'a String
) -> Self {
132 match string
.as_ref() {
133 "lib" => LibKind
::Lib
,
134 "rlib" => LibKind
::Rlib
,
135 "dylib" => LibKind
::Dylib
,
136 "proc-macro" => LibKind
::ProcMacro
,
137 s
=> LibKind
::Other(s
.to_string()),
142 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
143 pub enum TargetKind
{
148 ExampleLib(Vec
<LibKind
>),
153 impl ser
::Serialize
for TargetKind
{
154 fn serialize
<S
>(&self, s
: S
) -> Result
<S
::Ok
, S
::Error
>
158 use self::TargetKind
::*;
160 Lib(ref kinds
) => s
.collect_seq(kinds
.iter().map(LibKind
::crate_type
)),
161 Bin
=> ["bin"].serialize(s
),
162 ExampleBin
| ExampleLib(_
) => ["example"].serialize(s
),
163 Test
=> ["test"].serialize(s
),
164 CustomBuild
=> ["custom-build"].serialize(s
),
165 Bench
=> ["bench"].serialize(s
),
170 impl fmt
::Debug
for TargetKind
{
171 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
172 use self::TargetKind
::*;
174 Lib(ref kinds
) => kinds
.fmt(f
),
176 ExampleBin
| ExampleLib(_
) => "example".fmt(f
),
177 Test
=> "test".fmt(f
),
178 CustomBuild
=> "custom-build".fmt(f
),
179 Bench
=> "bench".fmt(f
),
185 pub fn description(&self) -> &'
static str {
187 TargetKind
::Lib(..) => "lib",
188 TargetKind
::Bin
=> "bin",
189 TargetKind
::Test
=> "integration-test",
190 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => "example",
191 TargetKind
::Bench
=> "bench",
192 TargetKind
::CustomBuild
=> "build-script",
197 /// Information about a binary, a library, an example, etc. that is part of the
199 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
203 // Note that the `src_path` here is excluded from the `Hash` implementation
204 // as it's absolute currently and is otherwise a little too brittle for
205 // causing rebuilds. Instead the hash for the path that we send to the
206 // compiler is handled elsewhere.
207 src_path
: TargetSourcePath
,
208 required_features
: Option
<Vec
<String
>>,
213 harness
: bool
, // whether to use the test harness (--test)
219 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
220 pub enum TargetSourcePath
{
225 impl TargetSourcePath
{
226 pub fn path(&self) -> Option
<&Path
> {
228 TargetSourcePath
::Path(path
) => Some(path
.as_ref()),
229 TargetSourcePath
::Metabuild
=> None
,
233 pub fn is_path(&self) -> bool
{
235 TargetSourcePath
::Path(_
) => true,
241 impl Hash
for TargetSourcePath
{
242 fn hash
<H
: Hasher
>(&self, _
: &mut H
) {
247 impl fmt
::Debug
for TargetSourcePath
{
248 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
250 TargetSourcePath
::Path(path
) => path
.fmt(f
),
251 TargetSourcePath
::Metabuild
=> "metabuild".fmt(f
),
256 impl From
<PathBuf
> for TargetSourcePath
{
257 fn from(path
: PathBuf
) -> Self {
258 assert
!(path
.is_absolute(), "`{}` is not absolute", path
.display());
259 TargetSourcePath
::Path(path
)
264 struct SerializedTarget
<'a
> {
265 /// Is this a `--bin bin`, `--lib`, `--example ex`?
266 /// Serialized as a list of strings for historical reasons.
267 kind
: &'a TargetKind
,
268 /// Corresponds to `--crate-type` compiler attribute.
269 /// See https://doc.rust-lang.org/reference/linkage.html
270 crate_types
: Vec
<&'a
str>,
272 src_path
: Option
<&'a PathBuf
>,
274 #[serde(rename = "required-features", skip_serializing_if = "Option::is_none")]
275 required_features
: Option
<Vec
<&'a
str>>,
278 impl ser
::Serialize
for Target
{
279 fn serialize
<S
: ser
::Serializer
>(&self, s
: S
) -> Result
<S
::Ok
, S
::Error
> {
280 let src_path
= match &self.src_path
{
281 TargetSourcePath
::Path(p
) => Some(p
),
282 // Unfortunately getting the correct path would require access to
283 // target_dir, which is not available here.
284 TargetSourcePath
::Metabuild
=> None
,
288 crate_types
: self.rustc_crate_types(),
291 edition
: &self.edition
.to_string(),
292 required_features
: self
295 .map(|rf
| rf
.iter().map(|s
| &**s
).collect()),
302 impl fmt
::Debug
for Target
{
303 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
304 let (default, default_name
) = {
306 TargetKind
::Lib(kinds
) => {
311 self.src_path().path().unwrap().to_path_buf(),
314 format
!("lib_target({:?}, {:?}, {:?}, {:?})",
315 self.name
, kinds
, self.src_path
, self.edition
),
318 TargetKind
::CustomBuild
=> {
319 match self.src_path
{
320 TargetSourcePath
::Path(ref path
) => {
322 Target
::custom_build_target(
327 format
!("custom_build_target({:?}, {:?}, {:?})",
328 self.name
, path
, self.edition
),
331 TargetSourcePath
::Metabuild
=> {
333 Target
::metabuild_target(&self.name
),
334 format
!("metabuild_target({:?})", self.name
),
340 Target
::new(self.src_path
.clone(), self.edition
),
341 format
!("with_path({:?}, {:?})", self.src_path
, self.edition
),
366 targets
: Vec
<Target
>,
367 exclude
: Vec
<String
>,
368 include
: Vec
<String
>,
369 links
: Option
<String
>,
370 metadata
: ManifestMetadata
,
371 custom_metadata
: Option
<toml
::Value
>,
373 publish
: Option
<Vec
<String
>>,
374 publish_lockfile
: bool
,
375 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
376 patch
: HashMap
<Url
, Vec
<Dependency
>>,
377 workspace
: WorkspaceConfig
,
380 im_a_teapot
: Option
<bool
>,
381 default_run
: Option
<String
>,
382 original
: Rc
<TomlManifest
>,
383 metabuild
: Option
<Vec
<String
>>,
388 warnings
: Warnings
::new(),
409 pub fn dependencies(&self) -> &[Dependency
] {
410 self.summary
.dependencies()
412 pub fn exclude(&self) -> &[String
] {
415 pub fn include(&self) -> &[String
] {
418 pub fn metadata(&self) -> &ManifestMetadata
{
421 pub fn name(&self) -> InternedString
{
422 self.package_id().name()
424 pub fn package_id(&self) -> PackageId
{
425 self.summary
.package_id()
427 pub fn summary(&self) -> &Summary
{
430 pub fn targets(&self) -> &[Target
] {
433 pub fn version(&self) -> &Version
{
434 self.package_id().version()
436 pub fn warnings_mut(&mut self) -> &mut Warnings
{
439 pub fn warnings(&self) -> &Warnings
{
442 pub fn profiles(&self) -> &Profiles
{
445 pub fn publish(&self) -> &Option
<Vec
<String
>> {
448 pub fn publish_lockfile(&self) -> bool
{
449 self.publish_lockfile
451 pub fn replace(&self) -> &[(PackageIdSpec
, Dependency
)] {
454 pub fn original(&self) -> &TomlManifest
{
457 pub fn patch(&self) -> &HashMap
<Url
, Vec
<Dependency
>> {
460 pub fn links(&self) -> Option
<&str> {
461 self.links
.as_ref().map(|s
| &s
[..])
464 pub fn workspace_config(&self) -> &WorkspaceConfig
{
468 pub fn features(&self) -> &Features
{
472 pub fn set_summary(&mut self, summary
: Summary
) {
473 self.summary
= summary
;
476 pub fn map_source(self, to_replace
: SourceId
, replace_with
: SourceId
) -> Manifest
{
478 summary
: self.summary
.map_source(to_replace
, replace_with
),
483 pub fn feature_gate(&self) -> CargoResult
<()> {
484 if self.im_a_teapot
.is_some() {
486 .require(Feature
::test_dummy_unstable())
488 failure
::format_err
!(
489 "the `im-a-teapot` manifest key is unstable and may \
490 not work properly in England"
495 if self.default_run
.is_some() {
497 .require(Feature
::default_run())
498 .chain_err(|| failure
::format_err
!("the `default-run` manifest key is unstable"))?
;
504 // Just a helper function to test out `-Z` flags on Cargo
505 pub fn print_teapot(&self, config
: &Config
) {
506 if let Some(teapot
) = self.im_a_teapot
{
507 if config
.cli_unstable().print_im_a_teapot
{
508 println
!("im-a-teapot = {}", teapot
);
513 pub fn edition(&self) -> Edition
{
517 pub fn custom_metadata(&self) -> Option
<&toml
::Value
> {
518 self.custom_metadata
.as_ref()
521 pub fn default_run(&self) -> Option
<&str> {
522 self.default_run
.as_ref().map(|s
| &s
[..])
525 pub fn metabuild(&self) -> Option
<&Vec
<String
>> {
526 self.metabuild
.as_ref()
529 pub fn metabuild_path(&self, target_dir
: Filesystem
) -> PathBuf
{
530 let hash
= short_hash(&self.package_id());
532 .into_path_unlocked()
534 .join(format
!("metabuild-{}-{}.rs", self.name(), hash
))
538 impl VirtualManifest
{
540 replace
: Vec
<(PackageIdSpec
, Dependency
)>,
541 patch
: HashMap
<Url
, Vec
<Dependency
>>,
542 workspace
: WorkspaceConfig
,
544 ) -> VirtualManifest
{
550 warnings
: Warnings
::new(),
554 pub fn replace(&self) -> &[(PackageIdSpec
, Dependency
)] {
558 pub fn patch(&self) -> &HashMap
<Url
, Vec
<Dependency
>> {
562 pub fn workspace_config(&self) -> &WorkspaceConfig
{
566 pub fn profiles(&self) -> &Profiles
{
570 pub fn warnings_mut(&mut self) -> &mut Warnings
{
574 pub fn warnings(&self) -> &Warnings
{
580 fn new(src_path
: TargetSourcePath
, edition
: Edition
) -> Target
{
582 kind
: TargetKind
::Bin
,
585 required_features
: None
,
597 fn with_path(src_path
: PathBuf
, edition
: Edition
) -> Target
{
598 Target
::new(TargetSourcePath
::from(src_path
), edition
)
603 crate_targets
: Vec
<LibKind
>,
608 kind
: TargetKind
::Lib(crate_targets
),
609 name
: name
.to_string(),
612 ..Target
::with_path(src_path
, edition
)
619 required_features
: Option
<Vec
<String
>>,
623 kind
: TargetKind
::Bin
,
624 name
: name
.to_string(),
627 ..Target
::with_path(src_path
, edition
)
631 /// Builds a `Target` corresponding to the `build = "build.rs"` entry.
632 pub fn custom_build_target(name
: &str, src_path
: PathBuf
, edition
: Edition
) -> Target
{
634 kind
: TargetKind
::CustomBuild
,
635 name
: name
.to_string(),
639 ..Target
::with_path(src_path
, edition
)
643 pub fn metabuild_target(name
: &str) -> Target
{
645 kind
: TargetKind
::CustomBuild
,
646 name
: name
.to_string(),
650 ..Target
::new(TargetSourcePath
::Metabuild
, Edition
::Edition2018
)
654 pub fn example_target(
656 crate_targets
: Vec
<LibKind
>,
658 required_features
: Option
<Vec
<String
>>,
661 let kind
= if crate_targets
.is_empty()
664 .all(|t
| *t
== LibKind
::Other("bin".into()))
666 TargetKind
::ExampleBin
668 TargetKind
::ExampleLib(crate_targets
)
673 name
: name
.to_string(),
677 ..Target
::with_path(src_path
, edition
)
684 required_features
: Option
<Vec
<String
>>,
688 kind
: TargetKind
::Test
,
689 name
: name
.to_string(),
692 ..Target
::with_path(src_path
, edition
)
699 required_features
: Option
<Vec
<String
>>,
703 kind
: TargetKind
::Bench
,
704 name
: name
.to_string(),
707 ..Target
::with_path(src_path
, edition
)
711 pub fn name(&self) -> &str {
714 pub fn crate_name(&self) -> String
{
715 self.name
.replace("-", "_")
717 pub fn src_path(&self) -> &TargetSourcePath
{
720 pub fn set_src_path(&mut self, src_path
: TargetSourcePath
) {
721 self.src_path
= src_path
;
723 pub fn required_features(&self) -> Option
<&Vec
<String
>> {
724 self.required_features
.as_ref()
726 pub fn kind(&self) -> &TargetKind
{
729 pub fn tested(&self) -> bool
{
732 pub fn harness(&self) -> bool
{
735 pub fn documented(&self) -> bool
{
738 pub fn for_host(&self) -> bool
{
741 pub fn proc_macro(&self) -> bool
{
744 pub fn edition(&self) -> Edition
{
747 pub fn benched(&self) -> bool
{
750 pub fn doctested(&self) -> bool
{
754 pub fn doctestable(&self) -> bool
{
756 TargetKind
::Lib(ref kinds
) => kinds
758 .any(|k
| *k
== LibKind
::Rlib
|| *k
== LibKind
::Lib
|| *k
== LibKind
::ProcMacro
),
763 pub fn allows_underscores(&self) -> bool
{
764 self.is_bin() || self.is_example() || self.is_custom_build()
767 pub fn is_lib(&self) -> bool
{
769 TargetKind
::Lib(_
) => true,
774 pub fn is_dylib(&self) -> bool
{
776 TargetKind
::Lib(ref libs
) => libs
.iter().any(|l
| *l
== LibKind
::Dylib
),
781 pub fn is_cdylib(&self) -> bool
{
782 let libs
= match self.kind
{
783 TargetKind
::Lib(ref libs
) => libs
,
786 libs
.iter().any(|l
| match *l
{
787 LibKind
::Other(ref s
) => s
== "cdylib",
792 pub fn linkable(&self) -> bool
{
794 TargetKind
::Lib(ref kinds
) => kinds
.iter().any(|k
| k
.linkable()),
799 pub fn is_bin(&self) -> bool
{
800 self.kind
== TargetKind
::Bin
803 pub fn is_example(&self) -> bool
{
805 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => true,
810 pub fn is_bin_example(&self) -> bool
{
811 // Needed for --all-examples in contexts where only runnable examples make sense
813 TargetKind
::ExampleBin
=> true,
818 pub fn is_test(&self) -> bool
{
819 self.kind
== TargetKind
::Test
821 pub fn is_bench(&self) -> bool
{
822 self.kind
== TargetKind
::Bench
824 pub fn is_custom_build(&self) -> bool
{
825 self.kind
== TargetKind
::CustomBuild
828 /// Returns the arguments suitable for `--crate-type` to pass to rustc.
829 pub fn rustc_crate_types(&self) -> Vec
<&str> {
831 TargetKind
::Lib(ref kinds
) | TargetKind
::ExampleLib(ref kinds
) => {
832 kinds
.iter().map(LibKind
::crate_type
).collect()
834 TargetKind
::CustomBuild
837 | TargetKind
::ExampleBin
838 | TargetKind
::Bin
=> vec
!["bin"],
842 pub fn can_lto(&self) -> bool
{
844 TargetKind
::Lib(ref v
) => {
845 !v
.contains(&LibKind
::Rlib
)
846 && !v
.contains(&LibKind
::Dylib
)
847 && !v
.contains(&LibKind
::Lib
)
853 pub fn set_tested(&mut self, tested
: bool
) -> &mut Target
{
854 self.tested
= tested
;
857 pub fn set_benched(&mut self, benched
: bool
) -> &mut Target
{
858 self.benched
= benched
;
861 pub fn set_doctest(&mut self, doctest
: bool
) -> &mut Target
{
862 self.doctest
= doctest
;
865 pub fn set_for_host(&mut self, for_host
: bool
) -> &mut Target
{
866 self.for_host
= for_host
;
869 pub fn set_proc_macro(&mut self, proc_macro
: bool
) -> &mut Target
{
870 self.proc_macro
= proc_macro
;
873 pub fn set_edition(&mut self, edition
: Edition
) -> &mut Target
{
874 self.edition
= edition
;
877 pub fn set_harness(&mut self, harness
: bool
) -> &mut Target
{
878 self.harness
= harness
;
881 pub fn set_doc(&mut self, doc
: bool
) -> &mut Target
{
887 impl fmt
::Display
for Target
{
888 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
890 TargetKind
::Lib(..) => write
!(f
, "Target(lib)"),
891 TargetKind
::Bin
=> write
!(f
, "Target(bin: {})", self.name
),
892 TargetKind
::Test
=> write
!(f
, "Target(test: {})", self.name
),
893 TargetKind
::Bench
=> write
!(f
, "Target(bench: {})", self.name
),
894 TargetKind
::ExampleBin
| TargetKind
::ExampleLib(..) => {
895 write
!(f
, "Target(example: {})", self.name
)
897 TargetKind
::CustomBuild
=> write
!(f
, "Target(script)"),
903 fn new() -> Warnings
{
907 pub fn add_warning(&mut self, s
: String
) {
908 self.0.push(DelayedWarning
{
914 pub fn add_critical_warning(&mut self, s
: String
) {
915 self.0.push(DelayedWarning
{
921 pub fn warnings(&self) -> &[DelayedWarning
] {