Skip to main content

uv_cache/
lib.rs

1use std::fmt::{Display, Formatter};
2use std::io;
3use std::io::Write;
4use std::ops::Deref;
5use std::path::{Path, PathBuf};
6use std::str::FromStr;
7use std::sync::Arc;
8
9use rustc_hash::FxHashMap;
10use tracing::{debug, trace, warn};
11
12use uv_cache_info::Timestamp;
13use uv_fs::{LockedFile, LockedFileError, LockedFileMode, Simplified, cachedir, directories};
14use uv_normalize::PackageName;
15use uv_pypi_types::ResolutionMetadata;
16
17pub use crate::by_timestamp::CachedByTimestamp;
18#[cfg(feature = "clap")]
19pub use crate::cli::CacheArgs;
20use crate::removal::Remover;
21pub use crate::removal::{Removal, rm_rf};
22pub use crate::wheel::WheelCache;
23use crate::wheel::WheelCacheKind;
24pub use archive::ArchiveId;
25
26mod archive;
27mod by_timestamp;
28#[cfg(feature = "clap")]
29mod cli;
30mod removal;
31mod wheel;
32
33/// The version of the archive bucket.
34///
35/// Must be kept in-sync with the version in [`CacheBucket::to_str`].
36pub const ARCHIVE_VERSION: u8 = 0;
37
38/// Error locking a cache entry or shard
39#[derive(Debug, thiserror::Error)]
40pub enum Error {
41    #[error(transparent)]
42    Io(#[from] io::Error),
43    #[error("Failed to initialize cache at `{}`", _0.user_display())]
44    Init(PathBuf, #[source] io::Error),
45    #[error("Could not make the path absolute")]
46    Absolute(#[source] io::Error),
47    #[error("Could not acquire lock")]
48    Acquire(#[from] LockedFileError),
49}
50
51/// A [`CacheEntry`] which may or may not exist yet.
52#[derive(Debug, Clone)]
53pub struct CacheEntry(PathBuf);
54
55impl CacheEntry {
56    /// Create a new [`CacheEntry`] from a directory and a file name.
57    pub fn new(dir: impl Into<PathBuf>, file: impl AsRef<Path>) -> Self {
58        Self(dir.into().join(file))
59    }
60
61    /// Create a new [`CacheEntry`] from a path.
62    pub fn from_path(path: impl Into<PathBuf>) -> Self {
63        Self(path.into())
64    }
65
66    /// Return the cache entry's parent directory.
67    pub fn shard(&self) -> CacheShard {
68        CacheShard(self.dir().to_path_buf())
69    }
70
71    /// Convert the [`CacheEntry`] into a [`PathBuf`].
72    #[inline]
73    pub fn into_path_buf(self) -> PathBuf {
74        self.0
75    }
76
77    /// Return the path to the [`CacheEntry`].
78    #[inline]
79    pub fn path(&self) -> &Path {
80        &self.0
81    }
82
83    /// Return the cache entry's parent directory.
84    #[inline]
85    pub fn dir(&self) -> &Path {
86        self.0.parent().expect("Cache entry has no parent")
87    }
88
89    /// Create a new [`CacheEntry`] with the given file name.
90    #[must_use]
91    pub fn with_file(&self, file: impl AsRef<Path>) -> Self {
92        Self(self.dir().join(file))
93    }
94
95    /// Acquire the [`CacheEntry`] as an exclusive lock.
96    pub async fn lock(&self) -> Result<LockedFile, Error> {
97        fs_err::create_dir_all(self.dir())?;
98        Ok(LockedFile::acquire(
99            self.path(),
100            LockedFileMode::Exclusive,
101            self.path().display(),
102        )
103        .await?)
104    }
105}
106
107impl AsRef<Path> for CacheEntry {
108    fn as_ref(&self) -> &Path {
109        &self.0
110    }
111}
112
113/// A subdirectory within the cache.
114#[derive(Debug, Clone)]
115pub struct CacheShard(PathBuf);
116
117impl CacheShard {
118    /// Return a [`CacheEntry`] within this shard.
119    pub fn entry(&self, file: impl AsRef<Path>) -> CacheEntry {
120        CacheEntry::new(&self.0, file)
121    }
122
123    /// Return a [`CacheShard`] within this shard.
124    #[must_use]
125    pub fn shard(&self, dir: impl AsRef<Path>) -> Self {
126        Self(self.0.join(dir.as_ref()))
127    }
128
129    /// Acquire the cache entry as an exclusive lock.
130    pub async fn lock(&self) -> Result<LockedFile, Error> {
131        fs_err::create_dir_all(self.as_ref())?;
132        Ok(LockedFile::acquire(
133            self.join(".lock"),
134            LockedFileMode::Exclusive,
135            self.display(),
136        )
137        .await?)
138    }
139
140    /// Return the [`CacheShard`] as a [`PathBuf`].
141    pub fn into_path_buf(self) -> PathBuf {
142        self.0
143    }
144}
145
146impl AsRef<Path> for CacheShard {
147    fn as_ref(&self) -> &Path {
148        &self.0
149    }
150}
151
152impl Deref for CacheShard {
153    type Target = Path;
154
155    fn deref(&self) -> &Self::Target {
156        &self.0
157    }
158}
159
160/// The main cache abstraction.
161///
162/// While the cache is active, it holds a read (shared) lock that prevents cache cleaning
163#[derive(Debug, Clone)]
164pub struct Cache {
165    /// The cache directory.
166    root: PathBuf,
167    /// The refresh strategy to use when reading from the cache.
168    refresh: Refresh,
169    /// A temporary cache directory, if the user requested `--no-cache`.
170    ///
171    /// Included to ensure that the temporary directory exists for the length of the operation, but
172    /// is dropped at the end as appropriate.
173    temp_dir: Option<Arc<tempfile::TempDir>>,
174    /// Ensure that `uv cache` operations don't remove items from the cache that are used by another
175    /// uv process.
176    lock_file: Option<Arc<LockedFile>>,
177}
178
179impl Cache {
180    /// A persistent cache directory at `root`.
181    pub fn from_path(root: impl Into<PathBuf>) -> Self {
182        Self {
183            root: root.into(),
184            refresh: Refresh::None(Timestamp::now()),
185            temp_dir: None,
186            lock_file: None,
187        }
188    }
189
190    /// Create a temporary cache directory.
191    pub fn temp() -> Result<Self, io::Error> {
192        let temp_dir = tempfile::tempdir()?;
193        Ok(Self {
194            root: temp_dir.path().to_path_buf(),
195            refresh: Refresh::None(Timestamp::now()),
196            temp_dir: Some(Arc::new(temp_dir)),
197            lock_file: None,
198        })
199    }
200
201    /// Set the [`Refresh`] policy for the cache.
202    #[must_use]
203    pub fn with_refresh(self, refresh: Refresh) -> Self {
204        Self { refresh, ..self }
205    }
206
207    /// Acquire a lock that allows removing entries from the cache.
208    pub async fn with_exclusive_lock(self) -> Result<Self, LockedFileError> {
209        let Self {
210            root,
211            refresh,
212            temp_dir,
213            lock_file,
214        } = self;
215
216        // Release the existing lock, avoid deadlocks from a cloned cache.
217        if let Some(lock_file) = lock_file {
218            drop(
219                Arc::try_unwrap(lock_file).expect(
220                    "cloning the cache before acquiring an exclusive lock causes a deadlock",
221                ),
222            );
223        }
224        let lock_file = LockedFile::acquire(
225            root.join(".lock"),
226            LockedFileMode::Exclusive,
227            root.simplified_display(),
228        )
229        .await?;
230
231        Ok(Self {
232            root,
233            refresh,
234            temp_dir,
235            lock_file: Some(Arc::new(lock_file)),
236        })
237    }
238
239    /// Acquire a lock that allows removing entries from the cache, if available.
240    ///
241    /// If the lock is not immediately available, returns [`Err`] with self.
242    pub fn with_exclusive_lock_no_wait(self) -> Result<Self, Self> {
243        let Self {
244            root,
245            refresh,
246            temp_dir,
247            lock_file,
248        } = self;
249
250        match LockedFile::acquire_no_wait(
251            root.join(".lock"),
252            LockedFileMode::Exclusive,
253            root.simplified_display(),
254        ) {
255            Some(lock_file) => Ok(Self {
256                root,
257                refresh,
258                temp_dir,
259                lock_file: Some(Arc::new(lock_file)),
260            }),
261            None => Err(Self {
262                root,
263                refresh,
264                temp_dir,
265                lock_file,
266            }),
267        }
268    }
269
270    /// Return the root of the cache.
271    pub fn root(&self) -> &Path {
272        &self.root
273    }
274
275    /// The folder for a specific cache bucket
276    pub fn bucket(&self, cache_bucket: CacheBucket) -> PathBuf {
277        self.root.join(cache_bucket.to_str())
278    }
279
280    /// Compute an entry in the cache.
281    pub fn shard(&self, cache_bucket: CacheBucket, dir: impl AsRef<Path>) -> CacheShard {
282        CacheShard(self.bucket(cache_bucket).join(dir.as_ref()))
283    }
284
285    /// Compute an entry in the cache.
286    pub fn entry(
287        &self,
288        cache_bucket: CacheBucket,
289        dir: impl AsRef<Path>,
290        file: impl AsRef<Path>,
291    ) -> CacheEntry {
292        CacheEntry::new(self.bucket(cache_bucket).join(dir), file)
293    }
294
295    /// Return the path to an archive in the cache.
296    pub fn archive(&self, id: &ArchiveId) -> PathBuf {
297        self.bucket(CacheBucket::Archive).join(id)
298    }
299
300    /// Create a temporary directory to be used as a Python virtual environment.
301    pub fn venv_dir(&self) -> io::Result<tempfile::TempDir> {
302        fs_err::create_dir_all(self.bucket(CacheBucket::Builds))?;
303        tempfile::tempdir_in(self.bucket(CacheBucket::Builds))
304    }
305
306    /// Create a temporary directory to be used for executing PEP 517 source distribution builds.
307    pub fn build_dir(&self) -> io::Result<tempfile::TempDir> {
308        fs_err::create_dir_all(self.bucket(CacheBucket::Builds))?;
309        tempfile::tempdir_in(self.bucket(CacheBucket::Builds))
310    }
311
312    /// Returns `true` if a cache entry must be revalidated given the [`Refresh`] policy.
313    pub fn must_revalidate_package(&self, package: &PackageName) -> bool {
314        match &self.refresh {
315            Refresh::None(_) => false,
316            Refresh::All(_) => true,
317            Refresh::Packages(packages, _, _) => packages.contains(package),
318        }
319    }
320
321    /// Returns `true` if a cache entry must be revalidated given the [`Refresh`] policy.
322    pub fn must_revalidate_path(&self, path: &Path) -> bool {
323        match &self.refresh {
324            Refresh::None(_) => false,
325            Refresh::All(_) => true,
326            Refresh::Packages(_, paths, _) => paths
327                .iter()
328                .any(|target| same_file::is_same_file(path, target).unwrap_or(false)),
329        }
330    }
331
332    /// Returns the [`Freshness`] for a cache entry, validating it against the [`Refresh`] policy.
333    ///
334    /// A cache entry is considered fresh if it was created after the cache itself was
335    /// initialized, or if the [`Refresh`] policy does not require revalidation.
336    pub fn freshness(
337        &self,
338        entry: &CacheEntry,
339        package: Option<&PackageName>,
340        path: Option<&Path>,
341    ) -> io::Result<Freshness> {
342        // Grab the cutoff timestamp, if it's relevant.
343        let timestamp = match &self.refresh {
344            Refresh::None(_) => return Ok(Freshness::Fresh),
345            Refresh::All(timestamp) => timestamp,
346            Refresh::Packages(packages, paths, timestamp) => {
347                if package.is_none_or(|package| packages.contains(package))
348                    || path.is_some_and(|path| {
349                        paths
350                            .iter()
351                            .any(|target| same_file::is_same_file(path, target).unwrap_or(false))
352                    })
353                {
354                    timestamp
355                } else {
356                    return Ok(Freshness::Fresh);
357                }
358            }
359        };
360
361        match fs_err::metadata(entry.path()) {
362            Ok(metadata) => {
363                if Timestamp::from_metadata(&metadata) >= *timestamp {
364                    Ok(Freshness::Fresh)
365                } else {
366                    Ok(Freshness::Stale)
367                }
368            }
369            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Freshness::Missing),
370            Err(err) => Err(err),
371        }
372    }
373
374    /// Persist a temporary directory to the artifact store, returning its unique ID.
375    pub async fn persist(
376        &self,
377        temp_dir: impl AsRef<Path>,
378        path: impl AsRef<Path>,
379    ) -> io::Result<ArchiveId> {
380        // Create a unique ID for the artifact.
381        // TODO(charlie): Support content-addressed persistence via SHAs.
382        let id = ArchiveId::new();
383
384        // Move the temporary directory into the directory store.
385        let archive_entry = self.entry(CacheBucket::Archive, "", &id);
386        fs_err::create_dir_all(archive_entry.dir())?;
387        uv_fs::rename_with_retry(temp_dir.as_ref(), archive_entry.path()).await?;
388
389        // Create a symlink to the directory store.
390        fs_err::create_dir_all(path.as_ref().parent().expect("Cache entry to have parent"))?;
391        self.create_link(&id, path.as_ref())?;
392
393        Ok(id)
394    }
395
396    /// Returns `true` if the [`Cache`] is temporary.
397    pub fn is_temporary(&self) -> bool {
398        self.temp_dir.is_some()
399    }
400
401    /// Populate the cache scaffold.
402    fn create_base_files(root: &PathBuf) -> io::Result<()> {
403        // Create the cache directory, if it doesn't exist.
404        fs_err::create_dir_all(root)?;
405
406        // Add the CACHEDIR.TAG.
407        cachedir::ensure_tag(root)?;
408
409        // Add the .gitignore.
410        match fs_err::OpenOptions::new()
411            .write(true)
412            .create_new(true)
413            .open(root.join(".gitignore"))
414        {
415            Ok(mut file) => file.write_all(b"*")?,
416            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
417            Err(err) => return Err(err),
418        }
419
420        // Add an empty .gitignore to the build bucket, to ensure that the cache's own .gitignore
421        // doesn't interfere with source distribution builds. Build backends (like hatchling) will
422        // traverse upwards to look for .gitignore files.
423        fs_err::create_dir_all(root.join(CacheBucket::SourceDistributions.to_str()))?;
424        match fs_err::OpenOptions::new()
425            .write(true)
426            .create_new(true)
427            .open(
428                root.join(CacheBucket::SourceDistributions.to_str())
429                    .join(".gitignore"),
430            ) {
431            Ok(_) => {}
432            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
433            Err(err) => return Err(err),
434        }
435
436        // Add a phony .git, if it doesn't exist, to ensure that the cache isn't considered to be
437        // part of a Git repository. (Some packages will include Git metadata (like a hash) in the
438        // built version if they're in a Git repository, but the cache should be viewed as an
439        // isolated store.).
440        // We have to put this below the gitignore. Otherwise, if the build backend uses the rust
441        // ignore crate it will walk up to the top level .gitignore and ignore its python source
442        // files.
443        let phony_git = root
444            .join(CacheBucket::SourceDistributions.to_str())
445            .join(".git");
446        match fs_err::OpenOptions::new()
447            .create(true)
448            .write(true)
449            .open(&phony_git)
450        {
451            Ok(_) => {}
452            // Handle read-only caches including sandboxed environments.
453            Err(err) if err.kind() == io::ErrorKind::ReadOnlyFilesystem => {
454                if !phony_git.exists() {
455                    return Err(err);
456                }
457            }
458            Err(err) => return Err(err),
459        }
460
461        Ok(())
462    }
463
464    /// Initialize the [`Cache`].
465    pub async fn init(self) -> Result<Self, Error> {
466        let root = &self.root;
467
468        Self::create_base_files(root).map_err(|err| Error::Init(root.clone(), err))?;
469
470        // Block cache removal operations from interfering.
471        let lock_file = match LockedFile::acquire(
472            root.join(".lock"),
473            LockedFileMode::Shared,
474            root.simplified_display(),
475        )
476        .await
477        {
478            Ok(lock_file) => Some(Arc::new(lock_file)),
479            Err(err)
480                if err
481                    .as_io_error()
482                    .is_some_and(|err| err.kind() == io::ErrorKind::Unsupported) =>
483            {
484                warn!(
485                    "Shared locking is not supported by the current platform or filesystem, \
486                        reduced parallel process safety with `uv cache clean` and `uv cache prune`."
487                );
488                None
489            }
490            Err(err) => return Err(err.into()),
491        };
492
493        Ok(Self {
494            root: std::path::absolute(root).map_err(Error::Absolute)?,
495            lock_file,
496            ..self
497        })
498    }
499
500    /// Initialize the [`Cache`], assuming that there are no other uv processes running.
501    pub fn init_no_wait(self) -> Result<Option<Self>, Error> {
502        let root = &self.root;
503
504        Self::create_base_files(root).map_err(|err| Error::Init(root.clone(), err))?;
505
506        // Block cache removal operations from interfering.
507        let Some(lock_file) = LockedFile::acquire_no_wait(
508            root.join(".lock"),
509            LockedFileMode::Shared,
510            root.simplified_display(),
511        ) else {
512            return Ok(None);
513        };
514        Ok(Some(Self {
515            root: std::path::absolute(root).map_err(Error::Absolute)?,
516            lock_file: Some(Arc::new(lock_file)),
517            ..self
518        }))
519    }
520
521    /// Clear the cache, removing all entries.
522    pub fn clear(self, reporter: Box<dyn CleanReporter>) -> Result<Removal, io::Error> {
523        // Remove everything but `.lock`, Windows does not allow removal of a locked file
524        let mut removal = Remover::new(reporter).rm_rf(&self.root, true)?;
525        let Self {
526            root, lock_file, ..
527        } = self;
528
529        // Remove the `.lock` file, unlocking it first
530        if let Some(lock) = lock_file {
531            drop(lock);
532            fs_err::remove_file(root.join(".lock"))?;
533        }
534        removal.num_files += 1;
535
536        // Remove the root directory
537        match fs_err::remove_dir(root) {
538            Ok(()) => {
539                removal.num_dirs += 1;
540            }
541            // On Windows, when `--force` is used, the `.lock` file can exist and be unremovable,
542            // so we make this non-fatal
543            Err(err) if err.kind() == io::ErrorKind::DirectoryNotEmpty => {
544                trace!("Failed to remove root cache directory: not empty");
545            }
546            Err(err) => return Err(err),
547        }
548
549        Ok(removal)
550    }
551
552    /// Remove a package from the cache.
553    ///
554    /// Returns the number of entries removed from the cache.
555    pub fn remove(&self, name: &PackageName) -> io::Result<Removal> {
556        // Collect the set of referenced archives.
557        let references = self.find_archive_references()?;
558
559        // Remove any entries for the package from the cache.
560        let mut summary = Removal::default();
561        for bucket in CacheBucket::iter() {
562            summary += bucket.remove(self, name)?;
563        }
564
565        // Remove any archives that are no longer referenced.
566        for (target, references) in references {
567            if references.iter().all(|path| !path.exists()) {
568                debug!("Removing dangling cache entry: {}", target.display());
569                summary += rm_rf(target)?;
570            }
571        }
572
573        Ok(summary)
574    }
575
576    /// Run the garbage collector on the cache, removing any dangling entries.
577    pub fn prune(&self, ci: bool) -> Result<Removal, io::Error> {
578        let mut summary = Removal::default();
579
580        // First, remove any top-level directories that are unused. These typically represent
581        // outdated cache buckets (e.g., `wheels-v0`, when latest is `wheels-v1`).
582        for entry in fs_err::read_dir(&self.root)? {
583            let entry = entry?;
584            let metadata = entry.metadata()?;
585
586            if entry.file_name() == "CACHEDIR.TAG"
587                || entry.file_name() == ".gitignore"
588                || entry.file_name() == ".git"
589                || entry.file_name() == ".lock"
590            {
591                continue;
592            }
593
594            if metadata.is_dir() {
595                // If the directory is not a cache bucket, remove it.
596                if CacheBucket::iter().all(|bucket| entry.file_name() != bucket.to_str()) {
597                    let path = entry.path();
598                    debug!("Removing dangling cache bucket: {}", path.display());
599                    summary += rm_rf(path)?;
600                }
601            } else {
602                // If the file is not a marker file, remove it.
603                let path = entry.path();
604                debug!("Removing dangling cache bucket: {}", path.display());
605                summary += rm_rf(path)?;
606            }
607        }
608
609        // Second, remove any cached environments. These are never referenced by symlinks, so we can
610        // remove them directly.
611        match fs_err::read_dir(self.bucket(CacheBucket::Environments)) {
612            Ok(entries) => {
613                for entry in entries {
614                    let entry = entry?;
615                    let path = fs_err::canonicalize(entry.path())?;
616                    debug!("Removing dangling cache environment: {}", path.display());
617                    summary += rm_rf(path)?;
618                }
619            }
620            Err(err) if err.kind() == io::ErrorKind::NotFound => (),
621            Err(err) => return Err(err),
622        }
623
624        // Third, if enabled, remove all unzipped wheels, leaving only the wheel archives.
625        if ci {
626            // Remove the entire pre-built wheel cache, since every entry is an unzipped wheel.
627            match fs_err::read_dir(self.bucket(CacheBucket::Wheels)) {
628                Ok(entries) => {
629                    for entry in entries {
630                        let entry = entry?;
631                        let path = fs_err::canonicalize(entry.path())?;
632                        if path.is_dir() {
633                            debug!("Removing unzipped wheel entry: {}", path.display());
634                            summary += rm_rf(path)?;
635                        }
636                    }
637                }
638                Err(err) if err.kind() == io::ErrorKind::NotFound => (),
639                Err(err) => return Err(err),
640            }
641
642            for entry in walkdir::WalkDir::new(self.bucket(CacheBucket::SourceDistributions)) {
643                let entry = entry?;
644
645                // If the directory contains a `metadata.msgpack`, then it's a built wheel revision.
646                if !entry.file_type().is_dir() {
647                    continue;
648                }
649
650                if !entry.path().join("metadata.msgpack").exists() {
651                    continue;
652                }
653
654                // Remove everything except the built wheel archive and the metadata.
655                for entry in fs_err::read_dir(entry.path())? {
656                    let entry = entry?;
657                    let path = entry.path();
658
659                    // Retain the resolved metadata (`metadata.msgpack`).
660                    if path
661                        .file_name()
662                        .is_some_and(|file_name| file_name == "metadata.msgpack")
663                    {
664                        continue;
665                    }
666
667                    // Retain any built wheel archives.
668                    if path
669                        .extension()
670                        .is_some_and(|ext| ext.eq_ignore_ascii_case("whl"))
671                    {
672                        continue;
673                    }
674
675                    debug!("Removing unzipped built wheel entry: {}", path.display());
676                    summary += rm_rf(path)?;
677                }
678            }
679        }
680
681        // Fourth, remove any unused archives (by searching for archives that are not symlinked).
682        let references = self.find_archive_references()?;
683
684        match fs_err::read_dir(self.bucket(CacheBucket::Archive)) {
685            Ok(entries) => {
686                for entry in entries {
687                    let entry = entry?;
688                    let path = fs_err::canonicalize(entry.path())?;
689                    if !references.contains_key(&path) {
690                        debug!("Removing dangling cache archive: {}", path.display());
691                        summary += rm_rf(path)?;
692                    }
693                }
694            }
695            Err(err) if err.kind() == io::ErrorKind::NotFound => (),
696            Err(err) => return Err(err),
697        }
698
699        Ok(summary)
700    }
701
702    /// Find all references to entries in the archive bucket.
703    ///
704    /// Archive entries are often referenced by symlinks in other cache buckets. This method
705    /// searches for all such references.
706    ///
707    /// Returns a map from archive path to paths that reference it.
708    fn find_archive_references(&self) -> Result<FxHashMap<PathBuf, Vec<PathBuf>>, io::Error> {
709        let mut references = FxHashMap::<PathBuf, Vec<PathBuf>>::default();
710        for bucket in [CacheBucket::SourceDistributions, CacheBucket::Wheels] {
711            let bucket_path = self.bucket(bucket);
712            if bucket_path.is_dir() {
713                let walker = walkdir::WalkDir::new(&bucket_path).into_iter();
714                for entry in walker.filter_entry(|entry| {
715                    !(
716                        // As an optimization, ignore any `.lock`, `.whl`, `.msgpack`, `.rev`, or
717                        // `.http` files, along with the `src` directory, which represents the
718                        // unpacked source distribution.
719                        entry.file_name() == "src"
720                            || entry.file_name() == ".lock"
721                            || entry.file_name() == ".gitignore"
722                            || entry.path().extension().is_some_and(|ext| {
723                                ext.eq_ignore_ascii_case("lock")
724                                    || ext.eq_ignore_ascii_case("whl")
725                                    || ext.eq_ignore_ascii_case("http")
726                                    || ext.eq_ignore_ascii_case("rev")
727                                    || ext.eq_ignore_ascii_case("msgpack")
728                            })
729                    )
730                }) {
731                    let entry = entry?;
732
733                    // On Unix, archive references use symlinks.
734                    if cfg!(unix) {
735                        if !entry.file_type().is_symlink() {
736                            continue;
737                        }
738                    }
739
740                    // On Windows, archive references are files containing structured data.
741                    if cfg!(windows) {
742                        if !entry.file_type().is_file() {
743                            continue;
744                        }
745                    }
746
747                    if let Ok(target) = self.resolve_link(entry.path()) {
748                        references
749                            .entry(target)
750                            .or_default()
751                            .push(entry.path().to_path_buf());
752                    }
753                }
754            }
755        }
756        Ok(references)
757    }
758
759    /// Create a link to a directory in the archive bucket.
760    ///
761    /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and
762    /// version. On Unix, we create a symlink to the target directory.
763    #[cfg(windows)]
764    #[expect(clippy::unused_self)]
765    fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> {
766        // Serialize the link.
767        let link = Link::new(id.clone());
768        let contents = link.to_string();
769
770        // First, attempt to create a file at the location, but fail if it already exists.
771        match fs_err::OpenOptions::new()
772            .write(true)
773            .create_new(true)
774            .open(dst.as_ref())
775        {
776            Ok(mut file) => {
777                // Write the target path to the file.
778                file.write_all(contents.as_bytes())?;
779                Ok(())
780            }
781            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
782                // Write to a temporary file, then move it into place.
783                let temp_dir = tempfile::tempdir_in(dst.as_ref().parent().unwrap())?;
784                let temp_file = temp_dir.path().join("link");
785                fs_err::write(&temp_file, contents.as_bytes())?;
786
787                // Move the symlink into the target location.
788                fs_err::rename(&temp_file, dst.as_ref())?;
789
790                Ok(())
791            }
792            Err(err) => Err(err),
793        }
794    }
795
796    /// Resolve an archive link, returning the fully-resolved path.
797    ///
798    /// Returns an error if the link target does not exist.
799    #[cfg(windows)]
800    pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
801        // Deserialize the link.
802        let contents = fs_err::read_to_string(path.as_ref())?;
803        let link = Link::from_str(&contents)?;
804
805        // Ignore stale links.
806        if link.version != ARCHIVE_VERSION {
807            return Err(io::Error::new(
808                io::ErrorKind::NotFound,
809                "The link target does not exist.",
810            ));
811        }
812
813        // Reconstruct the path.
814        let path = self.archive(&link.id);
815        path.canonicalize()
816    }
817
818    /// Create a link to a directory in the archive bucket.
819    ///
820    /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and
821    /// version. On Unix, we create a symlink to the target directory.
822    #[cfg(unix)]
823    fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> {
824        let dst = dst.as_ref();
825        let dst_parent = dst.parent().expect("Cache entry to have parent");
826        // Construct the relative link target.
827        let src = uv_fs::relative_to(self.archive(id), dst_parent)?;
828
829        // Attempt to create the symlink directly.
830        match fs_err::os::unix::fs::symlink(&src, dst) {
831            Ok(()) => Ok(()),
832            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
833                // Create a symlink, using a temporary file to ensure atomicity.
834                let temp_dir = tempfile::tempdir_in(dst_parent)?;
835                let temp_file = temp_dir.path().join("link");
836                fs_err::os::unix::fs::symlink(&src, &temp_file)?;
837
838                // Move the symlink into the target location.
839                fs_err::rename(&temp_file, dst)?;
840
841                Ok(())
842            }
843            Err(err) => Err(err),
844        }
845    }
846
847    /// Resolve an archive link, returning the fully-resolved path.
848    ///
849    /// Returns an error if the link target does not exist.
850    #[cfg(unix)]
851    pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
852        path.as_ref().canonicalize()
853    }
854}
855
856/// An archive (unzipped wheel) that exists in the local cache.
857#[derive(Debug, Clone)]
858#[allow(unused)]
859struct Link {
860    /// The unique ID of the entry in the archive bucket.
861    id: ArchiveId,
862    /// The version of the archive bucket.
863    version: u8,
864}
865
866#[allow(unused)]
867impl Link {
868    /// Create a new [`Archive`] with the given ID and hashes.
869    fn new(id: ArchiveId) -> Self {
870        Self {
871            id,
872            version: ARCHIVE_VERSION,
873        }
874    }
875}
876
877impl Display for Link {
878    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
879        write!(f, "archive-v{}/{}", self.version, self.id)
880    }
881}
882
883impl FromStr for Link {
884    type Err = io::Error;
885
886    fn from_str(s: &str) -> Result<Self, Self::Err> {
887        let mut parts = s.splitn(2, '/');
888        let version = parts
889            .next()
890            .filter(|s| !s.is_empty())
891            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version"))?;
892        let id = parts
893            .next()
894            .filter(|s| !s.is_empty())
895            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing ID"))?;
896
897        // Parse the archive version from `archive-v{version}/{id}`.
898        let version = version
899            .strip_prefix("archive-v")
900            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version prefix"))?;
901        let version = u8::from_str(version).map_err(|err| {
902            io::Error::new(
903                io::ErrorKind::InvalidData,
904                format!("failed to parse version: {err}"),
905            )
906        })?;
907
908        // Parse the ID from `archive-v{version}/{id}`.
909        let id = ArchiveId::from_str(id).map_err(|err| {
910            io::Error::new(
911                io::ErrorKind::InvalidData,
912                format!("failed to parse ID: {err}"),
913            )
914        })?;
915
916        Ok(Self { id, version })
917    }
918}
919
920pub trait CleanReporter: Send + Sync {
921    /// Called after one file or directory is removed.
922    fn on_clean(&self);
923
924    /// Called after all files and directories are removed.
925    fn on_complete(&self);
926}
927
928/// The different kinds of data in the cache are stored in different bucket, which in our case
929/// are subdirectories of the cache root.
930#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
931pub enum CacheBucket {
932    /// Wheels (excluding built wheels), alongside their metadata and cache policy.
933    ///
934    /// There are three kinds from cache entries: Wheel metadata and policy as `MsgPack` files, the
935    /// wheels themselves, and the unzipped wheel archives. If a wheel file is over an in-memory
936    /// size threshold, we first download the zip file into the cache, then unzip it into a
937    /// directory with the same name (exclusive of the `.whl` extension).
938    ///
939    /// Cache structure:
940    ///  * `wheel-metadata-v0/pypi/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
941    ///  * `wheel-metadata-v0/<digest(index-url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
942    ///  * `wheel-metadata-v0/url/<digest(url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
943    ///
944    /// See `uv_client::RegistryClient::wheel_metadata` for information on how wheel metadata
945    /// is fetched.
946    ///
947    /// # Example
948    ///
949    /// Consider the following `requirements.in`:
950    /// ```text
951    /// # pypi wheel
952    /// pandas
953    /// # url wheel
954    /// flask @ https://files.pythonhosted.org/packages/36/42/015c23096649b908c809c69388a805a571a3bea44362fe87e33fc3afa01f/flask-3.0.0-py3-none-any.whl
955    /// ```
956    ///
957    /// When we run `pip compile`, it will only fetch and cache the metadata (and cache policy), it
958    /// doesn't need the actual wheels yet:
959    /// ```text
960    /// wheel-v0
961    /// ├── pypi
962    /// │   ...
963    /// │   ├── pandas
964    /// │   │   └── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.msgpack
965    /// │   ...
966    /// └── url
967    ///     └── 4b8be67c801a7ecb
968    ///         └── flask
969    ///             └── flask-3.0.0-py3-none-any.msgpack
970    /// ```
971    ///
972    /// We get the following `requirement.txt` from `pip compile`:
973    ///
974    /// ```text
975    /// [...]
976    /// flask @ https://files.pythonhosted.org/packages/36/42/015c23096649b908c809c69388a805a571a3bea44362fe87e33fc3afa01f/flask-3.0.0-py3-none-any.whl
977    /// [...]
978    /// pandas==2.1.3
979    /// [...]
980    /// ```
981    ///
982    /// If we run `pip sync` on `requirements.txt` on a different machine, it also fetches the
983    /// wheels:
984    ///
985    /// TODO(konstin): This is still wrong, we need to store the cache policy too!
986    /// ```text
987    /// wheel-v0
988    /// ├── pypi
989    /// │   ...
990    /// │   ├── pandas
991    /// │   │   ├── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
992    /// │   │   ├── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64
993    /// │   ...
994    /// └── url
995    ///     └── 4b8be67c801a7ecb
996    ///         └── flask
997    ///             └── flask-3.0.0-py3-none-any.whl
998    ///                 ├── flask
999    ///                 │   └── ...
1000    ///                 └── flask-3.0.0.dist-info
1001    ///                     └── ...
1002    /// ```
1003    ///
1004    /// If we run first `pip compile` and then `pip sync` on the same machine, we get both:
1005    ///
1006    /// ```text
1007    /// wheels-v0
1008    /// ├── pypi
1009    /// │   ├── ...
1010    /// │   ├── pandas
1011    /// │   │   ├── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.msgpack
1012    /// │   │   ├── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
1013    /// │   │   └── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64
1014    /// │   │       ├── pandas
1015    /// │   │       │   ├── ...
1016    /// │   │       ├── pandas-2.1.3.dist-info
1017    /// │   │       │   ├── ...
1018    /// │   │       └── pandas.libs
1019    /// │   ├── ...
1020    /// └── url
1021    ///     └── 4b8be67c801a7ecb
1022    ///         └── flask
1023    ///             ├── flask-3.0.0-py3-none-any.msgpack
1024    ///             ├── flask-3.0.0-py3-none-any.msgpack
1025    ///             └── flask-3.0.0-py3-none-any
1026    ///                 ├── flask
1027    ///                 │   └── ...
1028    ///                 └── flask-3.0.0.dist-info
1029    ///                     └── ...
1030    Wheels,
1031    /// Source distributions, wheels built from source distributions, their extracted metadata, and the
1032    /// cache policy of the source distribution.
1033    ///
1034    /// The structure is similar of that of the `Wheel` bucket, except we have an additional layer
1035    /// for the source distribution filename and the metadata is at the source distribution-level,
1036    /// not at the wheel level.
1037    ///
1038    /// TODO(konstin): The cache policy should be on the source distribution level, the metadata we
1039    /// can put next to the wheels as in the `Wheels` bucket.
1040    ///
1041    /// The unzipped source distribution is stored in a directory matching the source distribution
1042    /// archive name.
1043    ///
1044    /// Source distributions are built into zipped wheel files (as PEP 517 specifies) and unzipped
1045    /// lazily before installing. So when resolving, we only build the wheel and store the archive
1046    /// file in the cache, when installing, we unpack it under the same name (exclusive of the
1047    /// `.whl` extension). You may find a mix of wheel archive zip files and unzipped wheel
1048    /// directories in the cache.
1049    ///
1050    /// Cache structure:
1051    ///  * `built-wheels-v0/pypi/foo/34a17436ed1e9669/{manifest.msgpack, metadata.msgpack, foo-1.0.0.zip, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1052    ///  * `built-wheels-v0/<digest(index-url)>/foo/foo-1.0.0.zip/{manifest.msgpack, metadata.msgpack, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1053    ///  * `built-wheels-v0/url/<digest(url)>/foo/foo-1.0.0.zip/{manifest.msgpack, metadata.msgpack, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1054    ///  * `built-wheels-v0/git/<digest(url)>/<git sha>/foo/foo-1.0.0.zip/{metadata.msgpack, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1055    ///
1056    /// But the url filename does not need to be a valid source dist filename
1057    /// (<https://github.com/search?q=path%3A**%2Frequirements.txt+master.zip&type=code>),
1058    /// so it could also be the following and we have to take any string as filename:
1059    ///  * `built-wheels-v0/url/<sha256(url)>/master.zip/metadata.msgpack`
1060    ///
1061    /// # Example
1062    ///
1063    /// The following requirements:
1064    /// ```text
1065    /// # git source dist
1066    /// pydantic-extra-types @ git+https://github.com/pydantic/pydantic-extra-types.git
1067    /// # pypi source dist
1068    /// django_allauth==0.51.0
1069    /// # url source dist
1070    /// werkzeug @ https://files.pythonhosted.org/packages/0d/cc/ff1904eb5eb4b455e442834dabf9427331ac0fa02853bf83db817a7dd53d/werkzeug-3.0.1.tar.gz
1071    /// ```
1072    ///
1073    /// ...may be cached as:
1074    /// ```text
1075    /// built-wheels-v4/
1076    /// ├── git
1077    /// │   └── 2122faf3e081fb7a
1078    /// │       └── 7a2d650a4a7b4d04
1079    /// │           ├── metadata.msgpack
1080    /// │           └── pydantic_extra_types-2.9.0-py3-none-any.whl
1081    /// ├── pypi
1082    /// │   └── django-allauth
1083    /// │       └── 0.51.0
1084    /// │           ├── 0gH-_fwv8tdJ7JwwjJsUc
1085    /// │           │   ├── django-allauth-0.51.0.tar.gz
1086    /// │           │   │   └── [UNZIPPED CONTENTS]
1087    /// │           │   ├── django_allauth-0.51.0-py3-none-any.whl
1088    /// │           │   └── metadata.msgpack
1089    /// │           └── revision.http
1090    /// └── url
1091    ///     └── 6781bd6440ae72c2
1092    ///         ├── APYY01rbIfpAo_ij9sCY6
1093    ///         │   ├── metadata.msgpack
1094    ///         │   ├── werkzeug-3.0.1-py3-none-any.whl
1095    ///         │   └── werkzeug-3.0.1.tar.gz
1096    ///         │       └── [UNZIPPED CONTENTS]
1097    ///         └── revision.http
1098    /// ```
1099    ///
1100    /// Structurally, the `manifest.msgpack` is empty, and only contains the caching information
1101    /// needed to invalidate the cache. The `metadata.msgpack` contains the metadata of the source
1102    /// distribution.
1103    SourceDistributions,
1104    /// Flat index responses, a format very similar to the simple metadata API.
1105    ///
1106    /// Cache structure:
1107    ///  * `flat-index-v0/index/<digest(flat_index_url)>.msgpack`
1108    ///
1109    /// The response is stored as `Vec<File>`.
1110    FlatIndex,
1111    /// Git repositories.
1112    Git,
1113    /// Information about an interpreter at a path.
1114    ///
1115    /// To avoid caching pyenv shims, bash scripts which may redirect to a new python version
1116    /// without the shim itself changing, we only cache when the path equals `sys.executable`, i.e.
1117    /// the path we're running is the python executable itself and not a shim.
1118    ///
1119    /// Cache structure: `interpreter-v0/<digest(path)>.msgpack`
1120    ///
1121    /// # Example
1122    ///
1123    /// The contents of each of the `MsgPack` files has a timestamp field in unix time, the [PEP 508]
1124    /// markers and some information from the `sys`/`sysconfig` modules.
1125    ///
1126    /// ```json
1127    /// {
1128    ///   "timestamp": 1698047994491,
1129    ///   "data": {
1130    ///     "markers": {
1131    ///       "implementation_name": "cpython",
1132    ///       "implementation_version": "3.12.0",
1133    ///       "os_name": "posix",
1134    ///       "platform_machine": "x86_64",
1135    ///       "platform_python_implementation": "CPython",
1136    ///       "platform_release": "6.5.0-13-generic",
1137    ///       "platform_system": "Linux",
1138    ///       "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov  3 12:16:05 UTC 2023",
1139    ///       "python_full_version": "3.12.0",
1140    ///       "python_version": "3.12",
1141    ///       "sys_platform": "linux"
1142    ///     },
1143    ///     "base_exec_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1144    ///     "base_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1145    ///     "sys_executable": "/home/ferris/projects/uv/.venv/bin/python"
1146    ///   }
1147    /// }
1148    /// ```
1149    ///
1150    /// [PEP 508]: https://peps.python.org/pep-0508/#environment-markers
1151    Interpreter,
1152    /// Index responses through the simple metadata API.
1153    ///
1154    /// Cache structure:
1155    ///  * `simple-v0/pypi/<package_name>.rkyv`
1156    ///  * `simple-v0/<digest(index_url)>/<package_name>.rkyv`
1157    ///
1158    /// The response is parsed into `uv_client::SimpleDetailMetadata` before storage.
1159    Simple,
1160    /// A cache of unzipped wheels, stored as directories. This is used internally within the cache.
1161    /// When other buckets need to store directories, they should persist them to
1162    /// [`CacheBucket::Archive`], and then symlink them into the appropriate bucket. This ensures
1163    /// that cache entries can be atomically replaced and removed, as storing directories in the
1164    /// other buckets directly would make atomic operations impossible.
1165    Archive,
1166    /// Ephemeral virtual environments used to execute PEP 517 builds and other operations.
1167    Builds,
1168    /// Reusable virtual environments used to invoke Python tools.
1169    Environments,
1170    /// Cached Python downloads
1171    Python,
1172    /// Downloaded tool binaries (e.g., Ruff).
1173    Binaries,
1174    /// Cached vulnerability data from [OSV](https://osv.dev/).
1175    ///
1176    /// Cache structure:
1177    ///  * `osv-v0/vulnerability/<vuln_id>.msgpack` — cached full vulnerability records
1178    Osv,
1179}
1180
1181impl CacheBucket {
1182    fn to_str(self) -> &'static str {
1183        match self {
1184            // Note that when bumping this, you'll also need to bump it
1185            // in `crates/uv/tests/it/cache_prune.rs`.
1186            Self::SourceDistributions => "sdists-v9",
1187            Self::FlatIndex => "flat-index-v2",
1188            Self::Git => "git-v0",
1189            Self::Interpreter => "interpreter-v4",
1190            // Note that when bumping this, you'll also need to bump it
1191            // in `crates/uv/tests/it/cache_clean.rs`.
1192            Self::Simple => "simple-v21",
1193            // Note that when bumping this, you'll also need to bump it
1194            // in `crates/uv/tests/it/cache_prune.rs`.
1195            Self::Wheels => "wheels-v6",
1196            // Note that when bumping this, you'll also need to bump
1197            // `ARCHIVE_VERSION` in `crates/uv-cache/src/lib.rs`.
1198            Self::Archive => "archive-v0",
1199            Self::Builds => "builds-v0",
1200            Self::Environments => "environments-v2",
1201            Self::Python => "python-v0",
1202            Self::Binaries => "binaries-v0",
1203            Self::Osv => "osv-v0",
1204        }
1205    }
1206
1207    /// Remove a package from the cache bucket.
1208    ///
1209    /// Returns the number of entries removed from the cache.
1210    fn remove(self, cache: &Cache, name: &PackageName) -> Result<Removal, io::Error> {
1211        /// Returns `true` if the [`Path`] represents a built wheel for the given package.
1212        fn is_match(path: &Path, name: &PackageName) -> bool {
1213            let Ok(metadata) = fs_err::read(path.join("metadata.msgpack")) else {
1214                return false;
1215            };
1216            let Ok(metadata) = rmp_serde::from_slice::<ResolutionMetadata>(&metadata) else {
1217                return false;
1218            };
1219            metadata.name == *name
1220        }
1221
1222        let mut summary = Removal::default();
1223        match self {
1224            Self::Wheels => {
1225                // For `pypi` wheels, we expect a directory per package (indexed by name).
1226                let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1227                summary += rm_rf(root.join(name.to_string()))?;
1228
1229                // For alternate indices, we expect a directory for every index (under an `index`
1230                // subdirectory), followed by a directory per package (indexed by name).
1231                let root = cache.bucket(self).join(WheelCacheKind::Index);
1232                for directory in directories(root)? {
1233                    summary += rm_rf(directory.join(name.to_string()))?;
1234                }
1235
1236                // For direct URLs, we expect a directory for every URL, followed by a
1237                // directory per package (indexed by name).
1238                let root = cache.bucket(self).join(WheelCacheKind::Url);
1239                for directory in directories(root)? {
1240                    summary += rm_rf(directory.join(name.to_string()))?;
1241                }
1242            }
1243            Self::SourceDistributions => {
1244                // For `pypi` wheels, we expect a directory per package (indexed by name).
1245                let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1246                summary += rm_rf(root.join(name.to_string()))?;
1247
1248                // For alternate indices, we expect a directory for every index (under an `index`
1249                // subdirectory), followed by a directory per package (indexed by name).
1250                let root = cache.bucket(self).join(WheelCacheKind::Index);
1251                for directory in directories(root)? {
1252                    summary += rm_rf(directory.join(name.to_string()))?;
1253                }
1254
1255                // For direct URLs, we expect a directory for every URL, followed by a
1256                // directory per version. To determine whether the URL is relevant, we need to
1257                // search for a wheel matching the package name.
1258                let root = cache.bucket(self).join(WheelCacheKind::Url);
1259                for url in directories(root)? {
1260                    if directories(&url)?.any(|version| is_match(&version, name)) {
1261                        summary += rm_rf(url)?;
1262                    }
1263                }
1264
1265                // For local dependencies, we expect a directory for every path, followed by a
1266                // directory per version. To determine whether the path is relevant, we need to
1267                // search for a wheel matching the package name.
1268                let root = cache.bucket(self).join(WheelCacheKind::Path);
1269                for path in directories(root)? {
1270                    if directories(&path)?.any(|version| is_match(&version, name)) {
1271                        summary += rm_rf(path)?;
1272                    }
1273                }
1274
1275                // For Git dependencies, we expect a directory for every repository, followed by a
1276                // directory for every SHA. To determine whether the SHA is relevant, we need to
1277                // search for a wheel matching the package name.
1278                let root = cache.bucket(self).join(WheelCacheKind::Git);
1279                for repository in directories(root)? {
1280                    for sha in directories(repository)? {
1281                        if is_match(&sha, name) {
1282                            summary += rm_rf(sha)?;
1283                        }
1284                    }
1285                }
1286            }
1287            Self::Simple => {
1288                // For `pypi` wheels, we expect a rkyv file per package, indexed by name.
1289                let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1290                summary += rm_rf(root.join(format!("{name}.rkyv")))?;
1291
1292                // For alternate indices, we expect a directory for every index (under an `index`
1293                // subdirectory), followed by a directory per package (indexed by name).
1294                let root = cache.bucket(self).join(WheelCacheKind::Index);
1295                for directory in directories(root)? {
1296                    summary += rm_rf(directory.join(format!("{name}.rkyv")))?;
1297                }
1298            }
1299            Self::FlatIndex => {
1300                // We can't know if the flat index includes a package, so we just remove the entire
1301                // cache entry.
1302                let root = cache.bucket(self);
1303                summary += rm_rf(root)?;
1304            }
1305            Self::Git
1306            | Self::Interpreter
1307            | Self::Archive
1308            | Self::Builds
1309            | Self::Environments
1310            | Self::Python
1311            | Self::Binaries
1312            | Self::Osv => {
1313                // Nothing to do.
1314            }
1315        }
1316        Ok(summary)
1317    }
1318
1319    /// Return an iterator over all cache buckets.
1320    fn iter() -> impl Iterator<Item = Self> {
1321        [
1322            Self::Wheels,
1323            Self::SourceDistributions,
1324            Self::FlatIndex,
1325            Self::Git,
1326            Self::Interpreter,
1327            Self::Simple,
1328            Self::Archive,
1329            Self::Builds,
1330            Self::Environments,
1331            Self::Binaries,
1332            Self::Osv,
1333        ]
1334        .iter()
1335        .copied()
1336    }
1337}
1338
1339impl Display for CacheBucket {
1340    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1341        f.write_str(self.to_str())
1342    }
1343}
1344
1345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1346pub enum Freshness {
1347    /// The cache entry is fresh according to the [`Refresh`] policy.
1348    Fresh,
1349    /// The cache entry is stale according to the [`Refresh`] policy.
1350    Stale,
1351    /// The cache entry does not exist.
1352    Missing,
1353}
1354
1355impl Freshness {
1356    pub const fn is_fresh(self) -> bool {
1357        matches!(self, Self::Fresh)
1358    }
1359}
1360
1361/// A refresh policy for cache entries.
1362#[derive(Debug, Clone)]
1363pub enum Refresh {
1364    /// Don't refresh any entries.
1365    None(Timestamp),
1366    /// Refresh entries linked to the given packages, if created before the given timestamp.
1367    Packages(Vec<PackageName>, Vec<Box<Path>>, Timestamp),
1368    /// Refresh all entries created before the given timestamp.
1369    All(Timestamp),
1370}
1371
1372impl Refresh {
1373    /// Determine the refresh strategy to use based on the command-line arguments.
1374    pub fn from_args(refresh: Option<bool>, refresh_package: Vec<PackageName>) -> Self {
1375        let timestamp = Timestamp::now();
1376        match refresh {
1377            Some(true) => Self::All(timestamp),
1378            Some(false) => Self::None(timestamp),
1379            None => {
1380                if refresh_package.is_empty() {
1381                    Self::None(timestamp)
1382                } else {
1383                    Self::Packages(refresh_package, vec![], timestamp)
1384                }
1385            }
1386        }
1387    }
1388
1389    /// Combine two [`Refresh`] policies, taking the "max" of the two policies.
1390    #[must_use]
1391    pub fn combine(self, other: Self) -> Self {
1392        match (self, other) {
1393            // If the policy is `None`, return the existing refresh policy.
1394            // Take the `max` of the two timestamps.
1395            (Self::None(t1), Self::None(t2)) => Self::None(t1.max(t2)),
1396            (Self::None(t1), Self::All(t2)) => Self::All(t1.max(t2)),
1397            (Self::None(t1), Self::Packages(packages, paths, t2)) => {
1398                Self::Packages(packages, paths, t1.max(t2))
1399            }
1400
1401            // If the policy is `All`, refresh all packages.
1402            (Self::All(t1), Self::None(t2) | Self::All(t2) | Self::Packages(.., t2)) => {
1403                Self::All(t1.max(t2))
1404            }
1405
1406            // If the policy is `Packages`, take the "max" of the two policies.
1407            (Self::Packages(packages, paths, t1), Self::None(t2)) => {
1408                Self::Packages(packages, paths, t1.max(t2))
1409            }
1410            (Self::Packages(.., t1), Self::All(t2)) => Self::All(t1.max(t2)),
1411            (Self::Packages(packages1, paths1, t1), Self::Packages(packages2, paths2, t2)) => {
1412                Self::Packages(
1413                    packages1.into_iter().chain(packages2).collect(),
1414                    paths1.into_iter().chain(paths2).collect(),
1415                    t1.max(t2),
1416                )
1417            }
1418        }
1419    }
1420}
1421
1422#[cfg(test)]
1423mod tests {
1424    use std::str::FromStr;
1425
1426    use crate::ArchiveId;
1427
1428    use super::Link;
1429
1430    #[test]
1431    fn test_link_round_trip() {
1432        let id = ArchiveId::new();
1433        let link = Link::new(id);
1434        let s = link.to_string();
1435        let parsed = Link::from_str(&s).unwrap();
1436        assert_eq!(link.id, parsed.id);
1437        assert_eq!(link.version, parsed.version);
1438    }
1439
1440    #[test]
1441    fn test_link_deserialize() {
1442        assert!(Link::from_str("archive-v0/foo").is_ok());
1443        assert!(Link::from_str("archive/foo").is_err());
1444        assert!(Link::from_str("v1/foo").is_err());
1445        assert!(Link::from_str("archive-v0/").is_err());
1446    }
1447}