use crate::{ChangeKind, FileChange, Source, content_hash, splice::SpliceLog};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
#[derive(Debug, Clone, Default)]
pub struct Slot {
pub before: Option<String>,
pub current: Option<String>,
pub log: SpliceLog,
}
pub struct Overlay<'a> {
source: &'a dyn Source,
slots: BTreeMap<PathBuf, Slot>,
}
impl<'a> Overlay<'a> {
pub fn new(source: &'a dyn Source) -> Self {
Self {
source,
slots: BTreeMap::new(),
}
}
pub fn slot(&mut self, path: &Path) -> Result<&mut Slot, String> {
if !self.slots.contains_key(path) {
let text = self.source.read(path)?;
self.slots.insert(
path.to_path_buf(),
Slot {
before: text.clone(),
current: text,
log: SpliceLog::default(),
},
);
}
self.slots
.get_mut(path)
.ok_or_else(|| format!("{}: slot vanished", path.display()))
}
#[must_use]
pub fn into_changes(self) -> Vec<FileChange> {
self.slots
.into_iter()
.filter(|(_, slot)| slot.before != slot.current)
.map(|(path, slot)| change(path, slot))
.collect()
}
}
fn change(path: PathBuf, slot: Slot) -> FileChange {
let kind = match (&slot.before, &slot.current) {
(None, _) => ChangeKind::Create,
(Some(_), None) => ChangeKind::Delete,
(Some(_), Some(_)) => ChangeKind::Modify,
};
FileChange {
path,
kind,
before_hash: slot.before.as_deref().map(content_hash),
after_hash: slot.current.as_deref().map(content_hash),
before: slot.before,
after: slot.current,
}
}