cargo_lock/
dependency.rs

1//! Package dependencies
2
3#[cfg(feature = "dependency-tree")]
4pub mod graph;
5#[cfg(feature = "dependency-tree")]
6pub mod tree;
7
8#[cfg(feature = "dependency-tree")]
9pub use self::tree::Tree;
10
11use crate::package::{Name, Package, SourceId};
12use semver::Version;
13use serde::{Deserialize, Serialize};
14use std::fmt;
15
16/// Package dependencies
17#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)]
18pub struct Dependency {
19    /// Name of the dependency
20    pub name: Name,
21
22    /// Version of the dependency
23    pub version: Version,
24
25    /// Source identifier for the dependency
26    pub source: Option<SourceId>,
27}
28
29impl Dependency {
30    /// Does the given [`Package`] exactly match this `Dependency`?
31    pub fn matches(&self, package: &Package) -> bool {
32        self.name == package.name && self.version == package.version
33    }
34}
35
36impl fmt::Display for Dependency {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(f, "{} {}", &self.name, &self.version)?;
39
40        if let Some(source) = &self.source {
41            write!(f, " ({source})")?;
42        }
43
44        Ok(())
45    }
46}
47
48impl From<&Package> for Dependency {
49    /// Get the [`Dependency`] requirement for this `[[package]]`
50    fn from(pkg: &Package) -> Dependency {
51        Self {
52            name: pkg.name.clone(),
53            version: pkg.version.clone(),
54            source: pkg
55                .source
56                .clone()
57                .map(|x| x.normalize_git_source_for_dependency()),
58        }
59    }
60}