pub mod tree;
pub mod watcher;
use std::fs;
use std::path::Path;
use anyhow::{Context, Result};
pub fn read_file(path: &Path) -> Result<String> {
let bytes = fs::read(path).with_context(|| format!("cannot read {}", path.display()))?;
String::from_utf8(bytes).with_context(|| format!("{} is not valid UTF-8", path.display()))
}
pub fn write_file(path: &Path, contents: &str) -> Result<()> {
let temp = temp_path(path);
fs::write(&temp, contents).with_context(|| format!("cannot write {}", temp.display()))?;
fs::rename(&temp, path)
.with_context(|| format!("cannot replace {}", path.display()))
.inspect_err(|_| {
let _ = fs::remove_file(&temp);
})
}
fn temp_path(path: &Path) -> std::path::PathBuf {
let mut name = std::ffi::OsString::from(".");
name.push(path.file_name().unwrap_or_else(|| "termi".as_ref()));
name.push(".termi-tmp");
path.with_file_name(name)
}