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