use std::io::Error as IoError;
use std::path::Path;
use tracing::{debug, error, trace};
pub fn prepare_file_path(path: &Path) -> Result<(), IoError> {
if path.exists() {
match std::fs::remove_file(path) {
Ok(_) => {}
Err(e) => {
error!("Failed to remove existing file: {}", path.display());
return Err(IoError::new(
e.kind(),
format!("Failed to remove existing file: {}", path.display()),
));
}
};
trace!("Removed existing file: {}", path.display());
}
if let Some(parent) = path.parent()
&& !parent.exists()
{
match std::fs::create_dir_all(parent) {
Ok(_) => {}
Err(e) => {
error!("Failed to create parent directories: {}", path.display());
return Err(IoError::new(
e.kind(),
format!("Failed to create parent directories: {}", path.display()),
));
}
};
debug!("Created directory: {}", path.display());
}
Ok(())
}