1use std::fs;
5use std::path::PathBuf;
6
7use corpora_core::subscriber::ek;
8use corpora_core::{Context, Diagnostic, Event, Interest, Subscriber};
9
10pub struct Writer {
11 out_dir: PathBuf,
12}
13
14impl Writer {
15 pub fn new(out_dir: impl Into<PathBuf>) -> Self {
16 Writer {
17 out_dir: out_dir.into(),
18 }
19 }
20}
21
22impl Subscriber for Writer {
23 fn name(&self) -> &'static str {
24 "writer"
25 }
26
27 fn interest(&self) -> Interest {
28 Interest::only(ek::REPORT)
29 }
30
31 fn handle(&mut self, ev: &Event, cx: &mut Context<'_>) {
32 let Event::Report(a) = ev else { return };
33 let dest = self.out_dir.join(&a.path.0);
34 if let Some(parent) = dest.parent() {
35 let _ = fs::create_dir_all(parent);
36 }
37 if let Err(e) = fs::write(&dest, &a.bytes) {
38 cx.error(Diagnostic::error("WRITE", &a.path, e.to_string()));
39 }
40 }
41}