gesha_core/io/
writer.rs

1use crate::Error::{CannotCreateFile, CannotRender};
2use crate::Result;
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        File::create(&self.path).map_err(|cause| CannotCreateFile {
22            path: self.path.clone(),
23            detail: format!("{:?}", cause),
24        })
25    }
26
27    #[instrument(skip_all)]
28    pub fn write_code(self, code: impl Display) -> Result<()> {
29        let mut file = self.touch()?;
30        write!(file, "{}", code).map_err(|cause| CannotRender {
31            path: self.path.clone(),
32            detail: format!("{:?}", cause),
33        })?;
34        Ok(())
35    }
36}