use std::fs;
use std::path::PathBuf;
use corpora_core::subscriber::ek;
use corpora_core::{Context, Diagnostic, Event, Interest, Subscriber};
pub struct Writer {
out_dir: PathBuf,
}
impl Writer {
pub fn new(out_dir: impl Into<PathBuf>) -> Self {
Writer {
out_dir: out_dir.into(),
}
}
}
impl Subscriber for Writer {
fn name(&self) -> &'static str {
"writer"
}
fn interest(&self) -> Interest {
Interest::only(ek::REPORT)
}
fn handle(&mut self, ev: &Event, cx: &mut Context<'_>) {
let Event::Report(a) = ev else { return };
let dest = self.out_dir.join(&a.path.0);
if let Some(parent) = dest.parent() {
let _ = fs::create_dir_all(parent);
}
if let Err(e) = fs::write(&dest, &a.bytes) {
cx.error(Diagnostic::error("WRITE", &a.path, e.to_string()));
}
}
}