[go: up one dir, main page]

uv-cache-key 0.0.6

This is an internal component crate of uv
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use std::borrow::Cow;
use std::fmt::{Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;

use url::Url;
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};

use crate::cache_key::{CacheKey, CacheKeyHasher};

/// A wrapper around `Url` which represents a "canonical" version of an original URL.
///
/// A "canonical" url is only intended for internal comparison purposes. It's to help paper over
/// mistakes such as depending on `github.com/foo/bar` vs. `github.com/foo/bar.git`.
///
/// This is **only** for internal purposes and provides no means to actually read the underlying
/// string value of the `Url` it contains. This is intentional, because all fetching should still
/// happen within the context of the original URL.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct CanonicalUrl(DisplaySafeUrl);

impl CanonicalUrl {
    pub fn new(url: &DisplaySafeUrl) -> Self {
        let mut url = url.clone();

        // If the URL cannot be a base, then it's not a valid URL anyway.
        if url.cannot_be_a_base() {
            return Self(url);
        }

        // Strip credentials.
        let _ = url.set_password(None);
        let _ = url.set_username("");

        // Strip a trailing slash.
        if url.path().ends_with('/') {
            url.path_segments_mut().unwrap().pop_if_empty();
        }

        // For GitHub URLs specifically, just lower-case everything. GitHub
        // treats both the same, but they hash differently, and we're gonna be
        // hashing them. This wants a more general solution, and also we're
        // almost certainly not using the same case conversion rules that GitHub
        // does. (See issue #84)
        if url.host_str() == Some("github.com") {
            let scheme = url.scheme().to_lowercase();
            url.set_scheme(&scheme).unwrap();
            let path = url.path().to_lowercase();
            url.set_path(&path);
        }

        // Repos can generally be accessed with or without `.git` extension.
        if let Some((prefix, suffix)) = url.path().rsplit_once('@') {
            // Ex) `git+https://github.com/pypa/sample-namespace-packages.git@2.0.0`
            let needs_chopping = std::path::Path::new(prefix)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("git"));
            if needs_chopping {
                let prefix = &prefix[..prefix.len() - 4];
                let path = format!("{prefix}@{suffix}");
                url.set_path(&path);
            }
        } else {
            // Ex) `git+https://github.com/pypa/sample-namespace-packages.git`
            let needs_chopping = std::path::Path::new(url.path())
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("git"));
            if needs_chopping {
                let last = {
                    // Unwrap safety: We checked `url.cannot_be_a_base()`, and `url.path()` having
                    // an extension implies at least one segment.
                    let last = url.path_segments().unwrap().next_back().unwrap();
                    last[..last.len() - 4].to_owned()
                };
                url.path_segments_mut().unwrap().pop().push(&last);
            }
        }

        // Decode any percent-encoded characters in the path.
        if memchr::memchr(b'%', url.path().as_bytes()).is_some() {
            // Unwrap safety: We checked `url.cannot_be_a_base()`.
            let decoded = url
                .path_segments()
                .unwrap()
                .map(|segment| {
                    percent_encoding::percent_decode_str(segment)
                        .decode_utf8()
                        .unwrap_or(Cow::Borrowed(segment))
                        .into_owned()
                })
                .collect::<Vec<_>>();

            let mut path_segments = url.path_segments_mut().unwrap();
            path_segments.clear();
            path_segments.extend(decoded);
        }

        Self(url)
    }

    pub fn parse(url: &str) -> Result<Self, DisplaySafeUrlError> {
        Ok(Self::new(&DisplaySafeUrl::parse(url)?))
    }
}

impl CacheKey for CanonicalUrl {
    fn cache_key(&self, state: &mut CacheKeyHasher) {
        // `as_str` gives the serialisation of a url (which has a spec) and so insulates against
        // possible changes in how the URL crate does hashing.
        self.0.as_str().cache_key(state);
    }
}

impl Hash for CanonicalUrl {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // `as_str` gives the serialisation of a url (which has a spec) and so insulates against
        // possible changes in how the URL crate does hashing.
        self.0.as_str().hash(state);
    }
}

impl From<CanonicalUrl> for DisplaySafeUrl {
    fn from(value: CanonicalUrl) -> Self {
        value.0
    }
}

impl std::fmt::Display for CanonicalUrl {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.0, f)
    }
}

/// Like [`CanonicalUrl`], but attempts to represent an underlying source repository, abstracting
/// away details like the specific commit or branch, or the subdirectory to build within the
/// repository.
///
/// For example, `https://github.com/pypa/package.git#subdirectory=pkg_a` and
/// `https://github.com/pypa/package.git#subdirectory=pkg_b` would map to different
/// [`CanonicalUrl`] values, but the same [`RepositoryUrl`], since they map to the same
/// resource.
///
/// The additional information it holds should only be used to discriminate between
/// sources that hold the exact same commit in their canonical representation,
/// but may differ in the contents such as when Git LFS is enabled.
///
/// A different cache key will be computed when Git LFS is enabled.
/// When Git LFS is `false` or `None`, the cache key remains unchanged.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct RepositoryUrl {
    repo_url: DisplaySafeUrl,
    with_lfs: Option<bool>,
}

impl RepositoryUrl {
    pub fn new(url: &DisplaySafeUrl) -> Self {
        let mut url = CanonicalUrl::new(url).0;

        // If a Git URL ends in a reference (like a branch, tag, or commit), remove it.
        if url.scheme().starts_with("git+") {
            if let Some(prefix) = url
                .path()
                .rsplit_once('@')
                .map(|(prefix, _suffix)| prefix.to_string())
            {
                url.set_path(&prefix);
            }
        }

        // Drop any fragments and query parameters.
        url.set_fragment(None);
        url.set_query(None);

        Self {
            repo_url: url,
            with_lfs: None,
        }
    }

    pub fn parse(url: &str) -> Result<Self, DisplaySafeUrlError> {
        Ok(Self::new(&DisplaySafeUrl::parse(url)?))
    }

    #[must_use]
    pub fn with_lfs(mut self, lfs: Option<bool>) -> Self {
        self.with_lfs = lfs;
        self
    }
}

impl CacheKey for RepositoryUrl {
    fn cache_key(&self, state: &mut CacheKeyHasher) {
        // `as_str` gives the serialisation of a url (which has a spec) and so insulates against
        // possible changes in how the URL crate does hashing.
        self.repo_url.as_str().cache_key(state);
        if let Some(true) = self.with_lfs {
            1u8.cache_key(state);
        }
    }
}

impl Hash for RepositoryUrl {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // `as_str` gives the serialisation of a url (which has a spec) and so insulates against
        // possible changes in how the URL crate does hashing.
        self.repo_url.as_str().hash(state);
        if let Some(true) = self.with_lfs {
            1u8.hash(state);
        }
    }
}

impl Deref for RepositoryUrl {
    type Target = Url;

    fn deref(&self) -> &Self::Target {
        &self.repo_url
    }
}

impl std::fmt::Display for RepositoryUrl {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.repo_url, f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn user_credential_does_not_affect_cache_key() -> Result<(), DisplaySafeUrlError> {
        let mut hasher = CacheKeyHasher::new();
        CanonicalUrl::parse("https://example.com/pypa/sample-namespace-packages.git@2.0.0")?
            .cache_key(&mut hasher);
        let hash_without_creds = hasher.finish();

        let mut hasher = CacheKeyHasher::new();
        CanonicalUrl::parse(
            "https://user:foo@example.com/pypa/sample-namespace-packages.git@2.0.0",
        )?
        .cache_key(&mut hasher);
        let hash_with_creds = hasher.finish();
        assert_eq!(
            hash_without_creds, hash_with_creds,
            "URLs with no user credentials should hash the same as URLs with different user credentials",
        );

        let mut hasher = CacheKeyHasher::new();
        CanonicalUrl::parse(
            "https://user:bar@example.com/pypa/sample-namespace-packages.git@2.0.0",
        )?
        .cache_key(&mut hasher);
        let hash_with_creds = hasher.finish();
        assert_eq!(
            hash_without_creds, hash_with_creds,
            "URLs with different user credentials should hash the same",
        );

        let mut hasher = CacheKeyHasher::new();
        CanonicalUrl::parse("https://:bar@example.com/pypa/sample-namespace-packages.git@2.0.0")?
            .cache_key(&mut hasher);
        let hash_with_creds = hasher.finish();
        assert_eq!(
            hash_without_creds, hash_with_creds,
            "URLs with no username, though with a password, should hash the same as URLs with different user credentials",
        );

        let mut hasher = CacheKeyHasher::new();
        CanonicalUrl::parse("https://user:@example.com/pypa/sample-namespace-packages.git@2.0.0")?
            .cache_key(&mut hasher);
        let hash_with_creds = hasher.finish();
        assert_eq!(
            hash_without_creds, hash_with_creds,
            "URLs with no password, though with a username, should hash the same as URLs with different user credentials",
        );

        Ok(())
    }

    #[test]
    fn canonical_url() -> Result<(), DisplaySafeUrlError> {
        // Two URLs should be considered equal regardless of the `.git` suffix.
        assert_eq!(
            CanonicalUrl::parse("git+https://github.com/pypa/sample-namespace-packages.git")?,
            CanonicalUrl::parse("git+https://github.com/pypa/sample-namespace-packages")?,
        );

        // Two URLs should be considered equal regardless of the `.git` suffix.
        assert_eq!(
            CanonicalUrl::parse("git+https://github.com/pypa/sample-namespace-packages.git@2.0.0")?,
            CanonicalUrl::parse("git+https://github.com/pypa/sample-namespace-packages@2.0.0")?,
        );

        // Two URLs should be _not_ considered equal if they point to different repositories.
        assert_ne!(
            CanonicalUrl::parse("git+https://github.com/pypa/sample-namespace-packages.git")?,
            CanonicalUrl::parse("git+https://github.com/pypa/sample-packages.git")?,
        );

        // Two URLs should _not_ be considered equal if they request different subdirectories.
        assert_ne!(
            CanonicalUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git#subdirectory=pkg_resources/pkg_a"
            )?,
            CanonicalUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git#subdirectory=pkg_resources/pkg_b"
            )?,
        );

        // Two URLs should _not_ be considered equal if they differ in Git LFS enablement.
        assert_ne!(
            CanonicalUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git#lfs=true"
            )?,
            CanonicalUrl::parse("git+https://github.com/pypa/sample-namespace-packages.git")?,
        );

        // Two URLs should _not_ be considered equal if they request different commit tags.
        assert_ne!(
            CanonicalUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git@v1.0.0"
            )?,
            CanonicalUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git@v2.0.0"
            )?,
        );

        // Two URLs that cannot be a base should be considered equal.
        assert_eq!(
            CanonicalUrl::parse("git+https:://github.com/pypa/sample-namespace-packages.git")?,
            CanonicalUrl::parse("git+https:://github.com/pypa/sample-namespace-packages.git")?,
        );

        // Two URLs should _not_ be considered equal based on percent-decoding slashes.
        assert_ne!(
            CanonicalUrl::parse("https://github.com/pypa/sample%2Fnamespace%2Fpackages")?,
            CanonicalUrl::parse("https://github.com/pypa/sample/namespace/packages")?,
        );

        // Two URLs should be considered equal regardless of percent-encoding.
        assert_eq!(
            CanonicalUrl::parse("https://github.com/pypa/sample%2Bnamespace%2Bpackages")?,
            CanonicalUrl::parse("https://github.com/pypa/sample+namespace+packages")?,
        );

        // Two URLs should _not_ be considered equal based on percent-decoding slashes.
        assert_ne!(
            CanonicalUrl::parse(
                "file:///home/ferris/my_project%2Fmy_project-0.1.0-py3-none-any.whl"
            )?,
            CanonicalUrl::parse(
                "file:///home/ferris/my_project/my_project-0.1.0-py3-none-any.whl"
            )?,
        );

        // Two URLs should be considered equal regardless of percent-encoding.
        assert_eq!(
            CanonicalUrl::parse(
                "file:///home/ferris/my_project/my_project-0.1.0+foo-py3-none-any.whl"
            )?,
            CanonicalUrl::parse(
                "file:///home/ferris/my_project/my_project-0.1.0%2Bfoo-py3-none-any.whl"
            )?,
        );

        Ok(())
    }

    #[test]
    fn repository_url() -> Result<(), DisplaySafeUrlError> {
        // Two URLs should be considered equal regardless of the `.git` suffix.
        assert_eq!(
            RepositoryUrl::parse("git+https://github.com/pypa/sample-namespace-packages.git")?,
            RepositoryUrl::parse("git+https://github.com/pypa/sample-namespace-packages")?,
        );

        // Two URLs should be considered equal regardless of the `.git` suffix.
        assert_eq!(
            RepositoryUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git@2.0.0"
            )?,
            RepositoryUrl::parse("git+https://github.com/pypa/sample-namespace-packages@2.0.0")?,
        );

        // Two URLs should be _not_ considered equal if they point to different repositories.
        assert_ne!(
            RepositoryUrl::parse("git+https://github.com/pypa/sample-namespace-packages.git")?,
            RepositoryUrl::parse("git+https://github.com/pypa/sample-packages.git")?,
        );

        // Two URLs should be considered equal if they map to the same repository, even if they
        // request different subdirectories.
        assert_eq!(
            RepositoryUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git#subdirectory=pkg_resources/pkg_a"
            )?,
            RepositoryUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git#subdirectory=pkg_resources/pkg_b"
            )?,
        );

        // Two URLs should be considered equal if they map to the same repository, even if they
        // request different commit tags.
        assert_eq!(
            RepositoryUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git@v1.0.0"
            )?,
            RepositoryUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git@v2.0.0"
            )?,
        );

        // Two URLs should be considered equal if they map to the same repository, even if they
        // differ in Git LFS enablement.
        assert_eq!(
            RepositoryUrl::parse(
                "git+https://github.com/pypa/sample-namespace-packages.git#lfs=true"
            )?,
            RepositoryUrl::parse("git+https://github.com/pypa/sample-namespace-packages.git")?,
        );

        Ok(())
    }

    #[test]
    fn repository_url_with_lfs() -> Result<(), DisplaySafeUrlError> {
        let mut hasher = CacheKeyHasher::new();
        RepositoryUrl::parse("https://example.com/pypa/sample-namespace-packages.git@2.0.0")?
            .cache_key(&mut hasher);
        let repo_url_basic = hasher.finish();

        let mut hasher = CacheKeyHasher::new();
        RepositoryUrl::parse(
            "https://user:foo@example.com/pypa/sample-namespace-packages.git@2.0.0#foo=bar",
        )?
        .cache_key(&mut hasher);
        let repo_url_with_fragments = hasher.finish();

        assert_eq!(
            repo_url_basic, repo_url_with_fragments,
            "repository urls should have the exact cache keys as fragments are removed",
        );

        let mut hasher = CacheKeyHasher::new();
        RepositoryUrl::parse(
            "https://user:foo@example.com/pypa/sample-namespace-packages.git@2.0.0#foo=bar",
        )?
        .with_lfs(None)
        .cache_key(&mut hasher);
        let git_url_with_fragments = hasher.finish();

        assert_eq!(
            repo_url_with_fragments, git_url_with_fragments,
            "both structs should have the exact cache keys as fragments are still removed",
        );

        let mut hasher = CacheKeyHasher::new();
        RepositoryUrl::parse(
            "https://user:foo@example.com/pypa/sample-namespace-packages.git@2.0.0#foo=bar",
        )?
        .with_lfs(Some(false))
        .cache_key(&mut hasher);
        let git_url_with_fragments_and_lfs_false = hasher.finish();

        assert_eq!(
            git_url_with_fragments, git_url_with_fragments_and_lfs_false,
            "both structs should have the exact cache keys as lfs false should not influence them",
        );

        let mut hasher = CacheKeyHasher::new();
        RepositoryUrl::parse(
            "https://user:foo@example.com/pypa/sample-namespace-packages.git@2.0.0#foo=bar",
        )?
        .with_lfs(Some(true))
        .cache_key(&mut hasher);
        let git_url_with_fragments_and_lfs_true = hasher.finish();

        assert_ne!(
            git_url_with_fragments, git_url_with_fragments_and_lfs_true,
            "both structs should have different cache keys as one has Git LFS enabled",
        );

        Ok(())
    }
}