uv-distribution 0.0.90

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
use std::fmt;
use std::path::PathBuf;

use owo_colors::OwoColorize;
use tokio::task::JoinError;

use crate::metadata::MetadataError;
use uv_cache::Error as CacheError;
use uv_client::WrappedReqwestError;
use uv_distribution_filename::{WheelFilename, WheelFilenameError};
use uv_distribution_types::{InstalledDist, InstalledDistError, IsBuildBackendError};
use uv_fs::Simplified;
use uv_git::GitError;
use uv_normalize::PackageName;
use uv_pep440::{Version, VersionSpecifiers};
use uv_platform_tags::Platform;
use uv_pypi_types::{HashAlgorithm, HashDigest};
use uv_python::PythonVariant;
use uv_redacted::DisplaySafeUrl;
use uv_types::AnyErrorBuild;

#[derive(Debug, Clone, Copy)]
pub struct PythonVersion {
    pub(crate) version: (u8, u8),
    pub(crate) variant: PythonVariant,
}

impl fmt::Display for PythonVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (major, minor) = self.version;
        write!(f, "{major}.{minor}{}", self.variant.executable_suffix())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("Building source distributions is disabled")]
    NoBuild,
    #[error("Building source distributions for `{0}` is disabled")]
    NoBuildPackage(PackageName),

    // Network error
    #[error(transparent)]
    InvalidUrl(#[from] uv_distribution_types::ToUrlError),
    #[error("Expected a file URL, but received: {0}")]
    NonFileUrl(DisplaySafeUrl),
    #[error(transparent)]
    Git(#[from] uv_git::GitResolverError),
    #[error(transparent)]
    Reqwest(#[from] WrappedReqwestError),
    #[error(transparent)]
    Client(#[from] uv_client::Error),
    #[error(transparent)]
    ClientBuild(#[from] uv_client::ClientBuildError),

    // Cache writing error
    #[error("Failed to read from the distribution cache")]
    CacheRead(#[source] std::io::Error),
    #[error("Failed to write to the distribution cache")]
    CacheWrite(#[source] std::io::Error),
    #[error("Failed to acquire lock on the distribution cache")]
    CacheLock(#[source] CacheError),
    #[error("Failed to deserialize cache entry")]
    CacheDecode(#[from] rmp_serde::decode::Error),
    #[error("Failed to serialize cache entry")]
    CacheEncode(#[from] rmp_serde::encode::Error),
    #[error("Failed to walk the distribution cache")]
    CacheWalk(#[source] walkdir::Error),
    #[error(transparent)]
    CacheInfo(#[from] uv_cache_info::CacheInfoError),

    // Build error
    #[error(transparent)]
    Build(AnyErrorBuild),
    #[error("Built wheel has an invalid filename")]
    WheelFilename(#[from] WheelFilenameError),
    #[error("Package metadata name `{metadata}` does not match given name `{given}`")]
    WheelMetadataNameMismatch {
        given: PackageName,
        metadata: PackageName,
    },
    #[error("Package metadata version `{metadata}` does not match given version `{given}`")]
    WheelMetadataVersionMismatch { given: Version, metadata: Version },
    #[error(
        "Package metadata name `{metadata}` does not match `{filename}` from the wheel filename"
    )]
    WheelFilenameNameMismatch {
        filename: PackageName,
        metadata: PackageName,
    },
    #[error(
        "Package metadata version `{metadata}` does not match `{filename}` from the wheel filename"
    )]
    WheelFilenameVersionMismatch {
        filename: Version,
        metadata: Version,
    },
    /// This shouldn't happen, it's a bug in the build backend.
    #[error(
        "The built wheel `{}` is not compatible with the current Python {} on {}",
        filename,
        python_version,
        python_platform.pretty(),
    )]
    BuiltWheelIncompatibleHostPlatform {
        filename: WheelFilename,
        python_platform: Platform,
        python_version: PythonVersion,
    },
    /// This may happen when trying to cross-install native dependencies without their build backend
    /// being aware that the target is a cross-install.
    #[error(
        "The built wheel `{}` is not compatible with the target Python {} on {}. Consider using `--no-build` to disable building wheels.",
        filename,
        python_version,
        python_platform.pretty(),
    )]
    BuiltWheelIncompatibleTargetPlatform {
        filename: WheelFilename,
        python_platform: Platform,
        python_version: PythonVersion,
    },
    #[error("Failed to parse metadata from built wheel")]
    Metadata(#[from] uv_pypi_types::MetadataError),
    #[error("Failed to read metadata: {}", _0.user_display())]
    WheelMetadata(PathBuf, #[source] Box<uv_metadata::Error>),
    #[error("Failed to read metadata from installed package `{0}`")]
    ReadInstalled(Box<InstalledDist>, #[source] InstalledDistError),
    #[error("Failed to extract archive: {0}")]
    Extract(String, #[source] uv_extract::Error),
    #[error("The source distribution is missing a `PKG-INFO` file")]
    MissingPkgInfo,
    #[error("The source distribution `{}` has no subdirectory `{}`", _0, _1.display())]
    MissingSubdirectory(DisplaySafeUrl, PathBuf),
    #[error("The source distribution `{0}` is missing Git LFS artifacts.")]
    MissingSourceDistGitLfsArtifacts(DisplaySafeUrl, #[source] GitError),
    #[error("The wheel `{0}` is missing Git LFS artifacts.")]
    MissingWheelGitLfsArtifacts(DisplaySafeUrl, #[source] GitError),
    #[error("Failed to extract static metadata from `PKG-INFO`")]
    PkgInfo(#[source] uv_pypi_types::MetadataError),
    #[error("The source distribution is missing a `pyproject.toml` file")]
    MissingPyprojectToml,
    #[error("Failed to extract static metadata from `pyproject.toml`")]
    PyprojectToml(#[source] uv_pypi_types::MetadataError),
    #[error(transparent)]
    MetadataLowering(#[from] MetadataError),
    #[error("Distribution not found at: {0}")]
    NotFound(DisplaySafeUrl),
    #[error("Attempted to re-extract the source distribution for `{}`, but the {} hash didn't match. Run `{}` to clear the cache.", _0, _1, "uv cache clean".green())]
    CacheHeal(String, HashAlgorithm),
    #[error("The source distribution requires Python {0}, but {1} is installed")]
    RequiresPython(VersionSpecifiers, Version),
    #[error("Failed to identify base Python interpreter")]
    BaseInterpreter(#[source] std::io::Error),

    /// A generic request middleware error happened while making a request.
    /// Refer to the error message for more details.
    #[error(transparent)]
    ReqwestMiddlewareError(#[from] anyhow::Error),

    /// Should not occur; only seen when another task panicked.
    #[error("The task executor is broken, did some other task panic?")]
    Join(#[from] JoinError),

    /// An I/O error that occurs while exhausting a reader to compute a hash.
    #[error("Failed to hash distribution")]
    HashExhaustion(#[source] std::io::Error),

    #[error("Hash mismatch for `{distribution}`\n\nExpected:\n{expected}\n\nComputed:\n{actual}")]
    MismatchedHashes {
        distribution: String,
        expected: String,
        actual: String,
    },

    #[error(
        "Size mismatch for `{distribution}`: expected {expected} bytes, but downloaded {actual} bytes"
    )]
    MismatchedSize {
        distribution: String,
        expected: u64,
        actual: u64,
    },

    #[error(
        "Content-Length mismatch for `{distribution}`: expected {expected} bytes, but the server advertised {actual} bytes"
    )]
    MismatchedContentLength {
        distribution: String,
        expected: u64,
        actual: u64,
    },

    #[error(
        "Range response size mismatch for `{distribution}`: expected {expected} bytes from Content-Range, but received {actual} bytes"
    )]
    MismatchedRangeSize {
        distribution: String,
        expected: u64,
        actual: u64,
    },

    #[error(
        "Hash-checking is enabled, but no hashes were provided or computed for: {distribution}"
    )]
    MissingHashes { distribution: String },

    #[error(
        "Hash-checking is enabled, but no hashes were computed for `{distribution}`\n\nExpected:\n{expected}"
    )]
    MissingActualHashes {
        distribution: String,
        expected: String,
    },

    #[error(
        "Hash-checking is enabled, but no hashes were provided for `{distribution}`\n\nComputed:\n{actual}"
    )]
    MissingExpectedHashes {
        distribution: String,
        actual: String,
    },

    #[error("Hash-checking is not supported for local directories: {0}")]
    HashesNotSupportedSourceTree(String),

    #[error("Hash-checking is not supported for Git repositories: {0}")]
    HashesNotSupportedGit(String),

    #[error(transparent)]
    InstallWheelError(uv_install_wheel::Error),
}

fn is_not_found_error(mut error: &(dyn std::error::Error + 'static)) -> bool {
    loop {
        if error
            .downcast_ref::<reqwest::Error>()
            .and_then(reqwest::Error::status)
            .is_some_and(|status| status == reqwest::StatusCode::NOT_FOUND)
        {
            return true;
        }
        let Some(source) = error.source() else {
            return false;
        };
        error = source;
    }
}

impl From<reqwest::Error> for Error {
    fn from(error: reqwest::Error) -> Self {
        Self::Reqwest(WrappedReqwestError::from(error))
    }
}

impl From<reqwest_middleware::Error> for Error {
    fn from(error: reqwest_middleware::Error) -> Self {
        match error {
            reqwest_middleware::Error::Middleware(error) => Self::ReqwestMiddlewareError(error),
            reqwest_middleware::Error::Reqwest(error) => {
                Self::Reqwest(WrappedReqwestError::from(error))
            }
        }
    }
}

impl uv_errors::Hinted for Error {
    fn hints(&self) -> uv_errors::Hints<'_> {
        match self {
            Self::Build(err) => err.hints(),
            Self::Client(err) => uv_errors::Hinted::hints(err),
            Self::MetadataLowering(err) => err.hints(),
            _ => uv_errors::Hints::none(),
        }
    }
}

impl IsBuildBackendError for Error {
    fn is_user_failure(&self) -> bool {
        Self::is_user_failure(self)
    }

    fn is_build_backend_error(&self) -> bool {
        match self {
            Self::Build(err) => err.is_build_backend_error(),
            _ => false,
        }
    }
}

impl Error {
    /// Return whether this is an expected user-facing failure.
    pub fn is_user_failure(&self) -> bool {
        match self {
            Self::NoBuild
            | Self::NoBuildPackage(_)
            | Self::InvalidUrl(_)
            | Self::NonFileUrl(_)
            | Self::WheelFilename(_)
            | Self::WheelMetadataNameMismatch { .. }
            | Self::WheelMetadataVersionMismatch { .. }
            | Self::WheelFilenameNameMismatch { .. }
            | Self::WheelFilenameVersionMismatch { .. }
            | Self::BuiltWheelIncompatibleHostPlatform { .. }
            | Self::BuiltWheelIncompatibleTargetPlatform { .. }
            | Self::Metadata(_)
            | Self::WheelMetadata(..)
            | Self::Extract(..)
            | Self::MissingPkgInfo
            | Self::MissingSubdirectory(..)
            | Self::MissingSourceDistGitLfsArtifacts(..)
            | Self::MissingWheelGitLfsArtifacts(..)
            | Self::PkgInfo(_)
            | Self::MissingPyprojectToml
            | Self::PyprojectToml(_)
            | Self::MetadataLowering(_)
            | Self::NotFound(_)
            | Self::RequiresPython(..)
            | Self::MismatchedHashes { .. }
            | Self::MismatchedSize { .. }
            | Self::MismatchedContentLength { .. }
            | Self::MismatchedRangeSize { .. }
            | Self::MissingHashes { .. }
            | Self::MissingActualHashes { .. }
            | Self::MissingExpectedHashes { .. }
            | Self::HashesNotSupportedSourceTree(_)
            | Self::HashesNotSupportedGit(_) => true,
            Self::Build(error) => error.is_user_failure(),
            Self::InstallWheelError(error) => error.is_user_failure(),
            Self::Git(error) => error.is_user_failure(),
            Self::Reqwest(error) => error.is_user_failure(),
            Self::Client(error) => error.is_user_failure(),
            Self::ClientBuild(error) => error.is_user_failure(),
            Self::CacheRead(_)
            | Self::CacheWrite(_)
            | Self::CacheLock(_)
            | Self::CacheDecode(_)
            | Self::CacheEncode(_)
            | Self::CacheWalk(_)
            | Self::CacheInfo(_)
            | Self::ReadInstalled(..)
            | Self::CacheHeal(..)
            | Self::BaseInterpreter(_)
            | Self::Join(_)
            | Self::HashExhaustion(_) => false,
            Self::ReqwestMiddlewareError(error) => is_not_found_error(error.as_ref()),
        }
    }

    /// Construct a hash mismatch error.
    pub fn hash_mismatch(
        distribution: String,
        expected: &[HashDigest],
        actual: &[HashDigest],
    ) -> Self {
        match (expected.is_empty(), actual.is_empty()) {
            (true, true) => Self::MissingHashes { distribution },
            (true, false) => {
                let actual = actual
                    .iter()
                    .map(|hash| format!("  {hash}"))
                    .collect::<Vec<_>>()
                    .join("\n");

                Self::MissingExpectedHashes {
                    distribution,
                    actual,
                }
            }
            (false, true) => {
                let expected = expected
                    .iter()
                    .map(|hash| format!("  {hash}"))
                    .collect::<Vec<_>>()
                    .join("\n");

                Self::MissingActualHashes {
                    distribution,
                    expected,
                }
            }
            (false, false) => {
                let expected = expected
                    .iter()
                    .map(|hash| format!("  {hash}"))
                    .collect::<Vec<_>>()
                    .join("\n");

                let actual = actual
                    .iter()
                    .map(|hash| format!("  {hash}"))
                    .collect::<Vec<_>>()
                    .join("\n");

                Self::MismatchedHashes {
                    distribution,
                    expected,
                    actual,
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Error, PythonVersion};
    use std::str::FromStr;
    use uv_distribution_filename::WheelFilename;
    use uv_platform_tags::{Arch, Os, Platform};
    use uv_python::PythonVariant;

    #[test]
    fn built_wheel_error_formats_freethreaded_python() {
        let err = Error::BuiltWheelIncompatibleHostPlatform {
            filename: WheelFilename::from_str(
                "cryptography-47.0.0.dev1-cp315-abi3t-macosx_11_0_arm64.whl",
            )
            .unwrap(),
            python_platform: Platform::new(
                Os::Macos {
                    major: 11,
                    minor: 0,
                },
                Arch::Aarch64,
            ),
            python_version: PythonVersion {
                version: (3, 15),
                variant: PythonVariant::Freethreaded,
            },
        };

        assert_eq!(
            err.to_string(),
            "The built wheel `cryptography-47.0.0.dev1-cp315-abi3t-macosx_11_0_arm64.whl` is not compatible with the current Python 3.15t on macOS aarch64"
        );
    }

    #[test]
    fn built_wheel_error_formats_target_python() {
        let err = Error::BuiltWheelIncompatibleTargetPlatform {
            filename: WheelFilename::from_str("py313-0.1.0-py313-none-any.whl").unwrap(),
            python_platform: Platform::new(
                Os::Manylinux {
                    major: 2,
                    minor: 28,
                },
                Arch::X86_64,
            ),
            python_version: PythonVersion {
                version: (3, 12),
                variant: PythonVariant::Default,
            },
        };

        assert_eq!(
            err.to_string(),
            "The built wheel `py313-0.1.0-py313-none-any.whl` is not compatible with the target Python 3.12 on Linux x86_64. Consider using `--no-build` to disable building wheels."
        );
    }
}