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