Skip to main content

rustybook_utilities/
lib.rs

1use std::path::Path;
2
3use rustybook_errors::WriteError;
4use tokio::fs;
5use tokio::io::AsyncWriteExt;
6use uuid::Uuid;
7
8/// Safely writes text into file
9pub async fn write_text(text: &str, path: impl AsRef<Path>) -> Result<(), WriteError> {
10    let path = path.as_ref();
11
12    if let Some(parent) = path.parent() {
13        fs::create_dir_all(parent).await?;
14    }
15
16    let tmp_path = path.with_extension(format!("tmp-{}", Uuid::new_v4()));
17
18    let mut file = fs::File::create(&tmp_path).await?;
19    file.write_all(text.as_bytes()).await?;
20    file.flush().await?;
21    file.sync_all().await?;
22
23    fs::rename(&tmp_path, path).await?;
24
25    Ok(())
26}