simple_fs/safer/
safer_remove_impl.rs1use crate::SPath;
2use crate::error::{Cause, PathAndCause};
3use crate::safer::{SaferRemoveOptions, support};
4use crate::{Error, Result};
5use std::fs;
6
7pub fn safer_remove_dir<'a>(dir_path: &SPath, options: impl Into<SaferRemoveOptions<'a>>) -> Result<bool> {
17 let options = options.into();
18
19 if !dir_path.exists() {
21 return Ok(false);
22 }
23
24 let causes = support::check_path_safety_causes(
25 dir_path,
26 options.restrict_to_current_dir,
27 options.must_contain_any,
28 options.must_contain_all,
29 )?;
30
31 if !causes.is_empty() {
32 return Err(Error::DirNotSafeToRemove(PathAndCause {
33 path: dir_path.to_string(),
34 cause: Cause::Custom(format!("Safety check failed: {}", causes.join("; "))),
35 }));
36 }
37
38 fs::remove_dir_all(dir_path.as_std_path()).map_err(|e| {
40 Error::DirNotSafeToRemove(PathAndCause {
41 path: dir_path.to_string(),
42 cause: Cause::Io(Box::new(e)),
43 })
44 })?;
45
46 Ok(true)
47}
48
49pub fn safer_remove_file<'a>(file_path: &SPath, options: impl Into<SaferRemoveOptions<'a>>) -> Result<bool> {
59 let options = options.into();
60
61 if !file_path.exists() {
63 return Ok(false);
64 }
65
66 let causes = support::check_path_safety_causes(
67 file_path,
68 options.restrict_to_current_dir,
69 options.must_contain_any,
70 options.must_contain_all,
71 )?;
72
73 if !causes.is_empty() {
74 return Err(Error::FileNotSafeToRemove(PathAndCause {
75 path: file_path.to_string(),
76 cause: Cause::Custom(format!("Safety check failed: {}", causes.join("; "))),
77 }));
78 }
79
80 fs::remove_file(file_path.as_std_path()).map_err(|e| {
82 Error::FileNotSafeToRemove(PathAndCause {
83 path: file_path.to_string(),
84 cause: Cause::Io(Box::new(e)),
85 })
86 })?;
87
88 Ok(true)
89}
90
91