-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathmod.rs
More file actions
6981 lines (6507 loc) · 264 KB
/
Copy pathmod.rs
File metadata and controls
6981 lines (6507 loc) · 264 KB
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::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use itertools::Itertools;
use jiff::Timestamp;
use owo_colors::OwoColorize;
use petgraph::graph::NodeIndex;
use petgraph::visit::EdgeRef;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use serde::Serializer;
use toml_edit::{Array, ArrayOfTables, InlineTable, Item, Table, Value, value};
use tracing::{debug, instrument, trace};
use url::Url;
use uv_cache_key::RepositoryUrl;
use uv_configuration::{
BuildOptions, Constraints, DependencyGroupsWithDefaults, ExtrasSpecificationWithDefaults,
InstallTarget,
};
use uv_distribution::{DistributionDatabase, FlatRequiresDist};
use uv_distribution_filename::{
BuildTag, DistExtension, ExtensionError, SourceDistExtension, WheelFilename,
};
use uv_distribution_types::{
BuiltDist, DependencyMetadata, DirectUrlBuiltDist, DirectUrlSourceDist, DirectorySourceDist,
Dist, FileLocation, GitSourceDist, Identifier, IndexLocations, IndexMetadata, IndexUrl, Name,
PathBuiltDist, PathSourceDist, RegistryBuiltDist, RegistryBuiltWheel, RegistrySourceDist,
RemoteSource, Requirement, RequirementSource, RequiresPython, ResolvedDist,
SimplifiedMarkerTree, StaticMetadata, ToUrlError, UrlString,
};
use uv_fs::{PortablePath, PortablePathBuf, Simplified, normalize_path, try_relative_to_if};
use uv_git::{RepositoryReference, ResolvedRepositoryReference};
use uv_git_types::{GitLfs, GitOid, GitReference, GitUrl, GitUrlParseError};
use uv_normalize::{ExtraName, GroupName, PackageName};
use uv_pep440::Version;
use uv_pep508::{
MarkerEnvironment, MarkerTree, Scheme, VerbatimUrl, VerbatimUrlError, split_scheme,
};
use uv_platform_tags::{
AbiTag, IncompatibleTag, LanguageTag, PlatformTag, TagCompatibility, TagPriority, Tags,
};
use uv_pypi_types::{
ConflictKind, Conflicts, HashAlgorithm, HashDigest, HashDigests, Hashes, ParsedArchiveUrl,
ParsedGitUrl, PyProjectToml,
};
use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
use uv_small_str::SmallString;
use uv_types::{BuildContext, HashStrategy};
use uv_workspace::{Editability, WorkspaceMember};
use crate::fork_strategy::ForkStrategy;
pub(crate) use crate::lock::export::PylockTomlPackage;
pub use crate::lock::export::RequirementsTxtExport;
pub use crate::lock::export::{Metadata, PylockToml, PylockTomlErrorKind, cyclonedx_json};
pub use crate::lock::installable::Installable;
pub use crate::lock::map::PackageMap;
pub use crate::lock::tree::TreeDisplay;
use crate::resolution::{AnnotatedDist, ResolutionGraphNode};
use crate::universal_marker::{ConflictMarker, UniversalMarker};
use crate::{
ExcludeNewer, ExcludeNewerOverride, ExcludeNewerPackage, ExcludeNewerSpan, ExcludeNewerValue,
InMemoryIndex, MetadataResponse, PrereleaseMode, ResolutionMode, ResolverOutput,
};
mod export;
mod installable;
mod map;
mod tree;
/// The current version of the lockfile format.
pub const VERSION: u32 = 1;
/// The current revision of the lockfile format.
const REVISION: u32 = 3;
static LINUX_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("os_name == 'posix' and sys_platform == 'linux'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static WINDOWS_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("os_name == 'nt' and sys_platform == 'win32'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static MAC_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("os_name == 'posix' and sys_platform == 'darwin'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static ANDROID_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("sys_platform == 'android'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 =
MarkerTree::from_str("platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ARM64'")
.unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 =
MarkerTree::from_str("platform_machine == 'x86_64' or platform_machine == 'amd64' or platform_machine == 'AMD64'")
.unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str(
"platform_machine == 'i686' or platform_machine == 'i386' or platform_machine == 'win32' or platform_machine == 'x86'",
)
.unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static PPC64LE_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("platform_machine == 'ppc64le'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static PPC64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("platform_machine == 'ppc64'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static S390X_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("platform_machine == 's390x'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static RISCV64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("platform_machine == 'riscv64'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static LOONGARCH64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("platform_machine == 'loongarch64'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static ARMV7L_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 =
MarkerTree::from_str("platform_machine == 'armv7l' or platform_machine == 'armv8l'")
.unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static ARMV6L_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let pep508 = MarkerTree::from_str("platform_machine == 'armv6l'").unwrap();
UniversalMarker::new(pep508, ConflictMarker::TRUE)
});
static LINUX_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*ARM_MARKERS);
marker
});
static LINUX_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*X86_64_MARKERS);
marker
});
static LINUX_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*X86_MARKERS);
marker
});
static LINUX_PPC64LE_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*PPC64LE_MARKERS);
marker
});
static LINUX_PPC64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*PPC64_MARKERS);
marker
});
static LINUX_S390X_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*S390X_MARKERS);
marker
});
static LINUX_RISCV64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*RISCV64_MARKERS);
marker
});
static LINUX_LOONGARCH64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*LOONGARCH64_MARKERS);
marker
});
static LINUX_ARMV7L_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*ARMV7L_MARKERS);
marker
});
static LINUX_ARMV6L_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *LINUX_MARKERS;
marker.and(*ARMV6L_MARKERS);
marker
});
static WINDOWS_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *WINDOWS_MARKERS;
marker.and(*ARM_MARKERS);
marker
});
static WINDOWS_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *WINDOWS_MARKERS;
marker.and(*X86_64_MARKERS);
marker
});
static WINDOWS_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *WINDOWS_MARKERS;
marker.and(*X86_MARKERS);
marker
});
static MAC_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *MAC_MARKERS;
marker.and(*ARM_MARKERS);
marker
});
static MAC_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *MAC_MARKERS;
marker.and(*X86_64_MARKERS);
marker
});
static MAC_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *MAC_MARKERS;
marker.and(*X86_MARKERS);
marker
});
static ANDROID_ARM_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *ANDROID_MARKERS;
marker.and(*ARM_MARKERS);
marker
});
static ANDROID_X86_64_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *ANDROID_MARKERS;
marker.and(*X86_64_MARKERS);
marker
});
static ANDROID_X86_MARKERS: LazyLock<UniversalMarker> = LazyLock::new(|| {
let mut marker = *ANDROID_MARKERS;
marker.and(*X86_MARKERS);
marker
});
/// A distribution with its associated hash.
///
/// This pairs a [`Dist`] with the [`HashDigests`] for the specific wheel or
/// sdist that would be installed.
pub(crate) struct HashedDist {
pub(crate) dist: Dist,
pub(crate) hashes: HashDigests,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(try_from = "LockWire")]
pub struct Lock {
/// The (major) version of the lockfile format.
///
/// Changes to the major version indicate backwards- and forwards-incompatible changes to the
/// lockfile format. A given uv version only supports a single major version of the lockfile
/// format.
///
/// In other words, a version of uv that supports version 2 of the lockfile format will not be
/// able to read lockfiles generated under version 1 or 3.
version: u32,
/// The revision of the lockfile format.
///
/// Changes to the revision indicate backwards-compatible changes to the lockfile format.
/// In other words, versions of uv that only support revision 1 _will_ be able to read lockfiles
/// with a revision greater than 1 (though they may ignore newer fields).
revision: 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<UniversalMarker>,
/// The conflicting groups/extras specified by the user.
conflicts: Conflicts,
/// The list of supported environments specified by the user.
supported_environments: Vec<MarkerTree>,
/// The list of required platforms specified by the user.
required_environments: Vec<MarkerTree>,
/// The range of supported Python versions.
requires_python: 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 [`ResolverOutput`].
pub fn from_resolution(
resolution: &ResolverOutput,
root: &Path,
supported_environments: Vec<MarkerTree>,
) -> Result<Self, LockError> {
let mut packages = BTreeMap::new();
let requires_python = resolution.requires_python.clone();
let supported_environments = supported_environments
.into_iter()
.map(|marker| requires_python.complexify_markers(marker))
.collect::<Vec<_>>();
let supported_environments_marker = if supported_environments.is_empty() {
None
} else {
let mut combined = MarkerTree::FALSE;
for marker in &supported_environments {
combined.or(*marker);
}
Some(UniversalMarker::new(combined, ConflictMarker::TRUE))
};
// Determine the set of packages included at multiple versions.
let mut seen = FxHashSet::default();
let mut duplicates = FxHashSet::default();
for node_index in resolution.graph.node_indices() {
let ResolutionGraphNode::Dist(dist) = &resolution.graph[node_index] else {
continue;
};
if !dist.is_base() {
continue;
}
if !seen.insert(dist.name()) {
duplicates.insert(dist.name());
}
}
// Lock all base packages.
for node_index in resolution.graph.node_indices() {
let ResolutionGraphNode::Dist(dist) = &resolution.graph[node_index] else {
continue;
};
if !dist.is_base() {
continue;
}
// If there are multiple distributions for the same package, include the markers of all
// forks that included the current distribution.
//
// Canonicalize the subset of fork markers that selected this distribution to
// match the form persisted in `uv.lock`.
let fork_markers = if duplicates.contains(dist.name()) {
let fork_markers = resolution
.fork_markers
.iter()
.filter(|fork_markers| !fork_markers.is_disjoint(dist.marker))
.copied()
.collect::<Vec<_>>();
canonicalize_universal_markers(&fork_markers, &requires_python)
} else {
vec![]
};
let mut package = Package::from_annotated_dist(dist, fork_markers, root)?;
let mut wheel_marker = dist.marker;
if let Some(supported_environments_marker) = supported_environments_marker {
wheel_marker.and(supported_environments_marker);
}
let wheels = &mut package.wheels;
wheels.retain(|wheel| {
!is_wheel_unreachable_for_marker(
&wheel.filename,
&requires_python,
&wheel_marker,
None,
)
});
// Add all dependencies
for edge in resolution.graph.edges(node_index) {
let ResolutionGraphNode::Dist(dependency_dist) = &resolution.graph[edge.target()]
else {
continue;
};
let marker = *edge.weight();
package.add_dependency(&requires_python, dependency_dist, marker, root)?;
}
let id = package.id.clone();
if let Some(locked_dist) = packages.insert(id, package) {
return Err(LockErrorKind::DuplicatePackage {
id: locked_dist.id.clone(),
}
.into());
}
}
// Lock all extras and development dependencies.
for node_index in resolution.graph.node_indices() {
let ResolutionGraphNode::Dist(dist) = &resolution.graph[node_index] else {
continue;
};
if let Some(extra) = dist.extra.as_ref() {
let id = PackageId::from_annotated_dist(dist, root)?;
let Some(package) = packages.get_mut(&id) else {
return Err(LockErrorKind::MissingExtraBase {
id,
extra: extra.clone(),
}
.into());
};
for edge in resolution.graph.edges(node_index) {
let ResolutionGraphNode::Dist(dependency_dist) =
&resolution.graph[edge.target()]
else {
continue;
};
let marker = *edge.weight();
package.add_optional_dependency(
&requires_python,
extra.clone(),
dependency_dist,
marker,
root,
)?;
}
}
if let Some(group) = dist.group.as_ref() {
let id = PackageId::from_annotated_dist(dist, root)?;
let Some(package) = packages.get_mut(&id) else {
return Err(LockErrorKind::MissingDevBase {
id,
group: group.clone(),
}
.into());
};
for edge in resolution.graph.edges(node_index) {
let ResolutionGraphNode::Dist(dependency_dist) =
&resolution.graph[edge.target()]
else {
continue;
};
let marker = *edge.weight();
package.add_group_dependency(
&requires_python,
group.clone(),
dependency_dist,
marker,
root,
)?;
}
}
}
let packages = packages.into_values().collect();
let options = ResolverOptions {
resolution_mode: resolution.options.resolution_mode,
prerelease_mode: resolution.options.prerelease_mode,
fork_strategy: resolution.options.fork_strategy,
exclude_newer: resolution.options.exclude_newer.clone().into(),
};
// Canonicalize the top-level fork markers to match what is persisted in
// `uv.lock`. In particular, conflict-only fork markers can serialize to
// nothing at the top level, and `uv lock --check` should compare against
// that canonical form rather than the raw resolver output.
let fork_markers =
canonicalize_universal_markers(&resolution.fork_markers, &requires_python);
let lock = Self::new(
VERSION,
REVISION,
packages,
requires_python,
options,
ResolverManifest::default(),
Conflicts::empty(),
supported_environments,
vec![],
fork_markers,
)?;
Ok(lock)
}
/// Initialize a [`Lock`] from a list of [`Package`] entries.
fn new(
version: u32,
revision: u32,
mut packages: Vec<Package>,
requires_python: RequiresPython,
options: ResolverOptions,
manifest: ResolverManifest,
conflicts: Conflicts,
supported_environments: Vec<MarkerTree>,
required_environments: Vec<MarkerTree>,
fork_markers: Vec<UniversalMarker>,
) -> 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.dependency_groups {
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());
}
}
}
}
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.dependency_groups.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.dependency_groups.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());
}
}
}
}
let lock = Self {
version,
revision,
fork_markers,
conflicts,
supported_environments,
required_environments,
requires_python,
options,
packages,
by_id,
manifest,
};
Ok(lock)
}
/// 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
}
/// Record the conflicting groups that were used to generate this lock.
#[must_use]
pub fn with_conflicts(mut self, conflicts: Conflicts) -> Self {
self.conflicts = conflicts;
self
}
/// Record the supported environments that were used to generate this lock.
#[must_use]
pub fn with_supported_environments(mut self, supported_environments: Vec<MarkerTree>) -> Self {
// We "complexify" the markers given, since the supported
// environments given might be coming directly from what's written in
// `pyproject.toml`, and those are assumed to be simplified (i.e.,
// they assume `requires-python` is true). But a `Lock` always uses
// non-simplified markers internally, so we need to re-complexify them
// here.
//
// The nice thing about complexifying is that it's a no-op if the
// markers given have already been complexified.
self.supported_environments = supported_environments
.into_iter()
.map(|marker| self.requires_python.complexify_markers(marker))
.collect();
self
}
/// Record the required platforms that were used to generate this lock.
#[must_use]
pub fn with_required_environments(mut self, required_environments: Vec<MarkerTree>) -> Self {
self.required_environments = required_environments
.into_iter()
.map(|marker| self.requires_python.complexify_markers(marker))
.collect();
self
}
/// Returns `true` if this [`Lock`] includes `provides-extra` metadata.
pub fn supports_provides_extra(&self) -> bool {
// `provides-extra` was added in Version 1 Revision 1.
(self.version(), self.revision()) >= (1, 1)
}
/// Returns `true` if this [`Lock`] includes entries for empty `dependency-group` metadata.
pub fn includes_empty_groups(&self) -> bool {
// Empty dependency groups are included as of https://github.com/astral-sh/uv/pull/8598,
// but Version 1 Revision 1 is the first revision published after that change.
(self.version(), self.revision()) >= (1, 1)
}
/// Returns the lockfile version.
pub fn version(&self) -> u32 {
self.version
}
/// Returns the lockfile revision.
pub fn revision(&self) -> u32 {
self.revision
}
/// 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 supported Python version range for the lockfile, if present.
pub fn requires_python(&self) -> &RequiresPython {
&self.requires_python
}
/// 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 multi-version mode used to generate this lock.
pub fn fork_strategy(&self) -> ForkStrategy {
self.options.fork_strategy
}
/// Returns the exclude newer setting used to generate this lock.
pub fn exclude_newer(&self) -> ExcludeNewer {
// TODO(zanieb): It'd be nice not to hide this clone here, but I am hesitant to introduce
// a whole new `ExcludeNewerRef` type just for this
self.options.exclude_newer.clone().into()
}
/// Returns the conflicting groups that were used to generate this lock.
pub fn conflicts(&self) -> &Conflicts {
&self.conflicts
}
/// Returns the supported environments that were used to generate this lock.
pub fn supported_environments(&self) -> &[MarkerTree] {
&self.supported_environments
}
/// Returns the required platforms that were used to generate this lock.
pub fn required_environments(&self) -> &[MarkerTree] {
&self.required_environments
}
/// Returns the workspace members that were used to generate this lock.
pub fn members(&self) -> &BTreeSet<PackageName> {
&self.manifest.members
}
/// Returns the dependency groups that were used to generate this lock.
pub fn requirements(&self) -> &BTreeSet<Requirement> {
&self.manifest.requirements
}
/// Returns the dependency groups that were used to generate this lock.
pub fn dependency_groups(&self) -> &BTreeMap<GroupName, BTreeSet<Requirement>> {
&self.manifest.dependency_groups
}
/// Returns the build constraints that were used to generate this lock.
pub fn build_constraints(&self, root: &Path) -> Constraints {
Constraints::from_requirements(
self.manifest
.build_constraints
.iter()
.cloned()
.map(|requirement| requirement.to_absolute(root)),
)
}
/// Returns the set of packages that should be audited, respecting the given
/// extras and dependency groups filters.
///
/// Workspace members and packages without version information are excluded
/// unconditionally, since neither can be meaningfully looked up in a
/// vulnerability database.
pub fn packages_for_audit<'lock>(
&'lock self,
extras: &'lock ExtrasSpecificationWithDefaults,
groups: &'lock DependencyGroupsWithDefaults,
) -> Vec<(&'lock PackageName, &'lock Version)> {
// Enqueue a dependency for auditability checks: base package (no extra) first, then each activated extra.
fn enqueue_dep<'lock>(
lock: &'lock Lock,
seen: &mut FxHashSet<(&'lock PackageId, Option<&'lock ExtraName>)>,
queue: &mut VecDeque<(&'lock Package, Option<&'lock ExtraName>)>,
dep: &'lock Dependency,
) {
let dep_pkg = lock.find_by_id(&dep.package_id);
for maybe_extra in std::iter::once(None).chain(dep.extra.iter().map(Some)) {
if seen.insert((&dep.package_id, maybe_extra)) {
queue.push_back((dep_pkg, maybe_extra));
}
}
}
// Identify workspace members (the implicit root counts for single-member workspaces).
let workspace_member_ids: FxHashSet<&PackageId> = if self.members().is_empty() {
self.root().into_iter().map(|package| &package.id).collect()
} else {
self.packages
.iter()
.filter(|package| self.members().contains(&package.id.name))
.map(|package| &package.id)
.collect()
};
// Lockfile traversal state: (package, optional extra to activate on that package).
let mut queue: VecDeque<(&Package, Option<&ExtraName>)> = VecDeque::new();
let mut seen: FxHashSet<(&PackageId, Option<&ExtraName>)> = FxHashSet::default();
// Seed from workspace members. Always queue with `None` so that we can traverse
// their dependency groups; only queue extras when prod mode is active.
for package in self
.packages
.iter()
.filter(|p| workspace_member_ids.contains(&p.id))
{
if seen.insert((&package.id, None)) {
queue.push_back((package, None));
}
if groups.prod() {
for extra in extras.extra_names(package.optional_dependencies.keys()) {
if seen.insert((&package.id, Some(extra))) {
queue.push_back((package, Some(extra)));
}
}
}
}
// Seed from requirements attached directly to the lock (e.g., PEP 723 scripts).
for requirement in self.requirements() {
for package in self
.packages
.iter()
.filter(|p| p.id.name == requirement.name)
{
if seen.insert((&package.id, None)) {
queue.push_back((package, None));
}
for extra in &*requirement.extras {
if seen.insert((&package.id, Some(extra))) {
queue.push_back((package, Some(extra)));
}
}
}
}
// Seed from dependency groups attached directly to the lock (e.g., project-less
// workspace roots).
for (group, requirements) in self.dependency_groups() {
if !groups.contains(group) {
continue;
}
for requirement in requirements {
for package in self
.packages
.iter()
.filter(|p| p.id.name == requirement.name)
{
if seen.insert((&package.id, None)) {
queue.push_back((package, None));
}
for extra in &*requirement.extras {
if seen.insert((&package.id, Some(extra))) {
queue.push_back((package, Some(extra)));
}
}
}
}
}
let mut auditable: BTreeSet<(&PackageName, &Version)> = BTreeSet::default();
while let Some((package, extra)) = queue.pop_front() {
let is_member = workspace_member_ids.contains(&package.id);
// Collect non-workspace packages that have version information.
if !is_member {
if let Some(version) = package.version() {
auditable.insert((package.name(), version));
} else {
trace!(
"Skipping audit for `{}` because it has no version information",
package.name()
);
}
}
// Follow allowed dependency groups.
if is_member && extra.is_none() {
for dep in package
.dependency_groups
.iter()
.filter(|(group, _)| groups.contains(group))
.flat_map(|(_, deps)| deps)
{
enqueue_dep(self, &mut seen, &mut queue, dep);
}
}
// Follow the regular/extra dependencies for this (package, extra) pair.
// For workspace members in only-group mode, skip regular dependencies.
let dependencies: &[Dependency] = match extra {
Some(extra) => package
.optional_dependencies
.get(extra)
.map(Vec::as_slice)
.unwrap_or_default(),
None if is_member && !groups.prod() => &[],
None => &package.dependencies,
};
for dep in dependencies {
enqueue_dep(self, &mut seen, &mut queue, dep);
}
}
auditable.into_iter().collect()
}
/// Return the workspace root used to generate this lock.
pub fn root(&self) -> Option<&Package> {
self.packages.iter().find(|package| {
let (Source::Editable(path) | Source::Virtual(path)) = &package.id.source else {
return false;
};
path.as_ref() == Path::new("")
})
}
/// Returns the supported environments that were used to generate this
/// lock.
///
/// The markers returned here are "simplified" with respect to the lock
/// file's `requires-python` setting. This means these should only be used
/// for direct comparison purposes with the supported environments written
/// by a human in `pyproject.toml`. (Think of "supported environments" in
/// `pyproject.toml` as having an implicit `and python_full_version >=
/// '{requires-python-bound}'` attached to each one.)
pub fn simplified_supported_environments(&self) -> Vec<MarkerTree> {
self.supported_environments()
.iter()
.copied()
.map(|marker| self.simplify_environment(marker))
.collect()
}
/// Returns the required platforms that were used to generate this
/// lock.
pub fn simplified_required_environments(&self) -> Vec<MarkerTree> {
self.required_environments()
.iter()
.copied()
.map(|marker| self.simplify_environment(marker))
.collect()
}
/// Simplify the given marker environment with respect to the lockfile's
/// `requires-python` setting.
pub fn simplify_environment(&self, marker: MarkerTree) -> MarkerTree {
self.requires_python.simplify_markers(marker)
}
/// If this lockfile was built from a forking resolution with non-identical forks, return the