cargo_lock/
lockfile.rs

1//! Parser for `Cargo.lock` files
2
3pub(crate) mod encoding;
4pub mod version;
5
6pub use self::version::ResolveVersion;
7
8use self::encoding::EncodableLockfile;
9use crate::{
10    error::{Error, Result},
11    metadata::Metadata,
12    package::Package,
13    patch::Patch,
14};
15use std::{fs, path::Path, str::FromStr, string::ToString};
16
17#[cfg(feature = "dependency-tree")]
18use crate::dependency::Tree;
19
20/// Parsed Cargo.lock file containing dependencies
21#[derive(Clone, Debug, Eq, PartialEq)]
22pub struct Lockfile {
23    /// Version of the Lockfile
24    pub version: ResolveVersion,
25
26    /// Dependencies enumerated in the lockfile
27    pub packages: Vec<Package>,
28
29    /// Legacy "root" dependency for backwards compatibility
30    pub root: Option<Package>,
31
32    /// Package metadata
33    pub metadata: Metadata,
34
35    /// Patches
36    pub patch: Patch,
37}
38
39impl Lockfile {
40    /// Load lock data from a `Cargo.lock` file
41    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
42        fs::read_to_string(path.as_ref())?.parse()
43    }
44
45    /// Get the dependency tree for this `Lockfile`. Returns an error if the
46    /// contents of this lockfile aren't well structured.
47    ///
48    /// The `dependency-tree` Cargo feature must be enabled to use this.
49    #[cfg(feature = "dependency-tree")]
50    pub fn dependency_tree(&self) -> Result<Tree> {
51        Tree::new(self)
52    }
53}
54
55impl FromStr for Lockfile {
56    type Err = Error;
57
58    fn from_str(toml_string: &str) -> Result<Self> {
59        toml::from_str(toml_string).map_err(|e| Error::Parse(e.to_string()))
60    }
61}
62
63#[allow(clippy::to_string_trait_impl)]
64impl ToString for Lockfile {
65    fn to_string(&self) -> String {
66        EncodableLockfile::from(self).to_string()
67    }
68}