2023-04-12 15:14:39 +03:00
|
|
|
use std::io::Write;
|
|
|
|
|
2023-04-14 13:25:07 +03:00
|
|
|
use anyhow::{Context, Result};
|
|
|
|
|
2023-04-12 15:14:39 +03:00
|
|
|
pub trait Writer {
|
|
|
|
fn write_string(&self, path: &str, contents: &str) -> Result<()>;
|
|
|
|
fn append_string(&self, path: &str, contents: &str) -> Result<()>;
|
|
|
|
}
|
|
|
|
|
2023-04-13 14:37:46 +03:00
|
|
|
pub struct DirWriter<'writer> {
|
|
|
|
root: &'writer std::path::Path,
|
2023-04-12 15:14:39 +03:00
|
|
|
}
|
|
|
|
|
2023-04-13 14:37:46 +03:00
|
|
|
impl<'writer> DirWriter<'writer> {
|
|
|
|
pub fn open(root: &'writer std::path::Path) -> Self {
|
|
|
|
Self { root }
|
|
|
|
}
|
2023-04-12 15:14:39 +03:00
|
|
|
}
|
|
|
|
|
2023-04-13 14:37:46 +03:00
|
|
|
impl Writer for DirWriter<'_> {
|
2023-04-12 15:14:39 +03:00
|
|
|
fn write_string(&self, path: &str, contents: &str) -> Result<()> {
|
2023-04-13 14:37:46 +03:00
|
|
|
let file_path = self.root.join(path);
|
2023-04-12 15:14:39 +03:00
|
|
|
let dir_path = file_path.parent().unwrap();
|
|
|
|
std::fs::create_dir_all(dir_path)?;
|
|
|
|
std::fs::write(path, contents)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn append_string(&self, path: &str, contents: &str) -> Result<()> {
|
2023-04-13 14:37:46 +03:00
|
|
|
let file_path = self.root.join(path);
|
2023-04-12 15:14:39 +03:00
|
|
|
let mut file = std::fs::OpenOptions::new()
|
|
|
|
.create(true)
|
|
|
|
.append(true)
|
|
|
|
.open(file_path)
|
|
|
|
.with_context(|| format!("failed to open file: {}", path))?;
|
|
|
|
file.write_all(contents.as_bytes())?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|