Skip to main content

uv_resolver/lock/
mod.rs

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