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