uv-installer 0.0.69

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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::borrow::Cow;
use std::fmt::Debug;

use same_file::is_same_file;
use tracing::{debug, trace};
use url::Url;

use uv_cache_info::CacheInfo;
use uv_cache_key::{CanonicalUrl, RepositoryUrl};
use uv_distribution_filename::ExpandedTags;
use uv_distribution_types::{
    BuildInfo, BuildVariables, ConfigSettings, ExtraBuildRequirement, ExtraBuildRequires,
    ExtraBuildVariables, InstalledDirectUrlDist, InstalledDist, InstalledDistKind,
    PackageConfigSettings, RequirementSource,
};
use uv_git_types::{GitLfs, GitOid};
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_platform_tags::{AbiTag, IncompatibleTag, TagCompatibility, Tags};
use uv_pypi_types::{DirInfo, DirectUrl, VcsInfo, VcsKind};

use crate::InstallationStrategy;

#[derive(Debug, Copy, Clone)]
pub(crate) enum RequirementSatisfaction {
    Mismatch,
    Satisfied,
    OutOfDate,
    CacheInvalid,
}

impl RequirementSatisfaction {
    /// Returns true if a requirement is satisfied by an installed distribution.
    ///
    /// Returns an error if IO fails during a freshness check for a local path.
    pub(crate) fn check(
        name: &PackageName,
        distribution: &InstalledDist,
        source: &RequirementSource,
        version: Option<&Version>,
        installation: InstallationStrategy,
        tags: &Tags,
        config_settings: &ConfigSettings,
        config_settings_package: &PackageConfigSettings,
        extra_build_requires: &ExtraBuildRequires,
        extra_build_variables: &ExtraBuildVariables,
    ) -> Self {
        trace!(
            "Comparing installed with source: {:?} {:?}",
            distribution, source
        );

        // If the distribution was built with other settings, it is out of date.
        if distribution.build_info().is_some_and(|dist_build_info| {
            let config_settings =
                config_settings_for(name, config_settings, config_settings_package);
            let extra_build_requires = extra_build_requires_for(name, extra_build_requires);
            let extra_build_variables = extra_build_variables_for(name, extra_build_variables);
            let build_info = BuildInfo::from_settings(
                config_settings.into_owned(),
                extra_build_requires.to_vec(),
                extra_build_variables.cloned(),
            );
            dist_build_info != &build_info
        }) {
            debug!("Build info mismatch for {name}: {distribution}");
            return Self::OutOfDate;
        }

        // Filter out already-installed packages.
        match source {
            // If the requirement comes from a registry, check by name.
            RequirementSource::Registry { specifier, .. } => {
                // If the installed distribution is _not_ from a registry, reject it if and only if
                // we're in a stateless install.
                //
                // For example: the `uv pip` CLI is stateful, in that it "respects"
                // already-installed packages in the virtual environment. So if you run `uv pip
                // install ./path/to/idna`, and then `uv pip install anyio` (which depends on
                // `idna`), we'll "accept" the already-installed `idna` even though it is implicitly
                // being "required" as a registry package.
                //
                // The `uv sync` CLI is stateless, in that all requirements must be defined
                // declaratively ahead-of-time. So if you `uv sync` to install `./path/to/idna` and
                // later `uv sync` to install `anyio`, we'll know (during that second sync) if the
                // already-installed `idna` should come from the registry or not.
                if installation == InstallationStrategy::Strict {
                    if !matches!(distribution.kind, InstalledDistKind::Registry { .. }) {
                        debug!("Distribution type mismatch for {name}: {distribution:?}");
                        return Self::Mismatch;
                    }
                }

                if !specifier.contains(distribution.version()) {
                    return Self::Mismatch;
                }
            }
            RequirementSource::Url {
                // We use the location since `direct_url.json` also stores this URL, e.g.
                // `pip install git+https://github.com/tqdm/tqdm@cc372d09dcd5a5eabdc6ed4cf365bdb0be004d44#subdirectory=.`
                // records `"url": "https://github.com/tqdm/tqdm"` in `direct_url.json`.
                location: requested_url,
                subdirectory: requested_subdirectory,
                ext: _,
                url: _,
            } => {
                let InstalledDistKind::Url(InstalledDirectUrlDist {
                    direct_url,
                    editable,
                    cache_info,
                    ..
                }) = &distribution.kind
                else {
                    return Self::Mismatch;
                };
                let DirectUrl::ArchiveUrl {
                    url: installed_url,
                    archive_info: _,
                    subdirectory: installed_subdirectory,
                } = direct_url.as_ref()
                else {
                    return Self::Mismatch;
                };

                if *editable {
                    return Self::Mismatch;
                }

                if requested_subdirectory != installed_subdirectory {
                    return Self::Mismatch;
                }

                if !CanonicalUrl::parse(installed_url).is_ok_and(|installed_url| {
                    installed_url == CanonicalUrl::new(requested_url.clone())
                }) {
                    return Self::Mismatch;
                }

                // If the requirement came from a local path, check freshness.
                if requested_url.scheme() == "file" {
                    if let Ok(archive) = requested_url.to_file_path() {
                        let Some(cache_info) = cache_info.as_ref() else {
                            return Self::OutOfDate;
                        };
                        match CacheInfo::from_path(&archive) {
                            Ok(read_cache_info) => {
                                if *cache_info != read_cache_info {
                                    return Self::OutOfDate;
                                }
                            }
                            Err(err) => {
                                debug!(
                                    "Failed to read cached requirement for: {distribution} ({err})"
                                );
                                return Self::CacheInvalid;
                            }
                        }
                    }
                }
            }
            RequirementSource::GitDirectory {
                url: _,
                git: requested_git,
                subdirectory: requested_subdirectory,
            } => {
                let InstalledDistKind::Url(InstalledDirectUrlDist { direct_url, .. }) =
                    &distribution.kind
                else {
                    return Self::Mismatch;
                };
                let DirectUrl::VcsUrl {
                    url: installed_url,
                    vcs_info:
                        VcsInfo {
                            vcs: VcsKind::Git,
                            requested_revision: _,
                            commit_id: installed_precise,
                            git_lfs: installed_git_lfs,
                        },
                    subdirectory: installed_subdirectory,
                    path: None,
                } = direct_url.as_ref()
                else {
                    return Self::Mismatch;
                };

                if requested_subdirectory != installed_subdirectory {
                    debug!(
                        "Subdirectory mismatch: {:?} vs. {:?}",
                        installed_subdirectory, requested_subdirectory
                    );
                    return Self::Mismatch;
                }

                let requested_git_lfs = requested_git.lfs();
                let installed_git_lfs = installed_git_lfs.map(GitLfs::from).unwrap_or_default();
                if requested_git_lfs != installed_git_lfs {
                    debug!(
                        "Git LFS mismatch: {} (installed) vs. {} (requested)",
                        installed_git_lfs, requested_git_lfs,
                    );
                    return Self::Mismatch;
                }

                if !RepositoryUrl::parse(installed_url)
                    .is_ok_and(|installed_url| installed_url == *requested_git.repository())
                {
                    debug!(
                        "Repository mismatch: {:?} vs. {:?}",
                        installed_url,
                        requested_git.url()
                    );
                    return Self::Mismatch;
                }

                // TODO(charlie): It would be more consistent for us to compare the requested
                // revisions here.
                if installed_precise.as_deref()
                    != requested_git.precise().as_ref().map(GitOid::as_str)
                {
                    debug!(
                        "Precise mismatch: {:?} vs. {:?}",
                        installed_precise,
                        requested_git.precise()
                    );
                    return Self::OutOfDate;
                }
            }
            RequirementSource::GitPath {
                url: _,
                git: requested_git,
                install_path: requested_path,
                ext: _,
            } => {
                let InstalledDistKind::Url(InstalledDirectUrlDist { direct_url, .. }) =
                    &distribution.kind
                else {
                    return Self::Mismatch;
                };
                let DirectUrl::VcsUrl {
                    url: installed_url,
                    vcs_info:
                        VcsInfo {
                            vcs: VcsKind::Git,
                            requested_revision: _,
                            commit_id: installed_precise,
                            git_lfs: installed_git_lfs,
                        },
                    subdirectory: None,
                    path: Some(installed_path),
                } = direct_url.as_ref()
                else {
                    return Self::Mismatch;
                };

                if requested_path != installed_path {
                    debug!(
                        "Path mismatch: {:?} vs. {:?}",
                        installed_path, requested_path
                    );
                    return Self::Mismatch;
                }

                let requested_git_lfs = requested_git.lfs();
                let installed_git_lfs = installed_git_lfs.map(GitLfs::from).unwrap_or_default();
                if requested_git_lfs != installed_git_lfs {
                    debug!(
                        "Git LFS mismatch: {} (installed) vs. {} (requested)",
                        installed_git_lfs, requested_git_lfs,
                    );
                    return Self::Mismatch;
                }

                if !RepositoryUrl::parse(installed_url)
                    .is_ok_and(|installed_url| installed_url == *requested_git.repository())
                {
                    debug!(
                        "Repository mismatch: {:?} vs. {:?}",
                        installed_url,
                        requested_git.url()
                    );
                    return Self::Mismatch;
                }

                if installed_precise.as_deref()
                    != requested_git.precise().as_ref().map(GitOid::as_str)
                {
                    debug!(
                        "Precise mismatch: {:?} vs. {:?}",
                        installed_precise,
                        requested_git.precise()
                    );
                    return Self::OutOfDate;
                }
            }
            RequirementSource::Path {
                install_path: requested_path,
                ext: _,
                url: _,
            } => {
                let InstalledDistKind::Url(InstalledDirectUrlDist {
                    direct_url,
                    cache_info,
                    ..
                }) = &distribution.kind
                else {
                    return Self::Mismatch;
                };
                let DirectUrl::ArchiveUrl {
                    url: installed_url,
                    archive_info: _,
                    subdirectory: None,
                } = direct_url.as_ref()
                else {
                    return Self::Mismatch;
                };

                let Some(installed_path) = Url::parse(installed_url)
                    .ok()
                    .and_then(|url| url.to_file_path().ok())
                else {
                    return Self::Mismatch;
                };

                if !(**requested_path == installed_path
                    || is_same_file(requested_path, &installed_path).unwrap_or(false))
                {
                    trace!(
                        "Path mismatch: {:?} vs. {:?}",
                        requested_path, installed_path,
                    );
                    return Self::Mismatch;
                }

                let Some(cache_info) = cache_info.as_ref() else {
                    return Self::OutOfDate;
                };
                match CacheInfo::from_path(requested_path) {
                    Ok(read_cache_info) => {
                        if *cache_info != read_cache_info {
                            return Self::OutOfDate;
                        }
                    }
                    Err(err) => {
                        debug!("Failed to read cached requirement for: {distribution} ({err})");
                        return Self::CacheInvalid;
                    }
                }
            }
            RequirementSource::Directory {
                install_path: requested_path,
                editable: requested_editable,
                r#virtual: _,
                url: _,
            } => {
                let InstalledDistKind::Url(InstalledDirectUrlDist {
                    direct_url,
                    cache_info,
                    ..
                }) = &distribution.kind
                else {
                    return Self::Mismatch;
                };
                let DirectUrl::LocalDirectory {
                    url: installed_url,
                    dir_info:
                        DirInfo {
                            editable: installed_editable,
                        },
                    subdirectory: None,
                } = direct_url.as_ref()
                else {
                    return Self::Mismatch;
                };

                if requested_editable != installed_editable {
                    trace!(
                        "Editable mismatch: {:?} vs. {:?}",
                        *requested_editable,
                        installed_editable.unwrap_or_default()
                    );
                    return Self::Mismatch;
                }

                let Some(installed_path) = Url::parse(installed_url)
                    .ok()
                    .and_then(|url| url.to_file_path().ok())
                else {
                    return Self::Mismatch;
                };

                if !(**requested_path == installed_path
                    || is_same_file(requested_path, &installed_path).unwrap_or(false))
                {
                    trace!(
                        "Path mismatch: {:?} vs. {:?}",
                        requested_path, installed_path,
                    );
                    return Self::Mismatch;
                }

                let Some(cache_info) = cache_info.as_ref() else {
                    return Self::OutOfDate;
                };
                match CacheInfo::from_path(requested_path) {
                    Ok(read_cache_info) => {
                        if *cache_info != read_cache_info {
                            return Self::OutOfDate;
                        }
                    }
                    Err(err) => {
                        debug!("Failed to read cached requirement for: {distribution} ({err})");
                        return Self::CacheInvalid;
                    }
                }
            }
        }

        // If the distribution isn't compatible with the current platform, it is a mismatch.
        if let Ok(Some(wheel_tags)) = distribution.read_tags() {
            if !wheel_tags.is_compatible(tags) {
                if let Some(hint) = generate_dist_compatibility_hint(wheel_tags, tags) {
                    debug!("Platform tags mismatch for {distribution}: {hint}");
                } else {
                    debug!("Platform tags mismatch for {distribution}");
                }
                return Self::Mismatch;
            }
        }

        // If a resolved version is provided, check that it matches the installed version.
        // This is needed for sources that don't include explicit version specifiers (e.g.,
        // directory dependencies with dynamic versioning), where the resolver may have determined
        // a new version should be installed.
        if let Some(version) = version {
            if distribution.version() != version {
                debug!(
                    "Installed version does not match resolved version for {name}: {} vs. {}",
                    distribution.version(),
                    version
                );
                return Self::OutOfDate;
            }
        }

        // Otherwise, assume the requirement is up-to-date.
        Self::Satisfied
    }
}

/// Determine the [`ConfigSettings`] for the given package name.
fn config_settings_for<'settings>(
    name: &PackageName,
    config_settings: &'settings ConfigSettings,
    config_settings_package: &PackageConfigSettings,
) -> Cow<'settings, ConfigSettings> {
    if let Some(package_settings) = config_settings_package.get(name) {
        Cow::Owned(package_settings.clone().merge(config_settings.clone()))
    } else {
        Cow::Borrowed(config_settings)
    }
}

/// Determine the extra build requirements for the given package name.
fn extra_build_requires_for<'settings>(
    name: &PackageName,
    extra_build_requires: &'settings ExtraBuildRequires,
) -> &'settings [ExtraBuildRequirement] {
    extra_build_requires
        .get(name)
        .map(Vec::as_slice)
        .unwrap_or(&[])
}

/// Determine the extra build variables for the given package name.
fn extra_build_variables_for<'settings>(
    name: &PackageName,
    extra_build_variables: &'settings ExtraBuildVariables,
) -> Option<&'settings BuildVariables> {
    extra_build_variables.get(name)
}

/// Generate a hint for explaining tag compatibility issues.
// TODO(zanieb): We should refactor this to share logic with `generate_wheel_compatibility_hint`
fn generate_dist_compatibility_hint(wheel_tags: &ExpandedTags, tags: &Tags) -> Option<String> {
    let TagCompatibility::Incompatible(incompatible_tag) = wheel_tags.compatibility(tags) else {
        return None;
    };

    match incompatible_tag {
        IncompatibleTag::Python => {
            let wheel_tags = wheel_tags.python_tags();
            let current_tag = tags.python_tag();

            if let Some(current) = current_tag {
                let message = if let Some(pretty) = current.pretty() {
                    format!("{pretty} (`{current}`)")
                } else {
                    format!("`{current}`")
                };

                Some(format!(
                    "The distribution is compatible with {}, but you're using {}",
                    wheel_tags
                        .map(|tag| if let Some(pretty) = tag.pretty() {
                            format!("{pretty} (`{tag}`)")
                        } else {
                            format!("`{tag}`")
                        })
                        .collect::<Vec<_>>()
                        .join(", "),
                    message
                ))
            } else {
                Some(format!(
                    "The distribution requires {}",
                    wheel_tags
                        .map(|tag| if let Some(pretty) = tag.pretty() {
                            format!("{pretty} (`{tag}`)")
                        } else {
                            format!("`{tag}`")
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                ))
            }
        }
        IncompatibleTag::FreethreadedAbi => {
            let wheel_abi = wheel_tags
                .abi_tags()
                .map(|tag| match tag {
                    AbiTag::Abi3 => format!("the stable ABI (`{tag}`)"),
                    _ => {
                        if let Some(pretty) = tag.pretty() {
                            format!("the {pretty} ABI (`{tag}`)")
                        } else {
                            format!("`{tag}`")
                        }
                    }
                })
                .collect::<Vec<_>>()
                .join(", ");
            let current = if let Some(current) = tags.abi_tag() {
                if let Some(pretty) = current.pretty() {
                    format!("{pretty} (`{current}`)")
                } else {
                    format!("`{current}`")
                }
            } else {
                "free-threaded Python".to_string()
            };
            Some(format!(
                "You're using {current}, but the distribution was built for {wheel_abi}, which requires a GIL-enabled interpreter"
            ))
        }
        IncompatibleTag::Abi => {
            let wheel_tags = wheel_tags.abi_tags();
            let current_tag = tags.abi_tag();
            if let Some(current) = current_tag {
                let message = if let Some(pretty) = current.pretty() {
                    format!("{pretty} (`{current}`)")
                } else {
                    format!("`{current}`")
                };
                Some(format!(
                    "The distribution is compatible with {}, but you're using {}",
                    wheel_tags
                        .map(|tag| if let Some(pretty) = tag.pretty() {
                            format!("{pretty} (`{tag}`)")
                        } else {
                            format!("`{tag}`")
                        })
                        .collect::<Vec<_>>()
                        .join(", "),
                    message
                ))
            } else {
                Some(format!(
                    "The distribution requires {}",
                    wheel_tags
                        .map(|tag| if let Some(pretty) = tag.pretty() {
                            format!("{pretty} (`{tag}`)")
                        } else {
                            format!("`{tag}`")
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                ))
            }
        }
        IncompatibleTag::Platform => {
            let wheel_tags = wheel_tags.platform_tags();
            let current_tag = tags.platform_tag();

            if let Some(current) = current_tag {
                let message = if let Some(pretty) = current.pretty() {
                    format!("{pretty} (`{current}`)")
                } else {
                    format!("`{current}`")
                };
                Some(format!(
                    "The distribution is compatible with {}, but you're on {}",
                    wheel_tags
                        .map(|tag| if let Some(pretty) = tag.pretty() {
                            format!("{pretty} (`{tag}`)")
                        } else {
                            format!("`{tag}`")
                        })
                        .collect::<Vec<_>>()
                        .join(", "),
                    message
                ))
            } else {
                Some(format!(
                    "The distribution requires {}",
                    wheel_tags
                        .map(|tag| if let Some(pretty) = tag.pretty() {
                            format!("{pretty} (`{tag}`)")
                        } else {
                            format!("`{tag}`")
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                ))
            }
        }
        _ => None,
    }
}