novel_cli/utils/
writer.rs

1use std::io::Cursor;
2use std::path::Path;
3
4use color_eyre::eyre::Result;
5use tokio::fs::{self, File};
6use tokio::io::{AsyncWriteExt, BufWriter};
7
8#[must_use]
9pub struct Writer {
10    writer: BufWriter<File>,
11}
12
13impl Writer {
14    pub async fn new<T>(path: T) -> Result<Self>
15    where
16        T: AsRef<Path>,
17    {
18        let parent = path.as_ref().parent().unwrap();
19        if !fs::try_exists(parent).await? {
20            fs::create_dir_all(parent).await?;
21        }
22
23        Ok(Self {
24            writer: BufWriter::new(File::create(&path).await?),
25        })
26    }
27
28    #[inline]
29    pub async fn write<T>(&mut self, text: T) -> Result<()>
30    where
31        T: AsRef<str>,
32    {
33        let mut buffer = Cursor::new(text.as_ref());
34        self.writer.write_all_buf(&mut buffer).await?;
35        Ok(())
36    }
37
38    #[inline]
39    pub async fn ln(&mut self) -> Result<()> {
40        self.writer.write_all(b"\n").await?;
41        Ok(())
42    }
43
44    #[inline]
45    pub async fn writeln<T>(&mut self, text: T) -> Result<()>
46    where
47        T: AsRef<str>,
48    {
49        self.write(text).await?;
50        self.ln().await?;
51        Ok(())
52    }
53
54    #[inline]
55    pub async fn flush(&mut self) -> Result<()> {
56        self.writer.flush().await?;
57        Ok(())
58    }
59}