1use std::fs;
4use std::path::Path;
5
6use uuid::Uuid;
7
8use crate::error::Result;
9
10pub fn read_text(path: &Path) -> Result<String> {
11 Ok(fs::read_to_string(path)?.trim_end().to_string())
12}
13
14pub fn write_text(path: &Path, content: &str) -> Result<()> {
15 if let Some(p) = path.parent() {
16 fs::create_dir_all(p)?;
17 }
18 fs::write(path, content)?;
19 Ok(())
20}
21
22pub fn write_text_atomic(path: &Path, content: &str) -> Result<()> {
24 if let Some(p) = path.parent() {
25 fs::create_dir_all(p)?;
26 }
27 let dir = path
28 .parent()
29 .ok_or_else(|| crate::Error::msg("path has no parent"))?;
30 let tmp = dir.join(format!(
31 ".{}.tmp.{}",
32 path.file_name()
33 .and_then(|s| s.to_str())
34 .unwrap_or("file"),
35 Uuid::new_v4()
36 ));
37 fs::write(&tmp, content)?;
38 fs::rename(&tmp, path)?;
39 Ok(())
40}