-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathlock.rs
3713 lines (3405 loc) · 132 KB
/
lock.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::convert::Infallible;
use std::fmt::{Debug, Display};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use either::Either;
use itertools::Itertools;
use petgraph::visit::EdgeRef;
use rustc_hash::{FxHashMap, FxHashSet};
use toml_edit::{value, Array, ArrayOfTables, InlineTable, Item, Table, Value};
use tracing::debug;
use url::Url;
use cache_key::RepositoryUrl;
use distribution_filename::{DistExtension, ExtensionError, SourceDistExtension, WheelFilename};
use distribution_types::{
BuiltDist, DirectUrlBuiltDist, DirectUrlSourceDist, DirectorySourceDist, Dist,
DistributionMetadata, FileLocation, FlatIndexLocation, GitSourceDist, HashPolicy,
IndexLocations, IndexUrl, Name, PathBuiltDist, PathSourceDist, RegistryBuiltDist,
RegistryBuiltWheel, RegistrySourceDist, RemoteSource, Resolution, ResolvedDist, ToUrlError,
UrlString,
};
use pep440_rs::Version;
use pep508_rs::{MarkerEnvironment, MarkerTree, VerbatimUrl, VerbatimUrlError};
use platform_tags::{TagCompatibility, TagPriority, Tags};
use pypi_types::{HashDigest, ParsedArchiveUrl, ParsedGitUrl, Requirement, RequirementSource};
use uv_configuration::ExtrasSpecification;
use uv_distribution::DistributionDatabase;
use uv_fs::{relative_to, PortablePath, PortablePathBuf, Simplified};
use uv_git::{GitReference, GitSha, RepositoryReference, ResolvedRepositoryReference};
use uv_normalize::{ExtraName, GroupName, PackageName};
use uv_types::BuildContext;
use uv_workspace::{VirtualProject, Workspace};
use crate::resolution::{AnnotatedDist, ResolutionGraphNode};
use crate::{ExcludeNewer, PrereleaseMode, RequiresPython, ResolutionGraph, ResolutionMode};
/// The current version of the lockfile format.
const VERSION: u32 = 1;
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(try_from = "LockWire")]
pub struct Lock {
version: u32,
/// If this lockfile was built from a forking resolution with non-identical forks, store the
/// forks in the lockfile so we can recreate them in subsequent resolutions.
fork_markers: Vec<MarkerTree>,
/// The range of supported Python versions.
requires_python: Option<RequiresPython>,
/// We discard the lockfile if these options don't match.
options: ResolverOptions,
/// The actual locked version and their metadata.
packages: Vec<Package>,
/// A map from package ID to index in `packages`.
///
/// This can be used to quickly lookup the full package for any ID
/// in this lock. For example, the dependencies for each package are
/// listed as package IDs. This map can be used to find the full
/// package for each such dependency.
///
/// It is guaranteed that every package in this lock has an entry in
/// this map, and that every dependency for every package has an ID
/// that exists in this map. That is, there are no dependencies that don't
/// have a corresponding locked package entry in the same lockfile.
by_id: FxHashMap<PackageId, usize>,
/// The input requirements to the resolution.
manifest: ResolverManifest,
}
impl Lock {
/// Initialize a [`Lock`] from a [`ResolutionGraph`].
pub fn from_resolution_graph(graph: &ResolutionGraph) -> Result<Self, LockError> {
let mut locked_dists = BTreeMap::new();
// Lock all base packages.
for node_index in graph.petgraph.node_indices() {
let ResolutionGraphNode::Dist(dist) = &graph.petgraph[node_index] else {
continue;
};
if dist.is_base() {
let fork_markers = graph
.fork_markers(dist.name(), &dist.version, dist.dist.version_or_url().url())
.cloned()
.unwrap_or_default();
let mut locked_dist = Package::from_annotated_dist(dist, fork_markers)?;
// Add all dependencies
for edge in graph.petgraph.edges(node_index) {
let ResolutionGraphNode::Dist(dependency_dist) = &graph.petgraph[edge.target()]
else {
continue;
};
let marker = edge.weight().clone();
locked_dist.add_dependency(dependency_dist, marker);
}
let id = locked_dist.id.clone();
if let Some(locked_dist) = locked_dists.insert(id, locked_dist) {
return Err(LockErrorKind::DuplicatePackage {
id: locked_dist.id.clone(),
}
.into());
}
}
}
// Lock all extras and development dependencies.
for node_index in graph.petgraph.node_indices() {
let ResolutionGraphNode::Dist(dist) = &graph.petgraph[node_index] else {
continue;
};
if let Some(extra) = dist.extra.as_ref() {
let id = PackageId::from_annotated_dist(dist);
let Some(locked_dist) = locked_dists.get_mut(&id) else {
return Err(LockErrorKind::MissingExtraBase {
id,
extra: extra.clone(),
}
.into());
};
for edge in graph.petgraph.edges(node_index) {
let ResolutionGraphNode::Dist(dependency_dist) = &graph.petgraph[edge.target()]
else {
continue;
};
let marker = edge.weight().clone();
locked_dist.add_optional_dependency(extra.clone(), dependency_dist, marker);
}
}
if let Some(group) = dist.dev.as_ref() {
let id = PackageId::from_annotated_dist(dist);
let Some(locked_dist) = locked_dists.get_mut(&id) else {
return Err(LockErrorKind::MissingDevBase {
id,
group: group.clone(),
}
.into());
};
for edge in graph.petgraph.edges(node_index) {
let ResolutionGraphNode::Dist(dependency_dist) = &graph.petgraph[edge.target()]
else {
continue;
};
let marker = edge.weight().clone();
locked_dist.add_dev_dependency(group.clone(), dependency_dist, marker);
}
}
}
let packages = locked_dists.into_values().collect();
let requires_python = graph.requires_python.clone();
let options = ResolverOptions {
resolution_mode: graph.options.resolution_mode,
prerelease_mode: graph.options.prerelease_mode,
exclude_newer: graph.options.exclude_newer,
};
let lock = Self::new(
VERSION,
packages,
requires_python,
options,
ResolverManifest::default(),
graph.fork_markers.clone(),
)?;
Ok(lock)
}
/// Initialize a [`Lock`] from a list of [`Package`] entries.
fn new(
version: u32,
mut packages: Vec<Package>,
requires_python: Option<RequiresPython>,
options: ResolverOptions,
manifest: ResolverManifest,
fork_markers: Vec<MarkerTree>,
) -> Result<Self, LockError> {
// Put all dependencies for each package in a canonical order and
// check for duplicates.
for package in &mut packages {
package.dependencies.sort();
for windows in package.dependencies.windows(2) {
let (dep1, dep2) = (&windows[0], &windows[1]);
if dep1 == dep2 {
return Err(LockErrorKind::DuplicateDependency {
id: package.id.clone(),
dependency: dep1.clone(),
}
.into());
}
}
// Perform the same validation for optional dependencies.
for (extra, dependencies) in &mut package.optional_dependencies {
dependencies.sort();
for windows in dependencies.windows(2) {
let (dep1, dep2) = (&windows[0], &windows[1]);
if dep1 == dep2 {
return Err(LockErrorKind::DuplicateOptionalDependency {
id: package.id.clone(),
extra: extra.clone(),
dependency: dep1.clone(),
}
.into());
}
}
}
// Perform the same validation for dev dependencies.
for (group, dependencies) in &mut package.dev_dependencies {
dependencies.sort();
for windows in dependencies.windows(2) {
let (dep1, dep2) = (&windows[0], &windows[1]);
if dep1 == dep2 {
return Err(LockErrorKind::DuplicateDevDependency {
id: package.id.clone(),
group: group.clone(),
dependency: dep1.clone(),
}
.into());
}
}
}
// Remove wheels that don't match `requires-python` and can't be selected for
// installation.
if let Some(requires_python) = &requires_python {
package
.wheels
.retain(|wheel| requires_python.matches_wheel_tag(&wheel.filename));
}
}
packages.sort_by(|dist1, dist2| dist1.id.cmp(&dist2.id));
// Check for duplicate package IDs and also build up the map for
// packages keyed by their ID.
let mut by_id = FxHashMap::default();
for (i, dist) in packages.iter().enumerate() {
if by_id.insert(dist.id.clone(), i).is_some() {
return Err(LockErrorKind::DuplicatePackage {
id: dist.id.clone(),
}
.into());
}
}
// Build up a map from ID to extras.
let mut extras_by_id = FxHashMap::default();
for dist in &packages {
for extra in dist.optional_dependencies.keys() {
extras_by_id
.entry(dist.id.clone())
.or_insert_with(FxHashSet::default)
.insert(extra.clone());
}
}
// Remove any non-existent extras (e.g., extras that were requested but don't exist).
for dist in &mut packages {
for dep in dist
.dependencies
.iter_mut()
.chain(dist.optional_dependencies.values_mut().flatten())
.chain(dist.dev_dependencies.values_mut().flatten())
{
dep.extra.retain(|extra| {
extras_by_id
.get(&dep.package_id)
.is_some_and(|extras| extras.contains(extra))
});
}
}
// Check that every dependency has an entry in `by_id`. If any don't,
// it implies we somehow have a dependency with no corresponding locked
// package.
for dist in &packages {
for dep in &dist.dependencies {
if !by_id.contains_key(&dep.package_id) {
return Err(LockErrorKind::UnrecognizedDependency {
id: dist.id.clone(),
dependency: dep.clone(),
}
.into());
}
}
// Perform the same validation for optional dependencies.
for dependencies in dist.optional_dependencies.values() {
for dep in dependencies {
if !by_id.contains_key(&dep.package_id) {
return Err(LockErrorKind::UnrecognizedDependency {
id: dist.id.clone(),
dependency: dep.clone(),
}
.into());
}
}
}
// Perform the same validation for dev dependencies.
for dependencies in dist.dev_dependencies.values() {
for dep in dependencies {
if !by_id.contains_key(&dep.package_id) {
return Err(LockErrorKind::UnrecognizedDependency {
id: dist.id.clone(),
dependency: dep.clone(),
}
.into());
}
}
}
// Also check that our sources are consistent with whether we have
// hashes or not.
if let Some(requires_hash) = dist.id.source.requires_hash() {
for wheel in &dist.wheels {
if requires_hash != wheel.hash.is_some() {
return Err(LockErrorKind::Hash {
id: dist.id.clone(),
artifact_type: "wheel",
expected: requires_hash,
}
.into());
}
}
}
}
Ok(Self {
version,
fork_markers,
requires_python,
options,
packages,
by_id,
manifest,
})
}
/// Record the requirements that were used to generate this lock.
#[must_use]
pub fn with_manifest(mut self, manifest: ResolverManifest) -> Self {
self.manifest = manifest;
self
}
/// Returns the number of packages in the lockfile.
pub fn len(&self) -> usize {
self.packages.len()
}
/// Returns `true` if the lockfile contains no packages.
pub fn is_empty(&self) -> bool {
self.packages.is_empty()
}
/// Returns the [`Package`] entries in this lock.
pub fn packages(&self) -> &[Package] {
&self.packages
}
/// Returns the owned [`Package`] entries in this lock.
pub fn into_packages(self) -> Vec<Package> {
self.packages
}
/// Returns the supported Python version range for the lockfile, if present.
pub fn requires_python(&self) -> Option<&RequiresPython> {
self.requires_python.as_ref()
}
/// Returns the resolution mode used to generate this lock.
pub fn resolution_mode(&self) -> ResolutionMode {
self.options.resolution_mode
}
/// Returns the pre-release mode used to generate this lock.
pub fn prerelease_mode(&self) -> PrereleaseMode {
self.options.prerelease_mode
}
/// Returns the exclude newer setting used to generate this lock.
pub fn exclude_newer(&self) -> Option<ExcludeNewer> {
self.options.exclude_newer
}
/// If this lockfile was built from a forking resolution with non-identical forks, return the
/// markers of those forks, otherwise `None`.
pub fn fork_markers(&self) -> &[MarkerTree] {
self.fork_markers.as_slice()
}
/// Convert the [`Lock`] to a [`Resolution`] using the given marker environment, tags, and root.
pub fn to_resolution(
&self,
project: &VirtualProject,
marker_env: &MarkerEnvironment,
tags: &Tags,
extras: &ExtrasSpecification,
dev: &[GroupName],
) -> Result<Resolution, LockError> {
let mut queue: VecDeque<(&Package, Option<&ExtraName>)> = VecDeque::new();
let mut seen = FxHashSet::default();
// Add the workspace packages to the queue.
for root_name in project.packages() {
let root = self
.find_by_name(root_name)
.expect("found too many packages matching root")
.expect("could not find root");
// Add the base package.
queue.push_back((root, None));
// Add any extras.
match extras {
ExtrasSpecification::None => {}
ExtrasSpecification::All => {
for extra in root.optional_dependencies.keys() {
queue.push_back((root, Some(extra)));
}
}
ExtrasSpecification::Some(extras) => {
for extra in extras {
queue.push_back((root, Some(extra)));
}
}
}
}
// Add any dependency groups that are exclusive to the workspace root (e.g., dev
// dependencies in virtual workspaces).
for group in dev {
for dependency in project.group(group) {
let root = self
.find_by_name(dependency)
.expect("found too many packages matching root")
.expect("could not find root");
queue.push_back((root, None));
}
}
let mut map = BTreeMap::default();
let mut hashes = BTreeMap::default();
while let Some((dist, extra)) = queue.pop_front() {
let deps =
if let Some(extra) = extra {
Either::Left(dist.optional_dependencies.get(extra).into_iter().flatten())
} else {
Either::Right(dist.dependencies.iter().chain(
dev.iter().flat_map(|group| {
dist.dev_dependencies.get(group).into_iter().flatten()
}),
))
};
for dep in deps {
if dep.marker.evaluate(marker_env, &[]) {
let dep_dist = self.find_by_id(&dep.package_id);
if seen.insert((&dep.package_id, None)) {
queue.push_back((dep_dist, None));
}
for extra in &dep.extra {
if seen.insert((&dep.package_id, Some(extra))) {
queue.push_back((dep_dist, Some(extra)));
}
}
}
}
map.insert(
dist.id.name.clone(),
ResolvedDist::Installable(dist.to_dist(project.workspace().install_path(), tags)?),
);
hashes.insert(dist.id.name.clone(), dist.hashes());
}
let diagnostics = vec![];
Ok(Resolution::new(map, hashes, diagnostics))
}
/// Returns the TOML representation of this lockfile.
pub fn to_toml(&self) -> anyhow::Result<String> {
// We construct a TOML document manually instead of going through Serde to enable
// the use of inline tables.
let mut doc = toml_edit::DocumentMut::new();
doc.insert("version", value(i64::from(self.version)));
if let Some(ref requires_python) = self.requires_python {
doc.insert("requires-python", value(requires_python.to_string()));
}
if !self.fork_markers.is_empty() {
let fork_markers = each_element_on_its_line_array(
self.fork_markers
.iter()
.filter_map(MarkerTree::contents)
.map(|marker| marker.to_string()),
);
doc.insert("environment-markers", value(fork_markers));
}
// Write the settings that were used to generate the resolution.
// This enables us to invalidate the lockfile if the user changes
// their settings.
{
let mut options_table = Table::new();
if self.options.resolution_mode != ResolutionMode::default() {
options_table.insert(
"resolution-mode",
value(self.options.resolution_mode.to_string()),
);
}
if self.options.prerelease_mode != PrereleaseMode::default() {
options_table.insert(
"prerelease-mode",
value(self.options.prerelease_mode.to_string()),
);
}
if let Some(exclude_newer) = self.options.exclude_newer {
options_table.insert("exclude-newer", value(exclude_newer.to_string()));
}
if !options_table.is_empty() {
doc.insert("options", Item::Table(options_table));
}
}
// Write the manifest that was used to generate the resolution.
{
let mut manifest_table = Table::new();
if !self.manifest.members.is_empty() {
manifest_table.insert(
"members",
value(each_element_on_its_line_array(
self.manifest
.members
.iter()
.map(std::string::ToString::to_string),
)),
);
}
if !self.manifest.constraints.is_empty() {
let constraints = self
.manifest
.constraints
.iter()
.map(|requirement| {
serde::Serialize::serialize(
&requirement,
toml_edit::ser::ValueSerializer::new(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let constraints = match constraints.as_slice() {
[] => Array::new(),
[requirement] => Array::from_iter([requirement]),
constraints => each_element_on_its_line_array(constraints.iter()),
};
manifest_table.insert("constraints", value(constraints));
}
if !self.manifest.overrides.is_empty() {
let overrides = self
.manifest
.overrides
.iter()
.map(|requirement| {
serde::Serialize::serialize(
&requirement,
toml_edit::ser::ValueSerializer::new(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let overrides = match overrides.as_slice() {
[] => Array::new(),
[requirement] => Array::from_iter([requirement]),
overrides => each_element_on_its_line_array(overrides.iter()),
};
manifest_table.insert("overrides", value(overrides));
}
if !manifest_table.is_empty() {
doc.insert("manifest", Item::Table(manifest_table));
}
}
// Count the number of packages for each package name. When
// there's only one package for a particular package name (the
// overwhelmingly common case), we can omit some data (like source and
// version) on dependency edges since it is strictly redundant.
let mut dist_count_by_name: FxHashMap<PackageName, u64> = FxHashMap::default();
for dist in &self.packages {
*dist_count_by_name.entry(dist.id.name.clone()).or_default() += 1;
}
let mut packages = ArrayOfTables::new();
for dist in &self.packages {
packages.push(dist.to_toml(&dist_count_by_name)?);
}
doc.insert("package", Item::ArrayOfTables(packages));
Ok(doc.to_string())
}
/// Returns the package with the given name. If there are multiple
/// matching packages, then an error is returned. If there are no
/// matching packages, then `Ok(None)` is returned.
fn find_by_name(&self, name: &PackageName) -> Result<Option<&Package>, String> {
let mut found_dist = None;
for dist in &self.packages {
if &dist.id.name == name {
if found_dist.is_some() {
return Err(format!("found multiple packages matching `{name}`"));
}
found_dist = Some(dist);
}
}
Ok(found_dist)
}
fn find_by_id(&self, id: &PackageId) -> &Package {
let index = *self.by_id.get(id).expect("locked package for ID");
let dist = self.packages.get(index).expect("valid index for package");
dist
}
/// Convert the [`Lock`] to a [`Resolution`] using the given marker environment, tags, and root.
pub async fn satisfies<Context: BuildContext>(
&self,
workspace: &Workspace,
members: &[PackageName],
constraints: &[Requirement],
overrides: &[Requirement],
indexes: Option<&IndexLocations>,
tags: &Tags,
database: &DistributionDatabase<'_, Context>,
) -> Result<SatisfiesResult<'_>, LockError> {
let mut queue: VecDeque<&Package> = VecDeque::new();
let mut seen = FxHashSet::default();
// Validate that the lockfile was generated with the same root members.
{
let expected = members.iter().cloned().collect::<BTreeSet<_>>();
let actual = &self.manifest.members;
if expected != *actual {
debug!(
"Mismatched members:\n expected: {:?}\n found: {:?}",
expected, actual
);
return Ok(SatisfiesResult::MismatchedMembers(expected, actual));
}
}
// Validate that the lockfile was generated with the same constraints.
{
let expected: BTreeSet<_> = constraints
.iter()
.cloned()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect();
let actual: BTreeSet<_> = self
.manifest
.constraints
.iter()
.cloned()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect();
if expected != actual {
debug!(
"Mismatched constraints:\n expected: {:?}\n found: {:?}",
expected, actual
);
return Ok(SatisfiesResult::MismatchedConstraints(expected, actual));
}
}
// Validate that the lockfile was generated with the same overrides.
{
let expected: BTreeSet<_> = overrides
.iter()
.cloned()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect();
let actual: BTreeSet<_> = self
.manifest
.overrides
.iter()
.cloned()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect();
if expected != actual {
debug!(
"Mismatched overrides:\n expected: {:?}\n found: {:?}",
expected, actual
);
return Ok(SatisfiesResult::MismatchedOverrides(expected, actual));
}
}
// Collect the set of available indexes (both `--index-url` and `--find-links` entries).
let indexes = indexes.map(|locations| {
locations
.indexes()
.map(IndexUrl::redacted)
.chain(locations.flat_index().map(FlatIndexLocation::redacted))
.map(UrlString::from)
.collect::<BTreeSet<_>>()
});
// Add the workspace packages to the queue.
for root_name in workspace.packages().keys() {
let root = self
.find_by_name(root_name)
.expect("found too many packages matching root");
let Some(root) = root else {
// The package is not in the lockfile, so it can't be satisfied.
debug!("Workspace package `{root_name}` not found in lockfile");
return Ok(SatisfiesResult::MissingRoot(root_name.clone()));
};
// Add the base package.
queue.push_back(root);
}
while let Some(package) = queue.pop_front() {
// If the lockfile references an index that was not provided, we can't validate it.
if let Source::Registry(index) = &package.id.source {
if indexes
.as_ref()
.is_some_and(|indexes| !indexes.contains(index))
{
return Ok(SatisfiesResult::MissingIndex(
&package.id.name,
&package.id.version,
index,
));
}
}
// If the package is immutable, we don't need to validate it (or its dependencies).
if package.id.source.is_immutable() {
continue;
}
// Get the metadata for the distribution.
let dist = package.to_dist(workspace.install_path(), tags)?;
let Ok(archive) = database
.get_or_build_wheel_metadata(&dist, HashPolicy::None)
.await
else {
debug!("Failed to get metadata for: {}", package.id);
return Ok(SatisfiesResult::MissingMetadata(
&package.id.name,
&package.id.version,
));
};
// Validate the `requires-dist` metadata.
{
let expected: BTreeSet<_> = archive
.metadata
.requires_dist
.into_iter()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect();
let actual: BTreeSet<_> = package
.metadata
.requires_dist
.iter()
.cloned()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect();
if expected != actual {
debug!(
"Mismatched `requires-dist` for {}:\n expected: {:?}\n found: {:?}",
package.id, expected, actual
);
return Ok(SatisfiesResult::MismatchedRequiresDist(
&package.id.name,
&package.id.version,
expected,
actual,
));
}
}
// Validate the `dev-dependencies` metadata.
{
let expected: BTreeMap<GroupName, BTreeSet<Requirement>> = archive
.metadata
.dev_dependencies
.into_iter()
.map(|(group, requirements)| {
(
group,
requirements
.into_iter()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect(),
)
})
.collect();
let actual: BTreeMap<GroupName, BTreeSet<Requirement>> = package
.metadata
.requires_dev
.iter()
.map(|(group, requirements)| {
(
group.clone(),
requirements
.iter()
.cloned()
.map(|requirement| normalize_requirement(requirement, workspace))
.collect(),
)
})
.collect();
if expected != actual {
debug!(
"Mismatched `requires-dev` for {}:\n expected: {:?}\n found: {:?}",
package.id, expected, actual
);
return Ok(SatisfiesResult::MismatchedDevDependencies(
&package.id.name,
&package.id.version,
expected,
actual,
));
}
}
// Recurse.
// TODO(charlie): Do we care about extras here, or any other fields on the `Dependency`?
// Should we instead recurse on `requires_dist`?
for dep in &package.dependencies {
if seen.insert(&dep.package_id) {
let dep_dist = self.find_by_id(&dep.package_id);
queue.push_back(dep_dist);
}
}
for dependencies in package.optional_dependencies.values() {
for dep in dependencies {
if seen.insert(&dep.package_id) {
let dep_dist = self.find_by_id(&dep.package_id);
queue.push_back(dep_dist);
}
}
}
for dependencies in package.dev_dependencies.values() {
for dep in dependencies {
if seen.insert(&dep.package_id) {
let dep_dist = self.find_by_id(&dep.package_id);
queue.push_back(dep_dist);
}
}
}
}
Ok(SatisfiesResult::Satisfied)
}
}
/// The result of checking if a lockfile satisfies a set of requirements.
#[derive(Debug)]
pub enum SatisfiesResult<'lock> {
/// The lockfile satisfies the requirements.
Satisfied,
/// The lockfile uses a different set of workspace members.
MismatchedMembers(BTreeSet<PackageName>, &'lock BTreeSet<PackageName>),
/// The lockfile uses a different set of constraints.
MismatchedConstraints(BTreeSet<Requirement>, BTreeSet<Requirement>),
/// The lockfile uses a different set of overrides.
MismatchedOverrides(BTreeSet<Requirement>, BTreeSet<Requirement>),
/// The lockfile is missing a workspace member.
MissingRoot(PackageName),
/// The lockfile referenced an index that was not provided
MissingIndex(&'lock PackageName, &'lock Version, &'lock UrlString),
/// The resolver failed to generate metadata for a given package.
MissingMetadata(&'lock PackageName, &'lock Version),
/// A package in the lockfile contains different `requires-dist` metadata than expected.
MismatchedRequiresDist(
&'lock PackageName,
&'lock Version,
BTreeSet<Requirement>,
BTreeSet<Requirement>,
),
/// A package in the lockfile contains different `dev-dependencies` metadata than expected.
MismatchedDevDependencies(
&'lock PackageName,
&'lock Version,
BTreeMap<GroupName, BTreeSet<Requirement>>,
BTreeMap<GroupName, BTreeSet<Requirement>>,
),
}
/// We discard the lockfile if these options match.
#[derive(Clone, Debug, Default, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
struct ResolverOptions {
/// The [`ResolutionMode`] used to generate this lock.
#[serde(default)]
resolution_mode: ResolutionMode,
/// The [`PrereleaseMode`] used to generate this lock.
#[serde(default)]
prerelease_mode: PrereleaseMode,
/// The [`ExcludeNewer`] used to generate this lock.
exclude_newer: Option<ExcludeNewer>,
}
#[derive(Clone, Debug, Default, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub struct ResolverManifest {
/// The workspace members included in the lockfile.
#[serde(default)]
members: BTreeSet<PackageName>,
/// The constraints provided to the resolver.
#[serde(default)]
constraints: BTreeSet<Requirement>,
/// The overrides provided to the resolver.
#[serde(default)]
overrides: BTreeSet<Requirement>,
}
impl ResolverManifest {
pub fn new(
members: impl IntoIterator<Item = PackageName>,
constraints: impl IntoIterator<Item = Requirement>,
overrides: impl IntoIterator<Item = Requirement>,
) -> Self {
Self {
members: members.into_iter().collect(),
constraints: constraints.into_iter().collect(),
overrides: overrides.into_iter().collect(),
}
}
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
struct LockWire {
version: u32,
#[serde(default)]
requires_python: Option<RequiresPython>,
/// If this lockfile was built from a forking resolution with non-identical forks, store the
/// forks in the lockfile so we can recreate them in subsequent resolutions.
#[serde(rename = "environment-markers", default)]
fork_markers: Vec<MarkerTree>,
/// We discard the lockfile if these options match.
#[serde(default)]
options: ResolverOptions,
#[serde(default)]
manifest: ResolverManifest,
#[serde(rename = "package", alias = "distribution", default)]
packages: Vec<PackageWire>,
}
impl From<Lock> for LockWire {
fn from(lock: Lock) -> LockWire {
LockWire {
version: lock.version,
requires_python: lock.requires_python,
fork_markers: lock.fork_markers,
options: lock.options,
manifest: lock.manifest,
packages: lock.packages.into_iter().map(PackageWire::from).collect(),
}
}
}
impl TryFrom<LockWire> for Lock {
type Error = LockError;
fn try_from(wire: LockWire) -> Result<Lock, LockError> {
// Count the number of sources for each package name. When
// there's only one source for a particular package name (the
// overwhelmingly common case), we can omit some data (like source and
// version) on dependency edges since it is strictly redundant.
let mut unambiguous_package_ids: FxHashMap<PackageName, PackageId> = FxHashMap::default();
let mut ambiguous = FxHashSet::default();
for dist in &wire.packages {
if ambiguous.contains(&dist.id.name) {
continue;
}
if unambiguous_package_ids.remove(&dist.id.name).is_some() {
ambiguous.insert(dist.id.name.clone());
continue;
}
unambiguous_package_ids.insert(dist.id.name.clone(), dist.id.clone());
}
let packages = wire
.packages
.into_iter()
.map(|dist| dist.unwire(&unambiguous_package_ids))