Skip to main content

uv_resolver/lock/
mod.rs

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