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