Skip to main content

cargo_workspace2/cargo/
deps.rs

1use super::v_to_s;
2use toml_edit::InlineTable;
3
4/// An intra-workspace dependency
5///
6/// In a Cargo.toml file these are expressed as paths, and sometimes
7/// also as versions.
8///
9/// ```toml
10/// [dependencies]
11/// my-other-crate = { version = "0.1.0", path = "../other-crate" }
12/// ```
13#[derive(Debug, Clone)]
14pub struct Dependency {
15    pub name: String,
16    pub alias: Option<String>,
17    pub version: Option<String>,
18    pub path: Option<String>,
19}
20
21impl Dependency {
22    pub(crate) fn parse(n: String, t: &InlineTable) -> Option<Self> {
23        let v = t.get("version").map(|s| v_to_s(s));
24        let p = t.get("path").map(|s| v_to_s(s));
25
26        // If a `package` key is present, set it as the name, and set
27        // the `n` as the alias.  When we look for keys later, the
28        // alias has precedence over the actual name, but this way
29        // `name` is always the actual crate name which is important
30        // for dependency resolution.
31        let (alias, name) = match t
32            .get("package")
33            .map(|s| v_to_s(s).replace("\"", "").trim().to_string())
34        {
35            Some(alias) => (Some(n), alias),
36            None => (None, n),
37        };
38
39        match (v, p) {
40            (version @ Some(_), path @ Some(_)) => Some(Self {
41                name,
42                alias,
43                version,
44                path,
45            }),
46            (version @ Some(_), None) => Some(Self {
47                name,
48                alias,
49                version,
50                path: None,
51            }),
52            (None, path @ Some(_)) => Some(Self {
53                name,
54                alias,
55                version: None,
56                path,
57            }),
58            (None, None) => None,
59        }
60    }
61
62    /// Check if the dependency has a provided version
63    pub fn has_version(&self) -> bool {
64        self.version.is_some()
65    }
66
67    /// Check if the dependency has a provided path
68    pub fn has_path(&self) -> bool {
69        self.path.is_some()
70    }
71
72    pub fn alias(&self) -> Option<String> {
73        self.alias.clone()
74    }
75}