1use std::path::{Path, PathBuf};
2
3use uv_cache_key::{CanonicalUrl, cache_digest};
4use uv_distribution_types::IndexUrl;
5use uv_redacted::SafeUrl;
6
7#[derive(Debug, Clone)]
9pub enum WheelCache<'a> {
10 Index(&'a IndexUrl),
12 Url(&'a SafeUrl),
14 Path(&'a SafeUrl),
16 Editable(&'a SafeUrl),
18 Git(&'a SafeUrl, &'a str),
23}
24
25impl WheelCache<'_> {
26 pub fn root(&self) -> PathBuf {
28 match self {
29 Self::Index(IndexUrl::Pypi(_)) => WheelCacheKind::Pypi.root(),
30 Self::Index(url) => WheelCacheKind::Index
31 .root()
32 .join(cache_digest(&CanonicalUrl::new(url.url().clone()))),
33 Self::Url(url) => WheelCacheKind::Url
34 .root()
35 .join(cache_digest(&CanonicalUrl::new((*url).clone()))),
36 Self::Path(url) => WheelCacheKind::Path
37 .root()
38 .join(cache_digest(&CanonicalUrl::new((*url).clone()))),
39 Self::Editable(url) => WheelCacheKind::Editable
40 .root()
41 .join(cache_digest(&CanonicalUrl::new((*url).clone()))),
42 Self::Git(url, sha) => WheelCacheKind::Git
43 .root()
44 .join(cache_digest(&CanonicalUrl::for_git_source((*url).clone())))
45 .join(sha),
46 }
47 }
48
49 pub fn wheel_dir(&self, package_name: impl AsRef<Path>) -> PathBuf {
51 self.root().join(package_name)
52 }
53}
54
55#[derive(Debug, Clone, Copy)]
56pub(crate) enum WheelCacheKind {
57 Pypi,
59 Index,
61 Url,
63 Path,
65 Editable,
67 Git,
69}
70
71impl WheelCacheKind {
72 fn to_str(self) -> &'static str {
73 match self {
74 Self::Pypi => "pypi",
75 Self::Index => "index",
76 Self::Url => "url",
77 Self::Path => "path",
78 Self::Editable => "editable",
79 Self::Git => "git",
80 }
81 }
82
83 fn root(self) -> PathBuf {
84 Path::new(self.to_str()).to_path_buf()
85 }
86}
87
88impl AsRef<Path> for WheelCacheKind {
89 fn as_ref(&self) -> &Path {
90 self.to_str().as_ref()
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use uv_redacted::SafeUrlError;
97
98 use super::*;
99
100 #[test]
101 fn direct_wheel_cache_paths_preserve_http_path_spelling() -> Result<(), SafeUrlError> {
102 let plain =
103 SafeUrl::parse("https://example.com/artifacts@channel/example-1.0-py3-none-any.whl")?;
104 let suffixed = SafeUrl::parse(
105 "https://example.com/artifacts.git@channel/example-1.0-py3-none-any.whl",
106 )?;
107 let plain_root = WheelCache::Url(&plain).root();
108 let suffixed_root = WheelCache::Url(&suffixed).root();
109 assert_ne!(plain_root, suffixed_root);
110
111 let escaped_at = SafeUrl::parse(
112 "https://example.com/artifacts.git%40channel/example-1.0-py3-none-any.whl",
113 )?;
114 let escaped_dot = SafeUrl::parse(
115 "https://example.com/artifacts%2Egit@channel/example-1.0-py3-none-any.whl",
116 )?;
117 assert_ne!(WheelCache::Url(&escaped_at).root(), suffixed_root);
118 assert_ne!(WheelCache::Url(&escaped_dot).root(), suffixed_root);
119 Ok(())
120 }
121}