1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::{error::Error, package::Package};
use std::{fs::File, io::Read, path::Path};
use toml;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct Lockfile {
#[serde(rename = "package")]
pub packages: Vec<Package>,
}
impl Lockfile {
pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let lockfile_str = path.as_ref().to_str().unwrap();
let mut file = File::open(path.as_ref())
.expect(format!("could not load lockfile: {:?}", lockfile_str).as_str());
let mut toml = String::new();
file.read_to_string(&mut toml)?;
Self::from_toml(&lockfile_str, &toml)
}
pub fn from_toml(lockfile: &str, toml_string: &str) -> Result<Self, Error> {
Ok(toml::from_str(toml_string).expect(format!("could not parse lockfile: {:?}", lockfile).as_str()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn load_cargo_lockfile() {
let lockfile = Lockfile::load("Cargo.lock").unwrap();
assert!(lockfile.packages.len() > 0);
}
#[test]
#[should_panic(expected = "could not load lockfile: \"nosuchfile.notexist\"")]
fn load_cargo_lockfile_nonexistant() {
Lockfile::load("nosuchfile.notexist").unwrap();
}
#[test]
#[should_panic(expected = "could not parse lockfile: \"README.md\"")]
fn load_cargo_lockfile_invalid() {
Lockfile::load("README.md").unwrap();
}
}