use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
pub const MAX_TEXT_BYTES: usize = 256 * 1024;
pub const MAX_FILES: usize = 32;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CellWrite {
pub path: PathBuf,
pub created: bool,
pub texts: Option<(String, String)>,
}
#[derive(Default)]
pub struct CellWrites {
enabled: AtomicBool,
lanes: Mutex<HashMap<String, Vec<CellWrite>>>,
}
fn small_text(path: &Path) -> Result<Option<String>, ()> {
match std::fs::metadata(path) {
Err(_) => Ok(None),
Ok(meta) if !meta.is_file() || meta.len() as usize > MAX_TEXT_BYTES => Err(()),
Ok(_) => std::fs::read(path)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.map(Some)
.ok_or(()),
}
}
impl CellWrites {
fn lanes(&self) -> std::sync::MutexGuard<'_, HashMap<String, Vec<CellWrite>>> {
self.lanes.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn set_enabled(&self, enabled: bool) {
self.enabled.store(enabled, Ordering::SeqCst);
}
pub fn begin(&self, lane: &str) {
self.lanes().remove(lane);
}
pub fn record(&self, lane: &str, path: &Path, content: &str) {
if !self.enabled.load(Ordering::SeqCst) {
return;
}
let mut lanes = self.lanes();
let writes = lanes.entry(lane.to_string()).or_default();
if let Some(write) = writes.iter_mut().find(|w| w.path == path) {
write.texts = match write.texts.take() {
Some((before, _)) if content.len() <= MAX_TEXT_BYTES => Some((before, content.to_string())),
_ => None,
};
return;
}
if writes.len() >= MAX_FILES {
return;
}
let before = small_text(path);
let created = matches!(before, Ok(None));
let texts = match before {
Ok(before) if content.len() <= MAX_TEXT_BYTES => Some((before.unwrap_or_default(), content.to_string())),
_ => None,
};
writes.push(CellWrite {
path: path.to_path_buf(),
created,
texts,
});
}
pub fn take(&self, lane: &str) -> Vec<CellWrite> {
let writes = self.lanes().remove(lane).unwrap_or_default();
writes
.into_iter()
.filter(|write| match &write.texts {
Some((before, after)) => {
(write.created || before != after)
&& std::fs::read(&write.path).is_ok_and(|now| now == after.as_bytes())
}
None => write.path.exists(),
})
.collect()
}
}