1use std::fs::Metadata;
6use std::io;
7#[cfg(unix)]
8use std::os::unix::fs::MetadataExt;
9use std::path::Path;
10
11use tracing::debug;
12use uv_fs::PhysicalSpaceError;
13
14use crate::CleanReporter;
15
16#[derive(Debug, Clone, Copy, Default)]
18pub enum RemovalAccounting {
19 #[default]
21 Coarse,
22 Fine,
24}
25
26#[derive(Default)]
28pub(crate) struct Remover {
29 reporter: Option<Box<dyn CleanReporter>>,
30 removal_accounting: RemovalAccounting,
31}
32
33impl Remover {
34 pub(crate) fn new(reporter: Box<dyn CleanReporter>) -> Self {
36 Self {
37 reporter: Some(reporter),
38 ..Self::default()
39 }
40 }
41
42 pub(crate) fn with_removal_accounting(mut self, removal_accounting: RemovalAccounting) -> Self {
44 self.removal_accounting = removal_accounting;
45 self
46 }
47
48 pub(crate) fn rm_rf(
51 &self,
52 path: impl AsRef<Path>,
53 skip_locked_file: bool,
54 ) -> io::Result<Removal> {
55 let mut removal = Removal::new(self.removal_accounting);
56 removal.rm_rf(path.as_ref(), self.reporter.as_deref(), skip_locked_file)?;
57 Ok(removal)
58 }
59}
60
61#[cfg(unix)]
63fn file_size(metadata: &Metadata) -> u64 {
64 if metadata.nlink() == 1 {
65 metadata.blocks().saturating_mul(512)
66 } else {
67 0
68 }
69}
70
71#[cfg(not(unix))]
73fn file_size(metadata: &Metadata) -> u64 {
74 metadata.len()
75}
76
77#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
79pub enum PhysicalBytes {
80 #[default]
82 Unavailable,
83 Measured(u64),
85 LowerBound(u64),
87}
88
89impl PhysicalBytes {
90 fn mark_incomplete(&mut self) {
91 if let Self::Measured(bytes) = *self {
92 *self = Self::LowerBound(bytes);
93 }
94 }
95
96 fn combine(self, other: Self) -> Self {
97 match (self, other) {
98 (Self::Unavailable, _) | (_, Self::Unavailable) => Self::Unavailable,
99 (Self::Measured(left), Self::Measured(right)) => {
100 Self::Measured(left.saturating_add(right))
101 }
102 (Self::LowerBound(left), Self::Measured(right) | Self::LowerBound(right))
103 | (Self::Measured(left), Self::LowerBound(right)) => {
104 Self::LowerBound(left.saturating_add(right))
105 }
106 }
107 }
108}
109
110#[derive(Debug, Default)]
112pub struct Removal {
113 pub num_files: u64,
115 pub num_dirs: u64,
117 pub coarse_bytes: u64,
119 pub physical_bytes: PhysicalBytes,
121}
122
123impl Removal {
124 pub(crate) fn new(removal_accounting: RemovalAccounting) -> Self {
126 Self {
127 physical_bytes: match removal_accounting {
128 RemovalAccounting::Coarse => PhysicalBytes::Unavailable,
129 RemovalAccounting::Fine => PhysicalBytes::Measured(0),
130 },
131 ..Self::default()
132 }
133 }
134
135 fn add_file(&mut self, path: &Path, metadata: &Metadata) {
137 self.coarse_bytes += file_size(metadata);
138
139 if let PhysicalBytes::Measured(total) | PhysicalBytes::LowerBound(total) =
140 &mut self.physical_bytes
141 {
142 match uv_fs::physical_space(path, metadata) {
143 Ok(bytes) => {
144 *total = total.saturating_add(bytes);
145 }
146 Err(PhysicalSpaceError::UnsupportedFilesystem) => {
147 debug!(
148 "Fine-grained space accounting is unsupported for `{}`; falling back to coarse accounting",
149 path.display()
150 );
151 self.physical_bytes = PhysicalBytes::Unavailable;
152 }
153 Err(PhysicalSpaceError::UnmeasurableFile(error)) => {
154 debug!(
155 "Failed to measure physical space for `{}`: {error}",
156 path.display()
157 );
158 self.physical_bytes.mark_incomplete();
159 }
160 }
161 }
162 }
163
164 fn rm_rf(
166 &mut self,
167 path: &Path,
168 reporter: Option<&dyn CleanReporter>,
169 skip_locked_file: bool,
170 ) -> io::Result<()> {
171 let path = uv_fs::verbatim_path(path);
172
173 let metadata = match fs_err::symlink_metadata(&path) {
174 Ok(metadata) => metadata,
175 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
176 Err(err) => return Err(err),
177 };
178
179 if !metadata.is_dir() {
180 self.num_files += 1;
181
182 self.add_file(&path, &metadata);
184 if metadata.is_symlink() {
185 cfg_select! {
186 windows => {
187 use std::os::windows::fs::FileTypeExt;
188
189 if metadata.file_type().is_symlink_dir() {
190 remove_dir(&path)?;
191 } else {
192 remove_file(&path)?;
193 }
194 }
195 _ => {
196 remove_file(&path)?;
197 }
198 }
199 } else {
200 remove_file(&path)?;
201 }
202
203 reporter.map(CleanReporter::on_clean);
204
205 return Ok(());
206 }
207
208 for entry in walkdir::WalkDir::new(&path).contents_first(true) {
209 if let Err(ref err) = entry {
211 if err
212 .io_error()
213 .is_some_and(|err| err.kind() == io::ErrorKind::PermissionDenied)
214 {
215 if let Some(dir) = err.path() {
216 if set_readable(dir).unwrap_or(false) {
217 return self.rm_rf(&path, reporter, skip_locked_file);
220 }
221 }
222 }
223 }
224
225 let entry = entry?;
226
227 if skip_locked_file
229 && entry.file_name() == ".lock"
230 && entry
231 .path()
232 .strip_prefix(&path)
233 .is_ok_and(|suffix| suffix == Path::new(".lock"))
234 {
235 continue;
236 }
237
238 if entry.file_type().is_symlink() && {
239 #[cfg(windows)]
240 {
241 use std::os::windows::fs::FileTypeExt;
242 entry.file_type().is_symlink_dir()
243 }
244 #[cfg(not(windows))]
245 {
246 false
247 }
248 } {
249 self.num_files += 1;
250 remove_dir(entry.path())?;
251 } else if entry.file_type().is_dir() {
252 if skip_locked_file && entry.path() == path.as_ref() {
254 continue;
255 }
256
257 self.num_dirs += 1;
258
259 remove_dir_all(entry.path())?;
263 } else {
264 self.num_files += 1;
265
266 if let Ok(metadata) = entry.metadata() {
268 self.add_file(entry.path(), &metadata);
269 } else {
270 self.physical_bytes.mark_incomplete();
271 }
272 remove_file(entry.path())?;
273 }
274
275 reporter.map(CleanReporter::on_clean);
276 }
277
278 reporter.map(CleanReporter::on_complete);
279
280 Ok(())
281 }
282}
283
284impl std::ops::AddAssign for Removal {
285 fn add_assign(&mut self, other: Self) {
286 self.num_files += other.num_files;
287 self.num_dirs += other.num_dirs;
288 self.coarse_bytes += other.coarse_bytes;
289 self.physical_bytes = self.physical_bytes.combine(other.physical_bytes);
290 }
291}
292
293#[cfg_attr(windows, allow(unused_variables, clippy::unnecessary_wraps))]
295fn set_readable(path: &Path) -> io::Result<bool> {
296 #[cfg(unix)]
297 {
298 use std::os::unix::fs::PermissionsExt;
299 let mut perms = fs_err::metadata(path)?.permissions();
300 if perms.mode() & 0o500 == 0 {
301 perms.set_mode(perms.mode() | 0o500);
302 fs_err::set_permissions(path, perms)?;
303 return Ok(true);
304 }
305 }
306 Ok(false)
307}
308
309fn set_not_readonly(path: &Path) -> io::Result<bool> {
311 let mut perms = fs_err::metadata(path)?.permissions();
312 if !perms.readonly() {
313 return Ok(false);
314 }
315
316 #[expect(clippy::permissions_set_readonly_false)]
318 perms.set_readonly(false);
319
320 fs_err::set_permissions(path, perms)?;
321
322 Ok(true)
323}
324
325fn remove_file(path: &Path) -> io::Result<()> {
328 match fs_err::remove_file(path) {
329 Ok(()) => Ok(()),
330 Err(err)
331 if err.kind() == io::ErrorKind::PermissionDenied
332 && set_not_readonly(path).unwrap_or(false) =>
333 {
334 fs_err::remove_file(path)
335 }
336 Err(err) => Err(err),
337 }
338}
339
340fn remove_dir(path: &Path) -> io::Result<()> {
343 match fs_err::remove_dir(path) {
344 Ok(()) => Ok(()),
345 Err(err)
346 if err.kind() == io::ErrorKind::PermissionDenied
347 && set_readable(path).unwrap_or(false) =>
348 {
349 fs_err::remove_dir(path)
350 }
351 Err(err) => Err(err),
352 }
353}
354
355fn remove_dir_all(path: &Path) -> io::Result<()> {
358 match fs_err::remove_dir_all(path) {
359 Ok(()) => Ok(()),
360 Err(err)
361 if err.kind() == io::ErrorKind::PermissionDenied
362 && set_readable(path).unwrap_or(false) =>
363 {
364 fs_err::remove_dir_all(path)
365 }
366 Err(err) => Err(err),
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::PhysicalBytes::{LowerBound, Measured, Unavailable};
373
374 #[test]
375 fn combine_physical_bytes() {
376 assert_eq!(Measured(2).combine(Measured(3)), Measured(5));
377 assert_eq!(LowerBound(2).combine(Measured(3)), LowerBound(5));
378 assert_eq!(Measured(2).combine(LowerBound(3)), LowerBound(5));
379 assert_eq!(LowerBound(2).combine(LowerBound(3)), LowerBound(5));
380 assert_eq!(LowerBound(2).combine(Unavailable), Unavailable);
381 assert_eq!(Unavailable.combine(Measured(3)), Unavailable);
382 }
383}