2019-11-03 15:39:27 +00:00
|
|
|
use serde_json::json;
|
|
|
|
pub use serde_json::Value;
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::io::Result;
|
2020-05-11 21:48:36 +00:00
|
|
|
use url::Url;
|
2019-11-03 15:39:27 +00:00
|
|
|
|
|
|
|
pub struct Lockfile {
|
|
|
|
need_read: bool,
|
|
|
|
map: HashMap<String, String>,
|
|
|
|
pub filename: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Lockfile {
|
|
|
|
pub fn new(filename: String) -> Lockfile {
|
|
|
|
Lockfile {
|
|
|
|
map: HashMap::new(),
|
|
|
|
filename,
|
|
|
|
need_read: true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn write(&self) -> Result<()> {
|
|
|
|
let j = json!(self.map);
|
|
|
|
let s = serde_json::to_string_pretty(&j).unwrap();
|
|
|
|
let mut f = std::fs::OpenOptions::new()
|
|
|
|
.write(true)
|
|
|
|
.create(true)
|
|
|
|
.truncate(true)
|
|
|
|
.open(&self.filename)?;
|
|
|
|
use std::io::Write;
|
|
|
|
f.write_all(s.as_bytes())?;
|
|
|
|
debug!("lockfile write {}", self.filename);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn read(&mut self) -> Result<()> {
|
|
|
|
debug!("lockfile read {}", self.filename);
|
|
|
|
let s = std::fs::read_to_string(&self.filename)?;
|
|
|
|
self.map = serde_json::from_str(&s)?;
|
|
|
|
self.need_read = false;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Lazily reads the filename, checks the given module is included.
|
|
|
|
/// Returns Ok(true) if check passed
|
2020-05-11 21:48:36 +00:00
|
|
|
pub fn check(&mut self, url: &Url, code: Vec<u8>) -> Result<bool> {
|
|
|
|
let url_str = url.to_string();
|
|
|
|
if url_str.starts_with("file:") {
|
2019-11-03 15:39:27 +00:00
|
|
|
return Ok(true);
|
|
|
|
}
|
|
|
|
if self.need_read {
|
|
|
|
self.read()?;
|
|
|
|
}
|
|
|
|
assert!(!self.need_read);
|
2020-05-11 21:48:36 +00:00
|
|
|
Ok(if let Some(lockfile_checksum) = self.map.get(&url_str) {
|
2020-06-29 12:17:37 +00:00
|
|
|
let compiled_checksum = crate::checksum::gen(&[&code]);
|
2019-11-03 15:39:27 +00:00
|
|
|
lockfile_checksum == &compiled_checksum
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if module was not already inserted.
|
2020-05-11 21:48:36 +00:00
|
|
|
pub fn insert(&mut self, url: &Url, code: Vec<u8>) -> bool {
|
|
|
|
let url_str = url.to_string();
|
|
|
|
if url_str.starts_with("file:") {
|
2019-11-03 15:39:27 +00:00
|
|
|
return false;
|
|
|
|
}
|
2020-06-29 12:17:37 +00:00
|
|
|
let checksum = crate::checksum::gen(&[&code]);
|
2020-05-11 21:48:36 +00:00
|
|
|
self.map.insert(url_str, checksum).is_none()
|
2019-11-03 15:39:27 +00:00
|
|
|
}
|
|
|
|
}
|