use crate::SPath;
use crate::error::{Cause, PathAndCause};
use crate::safer::{SaferRemoveOptions, support};
use crate::{Error, Result};
use std::fs;
pub fn safer_remove_dir<'a>(dir_path: &SPath, options: impl Into<SaferRemoveOptions<'a>>) -> Result<bool> {
let options = options.into();
if !dir_path.exists() {
return Ok(false);
}
let causes = support::check_path_safety_causes(
dir_path,
options.restrict_to_current_dir,
options.must_contain_any,
options.must_contain_all,
)?;
if !causes.is_empty() {
return Err(Error::DirNotSafeToRemove(PathAndCause {
path: dir_path.to_string(),
cause: Cause::Custom(format!("Safety check failed: {}", causes.join("; "))),
}));
}
fs::remove_dir_all(dir_path.as_std_path()).map_err(|e| {
Error::DirNotSafeToRemove(PathAndCause {
path: dir_path.to_string(),
cause: Cause::Io(Box::new(e)),
})
})?;
Ok(true)
}
pub fn safer_remove_file<'a>(file_path: &SPath, options: impl Into<SaferRemoveOptions<'a>>) -> Result<bool> {
let options = options.into();
if !file_path.exists() {
return Ok(false);
}
let causes = support::check_path_safety_causes(
file_path,
options.restrict_to_current_dir,
options.must_contain_any,
options.must_contain_all,
)?;
if !causes.is_empty() {
return Err(Error::FileNotSafeToRemove(PathAndCause {
path: file_path.to_string(),
cause: Cause::Custom(format!("Safety check failed: {}", causes.join("; "))),
}));
}
fs::remove_file(file_path.as_std_path()).map_err(|e| {
Error::FileNotSafeToRemove(PathAndCause {
path: file_path.to_string(),
cause: Cause::Io(Box::new(e)),
})
})?;
Ok(true)
}