1use anyhow::{anyhow, Context, Result};
2
3mod gz;
4mod json;
5mod json_each;
6mod protos;
7
8pub use gz::GzFormatter;
9pub use json::JsonFormatter;
10pub use json_each::JsonEachRowFormatter;
11pub use protos::{ProtoFormatter, ProtosFormatter};
12
13pub trait Formatter {
14 fn write_to(&self, writer: &mut dyn std::io::Write) -> Result<()>;
15
16 fn write_to_file(&self, path: &std::path::Path) -> Result<()> {
17 let directory = path
18 .parent()
19 .ok_or_else(|| anyhow!("Failed to get parent directory of file: {:?}", path))?;
20
21 std::fs::create_dir_all(directory)
22 .with_context(|| format!("Failed to create directory: {:?}", directory))?;
23
24 let mut file = std::fs::File::create(path)?;
25 self.write_to(&mut file)
26 }
27
28 fn read(&self) -> Result<Vec<u8>> {
29 let mut buffer = Vec::new();
30 self.write_to(&mut buffer)?;
31 Ok(buffer)
32 }
33}