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 mut file = File::open(path.as_ref())?;
let mut toml = String::new();
file.read_to_string(&mut toml)?;
Self::from_toml(&toml)
}
pub fn from_toml(toml_string: &str) -> Result<Self, Error> {
Ok(toml::from_str(toml_string)?)
}
}
#[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 = "No such file or directory (os error 2)")]
fn load_cargo_lockfile_nonexistant() {
Lockfile::load("nosuchfile.notexist").unwrap();
}
#[test]
#[should_panic(expected = "unexpected character found: `<` at line 1")]
fn load_cargo_lockfile_invalid() {
Lockfile::load("README.md").unwrap();
}
}