Skip to main content

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