cargo_metadata/
dependency.rs

1//! This module contains `Dependency` and the types/functions it uses for deserialization.
2
3use std::fmt;
4
5use camino::Utf8PathBuf;
6#[cfg(feature = "builder")]
7use derive_builder::Builder;
8use semver::VersionReq;
9use serde::{Deserialize, Deserializer, Serialize};
10
11#[derive(Eq, PartialEq, Clone, Debug, Copy, Hash, Serialize, Deserialize, Default)]
12/// Dependencies can come in three kinds
13pub enum DependencyKind {
14    #[serde(rename = "normal")]
15    #[default]
16    /// The 'normal' kind
17    Normal,
18    #[serde(rename = "dev")]
19    /// Those used in tests only
20    Development,
21    #[serde(rename = "build")]
22    /// Those used in build scripts only
23    Build,
24    #[doc(hidden)]
25    #[serde(other)]
26    Unknown,
27}
28
29impl fmt::Display for DependencyKind {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        let s = serde_json::to_string(self).unwrap();
32        // skip opening and closing quotes
33        f.write_str(&s[1..s.len() - 1])
34    }
35}
36
37/// The `kind` can be `null`, which is interpreted as the default - `Normal`.
38pub(super) fn parse_dependency_kind<'de, D>(d: D) -> Result<DependencyKind, D::Error>
39where
40    D: Deserializer<'de>,
41{
42    Deserialize::deserialize(d).map(|x: Option<_>| x.unwrap_or_default())
43}
44
45#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
46#[cfg_attr(feature = "builder", derive(Builder))]
47#[non_exhaustive]
48#[cfg_attr(feature = "builder", builder(pattern = "owned", setter(into)))]
49/// A dependency of the main crate
50pub struct Dependency {
51    /// Name as given in the `Cargo.toml`
52    pub name: String,
53    /// The source of dependency
54    pub source: Option<String>,
55    /// The required version
56    pub req: VersionReq,
57    /// The kind of dependency this is
58    #[serde(deserialize_with = "parse_dependency_kind")]
59    pub kind: DependencyKind,
60    /// Whether this dependency is required or optional
61    pub optional: bool,
62    /// Whether the default features in this dependency are used.
63    pub uses_default_features: bool,
64    /// The list of features enabled for this dependency.
65    pub features: Vec<String>,
66    /// The target this dependency is specific to.
67    ///
68    /// Use the [`Display`] trait to access the contents.
69    ///
70    /// [`Display`]: std::fmt::Display
71    pub target: Option<Platform>,
72    /// If the dependency is renamed, this is the new name for the dependency
73    /// as a string.  None if it is not renamed.
74    pub rename: Option<String>,
75    /// The URL of the index of the registry where this dependency is from.
76    ///
77    /// If None, the dependency is from crates.io.
78    pub registry: Option<String>,
79    /// The file system path for a local path dependency.
80    ///
81    /// Only produced on cargo 1.51+
82    pub path: Option<Utf8PathBuf>,
83}
84
85pub use cargo_platform::Platform;