gesha_core/io/
writer.rs

1use crate::Result;
2use crate::io::Error::{CannotCreateFile, CannotRender};
3use std::fmt::{Debug, Display};
4use std::fs::File;
5use std::io::Write;
6use std::path::PathBuf;
7use tracing::instrument;
8
9#[derive(Debug)]
10pub struct Writer {
11    pub(crate) path: PathBuf,
12}
13
14impl Writer {
15    /// path: The location where the file will be created.
16    pub fn new(path: impl Into<PathBuf>) -> Self {
17        Self { path: path.into() }
18    }
19
20    pub fn touch(&self) -> Result<File> {
21        let file = File::create(&self.path).map_err(|cause| CannotCreateFile {
22            path: self.path.clone(),
23            detail: format!("{:?}", cause),
24        })?;
25        Ok(file)
26    }
27
28    #[instrument(skip_all)]
29    pub fn write_code(self, code: impl Display) -> Result<()> {
30        let mut file = self.touch()?;
31        write!(file, "{}", code).map_err(|cause| CannotRender {
32            path: self.path.clone(),
33            detail: format!("{:?}", cause),
34        })?;
35        Ok(())
36    }
37}