use super::*;
pub(super) const MAX_KEPT_BYTES: u64 = 512 * 1024;
pub(super) const MAX_SNAPSHOT_BYTES: u64 = 32 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChangeKind {
Created,
Modified,
Deleted,
}
#[derive(Debug, PartialEq)]
pub struct Change {
pub file: String,
pub kind: ChangeKind,
}
pub(super) struct Before {
len: u64,
modified: Option<SystemTime>,
content: Option<Vec<u8>>,
}
pub struct Snapshot {
root: PathBuf,
files: HashMap<String, Before>,
}
impl Snapshot {
pub fn take(root: &Path, files: &[String]) -> Self {
let mut kept = 0;
let mut before = HashMap::new();
for file in files {
let path = root.join(file);
let Ok(data) = std::fs::metadata(&path) else {
continue;
};
let fits = data.len() <= MAX_KEPT_BYTES && kept + data.len() <= MAX_SNAPSHOT_BYTES;
let content = fits.then(|| std::fs::read(&path).ok()).flatten();
kept += content.as_ref().map_or(0, |content| content.len() as u64);
before.insert(
file.clone(),
Before {
len: data.len(),
modified: data.modified().ok(),
content,
},
);
}
Self {
root: root.to_path_buf(),
files: before,
}
}
pub fn changes(&self, files: &[String]) -> Vec<Change> {
let mut changes = Vec::new();
for file in files {
let path = self.root.join(file);
let kind = match self.files.get(file) {
None if !path.exists() => continue,
None => ChangeKind::Created,
Some(before) => {
let same = match (&before.content, std::fs::metadata(&path)) {
(Some(content), Ok(_)) => std::fs::read(&path).is_ok_and(|now| now == *content),
(None, Ok(data)) => {
data.len() == before.len && data.modified().ok() == before.modified
}
(_, Err(_)) => true,
};
if same {
continue;
}
ChangeKind::Modified
}
};
changes.push(Change { file: file.clone(), kind });
}
for file in self.files.keys() {
if !self.root.join(file).exists() {
changes.push(Change { file: file.clone(), kind: ChangeKind::Deleted });
}
}
changes.sort_by(|a, b| a.file.cmp(&b.file));
changes
}
pub fn restore(&self, changes: &[Change]) -> (usize, usize) {
let (mut restored, mut failed) = (0, 0);
for change in changes {
let path = self.root.join(&change.file);
let done = match (change.kind, self.files.get(&change.file)) {
(ChangeKind::Created, _) => std::fs::remove_file(&path).is_ok(),
(_, Some(Before { content: Some(content), .. })) => {
let folder = path.parent().unwrap_or(&self.root);
std::fs::create_dir_all(folder).is_ok() && std::fs::write(&path, content).is_ok()
}
_ => false,
};
if done {
restored += 1;
} else {
failed += 1;
}
}
(restored, failed)
}
}
pub fn describe(changes: &[Change]) -> String {
let names: Vec<String> = changes
.iter()
.map(|change| match change.kind {
ChangeKind::Created => format!("new {}", change.file),
ChangeKind::Modified => change.file.clone(),
ChangeKind::Deleted => format!("deleted {}", change.file),
})
.collect();
let files = if changes.len() == 1 { "file" } else { "files" };
format!("Changed {} {files}: {}", changes.len(), names.join(", "))
}