uv_resolver/lock/
mod.rs

1use std::borrow::Cow;
2use std::collections::{BTreeMap, BTreeSet, VecDeque};
3use std::error::Error;
4use std::fmt::{Debug, Display, Formatter};
5use std::io;
6use std::path::{Path, PathBuf};
7use std::str::FromStr;
8use std::sync::{Arc, LazyLock};
9
10use itertools::Itertools;
11use jiff::Timestamp;
12use owo_colors::OwoColorize;
13use petgraph::graph::NodeIndex;
14use petgraph::visit::EdgeRef;
15use rustc_hash::{FxHashMap, FxHashSet};
16use serde::Serializer;
17use toml_edit::{Array, ArrayOfTables, InlineTable, Item, Table, Value, value};
18use tracing::debug;
19use url::Url;
20
21use uv_cache_key::RepositoryUrl;
22use uv_configuration::{BuildOptions, Constraints, InstallTarget};
23use uv_distribution::{DistributionDatabase, FlatRequiresDist};
24use uv_distribution_filename::{
25    BuildTag, DistExtension, ExtensionError, SourceDistExtension, WheelFilename,
26};
27use uv_distribution_types::{
28    BuiltDist, DependencyMetadata, DirectUrlBuiltDist, DirectUrlSourceDist, DirectorySourceDist,
29    Dist, DistributionMetadata, FileLocation, GitSourceDist, IndexLocations, IndexMetadata,
30    IndexUrl, Name, PathBuiltDist, PathSourceDist, RegistryBuiltDist, RegistryBuiltWheel,
31    RegistrySourceDist, RemoteSource, Requirement, RequirementSource, RequiresPython, ResolvedDist,
32    SimplifiedMarkerTree, StaticMetadata, ToUrlError, UrlString,
33};
34use uv_fs::{PortablePath, PortablePathBuf, relative_to};
35use uv_git::{RepositoryReference, ResolvedRepositoryReference};
36use uv_git_types::{GitOid, GitReference, GitUrl, GitUrlParseError};
37use uv_normalize::{ExtraName, GroupName, PackageName};
38use uv_pep440::Version;
39use uv_pep508::{MarkerEnvironment, MarkerTree, VerbatimUrl, VerbatimUrlError, split_scheme};
40use uv_platform_tags::{
41    AbiTag, IncompatibleTag, LanguageTag, PlatformTag, TagCompatibility, TagPriority, Tags,
42};
43use uv_pypi_types::{
44    ConflictKind, Conflicts, HashAlgorithm, HashDigest, HashDigests, Hashes, ParsedArchiveUrl,
45    ParsedGitUrl, PyProjectToml,
46};
47use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
48use uv_small_str::SmallString;
49use uv_types::{BuildContext, HashStrategy};
50use uv_workspace::{Editability, WorkspaceMember};
51
52use crate::fork_strategy::ForkStrategy;
53pub(crate) use crate::lock::export::PylockTomlPackage;
54pub use crate::lock::export::RequirementsTxtExport;
55pub use crate::lock::export::{PylockToml, PylockTomlErrorKind, cyclonedx_json};
56pub use crate::lock::installable::Installable;
57pub use crate::lock::map::PackageMap;
58pub use crate::lock::tree::TreeDisplay;
59use crate::resolution::{AnnotatedDist, ResolutionGraphNode};
60use crate::universal_marker::{ConflictMarker, UniversalMarker};
61use crate::{
62    ExcludeNewer, ExcludeNewerPackage, ExcludeNewerTimestamp, InMemoryIndex, MetadataResponse,
63    PrereleaseMode, ResolutionMode, ResolverOutput,
64};
65
66mod export;
67mod installable;
68mod map;
69mod tree;
70
71/// The current version of the lockfile format.
72pub const VERSION: u32 = 1;
73
74/// The current revision of the lockfile format.
75const REVISION: u32 = 3;
76
77static LINUX_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
78    let pep508 = MarkerTree::from_str("os_name == 'posix' and sys_platform == 'linux'").unwrap();
79    UniversalMarker::new(pep508, ConflictMarker::TRUE)
80});
81static WINDOWS_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
82    let pep508 = MarkerTree::from_str("os_name == 'nt' and sys_platform == 'win32'").unwrap();
83    UniversalMarker::new(pep508, ConflictMarker::TRUE)
84});
85static MAC_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
86    let pep508 = MarkerTree::from_str("os_name == 'posix' and sys_platform == 'darwin'").unwrap();
87    UniversalMarker::new(pep508, ConflictMarker::TRUE)
88});
89static ANDROID_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
90    let pep508 = MarkerTree::from_str("sys_platform == 'android'").unwrap();
91    UniversalMarker::new(pep508, ConflictMarker::TRUE)
92});
93static ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
94    let pep508 =
95        MarkerTree::from_str("platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ARM64'")
96            .unwrap();
97    UniversalMarker::new(pep508, ConflictMarker::TRUE)
98});
99static X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
100    let pep508 =
101        MarkerTree::from_str("platform_machine == 'x86_64' or platform_machine == 'amd64' or platform_machine == 'AMD64'")
102            .unwrap();
103    UniversalMarker::new(pep508, ConflictMarker::TRUE)
104});
105static X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
106    let pep508 = MarkerTree::from_str(
107        "platform_machine == 'i686' or platform_machine == 'i386' or platform_machine == 'win32' or platform_machine == 'x86'",
108    )
109    .unwrap();
110    UniversalMarker::new(pep508, ConflictMarker::TRUE)
111});
112static LINUX_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
113    let mut marker = *LINUX_MARKERS;
114    marker.and(*ARM_MARKERS);
115    marker
116});
117static LINUX_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
118    let mut marker = *LINUX_MARKERS;
119    marker.and(*X86_64_MARKERS);
120    marker
121});
122static LINUX_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
123    let mut marker = *LINUX_MARKERS;
124    marker.and(*X86_MARKERS);
125    marker
126});
127static WINDOWS_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
128    let mut marker = *WINDOWS_MARKERS;
129    marker.and(*ARM_MARKERS);
130    marker
131});
132static WINDOWS_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
133    let mut marker = *WINDOWS_MARKERS;
134    marker.and(*X86_64_MARKERS);
135    marker
136});
137static WINDOWS_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
138    let mut marker = *WINDOWS_MARKERS;
139    marker.and(*X86_MARKERS);
140    marker
141});
142static MAC_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
143    let mut marker = *MAC_MARKERS;
144    marker.and(*ARM_MARKERS);
145    marker
146});
147static MAC_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
148    let mut marker = *MAC_MARKERS;
149    marker.and(*X86_64_MARKERS);
150    marker
151});
152static MAC_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
153    let mut marker = *MAC_MARKERS;
154    marker.and(*X86_MARKERS);
155    marker
156});
157static ANDROID_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
158    let mut marker = *ANDROID_MARKERS;
159    marker.and(*ARM_MARKERS);
160    marker
161});
162static ANDROID_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
163    let mut marker = *ANDROID_MARKERS;
164    marker.and(*X86_64_MARKERS);
165    marker
166});
167static ANDROID_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
168    let mut marker = *ANDROID_MARKERS;
169    marker.and(*X86_MARKERS);
170    marker
171});
172
173#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
174#[serde(try_from = "LockWire")]
175pub struct Lock {
176    /// The (major) version of the lockfile format.
177    ///
178    /// Changes to the major version indicate backwards- and forwards-incompatible changes to the
179    /// lockfile format. A given uv version only supports a single major version of the lockfile
180    /// format.
181    ///
182    /// In other words, a version of uv that supports version 2 of the lockfile format will not be
183    /// able to read lockfiles generated under version 1 or 3.
184    version: u32,
185    /// The revision of the lockfile format.
186    ///
187    /// Changes to the revision indicate backwards-compatible changes to the lockfile format.
188    /// In other words, versions of uv that only support revision 1 _will_ be able to read lockfiles
189    /// with a revision greater than 1 (though they may ignore newer fields).
190    revision: u32,
191    /// If this lockfile was built from a forking resolution with non-identical forks, store the
192    /// forks in the lockfile so we can recreate them in subsequent resolutions.
193    fork_markers: Vec<UniversalMarker>,
194    /// The conflicting groups/extras specified by the user.
195    conflicts: Conflicts,
196    /// The list of supported environments specified by the user.
197    supported_environments: Vec<MarkerTree>,
198    /// The list of required platforms specified by the user.
199    required_environments: Vec<MarkerTree>,
200    /// The range of supported Python versions.
201    requires_python: RequiresPython,
202    /// We discard the lockfile if these options don't match.
203    options: ResolverOptions,
204    /// The actual locked version and their metadata.
205    packages: Vec<Package>,
206    /// A map from package ID to index in `packages`.
207    ///
208    /// This can be used to quickly lookup the full package for any ID
209    /// in this lock. For example, the dependencies for each package are
210    /// listed as package IDs. This map can be used to find the full
211    /// package for each such dependency.
212    ///
213    /// It is guaranteed that every package in this lock has an entry in
214    /// this map, and that every dependency for every package has an ID
215    /// that exists in this map. That is, there are no dependencies that don't
216    /// have a corresponding locked package entry in the same lockfile.
217    by_id: FxHashMap<PackageId, usize>,
218    /// The input requirements to the resolution.
219    manifest: ResolverManifest,
220}
221
222impl Lock {
223    /// Initialize a [`Lock`] from a [`ResolverOutput`].
224    pub fn from_resolution(resolution: &ResolverOutput, root: &Path) -> Result<Self, LockError> {
225        let mut packages = BTreeMap::new();
226        let requires_python = resolution.requires_python.clone();
227
228        // Determine the set of packages included at multiple versions.
229        let mut seen = FxHashSet::default();
230        let mut duplicates = FxHashSet::default();
231        for node_index in resolution.graph.node_indices() {
232            let ResolutionGraphNode::Dist(dist) = &resolution.graph[node_index] else {
233                continue;
234            };
235            if !dist.is_base() {
236                continue;
237            }
238            if !seen.insert(dist.name()) {
239                duplicates.insert(dist.name());
240            }
241        }
242
243        // Lock all base packages.
244        for node_index in resolution.graph.node_indices() {
245            let ResolutionGraphNode::Dist(dist) = &resolution.graph[node_index] else {
246                continue;
247            };
248            if !dist.is_base() {
249                continue;
250            }
251
252            // If there are multiple distributions for the same package, include the markers of all
253            // forks that included the current distribution.
254            let fork_markers = if duplicates.contains(dist.name()) {
255                resolution
256                    .fork_markers
257                    .iter()
258                    .filter(|fork_markers| !fork_markers.is_disjoint(dist.marker))
259                    .copied()
260                    .collect()
261            } else {
262                vec![]
263            };
264
265            let mut package = Package::from_annotated_dist(dist, fork_markers, root)?;
266            Self::remove_unreachable_wheels(resolution, &requires_python, node_index, &mut package);
267
268            // Add all dependencies
269            for edge in resolution.graph.edges(node_index) {
270                let ResolutionGraphNode::Dist(dependency_dist) = &resolution.graph[edge.target()]
271                else {
272                    continue;
273                };
274                let marker = *edge.weight();
275                package.add_dependency(&requires_python, dependency_dist, marker, root)?;
276            }
277
278            let id = package.id.clone();
279            if let Some(locked_dist) = packages.insert(id, package) {
280                return Err(LockErrorKind::DuplicatePackage {
281                    id: locked_dist.id.clone(),
282                }
283                .into());
284            }
285        }
286
287        // Lock all extras and development dependencies.
288        for node_index in resolution.graph.node_indices() {
289            let ResolutionGraphNode::Dist(dist) = &resolution.graph[node_index] else {
290                continue;
291            };
292            if let Some(extra) = dist.extra.as_ref() {
293                let id = PackageId::from_annotated_dist(dist, root)?;
294                let Some(package) = packages.get_mut(&id) else {
295                    return Err(LockErrorKind::MissingExtraBase {
296                        id,
297                        extra: extra.clone(),
298                    }
299                    .into());
300                };
301                for edge in resolution.graph.edges(node_index) {
302                    let ResolutionGraphNode::Dist(dependency_dist) =
303                        &resolution.graph[edge.target()]
304                    else {
305                        continue;
306                    };
307                    let marker = *edge.weight();
308                    package.add_optional_dependency(
309                        &requires_python,
310                        extra.clone(),
311                        dependency_dist,
312                        marker,
313                        root,
314                    )?;
315                }
316            }
317            if let Some(group) = dist.group.as_ref() {
318                let id = PackageId::from_annotated_dist(dist, root)?;
319                let Some(package) = packages.get_mut(&id) else {
320                    return Err(LockErrorKind::MissingDevBase {
321                        id,
322                        group: group.clone(),
323                    }
324                    .into());
325                };
326                for edge in resolution.graph.edges(node_index) {
327                    let ResolutionGraphNode::Dist(dependency_dist) =
328                        &resolution.graph[edge.target()]
329                    else {
330                        continue;
331                    };
332                    let marker = *edge.weight();
333                    package.add_group_dependency(
334                        &requires_python,
335                        group.clone(),
336                        dependency_dist,
337                        marker,
338                        root,
339                    )?;
340                }
341            }
342        }
343
344        let packages = packages.into_values().collect();
345
346        let options = ResolverOptions {
347            resolution_mode: resolution.options.resolution_mode,
348            prerelease_mode: resolution.options.prerelease_mode,
349            fork_strategy: resolution.options.fork_strategy,
350            exclude_newer: resolution.options.exclude_newer.clone().into(),
351        };
352        let lock = Self::new(
353            VERSION,
354            REVISION,
355            packages,
356            requires_python,
357            options,
358            ResolverManifest::default(),
359            Conflicts::empty(),
360            vec![],
361            vec![],
362            resolution.fork_markers.clone(),
363        )?;
364        Ok(lock)
365    }
366
367    /// Remove wheels that can't be selected for installation due to environment markers.
368    ///
369    /// For example, a package included under `sys_platform == 'win32'` does not need Linux
370    /// wheels.
371    fn remove_unreachable_wheels(
372        graph: &ResolverOutput,
373        requires_python: &RequiresPython,
374        node_index: NodeIndex,
375        locked_dist: &mut Package,
376    ) {
377        // Remove wheels that don't match `requires-python` and can't be selected for installation.
378        locked_dist
379            .wheels
380            .retain(|wheel| requires_python.matches_wheel_tag(&wheel.filename));
381
382        // Filter by platform tags.
383        locked_dist.wheels.retain(|wheel| {
384            // Naively, we'd check whether `platform_system == 'Linux'` is disjoint, or
385            // `os_name == 'posix'` is disjoint, or `sys_platform == 'linux'` is disjoint (each on its
386            // own sufficient to exclude linux wheels), but due to
387            // `(A ∩ (B ∩ C) = ∅) => ((A ∩ B = ∅) or (A ∩ C = ∅))`
388            // a single disjointness check with the intersection is sufficient, so we have one
389            // constant per platform.
390            let platform_tags = wheel.filename.platform_tags();
391
392            if platform_tags.iter().all(PlatformTag::is_any) {
393                return true;
394            }
395
396            if platform_tags.iter().all(PlatformTag::is_linux) {
397                if platform_tags.iter().all(PlatformTag::is_arm) {
398                    if graph.graph[node_index]
399                        .marker()
400                        .is_disjoint(*LINUX_ARM_MARKERS)
401                    {
402                        return false;
403                    }
404                } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
405                    if graph.graph[node_index]
406                        .marker()
407                        .is_disjoint(*LINUX_X86_64_MARKERS)
408                    {
409                        return false;
410                    }
411                } else if platform_tags.iter().all(PlatformTag::is_x86) {
412                    if graph.graph[node_index]
413                        .marker()
414                        .is_disjoint(*LINUX_X86_MARKERS)
415                    {
416                        return false;
417                    }
418                } else if graph.graph[node_index].marker().is_disjoint(*LINUX_MARKERS) {
419                    return false;
420                }
421            }
422
423            if platform_tags.iter().all(PlatformTag::is_windows) {
424                if platform_tags.iter().all(PlatformTag::is_arm) {
425                    if graph.graph[node_index]
426                        .marker()
427                        .is_disjoint(*WINDOWS_ARM_MARKERS)
428                    {
429                        return false;
430                    }
431                } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
432                    if graph.graph[node_index]
433                        .marker()
434                        .is_disjoint(*WINDOWS_X86_64_MARKERS)
435                    {
436                        return false;
437                    }
438                } else if platform_tags.iter().all(PlatformTag::is_x86) {
439                    if graph.graph[node_index]
440                        .marker()
441                        .is_disjoint(*WINDOWS_X86_MARKERS)
442                    {
443                        return false;
444                    }
445                } else if graph.graph[node_index]
446                    .marker()
447                    .is_disjoint(*WINDOWS_MARKERS)
448                {
449                    return false;
450                }
451            }
452
453            if platform_tags.iter().all(PlatformTag::is_macos) {
454                if platform_tags.iter().all(PlatformTag::is_arm) {
455                    if graph.graph[node_index]
456                        .marker()
457                        .is_disjoint(*MAC_ARM_MARKERS)
458                    {
459                        return false;
460                    }
461                } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
462                    if graph.graph[node_index]
463                        .marker()
464                        .is_disjoint(*MAC_X86_64_MARKERS)
465                    {
466                        return false;
467                    }
468                } else if platform_tags.iter().all(PlatformTag::is_x86) {
469                    if graph.graph[node_index]
470                        .marker()
471                        .is_disjoint(*MAC_X86_MARKERS)
472                    {
473                        return false;
474                    }
475                } else if graph.graph[node_index].marker().is_disjoint(*MAC_MARKERS) {
476                    return false;
477                }
478            }
479
480            if platform_tags.iter().all(PlatformTag::is_android) {
481                if platform_tags.iter().all(PlatformTag::is_arm) {
482                    if graph.graph[node_index]
483                        .marker()
484                        .is_disjoint(*ANDROID_ARM_MARKERS)
485                    {
486                        return false;
487                    }
488                } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
489                    if graph.graph[node_index]
490                        .marker()
491                        .is_disjoint(*ANDROID_X86_64_MARKERS)
492                    {
493                        return false;
494                    }
495                } else if platform_tags.iter().all(PlatformTag::is_x86) {
496                    if graph.graph[node_index]
497                        .marker()
498                        .is_disjoint(*ANDROID_X86_MARKERS)
499                    {
500                        return false;
501                    }
502                } else if graph.graph[node_index]
503                    .marker()
504                    .is_disjoint(*ANDROID_MARKERS)
505                {
506                    return false;
507                }
508            }
509
510            if platform_tags.iter().all(PlatformTag::is_arm) {
511                if graph.graph[node_index].marker().is_disjoint(*ARM_MARKERS) {
512                    return false;
513                }
514            }
515
516            if platform_tags.iter().all(PlatformTag::is_x86_64) {
517                if graph.graph[node_index]
518                    .marker()
519                    .is_disjoint(*X86_64_MARKERS)
520                {
521                    return false;
522                }
523            }
524
525            if platform_tags.iter().all(PlatformTag::is_x86) {
526                if graph.graph[node_index].marker().is_disjoint(*X86_MARKERS) {
527                    return false;
528                }
529            }
530
531            true
532        });
533    }
534
535    /// Initialize a [`Lock`] from a list of [`Package`] entries.
536    fn new(
537        version: u32,
538        revision: u32,
539        mut packages: Vec<Package>,
540        requires_python: RequiresPython,
541        options: ResolverOptions,
542        manifest: ResolverManifest,
543        conflicts: Conflicts,
544        supported_environments: Vec<MarkerTree>,
545        required_environments: Vec<MarkerTree>,
546        fork_markers: Vec<UniversalMarker>,
547    ) -> Result<Self, LockError> {
548        // Put all dependencies for each package in a canonical order and
549        // check for duplicates.
550        for package in &mut packages {
551            package.dependencies.sort();
552            for windows in package.dependencies.windows(2) {
553                let (dep1, dep2) = (&windows[0], &windows[1]);
554                if dep1 == dep2 {
555                    return Err(LockErrorKind::DuplicateDependency {
556                        id: package.id.clone(),
557                        dependency: dep1.clone(),
558                    }
559                    .into());
560                }
561            }
562
563            // Perform the same validation for optional dependencies.
564            for (extra, dependencies) in &mut package.optional_dependencies {
565                dependencies.sort();
566                for windows in dependencies.windows(2) {
567                    let (dep1, dep2) = (&windows[0], &windows[1]);
568                    if dep1 == dep2 {
569                        return Err(LockErrorKind::DuplicateOptionalDependency {
570                            id: package.id.clone(),
571                            extra: extra.clone(),
572                            dependency: dep1.clone(),
573                        }
574                        .into());
575                    }
576                }
577            }
578
579            // Perform the same validation for dev dependencies.
580            for (group, dependencies) in &mut package.dependency_groups {
581                dependencies.sort();
582                for windows in dependencies.windows(2) {
583                    let (dep1, dep2) = (&windows[0], &windows[1]);
584                    if dep1 == dep2 {
585                        return Err(LockErrorKind::DuplicateDevDependency {
586                            id: package.id.clone(),
587                            group: group.clone(),
588                            dependency: dep1.clone(),
589                        }
590                        .into());
591                    }
592                }
593            }
594        }
595        packages.sort_by(|dist1, dist2| dist1.id.cmp(&dist2.id));
596
597        // Check for duplicate package IDs and also build up the map for
598        // packages keyed by their ID.
599        let mut by_id = FxHashMap::default();
600        for (i, dist) in packages.iter().enumerate() {
601            if by_id.insert(dist.id.clone(), i).is_some() {
602                return Err(LockErrorKind::DuplicatePackage {
603                    id: dist.id.clone(),
604                }
605                .into());
606            }
607        }
608
609        // Build up a map from ID to extras.
610        let mut extras_by_id = FxHashMap::default();
611        for dist in &packages {
612            for extra in dist.optional_dependencies.keys() {
613                extras_by_id
614                    .entry(dist.id.clone())
615                    .or_insert_with(FxHashSet::default)
616                    .insert(extra.clone());
617            }
618        }
619
620        // Remove any non-existent extras (e.g., extras that were requested but don't exist).
621        for dist in &mut packages {
622            for dep in dist
623                .dependencies
624                .iter_mut()
625                .chain(dist.optional_dependencies.values_mut().flatten())
626                .chain(dist.dependency_groups.values_mut().flatten())
627            {
628                dep.extra.retain(|extra| {
629                    extras_by_id
630                        .get(&dep.package_id)
631                        .is_some_and(|extras| extras.contains(extra))
632                });
633            }
634        }
635
636        // Check that every dependency has an entry in `by_id`. If any don't,
637        // it implies we somehow have a dependency with no corresponding locked
638        // package.
639        for dist in &packages {
640            for dep in &dist.dependencies {
641                if !by_id.contains_key(&dep.package_id) {
642                    return Err(LockErrorKind::UnrecognizedDependency {
643                        id: dist.id.clone(),
644                        dependency: dep.clone(),
645                    }
646                    .into());
647                }
648            }
649
650            // Perform the same validation for optional dependencies.
651            for dependencies in dist.optional_dependencies.values() {
652                for dep in dependencies {
653                    if !by_id.contains_key(&dep.package_id) {
654                        return Err(LockErrorKind::UnrecognizedDependency {
655                            id: dist.id.clone(),
656                            dependency: dep.clone(),
657                        }
658                        .into());
659                    }
660                }
661            }
662
663            // Perform the same validation for dev dependencies.
664            for dependencies in dist.dependency_groups.values() {
665                for dep in dependencies {
666                    if !by_id.contains_key(&dep.package_id) {
667                        return Err(LockErrorKind::UnrecognizedDependency {
668                            id: dist.id.clone(),
669                            dependency: dep.clone(),
670                        }
671                        .into());
672                    }
673                }
674            }
675
676            // Also check that our sources are consistent with whether we have
677            // hashes or not.
678            if let Some(requires_hash) = dist.id.source.requires_hash() {
679                for wheel in &dist.wheels {
680                    if requires_hash != wheel.hash.is_some() {
681                        return Err(LockErrorKind::Hash {
682                            id: dist.id.clone(),
683                            artifact_type: "wheel",
684                            expected: requires_hash,
685                        }
686                        .into());
687                    }
688                }
689            }
690        }
691        let lock = Self {
692            version,
693            revision,
694            fork_markers,
695            conflicts,
696            supported_environments,
697            required_environments,
698            requires_python,
699            options,
700            packages,
701            by_id,
702            manifest,
703        };
704        Ok(lock)
705    }
706
707    /// Record the requirements that were used to generate this lock.
708    #[must_use]
709    pub fn with_manifest(mut self, manifest: ResolverManifest) -> Self {
710        self.manifest = manifest;
711        self
712    }
713
714    /// Record the conflicting groups that were used to generate this lock.
715    #[must_use]
716    pub fn with_conflicts(mut self, conflicts: Conflicts) -> Self {
717        self.conflicts = conflicts;
718        self
719    }
720
721    /// Record the supported environments that were used to generate this lock.
722    #[must_use]
723    pub fn with_supported_environments(mut self, supported_environments: Vec<MarkerTree>) -> Self {
724        // We "complexify" the markers given, since the supported
725        // environments given might be coming directly from what's written in
726        // `pyproject.toml`, and those are assumed to be simplified (i.e.,
727        // they assume `requires-python` is true). But a `Lock` always uses
728        // non-simplified markers internally, so we need to re-complexify them
729        // here.
730        //
731        // The nice thing about complexifying is that it's a no-op if the
732        // markers given have already been complexified.
733        self.supported_environments = supported_environments
734            .into_iter()
735            .map(|marker| self.requires_python.complexify_markers(marker))
736            .collect();
737        self
738    }
739
740    /// Record the required platforms that were used to generate this lock.
741    #[must_use]
742    pub fn with_required_environments(mut self, required_environments: Vec<MarkerTree>) -> Self {
743        self.required_environments = required_environments
744            .into_iter()
745            .map(|marker| self.requires_python.complexify_markers(marker))
746            .collect();
747        self
748    }
749
750    /// Returns `true` if this [`Lock`] includes `provides-extra` metadata.
751    pub fn supports_provides_extra(&self) -> bool {
752        // `provides-extra` was added in Version 1 Revision 1.
753        (self.version(), self.revision()) >= (1, 1)
754    }
755
756    /// Returns `true` if this [`Lock`] includes entries for empty `dependency-group` metadata.
757    pub fn includes_empty_groups(&self) -> bool {
758        // Empty dependency groups are included as of https://github.com/astral-sh/uv/pull/8598,
759        // but Version 1 Revision 1 is the first revision published after that change.
760        (self.version(), self.revision()) >= (1, 1)
761    }
762
763    /// Returns the lockfile version.
764    pub fn version(&self) -> u32 {
765        self.version
766    }
767
768    /// Returns the lockfile revision.
769    pub fn revision(&self) -> u32 {
770        self.revision
771    }
772
773    /// Returns the number of packages in the lockfile.
774    pub fn len(&self) -> usize {
775        self.packages.len()
776    }
777
778    /// Returns `true` if the lockfile contains no packages.
779    pub fn is_empty(&self) -> bool {
780        self.packages.is_empty()
781    }
782
783    /// Returns the [`Package`] entries in this lock.
784    pub fn packages(&self) -> &[Package] {
785        &self.packages
786    }
787
788    /// Returns the supported Python version range for the lockfile, if present.
789    pub fn requires_python(&self) -> &RequiresPython {
790        &self.requires_python
791    }
792
793    /// Returns the resolution mode used to generate this lock.
794    pub fn resolution_mode(&self) -> ResolutionMode {
795        self.options.resolution_mode
796    }
797
798    /// Returns the pre-release mode used to generate this lock.
799    pub fn prerelease_mode(&self) -> PrereleaseMode {
800        self.options.prerelease_mode
801    }
802
803    /// Returns the multi-version mode used to generate this lock.
804    pub fn fork_strategy(&self) -> ForkStrategy {
805        self.options.fork_strategy
806    }
807
808    /// Returns the exclude newer setting used to generate this lock.
809    pub fn exclude_newer(&self) -> ExcludeNewer {
810        // TODO(zanieb): It'd be nice not to hide this clone here, but I am hesitant to introduce
811        // a whole new `ExcludeNewerRef` type just for this
812        self.options.exclude_newer.clone().into()
813    }
814
815    /// Returns the conflicting groups that were used to generate this lock.
816    pub fn conflicts(&self) -> &Conflicts {
817        &self.conflicts
818    }
819
820    /// Returns the supported environments that were used to generate this lock.
821    pub fn supported_environments(&self) -> &[MarkerTree] {
822        &self.supported_environments
823    }
824
825    /// Returns the required platforms that were used to generate this lock.
826    pub fn required_environments(&self) -> &[MarkerTree] {
827        &self.required_environments
828    }
829
830    /// Returns the workspace members that were used to generate this lock.
831    pub fn members(&self) -> &BTreeSet<PackageName> {
832        &self.manifest.members
833    }
834
835    /// Returns the dependency groups that were used to generate this lock.
836    pub fn requirements(&self) -> &BTreeSet<Requirement> {
837        &self.manifest.requirements
838    }
839
840    /// Returns the dependency groups that were used to generate this lock.
841    pub fn dependency_groups(&self) -> &BTreeMap<GroupName, BTreeSet<Requirement>> {
842        &self.manifest.dependency_groups
843    }
844
845    /// Returns the build constraints that were used to generate this lock.
846    pub fn build_constraints(&self, root: &Path) -> Constraints {
847        Constraints::from_requirements(
848            self.manifest
849                .build_constraints
850                .iter()
851                .cloned()
852                .map(|requirement| requirement.to_absolute(root)),
853        )
854    }
855
856    /// Return the workspace root used to generate this lock.
857    pub fn root(&self) -> Option<&Package> {
858        self.packages.iter().find(|package| {
859            let (Source::Editable(path) | Source::Virtual(path)) = &package.id.source else {
860                return false;
861            };
862            path.as_ref() == Path::new("")
863        })
864    }
865
866    /// Returns the supported environments that were used to generate this
867    /// lock.
868    ///
869    /// The markers returned here are "simplified" with respect to the lock
870    /// file's `requires-python` setting. This means these should only be used
871    /// for direct comparison purposes with the supported environments written
872    /// by a human in `pyproject.toml`. (Think of "supported environments" in
873    /// `pyproject.toml` as having an implicit `and python_full_version >=
874    /// '{requires-python-bound}'` attached to each one.)
875    pub fn simplified_supported_environments(&self) -> Vec<MarkerTree> {
876        self.supported_environments()
877            .iter()
878            .copied()
879            .map(|marker| self.simplify_environment(marker))
880            .collect()
881    }
882
883    /// Returns the required platforms that were used to generate this
884    /// lock.
885    pub fn simplified_required_environments(&self) -> Vec<MarkerTree> {
886        self.required_environments()
887            .iter()
888            .copied()
889            .map(|marker| self.simplify_environment(marker))
890            .collect()
891    }
892
893    /// Simplify the given marker environment with respect to the lockfile's
894    /// `requires-python` setting.
895    pub fn simplify_environment(&self, marker: MarkerTree) -> MarkerTree {
896        self.requires_python.simplify_markers(marker)
897    }
898
899    /// If this lockfile was built from a forking resolution with non-identical forks, return the
900    /// markers of those forks, otherwise `None`.
901    pub fn fork_markers(&self) -> &[UniversalMarker] {
902        self.fork_markers.as_slice()
903    }
904
905    /// Checks whether the fork markers cover the entire supported marker space.
906    ///
907    /// Returns the actually covered and the expected marker space on validation error.
908    pub fn check_marker_coverage(&self) -> Result<(), (MarkerTree, MarkerTree)> {
909        let fork_markers_union = if self.fork_markers().is_empty() {
910            self.requires_python.to_marker_tree()
911        } else {
912            let mut fork_markers_union = MarkerTree::FALSE;
913            for fork_marker in self.fork_markers() {
914                fork_markers_union.or(fork_marker.pep508());
915            }
916            fork_markers_union
917        };
918        let mut environments_union = if !self.supported_environments.is_empty() {
919            let mut environments_union = MarkerTree::FALSE;
920            for fork_marker in &self.supported_environments {
921                environments_union.or(*fork_marker);
922            }
923            environments_union
924        } else {
925            MarkerTree::TRUE
926        };
927        // When a user defines environments, they are implicitly constrained by requires-python.
928        environments_union.and(self.requires_python.to_marker_tree());
929        if fork_markers_union.negate().is_disjoint(environments_union) {
930            Ok(())
931        } else {
932            Err((fork_markers_union, environments_union))
933        }
934    }
935
936    /// Checks whether the new requires-python specification is disjoint with
937    /// the fork markers in this lock file.
938    ///
939    /// If they are disjoint, then the union of the fork markers along with the
940    /// given requires-python specification (converted to a marker tree) are
941    /// returned.
942    ///
943    /// When disjoint, the fork markers in the lock file should be dropped and
944    /// not used.
945    pub fn requires_python_coverage(
946        &self,
947        new_requires_python: &RequiresPython,
948    ) -> Result<(), (MarkerTree, MarkerTree)> {
949        let fork_markers_union = if self.fork_markers().is_empty() {
950            self.requires_python.to_marker_tree()
951        } else {
952            let mut fork_markers_union = MarkerTree::FALSE;
953            for fork_marker in self.fork_markers() {
954                fork_markers_union.or(fork_marker.pep508());
955            }
956            fork_markers_union
957        };
958        let new_requires_python = new_requires_python.to_marker_tree();
959        if fork_markers_union.is_disjoint(new_requires_python) {
960            Err((fork_markers_union, new_requires_python))
961        } else {
962            Ok(())
963        }
964    }
965
966    /// Returns the TOML representation of this lockfile.
967    pub fn to_toml(&self) -> Result<String, toml_edit::ser::Error> {
968        // Catch a lockfile where the union of fork markers doesn't cover the supported
969        // environments.
970        debug_assert!(self.check_marker_coverage().is_ok());
971
972        // We construct a TOML document manually instead of going through Serde to enable
973        // the use of inline tables.
974        let mut doc = toml_edit::DocumentMut::new();
975        doc.insert("version", value(i64::from(self.version)));
976
977        if self.revision > 0 {
978            doc.insert("revision", value(i64::from(self.revision)));
979        }
980
981        doc.insert("requires-python", value(self.requires_python.to_string()));
982
983        if !self.fork_markers.is_empty() {
984            let fork_markers = each_element_on_its_line_array(
985                simplified_universal_markers(&self.fork_markers, &self.requires_python).into_iter(),
986            );
987            if !fork_markers.is_empty() {
988                doc.insert("resolution-markers", value(fork_markers));
989            }
990        }
991
992        if !self.supported_environments.is_empty() {
993            let supported_environments = each_element_on_its_line_array(
994                self.supported_environments
995                    .iter()
996                    .copied()
997                    .map(|marker| SimplifiedMarkerTree::new(&self.requires_python, marker))
998                    .filter_map(SimplifiedMarkerTree::try_to_string),
999            );
1000            doc.insert("supported-markers", value(supported_environments));
1001        }
1002
1003        if !self.required_environments.is_empty() {
1004            let required_environments = each_element_on_its_line_array(
1005                self.required_environments
1006                    .iter()
1007                    .copied()
1008                    .map(|marker| SimplifiedMarkerTree::new(&self.requires_python, marker))
1009                    .filter_map(SimplifiedMarkerTree::try_to_string),
1010            );
1011            doc.insert("required-markers", value(required_environments));
1012        }
1013
1014        if !self.conflicts.is_empty() {
1015            let mut list = Array::new();
1016            for set in self.conflicts.iter() {
1017                list.push(each_element_on_its_line_array(set.iter().map(|item| {
1018                    let mut table = InlineTable::new();
1019                    table.insert("package", Value::from(item.package().to_string()));
1020                    match item.kind() {
1021                        ConflictKind::Project => {}
1022                        ConflictKind::Extra(extra) => {
1023                            table.insert("extra", Value::from(extra.to_string()));
1024                        }
1025                        ConflictKind::Group(group) => {
1026                            table.insert("group", Value::from(group.to_string()));
1027                        }
1028                    }
1029                    table
1030                })));
1031            }
1032            doc.insert("conflicts", value(list));
1033        }
1034
1035        // Write the settings that were used to generate the resolution.
1036        // This enables us to invalidate the lockfile if the user changes
1037        // their settings.
1038        {
1039            let mut options_table = Table::new();
1040
1041            if self.options.resolution_mode != ResolutionMode::default() {
1042                options_table.insert(
1043                    "resolution-mode",
1044                    value(self.options.resolution_mode.to_string()),
1045                );
1046            }
1047            if self.options.prerelease_mode != PrereleaseMode::default() {
1048                options_table.insert(
1049                    "prerelease-mode",
1050                    value(self.options.prerelease_mode.to_string()),
1051                );
1052            }
1053            if self.options.fork_strategy != ForkStrategy::default() {
1054                options_table.insert(
1055                    "fork-strategy",
1056                    value(self.options.fork_strategy.to_string()),
1057                );
1058            }
1059            let exclude_newer = ExcludeNewer::from(self.options.exclude_newer.clone());
1060            if !exclude_newer.is_empty() {
1061                // Always serialize global exclude-newer as a string
1062                if let Some(global) = exclude_newer.global {
1063                    options_table.insert("exclude-newer", value(global.to_string()));
1064                }
1065
1066                // Serialize package-specific exclusions as a separate field
1067                if !exclude_newer.package.is_empty() {
1068                    let mut package_table = toml_edit::Table::new();
1069                    for (name, timestamp) in &exclude_newer.package {
1070                        package_table.insert(name.as_ref(), value(timestamp.to_string()));
1071                    }
1072                    options_table.insert("exclude-newer-package", Item::Table(package_table));
1073                }
1074            }
1075
1076            if !options_table.is_empty() {
1077                doc.insert("options", Item::Table(options_table));
1078            }
1079        }
1080
1081        // Write the manifest that was used to generate the resolution.
1082        {
1083            let mut manifest_table = Table::new();
1084
1085            if !self.manifest.members.is_empty() {
1086                manifest_table.insert(
1087                    "members",
1088                    value(each_element_on_its_line_array(
1089                        self.manifest
1090                            .members
1091                            .iter()
1092                            .map(std::string::ToString::to_string),
1093                    )),
1094                );
1095            }
1096
1097            if !self.manifest.requirements.is_empty() {
1098                let requirements = self
1099                    .manifest
1100                    .requirements
1101                    .iter()
1102                    .map(|requirement| {
1103                        serde::Serialize::serialize(
1104                            &requirement,
1105                            toml_edit::ser::ValueSerializer::new(),
1106                        )
1107                    })
1108                    .collect::<Result<Vec<_>, _>>()?;
1109                let requirements = match requirements.as_slice() {
1110                    [] => Array::new(),
1111                    [requirement] => Array::from_iter([requirement]),
1112                    requirements => each_element_on_its_line_array(requirements.iter()),
1113                };
1114                manifest_table.insert("requirements", value(requirements));
1115            }
1116
1117            if !self.manifest.constraints.is_empty() {
1118                let constraints = self
1119                    .manifest
1120                    .constraints
1121                    .iter()
1122                    .map(|requirement| {
1123                        serde::Serialize::serialize(
1124                            &requirement,
1125                            toml_edit::ser::ValueSerializer::new(),
1126                        )
1127                    })
1128                    .collect::<Result<Vec<_>, _>>()?;
1129                let constraints = match constraints.as_slice() {
1130                    [] => Array::new(),
1131                    [requirement] => Array::from_iter([requirement]),
1132                    constraints => each_element_on_its_line_array(constraints.iter()),
1133                };
1134                manifest_table.insert("constraints", value(constraints));
1135            }
1136
1137            if !self.manifest.overrides.is_empty() {
1138                let overrides = self
1139                    .manifest
1140                    .overrides
1141                    .iter()
1142                    .map(|requirement| {
1143                        serde::Serialize::serialize(
1144                            &requirement,
1145                            toml_edit::ser::ValueSerializer::new(),
1146                        )
1147                    })
1148                    .collect::<Result<Vec<_>, _>>()?;
1149                let overrides = match overrides.as_slice() {
1150                    [] => Array::new(),
1151                    [requirement] => Array::from_iter([requirement]),
1152                    overrides => each_element_on_its_line_array(overrides.iter()),
1153                };
1154                manifest_table.insert("overrides", value(overrides));
1155            }
1156
1157            if !self.manifest.excludes.is_empty() {
1158                let excludes = self
1159                    .manifest
1160                    .excludes
1161                    .iter()
1162                    .map(|name| {
1163                        serde::Serialize::serialize(&name, toml_edit::ser::ValueSerializer::new())
1164                    })
1165                    .collect::<Result<Vec<_>, _>>()?;
1166                let excludes = match excludes.as_slice() {
1167                    [] => Array::new(),
1168                    [name] => Array::from_iter([name]),
1169                    excludes => each_element_on_its_line_array(excludes.iter()),
1170                };
1171                manifest_table.insert("excludes", value(excludes));
1172            }
1173
1174            if !self.manifest.build_constraints.is_empty() {
1175                let build_constraints = self
1176                    .manifest
1177                    .build_constraints
1178                    .iter()
1179                    .map(|requirement| {
1180                        serde::Serialize::serialize(
1181                            &requirement,
1182                            toml_edit::ser::ValueSerializer::new(),
1183                        )
1184                    })
1185                    .collect::<Result<Vec<_>, _>>()?;
1186                let build_constraints = match build_constraints.as_slice() {
1187                    [] => Array::new(),
1188                    [requirement] => Array::from_iter([requirement]),
1189                    build_constraints => each_element_on_its_line_array(build_constraints.iter()),
1190                };
1191                manifest_table.insert("build-constraints", value(build_constraints));
1192            }
1193
1194            if !self.manifest.dependency_groups.is_empty() {
1195                let mut dependency_groups = Table::new();
1196                for (extra, requirements) in &self.manifest.dependency_groups {
1197                    let requirements = requirements
1198                        .iter()
1199                        .map(|requirement| {
1200                            serde::Serialize::serialize(
1201                                &requirement,
1202                                toml_edit::ser::ValueSerializer::new(),
1203                            )
1204                        })
1205                        .collect::<Result<Vec<_>, _>>()?;
1206                    let requirements = match requirements.as_slice() {
1207                        [] => Array::new(),
1208                        [requirement] => Array::from_iter([requirement]),
1209                        requirements => each_element_on_its_line_array(requirements.iter()),
1210                    };
1211                    if !requirements.is_empty() {
1212                        dependency_groups.insert(extra.as_ref(), value(requirements));
1213                    }
1214                }
1215                if !dependency_groups.is_empty() {
1216                    manifest_table.insert("dependency-groups", Item::Table(dependency_groups));
1217                }
1218            }
1219
1220            if !self.manifest.dependency_metadata.is_empty() {
1221                let mut tables = ArrayOfTables::new();
1222                for metadata in &self.manifest.dependency_metadata {
1223                    let mut table = Table::new();
1224                    table.insert("name", value(metadata.name.to_string()));
1225                    if let Some(version) = metadata.version.as_ref() {
1226                        table.insert("version", value(version.to_string()));
1227                    }
1228                    if !metadata.requires_dist.is_empty() {
1229                        table.insert(
1230                            "requires-dist",
1231                            value(serde::Serialize::serialize(
1232                                &metadata.requires_dist,
1233                                toml_edit::ser::ValueSerializer::new(),
1234                            )?),
1235                        );
1236                    }
1237                    if let Some(requires_python) = metadata.requires_python.as_ref() {
1238                        table.insert("requires-python", value(requires_python.to_string()));
1239                    }
1240                    if !metadata.provides_extra.is_empty() {
1241                        table.insert(
1242                            "provides-extras",
1243                            value(serde::Serialize::serialize(
1244                                &metadata.provides_extra,
1245                                toml_edit::ser::ValueSerializer::new(),
1246                            )?),
1247                        );
1248                    }
1249                    tables.push(table);
1250                }
1251                manifest_table.insert("dependency-metadata", Item::ArrayOfTables(tables));
1252            }
1253
1254            if !manifest_table.is_empty() {
1255                doc.insert("manifest", Item::Table(manifest_table));
1256            }
1257        }
1258
1259        // Count the number of packages for each package name. When
1260        // there's only one package for a particular package name (the
1261        // overwhelmingly common case), we can omit some data (like source and
1262        // version) on dependency edges since it is strictly redundant.
1263        let mut dist_count_by_name: FxHashMap<PackageName, u64> = FxHashMap::default();
1264        for dist in &self.packages {
1265            *dist_count_by_name.entry(dist.id.name.clone()).or_default() += 1;
1266        }
1267
1268        let mut packages = ArrayOfTables::new();
1269        for dist in &self.packages {
1270            packages.push(dist.to_toml(&self.requires_python, &dist_count_by_name)?);
1271        }
1272
1273        doc.insert("package", Item::ArrayOfTables(packages));
1274        Ok(doc.to_string())
1275    }
1276
1277    /// Returns the package with the given name. If there are multiple
1278    /// matching packages, then an error is returned. If there are no
1279    /// matching packages, then `Ok(None)` is returned.
1280    pub fn find_by_name(&self, name: &PackageName) -> Result<Option<&Package>, String> {
1281        let mut found_dist = None;
1282        for dist in &self.packages {
1283            if &dist.id.name == name {
1284                if found_dist.is_some() {
1285                    return Err(format!("found multiple packages matching `{name}`"));
1286                }
1287                found_dist = Some(dist);
1288            }
1289        }
1290        Ok(found_dist)
1291    }
1292
1293    /// Returns the package with the given name.
1294    ///
1295    /// If there are multiple matching packages, returns the package that
1296    /// corresponds to the given marker tree.
1297    ///
1298    /// If there are multiple packages that are relevant to the current
1299    /// markers, then an error is returned.
1300    ///
1301    /// If there are no matching packages, then `Ok(None)` is returned.
1302    fn find_by_markers(
1303        &self,
1304        name: &PackageName,
1305        marker_env: &MarkerEnvironment,
1306    ) -> Result<Option<&Package>, String> {
1307        let mut found_dist = None;
1308        for dist in &self.packages {
1309            if &dist.id.name == name {
1310                if dist.fork_markers.is_empty()
1311                    || dist
1312                        .fork_markers
1313                        .iter()
1314                        .any(|marker| marker.evaluate_no_extras(marker_env))
1315                {
1316                    if found_dist.is_some() {
1317                        return Err(format!("found multiple packages matching `{name}`"));
1318                    }
1319                    found_dist = Some(dist);
1320                }
1321            }
1322        }
1323        Ok(found_dist)
1324    }
1325
1326    fn find_by_id(&self, id: &PackageId) -> &Package {
1327        let index = *self.by_id.get(id).expect("locked package for ID");
1328
1329        (self.packages.get(index).expect("valid index for package")) as _
1330    }
1331
1332    /// Return a [`SatisfiesResult`] if the given extras do not match the [`Package`] metadata.
1333    fn satisfies_provides_extra<'lock>(
1334        &self,
1335        provides_extra: Box<[ExtraName]>,
1336        package: &'lock Package,
1337    ) -> SatisfiesResult<'lock> {
1338        if !self.supports_provides_extra() {
1339            return SatisfiesResult::Satisfied;
1340        }
1341
1342        let expected: BTreeSet<_> = provides_extra.iter().collect();
1343        let actual: BTreeSet<_> = package.metadata.provides_extra.iter().collect();
1344
1345        if expected != actual {
1346            let expected = Box::into_iter(provides_extra).collect();
1347            return SatisfiesResult::MismatchedPackageProvidesExtra(
1348                &package.id.name,
1349                package.id.version.as_ref(),
1350                expected,
1351                actual,
1352            );
1353        }
1354
1355        SatisfiesResult::Satisfied
1356    }
1357
1358    /// Return a [`SatisfiesResult`] if the given requirements do not match the [`Package`] metadata.
1359    #[allow(clippy::unused_self)]
1360    fn satisfies_requires_dist<'lock>(
1361        &self,
1362        requires_dist: Box<[Requirement]>,
1363        dependency_groups: BTreeMap<GroupName, Box<[Requirement]>>,
1364        package: &'lock Package,
1365        root: &Path,
1366    ) -> Result<SatisfiesResult<'lock>, LockError> {
1367        // Special-case: if the version is dynamic, compare the flattened requirements.
1368        let flattened = if package.is_dynamic() {
1369            Some(
1370                FlatRequiresDist::from_requirements(requires_dist.clone(), &package.id.name)
1371                    .into_iter()
1372                    .map(|requirement| {
1373                        normalize_requirement(requirement, root, &self.requires_python)
1374                    })
1375                    .collect::<Result<BTreeSet<_>, _>>()?,
1376            )
1377        } else {
1378            None
1379        };
1380
1381        // Validate the `requires-dist` metadata.
1382        let expected: BTreeSet<_> = Box::into_iter(requires_dist)
1383            .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1384            .collect::<Result<_, _>>()?;
1385        let actual: BTreeSet<_> = package
1386            .metadata
1387            .requires_dist
1388            .iter()
1389            .cloned()
1390            .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1391            .collect::<Result<_, _>>()?;
1392
1393        if expected != actual && flattened.is_none_or(|expected| expected != actual) {
1394            return Ok(SatisfiesResult::MismatchedPackageRequirements(
1395                &package.id.name,
1396                package.id.version.as_ref(),
1397                expected,
1398                actual,
1399            ));
1400        }
1401
1402        // Validate the `dependency-groups` metadata.
1403        let expected: BTreeMap<GroupName, BTreeSet<Requirement>> = dependency_groups
1404            .into_iter()
1405            .filter(|(_, requirements)| self.includes_empty_groups() || !requirements.is_empty())
1406            .map(|(group, requirements)| {
1407                Ok::<_, LockError>((
1408                    group,
1409                    Box::into_iter(requirements)
1410                        .map(|requirement| {
1411                            normalize_requirement(requirement, root, &self.requires_python)
1412                        })
1413                        .collect::<Result<_, _>>()?,
1414                ))
1415            })
1416            .collect::<Result<_, _>>()?;
1417        let actual: BTreeMap<GroupName, BTreeSet<Requirement>> = package
1418            .metadata
1419            .dependency_groups
1420            .iter()
1421            .filter(|(_, requirements)| self.includes_empty_groups() || !requirements.is_empty())
1422            .map(|(group, requirements)| {
1423                Ok::<_, LockError>((
1424                    group.clone(),
1425                    requirements
1426                        .iter()
1427                        .cloned()
1428                        .map(|requirement| {
1429                            normalize_requirement(requirement, root, &self.requires_python)
1430                        })
1431                        .collect::<Result<_, _>>()?,
1432                ))
1433            })
1434            .collect::<Result<_, _>>()?;
1435
1436        if expected != actual {
1437            return Ok(SatisfiesResult::MismatchedPackageDependencyGroups(
1438                &package.id.name,
1439                package.id.version.as_ref(),
1440                expected,
1441                actual,
1442            ));
1443        }
1444
1445        Ok(SatisfiesResult::Satisfied)
1446    }
1447
1448    /// Convert the [`Lock`] to a [`Resolution`] using the given marker environment, tags, and root.
1449    pub async fn satisfies<Context: BuildContext>(
1450        &self,
1451        root: &Path,
1452        packages: &BTreeMap<PackageName, WorkspaceMember>,
1453        members: &[PackageName],
1454        required_members: &BTreeMap<PackageName, Editability>,
1455        requirements: &[Requirement],
1456        constraints: &[Requirement],
1457        overrides: &[Requirement],
1458        excludes: &[PackageName],
1459        build_constraints: &[Requirement],
1460        dependency_groups: &BTreeMap<GroupName, Vec<Requirement>>,
1461        dependency_metadata: &DependencyMetadata,
1462        indexes: Option<&IndexLocations>,
1463        tags: &Tags,
1464        markers: &MarkerEnvironment,
1465        hasher: &HashStrategy,
1466        index: &InMemoryIndex,
1467        database: &DistributionDatabase<'_, Context>,
1468    ) -> Result<SatisfiesResult<'_>, LockError> {
1469        let mut queue: VecDeque<&Package> = VecDeque::new();
1470        let mut seen = FxHashSet::default();
1471
1472        // Validate that the lockfile was generated with the same root members.
1473        {
1474            let expected = members.iter().cloned().collect::<BTreeSet<_>>();
1475            let actual = &self.manifest.members;
1476            if expected != *actual {
1477                return Ok(SatisfiesResult::MismatchedMembers(expected, actual));
1478            }
1479        }
1480
1481        // Validate that the member sources have not changed (e.g., that they've switched from
1482        // virtual to non-virtual or vice versa).
1483        for (name, member) in packages {
1484            let source = self.find_by_name(name).ok().flatten();
1485
1486            // Determine whether the member was required by any other member.
1487            let value = required_members.get(name);
1488            let is_required_member = value.is_some();
1489            let editability = value.copied().flatten();
1490
1491            // Verify that the member is virtual (or not).
1492            let expected_virtual = !member.pyproject_toml().is_package(!is_required_member);
1493            let actual_virtual =
1494                source.map(|package| matches!(package.id.source, Source::Virtual(..)));
1495            if actual_virtual != Some(expected_virtual) {
1496                return Ok(SatisfiesResult::MismatchedVirtual(
1497                    name.clone(),
1498                    expected_virtual,
1499                ));
1500            }
1501
1502            // Verify that the member is editable (or not).
1503            let expected_editable = if expected_virtual {
1504                false
1505            } else {
1506                editability.unwrap_or(true)
1507            };
1508            let actual_editable =
1509                source.map(|package| matches!(package.id.source, Source::Editable(..)));
1510            if actual_editable != Some(expected_editable) {
1511                return Ok(SatisfiesResult::MismatchedEditable(
1512                    name.clone(),
1513                    expected_editable,
1514                ));
1515            }
1516        }
1517
1518        // Validate that the lockfile was generated with the same requirements.
1519        {
1520            let expected: BTreeSet<_> = requirements
1521                .iter()
1522                .cloned()
1523                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1524                .collect::<Result<_, _>>()?;
1525            let actual: BTreeSet<_> = self
1526                .manifest
1527                .requirements
1528                .iter()
1529                .cloned()
1530                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1531                .collect::<Result<_, _>>()?;
1532            if expected != actual {
1533                return Ok(SatisfiesResult::MismatchedRequirements(expected, actual));
1534            }
1535        }
1536
1537        // Validate that the lockfile was generated with the same constraints.
1538        {
1539            let expected: BTreeSet<_> = constraints
1540                .iter()
1541                .cloned()
1542                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1543                .collect::<Result<_, _>>()?;
1544            let actual: BTreeSet<_> = self
1545                .manifest
1546                .constraints
1547                .iter()
1548                .cloned()
1549                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1550                .collect::<Result<_, _>>()?;
1551            if expected != actual {
1552                return Ok(SatisfiesResult::MismatchedConstraints(expected, actual));
1553            }
1554        }
1555
1556        // Validate that the lockfile was generated with the same overrides.
1557        {
1558            let expected: BTreeSet<_> = overrides
1559                .iter()
1560                .cloned()
1561                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1562                .collect::<Result<_, _>>()?;
1563            let actual: BTreeSet<_> = self
1564                .manifest
1565                .overrides
1566                .iter()
1567                .cloned()
1568                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1569                .collect::<Result<_, _>>()?;
1570            if expected != actual {
1571                return Ok(SatisfiesResult::MismatchedOverrides(expected, actual));
1572            }
1573        }
1574
1575        // Validate that the lockfile was generated with the same excludes.
1576        {
1577            let expected: BTreeSet<_> = excludes.iter().cloned().collect();
1578            let actual: BTreeSet<_> = self.manifest.excludes.iter().cloned().collect();
1579            if expected != actual {
1580                return Ok(SatisfiesResult::MismatchedExcludes(expected, actual));
1581            }
1582        }
1583
1584        // Validate that the lockfile was generated with the same build constraints.
1585        {
1586            let expected: BTreeSet<_> = build_constraints
1587                .iter()
1588                .cloned()
1589                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1590                .collect::<Result<_, _>>()?;
1591            let actual: BTreeSet<_> = self
1592                .manifest
1593                .build_constraints
1594                .iter()
1595                .cloned()
1596                .map(|requirement| normalize_requirement(requirement, root, &self.requires_python))
1597                .collect::<Result<_, _>>()?;
1598            if expected != actual {
1599                return Ok(SatisfiesResult::MismatchedBuildConstraints(
1600                    expected, actual,
1601                ));
1602            }
1603        }
1604
1605        // Validate that the lockfile was generated with the dependency groups.
1606        {
1607            let expected: BTreeMap<GroupName, BTreeSet<Requirement>> = dependency_groups
1608                .iter()
1609                .filter(|(_, requirements)| !requirements.is_empty())
1610                .map(|(group, requirements)| {
1611                    Ok::<_, LockError>((
1612                        group.clone(),
1613                        requirements
1614                            .iter()
1615                            .cloned()
1616                            .map(|requirement| {
1617                                normalize_requirement(requirement, root, &self.requires_python)
1618                            })
1619                            .collect::<Result<_, _>>()?,
1620                    ))
1621                })
1622                .collect::<Result<_, _>>()?;
1623            let actual: BTreeMap<GroupName, BTreeSet<Requirement>> = self
1624                .manifest
1625                .dependency_groups
1626                .iter()
1627                .filter(|(_, requirements)| !requirements.is_empty())
1628                .map(|(group, requirements)| {
1629                    Ok::<_, LockError>((
1630                        group.clone(),
1631                        requirements
1632                            .iter()
1633                            .cloned()
1634                            .map(|requirement| {
1635                                normalize_requirement(requirement, root, &self.requires_python)
1636                            })
1637                            .collect::<Result<_, _>>()?,
1638                    ))
1639                })
1640                .collect::<Result<_, _>>()?;
1641            if expected != actual {
1642                return Ok(SatisfiesResult::MismatchedDependencyGroups(
1643                    expected, actual,
1644                ));
1645            }
1646        }
1647
1648        // Validate that the lockfile was generated with the same static metadata.
1649        {
1650            let expected = dependency_metadata
1651                .values()
1652                .cloned()
1653                .collect::<BTreeSet<_>>();
1654            let actual = &self.manifest.dependency_metadata;
1655            if expected != *actual {
1656                return Ok(SatisfiesResult::MismatchedStaticMetadata(expected, actual));
1657            }
1658        }
1659
1660        // Collect the set of available indexes (both `--index-url` and `--find-links` entries).
1661        let mut remotes = indexes.map(|locations| {
1662            locations
1663                .allowed_indexes()
1664                .into_iter()
1665                .filter_map(|index| match index.url() {
1666                    IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
1667                        Some(UrlString::from(index.url().without_credentials().as_ref()))
1668                    }
1669                    IndexUrl::Path(_) => None,
1670                })
1671                .collect::<BTreeSet<_>>()
1672        });
1673
1674        let mut locals = indexes.map(|locations| {
1675            locations
1676                .allowed_indexes()
1677                .into_iter()
1678                .filter_map(|index| match index.url() {
1679                    IndexUrl::Pypi(_) | IndexUrl::Url(_) => None,
1680                    IndexUrl::Path(url) => {
1681                        let path = url.to_file_path().ok()?;
1682                        let path = relative_to(&path, root)
1683                            .or_else(|_| std::path::absolute(path))
1684                            .ok()?
1685                            .into_boxed_path();
1686                        Some(path)
1687                    }
1688                })
1689                .collect::<BTreeSet<_>>()
1690        });
1691
1692        // Add the workspace packages to the queue.
1693        for root_name in packages.keys() {
1694            let root = self
1695                .find_by_name(root_name)
1696                .expect("found too many packages matching root");
1697
1698            let Some(root) = root else {
1699                // The package is not in the lockfile, so it can't be satisfied.
1700                return Ok(SatisfiesResult::MissingRoot(root_name.clone()));
1701            };
1702
1703            // Add the base package.
1704            queue.push_back(root);
1705        }
1706
1707        while let Some(package) = queue.pop_front() {
1708            // If the lockfile references an index that was not provided, we can't validate it.
1709            if let Source::Registry(index) = &package.id.source {
1710                match index {
1711                    RegistrySource::Url(url) => {
1712                        if remotes
1713                            .as_ref()
1714                            .is_some_and(|remotes| !remotes.contains(url))
1715                        {
1716                            let name = &package.id.name;
1717                            let version = &package
1718                                .id
1719                                .version
1720                                .as_ref()
1721                                .expect("version for registry source");
1722                            return Ok(SatisfiesResult::MissingRemoteIndex(name, version, url));
1723                        }
1724                    }
1725                    RegistrySource::Path(path) => {
1726                        if locals.as_ref().is_some_and(|locals| !locals.contains(path)) {
1727                            let name = &package.id.name;
1728                            let version = &package
1729                                .id
1730                                .version
1731                                .as_ref()
1732                                .expect("version for registry source");
1733                            return Ok(SatisfiesResult::MissingLocalIndex(name, version, path));
1734                        }
1735                    }
1736                }
1737            }
1738
1739            // If the package is immutable, we don't need to validate it (or its dependencies).
1740            if package.id.source.is_immutable() {
1741                continue;
1742            }
1743
1744            if let Some(version) = package.id.version.as_ref() {
1745                // For a non-dynamic package, fetch the metadata from the distribution database.
1746                let dist = package.to_dist(
1747                    root,
1748                    TagPolicy::Preferred(tags),
1749                    &BuildOptions::default(),
1750                    markers,
1751                )?;
1752
1753                let metadata = {
1754                    let id = dist.version_id();
1755                    if let Some(archive) =
1756                        index
1757                            .distributions()
1758                            .get(&id)
1759                            .as_deref()
1760                            .and_then(|response| {
1761                                if let MetadataResponse::Found(archive, ..) = response {
1762                                    Some(archive)
1763                                } else {
1764                                    None
1765                                }
1766                            })
1767                    {
1768                        // If the metadata is already in the index, return it.
1769                        archive.metadata.clone()
1770                    } else {
1771                        // Run the PEP 517 build process to extract metadata from the source distribution.
1772                        let archive = database
1773                            .get_or_build_wheel_metadata(&dist, hasher.get(&dist))
1774                            .await
1775                            .map_err(|err| LockErrorKind::Resolution {
1776                                id: package.id.clone(),
1777                                err,
1778                            })?;
1779
1780                        let metadata = archive.metadata.clone();
1781
1782                        // Insert the metadata into the index.
1783                        index
1784                            .distributions()
1785                            .done(id, Arc::new(MetadataResponse::Found(archive)));
1786
1787                        metadata
1788                    }
1789                };
1790
1791                // If this is a local package, validate that it hasn't become dynamic (in which
1792                // case, we'd expect the version to be omitted).
1793                if package.id.source.is_source_tree() {
1794                    if metadata.dynamic {
1795                        return Ok(SatisfiesResult::MismatchedDynamic(&package.id.name, false));
1796                    }
1797                }
1798
1799                // Validate the `version` metadata.
1800                if metadata.version != *version {
1801                    return Ok(SatisfiesResult::MismatchedVersion(
1802                        &package.id.name,
1803                        version.clone(),
1804                        Some(metadata.version.clone()),
1805                    ));
1806                }
1807
1808                // Validate the `provides-extras` metadata.
1809                match self.satisfies_provides_extra(metadata.provides_extra, package) {
1810                    SatisfiesResult::Satisfied => {}
1811                    result => return Ok(result),
1812                }
1813
1814                // Validate that the requirements are unchanged.
1815                match self.satisfies_requires_dist(
1816                    metadata.requires_dist,
1817                    metadata.dependency_groups,
1818                    package,
1819                    root,
1820                )? {
1821                    SatisfiesResult::Satisfied => {}
1822                    result => return Ok(result),
1823                }
1824            } else if let Some(source_tree) = package.id.source.as_source_tree() {
1825                // For dynamic packages, we don't need the version. We only need to know that the
1826                // package is still dynamic, and that the requirements are unchanged.
1827                //
1828                // If the distribution is a source tree, attempt to extract the requirements from the
1829                // `pyproject.toml` directly. The distribution database will do this too, but we can be
1830                // even more aggressive here since we _only_ need the requirements. So, for example,
1831                // even if the version is dynamic, we can still extract the requirements without
1832                // performing a build, unlike in the database where we typically construct a "complete"
1833                // metadata object.
1834                let parent = root.join(source_tree);
1835                let path = parent.join("pyproject.toml");
1836                let metadata =
1837                    match fs_err::tokio::read_to_string(&path).await {
1838                        Ok(contents) => {
1839                            let pyproject_toml = toml::from_str::<PyProjectToml>(&contents)
1840                                .map_err(|err| LockErrorKind::InvalidPyprojectToml {
1841                                    path: path.clone(),
1842                                    err,
1843                                })?;
1844                            database
1845                                .requires_dist(&parent, &pyproject_toml)
1846                                .await
1847                                .map_err(|err| LockErrorKind::Resolution {
1848                                    id: package.id.clone(),
1849                                    err,
1850                                })?
1851                        }
1852                        Err(err) if err.kind() == io::ErrorKind::NotFound => None,
1853                        Err(err) => {
1854                            return Err(LockErrorKind::UnreadablePyprojectToml { path, err }.into());
1855                        }
1856                    };
1857
1858                let satisfied = metadata.is_some_and(|metadata| {
1859                    // Validate that the package is still dynamic.
1860                    if !metadata.dynamic {
1861                        debug!("Static `requires-dist` for `{}` is out-of-date; falling back to distribution database", package.id);
1862                        return false;
1863                    }
1864
1865                    // Validate that the extras are unchanged.
1866                    if let SatisfiesResult::Satisfied = self.satisfies_provides_extra(metadata.provides_extra, package, ) {
1867                        debug!("Static `provides-extra` for `{}` is up-to-date", package.id);
1868                    } else {
1869                        debug!("Static `provides-extra` for `{}` is out-of-date; falling back to distribution database", package.id);
1870                        return false;
1871                    }
1872
1873                    // Validate that the requirements are unchanged.
1874                    match self.satisfies_requires_dist(metadata.requires_dist, metadata.dependency_groups, package, root) {
1875                        Ok(SatisfiesResult::Satisfied) => {
1876                            debug!("Static `requires-dist` for `{}` is up-to-date", package.id);
1877                        },
1878                        Ok(..) => {
1879                            debug!("Static `requires-dist` for `{}` is out-of-date; falling back to distribution database", package.id);
1880                            return false;
1881                        },
1882                        Err(..) => {
1883                            debug!("Static `requires-dist` for `{}` is invalid; falling back to distribution database", package.id);
1884                            return false;
1885                        },
1886                    }
1887
1888                    true
1889                });
1890
1891                // If the `requires-dist` metadata matches the requirements, we're done; otherwise,
1892                // fetch the "full" metadata, which may involve invoking the build system. In some
1893                // cases, build backends return metadata that does _not_ match the `pyproject.toml`
1894                // exactly. For example, `hatchling` will flatten any recursive (or self-referential)
1895                // extras, while `setuptools` will not.
1896                if !satisfied {
1897                    let dist = package.to_dist(
1898                        root,
1899                        TagPolicy::Preferred(tags),
1900                        &BuildOptions::default(),
1901                        markers,
1902                    )?;
1903
1904                    let metadata = {
1905                        let id = dist.version_id();
1906                        if let Some(archive) =
1907                            index
1908                                .distributions()
1909                                .get(&id)
1910                                .as_deref()
1911                                .and_then(|response| {
1912                                    if let MetadataResponse::Found(archive, ..) = response {
1913                                        Some(archive)
1914                                    } else {
1915                                        None
1916                                    }
1917                                })
1918                        {
1919                            // If the metadata is already in the index, return it.
1920                            archive.metadata.clone()
1921                        } else {
1922                            // Run the PEP 517 build process to extract metadata from the source distribution.
1923                            let archive = database
1924                                .get_or_build_wheel_metadata(&dist, hasher.get(&dist))
1925                                .await
1926                                .map_err(|err| LockErrorKind::Resolution {
1927                                    id: package.id.clone(),
1928                                    err,
1929                                })?;
1930
1931                            let metadata = archive.metadata.clone();
1932
1933                            // Insert the metadata into the index.
1934                            index
1935                                .distributions()
1936                                .done(id, Arc::new(MetadataResponse::Found(archive)));
1937
1938                            metadata
1939                        }
1940                    };
1941
1942                    // Validate that the package is still dynamic.
1943                    if !metadata.dynamic {
1944                        return Ok(SatisfiesResult::MismatchedDynamic(&package.id.name, true));
1945                    }
1946
1947                    // Validate that the extras are unchanged.
1948                    match self.satisfies_provides_extra(metadata.provides_extra, package) {
1949                        SatisfiesResult::Satisfied => {}
1950                        result => return Ok(result),
1951                    }
1952
1953                    // Validate that the requirements are unchanged.
1954                    match self.satisfies_requires_dist(
1955                        metadata.requires_dist,
1956                        metadata.dependency_groups,
1957                        package,
1958                        root,
1959                    )? {
1960                        SatisfiesResult::Satisfied => {}
1961                        result => return Ok(result),
1962                    }
1963                }
1964            } else {
1965                return Ok(SatisfiesResult::MissingVersion(&package.id.name));
1966            }
1967
1968            // Add any explicit indexes to the list of known locals or remotes. These indexes may
1969            // not be available as top-level configuration (i.e., if they're defined within a
1970            // workspace member), but we already validated that the dependencies are up-to-date, so
1971            // we can consider them "available".
1972            for requirement in &package.metadata.requires_dist {
1973                if let RequirementSource::Registry {
1974                    index: Some(index), ..
1975                } = &requirement.source
1976                {
1977                    match &index.url {
1978                        IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
1979                            if let Some(remotes) = remotes.as_mut() {
1980                                remotes.insert(UrlString::from(
1981                                    index.url().without_credentials().as_ref(),
1982                                ));
1983                            }
1984                        }
1985                        IndexUrl::Path(url) => {
1986                            if let Some(locals) = locals.as_mut() {
1987                                if let Some(path) = url.to_file_path().ok().and_then(|path| {
1988                                    relative_to(&path, root)
1989                                        .or_else(|_| std::path::absolute(path))
1990                                        .ok()
1991                                }) {
1992                                    locals.insert(path.into_boxed_path());
1993                                }
1994                            }
1995                        }
1996                    }
1997                }
1998            }
1999
2000            // Recurse.
2001            for dep in &package.dependencies {
2002                if seen.insert(&dep.package_id) {
2003                    let dep_dist = self.find_by_id(&dep.package_id);
2004                    queue.push_back(dep_dist);
2005                }
2006            }
2007
2008            for dependencies in package.optional_dependencies.values() {
2009                for dep in dependencies {
2010                    if seen.insert(&dep.package_id) {
2011                        let dep_dist = self.find_by_id(&dep.package_id);
2012                        queue.push_back(dep_dist);
2013                    }
2014                }
2015            }
2016
2017            for dependencies in package.dependency_groups.values() {
2018                for dep in dependencies {
2019                    if seen.insert(&dep.package_id) {
2020                        let dep_dist = self.find_by_id(&dep.package_id);
2021                        queue.push_back(dep_dist);
2022                    }
2023                }
2024            }
2025        }
2026
2027        Ok(SatisfiesResult::Satisfied)
2028    }
2029}
2030
2031#[derive(Debug, Copy, Clone)]
2032enum TagPolicy<'tags> {
2033    /// Exclusively consider wheels that match the specified platform tags.
2034    Required(&'tags Tags),
2035    /// Prefer wheels that match the specified platform tags, but fall back to incompatible wheels
2036    /// if necessary.
2037    Preferred(&'tags Tags),
2038}
2039
2040impl<'tags> TagPolicy<'tags> {
2041    /// Returns the platform tags to consider.
2042    fn tags(&self) -> &'tags Tags {
2043        match self {
2044            Self::Required(tags) | Self::Preferred(tags) => tags,
2045        }
2046    }
2047}
2048
2049/// The result of checking if a lockfile satisfies a set of requirements.
2050#[derive(Debug)]
2051pub enum SatisfiesResult<'lock> {
2052    /// The lockfile satisfies the requirements.
2053    Satisfied,
2054    /// The lockfile uses a different set of workspace members.
2055    MismatchedMembers(BTreeSet<PackageName>, &'lock BTreeSet<PackageName>),
2056    /// A workspace member switched from virtual to non-virtual or vice versa.
2057    MismatchedVirtual(PackageName, bool),
2058    /// A workspace member switched from editable to non-editable or vice versa.
2059    MismatchedEditable(PackageName, bool),
2060    /// A source tree switched from dynamic to non-dynamic or vice versa.
2061    MismatchedDynamic(&'lock PackageName, bool),
2062    /// The lockfile uses a different set of version for its workspace members.
2063    MismatchedVersion(&'lock PackageName, Version, Option<Version>),
2064    /// The lockfile uses a different set of requirements.
2065    MismatchedRequirements(BTreeSet<Requirement>, BTreeSet<Requirement>),
2066    /// The lockfile uses a different set of constraints.
2067    MismatchedConstraints(BTreeSet<Requirement>, BTreeSet<Requirement>),
2068    /// The lockfile uses a different set of overrides.
2069    MismatchedOverrides(BTreeSet<Requirement>, BTreeSet<Requirement>),
2070    /// The lockfile uses a different set of excludes.
2071    MismatchedExcludes(BTreeSet<PackageName>, BTreeSet<PackageName>),
2072    /// The lockfile uses a different set of build constraints.
2073    MismatchedBuildConstraints(BTreeSet<Requirement>, BTreeSet<Requirement>),
2074    /// The lockfile uses a different set of dependency groups.
2075    MismatchedDependencyGroups(
2076        BTreeMap<GroupName, BTreeSet<Requirement>>,
2077        BTreeMap<GroupName, BTreeSet<Requirement>>,
2078    ),
2079    /// The lockfile uses different static metadata.
2080    MismatchedStaticMetadata(BTreeSet<StaticMetadata>, &'lock BTreeSet<StaticMetadata>),
2081    /// The lockfile is missing a workspace member.
2082    MissingRoot(PackageName),
2083    /// The lockfile referenced a remote index that was not provided
2084    MissingRemoteIndex(&'lock PackageName, &'lock Version, &'lock UrlString),
2085    /// The lockfile referenced a local index that was not provided
2086    MissingLocalIndex(&'lock PackageName, &'lock Version, &'lock Path),
2087    /// A package in the lockfile contains different `requires-dist` metadata than expected.
2088    MismatchedPackageRequirements(
2089        &'lock PackageName,
2090        Option<&'lock Version>,
2091        BTreeSet<Requirement>,
2092        BTreeSet<Requirement>,
2093    ),
2094    /// A package in the lockfile contains different `provides-extra` metadata than expected.
2095    MismatchedPackageProvidesExtra(
2096        &'lock PackageName,
2097        Option<&'lock Version>,
2098        BTreeSet<ExtraName>,
2099        BTreeSet<&'lock ExtraName>,
2100    ),
2101    /// A package in the lockfile contains different `dependency-groups` metadata than expected.
2102    MismatchedPackageDependencyGroups(
2103        &'lock PackageName,
2104        Option<&'lock Version>,
2105        BTreeMap<GroupName, BTreeSet<Requirement>>,
2106        BTreeMap<GroupName, BTreeSet<Requirement>>,
2107    ),
2108    /// The lockfile is missing a version.
2109    MissingVersion(&'lock PackageName),
2110}
2111
2112/// We discard the lockfile if these options match.
2113#[derive(Clone, Debug, Default, serde::Deserialize, PartialEq, Eq)]
2114#[serde(rename_all = "kebab-case")]
2115struct ResolverOptions {
2116    /// The [`ResolutionMode`] used to generate this lock.
2117    #[serde(default)]
2118    resolution_mode: ResolutionMode,
2119    /// The [`PrereleaseMode`] used to generate this lock.
2120    #[serde(default)]
2121    prerelease_mode: PrereleaseMode,
2122    /// The [`ForkStrategy`] used to generate this lock.
2123    #[serde(default)]
2124    fork_strategy: ForkStrategy,
2125    /// The [`ExcludeNewer`] setting used to generate this lock.
2126    #[serde(flatten)]
2127    exclude_newer: ExcludeNewerWire,
2128}
2129
2130#[derive(Clone, Debug, Default, serde::Deserialize, PartialEq, Eq)]
2131#[serde(rename_all = "kebab-case")]
2132struct ExcludeNewerWire {
2133    exclude_newer: Option<ExcludeNewerTimestamp>,
2134    #[serde(default, skip_serializing_if = "ExcludeNewerPackage::is_empty")]
2135    exclude_newer_package: ExcludeNewerPackage,
2136}
2137
2138impl From<ExcludeNewerWire> for ExcludeNewer {
2139    fn from(wire: ExcludeNewerWire) -> Self {
2140        Self {
2141            global: wire.exclude_newer,
2142            package: wire.exclude_newer_package,
2143        }
2144    }
2145}
2146
2147impl From<ExcludeNewer> for ExcludeNewerWire {
2148    fn from(exclude_newer: ExcludeNewer) -> Self {
2149        Self {
2150            exclude_newer: exclude_newer.global,
2151            exclude_newer_package: exclude_newer.package,
2152        }
2153    }
2154}
2155
2156#[derive(Clone, Debug, Default, serde::Deserialize, PartialEq, Eq)]
2157#[serde(rename_all = "kebab-case")]
2158pub struct ResolverManifest {
2159    /// The workspace members included in the lockfile.
2160    #[serde(default)]
2161    members: BTreeSet<PackageName>,
2162    /// The requirements provided to the resolver, exclusive of the workspace members.
2163    ///
2164    /// These are requirements that are attached to the project, but not to any of its
2165    /// workspace members. For example, the requirements in a PEP 723 script would be included here.
2166    #[serde(default)]
2167    requirements: BTreeSet<Requirement>,
2168    /// The dependency groups provided to the resolver, exclusive of the workspace members.
2169    ///
2170    /// These are dependency groups that are attached to the project, but not to any of its
2171    /// workspace members. For example, the dependency groups in a `pyproject.toml` without a
2172    /// `[project]` table would be included here.
2173    #[serde(default)]
2174    dependency_groups: BTreeMap<GroupName, BTreeSet<Requirement>>,
2175    /// The constraints provided to the resolver.
2176    #[serde(default)]
2177    constraints: BTreeSet<Requirement>,
2178    /// The overrides provided to the resolver.
2179    #[serde(default)]
2180    overrides: BTreeSet<Requirement>,
2181    /// The excludes provided to the resolver.
2182    #[serde(default)]
2183    excludes: BTreeSet<PackageName>,
2184    /// The build constraints provided to the resolver.
2185    #[serde(default)]
2186    build_constraints: BTreeSet<Requirement>,
2187    /// The static metadata provided to the resolver.
2188    #[serde(default)]
2189    dependency_metadata: BTreeSet<StaticMetadata>,
2190}
2191
2192impl ResolverManifest {
2193    /// Initialize a [`ResolverManifest`] with the given members, requirements, constraints, and
2194    /// overrides.
2195    pub fn new(
2196        members: impl IntoIterator<Item = PackageName>,
2197        requirements: impl IntoIterator<Item = Requirement>,
2198        constraints: impl IntoIterator<Item = Requirement>,
2199        overrides: impl IntoIterator<Item = Requirement>,
2200        excludes: impl IntoIterator<Item = PackageName>,
2201        build_constraints: impl IntoIterator<Item = Requirement>,
2202        dependency_groups: impl IntoIterator<Item = (GroupName, Vec<Requirement>)>,
2203        dependency_metadata: impl IntoIterator<Item = StaticMetadata>,
2204    ) -> Self {
2205        Self {
2206            members: members.into_iter().collect(),
2207            requirements: requirements.into_iter().collect(),
2208            constraints: constraints.into_iter().collect(),
2209            overrides: overrides.into_iter().collect(),
2210            excludes: excludes.into_iter().collect(),
2211            build_constraints: build_constraints.into_iter().collect(),
2212            dependency_groups: dependency_groups
2213                .into_iter()
2214                .map(|(group, requirements)| (group, requirements.into_iter().collect()))
2215                .collect(),
2216            dependency_metadata: dependency_metadata.into_iter().collect(),
2217        }
2218    }
2219
2220    /// Convert the manifest to a relative form using the given workspace.
2221    pub fn relative_to(self, root: &Path) -> Result<Self, io::Error> {
2222        Ok(Self {
2223            members: self.members,
2224            requirements: self
2225                .requirements
2226                .into_iter()
2227                .map(|requirement| requirement.relative_to(root))
2228                .collect::<Result<BTreeSet<_>, _>>()?,
2229            constraints: self
2230                .constraints
2231                .into_iter()
2232                .map(|requirement| requirement.relative_to(root))
2233                .collect::<Result<BTreeSet<_>, _>>()?,
2234            overrides: self
2235                .overrides
2236                .into_iter()
2237                .map(|requirement| requirement.relative_to(root))
2238                .collect::<Result<BTreeSet<_>, _>>()?,
2239            excludes: self.excludes,
2240            build_constraints: self
2241                .build_constraints
2242                .into_iter()
2243                .map(|requirement| requirement.relative_to(root))
2244                .collect::<Result<BTreeSet<_>, _>>()?,
2245            dependency_groups: self
2246                .dependency_groups
2247                .into_iter()
2248                .map(|(group, requirements)| {
2249                    Ok::<_, io::Error>((
2250                        group,
2251                        requirements
2252                            .into_iter()
2253                            .map(|requirement| requirement.relative_to(root))
2254                            .collect::<Result<BTreeSet<_>, _>>()?,
2255                    ))
2256                })
2257                .collect::<Result<BTreeMap<_, _>, _>>()?,
2258            dependency_metadata: self.dependency_metadata,
2259        })
2260    }
2261}
2262
2263#[derive(Clone, Debug, serde::Deserialize)]
2264#[serde(rename_all = "kebab-case")]
2265struct LockWire {
2266    version: u32,
2267    revision: Option<u32>,
2268    requires_python: RequiresPython,
2269    /// If this lockfile was built from a forking resolution with non-identical forks, store the
2270    /// forks in the lockfile so we can recreate them in subsequent resolutions.
2271    #[serde(rename = "resolution-markers", default)]
2272    fork_markers: Vec<SimplifiedMarkerTree>,
2273    #[serde(rename = "supported-markers", default)]
2274    supported_environments: Vec<SimplifiedMarkerTree>,
2275    #[serde(rename = "required-markers", default)]
2276    required_environments: Vec<SimplifiedMarkerTree>,
2277    #[serde(rename = "conflicts", default)]
2278    conflicts: Option<Conflicts>,
2279    /// We discard the lockfile if these options match.
2280    #[serde(default)]
2281    options: ResolverOptions,
2282    #[serde(default)]
2283    manifest: ResolverManifest,
2284    #[serde(rename = "package", alias = "distribution", default)]
2285    packages: Vec<PackageWire>,
2286}
2287
2288impl TryFrom<LockWire> for Lock {
2289    type Error = LockError;
2290
2291    fn try_from(wire: LockWire) -> Result<Self, LockError> {
2292        // Count the number of sources for each package name. When
2293        // there's only one source for a particular package name (the
2294        // overwhelmingly common case), we can omit some data (like source and
2295        // version) on dependency edges since it is strictly redundant.
2296        let mut unambiguous_package_ids: FxHashMap<PackageName, PackageId> = FxHashMap::default();
2297        let mut ambiguous = FxHashSet::default();
2298        for dist in &wire.packages {
2299            if ambiguous.contains(&dist.id.name) {
2300                continue;
2301            }
2302            if let Some(id) = unambiguous_package_ids.remove(&dist.id.name) {
2303                ambiguous.insert(id.name);
2304                continue;
2305            }
2306            unambiguous_package_ids.insert(dist.id.name.clone(), dist.id.clone());
2307        }
2308
2309        let packages = wire
2310            .packages
2311            .into_iter()
2312            .map(|dist| dist.unwire(&wire.requires_python, &unambiguous_package_ids))
2313            .collect::<Result<Vec<_>, _>>()?;
2314        let supported_environments = wire
2315            .supported_environments
2316            .into_iter()
2317            .map(|simplified_marker| simplified_marker.into_marker(&wire.requires_python))
2318            .collect();
2319        let required_environments = wire
2320            .required_environments
2321            .into_iter()
2322            .map(|simplified_marker| simplified_marker.into_marker(&wire.requires_python))
2323            .collect();
2324        let fork_markers = wire
2325            .fork_markers
2326            .into_iter()
2327            .map(|simplified_marker| simplified_marker.into_marker(&wire.requires_python))
2328            .map(UniversalMarker::from_combined)
2329            .collect();
2330        let lock = Self::new(
2331            wire.version,
2332            wire.revision.unwrap_or(0),
2333            packages,
2334            wire.requires_python,
2335            wire.options,
2336            wire.manifest,
2337            wire.conflicts.unwrap_or_else(Conflicts::empty),
2338            supported_environments,
2339            required_environments,
2340            fork_markers,
2341        )?;
2342
2343        Ok(lock)
2344    }
2345}
2346
2347/// Like [`Lock`], but limited to the version field. Used for error reporting: by limiting parsing
2348/// to the version field, we can verify compatibility for lockfiles that may otherwise be
2349/// unparsable.
2350#[derive(Clone, Debug, serde::Deserialize)]
2351#[serde(rename_all = "kebab-case")]
2352pub struct LockVersion {
2353    version: u32,
2354}
2355
2356impl LockVersion {
2357    /// Returns the lockfile version.
2358    pub fn version(&self) -> u32 {
2359        self.version
2360    }
2361}
2362
2363#[derive(Clone, Debug, PartialEq, Eq)]
2364pub struct Package {
2365    pub(crate) id: PackageId,
2366    sdist: Option<SourceDist>,
2367    wheels: Vec<Wheel>,
2368    /// If there are multiple versions or sources for the same package name, we add the markers of
2369    /// the fork(s) that contained this version or source, so we can set the correct preferences in
2370    /// the next resolution.
2371    ///
2372    /// Named `resolution-markers` in `uv.lock`.
2373    fork_markers: Vec<UniversalMarker>,
2374    /// The resolved dependencies of the package.
2375    dependencies: Vec<Dependency>,
2376    /// The resolved optional dependencies of the package.
2377    optional_dependencies: BTreeMap<ExtraName, Vec<Dependency>>,
2378    /// The resolved PEP 735 dependency groups of the package.
2379    dependency_groups: BTreeMap<GroupName, Vec<Dependency>>,
2380    /// The exact requirements from the package metadata.
2381    metadata: PackageMetadata,
2382}
2383
2384impl Package {
2385    fn from_annotated_dist(
2386        annotated_dist: &AnnotatedDist,
2387        fork_markers: Vec<UniversalMarker>,
2388        root: &Path,
2389    ) -> Result<Self, LockError> {
2390        let id = PackageId::from_annotated_dist(annotated_dist, root)?;
2391        let sdist = SourceDist::from_annotated_dist(&id, annotated_dist)?;
2392        let wheels = Wheel::from_annotated_dist(annotated_dist)?;
2393        let requires_dist = if id.source.is_immutable() {
2394            BTreeSet::default()
2395        } else {
2396            annotated_dist
2397                .metadata
2398                .as_ref()
2399                .expect("metadata is present")
2400                .requires_dist
2401                .iter()
2402                .cloned()
2403                .map(|requirement| requirement.relative_to(root))
2404                .collect::<Result<_, _>>()
2405                .map_err(LockErrorKind::RequirementRelativePath)?
2406        };
2407        let provides_extra = if id.source.is_immutable() {
2408            Box::default()
2409        } else {
2410            annotated_dist
2411                .metadata
2412                .as_ref()
2413                .expect("metadata is present")
2414                .provides_extra
2415                .clone()
2416        };
2417        let dependency_groups = if id.source.is_immutable() {
2418            BTreeMap::default()
2419        } else {
2420            annotated_dist
2421                .metadata
2422                .as_ref()
2423                .expect("metadata is present")
2424                .dependency_groups
2425                .iter()
2426                .map(|(group, requirements)| {
2427                    let requirements = requirements
2428                        .iter()
2429                        .cloned()
2430                        .map(|requirement| requirement.relative_to(root))
2431                        .collect::<Result<_, _>>()
2432                        .map_err(LockErrorKind::RequirementRelativePath)?;
2433                    Ok::<_, LockError>((group.clone(), requirements))
2434                })
2435                .collect::<Result<_, _>>()?
2436        };
2437        Ok(Self {
2438            id,
2439            sdist,
2440            wheels,
2441            fork_markers,
2442            dependencies: vec![],
2443            optional_dependencies: BTreeMap::default(),
2444            dependency_groups: BTreeMap::default(),
2445            metadata: PackageMetadata {
2446                requires_dist,
2447                provides_extra,
2448                dependency_groups,
2449            },
2450        })
2451    }
2452
2453    /// Add the [`AnnotatedDist`] as a dependency of the [`Package`].
2454    fn add_dependency(
2455        &mut self,
2456        requires_python: &RequiresPython,
2457        annotated_dist: &AnnotatedDist,
2458        marker: UniversalMarker,
2459        root: &Path,
2460    ) -> Result<(), LockError> {
2461        let new_dep =
2462            Dependency::from_annotated_dist(requires_python, annotated_dist, marker, root)?;
2463        for existing_dep in &mut self.dependencies {
2464            if existing_dep.package_id == new_dep.package_id
2465                // It's important that we do a comparison on
2466                // *simplified* markers here. In particular, when
2467                // we write markers out to the lock file, we use
2468                // "simplified" markers, or markers that are simplified
2469                // *given* that `requires-python` is satisfied. So if
2470                // we don't do equality based on what the simplified
2471                // marker is, we might wind up not merging dependencies
2472                // that ought to be merged and thus writing out extra
2473                // entries.
2474                //
2475                // For example, if `requires-python = '>=3.8'` and we
2476                // have `foo==1` and
2477                // `foo==1 ; python_version >= '3.8'` dependencies,
2478                // then they don't have equivalent complexified
2479                // markers, but their simplified markers are identical.
2480                //
2481                // NOTE: It does seem like perhaps this should
2482                // be implemented semantically/algebraically on
2483                // `MarkerTree` itself, but it wasn't totally clear
2484                // how to do that. I think `pep508` would need to
2485                // grow a concept of "requires python" and provide an
2486                // operation specifically for that.
2487                && existing_dep.simplified_marker == new_dep.simplified_marker
2488            {
2489                existing_dep.extra.extend(new_dep.extra);
2490                return Ok(());
2491            }
2492        }
2493
2494        self.dependencies.push(new_dep);
2495        Ok(())
2496    }
2497
2498    /// Add the [`AnnotatedDist`] as an optional dependency of the [`Package`].
2499    fn add_optional_dependency(
2500        &mut self,
2501        requires_python: &RequiresPython,
2502        extra: ExtraName,
2503        annotated_dist: &AnnotatedDist,
2504        marker: UniversalMarker,
2505        root: &Path,
2506    ) -> Result<(), LockError> {
2507        let dep = Dependency::from_annotated_dist(requires_python, annotated_dist, marker, root)?;
2508        let optional_deps = self.optional_dependencies.entry(extra).or_default();
2509        for existing_dep in &mut *optional_deps {
2510            if existing_dep.package_id == dep.package_id
2511                // See note in add_dependency for why we use
2512                // simplified markers here.
2513                && existing_dep.simplified_marker == dep.simplified_marker
2514            {
2515                existing_dep.extra.extend(dep.extra);
2516                return Ok(());
2517            }
2518        }
2519
2520        optional_deps.push(dep);
2521        Ok(())
2522    }
2523
2524    /// Add the [`AnnotatedDist`] to a dependency group of the [`Package`].
2525    fn add_group_dependency(
2526        &mut self,
2527        requires_python: &RequiresPython,
2528        group: GroupName,
2529        annotated_dist: &AnnotatedDist,
2530        marker: UniversalMarker,
2531        root: &Path,
2532    ) -> Result<(), LockError> {
2533        let dep = Dependency::from_annotated_dist(requires_python, annotated_dist, marker, root)?;
2534        let deps = self.dependency_groups.entry(group).or_default();
2535        for existing_dep in &mut *deps {
2536            if existing_dep.package_id == dep.package_id
2537                // See note in add_dependency for why we use
2538                // simplified markers here.
2539                && existing_dep.simplified_marker == dep.simplified_marker
2540            {
2541                existing_dep.extra.extend(dep.extra);
2542                return Ok(());
2543            }
2544        }
2545
2546        deps.push(dep);
2547        Ok(())
2548    }
2549
2550    /// Convert the [`Package`] to a [`Dist`] that can be used in installation.
2551    fn to_dist(
2552        &self,
2553        workspace_root: &Path,
2554        tag_policy: TagPolicy<'_>,
2555        build_options: &BuildOptions,
2556        markers: &MarkerEnvironment,
2557    ) -> Result<Dist, LockError> {
2558        let no_binary = build_options.no_binary_package(&self.id.name);
2559        let no_build = build_options.no_build_package(&self.id.name);
2560
2561        if !no_binary {
2562            if let Some(best_wheel_index) = self.find_best_wheel(tag_policy) {
2563                return match &self.id.source {
2564                    Source::Registry(source) => {
2565                        let wheels = self
2566                            .wheels
2567                            .iter()
2568                            .map(|wheel| wheel.to_registry_wheel(source, workspace_root))
2569                            .collect::<Result<_, LockError>>()?;
2570                        let reg_built_dist = RegistryBuiltDist {
2571                            wheels,
2572                            best_wheel_index,
2573                            sdist: None,
2574                        };
2575                        Ok(Dist::Built(BuiltDist::Registry(reg_built_dist)))
2576                    }
2577                    Source::Path(path) => {
2578                        let filename: WheelFilename =
2579                            self.wheels[best_wheel_index].filename.clone();
2580                        let install_path = absolute_path(workspace_root, path)?;
2581                        let path_dist = PathBuiltDist {
2582                            filename,
2583                            url: verbatim_url(&install_path, &self.id)?,
2584                            install_path: absolute_path(workspace_root, path)?.into_boxed_path(),
2585                        };
2586                        let built_dist = BuiltDist::Path(path_dist);
2587                        Ok(Dist::Built(built_dist))
2588                    }
2589                    Source::Direct(url, direct) => {
2590                        let filename: WheelFilename =
2591                            self.wheels[best_wheel_index].filename.clone();
2592                        let url = DisplaySafeUrl::from(ParsedArchiveUrl {
2593                            url: url.to_url().map_err(LockErrorKind::InvalidUrl)?,
2594                            subdirectory: direct.subdirectory.clone(),
2595                            ext: DistExtension::Wheel,
2596                        });
2597                        let direct_dist = DirectUrlBuiltDist {
2598                            filename,
2599                            location: Box::new(url.clone()),
2600                            url: VerbatimUrl::from_url(url),
2601                        };
2602                        let built_dist = BuiltDist::DirectUrl(direct_dist);
2603                        Ok(Dist::Built(built_dist))
2604                    }
2605                    Source::Git(_, _) => Err(LockErrorKind::InvalidWheelSource {
2606                        id: self.id.clone(),
2607                        source_type: "Git",
2608                    }
2609                    .into()),
2610                    Source::Directory(_) => Err(LockErrorKind::InvalidWheelSource {
2611                        id: self.id.clone(),
2612                        source_type: "directory",
2613                    }
2614                    .into()),
2615                    Source::Editable(_) => Err(LockErrorKind::InvalidWheelSource {
2616                        id: self.id.clone(),
2617                        source_type: "editable",
2618                    }
2619                    .into()),
2620                    Source::Virtual(_) => Err(LockErrorKind::InvalidWheelSource {
2621                        id: self.id.clone(),
2622                        source_type: "virtual",
2623                    }
2624                    .into()),
2625                };
2626            }
2627        }
2628
2629        if let Some(sdist) = self.to_source_dist(workspace_root)? {
2630            // Even with `--no-build`, allow virtual packages. (In the future, we may want to allow
2631            // any local source tree, or at least editable source trees, which we allow in
2632            // `uv pip`.)
2633            if !no_build || sdist.is_virtual() {
2634                return Ok(Dist::Source(sdist));
2635            }
2636        }
2637
2638        match (no_binary, no_build) {
2639            (true, true) => Err(LockErrorKind::NoBinaryNoBuild {
2640                id: self.id.clone(),
2641            }
2642            .into()),
2643            (true, false) if self.id.source.is_wheel() => Err(LockErrorKind::NoBinaryWheelOnly {
2644                id: self.id.clone(),
2645            }
2646            .into()),
2647            (true, false) => Err(LockErrorKind::NoBinary {
2648                id: self.id.clone(),
2649            }
2650            .into()),
2651            (false, true) => Err(LockErrorKind::NoBuild {
2652                id: self.id.clone(),
2653            }
2654            .into()),
2655            (false, false) if self.id.source.is_wheel() => Err(LockError {
2656                kind: Box::new(LockErrorKind::IncompatibleWheelOnly {
2657                    id: self.id.clone(),
2658                }),
2659                hint: self.tag_hint(tag_policy, markers),
2660            }),
2661            (false, false) => Err(LockError {
2662                kind: Box::new(LockErrorKind::NeitherSourceDistNorWheel {
2663                    id: self.id.clone(),
2664                }),
2665                hint: self.tag_hint(tag_policy, markers),
2666            }),
2667        }
2668    }
2669
2670    /// Generate a [`WheelTagHint`] based on wheel-tag incompatibilities.
2671    fn tag_hint(
2672        &self,
2673        tag_policy: TagPolicy<'_>,
2674        markers: &MarkerEnvironment,
2675    ) -> Option<WheelTagHint> {
2676        let filenames = self
2677            .wheels
2678            .iter()
2679            .map(|wheel| &wheel.filename)
2680            .collect::<Vec<_>>();
2681        WheelTagHint::from_wheels(
2682            &self.id.name,
2683            self.id.version.as_ref(),
2684            &filenames,
2685            tag_policy.tags(),
2686            markers,
2687        )
2688    }
2689
2690    /// Convert the source of this [`Package`] to a [`SourceDist`] that can be used in installation.
2691    ///
2692    /// Returns `Ok(None)` if the source cannot be converted because `self.sdist` is `None`. This is required
2693    /// for registry sources.
2694    fn to_source_dist(
2695        &self,
2696        workspace_root: &Path,
2697    ) -> Result<Option<uv_distribution_types::SourceDist>, LockError> {
2698        let sdist = match &self.id.source {
2699            Source::Path(path) => {
2700                // A direct path source can also be a wheel, so validate the extension.
2701                let DistExtension::Source(ext) = DistExtension::from_path(path).map_err(|err| {
2702                    LockErrorKind::MissingExtension {
2703                        id: self.id.clone(),
2704                        err,
2705                    }
2706                })?
2707                else {
2708                    return Ok(None);
2709                };
2710                let install_path = absolute_path(workspace_root, path)?;
2711                let path_dist = PathSourceDist {
2712                    name: self.id.name.clone(),
2713                    version: self.id.version.clone(),
2714                    url: verbatim_url(&install_path, &self.id)?,
2715                    install_path: install_path.into_boxed_path(),
2716                    ext,
2717                };
2718                uv_distribution_types::SourceDist::Path(path_dist)
2719            }
2720            Source::Directory(path) => {
2721                let install_path = absolute_path(workspace_root, path)?;
2722                let dir_dist = DirectorySourceDist {
2723                    name: self.id.name.clone(),
2724                    url: verbatim_url(&install_path, &self.id)?,
2725                    install_path: install_path.into_boxed_path(),
2726                    editable: Some(false),
2727                    r#virtual: Some(false),
2728                };
2729                uv_distribution_types::SourceDist::Directory(dir_dist)
2730            }
2731            Source::Editable(path) => {
2732                let install_path = absolute_path(workspace_root, path)?;
2733                let dir_dist = DirectorySourceDist {
2734                    name: self.id.name.clone(),
2735                    url: verbatim_url(&install_path, &self.id)?,
2736                    install_path: install_path.into_boxed_path(),
2737                    editable: Some(true),
2738                    r#virtual: Some(false),
2739                };
2740                uv_distribution_types::SourceDist::Directory(dir_dist)
2741            }
2742            Source::Virtual(path) => {
2743                let install_path = absolute_path(workspace_root, path)?;
2744                let dir_dist = DirectorySourceDist {
2745                    name: self.id.name.clone(),
2746                    url: verbatim_url(&install_path, &self.id)?,
2747                    install_path: install_path.into_boxed_path(),
2748                    editable: Some(false),
2749                    r#virtual: Some(true),
2750                };
2751                uv_distribution_types::SourceDist::Directory(dir_dist)
2752            }
2753            Source::Git(url, git) => {
2754                // Remove the fragment and query from the URL; they're already present in the
2755                // `GitSource`.
2756                let mut url = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
2757                url.set_fragment(None);
2758                url.set_query(None);
2759
2760                // Reconstruct the `GitUrl` from the `GitSource`.
2761                let git_url =
2762                    GitUrl::from_commit(url, GitReference::from(git.kind.clone()), git.precise)?;
2763
2764                // Reconstruct the PEP 508-compatible URL from the `GitSource`.
2765                let url = DisplaySafeUrl::from(ParsedGitUrl {
2766                    url: git_url.clone(),
2767                    subdirectory: git.subdirectory.clone(),
2768                });
2769
2770                let git_dist = GitSourceDist {
2771                    name: self.id.name.clone(),
2772                    url: VerbatimUrl::from_url(url),
2773                    git: Box::new(git_url),
2774                    subdirectory: git.subdirectory.clone(),
2775                };
2776                uv_distribution_types::SourceDist::Git(git_dist)
2777            }
2778            Source::Direct(url, direct) => {
2779                // A direct URL source can also be a wheel, so validate the extension.
2780                let DistExtension::Source(ext) =
2781                    DistExtension::from_path(url.base_str()).map_err(|err| {
2782                        LockErrorKind::MissingExtension {
2783                            id: self.id.clone(),
2784                            err,
2785                        }
2786                    })?
2787                else {
2788                    return Ok(None);
2789                };
2790                let location = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
2791                let url = DisplaySafeUrl::from(ParsedArchiveUrl {
2792                    url: location.clone(),
2793                    subdirectory: direct.subdirectory.clone(),
2794                    ext: DistExtension::Source(ext),
2795                });
2796                let direct_dist = DirectUrlSourceDist {
2797                    name: self.id.name.clone(),
2798                    location: Box::new(location),
2799                    subdirectory: direct.subdirectory.clone(),
2800                    ext,
2801                    url: VerbatimUrl::from_url(url),
2802                };
2803                uv_distribution_types::SourceDist::DirectUrl(direct_dist)
2804            }
2805            Source::Registry(RegistrySource::Url(url)) => {
2806                let Some(ref sdist) = self.sdist else {
2807                    return Ok(None);
2808                };
2809
2810                let name = &self.id.name;
2811                let version = self
2812                    .id
2813                    .version
2814                    .as_ref()
2815                    .expect("version for registry source");
2816
2817                let file_url = sdist.url().ok_or_else(|| LockErrorKind::MissingUrl {
2818                    name: name.clone(),
2819                    version: version.clone(),
2820                })?;
2821                let filename = sdist
2822                    .filename()
2823                    .ok_or_else(|| LockErrorKind::MissingFilename {
2824                        id: self.id.clone(),
2825                    })?;
2826                let ext = SourceDistExtension::from_path(filename.as_ref()).map_err(|err| {
2827                    LockErrorKind::MissingExtension {
2828                        id: self.id.clone(),
2829                        err,
2830                    }
2831                })?;
2832                let file = Box::new(uv_distribution_types::File {
2833                    dist_info_metadata: false,
2834                    filename: SmallString::from(filename),
2835                    hashes: sdist.hash().map_or(HashDigests::empty(), |hash| {
2836                        HashDigests::from(hash.0.clone())
2837                    }),
2838                    requires_python: None,
2839                    size: sdist.size(),
2840                    upload_time_utc_ms: sdist.upload_time().map(Timestamp::as_millisecond),
2841                    url: FileLocation::AbsoluteUrl(file_url.clone()),
2842                    yanked: None,
2843                    zstd: None,
2844                });
2845
2846                let index = IndexUrl::from(VerbatimUrl::from_url(
2847                    url.to_url().map_err(LockErrorKind::InvalidUrl)?,
2848                ));
2849
2850                let reg_dist = RegistrySourceDist {
2851                    name: name.clone(),
2852                    version: version.clone(),
2853                    file,
2854                    ext,
2855                    index,
2856                    wheels: vec![],
2857                };
2858                uv_distribution_types::SourceDist::Registry(reg_dist)
2859            }
2860            Source::Registry(RegistrySource::Path(path)) => {
2861                let Some(ref sdist) = self.sdist else {
2862                    return Ok(None);
2863                };
2864
2865                let name = &self.id.name;
2866                let version = self
2867                    .id
2868                    .version
2869                    .as_ref()
2870                    .expect("version for registry source");
2871
2872                let file_url = match sdist {
2873                    SourceDist::Url { url: file_url, .. } => {
2874                        FileLocation::AbsoluteUrl(file_url.clone())
2875                    }
2876                    SourceDist::Path {
2877                        path: file_path, ..
2878                    } => {
2879                        let file_path = workspace_root.join(path).join(file_path);
2880                        let file_url =
2881                            DisplaySafeUrl::from_file_path(&file_path).map_err(|()| {
2882                                LockErrorKind::PathToUrl {
2883                                    path: file_path.into_boxed_path(),
2884                                }
2885                            })?;
2886                        FileLocation::AbsoluteUrl(UrlString::from(file_url))
2887                    }
2888                    SourceDist::Metadata { .. } => {
2889                        return Err(LockErrorKind::MissingPath {
2890                            name: name.clone(),
2891                            version: version.clone(),
2892                        }
2893                        .into());
2894                    }
2895                };
2896                let filename = sdist
2897                    .filename()
2898                    .ok_or_else(|| LockErrorKind::MissingFilename {
2899                        id: self.id.clone(),
2900                    })?;
2901                let ext = SourceDistExtension::from_path(filename.as_ref()).map_err(|err| {
2902                    LockErrorKind::MissingExtension {
2903                        id: self.id.clone(),
2904                        err,
2905                    }
2906                })?;
2907                let file = Box::new(uv_distribution_types::File {
2908                    dist_info_metadata: false,
2909                    filename: SmallString::from(filename),
2910                    hashes: sdist.hash().map_or(HashDigests::empty(), |hash| {
2911                        HashDigests::from(hash.0.clone())
2912                    }),
2913                    requires_python: None,
2914                    size: sdist.size(),
2915                    upload_time_utc_ms: sdist.upload_time().map(Timestamp::as_millisecond),
2916                    url: file_url,
2917                    yanked: None,
2918                    zstd: None,
2919                });
2920
2921                let index = IndexUrl::from(
2922                    VerbatimUrl::from_absolute_path(workspace_root.join(path))
2923                        .map_err(LockErrorKind::RegistryVerbatimUrl)?,
2924                );
2925
2926                let reg_dist = RegistrySourceDist {
2927                    name: name.clone(),
2928                    version: version.clone(),
2929                    file,
2930                    ext,
2931                    index,
2932                    wheels: vec![],
2933                };
2934                uv_distribution_types::SourceDist::Registry(reg_dist)
2935            }
2936        };
2937
2938        Ok(Some(sdist))
2939    }
2940
2941    fn to_toml(
2942        &self,
2943        requires_python: &RequiresPython,
2944        dist_count_by_name: &FxHashMap<PackageName, u64>,
2945    ) -> Result<Table, toml_edit::ser::Error> {
2946        let mut table = Table::new();
2947
2948        self.id.to_toml(None, &mut table);
2949
2950        if !self.fork_markers.is_empty() {
2951            let fork_markers = each_element_on_its_line_array(
2952                simplified_universal_markers(&self.fork_markers, requires_python).into_iter(),
2953            );
2954            if !fork_markers.is_empty() {
2955                table.insert("resolution-markers", value(fork_markers));
2956            }
2957        }
2958
2959        if !self.dependencies.is_empty() {
2960            let deps = each_element_on_its_line_array(self.dependencies.iter().map(|dep| {
2961                dep.to_toml(requires_python, dist_count_by_name)
2962                    .into_inline_table()
2963            }));
2964            table.insert("dependencies", value(deps));
2965        }
2966
2967        if !self.optional_dependencies.is_empty() {
2968            let mut optional_deps = Table::new();
2969            for (extra, deps) in &self.optional_dependencies {
2970                let deps = each_element_on_its_line_array(deps.iter().map(|dep| {
2971                    dep.to_toml(requires_python, dist_count_by_name)
2972                        .into_inline_table()
2973                }));
2974                if !deps.is_empty() {
2975                    optional_deps.insert(extra.as_ref(), value(deps));
2976                }
2977            }
2978            if !optional_deps.is_empty() {
2979                table.insert("optional-dependencies", Item::Table(optional_deps));
2980            }
2981        }
2982
2983        if !self.dependency_groups.is_empty() {
2984            let mut dependency_groups = Table::new();
2985            for (extra, deps) in &self.dependency_groups {
2986                let deps = each_element_on_its_line_array(deps.iter().map(|dep| {
2987                    dep.to_toml(requires_python, dist_count_by_name)
2988                        .into_inline_table()
2989                }));
2990                if !deps.is_empty() {
2991                    dependency_groups.insert(extra.as_ref(), value(deps));
2992                }
2993            }
2994            if !dependency_groups.is_empty() {
2995                table.insert("dev-dependencies", Item::Table(dependency_groups));
2996            }
2997        }
2998
2999        if let Some(ref sdist) = self.sdist {
3000            table.insert("sdist", value(sdist.to_toml()?));
3001        }
3002
3003        if !self.wheels.is_empty() {
3004            let wheels = each_element_on_its_line_array(
3005                self.wheels
3006                    .iter()
3007                    .map(Wheel::to_toml)
3008                    .collect::<Result<Vec<_>, _>>()?
3009                    .into_iter(),
3010            );
3011            table.insert("wheels", value(wheels));
3012        }
3013
3014        // Write the package metadata, if non-empty.
3015        {
3016            let mut metadata_table = Table::new();
3017
3018            if !self.metadata.requires_dist.is_empty() {
3019                let requires_dist = self
3020                    .metadata
3021                    .requires_dist
3022                    .iter()
3023                    .map(|requirement| {
3024                        serde::Serialize::serialize(
3025                            &requirement,
3026                            toml_edit::ser::ValueSerializer::new(),
3027                        )
3028                    })
3029                    .collect::<Result<Vec<_>, _>>()?;
3030                let requires_dist = match requires_dist.as_slice() {
3031                    [] => Array::new(),
3032                    [requirement] => Array::from_iter([requirement]),
3033                    requires_dist => each_element_on_its_line_array(requires_dist.iter()),
3034                };
3035                metadata_table.insert("requires-dist", value(requires_dist));
3036            }
3037
3038            if !self.metadata.dependency_groups.is_empty() {
3039                let mut dependency_groups = Table::new();
3040                for (extra, deps) in &self.metadata.dependency_groups {
3041                    let deps = deps
3042                        .iter()
3043                        .map(|requirement| {
3044                            serde::Serialize::serialize(
3045                                &requirement,
3046                                toml_edit::ser::ValueSerializer::new(),
3047                            )
3048                        })
3049                        .collect::<Result<Vec<_>, _>>()?;
3050                    let deps = match deps.as_slice() {
3051                        [] => Array::new(),
3052                        [requirement] => Array::from_iter([requirement]),
3053                        deps => each_element_on_its_line_array(deps.iter()),
3054                    };
3055                    dependency_groups.insert(extra.as_ref(), value(deps));
3056                }
3057                if !dependency_groups.is_empty() {
3058                    metadata_table.insert("requires-dev", Item::Table(dependency_groups));
3059                }
3060            }
3061
3062            if !self.metadata.provides_extra.is_empty() {
3063                let provides_extras = self
3064                    .metadata
3065                    .provides_extra
3066                    .iter()
3067                    .map(|extra| {
3068                        serde::Serialize::serialize(&extra, toml_edit::ser::ValueSerializer::new())
3069                    })
3070                    .collect::<Result<Vec<_>, _>>()?;
3071                // This is just a list of names, so linebreaking it is excessive.
3072                let provides_extras = Array::from_iter(provides_extras);
3073                metadata_table.insert("provides-extras", value(provides_extras));
3074            }
3075
3076            if !metadata_table.is_empty() {
3077                table.insert("metadata", Item::Table(metadata_table));
3078            }
3079        }
3080
3081        Ok(table)
3082    }
3083
3084    fn find_best_wheel(&self, tag_policy: TagPolicy<'_>) -> Option<usize> {
3085        type WheelPriority<'lock> = (TagPriority, Option<&'lock BuildTag>);
3086
3087        let mut best: Option<(WheelPriority, usize)> = None;
3088        for (i, wheel) in self.wheels.iter().enumerate() {
3089            let TagCompatibility::Compatible(tag_priority) =
3090                wheel.filename.compatibility(tag_policy.tags())
3091            else {
3092                continue;
3093            };
3094            let build_tag = wheel.filename.build_tag();
3095            let wheel_priority = (tag_priority, build_tag);
3096            match best {
3097                None => {
3098                    best = Some((wheel_priority, i));
3099                }
3100                Some((best_priority, _)) => {
3101                    if wheel_priority > best_priority {
3102                        best = Some((wheel_priority, i));
3103                    }
3104                }
3105            }
3106        }
3107
3108        let best = best.map(|(_, i)| i);
3109        match tag_policy {
3110            TagPolicy::Required(_) => best,
3111            TagPolicy::Preferred(_) => best.or_else(|| self.wheels.first().map(|_| 0)),
3112        }
3113    }
3114
3115    /// Returns the [`PackageName`] of the package.
3116    pub fn name(&self) -> &PackageName {
3117        &self.id.name
3118    }
3119
3120    /// Returns the [`Version`] of the package.
3121    pub fn version(&self) -> Option<&Version> {
3122        self.id.version.as_ref()
3123    }
3124
3125    /// Returns the Git SHA of the package, if it is a Git source.
3126    pub fn git_sha(&self) -> Option<&GitOid> {
3127        match &self.id.source {
3128            Source::Git(_, git) => Some(&git.precise),
3129            _ => None,
3130        }
3131    }
3132
3133    /// Return the fork markers for this package, if any.
3134    pub fn fork_markers(&self) -> &[UniversalMarker] {
3135        self.fork_markers.as_slice()
3136    }
3137
3138    /// Returns the [`IndexUrl`] for the package, if it is a registry source.
3139    pub fn index(&self, root: &Path) -> Result<Option<IndexUrl>, LockError> {
3140        match &self.id.source {
3141            Source::Registry(RegistrySource::Url(url)) => {
3142                let index = IndexUrl::from(VerbatimUrl::from_url(
3143                    url.to_url().map_err(LockErrorKind::InvalidUrl)?,
3144                ));
3145                Ok(Some(index))
3146            }
3147            Source::Registry(RegistrySource::Path(path)) => {
3148                let index = IndexUrl::from(
3149                    VerbatimUrl::from_absolute_path(root.join(path))
3150                        .map_err(LockErrorKind::RegistryVerbatimUrl)?,
3151                );
3152                Ok(Some(index))
3153            }
3154            _ => Ok(None),
3155        }
3156    }
3157
3158    /// Returns all the hashes associated with this [`Package`].
3159    fn hashes(&self) -> HashDigests {
3160        let mut hashes = Vec::with_capacity(
3161            usize::from(self.sdist.as_ref().and_then(|sdist| sdist.hash()).is_some())
3162                + self
3163                    .wheels
3164                    .iter()
3165                    .map(|wheel| usize::from(wheel.hash.is_some()))
3166                    .sum::<usize>(),
3167        );
3168        if let Some(ref sdist) = self.sdist {
3169            if let Some(hash) = sdist.hash() {
3170                hashes.push(hash.0.clone());
3171            }
3172        }
3173        for wheel in &self.wheels {
3174            hashes.extend(wheel.hash.as_ref().map(|h| h.0.clone()));
3175            if let Some(zstd) = wheel.zstd.as_ref() {
3176                hashes.extend(zstd.hash.as_ref().map(|h| h.0.clone()));
3177            }
3178        }
3179        HashDigests::from(hashes)
3180    }
3181
3182    /// Returns the [`ResolvedRepositoryReference`] for the package, if it is a Git source.
3183    pub fn as_git_ref(&self) -> Result<Option<ResolvedRepositoryReference>, LockError> {
3184        match &self.id.source {
3185            Source::Git(url, git) => Ok(Some(ResolvedRepositoryReference {
3186                reference: RepositoryReference {
3187                    url: RepositoryUrl::new(&url.to_url().map_err(LockErrorKind::InvalidUrl)?),
3188                    reference: GitReference::from(git.kind.clone()),
3189                },
3190                sha: git.precise,
3191            })),
3192            _ => Ok(None),
3193        }
3194    }
3195
3196    /// Returns `true` if the package is a dynamic source tree.
3197    fn is_dynamic(&self) -> bool {
3198        self.id.version.is_none()
3199    }
3200
3201    /// Returns the extras the package provides, if any.
3202    pub fn provides_extras(&self) -> &[ExtraName] {
3203        &self.metadata.provides_extra
3204    }
3205
3206    /// Returns the dependency groups the package provides, if any.
3207    pub fn dependency_groups(&self) -> &BTreeMap<GroupName, BTreeSet<Requirement>> {
3208        &self.metadata.dependency_groups
3209    }
3210
3211    /// Returns the dependencies of the package.
3212    pub fn dependencies(&self) -> &[Dependency] {
3213        &self.dependencies
3214    }
3215
3216    /// Returns the optional dependencies of the package.
3217    pub fn optional_dependencies(&self) -> &BTreeMap<ExtraName, Vec<Dependency>> {
3218        &self.optional_dependencies
3219    }
3220
3221    /// Returns the resolved PEP 735 dependency groups of the package.
3222    pub fn resolved_dependency_groups(&self) -> &BTreeMap<GroupName, Vec<Dependency>> {
3223        &self.dependency_groups
3224    }
3225
3226    /// Returns an [`InstallTarget`] view for filtering decisions.
3227    pub fn as_install_target(&self) -> InstallTarget<'_> {
3228        InstallTarget {
3229            name: self.name(),
3230            is_local: self.id.source.is_local(),
3231        }
3232    }
3233}
3234
3235/// Attempts to construct a `VerbatimUrl` from the given normalized `Path`.
3236fn verbatim_url(path: &Path, id: &PackageId) -> Result<VerbatimUrl, LockError> {
3237    let url =
3238        VerbatimUrl::from_normalized_path(path).map_err(|err| LockErrorKind::VerbatimUrl {
3239            id: id.clone(),
3240            err,
3241        })?;
3242    Ok(url)
3243}
3244
3245/// Attempts to construct an absolute path from the given `Path`.
3246fn absolute_path(workspace_root: &Path, path: &Path) -> Result<PathBuf, LockError> {
3247    let path = uv_fs::normalize_absolute_path(&workspace_root.join(path))
3248        .map_err(LockErrorKind::AbsolutePath)?;
3249    Ok(path)
3250}
3251
3252#[derive(Clone, Debug, serde::Deserialize)]
3253#[serde(rename_all = "kebab-case")]
3254struct PackageWire {
3255    #[serde(flatten)]
3256    id: PackageId,
3257    #[serde(default)]
3258    metadata: PackageMetadata,
3259    #[serde(default)]
3260    sdist: Option<SourceDist>,
3261    #[serde(default)]
3262    wheels: Vec<Wheel>,
3263    #[serde(default, rename = "resolution-markers")]
3264    fork_markers: Vec<SimplifiedMarkerTree>,
3265    #[serde(default)]
3266    dependencies: Vec<DependencyWire>,
3267    #[serde(default)]
3268    optional_dependencies: BTreeMap<ExtraName, Vec<DependencyWire>>,
3269    #[serde(default, rename = "dev-dependencies", alias = "dependency-groups")]
3270    dependency_groups: BTreeMap<GroupName, Vec<DependencyWire>>,
3271}
3272
3273#[derive(Clone, Default, Debug, Eq, PartialEq, serde::Deserialize)]
3274#[serde(rename_all = "kebab-case")]
3275struct PackageMetadata {
3276    #[serde(default)]
3277    requires_dist: BTreeSet<Requirement>,
3278    #[serde(default, rename = "provides-extras")]
3279    provides_extra: Box<[ExtraName]>,
3280    #[serde(default, rename = "requires-dev", alias = "dependency-groups")]
3281    dependency_groups: BTreeMap<GroupName, BTreeSet<Requirement>>,
3282}
3283
3284impl PackageWire {
3285    fn unwire(
3286        self,
3287        requires_python: &RequiresPython,
3288        unambiguous_package_ids: &FxHashMap<PackageName, PackageId>,
3289    ) -> Result<Package, LockError> {
3290        // Consistency check
3291        if !uv_flags::contains(uv_flags::EnvironmentFlags::SKIP_WHEEL_FILENAME_CHECK) {
3292            if let Some(version) = &self.id.version {
3293                for wheel in &self.wheels {
3294                    if *version != wheel.filename.version
3295                        && *version != wheel.filename.version.clone().without_local()
3296                    {
3297                        return Err(LockError::from(LockErrorKind::InconsistentVersions {
3298                            name: self.id.name,
3299                            version: version.clone(),
3300                            wheel: wheel.clone(),
3301                        }));
3302                    }
3303                }
3304                // We can't check the source dist version since it does not need to contain the version
3305                // in the filename.
3306            }
3307        }
3308
3309        let unwire_deps = |deps: Vec<DependencyWire>| -> Result<Vec<Dependency>, LockError> {
3310            deps.into_iter()
3311                .map(|dep| dep.unwire(requires_python, unambiguous_package_ids))
3312                .collect()
3313        };
3314
3315        Ok(Package {
3316            id: self.id,
3317            metadata: self.metadata,
3318            sdist: self.sdist,
3319            wheels: self.wheels,
3320            fork_markers: self
3321                .fork_markers
3322                .into_iter()
3323                .map(|simplified_marker| simplified_marker.into_marker(requires_python))
3324                .map(UniversalMarker::from_combined)
3325                .collect(),
3326            dependencies: unwire_deps(self.dependencies)?,
3327            optional_dependencies: self
3328                .optional_dependencies
3329                .into_iter()
3330                .map(|(extra, deps)| Ok((extra, unwire_deps(deps)?)))
3331                .collect::<Result<_, LockError>>()?,
3332            dependency_groups: self
3333                .dependency_groups
3334                .into_iter()
3335                .map(|(group, deps)| Ok((group, unwire_deps(deps)?)))
3336                .collect::<Result<_, LockError>>()?,
3337        })
3338    }
3339}
3340
3341/// Inside the lockfile, we match a dependency entry to a package entry through a key made up
3342/// of the name, the version and the source url.
3343#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
3344#[serde(rename_all = "kebab-case")]
3345pub(crate) struct PackageId {
3346    pub(crate) name: PackageName,
3347    pub(crate) version: Option<Version>,
3348    source: Source,
3349}
3350
3351impl PackageId {
3352    fn from_annotated_dist(annotated_dist: &AnnotatedDist, root: &Path) -> Result<Self, LockError> {
3353        // Identify the source of the package.
3354        let source = Source::from_resolved_dist(&annotated_dist.dist, root)?;
3355        // Omit versions for dynamic source trees.
3356        let version = if source.is_source_tree()
3357            && annotated_dist
3358                .metadata
3359                .as_ref()
3360                .is_some_and(|metadata| metadata.dynamic)
3361        {
3362            None
3363        } else {
3364            Some(annotated_dist.version.clone())
3365        };
3366        let name = annotated_dist.name.clone();
3367        Ok(Self {
3368            name,
3369            version,
3370            source,
3371        })
3372    }
3373
3374    /// Writes this package ID inline into the table given.
3375    ///
3376    /// When a map is given, and if the package name in this ID is unambiguous
3377    /// (i.e., it has a count of 1 in the map), then the `version` and `source`
3378    /// fields are omitted. In all other cases, including when a map is not
3379    /// given, the `version` and `source` fields are written.
3380    fn to_toml(&self, dist_count_by_name: Option<&FxHashMap<PackageName, u64>>, table: &mut Table) {
3381        let count = dist_count_by_name.and_then(|map| map.get(&self.name).copied());
3382        table.insert("name", value(self.name.to_string()));
3383        if count.map(|count| count > 1).unwrap_or(true) {
3384            if let Some(version) = &self.version {
3385                table.insert("version", value(version.to_string()));
3386            }
3387            self.source.to_toml(table);
3388        }
3389    }
3390}
3391
3392impl Display for PackageId {
3393    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
3394        if let Some(version) = &self.version {
3395            write!(f, "{}=={} @ {}", self.name, version, self.source)
3396        } else {
3397            write!(f, "{} @ {}", self.name, self.source)
3398        }
3399    }
3400}
3401
3402#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
3403#[serde(rename_all = "kebab-case")]
3404struct PackageIdForDependency {
3405    name: PackageName,
3406    version: Option<Version>,
3407    source: Option<Source>,
3408}
3409
3410impl PackageIdForDependency {
3411    fn unwire(
3412        self,
3413        unambiguous_package_ids: &FxHashMap<PackageName, PackageId>,
3414    ) -> Result<PackageId, LockError> {
3415        let unambiguous_package_id = unambiguous_package_ids.get(&self.name);
3416        let source = self.source.map(Ok::<_, LockError>).unwrap_or_else(|| {
3417            let Some(package_id) = unambiguous_package_id else {
3418                return Err(LockErrorKind::MissingDependencySource {
3419                    name: self.name.clone(),
3420                }
3421                .into());
3422            };
3423            Ok(package_id.source.clone())
3424        })?;
3425        let version = if let Some(version) = self.version {
3426            Some(version)
3427        } else {
3428            if let Some(package_id) = unambiguous_package_id {
3429                package_id.version.clone()
3430            } else {
3431                // If the package is a source tree, assume that the missing `self.version` field is
3432                // indicative of a dynamic version.
3433                if source.is_source_tree() {
3434                    None
3435                } else {
3436                    return Err(LockErrorKind::MissingDependencyVersion {
3437                        name: self.name.clone(),
3438                    }
3439                    .into());
3440                }
3441            }
3442        };
3443        Ok(PackageId {
3444            name: self.name,
3445            version,
3446            source,
3447        })
3448    }
3449}
3450
3451impl From<PackageId> for PackageIdForDependency {
3452    fn from(id: PackageId) -> Self {
3453        Self {
3454            name: id.name,
3455            version: id.version,
3456            source: Some(id.source),
3457        }
3458    }
3459}
3460
3461/// A unique identifier to differentiate between different sources for the same version of a
3462/// package.
3463///
3464/// NOTE: Care should be taken when adding variants to this enum. Namely, new
3465/// variants should be added without changing the relative ordering of other
3466/// variants. Otherwise, this could cause the lockfile to have a different
3467/// canonical ordering of sources.
3468#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
3469#[serde(try_from = "SourceWire")]
3470enum Source {
3471    /// A registry or `--find-links` index.
3472    Registry(RegistrySource),
3473    /// A Git repository.
3474    Git(UrlString, GitSource),
3475    /// A direct HTTP(S) URL.
3476    Direct(UrlString, DirectSource),
3477    /// A path to a local source or built archive.
3478    Path(Box<Path>),
3479    /// A path to a local directory.
3480    Directory(Box<Path>),
3481    /// A path to a local directory that should be installed as editable.
3482    Editable(Box<Path>),
3483    /// A path to a local directory that should not be built or installed.
3484    Virtual(Box<Path>),
3485}
3486
3487impl Source {
3488    fn from_resolved_dist(resolved_dist: &ResolvedDist, root: &Path) -> Result<Self, LockError> {
3489        match *resolved_dist {
3490            // We pass empty installed packages for locking.
3491            ResolvedDist::Installed { .. } => unreachable!(),
3492            ResolvedDist::Installable { ref dist, .. } => Self::from_dist(dist, root),
3493        }
3494    }
3495
3496    fn from_dist(dist: &Dist, root: &Path) -> Result<Self, LockError> {
3497        match *dist {
3498            Dist::Built(ref built_dist) => Self::from_built_dist(built_dist, root),
3499            Dist::Source(ref source_dist) => Self::from_source_dist(source_dist, root),
3500        }
3501    }
3502
3503    fn from_built_dist(built_dist: &BuiltDist, root: &Path) -> Result<Self, LockError> {
3504        match *built_dist {
3505            BuiltDist::Registry(ref reg_dist) => Self::from_registry_built_dist(reg_dist, root),
3506            BuiltDist::DirectUrl(ref direct_dist) => Ok(Self::from_direct_built_dist(direct_dist)),
3507            BuiltDist::Path(ref path_dist) => Self::from_path_built_dist(path_dist, root),
3508        }
3509    }
3510
3511    fn from_source_dist(
3512        source_dist: &uv_distribution_types::SourceDist,
3513        root: &Path,
3514    ) -> Result<Self, LockError> {
3515        match *source_dist {
3516            uv_distribution_types::SourceDist::Registry(ref reg_dist) => {
3517                Self::from_registry_source_dist(reg_dist, root)
3518            }
3519            uv_distribution_types::SourceDist::DirectUrl(ref direct_dist) => {
3520                Ok(Self::from_direct_source_dist(direct_dist))
3521            }
3522            uv_distribution_types::SourceDist::Git(ref git_dist) => {
3523                Ok(Self::from_git_dist(git_dist))
3524            }
3525            uv_distribution_types::SourceDist::Path(ref path_dist) => {
3526                Self::from_path_source_dist(path_dist, root)
3527            }
3528            uv_distribution_types::SourceDist::Directory(ref directory) => {
3529                Self::from_directory_source_dist(directory, root)
3530            }
3531        }
3532    }
3533
3534    fn from_registry_built_dist(
3535        reg_dist: &RegistryBuiltDist,
3536        root: &Path,
3537    ) -> Result<Self, LockError> {
3538        Self::from_index_url(&reg_dist.best_wheel().index, root)
3539    }
3540
3541    fn from_registry_source_dist(
3542        reg_dist: &RegistrySourceDist,
3543        root: &Path,
3544    ) -> Result<Self, LockError> {
3545        Self::from_index_url(&reg_dist.index, root)
3546    }
3547
3548    fn from_direct_built_dist(direct_dist: &DirectUrlBuiltDist) -> Self {
3549        Self::Direct(
3550            normalize_url(direct_dist.url.to_url()),
3551            DirectSource { subdirectory: None },
3552        )
3553    }
3554
3555    fn from_direct_source_dist(direct_dist: &DirectUrlSourceDist) -> Self {
3556        Self::Direct(
3557            normalize_url(direct_dist.url.to_url()),
3558            DirectSource {
3559                subdirectory: direct_dist.subdirectory.clone(),
3560            },
3561        )
3562    }
3563
3564    fn from_path_built_dist(path_dist: &PathBuiltDist, root: &Path) -> Result<Self, LockError> {
3565        let path = relative_to(&path_dist.install_path, root)
3566            .or_else(|_| std::path::absolute(&path_dist.install_path))
3567            .map_err(LockErrorKind::DistributionRelativePath)?;
3568        Ok(Self::Path(path.into_boxed_path()))
3569    }
3570
3571    fn from_path_source_dist(path_dist: &PathSourceDist, root: &Path) -> Result<Self, LockError> {
3572        let path = relative_to(&path_dist.install_path, root)
3573            .or_else(|_| std::path::absolute(&path_dist.install_path))
3574            .map_err(LockErrorKind::DistributionRelativePath)?;
3575        Ok(Self::Path(path.into_boxed_path()))
3576    }
3577
3578    fn from_directory_source_dist(
3579        directory_dist: &DirectorySourceDist,
3580        root: &Path,
3581    ) -> Result<Self, LockError> {
3582        let path = relative_to(&directory_dist.install_path, root)
3583            .or_else(|_| std::path::absolute(&directory_dist.install_path))
3584            .map_err(LockErrorKind::DistributionRelativePath)?;
3585        if directory_dist.editable.unwrap_or(false) {
3586            Ok(Self::Editable(path.into_boxed_path()))
3587        } else if directory_dist.r#virtual.unwrap_or(false) {
3588            Ok(Self::Virtual(path.into_boxed_path()))
3589        } else {
3590            Ok(Self::Directory(path.into_boxed_path()))
3591        }
3592    }
3593
3594    fn from_index_url(index_url: &IndexUrl, root: &Path) -> Result<Self, LockError> {
3595        match index_url {
3596            IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
3597                // Remove any sensitive credentials from the index URL.
3598                let redacted = index_url.without_credentials();
3599                let source = RegistrySource::Url(UrlString::from(redacted.as_ref()));
3600                Ok(Self::Registry(source))
3601            }
3602            IndexUrl::Path(url) => {
3603                let path = url
3604                    .to_file_path()
3605                    .map_err(|()| LockErrorKind::UrlToPath { url: url.to_url() })?;
3606                let path = relative_to(&path, root)
3607                    .or_else(|_| std::path::absolute(&path))
3608                    .map_err(LockErrorKind::IndexRelativePath)?;
3609                let source = RegistrySource::Path(path.into_boxed_path());
3610                Ok(Self::Registry(source))
3611            }
3612        }
3613    }
3614
3615    fn from_git_dist(git_dist: &GitSourceDist) -> Self {
3616        Self::Git(
3617            UrlString::from(locked_git_url(git_dist)),
3618            GitSource {
3619                kind: GitSourceKind::from(git_dist.git.reference().clone()),
3620                precise: git_dist.git.precise().unwrap_or_else(|| {
3621                    panic!("Git distribution is missing a precise hash: {git_dist}")
3622                }),
3623                subdirectory: git_dist.subdirectory.clone(),
3624            },
3625        )
3626    }
3627
3628    /// Returns `true` if the source should be considered immutable.
3629    ///
3630    /// We assume that registry sources are immutable. In other words, we expect that once a
3631    /// package-version is published to a registry, its metadata will not change.
3632    ///
3633    /// We also assume that Git sources are immutable, since a Git source encodes a specific commit.
3634    fn is_immutable(&self) -> bool {
3635        matches!(self, Self::Registry(..) | Self::Git(_, _))
3636    }
3637
3638    /// Returns `true` if the source is that of a wheel.
3639    fn is_wheel(&self) -> bool {
3640        match self {
3641            Self::Path(path) => {
3642                matches!(
3643                    DistExtension::from_path(path).ok(),
3644                    Some(DistExtension::Wheel)
3645                )
3646            }
3647            Self::Direct(url, _) => {
3648                matches!(
3649                    DistExtension::from_path(url.as_ref()).ok(),
3650                    Some(DistExtension::Wheel)
3651                )
3652            }
3653            Self::Directory(..) => false,
3654            Self::Editable(..) => false,
3655            Self::Virtual(..) => false,
3656            Self::Git(..) => false,
3657            Self::Registry(..) => false,
3658        }
3659    }
3660
3661    /// Returns `true` if the source is that of a source tree.
3662    fn is_source_tree(&self) -> bool {
3663        match self {
3664            Self::Directory(..) | Self::Editable(..) | Self::Virtual(..) => true,
3665            Self::Path(..) | Self::Git(..) | Self::Registry(..) | Self::Direct(..) => false,
3666        }
3667    }
3668
3669    /// Returns the path to the source tree, if the source is a source tree.
3670    fn as_source_tree(&self) -> Option<&Path> {
3671        match self {
3672            Self::Directory(path) | Self::Editable(path) | Self::Virtual(path) => Some(path),
3673            Self::Path(..) | Self::Git(..) | Self::Registry(..) | Self::Direct(..) => None,
3674        }
3675    }
3676
3677    fn to_toml(&self, table: &mut Table) {
3678        let mut source_table = InlineTable::new();
3679        match self {
3680            Self::Registry(source) => match source {
3681                RegistrySource::Url(url) => {
3682                    source_table.insert("registry", Value::from(url.as_ref()));
3683                }
3684                RegistrySource::Path(path) => {
3685                    source_table.insert(
3686                        "registry",
3687                        Value::from(PortablePath::from(path).to_string()),
3688                    );
3689                }
3690            },
3691            Self::Git(url, _) => {
3692                source_table.insert("git", Value::from(url.as_ref()));
3693            }
3694            Self::Direct(url, DirectSource { subdirectory }) => {
3695                source_table.insert("url", Value::from(url.as_ref()));
3696                if let Some(ref subdirectory) = *subdirectory {
3697                    source_table.insert(
3698                        "subdirectory",
3699                        Value::from(PortablePath::from(subdirectory).to_string()),
3700                    );
3701                }
3702            }
3703            Self::Path(path) => {
3704                source_table.insert("path", Value::from(PortablePath::from(path).to_string()));
3705            }
3706            Self::Directory(path) => {
3707                source_table.insert(
3708                    "directory",
3709                    Value::from(PortablePath::from(path).to_string()),
3710                );
3711            }
3712            Self::Editable(path) => {
3713                source_table.insert(
3714                    "editable",
3715                    Value::from(PortablePath::from(path).to_string()),
3716                );
3717            }
3718            Self::Virtual(path) => {
3719                source_table.insert("virtual", Value::from(PortablePath::from(path).to_string()));
3720            }
3721        }
3722        table.insert("source", value(source_table));
3723    }
3724
3725    /// Check if a package is local by examining its source.
3726    pub(crate) fn is_local(&self) -> bool {
3727        matches!(
3728            self,
3729            Self::Path(_) | Self::Directory(_) | Self::Editable(_) | Self::Virtual(_)
3730        )
3731    }
3732}
3733
3734impl Display for Source {
3735    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
3736        match self {
3737            Self::Registry(RegistrySource::Url(url)) | Self::Git(url, _) | Self::Direct(url, _) => {
3738                write!(f, "{}+{}", self.name(), url)
3739            }
3740            Self::Registry(RegistrySource::Path(path))
3741            | Self::Path(path)
3742            | Self::Directory(path)
3743            | Self::Editable(path)
3744            | Self::Virtual(path) => {
3745                write!(f, "{}+{}", self.name(), PortablePath::from(path))
3746            }
3747        }
3748    }
3749}
3750
3751impl Source {
3752    fn name(&self) -> &str {
3753        match self {
3754            Self::Registry(..) => "registry",
3755            Self::Git(..) => "git",
3756            Self::Direct(..) => "direct",
3757            Self::Path(..) => "path",
3758            Self::Directory(..) => "directory",
3759            Self::Editable(..) => "editable",
3760            Self::Virtual(..) => "virtual",
3761        }
3762    }
3763
3764    /// Returns `Some(true)` to indicate that the source kind _must_ include a
3765    /// hash.
3766    ///
3767    /// Returns `Some(false)` to indicate that the source kind _must not_
3768    /// include a hash.
3769    ///
3770    /// Returns `None` to indicate that the source kind _may_ include a hash.
3771    fn requires_hash(&self) -> Option<bool> {
3772        match self {
3773            Self::Registry(..) => None,
3774            Self::Direct(..) | Self::Path(..) => Some(true),
3775            Self::Git(..) | Self::Directory(..) | Self::Editable(..) | Self::Virtual(..) => {
3776                Some(false)
3777            }
3778        }
3779    }
3780}
3781
3782#[derive(Clone, Debug, serde::Deserialize)]
3783#[serde(untagged, rename_all = "kebab-case")]
3784enum SourceWire {
3785    Registry {
3786        registry: RegistrySourceWire,
3787    },
3788    Git {
3789        git: String,
3790    },
3791    Direct {
3792        url: UrlString,
3793        subdirectory: Option<PortablePathBuf>,
3794    },
3795    Path {
3796        path: PortablePathBuf,
3797    },
3798    Directory {
3799        directory: PortablePathBuf,
3800    },
3801    Editable {
3802        editable: PortablePathBuf,
3803    },
3804    Virtual {
3805        r#virtual: PortablePathBuf,
3806    },
3807}
3808
3809impl TryFrom<SourceWire> for Source {
3810    type Error = LockError;
3811
3812    fn try_from(wire: SourceWire) -> Result<Self, LockError> {
3813        #[allow(clippy::enum_glob_use)]
3814        use self::SourceWire::*;
3815
3816        match wire {
3817            Registry { registry } => Ok(Self::Registry(registry.into())),
3818            Git { git } => {
3819                let url = DisplaySafeUrl::parse(&git)
3820                    .map_err(|err| SourceParseError::InvalidUrl {
3821                        given: git.clone(),
3822                        err,
3823                    })
3824                    .map_err(LockErrorKind::InvalidGitSourceUrl)?;
3825
3826                let git_source = GitSource::from_url(&url)
3827                    .map_err(|err| match err {
3828                        GitSourceError::InvalidSha => SourceParseError::InvalidSha { given: git },
3829                        GitSourceError::MissingSha => SourceParseError::MissingSha { given: git },
3830                    })
3831                    .map_err(LockErrorKind::InvalidGitSourceUrl)?;
3832
3833                Ok(Self::Git(UrlString::from(url), git_source))
3834            }
3835            Direct { url, subdirectory } => Ok(Self::Direct(
3836                url,
3837                DirectSource {
3838                    subdirectory: subdirectory.map(Box::<std::path::Path>::from),
3839                },
3840            )),
3841            Path { path } => Ok(Self::Path(path.into())),
3842            Directory { directory } => Ok(Self::Directory(directory.into())),
3843            Editable { editable } => Ok(Self::Editable(editable.into())),
3844            Virtual { r#virtual } => Ok(Self::Virtual(r#virtual.into())),
3845        }
3846    }
3847}
3848
3849/// The source for a registry, which could be a URL or a relative path.
3850#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
3851enum RegistrySource {
3852    /// Ex) `https://pypi.org/simple`
3853    Url(UrlString),
3854    /// Ex) `../path/to/local/index`
3855    Path(Box<Path>),
3856}
3857
3858impl Display for RegistrySource {
3859    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
3860        match self {
3861            Self::Url(url) => write!(f, "{url}"),
3862            Self::Path(path) => write!(f, "{}", path.display()),
3863        }
3864    }
3865}
3866
3867#[derive(Clone, Debug)]
3868enum RegistrySourceWire {
3869    /// Ex) `https://pypi.org/simple`
3870    Url(UrlString),
3871    /// Ex) `../path/to/local/index`
3872    Path(PortablePathBuf),
3873}
3874
3875impl<'de> serde::de::Deserialize<'de> for RegistrySourceWire {
3876    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3877    where
3878        D: serde::de::Deserializer<'de>,
3879    {
3880        struct Visitor;
3881
3882        impl serde::de::Visitor<'_> for Visitor {
3883            type Value = RegistrySourceWire;
3884
3885            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3886                formatter.write_str("a valid URL or a file path")
3887            }
3888
3889            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
3890            where
3891                E: serde::de::Error,
3892            {
3893                if split_scheme(value).is_some() {
3894                    Ok(
3895                        serde::Deserialize::deserialize(serde::de::value::StrDeserializer::new(
3896                            value,
3897                        ))
3898                        .map(RegistrySourceWire::Url)?,
3899                    )
3900                } else {
3901                    Ok(
3902                        serde::Deserialize::deserialize(serde::de::value::StrDeserializer::new(
3903                            value,
3904                        ))
3905                        .map(RegistrySourceWire::Path)?,
3906                    )
3907                }
3908            }
3909        }
3910
3911        deserializer.deserialize_str(Visitor)
3912    }
3913}
3914
3915impl From<RegistrySourceWire> for RegistrySource {
3916    fn from(wire: RegistrySourceWire) -> Self {
3917        match wire {
3918            RegistrySourceWire::Url(url) => Self::Url(url),
3919            RegistrySourceWire::Path(path) => Self::Path(path.into()),
3920        }
3921    }
3922}
3923
3924#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
3925#[serde(rename_all = "kebab-case")]
3926struct DirectSource {
3927    subdirectory: Option<Box<Path>>,
3928}
3929
3930/// NOTE: Care should be taken when adding variants to this enum. Namely, new
3931/// variants should be added without changing the relative ordering of other
3932/// variants. Otherwise, this could cause the lockfile to have a different
3933/// canonical ordering of package entries.
3934#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
3935struct GitSource {
3936    precise: GitOid,
3937    subdirectory: Option<Box<Path>>,
3938    kind: GitSourceKind,
3939}
3940
3941/// An error that occurs when a source string could not be parsed.
3942#[derive(Clone, Debug, Eq, PartialEq)]
3943enum GitSourceError {
3944    InvalidSha,
3945    MissingSha,
3946}
3947
3948impl GitSource {
3949    /// Extracts a Git source reference from the query pairs and the hash
3950    /// fragment in the given URL.
3951    fn from_url(url: &Url) -> Result<Self, GitSourceError> {
3952        let mut kind = GitSourceKind::DefaultBranch;
3953        let mut subdirectory = None;
3954        for (key, val) in url.query_pairs() {
3955            match &*key {
3956                "tag" => kind = GitSourceKind::Tag(val.into_owned()),
3957                "branch" => kind = GitSourceKind::Branch(val.into_owned()),
3958                "rev" => kind = GitSourceKind::Rev(val.into_owned()),
3959                "subdirectory" => subdirectory = Some(PortablePathBuf::from(val.as_ref()).into()),
3960                _ => {}
3961            }
3962        }
3963        let precise = GitOid::from_str(url.fragment().ok_or(GitSourceError::MissingSha)?)
3964            .map_err(|_| GitSourceError::InvalidSha)?;
3965
3966        Ok(Self {
3967            precise,
3968            subdirectory,
3969            kind,
3970        })
3971    }
3972}
3973
3974#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
3975#[serde(rename_all = "kebab-case")]
3976enum GitSourceKind {
3977    Tag(String),
3978    Branch(String),
3979    Rev(String),
3980    DefaultBranch,
3981}
3982
3983/// Inspired by: <https://discuss.python.org/t/lock-files-again-but-this-time-w-sdists/46593>
3984#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
3985#[serde(rename_all = "kebab-case")]
3986struct SourceDistMetadata {
3987    /// A hash of the source distribution.
3988    hash: Option<Hash>,
3989    /// The size of the source distribution in bytes.
3990    ///
3991    /// This is only present for source distributions that come from registries.
3992    size: Option<u64>,
3993    /// The upload time of the source distribution.
3994    #[serde(alias = "upload_time")]
3995    upload_time: Option<Timestamp>,
3996}
3997
3998/// A URL or file path where the source dist that was
3999/// locked against was found. The location does not need to exist in the
4000/// future, so this should be treated as only a hint to where to look
4001/// and/or recording where the source dist file originally came from.
4002#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
4003#[serde(from = "SourceDistWire")]
4004enum SourceDist {
4005    Url {
4006        url: UrlString,
4007        #[serde(flatten)]
4008        metadata: SourceDistMetadata,
4009    },
4010    Path {
4011        path: Box<Path>,
4012        #[serde(flatten)]
4013        metadata: SourceDistMetadata,
4014    },
4015    Metadata {
4016        #[serde(flatten)]
4017        metadata: SourceDistMetadata,
4018    },
4019}
4020
4021impl SourceDist {
4022    fn filename(&self) -> Option<Cow<'_, str>> {
4023        match self {
4024            Self::Metadata { .. } => None,
4025            Self::Url { url, .. } => url.filename().ok(),
4026            Self::Path { path, .. } => path.file_name().map(|filename| filename.to_string_lossy()),
4027        }
4028    }
4029
4030    fn url(&self) -> Option<&UrlString> {
4031        match self {
4032            Self::Metadata { .. } => None,
4033            Self::Url { url, .. } => Some(url),
4034            Self::Path { .. } => None,
4035        }
4036    }
4037
4038    pub(crate) fn hash(&self) -> Option<&Hash> {
4039        match self {
4040            Self::Metadata { metadata } => metadata.hash.as_ref(),
4041            Self::Url { metadata, .. } => metadata.hash.as_ref(),
4042            Self::Path { metadata, .. } => metadata.hash.as_ref(),
4043        }
4044    }
4045
4046    pub(crate) fn size(&self) -> Option<u64> {
4047        match self {
4048            Self::Metadata { metadata } => metadata.size,
4049            Self::Url { metadata, .. } => metadata.size,
4050            Self::Path { metadata, .. } => metadata.size,
4051        }
4052    }
4053
4054    pub(crate) fn upload_time(&self) -> Option<Timestamp> {
4055        match self {
4056            Self::Metadata { metadata } => metadata.upload_time,
4057            Self::Url { metadata, .. } => metadata.upload_time,
4058            Self::Path { metadata, .. } => metadata.upload_time,
4059        }
4060    }
4061}
4062
4063impl SourceDist {
4064    fn from_annotated_dist(
4065        id: &PackageId,
4066        annotated_dist: &AnnotatedDist,
4067    ) -> Result<Option<Self>, LockError> {
4068        match annotated_dist.dist {
4069            // We pass empty installed packages for locking.
4070            ResolvedDist::Installed { .. } => unreachable!(),
4071            ResolvedDist::Installable { ref dist, .. } => Self::from_dist(
4072                id,
4073                dist,
4074                annotated_dist.hashes.as_slice(),
4075                annotated_dist.index(),
4076            ),
4077        }
4078    }
4079
4080    fn from_dist(
4081        id: &PackageId,
4082        dist: &Dist,
4083        hashes: &[HashDigest],
4084        index: Option<&IndexUrl>,
4085    ) -> Result<Option<Self>, LockError> {
4086        match *dist {
4087            Dist::Built(BuiltDist::Registry(ref built_dist)) => {
4088                let Some(sdist) = built_dist.sdist.as_ref() else {
4089                    return Ok(None);
4090                };
4091                Self::from_registry_dist(sdist, index)
4092            }
4093            Dist::Built(_) => Ok(None),
4094            Dist::Source(ref source_dist) => Self::from_source_dist(id, source_dist, hashes, index),
4095        }
4096    }
4097
4098    fn from_source_dist(
4099        id: &PackageId,
4100        source_dist: &uv_distribution_types::SourceDist,
4101        hashes: &[HashDigest],
4102        index: Option<&IndexUrl>,
4103    ) -> Result<Option<Self>, LockError> {
4104        match *source_dist {
4105            uv_distribution_types::SourceDist::Registry(ref reg_dist) => {
4106                Self::from_registry_dist(reg_dist, index)
4107            }
4108            uv_distribution_types::SourceDist::DirectUrl(_) => {
4109                Self::from_direct_dist(id, hashes).map(Some)
4110            }
4111            uv_distribution_types::SourceDist::Path(_) => {
4112                Self::from_path_dist(id, hashes).map(Some)
4113            }
4114            // An actual sdist entry in the lockfile is only required when
4115            // it's from a registry or a direct URL. Otherwise, it's strictly
4116            // redundant with the information in all other kinds of `source`.
4117            uv_distribution_types::SourceDist::Git(_)
4118            | uv_distribution_types::SourceDist::Directory(_) => Ok(None),
4119        }
4120    }
4121
4122    fn from_registry_dist(
4123        reg_dist: &RegistrySourceDist,
4124        index: Option<&IndexUrl>,
4125    ) -> Result<Option<Self>, LockError> {
4126        // Reject distributions from registries that don't match the index URL, as can occur with
4127        // `--find-links`.
4128        if index.is_none_or(|index| *index != reg_dist.index) {
4129            return Ok(None);
4130        }
4131
4132        match &reg_dist.index {
4133            IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
4134                let url = normalize_file_location(&reg_dist.file.url)
4135                    .map_err(LockErrorKind::InvalidUrl)
4136                    .map_err(LockError::from)?;
4137                let hash = reg_dist.file.hashes.iter().max().cloned().map(Hash::from);
4138                let size = reg_dist.file.size;
4139                let upload_time = reg_dist
4140                    .file
4141                    .upload_time_utc_ms
4142                    .map(Timestamp::from_millisecond)
4143                    .transpose()
4144                    .map_err(LockErrorKind::InvalidTimestamp)?;
4145                Ok(Some(Self::Url {
4146                    url,
4147                    metadata: SourceDistMetadata {
4148                        hash,
4149                        size,
4150                        upload_time,
4151                    },
4152                }))
4153            }
4154            IndexUrl::Path(path) => {
4155                let index_path = path
4156                    .to_file_path()
4157                    .map_err(|()| LockErrorKind::UrlToPath { url: path.to_url() })?;
4158                let url = reg_dist
4159                    .file
4160                    .url
4161                    .to_url()
4162                    .map_err(LockErrorKind::InvalidUrl)?;
4163
4164                if url.scheme() == "file" {
4165                    let reg_dist_path = url
4166                        .to_file_path()
4167                        .map_err(|()| LockErrorKind::UrlToPath { url })?;
4168                    let path = relative_to(&reg_dist_path, index_path)
4169                        .or_else(|_| std::path::absolute(&reg_dist_path))
4170                        .map_err(LockErrorKind::DistributionRelativePath)?
4171                        .into_boxed_path();
4172                    let hash = reg_dist.file.hashes.iter().max().cloned().map(Hash::from);
4173                    let size = reg_dist.file.size;
4174                    let upload_time = reg_dist
4175                        .file
4176                        .upload_time_utc_ms
4177                        .map(Timestamp::from_millisecond)
4178                        .transpose()
4179                        .map_err(LockErrorKind::InvalidTimestamp)?;
4180                    Ok(Some(Self::Path {
4181                        path,
4182                        metadata: SourceDistMetadata {
4183                            hash,
4184                            size,
4185                            upload_time,
4186                        },
4187                    }))
4188                } else {
4189                    let url = normalize_file_location(&reg_dist.file.url)
4190                        .map_err(LockErrorKind::InvalidUrl)
4191                        .map_err(LockError::from)?;
4192                    let hash = reg_dist.file.hashes.iter().max().cloned().map(Hash::from);
4193                    let size = reg_dist.file.size;
4194                    let upload_time = reg_dist
4195                        .file
4196                        .upload_time_utc_ms
4197                        .map(Timestamp::from_millisecond)
4198                        .transpose()
4199                        .map_err(LockErrorKind::InvalidTimestamp)?;
4200                    Ok(Some(Self::Url {
4201                        url,
4202                        metadata: SourceDistMetadata {
4203                            hash,
4204                            size,
4205                            upload_time,
4206                        },
4207                    }))
4208                }
4209            }
4210        }
4211    }
4212
4213    fn from_direct_dist(id: &PackageId, hashes: &[HashDigest]) -> Result<Self, LockError> {
4214        let Some(hash) = hashes.iter().max().cloned().map(Hash::from) else {
4215            let kind = LockErrorKind::Hash {
4216                id: id.clone(),
4217                artifact_type: "direct URL source distribution",
4218                expected: true,
4219            };
4220            return Err(kind.into());
4221        };
4222        Ok(Self::Metadata {
4223            metadata: SourceDistMetadata {
4224                hash: Some(hash),
4225                size: None,
4226                upload_time: None,
4227            },
4228        })
4229    }
4230
4231    fn from_path_dist(id: &PackageId, hashes: &[HashDigest]) -> Result<Self, LockError> {
4232        let Some(hash) = hashes.iter().max().cloned().map(Hash::from) else {
4233            let kind = LockErrorKind::Hash {
4234                id: id.clone(),
4235                artifact_type: "path source distribution",
4236                expected: true,
4237            };
4238            return Err(kind.into());
4239        };
4240        Ok(Self::Metadata {
4241            metadata: SourceDistMetadata {
4242                hash: Some(hash),
4243                size: None,
4244                upload_time: None,
4245            },
4246        })
4247    }
4248}
4249
4250#[derive(Clone, Debug, serde::Deserialize)]
4251#[serde(untagged, rename_all = "kebab-case")]
4252enum SourceDistWire {
4253    Url {
4254        url: UrlString,
4255        #[serde(flatten)]
4256        metadata: SourceDistMetadata,
4257    },
4258    Path {
4259        path: PortablePathBuf,
4260        #[serde(flatten)]
4261        metadata: SourceDistMetadata,
4262    },
4263    Metadata {
4264        #[serde(flatten)]
4265        metadata: SourceDistMetadata,
4266    },
4267}
4268
4269impl SourceDist {
4270    /// Returns the TOML representation of this source distribution.
4271    fn to_toml(&self) -> Result<InlineTable, toml_edit::ser::Error> {
4272        let mut table = InlineTable::new();
4273        match self {
4274            Self::Metadata { .. } => {}
4275            Self::Url { url, .. } => {
4276                table.insert("url", Value::from(url.as_ref()));
4277            }
4278            Self::Path { path, .. } => {
4279                table.insert("path", Value::from(PortablePath::from(path).to_string()));
4280            }
4281        }
4282        if let Some(hash) = self.hash() {
4283            table.insert("hash", Value::from(hash.to_string()));
4284        }
4285        if let Some(size) = self.size() {
4286            table.insert(
4287                "size",
4288                toml_edit::ser::ValueSerializer::new().serialize_u64(size)?,
4289            );
4290        }
4291        if let Some(upload_time) = self.upload_time() {
4292            table.insert("upload-time", Value::from(upload_time.to_string()));
4293        }
4294        Ok(table)
4295    }
4296}
4297
4298impl From<SourceDistWire> for SourceDist {
4299    fn from(wire: SourceDistWire) -> Self {
4300        match wire {
4301            SourceDistWire::Url { url, metadata } => Self::Url { url, metadata },
4302            SourceDistWire::Path { path, metadata } => Self::Path {
4303                path: path.into(),
4304                metadata,
4305            },
4306            SourceDistWire::Metadata { metadata } => Self::Metadata { metadata },
4307        }
4308    }
4309}
4310
4311impl From<GitReference> for GitSourceKind {
4312    fn from(value: GitReference) -> Self {
4313        match value {
4314            GitReference::Branch(branch) => Self::Branch(branch),
4315            GitReference::Tag(tag) => Self::Tag(tag),
4316            GitReference::BranchOrTag(rev) => Self::Rev(rev),
4317            GitReference::BranchOrTagOrCommit(rev) => Self::Rev(rev),
4318            GitReference::NamedRef(rev) => Self::Rev(rev),
4319            GitReference::DefaultBranch => Self::DefaultBranch,
4320        }
4321    }
4322}
4323
4324impl From<GitSourceKind> for GitReference {
4325    fn from(value: GitSourceKind) -> Self {
4326        match value {
4327            GitSourceKind::Branch(branch) => Self::Branch(branch),
4328            GitSourceKind::Tag(tag) => Self::Tag(tag),
4329            GitSourceKind::Rev(rev) => Self::from_rev(rev),
4330            GitSourceKind::DefaultBranch => Self::DefaultBranch,
4331        }
4332    }
4333}
4334
4335/// Construct the lockfile-compatible [`DisplaySafeUrl`] for a [`GitSourceDist`].
4336fn locked_git_url(git_dist: &GitSourceDist) -> DisplaySafeUrl {
4337    let mut url = git_dist.git.repository().clone();
4338
4339    // Remove the credentials.
4340    url.remove_credentials();
4341
4342    // Clear out any existing state.
4343    url.set_fragment(None);
4344    url.set_query(None);
4345
4346    // Put the subdirectory in the query.
4347    if let Some(subdirectory) = git_dist
4348        .subdirectory
4349        .as_deref()
4350        .map(PortablePath::from)
4351        .as_ref()
4352        .map(PortablePath::to_string)
4353    {
4354        url.query_pairs_mut()
4355            .append_pair("subdirectory", &subdirectory);
4356    }
4357
4358    // Put the requested reference in the query.
4359    match git_dist.git.reference() {
4360        GitReference::Branch(branch) => {
4361            url.query_pairs_mut().append_pair("branch", branch.as_str());
4362        }
4363        GitReference::Tag(tag) => {
4364            url.query_pairs_mut().append_pair("tag", tag.as_str());
4365        }
4366        GitReference::BranchOrTag(rev)
4367        | GitReference::BranchOrTagOrCommit(rev)
4368        | GitReference::NamedRef(rev) => {
4369            url.query_pairs_mut().append_pair("rev", rev.as_str());
4370        }
4371        GitReference::DefaultBranch => {}
4372    }
4373
4374    // Put the precise commit in the fragment.
4375    url.set_fragment(
4376        git_dist
4377            .git
4378            .precise()
4379            .as_ref()
4380            .map(GitOid::to_string)
4381            .as_deref(),
4382    );
4383
4384    url
4385}
4386
4387#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
4388struct ZstdWheel {
4389    hash: Option<Hash>,
4390    size: Option<u64>,
4391}
4392
4393/// Inspired by: <https://discuss.python.org/t/lock-files-again-but-this-time-w-sdists/46593>
4394#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
4395#[serde(try_from = "WheelWire")]
4396struct Wheel {
4397    /// A URL or file path (via `file://`) where the wheel that was locked
4398    /// against was found. The location does not need to exist in the future,
4399    /// so this should be treated as only a hint to where to look and/or
4400    /// recording where the wheel file originally came from.
4401    url: WheelWireSource,
4402    /// A hash of the built distribution.
4403    ///
4404    /// This is only present for wheels that come from registries and direct
4405    /// URLs. Wheels from git or path dependencies do not have hashes
4406    /// associated with them.
4407    hash: Option<Hash>,
4408    /// The size of the built distribution in bytes.
4409    ///
4410    /// This is only present for wheels that come from registries.
4411    size: Option<u64>,
4412    /// The upload time of the built distribution.
4413    ///
4414    /// This is only present for wheels that come from registries.
4415    upload_time: Option<Timestamp>,
4416    /// The filename of the wheel.
4417    ///
4418    /// This isn't part of the wire format since it's redundant with the
4419    /// URL. But we do use it for various things, and thus compute it at
4420    /// deserialization time. Not being able to extract a wheel filename from a
4421    /// wheel URL is thus a deserialization error.
4422    filename: WheelFilename,
4423    /// The zstandard-compressed wheel metadata, if any.
4424    zstd: Option<ZstdWheel>,
4425}
4426
4427impl Wheel {
4428    fn from_annotated_dist(annotated_dist: &AnnotatedDist) -> Result<Vec<Self>, LockError> {
4429        match annotated_dist.dist {
4430            // We pass empty installed packages for locking.
4431            ResolvedDist::Installed { .. } => unreachable!(),
4432            ResolvedDist::Installable { ref dist, .. } => Self::from_dist(
4433                dist,
4434                annotated_dist.hashes.as_slice(),
4435                annotated_dist.index(),
4436            ),
4437        }
4438    }
4439
4440    fn from_dist(
4441        dist: &Dist,
4442        hashes: &[HashDigest],
4443        index: Option<&IndexUrl>,
4444    ) -> Result<Vec<Self>, LockError> {
4445        match *dist {
4446            Dist::Built(ref built_dist) => Self::from_built_dist(built_dist, hashes, index),
4447            Dist::Source(uv_distribution_types::SourceDist::Registry(ref source_dist)) => {
4448                source_dist
4449                    .wheels
4450                    .iter()
4451                    .filter(|wheel| {
4452                        // Reject distributions from registries that don't match the index URL, as can occur with
4453                        // `--find-links`.
4454                        index.is_some_and(|index| *index == wheel.index)
4455                    })
4456                    .map(Self::from_registry_wheel)
4457                    .collect()
4458            }
4459            Dist::Source(_) => Ok(vec![]),
4460        }
4461    }
4462
4463    fn from_built_dist(
4464        built_dist: &BuiltDist,
4465        hashes: &[HashDigest],
4466        index: Option<&IndexUrl>,
4467    ) -> Result<Vec<Self>, LockError> {
4468        match *built_dist {
4469            BuiltDist::Registry(ref reg_dist) => Self::from_registry_dist(reg_dist, index),
4470            BuiltDist::DirectUrl(ref direct_dist) => {
4471                Ok(vec![Self::from_direct_dist(direct_dist, hashes)])
4472            }
4473            BuiltDist::Path(ref path_dist) => Ok(vec![Self::from_path_dist(path_dist, hashes)]),
4474        }
4475    }
4476
4477    fn from_registry_dist(
4478        reg_dist: &RegistryBuiltDist,
4479        index: Option<&IndexUrl>,
4480    ) -> Result<Vec<Self>, LockError> {
4481        reg_dist
4482            .wheels
4483            .iter()
4484            .filter(|wheel| {
4485                // Reject distributions from registries that don't match the index URL, as can occur with
4486                // `--find-links`.
4487                index.is_some_and(|index| *index == wheel.index)
4488            })
4489            .map(Self::from_registry_wheel)
4490            .collect()
4491    }
4492
4493    fn from_registry_wheel(wheel: &RegistryBuiltWheel) -> Result<Self, LockError> {
4494        let url = match &wheel.index {
4495            IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
4496                let url = normalize_file_location(&wheel.file.url)
4497                    .map_err(LockErrorKind::InvalidUrl)
4498                    .map_err(LockError::from)?;
4499                WheelWireSource::Url { url }
4500            }
4501            IndexUrl::Path(path) => {
4502                let index_path = path
4503                    .to_file_path()
4504                    .map_err(|()| LockErrorKind::UrlToPath { url: path.to_url() })?;
4505                let wheel_url = wheel.file.url.to_url().map_err(LockErrorKind::InvalidUrl)?;
4506
4507                if wheel_url.scheme() == "file" {
4508                    let wheel_path = wheel_url
4509                        .to_file_path()
4510                        .map_err(|()| LockErrorKind::UrlToPath { url: wheel_url })?;
4511                    let path = relative_to(&wheel_path, index_path)
4512                        .or_else(|_| std::path::absolute(&wheel_path))
4513                        .map_err(LockErrorKind::DistributionRelativePath)?
4514                        .into_boxed_path();
4515                    WheelWireSource::Path { path }
4516                } else {
4517                    let url = normalize_file_location(&wheel.file.url)
4518                        .map_err(LockErrorKind::InvalidUrl)
4519                        .map_err(LockError::from)?;
4520                    WheelWireSource::Url { url }
4521                }
4522            }
4523        };
4524        let filename = wheel.filename.clone();
4525        let hash = wheel.file.hashes.iter().max().cloned().map(Hash::from);
4526        let size = wheel.file.size;
4527        let upload_time = wheel
4528            .file
4529            .upload_time_utc_ms
4530            .map(Timestamp::from_millisecond)
4531            .transpose()
4532            .map_err(LockErrorKind::InvalidTimestamp)?;
4533        let zstd = wheel.file.zstd.as_ref().map(|zstd| ZstdWheel {
4534            hash: zstd.hashes.iter().max().cloned().map(Hash::from),
4535            size: zstd.size,
4536        });
4537        Ok(Self {
4538            url,
4539            hash,
4540            size,
4541            upload_time,
4542            filename,
4543            zstd,
4544        })
4545    }
4546
4547    fn from_direct_dist(direct_dist: &DirectUrlBuiltDist, hashes: &[HashDigest]) -> Self {
4548        Self {
4549            url: WheelWireSource::Url {
4550                url: normalize_url(direct_dist.url.to_url()),
4551            },
4552            hash: hashes.iter().max().cloned().map(Hash::from),
4553            size: None,
4554            upload_time: None,
4555            filename: direct_dist.filename.clone(),
4556            zstd: None,
4557        }
4558    }
4559
4560    fn from_path_dist(path_dist: &PathBuiltDist, hashes: &[HashDigest]) -> Self {
4561        Self {
4562            url: WheelWireSource::Filename {
4563                filename: path_dist.filename.clone(),
4564            },
4565            hash: hashes.iter().max().cloned().map(Hash::from),
4566            size: None,
4567            upload_time: None,
4568            filename: path_dist.filename.clone(),
4569            zstd: None,
4570        }
4571    }
4572
4573    pub(crate) fn to_registry_wheel(
4574        &self,
4575        source: &RegistrySource,
4576        root: &Path,
4577    ) -> Result<RegistryBuiltWheel, LockError> {
4578        let filename: WheelFilename = self.filename.clone();
4579
4580        match source {
4581            RegistrySource::Url(url) => {
4582                let file_location = match &self.url {
4583                    WheelWireSource::Url { url: file_url } => {
4584                        FileLocation::AbsoluteUrl(file_url.clone())
4585                    }
4586                    WheelWireSource::Path { .. } | WheelWireSource::Filename { .. } => {
4587                        return Err(LockErrorKind::MissingUrl {
4588                            name: filename.name,
4589                            version: filename.version,
4590                        }
4591                        .into());
4592                    }
4593                };
4594                let file = Box::new(uv_distribution_types::File {
4595                    dist_info_metadata: false,
4596                    filename: SmallString::from(filename.to_string()),
4597                    hashes: self.hash.iter().map(|h| h.0.clone()).collect(),
4598                    requires_python: None,
4599                    size: self.size,
4600                    upload_time_utc_ms: self.upload_time.map(Timestamp::as_millisecond),
4601                    url: file_location,
4602                    yanked: None,
4603                    zstd: self
4604                        .zstd
4605                        .as_ref()
4606                        .map(|zstd| uv_distribution_types::Zstd {
4607                            hashes: zstd.hash.iter().map(|h| h.0.clone()).collect(),
4608                            size: zstd.size,
4609                        })
4610                        .map(Box::new),
4611                });
4612                let index = IndexUrl::from(VerbatimUrl::from_url(
4613                    url.to_url().map_err(LockErrorKind::InvalidUrl)?,
4614                ));
4615                Ok(RegistryBuiltWheel {
4616                    filename,
4617                    file,
4618                    index,
4619                })
4620            }
4621            RegistrySource::Path(index_path) => {
4622                let file_location = match &self.url {
4623                    WheelWireSource::Url { url: file_url } => {
4624                        FileLocation::AbsoluteUrl(file_url.clone())
4625                    }
4626                    WheelWireSource::Path { path: file_path } => {
4627                        let file_path = root.join(index_path).join(file_path);
4628                        let file_url =
4629                            DisplaySafeUrl::from_file_path(&file_path).map_err(|()| {
4630                                LockErrorKind::PathToUrl {
4631                                    path: file_path.into_boxed_path(),
4632                                }
4633                            })?;
4634                        FileLocation::AbsoluteUrl(UrlString::from(file_url))
4635                    }
4636                    WheelWireSource::Filename { .. } => {
4637                        return Err(LockErrorKind::MissingPath {
4638                            name: filename.name,
4639                            version: filename.version,
4640                        }
4641                        .into());
4642                    }
4643                };
4644                let file = Box::new(uv_distribution_types::File {
4645                    dist_info_metadata: false,
4646                    filename: SmallString::from(filename.to_string()),
4647                    hashes: self.hash.iter().map(|h| h.0.clone()).collect(),
4648                    requires_python: None,
4649                    size: self.size,
4650                    upload_time_utc_ms: self.upload_time.map(Timestamp::as_millisecond),
4651                    url: file_location,
4652                    yanked: None,
4653                    zstd: self
4654                        .zstd
4655                        .as_ref()
4656                        .map(|zstd| uv_distribution_types::Zstd {
4657                            hashes: zstd.hash.iter().map(|h| h.0.clone()).collect(),
4658                            size: zstd.size,
4659                        })
4660                        .map(Box::new),
4661                });
4662                let index = IndexUrl::from(
4663                    VerbatimUrl::from_absolute_path(root.join(index_path))
4664                        .map_err(LockErrorKind::RegistryVerbatimUrl)?,
4665                );
4666                Ok(RegistryBuiltWheel {
4667                    filename,
4668                    file,
4669                    index,
4670                })
4671            }
4672        }
4673    }
4674}
4675
4676#[derive(Clone, Debug, serde::Deserialize)]
4677#[serde(rename_all = "kebab-case")]
4678struct WheelWire {
4679    #[serde(flatten)]
4680    url: WheelWireSource,
4681    /// A hash of the built distribution.
4682    ///
4683    /// This is only present for wheels that come from registries and direct
4684    /// URLs. Wheels from git or path dependencies do not have hashes
4685    /// associated with them.
4686    hash: Option<Hash>,
4687    /// The size of the built distribution in bytes.
4688    ///
4689    /// This is only present for wheels that come from registries.
4690    size: Option<u64>,
4691    /// The upload time of the built distribution.
4692    ///
4693    /// This is only present for wheels that come from registries.
4694    #[serde(alias = "upload_time")]
4695    upload_time: Option<Timestamp>,
4696    /// The zstandard-compressed wheel metadata, if any.
4697    #[serde(alias = "zstd")]
4698    zstd: Option<ZstdWheel>,
4699}
4700
4701#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
4702#[serde(untagged, rename_all = "kebab-case")]
4703enum WheelWireSource {
4704    /// Used for all wheels that come from remote sources.
4705    Url {
4706        /// A URL where the wheel that was locked against was found. The location
4707        /// does not need to exist in the future, so this should be treated as
4708        /// only a hint to where to look and/or recording where the wheel file
4709        /// originally came from.
4710        url: UrlString,
4711    },
4712    /// Used for wheels that come from local registries (like `--find-links`).
4713    Path {
4714        /// The path to the wheel, relative to the index.
4715        path: Box<Path>,
4716    },
4717    /// Used for path wheels.
4718    ///
4719    /// We only store the filename for path wheel, since we can't store a relative path in the url
4720    Filename {
4721        /// We duplicate the filename since a lot of code relies on having the filename on the
4722        /// wheel entry.
4723        filename: WheelFilename,
4724    },
4725}
4726
4727impl Wheel {
4728    /// Returns the TOML representation of this wheel.
4729    fn to_toml(&self) -> Result<InlineTable, toml_edit::ser::Error> {
4730        let mut table = InlineTable::new();
4731        match &self.url {
4732            WheelWireSource::Url { url } => {
4733                table.insert("url", Value::from(url.as_ref()));
4734            }
4735            WheelWireSource::Path { path } => {
4736                table.insert("path", Value::from(PortablePath::from(path).to_string()));
4737            }
4738            WheelWireSource::Filename { filename } => {
4739                table.insert("filename", Value::from(filename.to_string()));
4740            }
4741        }
4742        if let Some(ref hash) = self.hash {
4743            table.insert("hash", Value::from(hash.to_string()));
4744        }
4745        if let Some(size) = self.size {
4746            table.insert(
4747                "size",
4748                toml_edit::ser::ValueSerializer::new().serialize_u64(size)?,
4749            );
4750        }
4751        if let Some(upload_time) = self.upload_time {
4752            table.insert("upload-time", Value::from(upload_time.to_string()));
4753        }
4754        if let Some(zstd) = &self.zstd {
4755            let mut inner = InlineTable::new();
4756            if let Some(ref hash) = zstd.hash {
4757                inner.insert("hash", Value::from(hash.to_string()));
4758            }
4759            if let Some(size) = zstd.size {
4760                inner.insert(
4761                    "size",
4762                    toml_edit::ser::ValueSerializer::new().serialize_u64(size)?,
4763                );
4764            }
4765            table.insert("zstd", Value::from(inner));
4766        }
4767        Ok(table)
4768    }
4769}
4770
4771impl TryFrom<WheelWire> for Wheel {
4772    type Error = String;
4773
4774    fn try_from(wire: WheelWire) -> Result<Self, String> {
4775        let filename = match &wire.url {
4776            WheelWireSource::Url { url } => {
4777                let filename = url.filename().map_err(|err| err.to_string())?;
4778                filename.parse::<WheelFilename>().map_err(|err| {
4779                    format!("failed to parse `{filename}` as wheel filename: {err}")
4780                })?
4781            }
4782            WheelWireSource::Path { path } => {
4783                let filename = path
4784                    .file_name()
4785                    .and_then(|file_name| file_name.to_str())
4786                    .ok_or_else(|| {
4787                        format!("path `{}` has no filename component", path.display())
4788                    })?;
4789                filename.parse::<WheelFilename>().map_err(|err| {
4790                    format!("failed to parse `{filename}` as wheel filename: {err}")
4791                })?
4792            }
4793            WheelWireSource::Filename { filename } => filename.clone(),
4794        };
4795
4796        Ok(Self {
4797            url: wire.url,
4798            hash: wire.hash,
4799            size: wire.size,
4800            upload_time: wire.upload_time,
4801            zstd: wire.zstd,
4802            filename,
4803        })
4804    }
4805}
4806
4807/// A single dependency of a package in a lockfile.
4808#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
4809pub struct Dependency {
4810    package_id: PackageId,
4811    extra: BTreeSet<ExtraName>,
4812    /// A marker simplified from the PEP 508 marker in `complexified_marker`
4813    /// by assuming `requires-python` is satisfied. So if
4814    /// `requires-python = '>=3.8'`, then
4815    /// `python_version >= '3.8' and python_version < '3.12'`
4816    /// gets simplified to `python_version < '3.12'`.
4817    ///
4818    /// Generally speaking, this marker should not be exposed to
4819    /// anything outside this module unless it's for a specialized use
4820    /// case. But specifically, it should never be used to evaluate
4821    /// against a marker environment or for disjointness checks or any
4822    /// other kind of marker algebra.
4823    ///
4824    /// It exists because there are some cases where we do actually
4825    /// want to compare markers in their "simplified" form. For
4826    /// example, when collapsing the extras on duplicate dependencies.
4827    /// Even if a dependency has different complexified markers,
4828    /// they might have identical markers once simplified. And since
4829    /// `requires-python` applies to the entire lock file, it's
4830    /// acceptable to do comparisons on the simplified form.
4831    simplified_marker: SimplifiedMarkerTree,
4832    /// The "complexified" marker is a universal marker whose PEP 508
4833    /// marker can stand on its own independent of `requires-python`.
4834    /// It can be safely used for any kind of marker algebra.
4835    complexified_marker: UniversalMarker,
4836}
4837
4838impl Dependency {
4839    fn new(
4840        requires_python: &RequiresPython,
4841        package_id: PackageId,
4842        extra: BTreeSet<ExtraName>,
4843        complexified_marker: UniversalMarker,
4844    ) -> Self {
4845        let simplified_marker =
4846            SimplifiedMarkerTree::new(requires_python, complexified_marker.combined());
4847        let complexified_marker = simplified_marker.into_marker(requires_python);
4848        Self {
4849            package_id,
4850            extra,
4851            simplified_marker,
4852            complexified_marker: UniversalMarker::from_combined(complexified_marker),
4853        }
4854    }
4855
4856    fn from_annotated_dist(
4857        requires_python: &RequiresPython,
4858        annotated_dist: &AnnotatedDist,
4859        complexified_marker: UniversalMarker,
4860        root: &Path,
4861    ) -> Result<Self, LockError> {
4862        let package_id = PackageId::from_annotated_dist(annotated_dist, root)?;
4863        let extra = annotated_dist.extra.iter().cloned().collect();
4864        Ok(Self::new(
4865            requires_python,
4866            package_id,
4867            extra,
4868            complexified_marker,
4869        ))
4870    }
4871
4872    /// Returns the TOML representation of this dependency.
4873    fn to_toml(
4874        &self,
4875        _requires_python: &RequiresPython,
4876        dist_count_by_name: &FxHashMap<PackageName, u64>,
4877    ) -> Table {
4878        let mut table = Table::new();
4879        self.package_id
4880            .to_toml(Some(dist_count_by_name), &mut table);
4881        if !self.extra.is_empty() {
4882            let extra_array = self
4883                .extra
4884                .iter()
4885                .map(ToString::to_string)
4886                .collect::<Array>();
4887            table.insert("extra", value(extra_array));
4888        }
4889        if let Some(marker) = self.simplified_marker.try_to_string() {
4890            table.insert("marker", value(marker));
4891        }
4892
4893        table
4894    }
4895
4896    /// Returns the package name of this dependency.
4897    pub fn package_name(&self) -> &PackageName {
4898        &self.package_id.name
4899    }
4900
4901    /// Returns the extras specified on this dependency.
4902    pub fn extra(&self) -> &BTreeSet<ExtraName> {
4903        &self.extra
4904    }
4905}
4906
4907impl Display for Dependency {
4908    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
4909        match (self.extra.is_empty(), self.package_id.version.as_ref()) {
4910            (true, Some(version)) => write!(f, "{}=={}", self.package_id.name, version),
4911            (true, None) => write!(f, "{}", self.package_id.name),
4912            (false, Some(version)) => write!(
4913                f,
4914                "{}[{}]=={}",
4915                self.package_id.name,
4916                self.extra.iter().join(","),
4917                version
4918            ),
4919            (false, None) => write!(
4920                f,
4921                "{}[{}]",
4922                self.package_id.name,
4923                self.extra.iter().join(",")
4924            ),
4925        }
4926    }
4927}
4928
4929/// A single dependency of a package in a lockfile.
4930#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, serde::Deserialize)]
4931#[serde(rename_all = "kebab-case")]
4932struct DependencyWire {
4933    #[serde(flatten)]
4934    package_id: PackageIdForDependency,
4935    #[serde(default)]
4936    extra: BTreeSet<ExtraName>,
4937    #[serde(default)]
4938    marker: SimplifiedMarkerTree,
4939}
4940
4941impl DependencyWire {
4942    fn unwire(
4943        self,
4944        requires_python: &RequiresPython,
4945        unambiguous_package_ids: &FxHashMap<PackageName, PackageId>,
4946    ) -> Result<Dependency, LockError> {
4947        let complexified_marker = self.marker.into_marker(requires_python);
4948        Ok(Dependency {
4949            package_id: self.package_id.unwire(unambiguous_package_ids)?,
4950            extra: self.extra,
4951            simplified_marker: self.marker,
4952            complexified_marker: UniversalMarker::from_combined(complexified_marker),
4953        })
4954    }
4955}
4956
4957/// A single hash for a distribution artifact in a lockfile.
4958///
4959/// A hash is encoded as a single TOML string in the format
4960/// `{algorithm}:{digest}`.
4961#[derive(Clone, Debug, PartialEq, Eq)]
4962struct Hash(HashDigest);
4963
4964impl From<HashDigest> for Hash {
4965    fn from(hd: HashDigest) -> Self {
4966        Self(hd)
4967    }
4968}
4969
4970impl FromStr for Hash {
4971    type Err = HashParseError;
4972
4973    fn from_str(s: &str) -> Result<Self, HashParseError> {
4974        let (algorithm, digest) = s.split_once(':').ok_or(HashParseError(
4975            "expected '{algorithm}:{digest}', but found no ':' in hash digest",
4976        ))?;
4977        let algorithm = algorithm
4978            .parse()
4979            .map_err(|_| HashParseError("unrecognized hash algorithm"))?;
4980        Ok(Self(HashDigest {
4981            algorithm,
4982            digest: digest.into(),
4983        }))
4984    }
4985}
4986
4987impl Display for Hash {
4988    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
4989        write!(f, "{}:{}", self.0.algorithm, self.0.digest)
4990    }
4991}
4992
4993impl<'de> serde::Deserialize<'de> for Hash {
4994    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4995    where
4996        D: serde::de::Deserializer<'de>,
4997    {
4998        struct Visitor;
4999
5000        impl serde::de::Visitor<'_> for Visitor {
5001            type Value = Hash;
5002
5003            fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
5004                f.write_str("a string")
5005            }
5006
5007            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
5008                Hash::from_str(v).map_err(serde::de::Error::custom)
5009            }
5010        }
5011
5012        deserializer.deserialize_str(Visitor)
5013    }
5014}
5015
5016impl From<Hash> for Hashes {
5017    fn from(value: Hash) -> Self {
5018        match value.0.algorithm {
5019            HashAlgorithm::Md5 => Self {
5020                md5: Some(value.0.digest),
5021                sha256: None,
5022                sha384: None,
5023                sha512: None,
5024                blake2b: None,
5025            },
5026            HashAlgorithm::Sha256 => Self {
5027                md5: None,
5028                sha256: Some(value.0.digest),
5029                sha384: None,
5030                sha512: None,
5031                blake2b: None,
5032            },
5033            HashAlgorithm::Sha384 => Self {
5034                md5: None,
5035                sha256: None,
5036                sha384: Some(value.0.digest),
5037                sha512: None,
5038                blake2b: None,
5039            },
5040            HashAlgorithm::Sha512 => Self {
5041                md5: None,
5042                sha256: None,
5043                sha384: None,
5044                sha512: Some(value.0.digest),
5045                blake2b: None,
5046            },
5047            HashAlgorithm::Blake2b => Self {
5048                md5: None,
5049                sha256: None,
5050                sha384: None,
5051                sha512: None,
5052                blake2b: Some(value.0.digest),
5053            },
5054        }
5055    }
5056}
5057
5058/// Convert a [`FileLocation`] into a normalized [`UrlString`].
5059fn normalize_file_location(location: &FileLocation) -> Result<UrlString, ToUrlError> {
5060    match location {
5061        FileLocation::AbsoluteUrl(absolute) => Ok(absolute.without_fragment().into_owned()),
5062        FileLocation::RelativeUrl(_, _) => Ok(normalize_url(location.to_url()?)),
5063    }
5064}
5065
5066/// Convert a [`DisplaySafeUrl`] into a normalized [`UrlString`] by removing the fragment.
5067fn normalize_url(mut url: DisplaySafeUrl) -> UrlString {
5068    url.set_fragment(None);
5069    UrlString::from(url)
5070}
5071
5072/// Normalize a [`Requirement`], which could come from a lockfile, a `pyproject.toml`, etc.
5073///
5074/// Performs the following steps:
5075///
5076/// 1. Removes any sensitive credentials.
5077/// 2. Ensures that the lock and install paths are appropriately framed with respect to the
5078///    current [`Workspace`].
5079/// 3. Removes the `origin` field, which is only used in `requirements.txt`.
5080/// 4. Simplifies the markers using the provided [`RequiresPython`] instance.
5081fn normalize_requirement(
5082    mut requirement: Requirement,
5083    root: &Path,
5084    requires_python: &RequiresPython,
5085) -> Result<Requirement, LockError> {
5086    // Sort the extras and groups for consistency.
5087    requirement.extras.sort();
5088    requirement.groups.sort();
5089
5090    // Normalize the requirement source.
5091    match requirement.source {
5092        RequirementSource::Git {
5093            git,
5094            subdirectory,
5095            url: _,
5096        } => {
5097            // Reconstruct the Git URL.
5098            let git = {
5099                let mut repository = git.repository().clone();
5100
5101                // Remove the credentials.
5102                repository.remove_credentials();
5103
5104                // Remove the fragment and query from the URL; they're already present in the source.
5105                repository.set_fragment(None);
5106                repository.set_query(None);
5107
5108                GitUrl::from_fields(repository, git.reference().clone(), git.precise())?
5109            };
5110
5111            // Reconstruct the PEP 508 URL from the underlying data.
5112            let url = DisplaySafeUrl::from(ParsedGitUrl {
5113                url: git.clone(),
5114                subdirectory: subdirectory.clone(),
5115            });
5116
5117            Ok(Requirement {
5118                name: requirement.name,
5119                extras: requirement.extras,
5120                groups: requirement.groups,
5121                marker: requires_python.simplify_markers(requirement.marker),
5122                source: RequirementSource::Git {
5123                    git,
5124                    subdirectory,
5125                    url: VerbatimUrl::from_url(url),
5126                },
5127                origin: None,
5128            })
5129        }
5130        RequirementSource::Path {
5131            install_path,
5132            ext,
5133            url: _,
5134        } => {
5135            let install_path =
5136                uv_fs::normalize_path_buf(root.join(&install_path)).into_boxed_path();
5137            let url = VerbatimUrl::from_normalized_path(&install_path)
5138                .map_err(LockErrorKind::RequirementVerbatimUrl)?;
5139
5140            Ok(Requirement {
5141                name: requirement.name,
5142                extras: requirement.extras,
5143                groups: requirement.groups,
5144                marker: requires_python.simplify_markers(requirement.marker),
5145                source: RequirementSource::Path {
5146                    install_path,
5147                    ext,
5148                    url,
5149                },
5150                origin: None,
5151            })
5152        }
5153        RequirementSource::Directory {
5154            install_path,
5155            editable,
5156            r#virtual,
5157            url: _,
5158        } => {
5159            let install_path =
5160                uv_fs::normalize_path_buf(root.join(&install_path)).into_boxed_path();
5161            let url = VerbatimUrl::from_normalized_path(&install_path)
5162                .map_err(LockErrorKind::RequirementVerbatimUrl)?;
5163
5164            Ok(Requirement {
5165                name: requirement.name,
5166                extras: requirement.extras,
5167                groups: requirement.groups,
5168                marker: requires_python.simplify_markers(requirement.marker),
5169                source: RequirementSource::Directory {
5170                    install_path,
5171                    editable: Some(editable.unwrap_or(false)),
5172                    r#virtual: Some(r#virtual.unwrap_or(false)),
5173                    url,
5174                },
5175                origin: None,
5176            })
5177        }
5178        RequirementSource::Registry {
5179            specifier,
5180            index,
5181            conflict,
5182        } => {
5183            // Round-trip the index to remove anything apart from the URL.
5184            let index = index
5185                .map(|index| index.url.into_url())
5186                .map(|mut index| {
5187                    index.remove_credentials();
5188                    index
5189                })
5190                .map(|index| IndexMetadata::from(IndexUrl::from(VerbatimUrl::from_url(index))));
5191            Ok(Requirement {
5192                name: requirement.name,
5193                extras: requirement.extras,
5194                groups: requirement.groups,
5195                marker: requires_python.simplify_markers(requirement.marker),
5196                source: RequirementSource::Registry {
5197                    specifier,
5198                    index,
5199                    conflict,
5200                },
5201                origin: None,
5202            })
5203        }
5204        RequirementSource::Url {
5205            mut location,
5206            subdirectory,
5207            ext,
5208            url: _,
5209        } => {
5210            // Remove the credentials.
5211            location.remove_credentials();
5212
5213            // Remove the fragment from the URL; it's already present in the source.
5214            location.set_fragment(None);
5215
5216            // Reconstruct the PEP 508 URL from the underlying data.
5217            let url = DisplaySafeUrl::from(ParsedArchiveUrl {
5218                url: location.clone(),
5219                subdirectory: subdirectory.clone(),
5220                ext,
5221            });
5222
5223            Ok(Requirement {
5224                name: requirement.name,
5225                extras: requirement.extras,
5226                groups: requirement.groups,
5227                marker: requires_python.simplify_markers(requirement.marker),
5228                source: RequirementSource::Url {
5229                    location,
5230                    subdirectory,
5231                    ext,
5232                    url: VerbatimUrl::from_url(url),
5233                },
5234                origin: None,
5235            })
5236        }
5237    }
5238}
5239
5240#[derive(Debug)]
5241pub struct LockError {
5242    kind: Box<LockErrorKind>,
5243    hint: Option<WheelTagHint>,
5244}
5245
5246impl std::error::Error for LockError {
5247    fn source(&self) -> Option<&(dyn Error + 'static)> {
5248        self.kind.source()
5249    }
5250}
5251
5252impl std::fmt::Display for LockError {
5253    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5254        write!(f, "{}", self.kind)?;
5255        if let Some(hint) = &self.hint {
5256            write!(f, "\n\n{hint}")?;
5257        }
5258        Ok(())
5259    }
5260}
5261
5262impl LockError {
5263    /// Returns true if the [`LockError`] is a resolver error.
5264    pub fn is_resolution(&self) -> bool {
5265        matches!(&*self.kind, LockErrorKind::Resolution { .. })
5266    }
5267}
5268
5269impl<E> From<E> for LockError
5270where
5271    LockErrorKind: From<E>,
5272{
5273    fn from(err: E) -> Self {
5274        Self {
5275            kind: Box::new(LockErrorKind::from(err)),
5276            hint: None,
5277        }
5278    }
5279}
5280
5281#[derive(Debug, Clone, PartialEq, Eq)]
5282#[allow(clippy::enum_variant_names)]
5283enum WheelTagHint {
5284    /// None of the available wheels for a package have a compatible Python language tag (e.g.,
5285    /// `cp310` in `cp310-abi3-manylinux_2_17_x86_64.whl`).
5286    LanguageTags {
5287        package: PackageName,
5288        version: Option<Version>,
5289        tags: BTreeSet<LanguageTag>,
5290        best: Option<LanguageTag>,
5291    },
5292    /// None of the available wheels for a package have a compatible ABI tag (e.g., `abi3` in
5293    /// `cp310-abi3-manylinux_2_17_x86_64.whl`).
5294    AbiTags {
5295        package: PackageName,
5296        version: Option<Version>,
5297        tags: BTreeSet<AbiTag>,
5298        best: Option<AbiTag>,
5299    },
5300    /// None of the available wheels for a package have a compatible platform tag (e.g.,
5301    /// `manylinux_2_17_x86_64` in `cp310-abi3-manylinux_2_17_x86_64.whl`).
5302    PlatformTags {
5303        package: PackageName,
5304        version: Option<Version>,
5305        tags: BTreeSet<PlatformTag>,
5306        best: Option<PlatformTag>,
5307        markers: MarkerEnvironment,
5308    },
5309}
5310
5311impl WheelTagHint {
5312    /// Generate a [`WheelTagHint`] from the given (incompatible) wheels.
5313    fn from_wheels(
5314        name: &PackageName,
5315        version: Option<&Version>,
5316        filenames: &[&WheelFilename],
5317        tags: &Tags,
5318        markers: &MarkerEnvironment,
5319    ) -> Option<Self> {
5320        let incompatibility = filenames
5321            .iter()
5322            .map(|filename| {
5323                tags.compatibility(
5324                    filename.python_tags(),
5325                    filename.abi_tags(),
5326                    filename.platform_tags(),
5327                )
5328            })
5329            .max()?;
5330        match incompatibility {
5331            TagCompatibility::Incompatible(IncompatibleTag::Python) => {
5332                let best = tags.python_tag();
5333                let tags = Self::python_tags(filenames.iter().copied()).collect::<BTreeSet<_>>();
5334                if tags.is_empty() {
5335                    None
5336                } else {
5337                    Some(Self::LanguageTags {
5338                        package: name.clone(),
5339                        version: version.cloned(),
5340                        tags,
5341                        best,
5342                    })
5343                }
5344            }
5345            TagCompatibility::Incompatible(IncompatibleTag::Abi) => {
5346                let best = tags.abi_tag();
5347                let tags = Self::abi_tags(filenames.iter().copied())
5348                    // Ignore `none`, which is universally compatible.
5349                    //
5350                    // As an example, `none` can appear here if we're solving for Python 3.13, and
5351                    // the distribution includes a wheel for `cp312-none-macosx_11_0_arm64`.
5352                    //
5353                    // In that case, the wheel isn't compatible, but when solving for Python 3.13,
5354                    // the `cp312` Python tag _can_ be compatible (e.g., for `cp312-abi3-macosx_11_0_arm64.whl`),
5355                    // so this is considered an ABI incompatibility rather than Python incompatibility.
5356                    .filter(|tag| *tag != AbiTag::None)
5357                    .collect::<BTreeSet<_>>();
5358                if tags.is_empty() {
5359                    None
5360                } else {
5361                    Some(Self::AbiTags {
5362                        package: name.clone(),
5363                        version: version.cloned(),
5364                        tags,
5365                        best,
5366                    })
5367                }
5368            }
5369            TagCompatibility::Incompatible(IncompatibleTag::Platform) => {
5370                let best = tags.platform_tag().cloned();
5371                let incompatible_tags = Self::platform_tags(filenames.iter().copied(), tags)
5372                    .cloned()
5373                    .collect::<BTreeSet<_>>();
5374                if incompatible_tags.is_empty() {
5375                    None
5376                } else {
5377                    Some(Self::PlatformTags {
5378                        package: name.clone(),
5379                        version: version.cloned(),
5380                        tags: incompatible_tags,
5381                        best,
5382                        markers: markers.clone(),
5383                    })
5384                }
5385            }
5386            _ => None,
5387        }
5388    }
5389
5390    /// Returns an iterator over the compatible Python tags of the available wheels.
5391    fn python_tags<'a>(
5392        filenames: impl Iterator<Item = &'a WheelFilename> + 'a,
5393    ) -> impl Iterator<Item = LanguageTag> + 'a {
5394        filenames.flat_map(WheelFilename::python_tags).copied()
5395    }
5396
5397    /// Returns an iterator over the compatible Python tags of the available wheels.
5398    fn abi_tags<'a>(
5399        filenames: impl Iterator<Item = &'a WheelFilename> + 'a,
5400    ) -> impl Iterator<Item = AbiTag> + 'a {
5401        filenames.flat_map(WheelFilename::abi_tags).copied()
5402    }
5403
5404    /// Returns the set of platform tags for the distribution that are ABI-compatible with the given
5405    /// tags.
5406    fn platform_tags<'a>(
5407        filenames: impl Iterator<Item = &'a WheelFilename> + 'a,
5408        tags: &'a Tags,
5409    ) -> impl Iterator<Item = &'a PlatformTag> + 'a {
5410        filenames.flat_map(move |filename| {
5411            if filename.python_tags().iter().any(|wheel_py| {
5412                filename
5413                    .abi_tags()
5414                    .iter()
5415                    .any(|wheel_abi| tags.is_compatible_abi(*wheel_py, *wheel_abi))
5416            }) {
5417                filename.platform_tags().iter()
5418            } else {
5419                [].iter()
5420            }
5421        })
5422    }
5423
5424    fn suggest_environment_marker(markers: &MarkerEnvironment) -> String {
5425        let sys_platform = markers.sys_platform();
5426        let platform_machine = markers.platform_machine();
5427
5428        // Generate the marker string based on actual environment values
5429        if platform_machine.is_empty() {
5430            format!("sys_platform == '{sys_platform}'")
5431        } else {
5432            format!("sys_platform == '{sys_platform}' and platform_machine == '{platform_machine}'")
5433        }
5434    }
5435}
5436
5437impl std::fmt::Display for WheelTagHint {
5438    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5439        match self {
5440            Self::LanguageTags {
5441                package,
5442                version,
5443                tags,
5444                best,
5445            } => {
5446                if let Some(best) = best {
5447                    let s = if tags.len() == 1 { "" } else { "s" };
5448                    let best = if let Some(pretty) = best.pretty() {
5449                        format!("{} (`{}`)", pretty.cyan(), best.cyan())
5450                    } else {
5451                        format!("{}", best.cyan())
5452                    };
5453                    if let Some(version) = version {
5454                        write!(
5455                            f,
5456                            "{}{} You're using {}, but `{}` ({}) only has wheels with the following Python implementation tag{s}: {}",
5457                            "hint".bold().cyan(),
5458                            ":".bold(),
5459                            best,
5460                            package.cyan(),
5461                            format!("v{version}").cyan(),
5462                            tags.iter()
5463                                .map(|tag| format!("`{}`", tag.cyan()))
5464                                .join(", "),
5465                        )
5466                    } else {
5467                        write!(
5468                            f,
5469                            "{}{} You're using {}, but `{}` only has wheels with the following Python implementation tag{s}: {}",
5470                            "hint".bold().cyan(),
5471                            ":".bold(),
5472                            best,
5473                            package.cyan(),
5474                            tags.iter()
5475                                .map(|tag| format!("`{}`", tag.cyan()))
5476                                .join(", "),
5477                        )
5478                    }
5479                } else {
5480                    let s = if tags.len() == 1 { "" } else { "s" };
5481                    if let Some(version) = version {
5482                        write!(
5483                            f,
5484                            "{}{} Wheels are available for `{}` ({}) with the following Python implementation tag{s}: {}",
5485                            "hint".bold().cyan(),
5486                            ":".bold(),
5487                            package.cyan(),
5488                            format!("v{version}").cyan(),
5489                            tags.iter()
5490                                .map(|tag| format!("`{}`", tag.cyan()))
5491                                .join(", "),
5492                        )
5493                    } else {
5494                        write!(
5495                            f,
5496                            "{}{} Wheels are available for `{}` with the following Python implementation tag{s}: {}",
5497                            "hint".bold().cyan(),
5498                            ":".bold(),
5499                            package.cyan(),
5500                            tags.iter()
5501                                .map(|tag| format!("`{}`", tag.cyan()))
5502                                .join(", "),
5503                        )
5504                    }
5505                }
5506            }
5507            Self::AbiTags {
5508                package,
5509                version,
5510                tags,
5511                best,
5512            } => {
5513                if let Some(best) = best {
5514                    let s = if tags.len() == 1 { "" } else { "s" };
5515                    let best = if let Some(pretty) = best.pretty() {
5516                        format!("{} (`{}`)", pretty.cyan(), best.cyan())
5517                    } else {
5518                        format!("{}", best.cyan())
5519                    };
5520                    if let Some(version) = version {
5521                        write!(
5522                            f,
5523                            "{}{} You're using {}, but `{}` ({}) only has wheels with the following Python ABI tag{s}: {}",
5524                            "hint".bold().cyan(),
5525                            ":".bold(),
5526                            best,
5527                            package.cyan(),
5528                            format!("v{version}").cyan(),
5529                            tags.iter()
5530                                .map(|tag| format!("`{}`", tag.cyan()))
5531                                .join(", "),
5532                        )
5533                    } else {
5534                        write!(
5535                            f,
5536                            "{}{} You're using {}, but `{}` only has wheels with the following Python ABI tag{s}: {}",
5537                            "hint".bold().cyan(),
5538                            ":".bold(),
5539                            best,
5540                            package.cyan(),
5541                            tags.iter()
5542                                .map(|tag| format!("`{}`", tag.cyan()))
5543                                .join(", "),
5544                        )
5545                    }
5546                } else {
5547                    let s = if tags.len() == 1 { "" } else { "s" };
5548                    if let Some(version) = version {
5549                        write!(
5550                            f,
5551                            "{}{} Wheels are available for `{}` ({}) with the following Python ABI tag{s}: {}",
5552                            "hint".bold().cyan(),
5553                            ":".bold(),
5554                            package.cyan(),
5555                            format!("v{version}").cyan(),
5556                            tags.iter()
5557                                .map(|tag| format!("`{}`", tag.cyan()))
5558                                .join(", "),
5559                        )
5560                    } else {
5561                        write!(
5562                            f,
5563                            "{}{} Wheels are available for `{}` with the following Python ABI tag{s}: {}",
5564                            "hint".bold().cyan(),
5565                            ":".bold(),
5566                            package.cyan(),
5567                            tags.iter()
5568                                .map(|tag| format!("`{}`", tag.cyan()))
5569                                .join(", "),
5570                        )
5571                    }
5572                }
5573            }
5574            Self::PlatformTags {
5575                package,
5576                version,
5577                tags,
5578                best,
5579                markers,
5580            } => {
5581                let s = if tags.len() == 1 { "" } else { "s" };
5582                if let Some(best) = best {
5583                    let example_marker = Self::suggest_environment_marker(markers);
5584                    let best = if let Some(pretty) = best.pretty() {
5585                        format!("{} (`{}`)", pretty.cyan(), best.cyan())
5586                    } else {
5587                        format!("`{}`", best.cyan())
5588                    };
5589                    let package_ref = if let Some(version) = version {
5590                        format!("`{}` ({})", package.cyan(), format!("v{version}").cyan())
5591                    } else {
5592                        format!("`{}`", package.cyan())
5593                    };
5594                    write!(
5595                        f,
5596                        "{}{} You're on {}, but {} only has wheels for the following platform{s}: {}; consider adding {} to `{}` to ensure uv resolves to a version with compatible wheels",
5597                        "hint".bold().cyan(),
5598                        ":".bold(),
5599                        best,
5600                        package_ref,
5601                        tags.iter()
5602                            .map(|tag| format!("`{}`", tag.cyan()))
5603                            .join(", "),
5604                        format!("\"{example_marker}\"").cyan(),
5605                        "tool.uv.required-environments".green()
5606                    )
5607                } else {
5608                    if let Some(version) = version {
5609                        write!(
5610                            f,
5611                            "{}{} Wheels are available for `{}` ({}) on the following platform{s}: {}",
5612                            "hint".bold().cyan(),
5613                            ":".bold(),
5614                            package.cyan(),
5615                            format!("v{version}").cyan(),
5616                            tags.iter()
5617                                .map(|tag| format!("`{}`", tag.cyan()))
5618                                .join(", "),
5619                        )
5620                    } else {
5621                        write!(
5622                            f,
5623                            "{}{} Wheels are available for `{}` on the following platform{s}: {}",
5624                            "hint".bold().cyan(),
5625                            ":".bold(),
5626                            package.cyan(),
5627                            tags.iter()
5628                                .map(|tag| format!("`{}`", tag.cyan()))
5629                                .join(", "),
5630                        )
5631                    }
5632                }
5633            }
5634        }
5635    }
5636}
5637
5638/// An error that occurs when generating a `Lock` data structure.
5639///
5640/// These errors are sometimes the result of possible programming bugs.
5641/// For example, if there are two or more duplicative distributions given
5642/// to `Lock::new`, then an error is returned. It's likely that the fault
5643/// is with the caller somewhere in such cases.
5644#[derive(Debug, thiserror::Error)]
5645enum LockErrorKind {
5646    /// An error that occurs when multiple packages with the same
5647    /// ID were found.
5648    #[error("Found duplicate package `{id}`", id = id.cyan())]
5649    DuplicatePackage {
5650        /// The ID of the conflicting package.
5651        id: PackageId,
5652    },
5653    /// An error that occurs when there are multiple dependencies for the
5654    /// same package that have identical identifiers.
5655    #[error("For package `{id}`, found duplicate dependency `{dependency}`", id = id.cyan(), dependency = dependency.cyan())]
5656    DuplicateDependency {
5657        /// The ID of the package for which a duplicate dependency was
5658        /// found.
5659        id: PackageId,
5660        /// The ID of the conflicting dependency.
5661        dependency: Dependency,
5662    },
5663    /// An error that occurs when there are multiple dependencies for the
5664    /// same package that have identical identifiers, as part of the
5665    /// that package's optional dependencies.
5666    #[error("For package `{id}`, found duplicate dependency `{dependency}`", id = format!("{id}[{extra}]").cyan(), dependency = dependency.cyan())]
5667    DuplicateOptionalDependency {
5668        /// The ID of the package for which a duplicate dependency was
5669        /// found.
5670        id: PackageId,
5671        /// The name of the extra.
5672        extra: ExtraName,
5673        /// The ID of the conflicting dependency.
5674        dependency: Dependency,
5675    },
5676    /// An error that occurs when there are multiple dependencies for the
5677    /// same package that have identical identifiers, as part of the
5678    /// that package's development dependencies.
5679    #[error("For package `{id}`, found duplicate dependency `{dependency}`", id = format!("{id}:{group}").cyan(), dependency = dependency.cyan())]
5680    DuplicateDevDependency {
5681        /// The ID of the package for which a duplicate dependency was
5682        /// found.
5683        id: PackageId,
5684        /// The name of the dev dependency group.
5685        group: GroupName,
5686        /// The ID of the conflicting dependency.
5687        dependency: Dependency,
5688    },
5689    /// An error that occurs when the URL to a file for a wheel or
5690    /// source dist could not be converted to a structured `url::Url`.
5691    #[error(transparent)]
5692    InvalidUrl(
5693        /// The underlying error that occurred. This includes the
5694        /// errant URL in its error message.
5695        #[from]
5696        ToUrlError,
5697    ),
5698    /// An error that occurs when the extension can't be determined
5699    /// for a given wheel or source distribution.
5700    #[error("Failed to parse file extension for `{id}`; expected one of: {err}", id = id.cyan())]
5701    MissingExtension {
5702        /// The filename that was expected to have an extension.
5703        id: PackageId,
5704        /// The list of valid extensions that were expected.
5705        err: ExtensionError,
5706    },
5707    /// Failed to parse a Git source URL.
5708    #[error("Failed to parse Git URL")]
5709    InvalidGitSourceUrl(
5710        /// The underlying error that occurred. This includes the
5711        /// errant URL in the message.
5712        #[source]
5713        SourceParseError,
5714    ),
5715    #[error("Failed to parse timestamp")]
5716    InvalidTimestamp(
5717        /// The underlying error that occurred. This includes the
5718        /// errant timestamp in the message.
5719        #[source]
5720        jiff::Error,
5721    ),
5722    /// An error that occurs when there's an unrecognized dependency.
5723    ///
5724    /// That is, a dependency for a package that isn't in the lockfile.
5725    #[error("For package `{id}`, found dependency `{dependency}` with no locked package", id = id.cyan(), dependency = dependency.cyan())]
5726    UnrecognizedDependency {
5727        /// The ID of the package that has an unrecognized dependency.
5728        id: PackageId,
5729        /// The ID of the dependency that doesn't have a corresponding package
5730        /// entry.
5731        dependency: Dependency,
5732    },
5733    /// An error that occurs when a hash is expected (or not) for a particular
5734    /// artifact, but one was not found (or was).
5735    #[error("Since the package `{id}` comes from a {source} dependency, a hash was {expected} but one was not found for {artifact_type}", id = id.cyan(), source = id.source.name(), expected = if *expected { "expected" } else { "not expected" })]
5736    Hash {
5737        /// The ID of the package that has a missing hash.
5738        id: PackageId,
5739        /// The specific type of artifact, e.g., "source package"
5740        /// or "wheel".
5741        artifact_type: &'static str,
5742        /// When true, a hash is expected to be present.
5743        expected: bool,
5744    },
5745    /// An error that occurs when a package is included with an extra name,
5746    /// but no corresponding base package (i.e., without the extra) exists.
5747    #[error("Found package `{id}` with extra `{extra}` but no base package", id = id.cyan(), extra = extra.cyan())]
5748    MissingExtraBase {
5749        /// The ID of the package that has a missing base.
5750        id: PackageId,
5751        /// The extra name that was found.
5752        extra: ExtraName,
5753    },
5754    /// An error that occurs when a package is included with a development
5755    /// dependency group, but no corresponding base package (i.e., without
5756    /// the group) exists.
5757    #[error("Found package `{id}` with development dependency group `{group}` but no base package", id = id.cyan())]
5758    MissingDevBase {
5759        /// The ID of the package that has a missing base.
5760        id: PackageId,
5761        /// The development dependency group that was found.
5762        group: GroupName,
5763    },
5764    /// An error that occurs from an invalid lockfile where a wheel comes from a non-wheel source
5765    /// such as a directory.
5766    #[error("Wheels cannot come from {source_type} sources")]
5767    InvalidWheelSource {
5768        /// The ID of the distribution that has a missing base.
5769        id: PackageId,
5770        /// The kind of the invalid source.
5771        source_type: &'static str,
5772    },
5773    /// An error that occurs when a distribution indicates that it is sourced from a remote
5774    /// registry, but is missing a URL.
5775    #[error("Found registry distribution `{name}` ({version}) without a valid URL", name = name.cyan(), version = format!("v{version}").cyan())]
5776    MissingUrl {
5777        /// The name of the distribution that is missing a URL.
5778        name: PackageName,
5779        /// The version of the distribution that is missing a URL.
5780        version: Version,
5781    },
5782    /// An error that occurs when a distribution indicates that it is sourced from a local registry,
5783    /// but is missing a path.
5784    #[error("Found registry distribution `{name}` ({version}) without a valid path", name = name.cyan(), version = format!("v{version}").cyan())]
5785    MissingPath {
5786        /// The name of the distribution that is missing a path.
5787        name: PackageName,
5788        /// The version of the distribution that is missing a path.
5789        version: Version,
5790    },
5791    /// An error that occurs when a distribution indicates that it is sourced from a registry, but
5792    /// is missing a filename.
5793    #[error("Found registry distribution `{id}` without a valid filename", id = id.cyan())]
5794    MissingFilename {
5795        /// The ID of the distribution that is missing a filename.
5796        id: PackageId,
5797    },
5798    /// An error that occurs when a distribution is included with neither wheels nor a source
5799    /// distribution.
5800    #[error("Distribution `{id}` can't be installed because it doesn't have a source distribution or wheel for the current platform", id = id.cyan())]
5801    NeitherSourceDistNorWheel {
5802        /// The ID of the distribution.
5803        id: PackageId,
5804    },
5805    /// An error that occurs when a distribution is marked as both `--no-binary` and `--no-build`.
5806    #[error("Distribution `{id}` can't be installed because it is marked as both `--no-binary` and `--no-build`", id = id.cyan())]
5807    NoBinaryNoBuild {
5808        /// The ID of the distribution.
5809        id: PackageId,
5810    },
5811    /// An error that occurs when a distribution is marked as `--no-binary`, but no source
5812    /// distribution is available.
5813    #[error("Distribution `{id}` can't be installed because it is marked as `--no-binary` but has no source distribution", id = id.cyan())]
5814    NoBinary {
5815        /// The ID of the distribution.
5816        id: PackageId,
5817    },
5818    /// An error that occurs when a distribution is marked as `--no-build`, but no binary
5819    /// distribution is available.
5820    #[error("Distribution `{id}` can't be installed because it is marked as `--no-build` but has no binary distribution", id = id.cyan())]
5821    NoBuild {
5822        /// The ID of the distribution.
5823        id: PackageId,
5824    },
5825    /// An error that occurs when a wheel-only distribution is incompatible with the current
5826    /// platform.
5827    #[error("Distribution `{id}` can't be installed because the binary distribution is incompatible with the current platform", id = id.cyan())]
5828    IncompatibleWheelOnly {
5829        /// The ID of the distribution.
5830        id: PackageId,
5831    },
5832    /// An error that occurs when a wheel-only source is marked as `--no-binary`.
5833    #[error("Distribution `{id}` can't be installed because it is marked as `--no-binary` but is itself a binary distribution", id = id.cyan())]
5834    NoBinaryWheelOnly {
5835        /// The ID of the distribution.
5836        id: PackageId,
5837    },
5838    /// An error that occurs when converting between URLs and paths.
5839    #[error("Found dependency `{id}` with no locked distribution", id = id.cyan())]
5840    VerbatimUrl {
5841        /// The ID of the distribution that has a missing base.
5842        id: PackageId,
5843        /// The inner error we forward.
5844        #[source]
5845        err: VerbatimUrlError,
5846    },
5847    /// An error that occurs when parsing an existing requirement.
5848    #[error("Could not compute relative path between workspace and distribution")]
5849    DistributionRelativePath(
5850        /// The inner error we forward.
5851        #[source]
5852        io::Error,
5853    ),
5854    /// An error that occurs when converting an index URL to a relative path
5855    #[error("Could not compute relative path between workspace and index")]
5856    IndexRelativePath(
5857        /// The inner error we forward.
5858        #[source]
5859        io::Error,
5860    ),
5861    /// An error that occurs when converting a lockfile path from relative to absolute.
5862    #[error("Could not compute absolute path from workspace root and lockfile path")]
5863    AbsolutePath(
5864        /// The inner error we forward.
5865        #[source]
5866        io::Error,
5867    ),
5868    /// An error that occurs when an ambiguous `package.dependency` is
5869    /// missing a `version` field.
5870    #[error("Dependency `{name}` has missing `version` field but has more than one matching package", name = name.cyan())]
5871    MissingDependencyVersion {
5872        /// The name of the dependency that is missing a `version` field.
5873        name: PackageName,
5874    },
5875    /// An error that occurs when an ambiguous `package.dependency` is
5876    /// missing a `source` field.
5877    #[error("Dependency `{name}` has missing `source` field but has more than one matching package", name = name.cyan())]
5878    MissingDependencySource {
5879        /// The name of the dependency that is missing a `source` field.
5880        name: PackageName,
5881    },
5882    /// An error that occurs when parsing an existing requirement.
5883    #[error("Could not compute relative path between workspace and requirement")]
5884    RequirementRelativePath(
5885        /// The inner error we forward.
5886        #[source]
5887        io::Error,
5888    ),
5889    /// An error that occurs when parsing an existing requirement.
5890    #[error("Could not convert between URL and path")]
5891    RequirementVerbatimUrl(
5892        /// The inner error we forward.
5893        #[source]
5894        VerbatimUrlError,
5895    ),
5896    /// An error that occurs when parsing a registry's index URL.
5897    #[error("Could not convert between URL and path")]
5898    RegistryVerbatimUrl(
5899        /// The inner error we forward.
5900        #[source]
5901        VerbatimUrlError,
5902    ),
5903    /// An error that occurs when converting a path to a URL.
5904    #[error("Failed to convert path to URL: {path}", path = path.display().cyan())]
5905    PathToUrl { path: Box<Path> },
5906    /// An error that occurs when converting a URL to a path
5907    #[error("Failed to convert URL to path: {url}", url = url.cyan())]
5908    UrlToPath { url: DisplaySafeUrl },
5909    /// An error that occurs when multiple packages with the same
5910    /// name were found when identifying the root packages.
5911    #[error("Found multiple packages matching `{name}`", name = name.cyan())]
5912    MultipleRootPackages {
5913        /// The ID of the package.
5914        name: PackageName,
5915    },
5916    /// An error that occurs when a root package can't be found.
5917    #[error("Could not find root package `{name}`", name = name.cyan())]
5918    MissingRootPackage {
5919        /// The ID of the package.
5920        name: PackageName,
5921    },
5922    /// An error that occurs when resolving metadata for a package.
5923    #[error("Failed to generate package metadata for `{id}`", id = id.cyan())]
5924    Resolution {
5925        /// The ID of the distribution that failed to resolve.
5926        id: PackageId,
5927        /// The inner error we forward.
5928        #[source]
5929        err: uv_distribution::Error,
5930    },
5931    /// A package has inconsistent versions in a single entry
5932    // Using name instead of id since the version in the id is part of the conflict.
5933    #[error("The entry for package `{name}` ({version}) has wheel `{wheel_filename}` with inconsistent version ({wheel_version}), which indicates a malformed wheel. If this is intentional, set `{env_var}`.", name = name.cyan(), wheel_filename = wheel.filename, wheel_version = wheel.filename.version, env_var = "UV_SKIP_WHEEL_FILENAME_CHECK=1".green())]
5934    InconsistentVersions {
5935        /// The name of the package with the inconsistent entry.
5936        name: PackageName,
5937        /// The version of the package with the inconsistent entry.
5938        version: Version,
5939        /// The wheel with the inconsistent version.
5940        wheel: Wheel,
5941    },
5942    #[error(
5943        "Found conflicting extras `{package1}[{extra1}]` \
5944         and `{package2}[{extra2}]` enabled simultaneously"
5945    )]
5946    ConflictingExtra {
5947        package1: PackageName,
5948        extra1: ExtraName,
5949        package2: PackageName,
5950        extra2: ExtraName,
5951    },
5952    #[error(transparent)]
5953    GitUrlParse(#[from] GitUrlParseError),
5954    #[error("Failed to read `{path}`")]
5955    UnreadablePyprojectToml {
5956        path: PathBuf,
5957        #[source]
5958        err: std::io::Error,
5959    },
5960    #[error("Failed to parse `{path}`")]
5961    InvalidPyprojectToml {
5962        path: PathBuf,
5963        #[source]
5964        err: toml::de::Error,
5965    },
5966    /// An error that occurs when a workspace member has a non-local source.
5967    #[error("Workspace member `{id}` has non-local source", id = id.cyan())]
5968    NonLocalWorkspaceMember {
5969        /// The ID of the workspace member with an invalid source.
5970        id: PackageId,
5971    },
5972}
5973
5974/// An error that occurs when a source string could not be parsed.
5975#[derive(Debug, thiserror::Error)]
5976enum SourceParseError {
5977    /// An error that occurs when the URL in the source is invalid.
5978    #[error("Invalid URL in source `{given}`")]
5979    InvalidUrl {
5980        /// The source string given.
5981        given: String,
5982        /// The URL parse error.
5983        #[source]
5984        err: DisplaySafeUrlError,
5985    },
5986    /// An error that occurs when a Git URL is missing a precise commit SHA.
5987    #[error("Missing SHA in source `{given}`")]
5988    MissingSha {
5989        /// The source string given.
5990        given: String,
5991    },
5992    /// An error that occurs when a Git URL has an invalid SHA.
5993    #[error("Invalid SHA in source `{given}`")]
5994    InvalidSha {
5995        /// The source string given.
5996        given: String,
5997    },
5998}
5999
6000/// An error that occurs when a hash digest could not be parsed.
6001#[derive(Clone, Debug, Eq, PartialEq)]
6002struct HashParseError(&'static str);
6003
6004impl std::error::Error for HashParseError {}
6005
6006impl Display for HashParseError {
6007    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
6008        Display::fmt(self.0, f)
6009    }
6010}
6011
6012/// Format an array so that each element is on its own line and has a trailing comma.
6013///
6014/// Example:
6015///
6016/// ```toml
6017/// dependencies = [
6018///     { name = "idna" },
6019///     { name = "sniffio" },
6020/// ]
6021/// ```
6022fn each_element_on_its_line_array(elements: impl Iterator<Item = impl Into<Value>>) -> Array {
6023    let mut array = elements
6024        .map(|item| {
6025            let mut value = item.into();
6026            // Each dependency is on its own line and indented.
6027            value.decor_mut().set_prefix("\n    ");
6028            value
6029        })
6030        .collect::<Array>();
6031    // With a trailing comma, inserting another entry doesn't change the preceding line,
6032    // reducing the diff noise.
6033    array.set_trailing_comma(true);
6034    // The line break between the last element's comma and the closing square bracket.
6035    array.set_trailing("\n");
6036    array
6037}
6038
6039/// Returns the simplified string-ified version of each marker given.
6040///
6041/// Note that the marker strings returned will include conflict markers if they
6042/// are present.
6043fn simplified_universal_markers(
6044    markers: &[UniversalMarker],
6045    requires_python: &RequiresPython,
6046) -> Vec<String> {
6047    let mut pep508_only = vec![];
6048    let mut seen = FxHashSet::default();
6049    for marker in markers {
6050        let simplified =
6051            SimplifiedMarkerTree::new(requires_python, marker.pep508()).as_simplified_marker_tree();
6052        if seen.insert(simplified) {
6053            pep508_only.push(simplified);
6054        }
6055    }
6056    let any_overlap = pep508_only
6057        .iter()
6058        .tuple_combinations()
6059        .any(|(&marker1, &marker2)| !marker1.is_disjoint(marker2));
6060    let markers = if !any_overlap {
6061        pep508_only
6062    } else {
6063        markers
6064            .iter()
6065            .map(|marker| {
6066                SimplifiedMarkerTree::new(requires_python, marker.combined())
6067                    .as_simplified_marker_tree()
6068            })
6069            .collect()
6070    };
6071    markers
6072        .into_iter()
6073        .filter_map(MarkerTree::try_to_string)
6074        .collect()
6075}
6076
6077#[cfg(test)]
6078mod tests {
6079    use uv_warnings::anstream;
6080
6081    use super::*;
6082
6083    /// Assert a given display snapshot, stripping ANSI color codes.
6084    macro_rules! assert_stripped_snapshot {
6085        ($expr:expr, @$snapshot:literal) => {{
6086            let expr = format!("{}", $expr);
6087            let expr = format!("{}", anstream::adapter::strip_str(&expr));
6088            insta::assert_snapshot!(expr, @$snapshot);
6089        }};
6090    }
6091
6092    #[test]
6093    fn missing_dependency_source_unambiguous() {
6094        let data = r#"
6095version = 1
6096requires-python = ">=3.12"
6097
6098[[package]]
6099name = "a"
6100version = "0.1.0"
6101source = { registry = "https://pypi.org/simple" }
6102sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6103
6104[[package]]
6105name = "b"
6106version = "0.1.0"
6107source = { registry = "https://pypi.org/simple" }
6108sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6109
6110[[package.dependencies]]
6111name = "a"
6112version = "0.1.0"
6113"#;
6114        let result: Result<Lock, _> = toml::from_str(data);
6115        insta::assert_debug_snapshot!(result);
6116    }
6117
6118    #[test]
6119    fn missing_dependency_version_unambiguous() {
6120        let data = r#"
6121version = 1
6122requires-python = ">=3.12"
6123
6124[[package]]
6125name = "a"
6126version = "0.1.0"
6127source = { registry = "https://pypi.org/simple" }
6128sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6129
6130[[package]]
6131name = "b"
6132version = "0.1.0"
6133source = { registry = "https://pypi.org/simple" }
6134sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6135
6136[[package.dependencies]]
6137name = "a"
6138source = { registry = "https://pypi.org/simple" }
6139"#;
6140        let result: Result<Lock, _> = toml::from_str(data);
6141        insta::assert_debug_snapshot!(result);
6142    }
6143
6144    #[test]
6145    fn missing_dependency_source_version_unambiguous() {
6146        let data = r#"
6147version = 1
6148requires-python = ">=3.12"
6149
6150[[package]]
6151name = "a"
6152version = "0.1.0"
6153source = { registry = "https://pypi.org/simple" }
6154sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6155
6156[[package]]
6157name = "b"
6158version = "0.1.0"
6159source = { registry = "https://pypi.org/simple" }
6160sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6161
6162[[package.dependencies]]
6163name = "a"
6164"#;
6165        let result: Result<Lock, _> = toml::from_str(data);
6166        insta::assert_debug_snapshot!(result);
6167    }
6168
6169    #[test]
6170    fn missing_dependency_source_ambiguous() {
6171        let data = r#"
6172version = 1
6173requires-python = ">=3.12"
6174
6175[[package]]
6176name = "a"
6177version = "0.1.0"
6178source = { registry = "https://pypi.org/simple" }
6179sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6180
6181[[package]]
6182name = "a"
6183version = "0.1.1"
6184source = { registry = "https://pypi.org/simple" }
6185sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6186
6187[[package]]
6188name = "b"
6189version = "0.1.0"
6190source = { registry = "https://pypi.org/simple" }
6191sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6192
6193[[package.dependencies]]
6194name = "a"
6195version = "0.1.0"
6196"#;
6197        let result = toml::from_str::<Lock>(data).unwrap_err();
6198        assert_stripped_snapshot!(result, @"Dependency `a` has missing `source` field but has more than one matching package");
6199    }
6200
6201    #[test]
6202    fn missing_dependency_version_ambiguous() {
6203        let data = r#"
6204version = 1
6205requires-python = ">=3.12"
6206
6207[[package]]
6208name = "a"
6209version = "0.1.0"
6210source = { registry = "https://pypi.org/simple" }
6211sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6212
6213[[package]]
6214name = "a"
6215version = "0.1.1"
6216source = { registry = "https://pypi.org/simple" }
6217sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6218
6219[[package]]
6220name = "b"
6221version = "0.1.0"
6222source = { registry = "https://pypi.org/simple" }
6223sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6224
6225[[package.dependencies]]
6226name = "a"
6227source = { registry = "https://pypi.org/simple" }
6228"#;
6229        let result = toml::from_str::<Lock>(data).unwrap_err();
6230        assert_stripped_snapshot!(result, @"Dependency `a` has missing `version` field but has more than one matching package");
6231    }
6232
6233    #[test]
6234    fn missing_dependency_source_version_ambiguous() {
6235        let data = r#"
6236version = 1
6237requires-python = ">=3.12"
6238
6239[[package]]
6240name = "a"
6241version = "0.1.0"
6242source = { registry = "https://pypi.org/simple" }
6243sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6244
6245[[package]]
6246name = "a"
6247version = "0.1.1"
6248source = { registry = "https://pypi.org/simple" }
6249sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6250
6251[[package]]
6252name = "b"
6253version = "0.1.0"
6254source = { registry = "https://pypi.org/simple" }
6255sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6256
6257[[package.dependencies]]
6258name = "a"
6259"#;
6260        let result = toml::from_str::<Lock>(data).unwrap_err();
6261        assert_stripped_snapshot!(result, @"Dependency `a` has missing `source` field but has more than one matching package");
6262    }
6263
6264    #[test]
6265    fn missing_dependency_version_dynamic() {
6266        let data = r#"
6267version = 1
6268requires-python = ">=3.12"
6269
6270[[package]]
6271name = "a"
6272source = { editable = "path/to/a" }
6273
6274[[package]]
6275name = "a"
6276version = "0.1.1"
6277source = { registry = "https://pypi.org/simple" }
6278sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6279
6280[[package]]
6281name = "b"
6282version = "0.1.0"
6283source = { registry = "https://pypi.org/simple" }
6284sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
6285
6286[[package.dependencies]]
6287name = "a"
6288source = { editable = "path/to/a" }
6289"#;
6290        let result = toml::from_str::<Lock>(data);
6291        insta::assert_debug_snapshot!(result);
6292    }
6293
6294    #[test]
6295    fn hash_optional_missing() {
6296        let data = r#"
6297version = 1
6298requires-python = ">=3.12"
6299
6300[[package]]
6301name = "anyio"
6302version = "4.3.0"
6303source = { registry = "https://pypi.org/simple" }
6304wheels = [{ url = "https://files.pythonhosted.org/packages/14/fd/2f20c40b45e4fb4324834aea24bd4afdf1143390242c0b33774da0e2e34f/anyio-4.3.0-py3-none-any.whl" }]
6305"#;
6306        let result: Result<Lock, _> = toml::from_str(data);
6307        insta::assert_debug_snapshot!(result);
6308    }
6309
6310    #[test]
6311    fn hash_optional_present() {
6312        let data = r#"
6313version = 1
6314requires-python = ">=3.12"
6315
6316[[package]]
6317name = "anyio"
6318version = "4.3.0"
6319source = { registry = "https://pypi.org/simple" }
6320wheels = [{ url = "https://files.pythonhosted.org/packages/14/fd/2f20c40b45e4fb4324834aea24bd4afdf1143390242c0b33774da0e2e34f/anyio-4.3.0-py3-none-any.whl", hash = "sha256:048e05d0f6caeed70d731f3db756d35dcc1f35747c8c403364a8332c630441b8" }]
6321"#;
6322        let result: Result<Lock, _> = toml::from_str(data);
6323        insta::assert_debug_snapshot!(result);
6324    }
6325
6326    #[test]
6327    fn hash_required_present() {
6328        let data = r#"
6329version = 1
6330requires-python = ">=3.12"
6331
6332[[package]]
6333name = "anyio"
6334version = "4.3.0"
6335source = { path = "file:///foo/bar" }
6336wheels = [{ url = "file:///foo/bar/anyio-4.3.0-py3-none-any.whl", hash = "sha256:048e05d0f6caeed70d731f3db756d35dcc1f35747c8c403364a8332c630441b8" }]
6337"#;
6338        let result: Result<Lock, _> = toml::from_str(data);
6339        insta::assert_debug_snapshot!(result);
6340    }
6341
6342    #[test]
6343    fn source_direct_no_subdir() {
6344        let data = r#"
6345version = 1
6346requires-python = ">=3.12"
6347
6348[[package]]
6349name = "anyio"
6350version = "4.3.0"
6351source = { url = "https://burntsushi.net" }
6352"#;
6353        let result: Result<Lock, _> = toml::from_str(data);
6354        insta::assert_debug_snapshot!(result);
6355    }
6356
6357    #[test]
6358    fn source_direct_has_subdir() {
6359        let data = r#"
6360version = 1
6361requires-python = ">=3.12"
6362
6363[[package]]
6364name = "anyio"
6365version = "4.3.0"
6366source = { url = "https://burntsushi.net", subdirectory = "wat/foo/bar" }
6367"#;
6368        let result: Result<Lock, _> = toml::from_str(data);
6369        insta::assert_debug_snapshot!(result);
6370    }
6371
6372    #[test]
6373    fn source_directory() {
6374        let data = r#"
6375version = 1
6376requires-python = ">=3.12"
6377
6378[[package]]
6379name = "anyio"
6380version = "4.3.0"
6381source = { directory = "path/to/dir" }
6382"#;
6383        let result: Result<Lock, _> = toml::from_str(data);
6384        insta::assert_debug_snapshot!(result);
6385    }
6386
6387    #[test]
6388    fn source_editable() {
6389        let data = r#"
6390version = 1
6391requires-python = ">=3.12"
6392
6393[[package]]
6394name = "anyio"
6395version = "4.3.0"
6396source = { editable = "path/to/dir" }
6397"#;
6398        let result: Result<Lock, _> = toml::from_str(data);
6399        insta::assert_debug_snapshot!(result);
6400    }
6401}