uv-installer 0.0.44

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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
use std::sync::Arc;

use anyhow::{Result, bail};
use owo_colors::OwoColorize;
use tracing::{debug, warn};

use uv_cache::{Cache, CacheBucket, WheelCache};
use uv_cache_info::Timestamp;
use uv_configuration::{BuildOptions, Reinstall};
use uv_distribution::{
    BuiltWheelIndex, HttpArchivePointer, LocalArchivePointer, RegistryWheelIndex,
};
use uv_distribution_filename::WheelFilename;
use uv_distribution_types::{
    BuiltDist, CachedDirectUrlDist, CachedDist, ConfigSettings, Dist, Error, ExtraBuildRequires,
    ExtraBuildVariables, Hashed, IndexLocations, InstalledDist, Name, PackageConfigSettings,
    RequirementSource, Resolution, ResolvedDist, SourceDist,
};
use uv_fs::Simplified;
use uv_normalize::PackageName;
use uv_platform_tags::{AbiTag, IncompatibleTag, TagCompatibility, Tags};
use uv_pypi_types::VerbatimParsedUrl;
use uv_python::PythonEnvironment;
use uv_types::HashStrategy;

use crate::satisfies::RequirementSatisfaction;
use crate::{InstallationStrategy, SitePackages};

/// A planner to generate an [`Plan`] based on a set of requirements.
#[derive(Debug)]
pub struct Planner<'a> {
    resolution: &'a Resolution,
}

impl<'a> Planner<'a> {
    /// Set the requirements use in the [`Plan`].
    pub fn new(resolution: &'a Resolution) -> Self {
        Self { resolution }
    }

    /// Partition a set of requirements into those that should be linked from the cache, those that
    /// need to be downloaded, and those that should be removed.
    ///
    /// The install plan will respect cache [`Freshness`]. Specifically, if refresh is enabled, the
    /// plan will respect cache entries created after the current time (as per the [`Refresh`]
    /// policy). Otherwise, entries will be ignored. The downstream distribution database may still
    /// read those entries from the cache after revalidating them.
    ///
    /// The install plan will also respect the required hashes, such that it will never return a
    /// cached distribution that does not match the required hash. Like pip, though, it _will_
    /// return an _installed_ distribution that does not match the required hash.
    pub fn build(
        self,
        mut site_packages: SitePackages,
        installation: InstallationStrategy,
        reinstall: &Reinstall,
        build_options: &BuildOptions,
        hasher: &HashStrategy,
        index_locations: &IndexLocations,
        config_settings: &ConfigSettings,
        config_settings_package: &PackageConfigSettings,
        extra_build_requires: &ExtraBuildRequires,
        extra_build_variables: &ExtraBuildVariables,
        cache: &Cache,
        venv: &PythonEnvironment,
        tags: &Tags,
    ) -> Result<Plan> {
        // Index all the already-downloaded wheels in the cache.
        let mut registry_index = RegistryWheelIndex::new(
            cache,
            tags,
            index_locations,
            hasher,
            config_settings,
            config_settings_package,
            extra_build_requires,
            extra_build_variables,
        );
        let built_index = BuiltWheelIndex::new(
            cache,
            tags,
            hasher,
            config_settings,
            config_settings_package,
            extra_build_requires,
            extra_build_variables,
        );

        let mut cached = vec![];
        let mut remote = vec![];
        let mut reinstalls = vec![];
        let mut extraneous = vec![];

        // TODO(charlie): There are a few assumptions here that are hard to spot:
        //
        // 1. Apparently, we never return direct URL distributions as [`ResolvedDist::Installed`].
        //    If you trace the resolver, we only ever return [`ResolvedDist::Installed`] if you go
        //    through the [`CandidateSelector`], and we only go through the [`CandidateSelector`]
        //    for registry distributions.
        //
        // 2. We expect any distribution returned as [`ResolvedDist::Installed`] to hit the
        //    "Requirement already installed" path (hence the `unreachable!`) a few lines below it.
        //    So, e.g., if a package is marked as `--reinstall`, we _expect_ that it's not passed in
        //    as [`ResolvedDist::Installed`] here.
        for dist in self.resolution.distributions() {
            // Check if the package should be reinstalled.
            let reinstall = reinstall.contains_package(dist.name())
                || dist
                    .source_tree()
                    .is_some_and(|source_tree| reinstall.contains_path(source_tree));

            // Check if installation of a binary version of the package should be allowed.
            let no_binary = build_options.no_binary_package(dist.name());
            let no_build = build_options.no_build_package(dist.name());

            // Determine whether the distribution is already installed.
            let installed_dists = site_packages.remove_packages(dist.name());
            if reinstall {
                reinstalls.extend(installed_dists);
            } else {
                match installed_dists.as_slice() {
                    [] => {}
                    [installed] => {
                        let source = RequirementSource::from(dist);
                        match RequirementSatisfaction::check(
                            dist.name(),
                            installed,
                            &source,
                            dist.version(),
                            installation,
                            tags,
                            config_settings,
                            config_settings_package,
                            extra_build_requires,
                            extra_build_variables,
                        ) {
                            RequirementSatisfaction::Mismatch => {
                                debug!(
                                    "Requirement installed, but mismatched:\n  Installed: {installed:?}\n  Requested: {source:?}"
                                );
                            }
                            RequirementSatisfaction::Satisfied => {
                                debug!("Requirement already installed: {installed}");
                                continue;
                            }
                            RequirementSatisfaction::OutOfDate => {
                                debug!("Requirement installed, but not fresh: {installed}");

                                // If we made it here, something went wrong in the resolver, because it returned an
                                // already-installed distribution that we "shouldn't" use. Typically, this means the
                                // distribution was considered out-of-date, but in a way that the resolver didn't
                                // detect, and is indicative of drift between the resolver's candidate selector and
                                // the install plan. For example, at present, the resolver doesn't check that an
                                // installed distribution was built with the expected build settings. Treat it as
                                // up-to-date for now; it's just means we may not rebuild a package when we otherwise
                                // should. This is a known issue, but should only affect the `uv pip` CLI, as the
                                // project APIs never return installed distributions during resolution (i.e., the
                                // resolver is stateless).
                                // TODO(charlie): Incorporate these checks into the resolver.
                                if matches!(dist, ResolvedDist::Installed { .. }) {
                                    warn!(
                                        "Installed distribution was considered out-of-date, but returned by the resolver: {dist}"
                                    );
                                    continue;
                                }
                            }
                            RequirementSatisfaction::CacheInvalid => {
                                // Already logged
                            }
                        }
                        reinstalls.push(installed.clone());
                    }
                    // We reinstall installed distributions with multiple versions because
                    // we do not want to keep multiple incompatible versions but removing
                    // one version is likely to break another.
                    _ => reinstalls.extend(installed_dists),
                }
            }

            let ResolvedDist::Installable { dist, .. } = dist else {
                unreachable!("Installed distribution could not be found in site-packages: {dist}");
            };

            if cache.must_revalidate_package(dist.name())
                || dist
                    .source_tree()
                    .is_some_and(|source_tree| cache.must_revalidate_path(source_tree))
            {
                debug!("Must revalidate requirement: {}", dist.name());
                remote.push(dist.clone());
                continue;
            }

            // Identify any cached distributions that satisfy the requirement.
            match dist.as_ref() {
                Dist::Built(BuiltDist::Registry(wheel)) => {
                    if let Some(distribution) = registry_index.get(wheel.name()).find_map(|entry| {
                        if *entry.index.url() != wheel.best_wheel().index {
                            return None;
                        }
                        if entry.dist.filename != wheel.best_wheel().filename {
                            return None;
                        }
                        if entry.built && no_build {
                            return None;
                        }
                        if !entry.built && no_binary {
                            return None;
                        }
                        Some(&entry.dist)
                    }) {
                        debug!("Registry requirement already cached: {distribution}");
                        cached.push(CachedDist::Registry(distribution.clone()));
                        continue;
                    }
                }
                Dist::Built(BuiltDist::DirectUrl(wheel)) => {
                    if !wheel.filename.is_compatible(tags) {
                        let hint = generate_wheel_compatibility_hint(&wheel.filename, tags);
                        if let Some(hint) = hint {
                            bail!(
                                "A URL dependency is incompatible with the current platform: {}\n\n{}{} {}",
                                wheel.url,
                                "hint".bold().cyan(),
                                ":".bold(),
                                hint
                            );
                        }
                        bail!(
                            "A URL dependency is incompatible with the current platform: {}",
                            wheel.url
                        );
                    }

                    if no_binary {
                        bail!(
                            "A URL dependency points to a wheel which conflicts with `--no-binary`: {}",
                            wheel.url
                        );
                    }

                    // Find the exact wheel from the cache, since we know the filename in
                    // advance.
                    let cache_entry = cache
                        .shard(
                            CacheBucket::Wheels,
                            WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
                        )
                        .entry(format!("{}.http", wheel.filename.cache_key()));

                    // Read the HTTP pointer.
                    match HttpArchivePointer::read_from(&cache_entry) {
                        Ok(Some(pointer)) => {
                            let cache_info = pointer.to_cache_info();
                            let build_info = pointer.to_build_info();
                            let archive = pointer.into_archive();
                            if archive.satisfies(hasher.get(dist.as_ref())) {
                                let cached_dist = CachedDirectUrlDist {
                                    filename: wheel.filename.clone(),
                                    url: VerbatimParsedUrl {
                                        parsed_url: wheel.parsed_url(),
                                        verbatim: wheel.url.clone(),
                                    },
                                    hashes: archive.hashes,
                                    cache_info,
                                    build_info,
                                    path: cache.archive(&archive.id).into_boxed_path(),
                                };

                                debug!("URL wheel requirement already cached: {cached_dist}");
                                cached.push(CachedDist::Url(cached_dist));
                                continue;
                            }
                            debug!(
                                "Cached URL wheel requirement does not match expected hash policy for: {wheel}"
                            );
                        }
                        Ok(None) => {}
                        Err(err) => {
                            debug!(
                                "Failed to deserialize cached URL wheel requirement for: {wheel} ({err})"
                            );
                        }
                    }
                }
                Dist::Built(BuiltDist::Path(wheel)) => {
                    // Validate that the path exists.
                    if !wheel.install_path.exists() {
                        return Err(Error::NotFound(wheel.url.to_url()).into());
                    }

                    if !wheel.filename.is_compatible(tags) {
                        let hint = generate_wheel_compatibility_hint(&wheel.filename, tags);
                        if let Some(hint) = hint {
                            bail!(
                                "A path dependency is incompatible with the current platform: {}\n\n{}{} {}",
                                wheel.install_path.user_display(),
                                "hint".bold().cyan(),
                                ":".bold(),
                                hint
                            );
                        }
                        bail!(
                            "A path dependency is incompatible with the current platform: {}",
                            wheel.install_path.user_display()
                        );
                    }

                    if no_binary {
                        bail!(
                            "A path dependency points to a wheel which conflicts with `--no-binary`: {}",
                            wheel.url
                        );
                    }

                    // Find the exact wheel from the cache, since we know the filename in
                    // advance.
                    let cache_entry = cache
                        .shard(
                            CacheBucket::Wheels,
                            WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
                        )
                        .entry(format!("{}.rev", wheel.filename.cache_key()));

                    match LocalArchivePointer::read_from(&cache_entry) {
                        Ok(Some(pointer)) => match Timestamp::from_path(&wheel.install_path) {
                            Ok(timestamp) => {
                                if pointer.is_up_to_date(timestamp) {
                                    let cache_info = pointer.to_cache_info();
                                    let build_info = pointer.to_build_info();
                                    let archive = pointer.into_archive();
                                    if archive.satisfies(hasher.get(dist.as_ref())) {
                                        let cached_dist = CachedDirectUrlDist {
                                            filename: wheel.filename.clone(),
                                            url: VerbatimParsedUrl {
                                                parsed_url: wheel.parsed_url(),
                                                verbatim: wheel.url.clone(),
                                            },
                                            hashes: archive.hashes,
                                            cache_info,
                                            build_info,
                                            path: cache.archive(&archive.id).into_boxed_path(),
                                        };

                                        debug!(
                                            "Path wheel requirement already cached: {cached_dist}"
                                        );
                                        cached.push(CachedDist::Url(cached_dist));
                                        continue;
                                    }
                                    debug!(
                                        "Cached path wheel requirement does not match expected hash policy for: {wheel}"
                                    );
                                }
                            }
                            Err(err) => {
                                debug!("Failed to get timestamp for wheel {wheel} ({err})");
                            }
                        },
                        Ok(None) => {}
                        Err(err) => {
                            debug!(
                                "Failed to deserialize cached path wheel requirement for: {wheel} ({err})"
                            );
                        }
                    }
                }
                Dist::Source(SourceDist::Registry(sdist)) => {
                    if let Some(distribution) = registry_index.get(sdist.name()).find_map(|entry| {
                        if *entry.index.url() != sdist.index {
                            return None;
                        }
                        if entry.dist.filename.name != sdist.name {
                            return None;
                        }
                        if entry.dist.filename.version != sdist.version {
                            return None;
                        }
                        if entry.built && no_build {
                            return None;
                        }
                        if !entry.built && no_binary {
                            return None;
                        }
                        Some(&entry.dist)
                    }) {
                        debug!("Registry requirement already cached: {distribution}");
                        cached.push(CachedDist::Registry(distribution.clone()));
                        continue;
                    }
                }
                Dist::Source(SourceDist::DirectUrl(sdist)) => {
                    // Find the most-compatible wheel from the cache, since we don't know
                    // the filename in advance.
                    match built_index.url(sdist) {
                        Ok(Some(wheel)) => {
                            if wheel.filename.name == sdist.name {
                                let cached_dist = wheel.into_url_dist(sdist);
                                debug!("URL source requirement already cached: {cached_dist}");
                                cached.push(CachedDist::Url(cached_dist));
                                continue;
                            }

                            warn!(
                                "Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
                                sdist, wheel.filename
                            );
                        }
                        Ok(None) => {}
                        Err(err) => {
                            debug!(
                                "Failed to deserialize cached wheel filename for: {sdist} ({err})"
                            );
                        }
                    }
                }
                Dist::Source(SourceDist::Git(sdist)) => {
                    // Find the most-compatible wheel from the cache, since we don't know
                    // the filename in advance.
                    if let Some(wheel) = built_index.git(sdist) {
                        if wheel.filename.name == sdist.name {
                            let cached_dist = wheel.into_git_dist(sdist);
                            debug!("Git source requirement already cached: {cached_dist}");
                            cached.push(CachedDist::Url(cached_dist));
                            continue;
                        }

                        warn!(
                            "Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
                            sdist, wheel.filename
                        );
                    }
                }
                Dist::Source(SourceDist::Path(sdist)) => {
                    // Validate that the path exists.
                    if !sdist.install_path.exists() {
                        return Err(Error::NotFound(sdist.url.to_url()).into());
                    }

                    // Find the most-compatible wheel from the cache, since we don't know
                    // the filename in advance.
                    match built_index.path(sdist) {
                        Ok(Some(wheel)) => {
                            if wheel.filename.name == sdist.name {
                                let cached_dist = wheel.into_path_dist(sdist);
                                debug!("Path source requirement already cached: {cached_dist}");
                                cached.push(CachedDist::Url(cached_dist));
                                continue;
                            }

                            warn!(
                                "Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
                                sdist, wheel.filename
                            );
                        }
                        Ok(None) => {}
                        Err(err) => {
                            debug!(
                                "Failed to deserialize cached wheel filename for: {sdist} ({err})"
                            );
                        }
                    }
                }
                Dist::Source(SourceDist::Directory(sdist)) => {
                    // Validate that the path exists.
                    if !sdist.install_path.exists() {
                        return Err(Error::NotFound(sdist.url.to_url()).into());
                    }

                    // Find the most-compatible wheel from the cache, since we don't know
                    // the filename in advance.
                    match built_index.directory(sdist) {
                        Ok(Some(wheel)) => {
                            if wheel.filename.name == sdist.name {
                                let cached_dist = wheel.into_directory_dist(sdist);
                                debug!(
                                    "Directory source requirement already cached: {cached_dist}"
                                );
                                cached.push(CachedDist::Url(cached_dist));
                                continue;
                            }

                            warn!(
                                "Cached wheel filename does not match requested distribution for: `{}` (found: `{}`)",
                                sdist, wheel.filename
                            );
                        }
                        Ok(None) => {}
                        Err(err) => {
                            debug!(
                                "Failed to deserialize cached wheel filename for: {sdist} ({err})"
                            );
                        }
                    }
                }
            }

            debug!("Identified uncached distribution: {dist}");
            remote.push(dist.clone());
        }

        // Remove any unnecessary packages.
        if site_packages.any() {
            // Retain seed packages unless: (1) the virtual environment was created by uv and
            // (2) the `--seed` argument was not passed to `uv venv`.
            let seed_packages = !venv.cfg().is_ok_and(|cfg| cfg.is_uv() && !cfg.is_seed());
            for dist_info in site_packages {
                if seed_packages && is_seed_package(&dist_info, venv) {
                    debug!("Preserving seed package: {dist_info}");
                    continue;
                }

                debug!("Unnecessary package: {dist_info}");
                extraneous.push(dist_info);
            }
        }

        Ok(Plan {
            cached,
            remote,
            reinstalls,
            extraneous,
        })
    }
}

/// Returns `true` if the given distribution is a seed package.
fn is_seed_package(dist_info: &InstalledDist, venv: &PythonEnvironment) -> bool {
    if venv.interpreter().python_tuple() >= (3, 12) {
        matches!(dist_info.name().as_ref(), "uv" | "pip")
    } else {
        // Include `setuptools` and `wheel` on Python <3.12.
        matches!(
            dist_info.name().as_ref(),
            "pip" | "setuptools" | "wheel" | "uv"
        )
    }
}

/// Generate a hint for explaining wheel compatibility issues.
fn generate_wheel_compatibility_hint(filename: &WheelFilename, tags: &Tags) -> Option<String> {
    let TagCompatibility::Incompatible(incompatible_tag) = filename.compatibility(tags) else {
        return None;
    };

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

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

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

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

#[derive(Debug, Default)]
pub struct Plan {
    /// The distributions that are not already installed in the current environment, but are
    /// available in the local cache.
    pub cached: Vec<CachedDist>,

    /// The distributions that are not already installed in the current environment, and are
    /// not available in the local cache.
    pub remote: Vec<Arc<Dist>>,

    /// Any distributions that are already installed in the current environment, but will be
    /// re-installed (including upgraded) to satisfy the requirements.
    pub reinstalls: Vec<InstalledDist>,

    /// Any distributions that are already installed in the current environment, and are
    /// _not_ necessary to satisfy the requirements.
    pub extraneous: Vec<InstalledDist>,
}

impl Plan {
    /// Returns `true` if the plan is empty.
    pub fn is_empty(&self) -> bool {
        self.cached.is_empty()
            && self.remote.is_empty()
            && self.reinstalls.is_empty()
            && self.extraneous.is_empty()
    }

    /// Partition the remote distributions based on a predicate function.
    ///
    /// Returns a tuple of plans, where the first plan contains the remote distributions that match
    /// the predicate, and the second plan contains those that do not.
    ///
    /// Any extraneous and cached distributions will be returned in the first plan, while the second
    /// plan will contain any `false` matches from the remote distributions, along with any
    /// reinstalls for those distributions.
    pub fn partition<F>(self, mut f: F) -> (Self, Self)
    where
        F: FnMut(&PackageName) -> bool,
    {
        let Self {
            cached,
            remote,
            reinstalls,
            extraneous,
        } = self;

        // Partition the remote distributions based on the predicate function.
        let (left_remote, right_remote) = remote
            .into_iter()
            .partition::<Vec<_>, _>(|dist| f(dist.name()));

        // If any remote distributions are not matched, but are already installed, ensure that
        // they're uninstalled as part of the right plan. (Uninstalling them as part of the left
        // plan risks uninstalling them from the environment _prior_ to the replacement being built.)
        let (left_reinstalls, right_reinstalls) = reinstalls
            .into_iter()
            .partition::<Vec<_>, _>(|dist| !right_remote.iter().any(|d| d.name() == dist.name()));

        // If the right plan is non-empty, then remove extraneous distributions as part of the
        // right plan, so they're present until the very end. Otherwise, we risk removing extraneous
        // packages that are actually build dependencies.
        let (left_extraneous, right_extraneous) = if right_remote.is_empty() {
            (extraneous, vec![])
        } else {
            (vec![], extraneous)
        };

        // Always include the cached distributions in the left plan.
        let (left_cached, right_cached) = (cached, vec![]);

        // Include all cached and extraneous distributions in the left plan.
        let left_plan = Self {
            cached: left_cached,
            remote: left_remote,
            reinstalls: left_reinstalls,
            extraneous: left_extraneous,
        };

        // The right plan will only contain the remote distributions that did not match the predicate,
        // along with any reinstalls for those distributions.
        let right_plan = Self {
            cached: right_cached,
            remote: right_remote,
            reinstalls: right_reinstalls,
            extraneous: right_extraneous,
        };

        (left_plan, right_plan)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;
    use uv_platform_tags::{Arch, Os, Platform, TagsOptions};

    #[test]
    fn test_abi3_on_free_threaded_python_hint() {
        // Create a Tags object for free-threaded Python 3.14
        let platform = Platform::new(
            Os::Manylinux {
                major: 2,
                minor: 28,
            },
            Arch::X86_64,
        );
        let tags = Tags::from_env(
            &platform,
            (3, 14),   // python_version
            "cpython", // implementation_name
            (3, 14),   // implementation_version
            TagsOptions {
                manylinux_compatible: true,
                gil_disabled: true,
                debug_enabled: false,
                is_cross: false,
            },
        )
        .unwrap();

        // Create a wheel filename with abi3 tag
        let filename =
            WheelFilename::from_str("foo-1.0-cp37-abi3-manylinux_2_17_x86_64.whl").unwrap();

        // Generate the hint
        let hint = generate_wheel_compatibility_hint(&filename, &tags).unwrap();

        let hint = anstream::adapter::strip_str(&hint);
        insta::assert_snapshot!(hint, @"You're using free-threaded CPython 3.14 (`cp314t`), but the wheel was built for the stable ABI (`abi3`), which requires a GIL-enabled interpreter");
    }

    #[test]
    fn test_gil_enabled_cpython_on_free_threaded_python_hint() {
        // Create a Tags object for free-threaded Python 3.14
        let platform = Platform::new(
            Os::Manylinux {
                major: 2,
                minor: 28,
            },
            Arch::X86_64,
        );
        let tags = Tags::from_env(
            &platform,
            (3, 14),   // python_version
            "cpython", // implementation_name
            (3, 14),   // implementation_version
            TagsOptions {
                manylinux_compatible: true,
                gil_disabled: true,
                debug_enabled: false,
                is_cross: false,
            },
        )
        .unwrap();

        // Create a wheel filename with cp314 ABI tag (same version, GIL-enabled)
        let filename =
            WheelFilename::from_str("foo-1.0-cp314-cp314-manylinux_2_17_x86_64.whl").unwrap();

        // Generate the hint
        let hint = generate_wheel_compatibility_hint(&filename, &tags).unwrap();

        let hint = anstream::adapter::strip_str(&hint);
        insta::assert_snapshot!(hint, @"You're using free-threaded CPython 3.14 (`cp314t`), but the wheel was built for the CPython 3.14 ABI (`cp314`), which requires a GIL-enabled interpreter");
    }

    #[test]
    fn test_abi3_on_regular_python_no_special_hint() {
        // Create a Tags object for regular (non-free-threaded) Python 3.14
        let platform = Platform::new(
            Os::Manylinux {
                major: 2,
                minor: 28,
            },
            Arch::X86_64,
        );
        let tags = Tags::from_env(
            &platform,
            (3, 14),   // python_version
            "cpython", // implementation_name
            (3, 14),   // implementation_version
            TagsOptions {
                manylinux_compatible: true,
                gil_disabled: false,
                debug_enabled: false,
                is_cross: false,
            },
        )
        .unwrap();

        // Create a wheel filename with abi3 tag
        let filename =
            WheelFilename::from_str("foo-1.0-cp37-abi3-manylinux_2_17_x86_64.whl").unwrap();

        // The wheel should be compatible (abi3 works on regular Python)
        let hint = generate_wheel_compatibility_hint(&filename, &tags);

        // No hint should be generated because the wheel is compatible
        assert!(
            hint.is_none(),
            "Expected no hint (wheel should be compatible), got: {hint:?}"
        );
    }
}