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