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