Repository navigation
Expand file tree
/
Copy pathsource_record.rs
More file actions
1646 lines (1482 loc) · 60.4 KB
/
Copy pathsource_record.rs
File metadata and controls
1646 lines (1482 loc) · 60.4 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
//! Source records for conda packages that require building from source.
//!
//! # Full vs Partial vs Unresolved
//!
//! Source records exist in three states:
//!
//! - **Full** ([`FullSourceRecord`]): all metadata is available (package record,
//! dependencies, sources). Safe to use for building and installing.
//! - **Partial** ([`PartialSourceRecord`]): only minimal metadata (name, depends,
//! sources). Produced when a *mutable* (path-based) source is written to the
//! lock file, because the full metadata would be stale by the next read.
//! - **Unresolved** ([`UnresolvedSourceRecord`]): may be either full or partial.
//! This is what the lock file produces on read.
//!
//! # State transitions
//!
//! ```text
//! Lock-file write: FullSourceRecord ──► Partial (if mutable source)
//! ──► Full (if immutable source, e.g. git)
//!
//! Lock-file read: ──► UnresolvedSourceRecord (Full or Partial)
//!
//! Startup resolve: UnresolvedSourceRecord ──► FullSourceRecord
//! (re-evaluates source metadata for partial records)
//! ```
//!
//! Use [`SourceRecord::map_data`] and [`SourceRecord::try_map_data`] for clean
//! state transitions without field-by-field reconstruction.
use pixi_git::sha::GitSha;
use pixi_spec::{GitReference, SourceLocationSpec};
use rattler_conda_types::{
Flag, MatchSpec, Matches, NamelessMatchSpec, PackageName, PackageRecord, PackageUrl,
package::RunExportsJson,
};
use rattler_lock::{
CondaSourceData, GitShallowSpec, PackageBuildSource, PartialSourceMetadata, SourceData,
SourceMetadata,
};
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::{
collections::{BTreeMap, BTreeSet},
path::Path,
str::FromStr,
};
use typed_path::Utf8TypedPathBuf;
use crate::{
ParseLockFileError, PinnedGitCheckout, PinnedGitSpec, PinnedPathSpec, PinnedSourceSpec,
PinnedUrlSpec, VariantValue,
};
/// Length of the hex-encoded identifier hash that disambiguates source
/// records at the same `(name, location)`.
const IDENTIFIER_HASH_LENGTH: usize = 8;
/// Compute the short hex identifier hash for a source record.
///
/// The identifier hash is a content-derived discriminator used by the lock
/// file's `name[hash] @ location` form to distinguish two records that share
/// a name and source location but differ in variants, build/host
/// environments, or other configuration. The exact algorithm is an internal
/// pixi detail and the hash is round-tripped verbatim through the lock file,
/// but satisfiability recomputes it for immutable source records and compares
/// it against the stored value: any change to the algorithm or its inputs
/// therefore invalidates such locked records once, surfacing as a one-time
/// re-lock (or a hard error under `--locked`) after a pixi upgrade.
///
/// Children's identifiers are looked up via their own `identifier_hash`
/// (source) or location (binary), so callers must compute hashes bottom-up:
/// every record reachable through `build_packages` / `host_packages` must
/// already carry its `identifier_hash`.
pub fn compute_identifier_hash<D: HashIdentifyingData>(
manifest_source: &PinnedSourceSpec,
build_source: Option<&PinnedBuildSourceSpec>,
variants: &BTreeMap<String, VariantValue>,
data: &D,
build_packages: &[crate::UnresolvedPixiRecord],
host_packages: &[crate::UnresolvedPixiRecord],
inline_content_hash: Option<u64>,
) -> String {
let mut hasher = xxhash_rust::xxh3::Xxh3::default();
manifest_source.hash(&mut hasher);
build_source.hash(&mut hasher);
variants.hash(&mut hasher);
hash_dep_records(&mut hasher, build_packages);
hash_dep_records(&mut hasher, host_packages);
data.hash_identifying(&mut hasher);
// An inline package definition is not represented on disk, so
// it must enter the identity explicitly. Editing the inline table changes
// this hash, which marks the locked record as outdated and forces a rebuild.
inline_content_hash.hash(&mut hasher);
format_short_hash(hasher.finish())
}
/// Hash a sequence of build/host dependency records by the *minimal* identity
/// we need to tell them apart in a parent's identifier: location for binary,
/// `name + manifest_source + identifier_hash` for source. The full record
/// contents are intentionally not visited — each child's `identifier_hash`
/// already encapsulates them.
///
/// The order of the slice is not part of the identity: the lock file
/// normalizes the order of build/host package references, so the solve-time
/// order is not reproducible after a round trip. Each record is hashed into
/// its own digest and the sorted digests are folded in, so the same set of
/// records always produces the same hash.
fn hash_dep_records<H: Hasher>(hasher: &mut H, records: &[crate::UnresolvedPixiRecord]) {
// Random constants separating the binary and source hash domains, so the
// two variants can never produce identical byte streams.
const BINARY_RECORD_TAG: u64 = 0x7c48_a5e3_91d6_0bf2;
const SOURCE_RECORD_TAG: u64 = 0xe19b_3d70_246c_f58a;
let mut digests: Vec<u64> = records
.iter()
.map(|record| {
let mut record_hasher = xxhash_rust::xxh3::Xxh3::default();
match record {
crate::UnresolvedPixiRecord::Binary(binary) => {
BINARY_RECORD_TAG.hash(&mut record_hasher);
binary.url.as_str().hash(&mut record_hasher);
}
crate::UnresolvedPixiRecord::Source(source) => {
SOURCE_RECORD_TAG.hash(&mut record_hasher);
source.name().as_source().hash(&mut record_hasher);
source.manifest_source.hash(&mut record_hasher);
source.identifier_hash.hash(&mut record_hasher);
}
}
record_hasher.finish()
})
.collect();
digests.sort_unstable();
digests.len().hash(hasher);
for digest in digests {
digest.hash(hasher);
}
}
fn format_short_hash(hash: u64) -> String {
let hex = format!("{hash:016x}");
hex[..IDENTIFIER_HASH_LENGTH].to_string()
}
/// The subset of a source record's data fields that contribute to its
/// identifier hash. Implemented per data variant so [`compute_identifier_hash`]
/// stays generic over full/partial/unresolved records.
pub trait HashIdentifyingData {
fn hash_identifying<H: Hasher>(&self, hasher: &mut H);
}
impl HashIdentifyingData for FullSourceRecordData {
fn hash_identifying<H: Hasher>(&self, hasher: &mut H) {
let pr = &self.package_record;
pr.version.hash(hasher);
pr.build.hash(hasher);
pr.build_number.hash(hasher);
pr.subdir.hash(hasher);
pr.noarch.hash(hasher);
pr.depends.hash(hasher);
pr.constrains.hash(hasher);
pr.extra_depends.hash(hasher);
pr.flags.hash(hasher);
pr.purls.hash(hasher);
self.sources.hash(hasher);
}
}
impl HashIdentifyingData for PartialSourceRecordData {
fn hash_identifying<H: Hasher>(&self, hasher: &mut H) {
self.depends.hash(hasher);
self.constrains.hash(hasher);
self.experimental_extra_depends.hash(hasher);
self.flags.hash(hasher);
self.purls.hash(hasher);
self.sources.hash(hasher);
}
}
impl HashIdentifyingData for SourceRecordData {
fn hash_identifying<H: Hasher>(&self, hasher: &mut H) {
match self {
SourceRecordData::Full(full) => full.hash_identifying(hasher),
SourceRecordData::Partial(partial) => partial.hash_identifying(hasher),
}
}
}
/// Represents a pinned build source with information about how it was originally specified in the
/// manifest.
///
/// When a build source is specified as a relative path (e.g., `../src`), we preserve the original
/// relative path for lock file serialization. Without this, we couldn't distinguish between a path
/// that was originally relative vs. absolute when the resolved path lies outside the workspace.
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PinnedBuildSourceSpec {
Absolute(PinnedSourceSpec),
Relative(String, PinnedSourceSpec),
}
impl Display for PinnedBuildSourceSpec {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Absolute(spec) => write!(f, "{spec}"),
Self::Relative(relative, spec) => write!(f, "{spec} ({relative})"),
}
}
}
impl PinnedBuildSourceSpec {
pub fn pinned(&self) -> &PinnedSourceSpec {
match self {
PinnedBuildSourceSpec::Absolute(pinned) => pinned,
PinnedBuildSourceSpec::Relative(_, pinned) => pinned,
}
}
pub fn into_pinned(self) -> PinnedSourceSpec {
match self {
PinnedBuildSourceSpec::Absolute(pinned) => pinned,
PinnedBuildSourceSpec::Relative(_, pinned) => pinned,
}
}
pub fn pinned_mut(&mut self) -> &mut PinnedSourceSpec {
match self {
PinnedBuildSourceSpec::Absolute(pinned) => pinned,
PinnedBuildSourceSpec::Relative(_, pinned) => pinned,
}
}
}
impl From<PinnedBuildSourceSpec> for PinnedSourceSpec {
fn from(pinned: PinnedBuildSourceSpec) -> Self {
pinned.into_pinned()
}
}
/// A record of a conda package that still requires building.
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SourceRecord<D> {
/// Information about the conda package.
pub data: D,
/// Exact definition of the source of the package.
pub manifest_source: PinnedSourceSpec,
/// The optional pinned source where the build should be executed
/// This is used when the manifest is not in the same location as the
/// source files.
pub build_source: Option<PinnedBuildSourceSpec>,
/// The variants that uniquely identify the way this package was built.
pub variants: BTreeMap<String, VariantValue>,
/// The short hash that disambiguates two records at the same `(name,
/// location)` — the `9f3c2a7b` part of `numba-cuda[9f3c2a7b] @ .`.
///
/// Every constructor must fill this. Compute it via
/// [`compute_identifier_hash`] (or [`SourceRecord::compute_identifier_hash`])
/// after the rest of the record is assembled, after children in
/// `build_packages` / `host_packages` already carry their own hashes.
pub identifier_hash: String,
/// Packages in the build environment used to build this source package
/// (compilers, build tools, etc.), as recorded in the lock file.
///
/// Skipped by serde: `UnresolvedPixiRecord` does not implement
/// `Serialize`/`Deserialize`; the canonical form lives in the lock file
/// via `rattler_lock::SourceData`'s package index sets, and callers
/// resolve them when building the in-memory record.
#[serde(skip)]
pub build_packages: Vec<crate::UnresolvedPixiRecord>,
/// Packages in the host environment used to build this source package
/// (libraries to link against, etc.), as recorded in the lock file.
///
/// Skipped by serde — see `build_packages`.
#[serde(skip)]
pub host_packages: Vec<crate::UnresolvedPixiRecord>,
}
/// A fully-resolved source record with all metadata available.
///
/// This is the primary type used throughout the codebase for building,
/// installing, and solving. Re-exported as `SourceRecord` from the crate root.
pub type FullSourceRecord = SourceRecord<FullSourceRecordData>;
/// A source record with only minimal metadata (name, depends, sources).
///
/// Produced when a mutable (path-based) source is written to the lock file.
/// Not used directly outside this crate; see [`UnresolvedSourceRecord`].
pub type PartialSourceRecord = SourceRecord<PartialSourceRecordData>;
/// A source record that may be either full or partial. This is the lock file
/// boundary type.
///
/// Use [`UnresolvedPixiRecord::try_into_resolved`](crate::UnresolvedPixiRecord::try_into_resolved)
/// to check whether resolution is needed.
pub type UnresolvedSourceRecord = SourceRecord<SourceRecordData>;
/// Minimal metadata for a source package whose full record is not yet known.
///
/// This is what gets stored in the lock file for mutable (path-based) sources,
/// since their full metadata (version, build string, etc.) can change between
/// runs and would be stale.
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PartialSourceRecordData {
/// The package name of the source record.
pub name: PackageName,
/// Dependencies on other packages (run-time requirements).
pub depends: Vec<String>,
/// Run-time constraints on co-installed packages.
pub constrains: Vec<String>,
/// Additional dependencies grouped by an extra/feature key.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub experimental_extra_depends: BTreeMap<String, Vec<String>>,
/// Variant-selection flags declared by the recipe.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub flags: Vec<Flag>,
/// PURLs (Package URLs) describing this package in other ecosystems.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purls: Option<BTreeSet<PackageUrl>>,
/// License of the package (SPDX expression or free-form string).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub license: Option<String>,
/// Run-exports declared by the recipe.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_exports: Option<RunExportsJson>,
/// Specifies which packages are expected to be installed as source packages
/// and from which location.
pub sources: BTreeMap<String, SourceLocationSpec>,
}
/// Complete metadata for a fully-evaluated source package.
///
/// Contains the full [`PackageRecord`] (version, build, dependencies, etc.)
/// plus the source dependency map.
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FullSourceRecordData {
#[serde(flatten)]
pub package_record: PackageRecord,
/// Specifies which packages are expected to be installed as source packages
/// and from which location.
pub sources: BTreeMap<String, SourceLocationSpec>,
}
/// Runtime-checked variant used at the lock file boundary.
///
/// After reading a lock file, source records may be either full (immutable
/// sources like git) or partial (mutable sources like local paths). This enum
/// captures both cases and is resolved to [`FullSourceRecordData`] at startup.
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
#[allow(clippy::large_enum_variant)]
pub enum SourceRecordData {
Partial(PartialSourceRecordData),
Full(FullSourceRecordData),
}
impl SourceRecordData {
pub fn package_name(&self) -> &PackageName {
match self {
SourceRecordData::Partial(data) => &data.name,
SourceRecordData::Full(data) => &data.package_record.name,
}
}
pub fn as_partial(&self) -> Option<&PartialSourceRecordData> {
if let SourceRecordData::Partial(data) = self {
Some(data)
} else {
None
}
}
pub fn as_full(&self) -> Option<&FullSourceRecordData> {
if let SourceRecordData::Full(data) = self {
Some(data)
} else {
None
}
}
pub fn is_partial(&self) -> bool {
matches!(self, SourceRecordData::Partial(_))
}
pub fn is_full(&self) -> bool {
matches!(self, SourceRecordData::Full(_))
}
}
impl<D> SourceRecord<D> {
/// The pinned source location from the manifest.
pub fn manifest_source(&self) -> &PinnedSourceSpec {
&self.manifest_source
}
/// The optional pinned build source.
pub fn build_source(&self) -> Option<&PinnedBuildSourceSpec> {
self.build_source.as_ref()
}
/// The variants that identify how this package was built.
pub fn variants(&self) -> &BTreeMap<String, VariantValue> {
&self.variants
}
/// Returns true if either the manifest source or build source is mutable
/// (i.e. path-based and may change over time).
pub fn has_mutable_source(&self) -> bool {
self.manifest_source().is_mutable()
|| self
.build_source()
.as_ref()
.is_some_and(|bs| bs.pinned().is_mutable())
}
/// Compute this record's identifier hash from its current contents and
/// the content hash of the inline package definition that applies to it
/// (if any).
///
/// Children referenced via `build_packages` / `host_packages` must already
/// have their own `identifier_hash` set; see [`compute_identifier_hash`].
pub fn compute_identifier_hash(&self, inline_content_hash: Option<u64>) -> String
where
D: HashIdentifyingData,
{
compute_identifier_hash(
&self.manifest_source,
self.build_source.as_ref(),
&self.variants,
&self.data,
&self.build_packages,
&self.host_packages,
inline_content_hash,
)
}
}
impl<D: HashIdentifyingData> SourceRecord<D> {
/// Construct a source record and derive its [`identifier_hash`] from the
/// supplied fields. Children referenced via `build_packages` /
/// `host_packages` must already carry their own identifier hashes — see
/// the [`compute_identifier_hash`] free function for details.
///
/// Use [`SourceRecord::from_parts_with_hash`] when the hash is already
/// known (e.g. round-trip from a serialized form).
pub fn new(
data: D,
manifest_source: PinnedSourceSpec,
build_source: Option<PinnedBuildSourceSpec>,
variants: BTreeMap<String, VariantValue>,
build_packages: Vec<crate::UnresolvedPixiRecord>,
host_packages: Vec<crate::UnresolvedPixiRecord>,
inline_content_hash: Option<u64>,
) -> Self {
let identifier_hash = compute_identifier_hash(
&manifest_source,
build_source.as_ref(),
&variants,
&data,
&build_packages,
&host_packages,
inline_content_hash,
);
Self {
data,
manifest_source,
build_source,
variants,
identifier_hash,
build_packages,
host_packages,
}
}
}
impl<D> SourceRecord<D> {
/// Construct a source record from an explicit hash. Use this when reading
/// a record that already carries an identifier (lock file, on-disk cache);
/// for fresh records prefer [`SourceRecord::new`] so the hash is derived
/// rather than supplied.
pub fn from_parts_with_hash(
data: D,
manifest_source: PinnedSourceSpec,
build_source: Option<PinnedBuildSourceSpec>,
variants: BTreeMap<String, VariantValue>,
identifier_hash: String,
build_packages: Vec<crate::UnresolvedPixiRecord>,
host_packages: Vec<crate::UnresolvedPixiRecord>,
) -> Self {
Self {
data,
manifest_source,
build_source,
variants,
identifier_hash,
build_packages,
host_packages,
}
}
/// Transform the data payload while preserving all shared fields.
///
/// Useful for state transitions (e.g. Full → Unresolved, Partial → Full)
/// without field-by-field reconstruction.
pub fn map_data<D2>(self, f: impl FnOnce(D) -> D2) -> SourceRecord<D2> {
SourceRecord {
data: f(self.data),
manifest_source: self.manifest_source,
build_source: self.build_source,
variants: self.variants,
identifier_hash: self.identifier_hash,
build_packages: self.build_packages,
host_packages: self.host_packages,
}
}
/// Fallible version of [`map_data`](Self::map_data).
///
/// On success the record carries the new data type; on failure the record
/// is reassembled with the error type so no information is lost.
#[allow(clippy::result_large_err)]
pub fn try_map_data<T, E>(
self,
f: impl FnOnce(D) -> Result<T, E>,
) -> Result<SourceRecord<T>, SourceRecord<E>> {
let SourceRecord {
data,
manifest_source,
build_source,
variants,
identifier_hash,
build_packages,
host_packages,
} = self;
match f(data) {
Ok(new_data) => Ok(SourceRecord {
data: new_data,
manifest_source,
build_source,
variants,
identifier_hash,
build_packages,
host_packages,
}),
Err(err_data) => Err(SourceRecord {
data: err_data,
manifest_source,
build_source,
variants,
identifier_hash,
build_packages,
host_packages,
}),
}
}
}
impl SourceRecord<FullSourceRecordData> {
/// The name of the package.
pub fn name(&self) -> &PackageName {
&self.data.package_record.name
}
/// The full package record.
pub fn package_record(&self) -> &PackageRecord {
&self.data.package_record
}
/// Run-time dependencies.
pub fn depends(&self) -> &[String] {
&self.data.package_record.depends
}
/// Source dependency locations.
pub fn sources(&self) -> &BTreeMap<String, SourceLocationSpec> {
&self.data.sources
}
/// Convert into lock file compatible `CondaSourceData`.
///
/// If either source (manifest or build) is mutable (path-based), the
/// record is downgraded to partial metadata. This is intentional: mutable
/// sources can change between runs, so storing full metadata (version,
/// build string, hashes) would be misleading because it would appear locked
/// but could silently become stale. By keeping only name, depends, and
/// sources, we force re-evaluation at the next lock file read.
pub fn into_conda_source_data(self, workspace_root: &Path) -> CondaSourceData {
let has_mutable = self.has_mutable_source();
let mut unresolved = SourceRecord::<SourceRecordData>::from(self);
if has_mutable {
// Downgrade full data to partial: keep name, depends, constrains,
// and sources. Version/build/etc are dropped because they would go
// stale on the next mutable-source rebuild.
if let SourceRecordData::Full(full) = unresolved.data {
unresolved.data = SourceRecordData::Partial(PartialSourceRecordData {
name: full.package_record.name,
depends: full.package_record.depends,
constrains: full.package_record.constrains,
experimental_extra_depends: full.package_record.extra_depends,
flags: full.package_record.flags,
purls: full.package_record.purls,
license: full.package_record.license,
run_exports: full.package_record.run_exports,
sources: full.sources,
});
}
}
unresolved.into_conda_source_data(workspace_root)
}
/// Returns true if this source record refers to the same output as the other source record.
/// This is determined by comparing the package name, and either the variants (if both records have them)
/// or the build, version and subdir (if variants are not present).
pub fn refers_to_same_output(&self, other: &SourceRecord<FullSourceRecordData>) -> bool {
if self.data.package_record.name != other.data.package_record.name {
return false;
}
if self.variants.is_empty() || other.variants.is_empty() {
return true;
}
self.variants == other.variants
}
}
impl Matches<SourceRecord<FullSourceRecordData>> for NamelessMatchSpec {
fn matches(&self, pkg: &SourceRecord<FullSourceRecordData>) -> bool {
if !self.matches(&pkg.data.package_record) {
return false;
}
if self.channel.is_some() {
// We don't have a channel in a source record. So if a matchspec requires that
// information it can't match.
return false;
}
true
}
}
impl Matches<SourceRecord<FullSourceRecordData>> for MatchSpec {
fn matches(&self, pkg: &SourceRecord<FullSourceRecordData>) -> bool {
if !self.matches(&pkg.data.package_record) {
return false;
}
if self.channel.is_some() {
// We don't have a channel in a source record. So if a matchspec requires that
// information it can't match.
return false;
}
true
}
}
impl AsRef<PackageRecord> for SourceRecord<FullSourceRecordData> {
fn as_ref(&self) -> &PackageRecord {
&self.data.package_record
}
}
impl SourceRecord<PartialSourceRecordData> {
/// The name of the package.
pub fn name(&self) -> &PackageName {
&self.data.name
}
/// Run-time dependencies.
pub fn depends(&self) -> &[String] {
&self.data.depends
}
/// Run-time constraints.
pub fn constrains(&self) -> &[String] {
&self.data.constrains
}
/// Source dependency locations.
pub fn sources(&self) -> &BTreeMap<String, SourceLocationSpec> {
&self.data.sources
}
}
impl SourceRecord<SourceRecordData> {
/// The name of the package.
pub fn name(&self) -> &PackageName {
self.data.package_name()
}
/// Run-time dependencies.
pub fn depends(&self) -> &[String] {
match &self.data {
SourceRecordData::Full(full) => &full.package_record.depends,
SourceRecordData::Partial(partial) => &partial.depends,
}
}
/// Run-time constraints.
pub fn constrains(&self) -> &[String] {
match &self.data {
SourceRecordData::Full(full) => &full.package_record.constrains,
SourceRecordData::Partial(partial) => &partial.constrains,
}
}
/// Extra groups, keyed by group name.
pub fn experimental_extra_depends(&self) -> &BTreeMap<String, Vec<String>> {
match &self.data {
SourceRecordData::Full(full) => &full.package_record.extra_depends,
SourceRecordData::Partial(partial) => &partial.experimental_extra_depends,
}
}
/// Source dependency locations.
pub fn sources(&self) -> &BTreeMap<String, SourceLocationSpec> {
match &self.data {
SourceRecordData::Full(full) => &full.sources,
SourceRecordData::Partial(partial) => &partial.sources,
}
}
/// Convert into lock file compatible `CondaSourceData<SourceMetadata>`.
///
/// If the source is mutable (path-based), full metadata is downgraded to
/// partial so the lock file does not store stale version/build data.
pub fn into_conda_source_data(self, _workspace_root: &Path) -> CondaSourceData {
// Downgrade full records to partial when the source is mutable.
let is_mutable = self.manifest_source.is_mutable()
|| self
.build_source
.as_ref()
.is_some_and(|bs| bs.pinned().is_mutable());
let package_build_source = build_source_to_package_build_source(self.build_source);
let data = if is_mutable {
match self.data {
SourceRecordData::Full(full) => {
SourceRecordData::Partial(PartialSourceRecordData {
name: full.package_record.name,
depends: full.package_record.depends,
constrains: full.package_record.constrains,
experimental_extra_depends: full.package_record.extra_depends,
flags: full.package_record.flags,
purls: full.package_record.purls,
license: full.package_record.license,
run_exports: full.package_record.run_exports,
sources: full.sources,
})
}
partial @ SourceRecordData::Partial(_) => partial,
}
} else {
self.data
};
let (metadata, sources) = match data {
SourceRecordData::Full(full) => (
SourceMetadata::Full(Box::new(full.package_record)),
full.sources,
),
SourceRecordData::Partial(partial) => (
SourceMetadata::Partial(Box::new(PartialSourceMetadata {
name: partial.name,
depends: partial.depends,
constrains: partial.constrains,
extra_depends: partial.experimental_extra_depends,
flags: partial.flags,
license: partial.license,
purls: partial.purls,
run_exports: partial.run_exports,
})),
partial.sources,
),
};
CondaSourceData {
location: self.manifest_source.clone().into(),
package_build_source,
variants: self
.variants
.into_iter()
.map(|(k, v)| (k, v.into()))
.collect(),
identifier_hash: Some(self.identifier_hash),
sources: sources.into_iter().map(|(k, v)| (k, v.into())).collect(),
source_data: SourceData::default(),
metadata,
}
}
/// Create from lock file `CondaSourceData<SourceMetadata>`.
///
/// `build_packages` and `host_packages` must be resolved by the caller
/// from the lock file's package table, since `CondaSourceData` only
/// carries index sets and the full list of packages is not available
/// here.
pub fn from_conda_source_data(
data: CondaSourceData,
_workspace_root: &std::path::Path,
build_packages: Vec<crate::UnresolvedPixiRecord>,
host_packages: Vec<crate::UnresolvedPixiRecord>,
) -> Result<Self, ParseLockFileError> {
let manifest_source: PinnedSourceSpec = data.location.try_into()?;
let build_source =
package_build_source_to_build_source(data.package_build_source, &manifest_source)?;
let sources = data
.sources
.into_iter()
.map(|(k, v)| (k, SourceLocationSpec::from(v)))
.collect();
let record_data = match data.metadata {
SourceMetadata::Full(package_record) => SourceRecordData::Full(FullSourceRecordData {
package_record: package_record.as_ref().clone(),
sources,
}),
SourceMetadata::Partial(partial) => {
SourceRecordData::Partial(PartialSourceRecordData {
name: partial.name,
depends: partial.depends,
constrains: partial.constrains,
experimental_extra_depends: partial.extra_depends,
flags: partial.flags,
purls: partial.purls,
license: partial.license,
run_exports: partial.run_exports,
sources,
})
}
};
let variants: BTreeMap<String, VariantValue> = data
.variants
.into_iter()
.map(|(k, v)| (k, VariantValue::from(v)))
.collect();
// v7 lock files always carry the hash; the fallback is only reached
// for older/hand-rolled lock files that omit it. Children are
// resolved before parents (see `LockFileResolver`), so their hashes
// are already filled when we recompute here.
let identifier_hash = data.identifier_hash.unwrap_or_else(|| {
compute_identifier_hash(
&manifest_source,
build_source.as_ref(),
&variants,
&record_data,
&build_packages,
&host_packages,
None,
)
});
Ok(Self::from_parts_with_hash(
record_data,
manifest_source,
build_source,
variants,
identifier_hash,
build_packages,
host_packages,
))
}
}
/// Upcast from full to unresolved.
impl From<SourceRecord<FullSourceRecordData>> for SourceRecord<SourceRecordData> {
fn from(record: SourceRecord<FullSourceRecordData>) -> Self {
record.map_data(SourceRecordData::Full)
}
}
/// Convert build source to rattler's PackageBuildSource.
fn build_source_to_package_build_source(
build_source: Option<PinnedBuildSourceSpec>,
) -> Option<PackageBuildSource> {
match build_source {
Some(PinnedBuildSourceSpec::Relative(path, _)) => Some(PackageBuildSource::Path {
path: Utf8TypedPathBuf::from(path),
}),
Some(PinnedBuildSourceSpec::Absolute(PinnedSourceSpec::Url(pinned_url_spec))) => {
Some(PackageBuildSource::Url {
url: pinned_url_spec.url,
sha256: pinned_url_spec.sha256,
subdir: pinned_url_spec
.subdirectory
.to_option_string()
.map(Utf8TypedPathBuf::from),
})
}
Some(PinnedBuildSourceSpec::Absolute(PinnedSourceSpec::Git(pinned_git_spec))) => {
Some(PackageBuildSource::Git {
url: pinned_git_spec.git,
spec: to_git_shallow(&pinned_git_spec.source.reference),
rev: pinned_git_spec.source.commit.to_string(),
subdir: pinned_git_spec
.source
.subdirectory
.to_option_string()
.map(Utf8TypedPathBuf::from),
})
}
Some(PinnedBuildSourceSpec::Absolute(PinnedSourceSpec::Path(pinned_path_spec))) => {
Some(PackageBuildSource::Path {
path: pinned_path_spec.path,
})
}
None => None,
}
}
/// Convert rattler's PackageBuildSource back to PinnedBuildSourceSpec.
fn package_build_source_to_build_source(
pbs: Option<PackageBuildSource>,
manifest_source: &PinnedSourceSpec,
) -> Result<Option<PinnedBuildSourceSpec>, ParseLockFileError> {
match pbs {
None => Ok(None),
Some(PackageBuildSource::Path { path }) if path.is_relative() => {
let pinned = manifest_source.join(path.to_path());
Ok(Some(PinnedBuildSourceSpec::Relative(
path.to_string(),
pinned,
)))
}
Some(PackageBuildSource::Path { path }) => Ok(Some(PinnedBuildSourceSpec::Absolute(
PinnedSourceSpec::Path(PinnedPathSpec { path }),
))),
Some(PackageBuildSource::Git {
url,
spec,
rev,
subdir,
}) => {
let reference = git_reference_from_shallow(spec, &rev);
Ok(Some(PinnedBuildSourceSpec::Absolute(
PinnedSourceSpec::Git(PinnedGitSpec {
git: url,
source: PinnedGitCheckout {
commit: GitSha::from_str(&rev).unwrap(),
subdirectory: subdir
.and_then(|s| pixi_spec::Subdirectory::try_from(s.to_string()).ok())
.unwrap_or_default(),
reference,
},
}),
)))
}
Some(PackageBuildSource::Url {
url,
sha256,
subdir,
}) => Ok(Some(PinnedBuildSourceSpec::Absolute(
PinnedSourceSpec::Url(PinnedUrlSpec {
url,
sha256,
md5: None,
subdirectory: subdir
.and_then(|s| pixi_spec::Subdirectory::try_from(s.to_string()).ok())
.unwrap_or_default(),
}),
))),
}
}
fn to_git_shallow(reference: &GitReference) -> Option<GitShallowSpec> {
match reference {
GitReference::Branch(branch) => Some(GitShallowSpec::Branch(branch.clone())),
GitReference::Tag(tag) => Some(GitShallowSpec::Tag(tag.clone())),
GitReference::Rev(_) => Some(GitShallowSpec::Rev),
GitReference::DefaultBranch => None,
}
}
fn git_reference_from_shallow(spec: Option<GitShallowSpec>, rev: &str) -> GitReference {
match spec {
Some(GitShallowSpec::Branch(branch)) => GitReference::Branch(branch),
Some(GitShallowSpec::Tag(tag)) => GitReference::Tag(tag),
Some(GitShallowSpec::Rev) => GitReference::Rev(rev.to_string()),
None => GitReference::DefaultBranch,
}
}
#[cfg(test)]
mod tests {
use super::*;