use anyhow::{Context, Result};
use std::fs;
use std::path::Path;
pub fn ensure_dir<P: AsRef<Path>>(path: P) -> Result<()> {
fs::create_dir_all(&path)
.with_context(|| format!("Failed to create directory: {}", path.as_ref().display()))
}
pub fn clean_dir<P: AsRef<Path>>(path: P) -> Result<()> {
if path.as_ref().exists() {
fs::remove_dir_all(&path)
.with_context(|| format!("Failed to remove directory: {}", path.as_ref().display()))?;
}
ensure_dir(path)
}
pub fn write_if_not_exists<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, content: C) -> Result<bool> {
if path.as_ref().exists() {
return Ok(false);
}
write_force(path, content)?;
Ok(true)
}
pub fn write_force<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, content: C) -> Result<()> {
if let Some(parent) = path.as_ref().parent() {
ensure_dir(parent)?;
}
fs::write(&path, content)
.with_context(|| format!("Failed to write file: {}", path.as_ref().display()))
}
pub fn copy_force<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> {
if let Some(parent) = to.as_ref().parent() {
ensure_dir(parent)?;
}
fs::copy(&from, &to).with_context(|| {
format!(
"Failed to copy {} to {}",
from.as_ref().display(),
to.as_ref().display()
)
})
}
pub fn exists<P: AsRef<Path>>(path: P) -> bool {
path.as_ref().exists()
}
pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
fs::read_to_string(&path)
.with_context(|| format!("Failed to read file: {}", path.as_ref().display()))
}