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                        };
3706                        let built_dist = BuiltDist::DirectUrl(direct_dist);
3707                        Dist::Built(built_dist)
3708                    }
3709                    Source::Git(url, git) => {
3710                        let Some(install_path) = git.path.as_ref() else {
3711                            return Err(LockErrorKind::InvalidWheelSource {
3712                                id: self.id.clone(),
3713                                source_type: "Git",
3714                            }
3715                            .into());
3716                        };
3717
3718                        // Remove the fragment and query from the URL; they're already present in the
3719                        // `GitSource`.
3720                        let mut url = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
3721                        url.set_fragment(None);
3722                        url.set_query(None);
3723
3724                        // Reconstruct the `GitUrl` from the `GitSource`.
3725                        let git_url = GitUrl::from_commit(
3726                            url,
3727                            GitReference::from(git.kind.clone()),
3728                            git.precise,
3729                            git.lfs,
3730                        )?;
3731
3732                        // Reconstruct the PEP 508-compatible URL from the `GitSource`.
3733                        let url = DisplaySafeUrl::from(ParsedGitPathUrl {
3734                            url: git_url.clone(),
3735                            install_path: install_path.clone(),
3736                            ext: DistExtension::Wheel,
3737                        });
3738
3739                        let filename: WheelFilename =
3740                            self.wheels[best_wheel_index].filename.clone();
3741
3742                        let git_dist = GitPathBuiltDist {
3743                            filename,
3744                            git: Box::new(git_url),
3745                            install_path: install_path.clone(),
3746                            url: VerbatimUrl::from_url(url),
3747                        };
3748                        let built_dist = BuiltDist::GitPath(git_dist);
3749                        Dist::Built(built_dist)
3750                    }
3751                    Source::Directory(_) => {
3752                        return Err(LockErrorKind::InvalidWheelSource {
3753                            id: self.id.clone(),
3754                            source_type: "directory",
3755                        }
3756                        .into());
3757                    }
3758                    Source::Editable(_) => {
3759                        return Err(LockErrorKind::InvalidWheelSource {
3760                            id: self.id.clone(),
3761                            source_type: "editable",
3762                        }
3763                        .into());
3764                    }
3765                    Source::Virtual(_) => {
3766                        return Err(LockErrorKind::InvalidWheelSource {
3767                            id: self.id.clone(),
3768                            source_type: "virtual",
3769                        }
3770                        .into());
3771                    }
3772                };
3773
3774                return Ok(HashedDist { dist, hashes });
3775            }
3776        }
3777
3778        if let Some(sdist) = self.to_source_dist(workspace_root)? {
3779            // Even with `--no-build`, allow virtual packages. (In the future, we may want to allow
3780            // any local source tree, or at least editable source trees, which we allow in
3781            // `uv pip`.)
3782            if !no_build || sdist.is_virtual() {
3783                let hashes = self
3784                    .sdist
3785                    .as_ref()
3786                    .and_then(|s| s.hash())
3787                    .map(|hash| HashDigests::from(vec![hash.0.clone()]))
3788                    .unwrap_or_else(|| HashDigests::from(vec![]));
3789                return Ok(HashedDist {
3790                    dist: Dist::Source(sdist),
3791                    hashes,
3792                });
3793            }
3794        }
3795
3796        match (no_binary, no_build) {
3797            (true, true) => Err(LockErrorKind::NoBinaryNoBuild {
3798                id: self.id.clone(),
3799            }
3800            .into()),
3801            (true, false) if self.id.source.is_wheel() => Err(LockErrorKind::NoBinaryWheelOnly {
3802                id: self.id.clone(),
3803            }
3804            .into()),
3805            (true, false) => Err(LockErrorKind::NoBinary {
3806                id: self.id.clone(),
3807            }
3808            .into()),
3809            (false, true) => Err(LockErrorKind::NoBuild {
3810                id: self.id.clone(),
3811            }
3812            .into()),
3813            (false, false) if self.id.source.is_wheel() => Err(LockError {
3814                kind: Box::new(LockErrorKind::IncompatibleWheelOnly {
3815                    id: self.id.clone(),
3816                }),
3817                hint: self.tag_hint(tag_policy, markers),
3818            }),
3819            (false, false) => Err(LockError {
3820                kind: Box::new(LockErrorKind::NeitherSourceDistNorWheel {
3821                    id: self.id.clone(),
3822                }),
3823                hint: self.tag_hint(tag_policy, markers),
3824            }),
3825        }
3826    }
3827
3828    /// Generate a [`WheelTagHint`] based on wheel-tag incompatibilities.
3829    fn tag_hint(
3830        &self,
3831        tag_policy: TagPolicy<'_>,
3832        markers: &MarkerEnvironment,
3833    ) -> Option<WheelTagHint> {
3834        let filenames = self
3835            .wheels
3836            .iter()
3837            .map(|wheel| &wheel.filename)
3838            .collect::<Vec<_>>();
3839        WheelTagHint::from_wheels(
3840            &self.id.name,
3841            self.id.version.as_ref(),
3842            &filenames,
3843            tag_policy.tags(),
3844            markers,
3845        )
3846    }
3847
3848    /// Convert the source of this [`Package`] to a [`SourceDist`] that can be used in installation.
3849    ///
3850    /// Returns `Ok(None)` if the source cannot be converted because `self.sdist` is `None`. This is required
3851    /// for registry sources.
3852    fn to_source_dist(
3853        &self,
3854        workspace_root: &Path,
3855    ) -> Result<Option<uv_distribution_types::SourceDist>, LockError> {
3856        let sdist = match &self.id.source {
3857            Source::Path(path) => {
3858                // A direct path source can also be a wheel, so validate the extension.
3859                let DistExtension::Source(ext) = DistExtension::from_path(path).map_err(|err| {
3860                    LockErrorKind::MissingExtension {
3861                        id: self.id.clone(),
3862                        err,
3863                    }
3864                })?
3865                else {
3866                    return Ok(None);
3867                };
3868                let install_path = absolute_path(workspace_root, path)?;
3869                let given = path.to_str().expect("lock file paths must be UTF-8");
3870                let path_dist = PathSourceDist {
3871                    name: self.id.name.clone(),
3872                    version: self.id.version.clone(),
3873                    url: verbatim_url(&install_path, &self.id)?.with_given(given),
3874                    install_path: install_path.into_boxed_path(),
3875                    ext,
3876                };
3877                uv_distribution_types::SourceDist::Path(path_dist)
3878            }
3879            Source::Directory(path) => {
3880                let install_path = absolute_path(workspace_root, path)?;
3881                let given = path.to_str().expect("lock file paths must be UTF-8");
3882                let dir_dist = DirectorySourceDist {
3883                    name: self.id.name.clone(),
3884                    url: verbatim_url(&install_path, &self.id)?.with_given(given),
3885                    install_path: install_path.into_boxed_path(),
3886                    editable: Some(false),
3887                    r#virtual: Some(false),
3888                };
3889                uv_distribution_types::SourceDist::Directory(dir_dist)
3890            }
3891            Source::Editable(path) => {
3892                let install_path = absolute_path(workspace_root, path)?;
3893                let given = path.to_str().expect("lock file paths must be UTF-8");
3894                let dir_dist = DirectorySourceDist {
3895                    name: self.id.name.clone(),
3896                    url: verbatim_url(&install_path, &self.id)?.with_given(given),
3897                    install_path: install_path.into_boxed_path(),
3898                    editable: Some(true),
3899                    r#virtual: Some(false),
3900                };
3901                uv_distribution_types::SourceDist::Directory(dir_dist)
3902            }
3903            Source::Virtual(path) => {
3904                let install_path = absolute_path(workspace_root, path)?;
3905                let given = path.to_str().expect("lock file paths must be UTF-8");
3906                let dir_dist = DirectorySourceDist {
3907                    name: self.id.name.clone(),
3908                    url: verbatim_url(&install_path, &self.id)?.with_given(given),
3909                    install_path: install_path.into_boxed_path(),
3910                    editable: Some(false),
3911                    r#virtual: Some(true),
3912                };
3913                uv_distribution_types::SourceDist::Directory(dir_dist)
3914            }
3915            Source::Git(url, git) => {
3916                // Remove the fragment and query from the URL; they're already present in the
3917                // `GitSource`.
3918                let mut url = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
3919                url.set_fragment(None);
3920                url.set_query(None);
3921
3922                let git_url = GitUrl::from_commit(
3923                    url,
3924                    GitReference::from(git.kind.clone()),
3925                    git.precise,
3926                    git.lfs,
3927                )?;
3928
3929                if let Some(install_path) = git.path.as_ref() {
3930                    // A direct path source can also be a wheel, so validate the extension.
3931                    let DistExtension::Source(ext) = DistExtension::from_path(install_path)
3932                        .map_err(|err| LockErrorKind::MissingExtension {
3933                            id: self.id.clone(),
3934                            err,
3935                        })?
3936                    else {
3937                        return Ok(None);
3938                    };
3939
3940                    // Reconstruct the PEP 508-compatible URL from the `GitSource`.
3941                    let url = DisplaySafeUrl::from(ParsedGitPathUrl {
3942                        url: git_url.clone(),
3943                        install_path: install_path.clone(),
3944                        ext: DistExtension::Source(ext),
3945                    });
3946
3947                    let git_dist = GitPathSourceDist {
3948                        name: self.id.name.clone(),
3949                        url: VerbatimUrl::from_url(url),
3950                        git: Box::new(git_url),
3951                        install_path: install_path.clone(),
3952                        ext,
3953                    };
3954                    uv_distribution_types::SourceDist::GitPath(git_dist)
3955                } else {
3956                    // Reconstruct the PEP 508-compatible URL from the `GitSource`.
3957                    let url = DisplaySafeUrl::from(ParsedGitDirectoryUrl {
3958                        url: git_url.clone(),
3959                        subdirectory: git.subdirectory.clone(),
3960                    });
3961
3962                    let git_dist = GitDirectorySourceDist {
3963                        name: self.id.name.clone(),
3964                        url: VerbatimUrl::from_url(url),
3965                        git: Box::new(git_url),
3966                        subdirectory: git.subdirectory.clone(),
3967                    };
3968                    uv_distribution_types::SourceDist::GitDirectory(git_dist)
3969                }
3970            }
3971            Source::Direct(url, direct) => {
3972                // A direct URL source can also be a wheel, so validate the extension.
3973                let DistExtension::Source(ext) =
3974                    DistExtension::from_path(url.base_str()).map_err(|err| {
3975                        LockErrorKind::MissingExtension {
3976                            id: self.id.clone(),
3977                            err,
3978                        }
3979                    })?
3980                else {
3981                    return Ok(None);
3982                };
3983                let location = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
3984                let url = DisplaySafeUrl::from(ParsedArchiveUrl {
3985                    url: location.clone(),
3986                    subdirectory: direct.subdirectory.clone(),
3987                    ext: DistExtension::Source(ext),
3988                });
3989                let direct_dist = DirectUrlSourceDist {
3990                    name: self.id.name.clone(),
3991                    location: Box::new(location),
3992                    subdirectory: direct.subdirectory.clone(),
3993                    ext,
3994                    url: VerbatimUrl::from_url(url),
3995                };
3996                uv_distribution_types::SourceDist::DirectUrl(direct_dist)
3997            }
3998            Source::Registry(RegistrySource::Url(url)) => {
3999                let Some(ref sdist) = self.sdist else {
4000                    return Ok(None);
4001                };
4002
4003                let name = &self.id.name;
4004                let version = self
4005                    .id
4006                    .version
4007                    .as_ref()
4008                    .expect("version for registry source");
4009
4010                let file_url = sdist.url().ok_or_else(|| LockErrorKind::MissingUrl {
4011                    name: name.clone(),
4012                    version: version.clone(),
4013                })?;
4014                let filename = sdist
4015                    .filename()
4016                    .ok_or_else(|| LockErrorKind::MissingFilename {
4017                        id: self.id.clone(),
4018                    })?;
4019                let ext = SourceDistExtension::from_path(filename.as_ref()).map_err(|err| {
4020                    LockErrorKind::MissingExtension {
4021                        id: self.id.clone(),
4022                        err,
4023                    }
4024                })?;
4025                let file = Box::new(uv_distribution_types::File {
4026                    dist_info_metadata: false,
4027                    filename: SmallString::from(filename),
4028                    hashes: sdist.hash().map_or(HashDigests::empty(), |hash| {
4029                        HashDigests::from(hash.0.clone())
4030                    }),
4031                    requires_python: None,
4032                    size: sdist.size(),
4033                    upload_time_utc_ms: sdist.upload_time().map(Timestamp::as_millisecond),
4034                    url: FileLocation::AbsoluteUrl(file_url.clone()),
4035                    yanked: None,
4036                    zstd: None,
4037                });
4038
4039                let index = IndexUrl::from(VerbatimUrl::from_url(
4040                    url.to_url().map_err(LockErrorKind::InvalidUrl)?,
4041                ));
4042
4043                let reg_dist = RegistrySourceDist {
4044                    name: name.clone(),
4045                    version: version.clone(),
4046                    file,
4047                    ext,
4048                    index,
4049                    wheels: vec![],
4050                };
4051                uv_distribution_types::SourceDist::Registry(reg_dist)
4052            }
4053            Source::Registry(RegistrySource::Path(path)) => {
4054                let Some(ref sdist) = self.sdist else {
4055                    return Ok(None);
4056                };
4057
4058                let name = &self.id.name;
4059                let version = self
4060                    .id
4061                    .version
4062                    .as_ref()
4063                    .expect("version for registry source");
4064
4065                let file_url = match sdist {
4066                    SourceDist::Url { url: file_url, .. } => {
4067                        FileLocation::AbsoluteUrl(file_url.clone())
4068                    }
4069                    SourceDist::Path {
4070                        path: file_path, ..
4071                    } => {
4072                        let file_path = workspace_root.join(path).join(file_path);
4073                        let file_url =
4074                            DisplaySafeUrl::from_file_path(&file_path).map_err(|()| {
4075                                LockErrorKind::PathToUrl {
4076                                    path: file_path.into_boxed_path(),
4077                                }
4078                            })?;
4079                        FileLocation::AbsoluteUrl(UrlString::from(file_url))
4080                    }
4081                    SourceDist::Metadata { .. } => {
4082                        return Err(LockErrorKind::MissingPath {
4083                            name: name.clone(),
4084                            version: version.clone(),
4085                        }
4086                        .into());
4087                    }
4088                };
4089                let filename = sdist
4090                    .filename()
4091                    .ok_or_else(|| LockErrorKind::MissingFilename {
4092                        id: self.id.clone(),
4093                    })?;
4094                let ext = SourceDistExtension::from_path(filename.as_ref()).map_err(|err| {
4095                    LockErrorKind::MissingExtension {
4096                        id: self.id.clone(),
4097                        err,
4098                    }
4099                })?;
4100                let file = Box::new(uv_distribution_types::File {
4101                    dist_info_metadata: false,
4102                    filename: SmallString::from(filename),
4103                    hashes: sdist.hash().map_or(HashDigests::empty(), |hash| {
4104                        HashDigests::from(hash.0.clone())
4105                    }),
4106                    requires_python: None,
4107                    size: sdist.size(),
4108                    upload_time_utc_ms: sdist.upload_time().map(Timestamp::as_millisecond),
4109                    url: file_url,
4110                    yanked: None,
4111                    zstd: None,
4112                });
4113
4114                let index = IndexUrl::from(
4115                    VerbatimUrl::from_absolute_path(workspace_root.join(path))
4116                        .map_err(LockErrorKind::RegistryVerbatimUrl)?,
4117                );
4118
4119                let reg_dist = RegistrySourceDist {
4120                    name: name.clone(),
4121                    version: version.clone(),
4122                    file,
4123                    ext,
4124                    index,
4125                    wheels: vec![],
4126                };
4127                uv_distribution_types::SourceDist::Registry(reg_dist)
4128            }
4129        };
4130
4131        Ok(Some(sdist))
4132    }
4133
4134    fn find_best_wheel(&self, tag_policy: TagPolicy<'_>) -> Option<usize> {
4135        type WheelPriority<'lock> = (TagPriority, Option<&'lock BuildTag>);
4136
4137        let mut best: Option<(WheelPriority, usize)> = None;
4138        for (i, wheel) in self.wheels.iter().enumerate() {
4139            let TagCompatibility::Compatible(tag_priority) =
4140                wheel.filename.compatibility(tag_policy.tags())
4141            else {
4142                continue;
4143            };
4144            let build_tag = wheel.filename.build_tag();
4145            let wheel_priority = (tag_priority, build_tag);
4146            match best {
4147                None => {
4148                    best = Some((wheel_priority, i));
4149                }
4150                Some((best_priority, _)) => {
4151                    if wheel_priority > best_priority {
4152                        best = Some((wheel_priority, i));
4153                    }
4154                }
4155            }
4156        }
4157
4158        let best = best.map(|(_, i)| i);
4159        match tag_policy {
4160            TagPolicy::Required(_) => best,
4161            TagPolicy::Preferred(_) => best.or_else(|| self.wheels.first().map(|_| 0)),
4162        }
4163    }
4164
4165    /// Returns the [`PackageName`] of the package.
4166    pub fn name(&self) -> &PackageName {
4167        &self.id.name
4168    }
4169
4170    /// Returns the [`Version`] of the package.
4171    pub fn version(&self) -> Option<&Version> {
4172        self.id.version.as_ref()
4173    }
4174
4175    /// Returns the Git SHA of the package, if it is a Git source.
4176    pub fn git_sha(&self) -> Option<&GitOid> {
4177        match &self.id.source {
4178            Source::Git(_, git) => Some(&git.precise),
4179            _ => None,
4180        }
4181    }
4182
4183    /// Return the fork markers for this package, if any.
4184    pub(crate) fn fork_markers(&self) -> &[UniversalMarker] {
4185        self.fork_markers.as_slice()
4186    }
4187
4188    /// Returns whether this package is included by the given PEP 508 marker.
4189    pub fn is_included_by_marker(&self, marker: MarkerTree) -> bool {
4190        self.fork_markers.is_empty()
4191            || self
4192                .fork_markers
4193                .iter()
4194                .any(|fork_marker| !fork_marker.pep508().is_disjoint(marker))
4195    }
4196
4197    /// Returns the [`IndexUrl`] for the package, if it is a registry source.
4198    pub fn index(&self, root: &Path) -> Result<Option<IndexUrl>, LockError> {
4199        match &self.id.source {
4200            Source::Registry(RegistrySource::Url(url)) => {
4201                let index = IndexUrl::from(VerbatimUrl::from_url(
4202                    url.to_url().map_err(LockErrorKind::InvalidUrl)?,
4203                ));
4204                Ok(Some(index))
4205            }
4206            Source::Registry(RegistrySource::Path(path)) => {
4207                let index = IndexUrl::from(
4208                    VerbatimUrl::from_absolute_path(root.join(path))
4209                        .map_err(LockErrorKind::RegistryVerbatimUrl)?,
4210                );
4211                Ok(Some(index))
4212            }
4213            _ => Ok(None),
4214        }
4215    }
4216
4217    /// Returns all the hashes associated with this [`Package`].
4218    fn hashes(&self) -> HashDigests {
4219        let mut hashes = Vec::with_capacity(
4220            usize::from(self.sdist.as_ref().and_then(|sdist| sdist.hash()).is_some())
4221                + self
4222                    .wheels
4223                    .iter()
4224                    .map(|wheel| usize::from(wheel.hash.is_some()))
4225                    .sum::<usize>(),
4226        );
4227        if let Some(ref sdist) = self.sdist {
4228            if let Some(hash) = sdist.hash() {
4229                hashes.push(hash.0.clone());
4230            }
4231        }
4232        for wheel in &self.wheels {
4233            hashes.extend(wheel.hash.as_ref().map(|h| h.0.clone()));
4234            if let Some(zstd) = wheel.zstd.as_ref() {
4235                hashes.extend(zstd.hash.as_ref().map(|h| h.0.clone()));
4236            }
4237        }
4238        HashDigests::from(hashes)
4239    }
4240
4241    /// Returns the [`ResolvedRepositoryReference`] for the package, if it is a Git source.
4242    pub fn as_git_ref(&self) -> Result<Option<ResolvedRepositoryReference>, LockError> {
4243        match &self.id.source {
4244            Source::Git(url, git) => Ok(Some(ResolvedRepositoryReference {
4245                reference: RepositoryReference {
4246                    url: RepositoryUrl::new(url.to_url().map_err(LockErrorKind::InvalidUrl)?),
4247                    reference: GitReference::from(git.kind.clone()),
4248                },
4249                sha: git.precise,
4250            })),
4251            _ => Ok(None),
4252        }
4253    }
4254
4255    /// Returns `true` if the package is a dynamic source tree.
4256    fn is_dynamic(&self) -> bool {
4257        self.id.version.is_none()
4258    }
4259
4260    /// Returns `true` if the package contains the validation-only package metadata.
4261    pub fn has_metadata(&self) -> bool {
4262        self.metadata != PackageMetadata::default()
4263    }
4264
4265    /// Returns the extras the package provides, if any.
4266    pub fn provides_extras(&self) -> &[ExtraName] {
4267        &self.metadata.provides_extra
4268    }
4269
4270    /// Returns the dependency groups the package provides, if any.
4271    pub fn dependency_groups(&self) -> &BTreeMap<GroupName, BTreeSet<Requirement>> {
4272        &self.metadata.dependency_groups
4273    }
4274
4275    /// Returns the dependencies of the package.
4276    pub fn dependencies(&self) -> &[Dependency] {
4277        &self.dependencies
4278    }
4279
4280    /// Returns all production, optional, and development dependencies of the [`Package`].
4281    fn all_dependencies(&self) -> impl Iterator<Item = &Dependency> {
4282        self.dependencies
4283            .iter()
4284            .chain(self.optional_dependencies.values().flatten())
4285            .chain(self.dependency_groups.values().flatten())
4286    }
4287
4288    /// Returns the optional dependencies of the package.
4289    pub fn optional_dependencies(&self) -> &BTreeMap<ExtraName, Vec<Dependency>> {
4290        &self.optional_dependencies
4291    }
4292
4293    /// Returns the resolved PEP 735 dependency groups of the package.
4294    pub fn resolved_dependency_groups(&self) -> &BTreeMap<GroupName, Vec<Dependency>> {
4295        &self.dependency_groups
4296    }
4297
4298    /// Returns an [`InstallTarget`] view for filtering decisions.
4299    fn as_install_target(&self) -> InstallTarget<'_> {
4300        InstallTarget {
4301            name: self.name(),
4302            is_local: self.id.source.is_local(),
4303        }
4304    }
4305}
4306
4307/// Attempts to construct a `VerbatimUrl` from the given normalized `Path`.
4308fn verbatim_url(path: &Path, id: &PackageId) -> Result<VerbatimUrl, LockError> {
4309    let url =
4310        VerbatimUrl::from_normalized_path(path).map_err(|err| LockErrorKind::VerbatimUrl {
4311            id: id.clone(),
4312            err,
4313        })?;
4314    Ok(url)
4315}
4316
4317/// Attempts to construct an absolute path from the given `Path`.
4318fn absolute_path(workspace_root: &Path, path: &Path) -> Result<PathBuf, LockError> {
4319    let path = uv_fs::normalize_absolute_path(&workspace_root.join(path))
4320        .map_err(LockErrorKind::AbsolutePath)?;
4321    Ok(path)
4322}
4323
4324#[derive(Clone, Debug, serde::Deserialize)]
4325#[serde(rename_all = "kebab-case")]
4326struct PackageWire {
4327    #[serde(flatten)]
4328    id: PackageId,
4329    #[serde(default)]
4330    metadata: PackageMetadata,
4331    #[serde(default)]
4332    sdist: Option<SourceDist>,
4333    #[serde(default)]
4334    wheels: Vec<Wheel>,
4335    #[serde(default, rename = "resolution-markers")]
4336    fork_markers: Vec<SimplifiedMarkerTree>,
4337    #[serde(default)]
4338    dependencies: Vec<DependencyWire>,
4339    #[serde(default)]
4340    optional_dependencies: BTreeMap<ExtraName, Vec<DependencyWire>>,
4341    #[serde(default, rename = "dev-dependencies", alias = "dependency-groups")]
4342    dependency_groups: BTreeMap<GroupName, Vec<DependencyWire>>,
4343}
4344
4345#[derive(Clone, Default, Debug, Eq, PartialEq, serde::Deserialize)]
4346#[serde(rename_all = "kebab-case")]
4347struct PackageMetadata {
4348    #[serde(default)]
4349    requires_dist: BTreeSet<Requirement>,
4350    #[serde(default, rename = "provides-extras")]
4351    provides_extra: Box<[ExtraName]>,
4352    #[serde(default, rename = "requires-dev", alias = "dependency-groups")]
4353    dependency_groups: BTreeMap<GroupName, BTreeSet<Requirement>>,
4354}
4355
4356impl PackageWire {
4357    fn unwire(
4358        self,
4359        requires_python: &RequiresPython,
4360        environment: SimplifiedMarkerTree,
4361        default: UniversalMarker,
4362        unambiguous_package_ids: &FxHashMap<PackageName, PackageId>,
4363    ) -> Result<Package, LockError> {
4364        // Consistency check
4365        if !uv_flags::contains(uv_flags::EnvironmentFlags::SKIP_WHEEL_FILENAME_CHECK) {
4366            if let Some(version) = &self.id.version {
4367                for wheel in &self.wheels {
4368                    if *version != wheel.filename.version
4369                        && *version != wheel.filename.version.clone().without_local()
4370                    {
4371                        return Err(LockError::from(LockErrorKind::InconsistentVersions {
4372                            name: self.id.name,
4373                            version: version.clone(),
4374                            wheel: wheel.clone(),
4375                        }));
4376                    }
4377                }
4378                // We can't check the source dist version since it does not need to contain the version
4379                // in the filename.
4380            }
4381        }
4382
4383        // A registry-source package must carry a version; downstream conversions
4384        // (e.g. `to_source_dist`, `satisfies`) rely on it.
4385        if matches!(self.id.source, Source::Registry(_)) && self.id.version.is_none() {
4386            return Err(LockErrorKind::MissingPackageVersion {
4387                name: self.id.name.clone(),
4388            }
4389            .into());
4390        }
4391
4392        let unwire_deps = |deps: Vec<DependencyWire>| -> Result<Vec<Dependency>, LockError> {
4393            deps.into_iter()
4394                .map(|dep| {
4395                    dep.unwire(
4396                        requires_python,
4397                        environment,
4398                        default,
4399                        unambiguous_package_ids,
4400                    )
4401                })
4402                .collect()
4403        };
4404
4405        Ok(Package {
4406            id: self.id,
4407            metadata: self.metadata,
4408            sdist: self.sdist,
4409            wheels: self.wheels,
4410            fork_markers: self
4411                .fork_markers
4412                .into_iter()
4413                .map(|simplified_marker| simplified_marker.into_marker(requires_python))
4414                .map(UniversalMarker::from_combined)
4415                .collect(),
4416            dependencies: unwire_deps(self.dependencies)?,
4417            optional_dependencies: self
4418                .optional_dependencies
4419                .into_iter()
4420                .map(|(extra, deps)| Ok((extra, unwire_deps(deps)?)))
4421                .collect::<Result<_, LockError>>()?,
4422            dependency_groups: self
4423                .dependency_groups
4424                .into_iter()
4425                .map(|(group, deps)| Ok((group, unwire_deps(deps)?)))
4426                .collect::<Result<_, LockError>>()?,
4427        })
4428    }
4429}
4430
4431/// Inside the lockfile, we match a dependency entry to a package entry through a key made up
4432/// of the name, the version and the source url.
4433#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
4434#[serde(rename_all = "kebab-case")]
4435pub(crate) struct PackageId {
4436    pub(crate) name: PackageName,
4437    version: Option<Version>,
4438    source: Source,
4439}
4440
4441impl PackageId {
4442    fn from_annotated_dist(annotated_dist: &AnnotatedDist, root: &Path) -> Result<Self, LockError> {
4443        // Identify the source of the package.
4444        let source = Source::from_resolved_dist(&annotated_dist.dist, root)?;
4445        // Omit versions for dynamic source trees.
4446        let version = if source.is_source_tree()
4447            && annotated_dist
4448                .metadata
4449                .as_ref()
4450                .is_some_and(|metadata| metadata.dynamic)
4451        {
4452            None
4453        } else {
4454            Some(annotated_dist.version.clone())
4455        };
4456        let name = annotated_dist.name.clone();
4457        Ok(Self {
4458            name,
4459            version,
4460            source,
4461        })
4462    }
4463}
4464
4465impl Display for PackageId {
4466    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
4467        if let Some(version) = &self.version {
4468            write!(f, "{}=={} @ {}", self.name, version, self.source)
4469        } else {
4470            write!(f, "{} @ {}", self.name, self.source)
4471        }
4472    }
4473}
4474
4475#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
4476#[serde(rename_all = "kebab-case")]
4477struct PackageIdForDependency {
4478    name: PackageName,
4479    version: Option<Version>,
4480    source: Option<Source>,
4481}
4482
4483impl PackageIdForDependency {
4484    fn unwire(
4485        self,
4486        unambiguous_package_ids: &FxHashMap<PackageName, PackageId>,
4487    ) -> Result<PackageId, LockError> {
4488        let unambiguous_package_id = unambiguous_package_ids.get(&self.name);
4489        let source = self.source.map(Ok::<_, LockError>).unwrap_or_else(|| {
4490            let Some(package_id) = unambiguous_package_id else {
4491                return Err(LockErrorKind::MissingDependencySource {
4492                    name: self.name.clone(),
4493                }
4494                .into());
4495            };
4496            Ok(package_id.source.clone())
4497        })?;
4498        let version = if let Some(version) = self.version {
4499            Some(version)
4500        } else {
4501            if let Some(package_id) = unambiguous_package_id {
4502                package_id.version.clone()
4503            } else {
4504                // If the package is a source tree, assume that the missing `self.version` field is
4505                // indicative of a dynamic version.
4506                if source.is_source_tree() {
4507                    None
4508                } else {
4509                    return Err(LockErrorKind::MissingDependencyVersion {
4510                        name: self.name.clone(),
4511                    }
4512                    .into());
4513                }
4514            }
4515        };
4516        Ok(PackageId {
4517            name: self.name,
4518            version,
4519            source,
4520        })
4521    }
4522}
4523
4524impl From<PackageId> for PackageIdForDependency {
4525    fn from(id: PackageId) -> Self {
4526        Self {
4527            name: id.name,
4528            version: id.version,
4529            source: Some(id.source),
4530        }
4531    }
4532}
4533
4534/// A unique identifier to differentiate between different sources for the same version of a
4535/// package.
4536///
4537/// NOTE: Care should be taken when adding variants to this enum. Namely, new
4538/// variants should be added without changing the relative ordering of other
4539/// variants. Otherwise, this could cause the lockfile to have a different
4540/// canonical ordering of sources.
4541#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
4542#[serde(try_from = "SourceWire")]
4543enum Source {
4544    /// A registry or `--find-links` index.
4545    Registry(RegistrySource),
4546    /// A Git repository.
4547    Git(UrlString, GitSource),
4548    /// A direct HTTP(S) URL.
4549    Direct(UrlString, DirectSource),
4550    /// A path to a local source or built archive.
4551    Path(Box<Path>),
4552    /// A path to a local directory.
4553    Directory(Box<Path>),
4554    /// A path to a local directory that should be installed as editable.
4555    Editable(Box<Path>),
4556    /// A path to a local directory that should not be built or installed.
4557    Virtual(Box<Path>),
4558}
4559
4560impl Source {
4561    fn from_resolved_dist(resolved_dist: &ResolvedDist, root: &Path) -> Result<Self, LockError> {
4562        match *resolved_dist {
4563            // We pass empty installed packages for locking.
4564            ResolvedDist::Installed { .. } => unreachable!(),
4565            ResolvedDist::Installable { ref dist, .. } => Self::from_dist(dist, root),
4566        }
4567    }
4568
4569    fn from_dist(dist: &Dist, root: &Path) -> Result<Self, LockError> {
4570        match *dist {
4571            Dist::Built(ref built_dist) => Self::from_built_dist(built_dist, root),
4572            Dist::Source(ref source_dist) => Self::from_source_dist(source_dist, root),
4573        }
4574    }
4575
4576    fn from_built_dist(built_dist: &BuiltDist, root: &Path) -> Result<Self, LockError> {
4577        match *built_dist {
4578            BuiltDist::Registry(ref reg_dist) => Self::from_registry_built_dist(reg_dist, root),
4579            BuiltDist::DirectUrl(ref direct_dist) => Ok(Self::from_direct_built_dist(direct_dist)),
4580            BuiltDist::Path(ref path_dist) => Self::from_path_built_dist(path_dist, root),
4581            BuiltDist::GitPath(ref git_dist) => Self::from_git_path_built_dist(git_dist, root),
4582        }
4583    }
4584
4585    fn from_source_dist(
4586        source_dist: &uv_distribution_types::SourceDist,
4587        root: &Path,
4588    ) -> Result<Self, LockError> {
4589        match *source_dist {
4590            uv_distribution_types::SourceDist::Registry(ref reg_dist) => {
4591                Self::from_registry_source_dist(reg_dist, root)
4592            }
4593            uv_distribution_types::SourceDist::DirectUrl(ref direct_dist) => {
4594                Ok(Self::from_direct_source_dist(direct_dist))
4595            }
4596            uv_distribution_types::SourceDist::GitDirectory(ref git_dist) => {
4597                Ok(Self::from_git_directory_source_dist(git_dist))
4598            }
4599            uv_distribution_types::SourceDist::GitPath(ref git_dist) => {
4600                Self::from_git_path_source_dist(git_dist, root)
4601            }
4602            uv_distribution_types::SourceDist::Path(ref path_dist) => {
4603                Self::from_path_source_dist(path_dist, root)
4604            }
4605            uv_distribution_types::SourceDist::Directory(ref directory) => {
4606                Self::from_directory_source_dist(directory, root)
4607            }
4608        }
4609    }
4610
4611    fn from_registry_built_dist(
4612        reg_dist: &RegistryBuiltDist,
4613        root: &Path,
4614    ) -> Result<Self, LockError> {
4615        Self::from_index_url(&reg_dist.best_wheel().index, root)
4616    }
4617
4618    fn from_registry_source_dist(
4619        reg_dist: &RegistrySourceDist,
4620        root: &Path,
4621    ) -> Result<Self, LockError> {
4622        Self::from_index_url(&reg_dist.index, root)
4623    }
4624
4625    fn from_direct_built_dist(direct_dist: &DirectUrlBuiltDist) -> Self {
4626        Self::Direct(
4627            normalize_url(direct_dist.url.to_url()),
4628            DirectSource { subdirectory: None },
4629        )
4630    }
4631
4632    fn from_direct_source_dist(direct_dist: &DirectUrlSourceDist) -> Self {
4633        Self::Direct(
4634            normalize_url(direct_dist.url.to_url()),
4635            DirectSource {
4636                subdirectory: direct_dist.subdirectory.clone(),
4637            },
4638        )
4639    }
4640
4641    fn from_path_built_dist(path_dist: &PathBuiltDist, root: &Path) -> Result<Self, LockError> {
4642        let path = try_relative_to_if(
4643            &path_dist.install_path,
4644            root,
4645            !path_dist.url.was_given_absolute(),
4646        )
4647        .map_err(LockErrorKind::DistributionRelativePath)?;
4648        Ok(Self::Path(path.into_boxed_path()))
4649    }
4650
4651    fn from_path_source_dist(path_dist: &PathSourceDist, root: &Path) -> Result<Self, LockError> {
4652        let path = try_relative_to_if(
4653            &path_dist.install_path,
4654            root,
4655            !path_dist.url.was_given_absolute(),
4656        )
4657        .map_err(LockErrorKind::DistributionRelativePath)?;
4658        Ok(Self::Path(path.into_boxed_path()))
4659    }
4660
4661    fn from_directory_source_dist(
4662        directory_dist: &DirectorySourceDist,
4663        root: &Path,
4664    ) -> Result<Self, LockError> {
4665        let path = try_relative_to_if(
4666            &directory_dist.install_path,
4667            root,
4668            !directory_dist.url.was_given_absolute(),
4669        )
4670        .map_err(LockErrorKind::DistributionRelativePath)?;
4671        if directory_dist.editable.unwrap_or(false) {
4672            Ok(Self::Editable(path.into_boxed_path()))
4673        } else if directory_dist.r#virtual.unwrap_or(false) {
4674            Ok(Self::Virtual(path.into_boxed_path()))
4675        } else {
4676            Ok(Self::Directory(path.into_boxed_path()))
4677        }
4678    }
4679
4680    fn from_index_url(index_url: &IndexUrl, root: &Path) -> Result<Self, LockError> {
4681        match index_url {
4682            IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
4683                // Remove any sensitive credentials from the index URL.
4684                let redacted = index_url.without_credentials();
4685                let source = RegistrySource::Url(UrlString::from(redacted.as_ref()));
4686                Ok(Self::Registry(source))
4687            }
4688            IndexUrl::Path(url) => {
4689                let path = url
4690                    .to_file_path()
4691                    .map_err(|()| LockErrorKind::UrlToPath { url: url.to_url() })?;
4692                let path = try_relative_to_if(&path, root, !url.was_given_absolute())
4693                    .map_err(LockErrorKind::IndexRelativePath)?;
4694                let source = RegistrySource::Path(path.into_boxed_path());
4695                Ok(Self::Registry(source))
4696            }
4697        }
4698    }
4699
4700    fn from_git_path_built_dist(
4701        git_dist: &GitPathBuiltDist,
4702        root: &Path,
4703    ) -> Result<Self, LockError> {
4704        let path = relative_to(&git_dist.install_path, root)
4705            .or_else(|_| std::path::absolute(&git_dist.install_path))
4706            .map_err(LockErrorKind::DistributionRelativePath)?;
4707        Ok(Self::Git(
4708            UrlString::from(locked_git_url(
4709                &git_dist.git,
4710                None,
4711                Some(git_dist.install_path.as_path()),
4712            )),
4713            GitSource {
4714                kind: GitSourceKind::from(git_dist.git.reference().clone()),
4715                precise: git_dist.git.precise().unwrap_or_else(|| {
4716                    panic!("Git distribution is missing a precise hash: {git_dist}")
4717                }),
4718                subdirectory: None,
4719                path: Some(path),
4720                lfs: git_dist.git.lfs(),
4721            },
4722        ))
4723    }
4724
4725    fn from_git_path_source_dist(
4726        git_dist: &GitPathSourceDist,
4727        root: &Path,
4728    ) -> Result<Self, LockError> {
4729        let path = relative_to(&git_dist.install_path, root)
4730            .or_else(|_| std::path::absolute(&git_dist.install_path))
4731            .map_err(LockErrorKind::DistributionRelativePath)?;
4732        Ok(Self::Git(
4733            UrlString::from(locked_git_url(
4734                &git_dist.git,
4735                None,
4736                Some(git_dist.install_path.as_path()),
4737            )),
4738            GitSource {
4739                kind: GitSourceKind::from(git_dist.git.reference().clone()),
4740                precise: git_dist.git.precise().unwrap_or_else(|| {
4741                    panic!("Git distribution is missing a precise hash: {git_dist}")
4742                }),
4743                subdirectory: None,
4744                path: Some(path),
4745                lfs: git_dist.git.lfs(),
4746            },
4747        ))
4748    }
4749
4750    fn from_git_directory_source_dist(git_dist: &GitDirectorySourceDist) -> Self {
4751        Self::Git(
4752            UrlString::from(locked_git_url(
4753                &git_dist.git,
4754                git_dist.subdirectory.as_deref(),
4755                None,
4756            )),
4757            GitSource {
4758                kind: GitSourceKind::from(git_dist.git.reference().clone()),
4759                precise: git_dist.git.precise().unwrap_or_else(|| {
4760                    panic!("Git distribution is missing a precise hash: {git_dist}")
4761                }),
4762                subdirectory: git_dist.subdirectory.clone(),
4763                path: None,
4764                lfs: git_dist.git.lfs(),
4765            },
4766        )
4767    }
4768
4769    /// Returns `true` if the source is a registry entry pointing at PyPI (`https://pypi.org/simple`).
4770    fn is_pypi_registry(&self) -> bool {
4771        matches!(
4772            self,
4773            Self::Registry(RegistrySource::Url(url)) if url.as_ref() == PYPI_URL.as_str()
4774        )
4775    }
4776
4777    /// Returns whether this locked source can satisfy a refreshed requirement.
4778    fn satisfies_requirement_source(
4779        &self,
4780        requirement: &RequirementSource,
4781        root: &Path,
4782    ) -> Result<bool, LockError> {
4783        let result = match (self, requirement) {
4784            (Self::Registry(_), RequirementSource::Registry { index: None, .. }) => true,
4785            (
4786                Self::Registry(RegistrySource::Path(actual)),
4787                RequirementSource::Registry {
4788                    index:
4789                        Some(IndexMetadata {
4790                            url: IndexUrl::Path(expected),
4791                            ..
4792                        }),
4793                    ..
4794                },
4795            ) => {
4796                let expected = expected
4797                    .to_file_path()
4798                    .map_err(|()| LockErrorKind::UrlToPath {
4799                        url: expected.to_url(),
4800                    })?;
4801                normalize_path(root.join(actual)).as_ref() == normalize_path(expected).as_ref()
4802            }
4803            (
4804                Self::Registry(_),
4805                RequirementSource::Registry {
4806                    index: Some(index), ..
4807                },
4808            ) => Self::from_index_url(&index.url, root)? == *self,
4809            (
4810                Self::Direct(url, source),
4811                RequirementSource::Url {
4812                    location,
4813                    subdirectory,
4814                    ..
4815                },
4816            ) => {
4817                let mut actual = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
4818                actual.remove_credentials();
4819                normalize_url(actual) == normalize_url(location.clone())
4820                    && source.subdirectory == *subdirectory
4821            }
4822            (Self::Path(path), RequirementSource::Path { install_path, .. }) => {
4823                normalize_path(root.join(path)).as_ref() == install_path.as_ref()
4824            }
4825            (
4826                Self::Directory(path) | Self::Editable(path) | Self::Virtual(path),
4827                RequirementSource::Directory {
4828                    install_path,
4829                    editable,
4830                    r#virtual,
4831                    ..
4832                },
4833            ) => {
4834                let actual = normalize_path(root.join(path));
4835                actual.as_ref() == install_path.as_ref()
4836                    && matches!(self, Self::Editable(_)) == editable.unwrap_or(false)
4837                    && (matches!(self, Self::Virtual(_)) == r#virtual.unwrap_or(false)
4838                        || matches!(self, Self::Virtual(_))
4839                            && install_path.as_ref() == normalize_path(root).as_ref())
4840            }
4841            (
4842                Self::Git(url, source),
4843                RequirementSource::GitDirectory {
4844                    git, subdirectory, ..
4845                },
4846            ) => {
4847                let mut expected = locked_git_url(git, subdirectory.as_deref(), None);
4848                expected.set_fragment(None);
4849                let mut actual = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
4850                actual.set_fragment(None);
4851                expected == actual
4852                    && source.path.is_none()
4853                    && git
4854                        .precise()
4855                        .as_ref()
4856                        .is_none_or(|precise| precise == &source.precise)
4857            }
4858            (
4859                Self::Git(url, source),
4860                RequirementSource::GitPath {
4861                    git, install_path, ..
4862                },
4863            ) => {
4864                let mut expected = locked_git_url(git, None, Some(install_path));
4865                expected.set_fragment(None);
4866                let mut actual = url.to_url().map_err(LockErrorKind::InvalidUrl)?;
4867                actual.set_fragment(None);
4868                expected == actual
4869                    && source.path.is_some()
4870                    && git
4871                        .precise()
4872                        .as_ref()
4873                        .is_none_or(|precise| precise == &source.precise)
4874            }
4875            _ => false,
4876        };
4877        Ok(result)
4878    }
4879
4880    /// Returns `true` if the source should be considered immutable.
4881    ///
4882    /// We assume that registry sources are immutable. In other words, we expect that once a
4883    /// package-version is published to a registry, its metadata will not change.
4884    ///
4885    /// We also assume that Git sources are immutable, since a Git source encodes a specific commit.
4886    fn is_immutable(&self) -> bool {
4887        matches!(self, Self::Registry(..) | Self::Git(_, _))
4888    }
4889
4890    /// Returns `true` if the source is that of a wheel.
4891    fn is_wheel(&self) -> bool {
4892        match self {
4893            Self::Path(path) => {
4894                matches!(
4895                    DistExtension::from_path(path).ok(),
4896                    Some(DistExtension::Wheel)
4897                )
4898            }
4899            Self::Direct(url, _) => {
4900                matches!(
4901                    DistExtension::from_path(url.as_ref()).ok(),
4902                    Some(DistExtension::Wheel)
4903                )
4904            }
4905            Self::Directory(..) => false,
4906            Self::Editable(..) => false,
4907            Self::Virtual(..) => false,
4908            Self::Git(..) => false,
4909            Self::Registry(..) => false,
4910        }
4911    }
4912
4913    /// Returns `true` if the source is that of a source tree.
4914    fn is_source_tree(&self) -> bool {
4915        match self {
4916            Self::Directory(..) | Self::Editable(..) | Self::Virtual(..) => true,
4917            Self::Path(..) | Self::Git(..) | Self::Registry(..) | Self::Direct(..) => false,
4918        }
4919    }
4920
4921    /// Returns the path to the source tree, if the source is a source tree.
4922    fn as_source_tree(&self) -> Option<&Path> {
4923        match self {
4924            Self::Directory(path) | Self::Editable(path) | Self::Virtual(path) => Some(path),
4925            Self::Path(..) | Self::Git(..) | Self::Registry(..) | Self::Direct(..) => None,
4926        }
4927    }
4928
4929    /// Check if a package is local by examining its source.
4930    fn is_local(&self) -> bool {
4931        matches!(
4932            self,
4933            Self::Path(_) | Self::Directory(_) | Self::Editable(_) | Self::Virtual(_)
4934        )
4935    }
4936}
4937
4938impl Display for Source {
4939    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
4940        match self {
4941            Self::Registry(RegistrySource::Url(url)) | Self::Git(url, _) | Self::Direct(url, _) => {
4942                write!(f, "{}+{}", self.name(), url)
4943            }
4944            Self::Registry(RegistrySource::Path(path))
4945            | Self::Path(path)
4946            | Self::Directory(path)
4947            | Self::Editable(path)
4948            | Self::Virtual(path) => {
4949                write!(f, "{}+{}", self.name(), PortablePath::from(path))
4950            }
4951        }
4952    }
4953}
4954
4955impl Source {
4956    fn name(&self) -> &str {
4957        match self {
4958            Self::Registry(..) => "registry",
4959            Self::Git(..) => "git",
4960            Self::Direct(..) => "direct",
4961            Self::Path(..) => "path",
4962            Self::Directory(..) => "directory",
4963            Self::Editable(..) => "editable",
4964            Self::Virtual(..) => "virtual",
4965        }
4966    }
4967
4968    /// Returns `Some(true)` to indicate that the source kind _must_ include a
4969    /// hash.
4970    ///
4971    /// Returns `Some(false)` to indicate that the source kind _must not_
4972    /// include a hash.
4973    ///
4974    /// Returns `None` to indicate that the source kind _may_ include a hash.
4975    fn requires_hash(&self) -> Option<bool> {
4976        match self {
4977            Self::Registry(..) => None,
4978            Self::Direct(..) | Self::Path(..) => Some(true),
4979            Self::Git(.., GitSource { path, .. }) => Some(path.is_some()),
4980            Self::Directory(..) | Self::Editable(..) | Self::Virtual(..) => Some(false),
4981        }
4982    }
4983}
4984
4985#[derive(Clone, Debug, serde::Deserialize)]
4986#[serde(untagged, rename_all = "kebab-case")]
4987enum SourceWire {
4988    Registry {
4989        registry: RegistrySourceWire,
4990    },
4991    Git {
4992        git: String,
4993    },
4994    Direct {
4995        url: UrlString,
4996        subdirectory: Option<PortablePathBuf>,
4997    },
4998    Path {
4999        path: PortablePathBuf,
5000    },
5001    Directory {
5002        directory: PortablePathBuf,
5003    },
5004    Editable {
5005        editable: PortablePathBuf,
5006    },
5007    Virtual {
5008        r#virtual: PortablePathBuf,
5009    },
5010}
5011
5012impl TryFrom<SourceWire> for Source {
5013    type Error = LockError;
5014
5015    fn try_from(wire: SourceWire) -> Result<Self, LockError> {
5016        use self::SourceWire::{Direct, Directory, Editable, Git, Path, Registry, Virtual};
5017
5018        match wire {
5019            Registry { registry } => Ok(Self::Registry(registry.into())),
5020            Git { git } => {
5021                let url = DisplaySafeUrl::parse(&git)
5022                    .map_err(|err| SourceParseError::InvalidUrl {
5023                        given: git.clone(),
5024                        err,
5025                    })
5026                    .map_err(LockErrorKind::InvalidGitSourceUrl)?;
5027
5028                let git_source = GitSource::from_url(&url)
5029                    .map_err(|err| match err {
5030                        GitSourceError::InvalidSha => SourceParseError::InvalidSha { given: git },
5031                        GitSourceError::MissingSha => SourceParseError::MissingSha { given: git },
5032                    })
5033                    .map_err(LockErrorKind::InvalidGitSourceUrl)?;
5034
5035                Ok(Self::Git(UrlString::from(url), git_source))
5036            }
5037            Direct { url, subdirectory } => Ok(Self::Direct(
5038                url,
5039                DirectSource {
5040                    subdirectory: subdirectory.map(Box::<std::path::Path>::from),
5041                },
5042            )),
5043            Path { path } => Ok(Self::Path(path.into())),
5044            Directory { directory } => Ok(Self::Directory(directory.into())),
5045            Editable { editable } => Ok(Self::Editable(editable.into())),
5046            Virtual { r#virtual } => Ok(Self::Virtual(r#virtual.into())),
5047        }
5048    }
5049}
5050
5051/// The source for a registry, which could be a URL or a relative path.
5052#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
5053enum RegistrySource {
5054    /// Ex) `https://pypi.org/simple`
5055    Url(UrlString),
5056    /// Ex) `../path/to/local/index`
5057    Path(Box<Path>),
5058}
5059
5060impl Display for RegistrySource {
5061    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
5062        match self {
5063            Self::Url(url) => write!(f, "{url}"),
5064            Self::Path(path) => write!(f, "{}", path.display()),
5065        }
5066    }
5067}
5068
5069#[derive(Clone, Debug)]
5070enum RegistrySourceWire {
5071    /// Ex) `https://pypi.org/simple`
5072    Url(UrlString),
5073    /// Ex) `../path/to/local/index`
5074    Path(PortablePathBuf),
5075}
5076
5077impl<'de> serde::de::Deserialize<'de> for RegistrySourceWire {
5078    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5079    where
5080        D: serde::de::Deserializer<'de>,
5081    {
5082        struct Visitor;
5083
5084        impl serde::de::Visitor<'_> for Visitor {
5085            type Value = RegistrySourceWire;
5086
5087            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
5088                formatter.write_str("a valid URL or a file path")
5089            }
5090
5091            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
5092            where
5093                E: serde::de::Error,
5094            {
5095                if split_scheme(value).is_some_and(|(scheme, _)| Scheme::parse(scheme).is_some()) {
5096                    Ok(
5097                        serde::Deserialize::deserialize(serde::de::value::StrDeserializer::new(
5098                            value,
5099                        ))
5100                        .map(RegistrySourceWire::Url)?,
5101                    )
5102                } else {
5103                    Ok(
5104                        serde::Deserialize::deserialize(serde::de::value::StrDeserializer::new(
5105                            value,
5106                        ))
5107                        .map(RegistrySourceWire::Path)?,
5108                    )
5109                }
5110            }
5111        }
5112
5113        deserializer.deserialize_str(Visitor)
5114    }
5115}
5116
5117impl From<RegistrySourceWire> for RegistrySource {
5118    fn from(wire: RegistrySourceWire) -> Self {
5119        match wire {
5120            RegistrySourceWire::Url(url) => Self::Url(url),
5121            RegistrySourceWire::Path(path) => Self::Path(path.into()),
5122        }
5123    }
5124}
5125
5126#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
5127#[serde(rename_all = "kebab-case")]
5128struct DirectSource {
5129    subdirectory: Option<Box<Path>>,
5130}
5131
5132/// NOTE: Care should be taken when adding variants to this enum. Namely, new
5133/// variants should be added without changing the relative ordering of other
5134/// variants. Otherwise, this could cause the lockfile to have a different
5135/// canonical ordering of package entries.
5136#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
5137struct GitSource {
5138    precise: GitOid,
5139    subdirectory: Option<Box<Path>>,
5140    path: Option<PathBuf>,
5141    kind: GitSourceKind,
5142    lfs: GitLfs,
5143}
5144
5145/// An error that occurs when a source string could not be parsed.
5146#[derive(Clone, Debug, Eq, PartialEq)]
5147enum GitSourceError {
5148    InvalidSha,
5149    MissingSha,
5150}
5151
5152impl GitSource {
5153    /// Extracts a Git source reference from the query pairs and the hash
5154    /// fragment in the given URL.
5155    fn from_url(url: &Url) -> Result<Self, GitSourceError> {
5156        let mut kind = GitSourceKind::DefaultBranch;
5157        let mut subdirectory = None;
5158        let mut lfs = GitLfs::Disabled;
5159        let mut path = None;
5160        for (key, val) in url.query_pairs() {
5161            match &*key {
5162                "tag" => kind = GitSourceKind::Tag(val.into_owned()),
5163                "branch" => kind = GitSourceKind::Branch(val.into_owned()),
5164                "rev" => kind = GitSourceKind::Rev(val.into_owned()),
5165                "subdirectory" => subdirectory = Some(PortablePathBuf::from(val.as_ref()).into()),
5166                "lfs" => lfs = GitLfs::from(val.eq_ignore_ascii_case("true")),
5167                "path" => {
5168                    path = Some(PathBuf::from(Box::<Path>::from(PortablePathBuf::from(
5169                        val.as_ref(),
5170                    ))));
5171                }
5172                _ => {}
5173            }
5174        }
5175
5176        let precise = GitOid::from_str(url.fragment().ok_or(GitSourceError::MissingSha)?)
5177            .map_err(|_| GitSourceError::InvalidSha)?;
5178
5179        Ok(Self {
5180            precise,
5181            subdirectory,
5182            path,
5183            kind,
5184            lfs,
5185        })
5186    }
5187}
5188
5189#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, serde::Deserialize)]
5190#[serde(rename_all = "kebab-case")]
5191enum GitSourceKind {
5192    Tag(String),
5193    Branch(String),
5194    Rev(String),
5195    DefaultBranch,
5196}
5197
5198/// Inspired by: <https://discuss.python.org/t/lock-files-again-but-this-time-w-sdists/46593>
5199#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
5200#[serde(rename_all = "kebab-case")]
5201struct SourceDistMetadata {
5202    /// A hash of the source distribution.
5203    hash: Option<Hash>,
5204    /// The size of the source distribution in bytes.
5205    ///
5206    /// This is only present for source distributions that come from registries.
5207    size: Option<u64>,
5208    /// The upload time of the source distribution.
5209    #[serde(alias = "upload_time")]
5210    upload_time: Option<Timestamp>,
5211}
5212
5213/// A URL or file path where the source dist that was
5214/// locked against was found. The location does not need to exist in the
5215/// future, so this should be treated as only a hint to where to look
5216/// and/or recording where the source dist file originally came from.
5217#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
5218#[serde(from = "SourceDistWire")]
5219enum SourceDist {
5220    Url {
5221        url: UrlString,
5222        #[serde(flatten)]
5223        metadata: SourceDistMetadata,
5224    },
5225    Path {
5226        path: Box<Path>,
5227        #[serde(flatten)]
5228        metadata: SourceDistMetadata,
5229    },
5230    Metadata {
5231        #[serde(flatten)]
5232        metadata: SourceDistMetadata,
5233    },
5234}
5235
5236impl SourceDist {
5237    fn filename(&self) -> Option<Cow<'_, str>> {
5238        match self {
5239            Self::Metadata { .. } => None,
5240            Self::Url { url, .. } => url.filename().ok(),
5241            Self::Path { path, .. } => path.file_name().map(|filename| filename.to_string_lossy()),
5242        }
5243    }
5244
5245    fn url(&self) -> Option<&UrlString> {
5246        match self {
5247            Self::Metadata { .. } => None,
5248            Self::Url { url, .. } => Some(url),
5249            Self::Path { .. } => None,
5250        }
5251    }
5252
5253    fn hash(&self) -> Option<&Hash> {
5254        match self {
5255            Self::Metadata { metadata } => metadata.hash.as_ref(),
5256            Self::Url { metadata, .. } => metadata.hash.as_ref(),
5257            Self::Path { metadata, .. } => metadata.hash.as_ref(),
5258        }
5259    }
5260
5261    fn size(&self) -> Option<u64> {
5262        match self {
5263            Self::Metadata { metadata } => metadata.size,
5264            Self::Url { metadata, .. } => metadata.size,
5265            Self::Path { metadata, .. } => metadata.size,
5266        }
5267    }
5268
5269    fn upload_time(&self) -> Option<Timestamp> {
5270        match self {
5271            Self::Metadata { metadata } => metadata.upload_time,
5272            Self::Url { metadata, .. } => metadata.upload_time,
5273            Self::Path { metadata, .. } => metadata.upload_time,
5274        }
5275    }
5276}
5277
5278impl SourceDist {
5279    fn from_annotated_dist(
5280        id: &PackageId,
5281        annotated_dist: &AnnotatedDist,
5282        index_locations: &IndexLocations,
5283    ) -> Result<Option<Self>, LockError> {
5284        match annotated_dist.dist {
5285            // We pass empty installed packages for locking.
5286            ResolvedDist::Installed { .. } => unreachable!(),
5287            ResolvedDist::Installable { ref dist, .. } => Self::from_dist(
5288                id,
5289                dist,
5290                annotated_dist.hashes.as_slice(),
5291                annotated_dist.index(),
5292                index_locations,
5293            ),
5294        }
5295    }
5296
5297    fn from_dist(
5298        id: &PackageId,
5299        dist: &Dist,
5300        hashes: &[HashDigest],
5301        index: Option<&IndexUrl>,
5302        index_locations: &IndexLocations,
5303    ) -> Result<Option<Self>, LockError> {
5304        match *dist {
5305            Dist::Built(BuiltDist::Registry(ref built_dist)) => {
5306                let Some(sdist) = built_dist.sdist.as_ref() else {
5307                    return Ok(None);
5308                };
5309                Self::from_registry_dist(sdist, index, index_locations)
5310            }
5311            Dist::Built(_) => Ok(None),
5312            Dist::Source(ref source_dist) => {
5313                Self::from_source_dist(id, source_dist, hashes, index, index_locations)
5314            }
5315        }
5316    }
5317
5318    fn from_source_dist(
5319        id: &PackageId,
5320        source_dist: &uv_distribution_types::SourceDist,
5321        hashes: &[HashDigest],
5322        index: Option<&IndexUrl>,
5323        index_locations: &IndexLocations,
5324    ) -> Result<Option<Self>, LockError> {
5325        match *source_dist {
5326            uv_distribution_types::SourceDist::Registry(ref reg_dist) => {
5327                Self::from_registry_dist(reg_dist, index, index_locations)
5328            }
5329            uv_distribution_types::SourceDist::DirectUrl(_) => {
5330                Self::from_direct_dist(id, hashes).map(Some)
5331            }
5332            uv_distribution_types::SourceDist::Path(_) => {
5333                Self::from_path_dist(id, hashes).map(Some)
5334            }
5335            uv_distribution_types::SourceDist::GitPath(_) => {
5336                Self::from_git_path_dist(id, hashes).map(Some)
5337            }
5338            uv_distribution_types::SourceDist::GitDirectory(_)
5339            | uv_distribution_types::SourceDist::Directory(_) => Ok(None),
5340        }
5341    }
5342
5343    fn from_registry_dist(
5344        reg_dist: &RegistrySourceDist,
5345        index: Option<&IndexUrl>,
5346        index_locations: &IndexLocations,
5347    ) -> Result<Option<Self>, LockError> {
5348        // Reject distributions from registries that don't match the index URL, as can occur with
5349        // `--find-links`.
5350        if index.is_none_or(|index| *index != reg_dist.index) {
5351            return Ok(None);
5352        }
5353
5354        let hash = select_registry_hash(
5355            &reg_dist.file.hashes,
5356            &reg_dist.index,
5357            index_locations,
5358            reg_dist.file.filename.as_ref(),
5359        )?;
5360
5361        match &reg_dist.index {
5362            IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
5363                let url = normalize_file_location(&reg_dist.file.url)
5364                    .map_err(LockErrorKind::InvalidUrl)
5365                    .map_err(LockError::from)?;
5366                let size = reg_dist.file.size;
5367                let upload_time = reg_dist
5368                    .file
5369                    .upload_time_utc_ms
5370                    .map(Timestamp::from_millisecond)
5371                    .transpose()
5372                    .map_err(LockErrorKind::InvalidTimestamp)?;
5373                Ok(Some(Self::Url {
5374                    url,
5375                    metadata: SourceDistMetadata {
5376                        hash,
5377                        size,
5378                        upload_time,
5379                    },
5380                }))
5381            }
5382            IndexUrl::Path(path) => {
5383                let index_path = path
5384                    .to_file_path()
5385                    .map_err(|()| LockErrorKind::UrlToPath { url: path.to_url() })?;
5386                let url = reg_dist
5387                    .file
5388                    .url
5389                    .to_url()
5390                    .map_err(LockErrorKind::InvalidUrl)?;
5391
5392                if url.scheme() == "file" {
5393                    let reg_dist_path = url
5394                        .to_file_path()
5395                        .map_err(|()| LockErrorKind::UrlToPath { url })?;
5396                    let path =
5397                        try_relative_to_if(&reg_dist_path, index_path, !path.was_given_absolute())
5398                            .map_err(LockErrorKind::DistributionRelativePath)?
5399                            .into_boxed_path();
5400                    let size = reg_dist.file.size;
5401                    let upload_time = reg_dist
5402                        .file
5403                        .upload_time_utc_ms
5404                        .map(Timestamp::from_millisecond)
5405                        .transpose()
5406                        .map_err(LockErrorKind::InvalidTimestamp)?;
5407                    Ok(Some(Self::Path {
5408                        path,
5409                        metadata: SourceDistMetadata {
5410                            hash,
5411                            size,
5412                            upload_time,
5413                        },
5414                    }))
5415                } else {
5416                    let url = normalize_file_location(&reg_dist.file.url)
5417                        .map_err(LockErrorKind::InvalidUrl)
5418                        .map_err(LockError::from)?;
5419                    let size = reg_dist.file.size;
5420                    let upload_time = reg_dist
5421                        .file
5422                        .upload_time_utc_ms
5423                        .map(Timestamp::from_millisecond)
5424                        .transpose()
5425                        .map_err(LockErrorKind::InvalidTimestamp)?;
5426                    Ok(Some(Self::Url {
5427                        url,
5428                        metadata: SourceDistMetadata {
5429                            hash,
5430                            size,
5431                            upload_time,
5432                        },
5433                    }))
5434                }
5435            }
5436        }
5437    }
5438
5439    fn from_direct_dist(id: &PackageId, hashes: &[HashDigest]) -> Result<Self, LockError> {
5440        let Some(hash) = hashes.iter().max().cloned().map(Hash::from) else {
5441            let kind = LockErrorKind::Hash {
5442                id: id.clone(),
5443                artifact_type: "direct URL source distribution",
5444                expected: true,
5445            };
5446            return Err(kind.into());
5447        };
5448        Ok(Self::Metadata {
5449            metadata: SourceDistMetadata {
5450                hash: Some(hash),
5451                size: None,
5452                upload_time: None,
5453            },
5454        })
5455    }
5456
5457    fn from_path_dist(id: &PackageId, hashes: &[HashDigest]) -> Result<Self, LockError> {
5458        let Some(hash) = hashes.iter().max().cloned().map(Hash::from) else {
5459            let kind = LockErrorKind::Hash {
5460                id: id.clone(),
5461                artifact_type: "path source distribution",
5462                expected: true,
5463            };
5464            return Err(kind.into());
5465        };
5466        Ok(Self::Metadata {
5467            metadata: SourceDistMetadata {
5468                hash: Some(hash),
5469                size: None,
5470                upload_time: None,
5471            },
5472        })
5473    }
5474
5475    fn from_git_path_dist(id: &PackageId, hashes: &[HashDigest]) -> Result<Self, LockError> {
5476        let Some(hash) = hashes.iter().max().cloned().map(Hash::from) else {
5477            let kind = LockErrorKind::Hash {
5478                id: id.clone(),
5479                artifact_type: "Git archive source distribution",
5480                expected: true,
5481            };
5482            return Err(kind.into());
5483        };
5484        Ok(Self::Metadata {
5485            metadata: SourceDistMetadata {
5486                hash: Some(hash),
5487                size: None,
5488                upload_time: None,
5489            },
5490        })
5491    }
5492}
5493
5494#[derive(Clone, Debug, serde::Deserialize)]
5495#[serde(untagged, rename_all = "kebab-case")]
5496enum SourceDistWire {
5497    Url {
5498        url: UrlString,
5499        #[serde(flatten)]
5500        metadata: SourceDistMetadata,
5501    },
5502    Path {
5503        path: PortablePathBuf,
5504        #[serde(flatten)]
5505        metadata: SourceDistMetadata,
5506    },
5507    Metadata {
5508        #[serde(flatten)]
5509        metadata: SourceDistMetadata,
5510    },
5511}
5512
5513impl From<SourceDistWire> for SourceDist {
5514    fn from(wire: SourceDistWire) -> Self {
5515        match wire {
5516            SourceDistWire::Url { url, metadata } => Self::Url { url, metadata },
5517            SourceDistWire::Path { path, metadata } => Self::Path {
5518                path: path.into(),
5519                metadata,
5520            },
5521            SourceDistWire::Metadata { metadata } => Self::Metadata { metadata },
5522        }
5523    }
5524}
5525
5526impl From<GitReference> for GitSourceKind {
5527    fn from(value: GitReference) -> Self {
5528        match value {
5529            GitReference::Branch(branch) => Self::Branch(branch),
5530            GitReference::Tag(tag) => Self::Tag(tag),
5531            GitReference::BranchOrTag(rev) => Self::Rev(rev),
5532            GitReference::BranchOrTagOrCommit(rev) => Self::Rev(rev),
5533            GitReference::NamedRef(rev) => Self::Rev(rev),
5534            GitReference::DefaultBranch => Self::DefaultBranch,
5535        }
5536    }
5537}
5538
5539impl From<GitSourceKind> for GitReference {
5540    fn from(value: GitSourceKind) -> Self {
5541        match value {
5542            GitSourceKind::Branch(branch) => Self::Branch(branch),
5543            GitSourceKind::Tag(tag) => Self::Tag(tag),
5544            GitSourceKind::Rev(rev) => Self::from_rev(rev),
5545            GitSourceKind::DefaultBranch => Self::DefaultBranch,
5546        }
5547    }
5548}
5549
5550/// Construct the lockfile-compatible [`DisplaySafeUrl`] for a [`GitUrl`].
5551fn locked_git_url(
5552    git: &GitUrl,
5553    subdirectory: Option<&Path>,
5554    path: Option<&Path>,
5555) -> DisplaySafeUrl {
5556    let mut url = git.url().clone();
5557
5558    // Remove the credentials.
5559    url.remove_credentials();
5560
5561    // Clear out any existing state.
5562    url.set_fragment(None);
5563    url.set_query(None);
5564
5565    // Put the subdirectory in the query.
5566    if let Some(subdirectory) = subdirectory
5567        .map(PortablePath::from)
5568        .as_ref()
5569        .map(PortablePath::to_string)
5570    {
5571        url.query_pairs_mut()
5572            .append_pair("subdirectory", &subdirectory);
5573    }
5574
5575    // Put the path in the query.
5576    if let Some(path) = path
5577        .map(PortablePath::from)
5578        .as_ref()
5579        .map(PortablePath::to_string)
5580    {
5581        url.query_pairs_mut().append_pair("path", &path);
5582    }
5583
5584    // Put lfs=true in the package source git url only when explicitly enabled.
5585    if git.lfs().enabled() {
5586        url.query_pairs_mut().append_pair("lfs", "true");
5587    }
5588
5589    // Put the requested reference in the query.
5590    match git.reference() {
5591        GitReference::Branch(branch) => {
5592            url.query_pairs_mut().append_pair("branch", branch.as_str());
5593        }
5594        GitReference::Tag(tag) => {
5595            url.query_pairs_mut().append_pair("tag", tag.as_str());
5596        }
5597        GitReference::BranchOrTag(rev)
5598        | GitReference::BranchOrTagOrCommit(rev)
5599        | GitReference::NamedRef(rev) => {
5600            url.query_pairs_mut().append_pair("rev", rev.as_str());
5601        }
5602        GitReference::DefaultBranch => {}
5603    }
5604
5605    // Put the precise commit in the fragment.
5606    url.set_fragment(git.precise().as_ref().map(GitOid::to_string).as_deref());
5607
5608    url
5609}
5610
5611#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
5612struct ZstdWheel {
5613    hash: Option<Hash>,
5614    size: Option<u64>,
5615}
5616
5617/// Inspired by: <https://discuss.python.org/t/lock-files-again-but-this-time-w-sdists/46593>
5618#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
5619#[serde(try_from = "WheelWire")]
5620struct Wheel {
5621    /// A URL or file path (via `file://`) where the wheel that was locked
5622    /// against was found. The location does not need to exist in the future,
5623    /// so this should be treated as only a hint to where to look and/or
5624    /// recording where the wheel file originally came from.
5625    url: WheelWireSource,
5626    /// A hash of the built distribution.
5627    ///
5628    /// This is only present for wheels that come from registries and direct
5629    /// URLs. Wheels from git or path dependencies do not have hashes
5630    /// associated with them.
5631    hash: Option<Hash>,
5632    /// The size of the built distribution in bytes.
5633    ///
5634    /// This is only present for wheels that come from registries.
5635    size: Option<u64>,
5636    /// The upload time of the built distribution.
5637    ///
5638    /// This is only present for wheels that come from registries.
5639    upload_time: Option<Timestamp>,
5640    /// The filename of the wheel.
5641    ///
5642    /// This isn't part of the wire format since it's redundant with the
5643    /// URL. But we do use it for various things, and thus compute it at
5644    /// deserialization time. Not being able to extract a wheel filename from a
5645    /// wheel URL is thus a deserialization error.
5646    filename: WheelFilename,
5647    /// The zstandard-compressed wheel metadata, if any.
5648    zstd: Option<ZstdWheel>,
5649}
5650
5651impl Wheel {
5652    fn from_annotated_dist(
5653        annotated_dist: &AnnotatedDist,
5654        index_locations: &IndexLocations,
5655    ) -> Result<Vec<Self>, LockError> {
5656        match annotated_dist.dist {
5657            // We pass empty installed packages for locking.
5658            ResolvedDist::Installed { .. } => unreachable!(),
5659            ResolvedDist::Installable { ref dist, .. } => Self::from_dist(
5660                dist,
5661                annotated_dist.hashes.as_slice(),
5662                annotated_dist.index(),
5663                index_locations,
5664            ),
5665        }
5666    }
5667
5668    fn from_dist(
5669        dist: &Dist,
5670        hashes: &[HashDigest],
5671        index: Option<&IndexUrl>,
5672        index_locations: &IndexLocations,
5673    ) -> Result<Vec<Self>, LockError> {
5674        match *dist {
5675            Dist::Built(ref built_dist) => {
5676                Self::from_built_dist(built_dist, hashes, index, index_locations)
5677            }
5678            Dist::Source(uv_distribution_types::SourceDist::Registry(ref source_dist)) => {
5679                source_dist
5680                    .wheels
5681                    .iter()
5682                    .filter(|wheel| {
5683                        // Reject distributions from registries that don't match the index URL, as can occur with
5684                        // `--find-links`.
5685                        index.is_some_and(|index| *index == wheel.index)
5686                    })
5687                    .map(|wheel| Self::from_registry_wheel(wheel, index_locations))
5688                    .collect()
5689            }
5690            Dist::Source(_) => Ok(vec![]),
5691        }
5692    }
5693
5694    fn from_built_dist(
5695        built_dist: &BuiltDist,
5696        hashes: &[HashDigest],
5697        index: Option<&IndexUrl>,
5698        index_locations: &IndexLocations,
5699    ) -> Result<Vec<Self>, LockError> {
5700        match *built_dist {
5701            BuiltDist::Registry(ref reg_dist) => {
5702                Self::from_registry_dist(reg_dist, index, index_locations)
5703            }
5704            BuiltDist::DirectUrl(ref direct_dist) => {
5705                Ok(vec![Self::from_direct_dist(direct_dist, hashes)])
5706            }
5707            BuiltDist::Path(ref path_dist) => Ok(vec![Self::from_path_dist(path_dist, hashes)]),
5708            BuiltDist::GitPath(ref git_dist) => {
5709                Ok(vec![Self::from_git_path_dist(git_dist, hashes)])
5710            }
5711        }
5712    }
5713
5714    fn from_registry_dist(
5715        reg_dist: &RegistryBuiltDist,
5716        index: Option<&IndexUrl>,
5717        index_locations: &IndexLocations,
5718    ) -> Result<Vec<Self>, LockError> {
5719        reg_dist
5720            .wheels
5721            .iter()
5722            .filter(|wheel| {
5723                // Reject distributions from registries that don't match the index URL, as can occur with
5724                // `--find-links`.
5725                index.is_some_and(|index| *index == wheel.index)
5726            })
5727            .map(|wheel| Self::from_registry_wheel(wheel, index_locations))
5728            .collect()
5729    }
5730
5731    fn from_registry_wheel(
5732        wheel: &RegistryBuiltWheel,
5733        index_locations: &IndexLocations,
5734    ) -> Result<Self, LockError> {
5735        let url = match &wheel.index {
5736            IndexUrl::Pypi(_) | IndexUrl::Url(_) => {
5737                let url = normalize_file_location(&wheel.file.url)
5738                    .map_err(LockErrorKind::InvalidUrl)
5739                    .map_err(LockError::from)?;
5740                WheelWireSource::Url { url }
5741            }
5742            IndexUrl::Path(path) => {
5743                let index_path = path
5744                    .to_file_path()
5745                    .map_err(|()| LockErrorKind::UrlToPath { url: path.to_url() })?;
5746                let wheel_url = wheel.file.url.to_url().map_err(LockErrorKind::InvalidUrl)?;
5747
5748                if wheel_url.scheme() == "file" {
5749                    let wheel_path = wheel_url
5750                        .to_file_path()
5751                        .map_err(|()| LockErrorKind::UrlToPath { url: wheel_url })?;
5752                    let path =
5753                        try_relative_to_if(&wheel_path, index_path, !path.was_given_absolute())
5754                            .map_err(LockErrorKind::DistributionRelativePath)?
5755                            .into_boxed_path();
5756                    WheelWireSource::Path { path }
5757                } else {
5758                    let url = normalize_file_location(&wheel.file.url)
5759                        .map_err(LockErrorKind::InvalidUrl)
5760                        .map_err(LockError::from)?;
5761                    WheelWireSource::Url { url }
5762                }
5763            }
5764        };
5765        let filename = wheel.filename.clone();
5766        let hash = select_registry_hash(
5767            &wheel.file.hashes,
5768            &wheel.index,
5769            index_locations,
5770            wheel.file.filename.as_ref(),
5771        )?;
5772        let size = wheel.file.size;
5773        let upload_time = wheel
5774            .file
5775            .upload_time_utc_ms
5776            .map(Timestamp::from_millisecond)
5777            .transpose()
5778            .map_err(LockErrorKind::InvalidTimestamp)?;
5779        let zstd = if let Some(zstd) = wheel.file.zstd.as_ref() {
5780            Some(ZstdWheel {
5781                hash: select_registry_hash(
5782                    &zstd.hashes,
5783                    &wheel.index,
5784                    index_locations,
5785                    wheel.file.filename.as_ref(),
5786                )?,
5787                size: zstd.size,
5788            })
5789        } else {
5790            None
5791        };
5792        Ok(Self {
5793            url,
5794            hash,
5795            size,
5796            upload_time,
5797            filename,
5798            zstd,
5799        })
5800    }
5801
5802    fn from_direct_dist(direct_dist: &DirectUrlBuiltDist, hashes: &[HashDigest]) -> Self {
5803        Self {
5804            url: WheelWireSource::Url {
5805                url: normalize_url(direct_dist.url.to_url()),
5806            },
5807            hash: hashes.iter().max().cloned().map(Hash::from),
5808            size: None,
5809            upload_time: None,
5810            filename: direct_dist.filename.clone(),
5811            zstd: None,
5812        }
5813    }
5814
5815    fn from_path_dist(path_dist: &PathBuiltDist, hashes: &[HashDigest]) -> Self {
5816        Self {
5817            url: WheelWireSource::Filename {
5818                filename: path_dist.filename.clone(),
5819            },
5820            hash: hashes.iter().max().cloned().map(Hash::from),
5821            size: None,
5822            upload_time: None,
5823            filename: path_dist.filename.clone(),
5824            zstd: None,
5825        }
5826    }
5827
5828    fn from_git_path_dist(path_dist: &GitPathBuiltDist, hashes: &[HashDigest]) -> Self {
5829        Self {
5830            url: WheelWireSource::Filename {
5831                filename: path_dist.filename.clone(),
5832            },
5833            hash: hashes.iter().max().cloned().map(Hash::from),
5834            size: None,
5835            upload_time: None,
5836            filename: path_dist.filename.clone(),
5837            zstd: None,
5838        }
5839    }
5840
5841    fn to_registry_wheel(
5842        &self,
5843        source: &RegistrySource,
5844        root: &Path,
5845    ) -> Result<RegistryBuiltWheel, LockError> {
5846        let filename: WheelFilename = self.filename.clone();
5847
5848        match source {
5849            RegistrySource::Url(url) => {
5850                let file_location = match &self.url {
5851                    WheelWireSource::Url { url: file_url } => {
5852                        FileLocation::AbsoluteUrl(file_url.clone())
5853                    }
5854                    WheelWireSource::Path { .. } | WheelWireSource::Filename { .. } => {
5855                        return Err(LockErrorKind::MissingUrl {
5856                            name: filename.name,
5857                            version: filename.version,
5858                        }
5859                        .into());
5860                    }
5861                };
5862                let file = Box::new(uv_distribution_types::File {
5863                    dist_info_metadata: false,
5864                    filename: SmallString::from(filename.to_string()),
5865                    hashes: self.hash.iter().map(|h| h.0.clone()).collect(),
5866                    requires_python: None,
5867                    size: self.size,
5868                    upload_time_utc_ms: self.upload_time.map(Timestamp::as_millisecond),
5869                    url: file_location,
5870                    yanked: None,
5871                    zstd: self
5872                        .zstd
5873                        .as_ref()
5874                        .map(|zstd| uv_distribution_types::Zstd {
5875                            hashes: zstd.hash.iter().map(|h| h.0.clone()).collect(),
5876                            size: zstd.size,
5877                        })
5878                        .map(Box::new),
5879                });
5880                let index = IndexUrl::from(VerbatimUrl::from_url(
5881                    url.to_url().map_err(LockErrorKind::InvalidUrl)?,
5882                ));
5883                Ok(RegistryBuiltWheel {
5884                    filename,
5885                    file,
5886                    index,
5887                })
5888            }
5889            RegistrySource::Path(index_path) => {
5890                let file_location = match &self.url {
5891                    WheelWireSource::Url { url: file_url } => {
5892                        FileLocation::AbsoluteUrl(file_url.clone())
5893                    }
5894                    WheelWireSource::Path { path: file_path } => {
5895                        let file_path = root.join(index_path).join(file_path);
5896                        let file_url =
5897                            DisplaySafeUrl::from_file_path(&file_path).map_err(|()| {
5898                                LockErrorKind::PathToUrl {
5899                                    path: file_path.into_boxed_path(),
5900                                }
5901                            })?;
5902                        FileLocation::AbsoluteUrl(UrlString::from(file_url))
5903                    }
5904                    WheelWireSource::Filename { .. } => {
5905                        return Err(LockErrorKind::MissingPath {
5906                            name: filename.name,
5907                            version: filename.version,
5908                        }
5909                        .into());
5910                    }
5911                };
5912                let file = Box::new(uv_distribution_types::File {
5913                    dist_info_metadata: false,
5914                    filename: SmallString::from(filename.to_string()),
5915                    hashes: self.hash.iter().map(|h| h.0.clone()).collect(),
5916                    requires_python: None,
5917                    size: self.size,
5918                    upload_time_utc_ms: self.upload_time.map(Timestamp::as_millisecond),
5919                    url: file_location,
5920                    yanked: None,
5921                    zstd: self
5922                        .zstd
5923                        .as_ref()
5924                        .map(|zstd| uv_distribution_types::Zstd {
5925                            hashes: zstd.hash.iter().map(|h| h.0.clone()).collect(),
5926                            size: zstd.size,
5927                        })
5928                        .map(Box::new),
5929                });
5930                let index = IndexUrl::from(
5931                    VerbatimUrl::from_absolute_path(root.join(index_path))
5932                        .map_err(LockErrorKind::RegistryVerbatimUrl)?,
5933                );
5934                Ok(RegistryBuiltWheel {
5935                    filename,
5936                    file,
5937                    index,
5938                })
5939            }
5940        }
5941    }
5942}
5943
5944#[derive(Clone, Debug, serde::Deserialize)]
5945#[serde(rename_all = "kebab-case")]
5946struct WheelWire {
5947    #[serde(flatten)]
5948    url: WheelWireSource,
5949    /// A hash of the built distribution.
5950    ///
5951    /// This is only present for wheels that come from registries and direct
5952    /// URLs. Wheels from git or path dependencies do not have hashes
5953    /// associated with them.
5954    hash: Option<Hash>,
5955    /// The size of the built distribution in bytes.
5956    ///
5957    /// This is only present for wheels that come from registries.
5958    size: Option<u64>,
5959    /// The upload time of the built distribution.
5960    ///
5961    /// This is only present for wheels that come from registries.
5962    #[serde(alias = "upload_time")]
5963    upload_time: Option<Timestamp>,
5964    /// The zstandard-compressed wheel metadata, if any.
5965    #[serde(alias = "zstd")]
5966    zstd: Option<ZstdWheel>,
5967}
5968
5969#[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)]
5970#[serde(untagged, rename_all = "kebab-case")]
5971enum WheelWireSource {
5972    /// Used for all wheels that come from remote sources.
5973    Url {
5974        /// A URL where the wheel that was locked against was found. The location
5975        /// does not need to exist in the future, so this should be treated as
5976        /// only a hint to where to look and/or recording where the wheel file
5977        /// originally came from.
5978        url: UrlString,
5979    },
5980    /// Used for wheels that come from local registries (like `--find-links`).
5981    Path {
5982        /// The path to the wheel, relative to the index.
5983        path: Box<Path>,
5984    },
5985    /// Used for path wheels.
5986    ///
5987    /// We only store the filename for path wheel, since we can't store a relative path in the url
5988    Filename {
5989        /// We duplicate the filename since a lot of code relies on having the filename on the
5990        /// wheel entry.
5991        filename: WheelFilename,
5992    },
5993}
5994
5995impl TryFrom<WheelWire> for Wheel {
5996    type Error = String;
5997
5998    fn try_from(wire: WheelWire) -> Result<Self, String> {
5999        let filename = match &wire.url {
6000            WheelWireSource::Url { url } => {
6001                let filename = url.filename().map_err(|err| err.to_string())?;
6002                filename.parse::<WheelFilename>().map_err(|err| {
6003                    format!("failed to parse `{filename}` as wheel filename: {err}")
6004                })?
6005            }
6006            WheelWireSource::Path { path } => {
6007                let filename = path
6008                    .file_name()
6009                    .and_then(|file_name| file_name.to_str())
6010                    .ok_or_else(|| {
6011                        format!("path `{}` has no filename component", path.display())
6012                    })?;
6013                filename.parse::<WheelFilename>().map_err(|err| {
6014                    format!("failed to parse `{filename}` as wheel filename: {err}")
6015                })?
6016            }
6017            WheelWireSource::Filename { filename } => filename.clone(),
6018        };
6019
6020        Ok(Self {
6021            url: wire.url,
6022            hash: wire.hash,
6023            size: wire.size,
6024            upload_time: wire.upload_time,
6025            zstd: wire.zstd,
6026            filename,
6027        })
6028    }
6029}
6030
6031/// A single dependency of a package in a lockfile.
6032#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
6033pub struct Dependency {
6034    package_id: PackageId,
6035    extra: BTreeSet<ExtraName>,
6036    /// A marker simplified from the PEP 508 marker in `complexified_marker`
6037    /// by assuming `requires-python` and the PEP 508 portion of the parent package's reachability
6038    /// marker are satisfied. The parent's conflict predicates are retained for compatibility with
6039    /// older lockfile readers. So if
6040    /// `requires-python = '>=3.8'`, then
6041    /// `python_version >= '3.8' and python_version < '3.12'`
6042    /// gets simplified to `python_version < '3.12'`.
6043    ///
6044    /// Generally speaking, this marker should not be exposed to anything outside this module
6045    /// unless it's for a specialized use case. But specifically, it should never be used to
6046    /// evaluate against a marker environment or for disjointness checks or any other kind of
6047    /// marker algebra. It is only meaningful while traversing from its parent package.
6048    ///
6049    /// It exists because there are some cases where we do actually
6050    /// want to compare markers in their "simplified" form. For
6051    /// example, when collapsing the extras on duplicate dependencies.
6052    /// Even if a dependency has different complexified markers,
6053    /// they might have identical markers once simplified. And since
6054    /// `requires-python` applies to the entire lock file, it's
6055    /// acceptable to do comparisons on the simplified form.
6056    simplified_marker: SimplifiedMarkerTree,
6057    /// The "complexified" marker is independent of `requires-python`, but remains contextual to
6058    /// the PEP 508 reachability of its parent package. It can be evaluated while traversing
6059    /// dependencies from that package.
6060    complexified_marker: UniversalMarker,
6061}
6062
6063impl Dependency {
6064    fn new(
6065        requires_python: &RequiresPython,
6066        package_id: PackageId,
6067        extra: BTreeSet<ExtraName>,
6068        simplified_marker: SimplifiedMarkerTree,
6069    ) -> Self {
6070        let complexified_marker = simplified_marker.into_marker(requires_python);
6071        Self {
6072            package_id,
6073            extra,
6074            simplified_marker,
6075            complexified_marker: UniversalMarker::from_combined(complexified_marker),
6076        }
6077    }
6078
6079    /// Returns the package name of this dependency.
6080    pub fn package_name(&self) -> &PackageName {
6081        &self.package_id.name
6082    }
6083
6084    /// Returns the extras specified on this dependency.
6085    pub fn extra(&self) -> &BTreeSet<ExtraName> {
6086        &self.extra
6087    }
6088}
6089
6090impl Display for Dependency {
6091    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
6092        match (self.extra.is_empty(), self.package_id.version.as_ref()) {
6093            (true, Some(version)) => write!(f, "{}=={}", self.package_id.name, version),
6094            (true, None) => write!(f, "{}", self.package_id.name),
6095            (false, Some(version)) => write!(
6096                f,
6097                "{}[{}]=={}",
6098                self.package_id.name,
6099                self.extra.iter().join(","),
6100                version
6101            ),
6102            (false, None) => write!(
6103                f,
6104                "{}[{}]",
6105                self.package_id.name,
6106                self.extra.iter().join(",")
6107            ),
6108        }
6109    }
6110}
6111
6112/// A single dependency of a package in a lockfile.
6113#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, serde::Deserialize)]
6114#[serde(rename_all = "kebab-case")]
6115struct DependencyWire {
6116    #[serde(flatten)]
6117    package_id: PackageIdForDependency,
6118    #[serde(default)]
6119    extra: BTreeSet<ExtraName>,
6120    #[serde(default)]
6121    marker: SimplifiedMarkerTree,
6122}
6123
6124impl DependencyWire {
6125    fn unwire(
6126        self,
6127        requires_python: &RequiresPython,
6128        environment: SimplifiedMarkerTree,
6129        default: UniversalMarker,
6130        unambiguous_package_ids: &FxHashMap<PackageName, PackageId>,
6131    ) -> Result<Dependency, LockError> {
6132        let (simplified_marker, complexified_marker) =
6133            if self.marker.as_simplified_marker_tree().is_true() {
6134                (environment, default)
6135            } else {
6136                let mut simplified_marker = self.marker;
6137                simplified_marker.and(environment);
6138                let complexified_marker =
6139                    UniversalMarker::from_combined(simplified_marker.into_marker(requires_python));
6140                (simplified_marker, complexified_marker)
6141            };
6142        Ok(Dependency {
6143            package_id: self.package_id.unwire(unambiguous_package_ids)?,
6144            extra: self.extra,
6145            simplified_marker,
6146            complexified_marker,
6147        })
6148    }
6149}
6150
6151/// A single hash for a distribution artifact in a lockfile.
6152///
6153/// A hash is encoded as a single TOML string in the format
6154/// `{algorithm}:{digest}`.
6155#[derive(Clone, Debug, PartialEq, Eq)]
6156struct Hash(HashDigest);
6157
6158impl From<HashDigest> for Hash {
6159    fn from(hd: HashDigest) -> Self {
6160        Self(hd)
6161    }
6162}
6163
6164/// Select the configured hash algorithm for a registry artifact, preserving the default hash
6165/// selection when the index has no requirement.
6166///
6167/// Returns an error if the required algorithm is not advertised.
6168fn select_registry_hash(
6169    hashes: &HashDigests,
6170    index: &IndexUrl,
6171    index_locations: &IndexLocations,
6172    filename: &str,
6173) -> Result<Option<Hash>, LockError> {
6174    let Some(algorithm) = index_locations.hash_algorithm_for(index) else {
6175        return Ok(hashes.iter().max().cloned().map(Hash::from));
6176    };
6177    warn_index_hash_algorithm_preview();
6178
6179    hashes
6180        .iter()
6181        .find(|hash| hash.algorithm == algorithm)
6182        .cloned()
6183        .map(Hash::from)
6184        .map(Some)
6185        .ok_or_else(|| {
6186            LockErrorKind::MissingHashAlgorithm {
6187                index: index.clone(),
6188                filename: filename.to_string(),
6189                algorithm,
6190            }
6191            .into()
6192        })
6193}
6194
6195/// Warn if an index-specific hash algorithm is used without its preview feature enabled.
6196fn warn_index_hash_algorithm_preview() {
6197    if !uv_preview::is_enabled(PreviewFeature::IndexHashAlgorithm) {
6198        warn_user_once!(
6199            "Setting `hash-algorithm` on configured indexes is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.",
6200            PreviewFeature::IndexHashAlgorithm
6201        );
6202    }
6203}
6204
6205impl FromStr for Hash {
6206    type Err = HashParseError;
6207
6208    fn from_str(s: &str) -> Result<Self, HashParseError> {
6209        let (algorithm, digest) = s.split_once(':').ok_or(HashParseError(
6210            "expected '{algorithm}:{digest}', but found no ':' in hash digest",
6211        ))?;
6212        let algorithm = algorithm
6213            .parse()
6214            .map_err(|_| HashParseError("unrecognized hash algorithm"))?;
6215        Ok(Self(HashDigest {
6216            algorithm,
6217            digest: digest.into(),
6218        }))
6219    }
6220}
6221
6222impl Display for Hash {
6223    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
6224        write!(f, "{}:{}", self.0.algorithm, self.0.digest)
6225    }
6226}
6227
6228impl<'de> serde::Deserialize<'de> for Hash {
6229    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
6230    where
6231        D: serde::de::Deserializer<'de>,
6232    {
6233        struct Visitor;
6234
6235        impl serde::de::Visitor<'_> for Visitor {
6236            type Value = Hash;
6237
6238            fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
6239                f.write_str("a string")
6240            }
6241
6242            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
6243                Hash::from_str(v).map_err(serde::de::Error::custom)
6244            }
6245        }
6246
6247        deserializer.deserialize_str(Visitor)
6248    }
6249}
6250
6251impl From<Hash> for Hashes {
6252    fn from(value: Hash) -> Self {
6253        match value.0.algorithm {
6254            HashAlgorithm::Md5 => Self {
6255                md5: Some(value.0.digest),
6256                sha256: None,
6257                sha384: None,
6258                sha512: None,
6259                blake2b: None,
6260            },
6261            HashAlgorithm::Sha256 => Self {
6262                md5: None,
6263                sha256: Some(value.0.digest),
6264                sha384: None,
6265                sha512: None,
6266                blake2b: None,
6267            },
6268            HashAlgorithm::Sha384 => Self {
6269                md5: None,
6270                sha256: None,
6271                sha384: Some(value.0.digest),
6272                sha512: None,
6273                blake2b: None,
6274            },
6275            HashAlgorithm::Sha512 => Self {
6276                md5: None,
6277                sha256: None,
6278                sha384: None,
6279                sha512: Some(value.0.digest),
6280                blake2b: None,
6281            },
6282            HashAlgorithm::Blake2b => Self {
6283                md5: None,
6284                sha256: None,
6285                sha384: None,
6286                sha512: None,
6287                blake2b: Some(value.0.digest),
6288            },
6289        }
6290    }
6291}
6292
6293/// Convert a [`FileLocation`] into a normalized [`UrlString`].
6294fn normalize_file_location(location: &FileLocation) -> Result<UrlString, ToUrlError> {
6295    match location {
6296        FileLocation::AbsoluteUrl(absolute) => Ok(absolute.without_fragment().into_owned()),
6297        FileLocation::RelativeUrl(_, _) => Ok(normalize_url(location.to_url()?)),
6298    }
6299}
6300
6301/// Convert a [`DisplaySafeUrl`] into a normalized [`UrlString`] by removing the fragment.
6302fn normalize_url(mut url: DisplaySafeUrl) -> UrlString {
6303    url.set_fragment(None);
6304    UrlString::from(url)
6305}
6306
6307/// Normalize a [`Requirement`], which could come from a lockfile, a `pyproject.toml`, etc.
6308///
6309/// Performs the following steps:
6310///
6311/// 1. Removes any sensitive credentials.
6312/// 2. Ensures that the lock and install paths are appropriately framed with respect to the
6313///    current [`Workspace`].
6314/// 3. Removes the `origin` field, which is only used in `requirements.txt`.
6315/// 4. Simplifies the markers using the provided [`RequiresPython`] instance.
6316fn normalize_requirement(
6317    mut requirement: Requirement,
6318    root: &Path,
6319    requires_python: &RequiresPython,
6320) -> Result<Requirement, LockError> {
6321    // Sort the extras and groups for consistency.
6322    requirement.extras.sort();
6323    requirement.groups.sort();
6324
6325    // Normalize the requirement source.
6326    match requirement.source {
6327        RequirementSource::GitDirectory {
6328            git,
6329            subdirectory,
6330            url: _,
6331        } => {
6332            // Reconstruct the Git URL.
6333            let git = {
6334                let mut repository = git.url().clone();
6335
6336                // Remove the credentials.
6337                repository.remove_credentials();
6338
6339                // Remove the fragment and query from the URL; they're already present in the source.
6340                repository.set_fragment(None);
6341                repository.set_query(None);
6342
6343                GitUrl::from_fields(
6344                    repository,
6345                    git.reference().clone(),
6346                    git.precise(),
6347                    git.lfs(),
6348                )?
6349            };
6350
6351            // Reconstruct the PEP 508 URL from the underlying data.
6352            let url = DisplaySafeUrl::from(ParsedGitDirectoryUrl {
6353                url: git.clone(),
6354                subdirectory: subdirectory.clone(),
6355            });
6356
6357            Ok(Requirement {
6358                name: requirement.name,
6359                extras: requirement.extras,
6360                groups: requirement.groups,
6361                marker: requires_python.simplify_markers(requirement.marker),
6362                source: RequirementSource::GitDirectory {
6363                    git,
6364                    subdirectory,
6365                    url: VerbatimUrl::from_url(url),
6366                },
6367                origin: None,
6368            })
6369        }
6370        RequirementSource::GitPath {
6371            git,
6372            install_path,
6373            ext,
6374            url: _,
6375        } => {
6376            // Reconstruct the Git URL.
6377            let git = {
6378                let mut repository = git.url().clone();
6379
6380                // Remove the credentials.
6381                repository.remove_credentials();
6382
6383                // Remove the fragment and query from the URL; they're already present in the source.
6384                repository.set_fragment(None);
6385                repository.set_query(None);
6386
6387                GitUrl::from_fields(
6388                    repository,
6389                    git.reference().clone(),
6390                    git.precise(),
6391                    git.lfs(),
6392                )?
6393            };
6394
6395            // Reconstruct the PEP 508 URL from the underlying data.
6396            let url = DisplaySafeUrl::from(ParsedGitPathUrl {
6397                url: git.clone(),
6398                install_path: install_path.clone(),
6399                ext,
6400            });
6401
6402            Ok(Requirement {
6403                name: requirement.name,
6404                extras: requirement.extras,
6405                groups: requirement.groups,
6406                marker: requires_python.simplify_markers(requirement.marker),
6407                source: RequirementSource::GitPath {
6408                    git,
6409                    install_path,
6410                    ext,
6411                    url: VerbatimUrl::from_url(url),
6412                },
6413                origin: None,
6414            })
6415        }
6416        RequirementSource::Path {
6417            install_path,
6418            ext,
6419            url: _,
6420        } => {
6421            let path = root.join(&install_path);
6422            let install_path = normalize_path(path).into_owned().into_boxed_path();
6423            let url = VerbatimUrl::from_normalized_path(&install_path)
6424                .map_err(LockErrorKind::RequirementVerbatimUrl)?;
6425
6426            Ok(Requirement {
6427                name: requirement.name,
6428                extras: requirement.extras,
6429                groups: requirement.groups,
6430                marker: requires_python.simplify_markers(requirement.marker),
6431                source: RequirementSource::Path {
6432                    install_path,
6433                    ext,
6434                    url,
6435                },
6436                origin: None,
6437            })
6438        }
6439        RequirementSource::Directory {
6440            install_path,
6441            editable,
6442            r#virtual,
6443            url: _,
6444        } => {
6445            let path = root.join(&install_path);
6446            let install_path = normalize_path(path).into_owned().into_boxed_path();
6447            let url = VerbatimUrl::from_normalized_path(&install_path)
6448                .map_err(LockErrorKind::RequirementVerbatimUrl)?;
6449
6450            Ok(Requirement {
6451                name: requirement.name,
6452                extras: requirement.extras,
6453                groups: requirement.groups,
6454                marker: requires_python.simplify_markers(requirement.marker),
6455                source: RequirementSource::Directory {
6456                    install_path,
6457                    editable: Some(editable.unwrap_or(false)),
6458                    r#virtual: Some(r#virtual.unwrap_or(false)),
6459                    url,
6460                },
6461                origin: None,
6462            })
6463        }
6464        RequirementSource::Registry {
6465            specifier,
6466            index,
6467            conflict,
6468        } => {
6469            // Round-trip the index to remove anything apart from the URL.
6470            let index = index
6471                .map(|index| index.url.into_url())
6472                .map(|mut index| {
6473                    index.remove_credentials();
6474                    index
6475                })
6476                .map(|index| IndexMetadata::from(IndexUrl::from(VerbatimUrl::from_url(index))));
6477            Ok(Requirement {
6478                name: requirement.name,
6479                extras: requirement.extras,
6480                groups: requirement.groups,
6481                marker: requires_python.simplify_markers(requirement.marker),
6482                source: RequirementSource::Registry {
6483                    specifier,
6484                    index,
6485                    conflict,
6486                },
6487                origin: None,
6488            })
6489        }
6490        RequirementSource::Url {
6491            mut location,
6492            subdirectory,
6493            ext,
6494            url: _,
6495        } => {
6496            // Remove the credentials.
6497            location.remove_credentials();
6498
6499            // Remove the fragment from the URL; it's already present in the source.
6500            location.set_fragment(None);
6501
6502            // Reconstruct the PEP 508 URL from the underlying data.
6503            let url = DisplaySafeUrl::from(ParsedArchiveUrl {
6504                url: location.clone(),
6505                subdirectory: subdirectory.clone(),
6506                ext,
6507            });
6508
6509            Ok(Requirement {
6510                name: requirement.name,
6511                extras: requirement.extras,
6512                groups: requirement.groups,
6513                marker: requires_python.simplify_markers(requirement.marker),
6514                source: RequirementSource::Url {
6515                    location,
6516                    subdirectory,
6517                    ext,
6518                    url: VerbatimUrl::from_url(url),
6519                },
6520                origin: None,
6521            })
6522        }
6523    }
6524}
6525
6526#[derive(Debug)]
6527pub struct LockError {
6528    kind: Box<LockErrorKind>,
6529    hint: Option<WheelTagHint>,
6530}
6531
6532impl std::error::Error for LockError {
6533    fn source(&self) -> Option<&(dyn Error + 'static)> {
6534        self.kind.source()
6535    }
6536}
6537
6538impl uv_errors::Hint for LockError {
6539    fn hints(&self) -> uv_errors::Hints<'_> {
6540        if let Some(hint) = &self.hint {
6541            uv_errors::Hints::from(hint.to_string())
6542        } else {
6543            uv_errors::Hints::none()
6544        }
6545    }
6546}
6547
6548impl std::fmt::Display for LockError {
6549    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6550        write!(f, "{}", self.kind)
6551    }
6552}
6553
6554impl LockError {
6555    /// Returns true if the [`LockError`] is a resolver error.
6556    pub fn is_resolution(&self) -> bool {
6557        matches!(&*self.kind, LockErrorKind::Resolution { .. })
6558    }
6559
6560    /// Returns true if the [`LockError`] is caused by disabled builds.
6561    pub fn is_no_build(&self) -> bool {
6562        matches!(
6563            &*self.kind,
6564            LockErrorKind::NoBuild { .. } | LockErrorKind::NoBinaryNoBuild { .. }
6565        )
6566    }
6567}
6568
6569impl<E> From<E> for LockError
6570where
6571    LockErrorKind: From<E>,
6572{
6573    fn from(err: E) -> Self {
6574        Self {
6575            kind: Box::new(LockErrorKind::from(err)),
6576            hint: None,
6577        }
6578    }
6579}
6580
6581#[derive(Debug, Clone, PartialEq, Eq)]
6582#[expect(clippy::enum_variant_names)]
6583enum WheelTagHint {
6584    /// None of the available wheels for a package have a compatible Python language tag (e.g.,
6585    /// `cp310` in `cp310-abi3-manylinux_2_17_x86_64.whl`).
6586    LanguageTags {
6587        package: PackageName,
6588        version: Option<Version>,
6589        tags: BTreeSet<LanguageTag>,
6590        best: Option<LanguageTag>,
6591    },
6592    /// None of the available wheels for a package have a compatible ABI tag (e.g., `abi3` in
6593    /// `cp310-abi3-manylinux_2_17_x86_64.whl`).
6594    AbiTags {
6595        package: PackageName,
6596        version: Option<Version>,
6597        tags: BTreeSet<AbiTag>,
6598        best: Option<AbiTag>,
6599    },
6600    /// None of the available wheels for a package have a compatible platform tag (e.g.,
6601    /// `manylinux_2_17_x86_64` in `cp310-abi3-manylinux_2_17_x86_64.whl`).
6602    PlatformTags {
6603        package: PackageName,
6604        version: Option<Version>,
6605        tags: BTreeSet<PlatformTag>,
6606        best: Option<PlatformTag>,
6607        markers: MarkerEnvironment,
6608    },
6609}
6610
6611impl WheelTagHint {
6612    /// Generate a [`WheelTagHint`] from the given (incompatible) wheels.
6613    fn from_wheels(
6614        name: &PackageName,
6615        version: Option<&Version>,
6616        filenames: &[&WheelFilename],
6617        tags: &Tags,
6618        markers: &MarkerEnvironment,
6619    ) -> Option<Self> {
6620        let incompatibility = filenames
6621            .iter()
6622            .map(|filename| {
6623                tags.compatibility(
6624                    filename.python_tags().iter(),
6625                    filename.abi_tags().iter(),
6626                    filename.platform_tags().iter(),
6627                )
6628            })
6629            .max()?;
6630        match incompatibility {
6631            TagCompatibility::Incompatible(IncompatibleTag::Python) => {
6632                let best = tags.python_tag();
6633                let tags = Self::python_tags(filenames.iter().copied()).collect::<BTreeSet<_>>();
6634                if tags.is_empty() {
6635                    None
6636                } else {
6637                    Some(Self::LanguageTags {
6638                        package: name.clone(),
6639                        version: version.cloned(),
6640                        tags,
6641                        best,
6642                    })
6643                }
6644            }
6645            TagCompatibility::Incompatible(IncompatibleTag::Abi) => {
6646                let best = tags.abi_tag();
6647                let tags = Self::abi_tags(filenames.iter().copied())
6648                    // Ignore `none`, which is universally compatible.
6649                    //
6650                    // As an example, `none` can appear here if we're solving for Python 3.13, and
6651                    // the distribution includes a wheel for `cp312-none-macosx_11_0_arm64`.
6652                    //
6653                    // In that case, the wheel isn't compatible, but when solving for Python 3.13,
6654                    // the `cp312` Python tag _can_ be compatible (e.g., for `cp312-abi3-macosx_11_0_arm64.whl`),
6655                    // so this is considered an ABI incompatibility rather than Python incompatibility.
6656                    .filter(|tag| *tag != AbiTag::None)
6657                    .collect::<BTreeSet<_>>();
6658                if tags.is_empty() {
6659                    None
6660                } else {
6661                    Some(Self::AbiTags {
6662                        package: name.clone(),
6663                        version: version.cloned(),
6664                        tags,
6665                        best,
6666                    })
6667                }
6668            }
6669            TagCompatibility::Incompatible(IncompatibleTag::Platform) => {
6670                let best = tags.platform_tag().cloned();
6671                let incompatible_tags = Self::platform_tags(filenames.iter().copied(), tags)
6672                    .cloned()
6673                    .collect::<BTreeSet<_>>();
6674                if incompatible_tags.is_empty() {
6675                    None
6676                } else {
6677                    Some(Self::PlatformTags {
6678                        package: name.clone(),
6679                        version: version.cloned(),
6680                        tags: incompatible_tags,
6681                        best,
6682                        markers: markers.clone(),
6683                    })
6684                }
6685            }
6686            _ => None,
6687        }
6688    }
6689
6690    /// Returns an iterator over the compatible Python tags of the available wheels.
6691    fn python_tags<'a>(
6692        filenames: impl Iterator<Item = &'a WheelFilename> + 'a,
6693    ) -> impl Iterator<Item = LanguageTag> + 'a {
6694        filenames.flat_map(WheelFilename::python_tags).copied()
6695    }
6696
6697    /// Returns an iterator over the compatible Python tags of the available wheels.
6698    fn abi_tags<'a>(
6699        filenames: impl Iterator<Item = &'a WheelFilename> + 'a,
6700    ) -> impl Iterator<Item = AbiTag> + 'a {
6701        filenames.flat_map(WheelFilename::abi_tags).copied()
6702    }
6703
6704    /// Returns the set of platform tags for the distribution that are ABI-compatible with the given
6705    /// tags.
6706    fn platform_tags<'a>(
6707        filenames: impl Iterator<Item = &'a WheelFilename> + 'a,
6708        tags: &'a Tags,
6709    ) -> impl Iterator<Item = &'a PlatformTag> + 'a {
6710        filenames.flat_map(move |filename| {
6711            if filename.python_tags().iter().any(|wheel_py| {
6712                filename
6713                    .abi_tags()
6714                    .iter()
6715                    .any(|wheel_abi| tags.is_compatible_abi(*wheel_py, *wheel_abi))
6716            }) {
6717                filename.platform_tags().iter()
6718            } else {
6719                [].iter()
6720            }
6721        })
6722    }
6723
6724    fn suggest_environment_marker(markers: &MarkerEnvironment) -> String {
6725        let sys_platform = markers.sys_platform();
6726        let platform_machine = markers.platform_machine();
6727
6728        // Generate the marker string based on actual environment values
6729        if platform_machine.is_empty() {
6730            format!("sys_platform == '{sys_platform}'")
6731        } else {
6732            format!("sys_platform == '{sys_platform}' and platform_machine == '{platform_machine}'")
6733        }
6734    }
6735}
6736
6737impl std::fmt::Display for WheelTagHint {
6738    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6739        match self {
6740            Self::LanguageTags {
6741                package,
6742                version,
6743                tags,
6744                best,
6745            } => {
6746                if let Some(best) = best {
6747                    let s = if tags.len() == 1 { "" } else { "s" };
6748                    let best = if let Some(pretty) = best.pretty() {
6749                        format!("{} (`{}`)", pretty.cyan(), best.cyan())
6750                    } else {
6751                        format!("{}", best.cyan())
6752                    };
6753                    if let Some(version) = version {
6754                        write!(
6755                            f,
6756                            "You're using {}, but `{}` ({}) only has wheels with the following Python implementation tag{s}: {}",
6757                            best,
6758                            package.cyan(),
6759                            format!("v{version}").cyan(),
6760                            tags.iter()
6761                                .map(|tag| format!("`{}`", tag.cyan()))
6762                                .join(", "),
6763                        )
6764                    } else {
6765                        write!(
6766                            f,
6767                            "You're using {}, but `{}` only has wheels with the following Python implementation tag{s}: {}",
6768                            best,
6769                            package.cyan(),
6770                            tags.iter()
6771                                .map(|tag| format!("`{}`", tag.cyan()))
6772                                .join(", "),
6773                        )
6774                    }
6775                } else {
6776                    let s = if tags.len() == 1 { "" } else { "s" };
6777                    if let Some(version) = version {
6778                        write!(
6779                            f,
6780                            "Wheels are available for `{}` ({}) with the following Python implementation tag{s}: {}",
6781                            package.cyan(),
6782                            format!("v{version}").cyan(),
6783                            tags.iter()
6784                                .map(|tag| format!("`{}`", tag.cyan()))
6785                                .join(", "),
6786                        )
6787                    } else {
6788                        write!(
6789                            f,
6790                            "Wheels are available for `{}` with the following Python implementation tag{s}: {}",
6791                            package.cyan(),
6792                            tags.iter()
6793                                .map(|tag| format!("`{}`", tag.cyan()))
6794                                .join(", "),
6795                        )
6796                    }
6797                }
6798            }
6799            Self::AbiTags {
6800                package,
6801                version,
6802                tags,
6803                best,
6804            } => {
6805                if let Some(best) = best {
6806                    let s = if tags.len() == 1 { "" } else { "s" };
6807                    let best = if let Some(pretty) = best.pretty() {
6808                        format!("{} (`{}`)", pretty.cyan(), best.cyan())
6809                    } else {
6810                        format!("{}", best.cyan())
6811                    };
6812                    if let Some(version) = version {
6813                        write!(
6814                            f,
6815                            "You're using {}, but `{}` ({}) only has wheels with the following Python ABI tag{s}: {}",
6816                            best,
6817                            package.cyan(),
6818                            format!("v{version}").cyan(),
6819                            tags.iter()
6820                                .map(|tag| format!("`{}`", tag.cyan()))
6821                                .join(", "),
6822                        )
6823                    } else {
6824                        write!(
6825                            f,
6826                            "You're using {}, but `{}` only has wheels with the following Python ABI tag{s}: {}",
6827                            best,
6828                            package.cyan(),
6829                            tags.iter()
6830                                .map(|tag| format!("`{}`", tag.cyan()))
6831                                .join(", "),
6832                        )
6833                    }
6834                } else {
6835                    let s = if tags.len() == 1 { "" } else { "s" };
6836                    if let Some(version) = version {
6837                        write!(
6838                            f,
6839                            "Wheels are available for `{}` ({}) with the following Python ABI tag{s}: {}",
6840                            package.cyan(),
6841                            format!("v{version}").cyan(),
6842                            tags.iter()
6843                                .map(|tag| format!("`{}`", tag.cyan()))
6844                                .join(", "),
6845                        )
6846                    } else {
6847                        write!(
6848                            f,
6849                            "Wheels are available for `{}` with the following Python ABI tag{s}: {}",
6850                            package.cyan(),
6851                            tags.iter()
6852                                .map(|tag| format!("`{}`", tag.cyan()))
6853                                .join(", "),
6854                        )
6855                    }
6856                }
6857            }
6858            Self::PlatformTags {
6859                package,
6860                version,
6861                tags,
6862                best,
6863                markers,
6864            } => {
6865                let s = if tags.len() == 1 { "" } else { "s" };
6866                if let Some(best) = best {
6867                    let example_marker = Self::suggest_environment_marker(markers);
6868                    let best = if let Some(pretty) = best.pretty() {
6869                        format!("{} (`{}`)", pretty.cyan(), best.cyan())
6870                    } else {
6871                        format!("`{}`", best.cyan())
6872                    };
6873                    let package_ref = if let Some(version) = version {
6874                        format!("`{}` ({})", package.cyan(), format!("v{version}").cyan())
6875                    } else {
6876                        format!("`{}`", package.cyan())
6877                    };
6878                    write!(
6879                        f,
6880                        "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",
6881                        best,
6882                        package_ref,
6883                        tags.iter()
6884                            .map(|tag| format!("`{}`", tag.cyan()))
6885                            .join(", "),
6886                        format!("\"{example_marker}\"").cyan(),
6887                        "tool.uv.required-environments".green()
6888                    )
6889                } else {
6890                    if let Some(version) = version {
6891                        write!(
6892                            f,
6893                            "Wheels are available for `{}` ({}) on the following platform{s}: {}",
6894                            package.cyan(),
6895                            format!("v{version}").cyan(),
6896                            tags.iter()
6897                                .map(|tag| format!("`{}`", tag.cyan()))
6898                                .join(", "),
6899                        )
6900                    } else {
6901                        write!(
6902                            f,
6903                            "Wheels are available for `{}` on the following platform{s}: {}",
6904                            package.cyan(),
6905                            tags.iter()
6906                                .map(|tag| format!("`{}`", tag.cyan()))
6907                                .join(", "),
6908                        )
6909                    }
6910                }
6911            }
6912        }
6913    }
6914}
6915
6916/// An error that occurs when generating a `Lock` data structure.
6917///
6918/// These errors are sometimes the result of possible programming bugs.
6919/// For example, if there are two or more duplicative distributions given
6920/// to `Lock::new`, then an error is returned. It's likely that the fault
6921/// is with the caller somewhere in such cases.
6922#[derive(Debug, thiserror::Error)]
6923enum LockErrorKind {
6924    /// An error that occurs when the overrides for validating a
6925    /// metadata-free lockfile cannot be scoped to their packages.
6926    #[error(transparent)]
6927    InvalidScopedOverride(#[from] ScopedOverrideSourceError),
6928    /// An error that occurs when multiple packages with the same
6929    /// ID were found.
6930    #[error("Found duplicate package `{id}`", id = id.cyan())]
6931    DuplicatePackage {
6932        /// The ID of the conflicting package.
6933        id: PackageId,
6934    },
6935    /// An error that occurs when there are multiple dependencies for the
6936    /// same package that have identical identifiers.
6937    #[error("For package `{id}`, found duplicate dependency `{dependency}`", id = id.cyan(), dependency = dependency.cyan())]
6938    DuplicateDependency {
6939        /// The ID of the package for which a duplicate dependency was
6940        /// found.
6941        id: PackageId,
6942        /// The ID of the conflicting dependency.
6943        dependency: Dependency,
6944    },
6945    /// An error that occurs when there are multiple dependencies for the
6946    /// same package that have identical identifiers, as part of the
6947    /// that package's optional dependencies.
6948    #[error("For package `{id}`, found duplicate dependency `{dependency}`", id = format!("{id}[{extra}]").cyan(), dependency = dependency.cyan())]
6949    DuplicateOptionalDependency {
6950        /// The ID of the package for which a duplicate dependency was
6951        /// found.
6952        id: PackageId,
6953        /// The name of the extra.
6954        extra: ExtraName,
6955        /// The ID of the conflicting dependency.
6956        dependency: Dependency,
6957    },
6958    /// An error that occurs when there are multiple dependencies for the
6959    /// same package that have identical identifiers, as part of the
6960    /// that package's development dependencies.
6961    #[error("For package `{id}`, found duplicate dependency `{dependency}`", id = format!("{id}:{group}").cyan(), dependency = dependency.cyan())]
6962    DuplicateDevDependency {
6963        /// The ID of the package for which a duplicate dependency was
6964        /// found.
6965        id: PackageId,
6966        /// The name of the dev dependency group.
6967        group: GroupName,
6968        /// The ID of the conflicting dependency.
6969        dependency: Dependency,
6970    },
6971    /// An error that occurs when the URL to a file for a wheel or
6972    /// source dist could not be converted to a structured `url::Url`.
6973    #[error(transparent)]
6974    InvalidUrl(
6975        /// The underlying error that occurred. This includes the
6976        /// errant URL in its error message.
6977        #[from]
6978        ToUrlError,
6979    ),
6980    /// An error that occurs when the extension can't be determined
6981    /// for a given wheel or source distribution.
6982    #[error("Failed to parse file extension for `{id}`; expected one of: {err}", id = id.cyan())]
6983    MissingExtension {
6984        /// The filename that was expected to have an extension.
6985        id: PackageId,
6986        /// The list of valid extensions that were expected.
6987        err: ExtensionError,
6988    },
6989    /// Failed to parse a Git source URL.
6990    #[error("Failed to parse Git URL")]
6991    InvalidGitSourceUrl(
6992        /// The underlying error that occurred. This includes the
6993        /// errant URL in the message.
6994        #[source]
6995        SourceParseError,
6996    ),
6997    #[error("Failed to parse timestamp")]
6998    InvalidTimestamp(
6999        /// The underlying error that occurred. This includes the
7000        /// errant timestamp in the message.
7001        #[source]
7002        jiff::Error,
7003    ),
7004    /// An error that occurs when there's an unrecognized dependency.
7005    ///
7006    /// That is, a dependency for a package that isn't in the lockfile.
7007    #[error("For package `{id}`, found dependency `{dependency}` with no locked package", id = id.cyan(), dependency = dependency.cyan())]
7008    UnrecognizedDependency {
7009        /// The ID of the package that has an unrecognized dependency.
7010        id: PackageId,
7011        /// The ID of the dependency that doesn't have a corresponding package
7012        /// entry.
7013        dependency: Dependency,
7014    },
7015    /// An error that occurs when a hash is expected (or not) for a particular
7016    /// artifact, but one was not found (or was).
7017    #[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" })]
7018    Hash {
7019        /// The ID of the package that has a missing hash.
7020        id: PackageId,
7021        /// The specific type of artifact, e.g., "source package"
7022        /// or "wheel".
7023        artifact_type: &'static str,
7024        /// Whether a hash was expected.
7025        expected: bool,
7026    },
7027    /// An error that occurs when an index requires a hash algorithm that an artifact does not
7028    /// advertise.
7029    #[error(
7030        "The index `{index}` requires `{algorithm}` hashes, but `{filename}` does not provide one"
7031    )]
7032    MissingHashAlgorithm {
7033        index: IndexUrl,
7034        filename: String,
7035        algorithm: HashAlgorithm,
7036    },
7037    /// An error that occurs when a package is included with an extra name,
7038    /// but no corresponding base package (i.e., without the extra) exists.
7039    #[error("Found package `{id}` with extra `{extra}` but no base package", id = id.cyan(), extra = extra.cyan())]
7040    MissingExtraBase {
7041        /// The ID of the package that has a missing base.
7042        id: PackageId,
7043        /// The extra name that was found.
7044        extra: ExtraName,
7045    },
7046    /// An error that occurs when a package is included with a development
7047    /// dependency group, but no corresponding base package (i.e., without
7048    /// the group) exists.
7049    #[error("Found package `{id}` with development dependency group `{group}` but no base package", id = id.cyan())]
7050    MissingDevBase {
7051        /// The ID of the package that has a missing base.
7052        id: PackageId,
7053        /// The development dependency group that was found.
7054        group: GroupName,
7055    },
7056    /// An error that occurs from an invalid lockfile where a wheel comes from a non-wheel source
7057    /// such as a directory.
7058    #[error("Wheels cannot come from {source_type} sources")]
7059    InvalidWheelSource {
7060        /// The ID of the distribution that has a missing base.
7061        id: PackageId,
7062        /// The kind of the invalid source.
7063        source_type: &'static str,
7064    },
7065    /// An error that occurs when a distribution indicates that it is sourced from a remote
7066    /// registry, but is missing a URL.
7067    #[error("Found registry distribution `{name}` ({version}) without a valid URL", name = name.cyan(), version = format!("v{version}").cyan())]
7068    MissingUrl {
7069        /// The name of the distribution that is missing a URL.
7070        name: PackageName,
7071        /// The version of the distribution that is missing a URL.
7072        version: Version,
7073    },
7074    /// An error that occurs when a distribution indicates that it is sourced from a local registry,
7075    /// but is missing a path.
7076    #[error("Found registry distribution `{name}` ({version}) without a valid path", name = name.cyan(), version = format!("v{version}").cyan())]
7077    MissingPath {
7078        /// The name of the distribution that is missing a path.
7079        name: PackageName,
7080        /// The version of the distribution that is missing a path.
7081        version: Version,
7082    },
7083    /// An error that occurs when a distribution indicates that it is sourced from a registry, but
7084    /// is missing a filename.
7085    #[error("Found registry distribution `{id}` without a valid filename", id = id.cyan())]
7086    MissingFilename {
7087        /// The ID of the distribution that is missing a filename.
7088        id: PackageId,
7089    },
7090    /// An error that occurs when a distribution is included with neither wheels nor a source
7091    /// distribution.
7092    #[error("Distribution `{id}` can't be installed because it doesn't have a source distribution or wheel for the current platform", id = id.cyan())]
7093    NeitherSourceDistNorWheel {
7094        /// The ID of the distribution.
7095        id: PackageId,
7096    },
7097    /// An error that occurs when a distribution is marked as both `--no-binary` and `--no-build`.
7098    #[error("Distribution `{id}` can't be installed because it is marked as both `--no-binary` and `--no-build`", id = id.cyan())]
7099    NoBinaryNoBuild {
7100        /// The ID of the distribution.
7101        id: PackageId,
7102    },
7103    /// An error that occurs when a distribution is marked as `--no-binary`, but no source
7104    /// distribution is available.
7105    #[error("Distribution `{id}` can't be installed because it is marked as `--no-binary` but has no source distribution", id = id.cyan())]
7106    NoBinary {
7107        /// The ID of the distribution.
7108        id: PackageId,
7109    },
7110    /// An error that occurs when a distribution is marked as `--no-build`, but no binary
7111    /// distribution is available.
7112    #[error("Distribution `{id}` can't be installed because it is marked as `--no-build` but has no binary distribution", id = id.cyan())]
7113    NoBuild {
7114        /// The ID of the distribution.
7115        id: PackageId,
7116    },
7117    /// An error that occurs when a wheel-only distribution is incompatible with the current
7118    /// platform.
7119    #[error("Distribution `{id}` can't be installed because the binary distribution is incompatible with the current platform", id = id.cyan())]
7120    IncompatibleWheelOnly {
7121        /// The ID of the distribution.
7122        id: PackageId,
7123    },
7124    /// An error that occurs when a wheel-only source is marked as `--no-binary`.
7125    #[error("Distribution `{id}` can't be installed because it is marked as `--no-binary` but is itself a binary distribution", id = id.cyan())]
7126    NoBinaryWheelOnly {
7127        /// The ID of the distribution.
7128        id: PackageId,
7129    },
7130    /// An error that occurs when converting between URLs and paths.
7131    #[error("Found dependency `{id}` with no locked distribution", id = id.cyan())]
7132    VerbatimUrl {
7133        /// The ID of the distribution that has a missing base.
7134        id: PackageId,
7135        /// The inner error we forward.
7136        #[source]
7137        err: VerbatimUrlError,
7138    },
7139    /// An error that occurs when parsing an existing requirement.
7140    #[error("Could not compute relative path between workspace and distribution")]
7141    DistributionRelativePath(
7142        /// The inner error we forward.
7143        #[source]
7144        io::Error,
7145    ),
7146    /// An error that occurs when converting an index URL to a relative path
7147    #[error("Could not compute relative path between workspace and index")]
7148    IndexRelativePath(
7149        /// The inner error we forward.
7150        #[source]
7151        io::Error,
7152    ),
7153    /// An error that occurs when converting a lockfile path from relative to absolute.
7154    #[error("Could not compute absolute path from workspace root and lockfile path")]
7155    AbsolutePath(
7156        /// The inner error we forward.
7157        #[source]
7158        io::Error,
7159    ),
7160    /// An error that occurs when an ambiguous `package.dependency` is
7161    /// missing a `version` field.
7162    #[error("Dependency `{name}` has missing `version` field but has more than one matching package", name = name.cyan())]
7163    MissingDependencyVersion {
7164        /// The name of the dependency that is missing a `version` field.
7165        name: PackageName,
7166    },
7167    /// An error that occurs when a registry-source package is missing a
7168    /// `version` field.
7169    #[error("Package `{name}` from a registry source has a missing `version` field", name = name.cyan())]
7170    MissingPackageVersion {
7171        /// The name of the package that is missing a `version` field.
7172        name: PackageName,
7173    },
7174    /// An error that occurs when an ambiguous `package.dependency` is
7175    /// missing a `source` field.
7176    #[error("Dependency `{name}` has missing `source` field but has more than one matching package", name = name.cyan())]
7177    MissingDependencySource {
7178        /// The name of the dependency that is missing a `source` field.
7179        name: PackageName,
7180    },
7181    /// An error that occurs when parsing an existing requirement.
7182    #[error("Could not compute relative path between workspace and requirement")]
7183    RequirementRelativePath(
7184        /// The inner error we forward.
7185        #[source]
7186        io::Error,
7187    ),
7188    /// An error that occurs when parsing an existing requirement.
7189    #[error("Could not convert between URL and path")]
7190    RequirementVerbatimUrl(
7191        /// The inner error we forward.
7192        #[source]
7193        VerbatimUrlError,
7194    ),
7195    /// An error that occurs when parsing a registry's index URL.
7196    #[error("Could not convert between URL and path")]
7197    RegistryVerbatimUrl(
7198        /// The inner error we forward.
7199        #[source]
7200        VerbatimUrlError,
7201    ),
7202    /// An error that occurs when converting a path to a URL.
7203    #[error("Failed to convert path to URL: {path}", path = path.display().cyan())]
7204    PathToUrl { path: Box<Path> },
7205    /// An error that occurs when converting a URL to a path
7206    #[error("Failed to convert URL to path: {url}", url = url.cyan())]
7207    UrlToPath { url: DisplaySafeUrl },
7208    /// An error that occurs when multiple packages with the same
7209    /// name were found when identifying the root packages.
7210    #[error("Found multiple packages matching `{name}`", name = name.cyan())]
7211    MultipleRootPackages {
7212        /// The ID of the package.
7213        name: PackageName,
7214    },
7215    /// An error that occurs when a root package can't be found.
7216    #[error("Could not find root package `{name}`", name = name.cyan())]
7217    MissingRootPackage {
7218        /// The ID of the package.
7219        name: PackageName,
7220    },
7221    /// An error that occurs when a concrete root package does not belong to the lock.
7222    #[error("Could not find root package `{id}` in lock", id = id.cyan())]
7223    RootPackageMissingFromLock {
7224        /// The ID of the package.
7225        id: PackageId,
7226    },
7227    /// A dependency marker depends on a package outside the selected subgraph.
7228    #[error(
7229        "Cannot materialize dependency `{dependency}` of `{package}` because its conflict marker depends on a package outside the selected subgraph",
7230        package = package.cyan(),
7231        dependency = dependency.cyan()
7232    )]
7233    DependencyConflictOutsideSubgraph {
7234        /// The ID of the package that declares the dependency.
7235        package: PackageId,
7236        /// The ID of the dependency whose inclusion is ambiguous.
7237        dependency: PackageId,
7238    },
7239    /// An error that occurs when resolving metadata for a package.
7240    #[error("Failed to generate package metadata for `{id}`", id = id.cyan())]
7241    Resolution {
7242        /// The ID of the distribution that failed to resolve.
7243        id: PackageId,
7244        /// The inner error we forward.
7245        #[source]
7246        err: uv_distribution::Error,
7247    },
7248    /// A package has inconsistent versions in a single entry
7249    // Using name instead of id since the version in the id is part of the conflict.
7250    #[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())]
7251    InconsistentVersions {
7252        /// The name of the package with the inconsistent entry.
7253        name: PackageName,
7254        /// The version of the package with the inconsistent entry.
7255        version: Version,
7256        /// The wheel with the inconsistent version.
7257        wheel: Wheel,
7258    },
7259    #[error(
7260        "Found conflicting extras `{package1}[{extra1}]` \
7261         and `{package2}[{extra2}]` enabled simultaneously"
7262    )]
7263    ConflictingExtra {
7264        package1: PackageName,
7265        extra1: ExtraName,
7266        package2: PackageName,
7267        extra2: ExtraName,
7268    },
7269    #[error(transparent)]
7270    GitUrlParse(#[from] GitUrlParseError),
7271    #[error("Failed to read `{path}`")]
7272    UnreadablePyprojectToml {
7273        path: PathBuf,
7274        #[source]
7275        err: std::io::Error,
7276    },
7277    #[error("Failed to parse `{path}`")]
7278    InvalidPyprojectToml {
7279        path: PathBuf,
7280        #[source]
7281        err: uv_pypi_types::MetadataError,
7282    },
7283    /// An error that occurs when a workspace member has a non-local source.
7284    #[error("Workspace member `{id}` has non-local source", id = id.cyan())]
7285    NonLocalWorkspaceMember {
7286        /// The ID of the workspace member with an invalid source.
7287        id: PackageId,
7288    },
7289}
7290
7291/// An error that occurs when a source string could not be parsed.
7292#[derive(Debug, thiserror::Error)]
7293enum SourceParseError {
7294    /// An error that occurs when the URL in the source is invalid.
7295    #[error("Invalid URL in source `{given}`")]
7296    InvalidUrl {
7297        /// The source string given.
7298        given: String,
7299        /// The URL parse error.
7300        #[source]
7301        err: DisplaySafeUrlError,
7302    },
7303    /// An error that occurs when a Git URL is missing a precise commit SHA.
7304    #[error("Missing SHA in source `{given}`")]
7305    MissingSha {
7306        /// The source string given.
7307        given: String,
7308    },
7309    /// An error that occurs when a Git URL has an invalid SHA.
7310    #[error("Invalid SHA in source `{given}`")]
7311    InvalidSha {
7312        /// The source string given.
7313        given: String,
7314    },
7315}
7316
7317/// An error that occurs when a hash digest could not be parsed.
7318#[derive(Clone, Debug, Eq, PartialEq)]
7319struct HashParseError(&'static str);
7320
7321impl std::error::Error for HashParseError {}
7322
7323impl Display for HashParseError {
7324    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
7325        Display::fmt(self.0, f)
7326    }
7327}
7328
7329/// Return the PEP 508 marker space covered by the resolution.
7330fn fork_markers_union(
7331    fork_markers: &[UniversalMarker],
7332    requires_python: &RequiresPython,
7333) -> MarkerTree {
7334    if fork_markers.is_empty() {
7335        return requires_python.to_marker_tree();
7336    }
7337    let mut environment = MarkerTree::FALSE;
7338    for fork_marker in fork_markers {
7339        environment = environment.or(fork_marker.pep508());
7340    }
7341    environment
7342}
7343
7344/// Simplify an edge marker using the PEP 508 conditions that must already hold to reach its parent
7345/// node. Parent conflict predicates remain on the edge for compatibility with older lockfile
7346/// readers that evaluate dependency markers independently during conflict discovery.
7347fn simplify_dependency_marker(
7348    requires_python: &RequiresPython,
7349    environment: SimplifiedMarkerTree,
7350    parent: UniversalMarker,
7351    marker: UniversalMarker,
7352) -> SimplifiedMarkerTree {
7353    let parent =
7354        SimplifiedMarkerTree::new(requires_python, parent.pep508()).as_simplified_marker_tree();
7355    let marker =
7356        SimplifiedMarkerTree::new(requires_python, marker.combined()).as_simplified_marker_tree();
7357    let marker = marker.restrict(parent);
7358
7359    // Retain the resolution environment internally. The lockfile writer removes it from the wire
7360    // marker, and the reader restores it, keeping freshly resolved and deserialized locks equal.
7361    let mut marker = SimplifiedMarkerTree::new(requires_python, marker);
7362    marker.and(environment);
7363    marker
7364}
7365
7366/// Returns the simplified string-ified version of each marker given.
7367///
7368/// Note that the marker strings returned will include conflict markers if they
7369/// are present.
7370fn simplified_universal_markers(
7371    markers: &[UniversalMarker],
7372    requires_python: &RequiresPython,
7373) -> Vec<String> {
7374    canonical_marker_trees(markers, requires_python)
7375        .into_iter()
7376        .filter_map(MarkerTree::try_to_string)
7377        .collect()
7378}
7379
7380/// Canonicalize universal markers to match the form persisted in `uv.lock`.
7381///
7382/// When the PEP 508 portions of the markers are disjoint, the lockfile stores
7383/// only those simplified PEP 508 markers. Otherwise, it stores the simplified
7384/// combined markers (including conflict markers). Markers that serialize to
7385/// `true` are omitted.
7386fn canonicalize_universal_markers(
7387    markers: &[UniversalMarker],
7388    requires_python: &RequiresPython,
7389) -> Vec<UniversalMarker> {
7390    canonical_marker_trees(markers, requires_python)
7391        .into_iter()
7392        .map(|marker| {
7393            let simplified = SimplifiedMarkerTree::new(requires_python, marker);
7394            UniversalMarker::from_combined(simplified.into_marker(requires_python))
7395        })
7396        .collect()
7397}
7398
7399/// Return the simplified marker trees that would be persisted in `uv.lock`.
7400fn canonical_marker_trees(
7401    markers: &[UniversalMarker],
7402    requires_python: &RequiresPython,
7403) -> Vec<MarkerTree> {
7404    let mut pep508_only = vec![];
7405    let mut seen = FxHashSet::default();
7406    for marker in markers {
7407        let simplified =
7408            SimplifiedMarkerTree::new(requires_python, marker.pep508()).as_simplified_marker_tree();
7409        if seen.insert(simplified) {
7410            pep508_only.push(simplified);
7411        }
7412    }
7413    let any_overlap = pep508_only
7414        .iter()
7415        .tuple_combinations()
7416        .any(|(&marker1, &marker2)| !marker1.is_disjoint(marker2));
7417    let markers = if !any_overlap {
7418        pep508_only
7419    } else {
7420        markers
7421            .iter()
7422            .map(|marker| {
7423                SimplifiedMarkerTree::new(requires_python, marker.combined())
7424                    .as_simplified_marker_tree()
7425            })
7426            .collect()
7427    };
7428    markers
7429        .into_iter()
7430        .filter(|marker| !marker.is_true())
7431        .collect()
7432}
7433
7434/// Filter out wheels that can't be selected for installation due to environment markers.
7435///
7436/// For example, a package included under `sys_platform == 'win32'` does not need Linux
7437/// wheels.
7438///
7439/// Returns `true` if the wheel is definitely unreachable, and `false` if it may be reachable,
7440/// including if the wheel tag isn't recognized.
7441fn is_wheel_unreachable_for_marker(
7442    filename: &WheelFilename,
7443    requires_python: &RequiresPython,
7444    marker: &UniversalMarker,
7445    tags: Option<&Tags>,
7446) -> bool {
7447    if let Some(tags) = tags
7448        && !filename.compatibility(tags).is_compatible()
7449    {
7450        return true;
7451    }
7452    // Remove wheels that don't match `requires-python` and can't be selected for installation.
7453    if !requires_python.matches_wheel_tag(filename) {
7454        return true;
7455    }
7456
7457    // Filter by platform tags.
7458
7459    // Naively, we'd check whether `platform_system == 'Linux'` is disjoint, or
7460    // `os_name == 'posix'` is disjoint, or `sys_platform == 'linux'` is disjoint (each on its
7461    // own sufficient to exclude linux wheels), but due to
7462    // `(A ∩ (B ∩ C) = ∅) => ((A ∩ B = ∅) or (A ∩ C = ∅))`
7463    // a single disjointness check with the intersection is sufficient, so we have one
7464    // constant per platform.
7465    let platform_tags = filename.platform_tags();
7466
7467    if platform_tags.iter().all(PlatformTag::is_any) {
7468        return false;
7469    }
7470
7471    if platform_tags.iter().all(PlatformTag::is_linux) {
7472        if platform_tags.iter().all(PlatformTag::is_arm) {
7473            if marker.is_disjoint(*LINUX_ARM_MARKERS) {
7474                return true;
7475            }
7476        } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
7477            if marker.is_disjoint(*LINUX_X86_64_MARKERS) {
7478                return true;
7479            }
7480        } else if platform_tags.iter().all(PlatformTag::is_x86) {
7481            if marker.is_disjoint(*LINUX_X86_MARKERS) {
7482                return true;
7483            }
7484        } else if platform_tags.iter().all(PlatformTag::is_ppc64le) {
7485            if marker.is_disjoint(*LINUX_PPC64LE_MARKERS) {
7486                return true;
7487            }
7488        } else if platform_tags.iter().all(PlatformTag::is_ppc64) {
7489            if marker.is_disjoint(*LINUX_PPC64_MARKERS) {
7490                return true;
7491            }
7492        } else if platform_tags.iter().all(PlatformTag::is_s390x) {
7493            if marker.is_disjoint(*LINUX_S390X_MARKERS) {
7494                return true;
7495            }
7496        } else if platform_tags.iter().all(PlatformTag::is_riscv64) {
7497            if marker.is_disjoint(*LINUX_RISCV64_MARKERS) {
7498                return true;
7499            }
7500        } else if platform_tags.iter().all(PlatformTag::is_loongarch64) {
7501            if marker.is_disjoint(*LINUX_LOONGARCH64_MARKERS) {
7502                return true;
7503            }
7504        } else if platform_tags.iter().all(PlatformTag::is_armv7l) {
7505            if marker.is_disjoint(*LINUX_ARMV7L_MARKERS) {
7506                return true;
7507            }
7508        } else if platform_tags.iter().all(PlatformTag::is_armv6l) {
7509            if marker.is_disjoint(*LINUX_ARMV6L_MARKERS) {
7510                return true;
7511            }
7512        } else if marker.is_disjoint(*LINUX_MARKERS) {
7513            return true;
7514        }
7515    }
7516
7517    if platform_tags.iter().all(PlatformTag::is_windows) {
7518        if platform_tags.iter().all(PlatformTag::is_arm) {
7519            if marker.is_disjoint(*WINDOWS_ARM_MARKERS) {
7520                return true;
7521            }
7522        } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
7523            if marker.is_disjoint(*WINDOWS_X86_64_MARKERS) {
7524                return true;
7525            }
7526        } else if platform_tags.iter().all(PlatformTag::is_x86) {
7527            if marker.is_disjoint(*WINDOWS_X86_MARKERS) {
7528                return true;
7529            }
7530        } else if marker.is_disjoint(*WINDOWS_MARKERS) {
7531            return true;
7532        }
7533    }
7534
7535    if platform_tags.iter().all(PlatformTag::is_macos) {
7536        if platform_tags.iter().all(PlatformTag::is_arm) {
7537            if marker.is_disjoint(*MAC_ARM_MARKERS) {
7538                return true;
7539            }
7540        } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
7541            if marker.is_disjoint(*MAC_X86_64_MARKERS) {
7542                return true;
7543            }
7544        } else if platform_tags.iter().all(PlatformTag::is_x86) {
7545            if marker.is_disjoint(*MAC_X86_MARKERS) {
7546                return true;
7547            }
7548        } else if marker.is_disjoint(*MAC_MARKERS) {
7549            return true;
7550        }
7551    }
7552
7553    if platform_tags.iter().all(PlatformTag::is_android) {
7554        if platform_tags.iter().all(PlatformTag::is_arm) {
7555            if marker.is_disjoint(*ANDROID_ARM_MARKERS) {
7556                return true;
7557            }
7558        } else if platform_tags.iter().all(PlatformTag::is_x86_64) {
7559            if marker.is_disjoint(*ANDROID_X86_64_MARKERS) {
7560                return true;
7561            }
7562        } else if platform_tags.iter().all(PlatformTag::is_x86) {
7563            if marker.is_disjoint(*ANDROID_X86_MARKERS) {
7564                return true;
7565            }
7566        } else if marker.is_disjoint(*ANDROID_MARKERS) {
7567            return true;
7568        }
7569    }
7570
7571    if platform_tags.iter().all(PlatformTag::is_arm) {
7572        if marker.is_disjoint(*ARM_MARKERS) {
7573            return true;
7574        }
7575    }
7576
7577    if platform_tags.iter().all(PlatformTag::is_x86_64) {
7578        if marker.is_disjoint(*X86_64_MARKERS) {
7579            return true;
7580        }
7581    }
7582
7583    if platform_tags.iter().all(PlatformTag::is_x86) {
7584        if marker.is_disjoint(*X86_MARKERS) {
7585            return true;
7586        }
7587    }
7588
7589    if platform_tags.iter().all(PlatformTag::is_ppc64le) {
7590        if marker.is_disjoint(*PPC64LE_MARKERS) {
7591            return true;
7592        }
7593    }
7594
7595    if platform_tags.iter().all(PlatformTag::is_ppc64) {
7596        if marker.is_disjoint(*PPC64_MARKERS) {
7597            return true;
7598        }
7599    }
7600
7601    if platform_tags.iter().all(PlatformTag::is_s390x) {
7602        if marker.is_disjoint(*S390X_MARKERS) {
7603            return true;
7604        }
7605    }
7606
7607    if platform_tags.iter().all(PlatformTag::is_riscv64) {
7608        if marker.is_disjoint(*RISCV64_MARKERS) {
7609            return true;
7610        }
7611    }
7612
7613    if platform_tags.iter().all(PlatformTag::is_loongarch64) {
7614        if marker.is_disjoint(*LOONGARCH64_MARKERS) {
7615            return true;
7616        }
7617    }
7618
7619    if platform_tags.iter().all(PlatformTag::is_armv7l) {
7620        if marker.is_disjoint(*ARMV7L_MARKERS) {
7621            return true;
7622        }
7623    }
7624
7625    if platform_tags.iter().all(PlatformTag::is_armv6l) {
7626        if marker.is_disjoint(*ARMV6L_MARKERS) {
7627            return true;
7628        }
7629    }
7630
7631    false
7632}
7633
7634pub(crate) fn is_wheel_unreachable(
7635    filename: &WheelFilename,
7636    graph: &ResolverOutput,
7637    requires_python: &RequiresPython,
7638    node_index: NodeIndex,
7639    tags: Option<&Tags>,
7640) -> bool {
7641    is_wheel_unreachable_for_marker(
7642        filename,
7643        requires_python,
7644        graph.graph[node_index].marker(),
7645        tags,
7646    )
7647}
7648
7649#[cfg(test)]
7650mod tests {
7651    use uv_pep440::VersionSpecifiers;
7652    use uv_pep508::MarkerEnvironmentBuilder;
7653    use uv_warnings::anstream;
7654
7655    use super::*;
7656
7657    /// Assert a given display snapshot, stripping ANSI color codes.
7658    macro_rules! assert_stripped_snapshot {
7659        ($expr:expr, @$snapshot:literal) => {{
7660            let expr = format!("{}", $expr);
7661            let expr = format!("{}", anstream::adapter::strip_str(&expr));
7662            insta::assert_snapshot!(expr, @$snapshot);
7663        }};
7664    }
7665
7666    fn marker_environment() -> MarkerEnvironment {
7667        MarkerEnvironment::try_from(MarkerEnvironmentBuilder {
7668            implementation_name: "cpython",
7669            implementation_version: "3.12.0",
7670            os_name: "posix",
7671            platform_machine: "arm64",
7672            platform_python_implementation: "CPython",
7673            platform_release: "23.0.0",
7674            platform_system: "Darwin",
7675            platform_version: "test",
7676            python_full_version: "3.12.0",
7677            python_version: "3.12",
7678            sys_platform: "darwin",
7679        })
7680        .expect("valid marker environment")
7681    }
7682
7683    #[test]
7684    fn dependency_marker_preserves_parent_conflicts() {
7685        let requires_python = RequiresPython::from_specifiers(
7686            VersionSpecifiers::from_str(">=3.12").expect("valid version specifier"),
7687        );
7688        let parent = UniversalMarker::from_combined(
7689            MarkerTree::from_str(
7690                "python_full_version >= '3.12' and sys_platform == 'darwin' and extra != 'extra-1-x-foo'",
7691            )
7692            .expect("valid parent marker"),
7693        );
7694        let environment = SimplifiedMarkerTree::new(&requires_python, MarkerTree::TRUE);
7695
7696        let simplified_marker =
7697            simplify_dependency_marker(&requires_python, environment, parent, parent);
7698        assert_eq!(
7699            simplified_marker.try_to_string().as_deref(),
7700            Some("extra != 'extra-1-x-foo'")
7701        );
7702
7703        let marker = simplified_marker.into_marker(&requires_python);
7704        assert_eq!(
7705            marker.try_to_string().as_deref(),
7706            Some("python_full_version >= '3.12' and extra != 'extra-1-x-foo'")
7707        );
7708    }
7709
7710    #[test]
7711    fn dependency_selection_resolves_included_groups_to_same_package() {
7712        let lock: Lock = toml::from_str(
7713            r#"
7714version = 1
7715revision = 3
7716requires-python = ">=3.12"
7717
7718[[package]]
7719name = "project"
7720version = "0.1.0"
7721source = { virtual = "." }
7722dependencies = [{ name = "ty" }]
7723
7724[package.dependency-groups]
7725dev = [{ name = "ty" }]
7726typing = [{ name = "ty" }]
7727
7728[[package]]
7729name = "ty"
7730version = "1.0.0"
7731source = { registry = "https://example.com/simple" }
7732"#,
7733        )
7734        .expect("valid lock");
7735        let project_name = PackageName::from_str("project").expect("valid package name");
7736        let dependency_name = PackageName::from_str("ty").expect("valid package name");
7737        let dev = GroupName::from_str("dev").expect("valid group name");
7738        let typing = GroupName::from_str("typing").expect("valid group name");
7739        let marker_environment = marker_environment();
7740
7741        let selection = lock
7742            .dependency_selection(Some(&project_name), &dependency_name, &marker_environment)
7743            .expect("unique project package");
7744        let preferred = selection.group(&dev).expect("dev dependency").package();
7745        let included = selection
7746            .group(&typing)
7747            .expect("typing dependency")
7748            .package();
7749        let production = selection
7750            .production()
7751            .expect("production dependency")
7752            .package();
7753
7754        assert!(std::ptr::eq(preferred, included));
7755        assert!(std::ptr::eq(preferred, production));
7756    }
7757
7758    #[test]
7759    fn dependency_selection_resolves_lock_manifest_requirement() {
7760        let lock: Lock = toml::from_str(
7761            r#"
7762version = 1
7763revision = 3
7764requires-python = ">=3.12"
7765
7766[manifest]
7767requirements = [{ name = "ty" }]
7768
7769[[package]]
7770name = "ty"
7771version = "1.0.0"
7772source = { registry = "https://example.com/simple" }
7773"#,
7774        )
7775        .expect("valid lock");
7776        let dependency_name = PackageName::from_str("ty").expect("valid package name");
7777        let marker_environment = marker_environment();
7778
7779        let selection = lock
7780            .dependency_selection(None, &dependency_name, &marker_environment)
7781            .expect("unique root package");
7782        let root = selection.root().expect("root dependency");
7783
7784        assert_eq!(root.package().name(), &dependency_name);
7785        assert!(selection.production().is_none());
7786    }
7787
7788    #[test]
7789    fn dependency_selection_returns_any_selection_error() {
7790        let lock: Lock = toml::from_str(
7791            r#"
7792version = 1
7793revision = 3
7794requires-python = ">=3.12"
7795
7796[[package]]
7797name = "project"
7798version = "0.1.0"
7799source = { virtual = "." }
7800dependencies = [
7801    { name = "ty", version = "1.0.0", source = { registry = "https://example.com/simple" } },
7802    { name = "ty", version = "2.0.0", source = { registry = "https://example.com/simple" } },
7803]
7804
7805[package.dependency-groups]
7806dev = [
7807    { name = "ty", version = "1.0.0", source = { registry = "https://example.com/simple" } },
7808]
7809
7810[[package]]
7811name = "ty"
7812version = "1.0.0"
7813source = { registry = "https://example.com/simple" }
7814
7815[[package]]
7816name = "ty"
7817version = "2.0.0"
7818source = { registry = "https://example.com/simple" }
7819"#,
7820        )
7821        .expect("valid lock");
7822        let project_name = PackageName::from_str("project").expect("valid package name");
7823        let dependency_name = PackageName::from_str("ty").expect("valid package name");
7824        let marker_environment = marker_environment();
7825
7826        let error = lock
7827            .dependency_selection(Some(&project_name), &dependency_name, &marker_environment)
7828            .expect_err("ambiguous production selection");
7829        insta::assert_snapshot!(error, @"found multiple packages matching production dependency `ty` for `project`");
7830    }
7831
7832    #[test]
7833    fn missing_dependency_source_unambiguous() {
7834        let data = r#"
7835version = 1
7836requires-python = ">=3.12"
7837
7838[[package]]
7839name = "a"
7840version = "0.1.0"
7841source = { registry = "https://pypi.org/simple" }
7842sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7843
7844[[package]]
7845name = "b"
7846version = "0.1.0"
7847source = { registry = "https://pypi.org/simple" }
7848sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7849
7850[[package.dependencies]]
7851name = "a"
7852version = "0.1.0"
7853"#;
7854        let result: Result<Lock, _> = toml::from_str(data);
7855        insta::assert_debug_snapshot!(result);
7856    }
7857
7858    #[test]
7859    fn missing_dependency_version_unambiguous() {
7860        let data = r#"
7861version = 1
7862requires-python = ">=3.12"
7863
7864[[package]]
7865name = "a"
7866version = "0.1.0"
7867source = { registry = "https://pypi.org/simple" }
7868sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7869
7870[[package]]
7871name = "b"
7872version = "0.1.0"
7873source = { registry = "https://pypi.org/simple" }
7874sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7875
7876[[package.dependencies]]
7877name = "a"
7878source = { registry = "https://pypi.org/simple" }
7879"#;
7880        let result: Result<Lock, _> = toml::from_str(data);
7881        insta::assert_debug_snapshot!(result);
7882    }
7883
7884    #[test]
7885    fn missing_dependency_source_version_unambiguous() {
7886        let data = r#"
7887version = 1
7888requires-python = ">=3.12"
7889
7890[[package]]
7891name = "a"
7892version = "0.1.0"
7893source = { registry = "https://pypi.org/simple" }
7894sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7895
7896[[package]]
7897name = "b"
7898version = "0.1.0"
7899source = { registry = "https://pypi.org/simple" }
7900sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7901
7902[[package.dependencies]]
7903name = "a"
7904"#;
7905        let result: Result<Lock, _> = toml::from_str(data);
7906        insta::assert_debug_snapshot!(result);
7907    }
7908
7909    #[test]
7910    fn missing_dependency_source_ambiguous() {
7911        let data = r#"
7912version = 1
7913requires-python = ">=3.12"
7914
7915[[package]]
7916name = "a"
7917version = "0.1.0"
7918source = { registry = "https://pypi.org/simple" }
7919sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7920
7921[[package]]
7922name = "a"
7923version = "0.1.1"
7924source = { registry = "https://pypi.org/simple" }
7925sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7926
7927[[package]]
7928name = "b"
7929version = "0.1.0"
7930source = { registry = "https://pypi.org/simple" }
7931sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7932
7933[[package.dependencies]]
7934name = "a"
7935version = "0.1.0"
7936"#;
7937        let result = toml::from_str::<Lock>(data).unwrap_err();
7938        assert_stripped_snapshot!(result, @"Dependency `a` has missing `source` field but has more than one matching package");
7939    }
7940
7941    #[test]
7942    fn missing_dependency_version_ambiguous() {
7943        let data = r#"
7944version = 1
7945requires-python = ">=3.12"
7946
7947[[package]]
7948name = "a"
7949version = "0.1.0"
7950source = { registry = "https://pypi.org/simple" }
7951sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7952
7953[[package]]
7954name = "a"
7955version = "0.1.1"
7956source = { registry = "https://pypi.org/simple" }
7957sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7958
7959[[package]]
7960name = "b"
7961version = "0.1.0"
7962source = { registry = "https://pypi.org/simple" }
7963sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7964
7965[[package.dependencies]]
7966name = "a"
7967source = { registry = "https://pypi.org/simple" }
7968"#;
7969        let result = toml::from_str::<Lock>(data).unwrap_err();
7970        assert_stripped_snapshot!(result, @"Dependency `a` has missing `version` field but has more than one matching package");
7971    }
7972
7973    #[test]
7974    fn missing_package_version_registry() {
7975        let data = r#"
7976version = 1
7977requires-python = ">=3.12"
7978
7979[[package]]
7980name = "a"
7981source = { registry = "https://pypi.org/simple" }
7982sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7983"#;
7984        let result = toml::from_str::<Lock>(data).unwrap_err();
7985        assert_stripped_snapshot!(result, @"Package `a` from a registry source has a missing `version` field");
7986    }
7987
7988    #[test]
7989    fn missing_dependency_source_version_ambiguous() {
7990        let data = r#"
7991version = 1
7992requires-python = ">=3.12"
7993
7994[[package]]
7995name = "a"
7996version = "0.1.0"
7997source = { registry = "https://pypi.org/simple" }
7998sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
7999
8000[[package]]
8001name = "a"
8002version = "0.1.1"
8003source = { registry = "https://pypi.org/simple" }
8004sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
8005
8006[[package]]
8007name = "b"
8008version = "0.1.0"
8009source = { registry = "https://pypi.org/simple" }
8010sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
8011
8012[[package.dependencies]]
8013name = "a"
8014"#;
8015        let result = toml::from_str::<Lock>(data).unwrap_err();
8016        assert_stripped_snapshot!(result, @"Dependency `a` has missing `source` field but has more than one matching package");
8017    }
8018
8019    #[test]
8020    fn missing_dependency_version_dynamic() {
8021        let data = r#"
8022version = 1
8023requires-python = ">=3.12"
8024
8025[[package]]
8026name = "a"
8027source = { editable = "path/to/a" }
8028
8029[[package]]
8030name = "a"
8031version = "0.1.1"
8032source = { registry = "https://pypi.org/simple" }
8033sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
8034
8035[[package]]
8036name = "b"
8037version = "0.1.0"
8038source = { registry = "https://pypi.org/simple" }
8039sdist = { url = "https://example.com", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 0 }
8040
8041[[package.dependencies]]
8042name = "a"
8043source = { editable = "path/to/a" }
8044"#;
8045        let result = toml::from_str::<Lock>(data);
8046        insta::assert_debug_snapshot!(result);
8047    }
8048
8049    #[test]
8050    fn hash_optional_missing() {
8051        let data = r#"
8052version = 1
8053requires-python = ">=3.12"
8054
8055[[package]]
8056name = "anyio"
8057version = "4.3.0"
8058source = { registry = "https://pypi.org/simple" }
8059wheels = [{ url = "https://files.pythonhosted.org/packages/14/fd/2f20c40b45e4fb4324834aea24bd4afdf1143390242c0b33774da0e2e34f/anyio-4.3.0-py3-none-any.whl" }]
8060"#;
8061        let result: Result<Lock, _> = toml::from_str(data);
8062        insta::assert_debug_snapshot!(result);
8063    }
8064
8065    #[test]
8066    fn hash_optional_present() {
8067        let data = r#"
8068version = 1
8069requires-python = ">=3.12"
8070
8071[[package]]
8072name = "anyio"
8073version = "4.3.0"
8074source = { registry = "https://pypi.org/simple" }
8075wheels = [{ url = "https://files.pythonhosted.org/packages/14/fd/2f20c40b45e4fb4324834aea24bd4afdf1143390242c0b33774da0e2e34f/anyio-4.3.0-py3-none-any.whl", hash = "sha256:048e05d0f6caeed70d731f3db756d35dcc1f35747c8c403364a8332c630441b8" }]
8076"#;
8077        let result: Result<Lock, _> = toml::from_str(data);
8078        insta::assert_debug_snapshot!(result);
8079    }
8080
8081    #[test]
8082    fn hash_required_present() {
8083        let data = r#"
8084version = 1
8085requires-python = ">=3.12"
8086
8087[[package]]
8088name = "anyio"
8089version = "4.3.0"
8090source = { path = "file:///foo/bar" }
8091wheels = [{ url = "file:///foo/bar/anyio-4.3.0-py3-none-any.whl", hash = "sha256:048e05d0f6caeed70d731f3db756d35dcc1f35747c8c403364a8332c630441b8" }]
8092"#;
8093        let result: Result<Lock, _> = toml::from_str(data);
8094        insta::assert_debug_snapshot!(result);
8095    }
8096
8097    #[test]
8098    fn source_direct_no_subdir() {
8099        let data = r#"
8100version = 1
8101requires-python = ">=3.12"
8102
8103[[package]]
8104name = "anyio"
8105version = "4.3.0"
8106source = { url = "https://burntsushi.net" }
8107"#;
8108        let result: Result<Lock, _> = toml::from_str(data);
8109        insta::assert_debug_snapshot!(result);
8110    }
8111
8112    #[test]
8113    fn source_direct_has_subdir() {
8114        let data = r#"
8115version = 1
8116requires-python = ">=3.12"
8117
8118[[package]]
8119name = "anyio"
8120version = "4.3.0"
8121source = { url = "https://burntsushi.net", subdirectory = "wat/foo/bar" }
8122"#;
8123        let result: Result<Lock, _> = toml::from_str(data);
8124        insta::assert_debug_snapshot!(result);
8125    }
8126
8127    #[test]
8128    fn source_directory() {
8129        let data = r#"
8130version = 1
8131requires-python = ">=3.12"
8132
8133[[package]]
8134name = "anyio"
8135version = "4.3.0"
8136source = { directory = "path/to/dir" }
8137"#;
8138        let result: Result<Lock, _> = toml::from_str(data);
8139        insta::assert_debug_snapshot!(result);
8140    }
8141
8142    #[test]
8143    fn source_editable() {
8144        let data = r#"
8145version = 1
8146requires-python = ">=3.12"
8147
8148[[package]]
8149name = "anyio"
8150version = "4.3.0"
8151source = { editable = "path/to/dir" }
8152"#;
8153        let result: Result<Lock, _> = toml::from_str(data);
8154        insta::assert_debug_snapshot!(result);
8155    }
8156
8157    /// Windows drive letter paths like `C:/...` should be deserialized as local path registry
8158    /// sources, not as URLs. The `C:` prefix must not be misinterpreted as a URL scheme.
8159    #[test]
8160    fn registry_source_windows_drive_letter() {
8161        let data = r#"
8162version = 1
8163requires-python = ">=3.12"
8164
8165[[package]]
8166name = "tqdm"
8167version = "1000.0.0"
8168source = { registry = "C:/Users/user/links" }
8169wheels = [
8170    { path = "C:/Users/user/links/tqdm-1000.0.0-py3-none-any.whl" },
8171]
8172"#;
8173        let lock: Lock = toml::from_str(data).unwrap();
8174        assert_eq!(
8175            lock.packages[0].id.source,
8176            Source::Registry(RegistrySource::Path(
8177                Path::new("C:/Users/user/links").into()
8178            ))
8179        );
8180    }
8181}