use std::path::Path;
pub fn ensure_dir_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
let path = path.as_ref();
std::fs::create_dir_all(path).map_err(|err| {
std::io::Error::new(
err.kind(),
format!("failed to create directory '{}': {err}", path.display()),
)
})
}
pub fn ensure_parent_dir_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
if let Some(parent) = path.as_ref().parent()
&& !parent.as_os_str().is_empty()
{
ensure_dir_exists(parent)?;
}
Ok(())
}
pub fn remove_file_if_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
let path = path.as_ref();
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(std::io::Error::new(
err.kind(),
format!("failed to remove file '{}': {err}", path.display()),
)),
}
}
pub fn remove_dir_all_if_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
let path = path.as_ref();
match std::fs::remove_dir_all(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(std::io::Error::new(
err.kind(),
format!("failed to remove directory '{}': {err}", path.display()),
)),
}
}
#[cfg(test)]
mod tests;