Skip to main content

uv_cache/
removal.rs

1//! Derived from Cargo's `clean` implementation.
2//! Cargo is dual-licensed under either Apache 2.0 or MIT, at the user's choice.
3//! Source: <https://github.com/rust-lang/cargo/blob/e1ebce1035f9b53bb46a55bd4b0ecf51e24c6458/src/cargo/ops/cargo_clean.rs#L324>
4
5use 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/// How to estimate reclaimed storage when removing cache entries.
17#[derive(Debug, Clone, Copy, Default)]
18pub enum RemovalAccounting {
19    /// Estimate reclaimed storage from ordinary filesystem metadata.
20    #[default]
21    Coarse,
22    /// Inspect filesystem allocation and sharing where supported.
23    Fine,
24}
25
26/// A builder for a [`Remover`] that can remove files and directories.
27#[derive(Default)]
28pub(crate) struct Remover {
29    reporter: Option<Box<dyn CleanReporter>>,
30    removal_accounting: RemovalAccounting,
31}
32
33impl Remover {
34    /// Create a new [`Remover`] with the given reporter.
35    pub(crate) fn new(reporter: Box<dyn CleanReporter>) -> Self {
36        Self {
37            reporter: Some(reporter),
38            ..Self::default()
39        }
40    }
41
42    /// Set the storage accounting used before each file is removed.
43    pub(crate) fn with_removal_accounting(mut self, removal_accounting: RemovalAccounting) -> Self {
44        self.removal_accounting = removal_accounting;
45        self
46    }
47
48    /// Remove a file or directory and all its contents, returning a [`Removal`] with
49    /// the number of files and directories removed, along with a total byte count.
50    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/// Estimate the storage reclaimed by removing a non-directory entry.
62#[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/// Estimate the storage reclaimed by removing a non-directory entry.
72#[cfg(not(unix))]
73fn file_size(metadata: &Metadata) -> u64 {
74    metadata.len()
75}
76
77/// The estimated physical space reclaimed by a cache removal.
78#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
79pub enum PhysicalBytes {
80    /// Physical accounting was disabled or unsupported.
81    #[default]
82    Unavailable,
83    /// Every removed file contributed a measurement.
84    Measured(u64),
85    /// Some files could not be measured.
86    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/// A removal operation with statistics on the number of files and directories removed.
111#[derive(Debug, Default)]
112pub struct Removal {
113    /// The number of files removed.
114    pub num_files: u64,
115    /// The number of directories removed.
116    pub num_dirs: u64,
117    /// The coarse estimate of the number of bytes occupied by the removed files.
118    pub coarse_bytes: u64,
119    /// The fine-grained estimate of reclaimed physical file data.
120    pub physical_bytes: PhysicalBytes,
121}
122
123impl Removal {
124    /// Create an empty removal summary with the requested storage accounting.
125    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    /// Account for a file while its current sharing state can still be inspected.
136    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    /// Recursively remove a file or directory and all its contents.
165    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            // Remove the file.
183            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 we hit a directory that lacks read permissions, try to make it readable.
210            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                            // Retry the operation; if we _just_ `self.rm_rf(dir)` and continue,
218                            // `walkdir` may give us duplicate entries for the directory.
219                            return self.rm_rf(&path, reporter, skip_locked_file);
220                        }
221                    }
222                }
223            }
224
225            let entry = entry?;
226
227            // Keep the root lock in place for other uv processes.
228            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                // Keep the root directory containing the lock, too.
253                if skip_locked_file && entry.path() == path.as_ref() {
254                    continue;
255                }
256
257                self.num_dirs += 1;
258
259                // The contents should have been removed by now, but sometimes a race condition is
260                // hit where other files have been added by the OS. Fall back to `remove_dir_all`,
261                // which will remove the directory robustly across platforms.
262                remove_dir_all(entry.path())?;
263            } else {
264                self.num_files += 1;
265
266                // Remove the file.
267                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/// If the directory isn't readable by the current user, change the permissions to make it readable.
294#[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
309/// If the file is readonly, change the permissions to make it _not_ readonly.
310fn 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    // We're about to delete the file, so it's fine to set the permissions to world-writable.
317    #[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
325/// Like [`fs_err::remove_file`], but attempts to change the permissions to force the file to be
326/// deleted (if it is readonly).
327fn 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
340/// Like [`fs_err::remove_dir`], but attempts to change the permissions to force the directory to
341/// be deleted (if it is readonly).
342fn 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
355/// Like [`fs_err::remove_dir_all`], but attempts to change the permissions to force the directory
356/// to be deleted (if it is readonly).
357fn 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}