-
-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathresource_collection.rs
More file actions
4686 lines (4142 loc) · 160 KB
/
Copy pathresource_collection.rs
File metadata and controls
4686 lines (4142 loc) · 160 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/*! Functionality for collecting Python resources. */
use {
crate::{
bytecode::{
compute_bytecode_header, BytecodeHeaderMode, CompileMode, PythonBytecodeCompiler,
},
libpython::LibPythonBuildContext,
location::{AbstractResourceLocation, ConcreteResourceLocation},
module_util::{packages_from_module_name, resolve_path_for_module},
python_source::has_dunder_file,
resource::{
BytecodeOptimizationLevel, PythonExtensionModule, PythonModuleBytecode,
PythonModuleBytecodeFromSource, PythonModuleSource, PythonPackageDistributionResource,
PythonPackageResource, PythonResource, SharedLibrary,
},
},
anyhow::{anyhow, Context, Result},
python_packed_resources::Resource,
std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet, HashMap},
convert::TryFrom,
path::PathBuf,
},
tugger_file_manifest::{File, FileData, FileEntry, FileManifest},
tugger_licensing::{ComponentFlavor, LicensedComponent, LicensedComponents},
};
/// Represents a single file install.
///
/// Tuple is the relative install path, the data to install, and whether the file
/// should be executable.
pub type FileInstall = (PathBuf, FileData, bool);
/// Describes how Python module bytecode will be obtained.
#[derive(Clone, Debug, PartialEq)]
pub enum PythonModuleBytecodeProvider {
/// Bytecode is already available.
Provided(FileData),
/// Bytecode will be computed from source.
FromSource(FileData),
}
/// Represents a Python resource entry before it is packaged.
///
/// Instances hold the same fields as `Resource` except fields holding
/// content are backed by a `FileData` instead of `Vec<u8>`, since
/// we want data resolution to be lazy. In addition, bytecode can either be
/// provided verbatim or via source.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PrePackagedResource {
pub name: String,
pub is_package: bool,
pub is_namespace_package: bool,
pub in_memory_source: Option<FileData>,
pub in_memory_bytecode: Option<PythonModuleBytecodeProvider>,
pub in_memory_bytecode_opt1: Option<PythonModuleBytecodeProvider>,
pub in_memory_bytecode_opt2: Option<PythonModuleBytecodeProvider>,
pub in_memory_extension_module_shared_library: Option<FileData>,
pub in_memory_resources: Option<BTreeMap<String, FileData>>,
pub in_memory_distribution_resources: Option<BTreeMap<String, FileData>>,
pub in_memory_shared_library: Option<FileData>,
pub shared_library_dependency_names: Option<Vec<String>>,
// (prefix, source code)
pub relative_path_module_source: Option<(String, FileData)>,
// (prefix, bytecode tag, source code)
pub relative_path_bytecode: Option<(String, String, PythonModuleBytecodeProvider)>,
pub relative_path_bytecode_opt1: Option<(String, String, PythonModuleBytecodeProvider)>,
pub relative_path_bytecode_opt2: Option<(String, String, PythonModuleBytecodeProvider)>,
// (path, data)
pub relative_path_extension_module_shared_library: Option<(PathBuf, FileData)>,
pub relative_path_package_resources: Option<BTreeMap<String, (PathBuf, FileData)>>,
pub relative_path_distribution_resources: Option<BTreeMap<String, (PathBuf, FileData)>>,
pub relative_path_shared_library: Option<(String, PathBuf, FileData)>,
pub is_module: bool,
pub is_builtin_extension_module: bool,
pub is_frozen_module: bool,
pub is_extension_module: bool,
pub is_shared_library: bool,
pub is_utf8_filename_data: bool,
pub file_executable: bool,
pub file_data_embedded: Option<FileData>,
pub file_data_utf8_relative_path: Option<(PathBuf, FileData)>,
}
impl PrePackagedResource {
/// Whether this resource represents a Python resource.
pub fn is_python_resource(&self) -> bool {
self.is_module
|| self.is_builtin_extension_module
|| self.is_frozen_module
|| self.is_extension_module
}
/// Convert the instance to a `Resource`.
///
/// This will compile bytecode from source code using the specified compiler.
/// It will also emit a list of file installs that must be performed for all
/// referenced resources to function as intended.
pub fn to_resource<'a>(
&self,
compiler: &mut dyn PythonBytecodeCompiler,
) -> Result<(Resource<'a, u8>, Vec<FileInstall>)> {
let mut installs = Vec::new();
let resource = Resource {
name: Cow::Owned(self.name.clone()),
is_python_package: self.is_package,
is_python_namespace_package: self.is_namespace_package,
in_memory_source: if let Some(location) = &self.in_memory_source {
Some(Cow::Owned(location.resolve_content()?))
} else {
None
},
in_memory_bytecode: match &self.in_memory_bytecode {
Some(PythonModuleBytecodeProvider::Provided(location)) => {
Some(Cow::Owned(location.resolve_content()?))
}
Some(PythonModuleBytecodeProvider::FromSource(location)) => Some(Cow::Owned(
compiler
.compile(
&location.resolve_content()?,
&self.name,
BytecodeOptimizationLevel::Zero,
CompileMode::Bytecode,
)
.context("compiling in-memory bytecode")?,
)),
None => None,
},
in_memory_bytecode_opt1: match &self.in_memory_bytecode_opt1 {
Some(PythonModuleBytecodeProvider::Provided(location)) => {
Some(Cow::Owned(location.resolve_content()?))
}
Some(PythonModuleBytecodeProvider::FromSource(location)) => Some(Cow::Owned(
compiler
.compile(
&location.resolve_content()?,
&self.name,
BytecodeOptimizationLevel::One,
CompileMode::Bytecode,
)
.context("compiling in-memory bytecode opt-1")?,
)),
None => None,
},
in_memory_bytecode_opt2: match &self.in_memory_bytecode_opt2 {
Some(PythonModuleBytecodeProvider::Provided(location)) => {
Some(Cow::Owned(location.resolve_content()?))
}
Some(PythonModuleBytecodeProvider::FromSource(location)) => Some(Cow::Owned(
compiler
.compile(
&location.resolve_content()?,
&self.name,
BytecodeOptimizationLevel::Two,
CompileMode::Bytecode,
)
.context("compiling in-memory bytecode opt2")?,
)),
None => None,
},
in_memory_extension_module_shared_library: if let Some(location) =
&self.in_memory_extension_module_shared_library
{
Some(Cow::Owned(location.resolve_content()?))
} else {
None
},
in_memory_package_resources: if let Some(resources) = &self.in_memory_resources {
let mut res = HashMap::new();
for (key, location) in resources {
res.insert(
Cow::Owned(key.clone()),
Cow::Owned(location.resolve_content()?),
);
}
Some(res)
} else {
None
},
in_memory_distribution_resources: if let Some(resources) =
&self.in_memory_distribution_resources
{
let mut res = HashMap::new();
for (key, location) in resources {
res.insert(
Cow::Owned(key.clone()),
Cow::Owned(location.resolve_content()?),
);
}
Some(res)
} else {
None
},
in_memory_shared_library: if let Some(location) = &self.in_memory_shared_library {
Some(Cow::Owned(location.resolve_content()?))
} else {
None
},
shared_library_dependency_names: self
.shared_library_dependency_names
.as_ref()
.map(|x| x.iter().map(|x| Cow::Owned(x.clone())).collect()),
relative_path_module_source: if let Some((prefix, location)) =
&self.relative_path_module_source
{
let path = resolve_path_for_module(prefix, &self.name, self.is_package, None);
installs.push((path.clone(), location.clone(), false));
Some(Cow::Owned(path))
} else {
None
},
relative_path_module_bytecode: if let Some((prefix, cache_tag, provider)) =
&self.relative_path_bytecode
{
let path = resolve_path_for_module(
prefix,
&self.name,
self.is_package,
Some(&format!(
"{}{}",
cache_tag,
BytecodeOptimizationLevel::Zero.to_extra_tag()
)),
);
installs.push((
path.clone(),
FileData::Memory(match provider {
PythonModuleBytecodeProvider::FromSource(location) => compiler
.compile(
&location.resolve_content()?,
&self.name,
BytecodeOptimizationLevel::Zero,
CompileMode::PycUncheckedHash,
)
.context("compiling relative path module bytecode")?,
PythonModuleBytecodeProvider::Provided(location) => {
let mut data = compute_bytecode_header(
compiler.get_magic_number(),
BytecodeHeaderMode::UncheckedHash(0),
)?;
data.extend(location.resolve_content()?);
data
}
}),
false,
));
Some(Cow::Owned(path))
} else {
None
},
relative_path_module_bytecode_opt1: if let Some((prefix, cache_tag, provider)) =
&self.relative_path_bytecode_opt1
{
let path = resolve_path_for_module(
prefix,
&self.name,
self.is_package,
Some(&format!(
"{}{}",
cache_tag,
BytecodeOptimizationLevel::One.to_extra_tag()
)),
);
installs.push((
path.clone(),
FileData::Memory(match provider {
PythonModuleBytecodeProvider::FromSource(location) => compiler
.compile(
&location.resolve_content()?,
&self.name,
BytecodeOptimizationLevel::One,
CompileMode::PycUncheckedHash,
)
.context("compiling relative path module bytecode opt-1")?,
PythonModuleBytecodeProvider::Provided(location) => {
let mut data = compute_bytecode_header(
compiler.get_magic_number(),
BytecodeHeaderMode::UncheckedHash(0),
)?;
data.extend(location.resolve_content()?);
data
}
}),
false,
));
Some(Cow::Owned(path))
} else {
None
},
relative_path_module_bytecode_opt2: if let Some((prefix, cache_tag, provider)) =
&self.relative_path_bytecode_opt2
{
let path = resolve_path_for_module(
prefix,
&self.name,
self.is_package,
Some(&format!(
"{}{}",
cache_tag,
BytecodeOptimizationLevel::Two.to_extra_tag()
)),
);
installs.push((
path.clone(),
FileData::Memory(match provider {
PythonModuleBytecodeProvider::FromSource(location) => compiler.compile(
&location.resolve_content()?,
&self.name,
BytecodeOptimizationLevel::Two,
CompileMode::PycUncheckedHash,
)?,
PythonModuleBytecodeProvider::Provided(location) => {
let mut data = compute_bytecode_header(
compiler.get_magic_number(),
BytecodeHeaderMode::UncheckedHash(0),
)
.context("compiling relative path module bytecode opt-2")?;
data.extend(location.resolve_content()?);
data
}
}),
false,
));
Some(Cow::Owned(path))
} else {
None
},
relative_path_extension_module_shared_library: if let Some((path, location)) =
&self.relative_path_extension_module_shared_library
{
installs.push((path.clone(), location.clone(), true));
Some(Cow::Owned(path.clone()))
} else {
None
},
relative_path_package_resources: if let Some(resources) =
&self.relative_path_package_resources
{
let mut res = HashMap::new();
for (key, (path, location)) in resources {
installs.push((path.clone(), location.clone(), false));
res.insert(Cow::Owned(key.clone()), Cow::Owned(path.clone()));
}
Some(res)
} else {
None
},
relative_path_distribution_resources: if let Some(resources) =
&self.relative_path_distribution_resources
{
let mut res = HashMap::new();
for (key, (path, location)) in resources {
installs.push((path.clone(), location.clone(), false));
res.insert(Cow::Owned(key.clone()), Cow::Owned(path.clone()));
}
Some(res)
} else {
None
},
is_python_module: self.is_module,
is_python_builtin_extension_module: self.is_builtin_extension_module,
is_python_frozen_module: self.is_frozen_module,
is_python_extension_module: self.is_extension_module,
is_shared_library: self.is_shared_library,
is_utf8_filename_data: self.is_utf8_filename_data,
file_executable: self.file_executable,
file_data_embedded: if let Some(location) = &self.file_data_embedded {
Some(Cow::Owned(location.resolve_content()?))
} else {
None
},
file_data_utf8_relative_path: if let Some((path, location)) =
&self.file_data_utf8_relative_path
{
installs.push((path.clone(), location.clone(), self.file_executable));
Some(Cow::Owned(path.to_string_lossy().to_string()))
} else {
None
},
};
if let Some((prefix, filename, location)) = &self.relative_path_shared_library {
installs.push((PathBuf::from(prefix).join(filename), location.clone(), true));
}
Ok((resource, installs))
}
}
/// Fill in missing data on parent packages.
///
/// When resources are added, their parent packages could be missing
/// data. If we simply materialized the child resources without the
/// parents, Python's importer would get confused due to the missing
/// resources.
///
/// This function fills in the blanks in our resources state.
///
/// The way this works is that if a child resource has data in
/// a particular field, we populate that field in all its parent
/// packages. If a corresponding fields is already populated, we
/// copy its data as well.
pub fn populate_parent_packages(
resources: &mut BTreeMap<String, PrePackagedResource>,
) -> Result<()> {
let original_resources = resources
.iter()
.filter_map(|(k, v)| {
if v.is_python_resource() {
Some((k.to_owned(), v.to_owned()))
} else {
None
}
})
.collect::<Vec<(String, PrePackagedResource)>>();
for (name, original) in original_resources {
for package in packages_from_module_name(&name) {
let entry = resources
.entry(package.clone())
.or_insert_with(|| PrePackagedResource {
name: package,
..PrePackagedResource::default()
});
// Parents must be modules + packages by definition.
entry.is_module = true;
entry.is_package = true;
// We want to materialize bytecode on parent packages no matter
// what. If the original resource has a variant of bytecode in a
// location, we materialize that variant on parents. We take
// the source from the parent resource, if present. Otherwise
// defaulting to empty.
if original.in_memory_bytecode.is_some() && entry.in_memory_bytecode.is_none() {
entry.in_memory_bytecode = Some(PythonModuleBytecodeProvider::FromSource(
if let Some(source) = &entry.in_memory_source {
source.clone()
} else {
FileData::Memory(vec![])
},
));
}
if original.in_memory_bytecode_opt1.is_some() && entry.in_memory_bytecode_opt1.is_none()
{
entry.in_memory_bytecode_opt1 = Some(PythonModuleBytecodeProvider::FromSource(
if let Some(source) = &entry.in_memory_source {
source.clone()
} else {
FileData::Memory(vec![])
},
));
}
if original.in_memory_bytecode_opt2.is_some() && entry.in_memory_bytecode_opt2.is_none()
{
entry.in_memory_bytecode_opt2 = Some(PythonModuleBytecodeProvider::FromSource(
if let Some(source) = &entry.in_memory_source {
source.clone()
} else {
FileData::Memory(vec![])
},
));
}
if let Some((prefix, cache_tag, _)) = &original.relative_path_bytecode {
if entry.relative_path_bytecode.is_none() {
entry.relative_path_bytecode = Some((
prefix.clone(),
cache_tag.clone(),
PythonModuleBytecodeProvider::FromSource(
if let Some((_, location)) = &entry.relative_path_module_source {
location.clone()
} else {
FileData::Memory(vec![])
},
),
));
}
}
if let Some((prefix, cache_tag, _)) = &original.relative_path_bytecode_opt1 {
if entry.relative_path_bytecode_opt1.is_none() {
entry.relative_path_bytecode_opt1 = Some((
prefix.clone(),
cache_tag.clone(),
PythonModuleBytecodeProvider::FromSource(
if let Some((_, location)) = &entry.relative_path_module_source {
location.clone()
} else {
FileData::Memory(vec![])
},
),
));
}
}
if let Some((prefix, cache_tag, _)) = &original.relative_path_bytecode_opt2 {
if entry.relative_path_bytecode_opt2.is_none() {
entry.relative_path_bytecode_opt2 = Some((
prefix.clone(),
cache_tag.clone(),
PythonModuleBytecodeProvider::FromSource(
if let Some((_, location)) = &entry.relative_path_module_source {
location.clone()
} else {
FileData::Memory(vec![])
},
),
));
}
}
// If the child had path-based source, we need to materialize source as well.
if let Some((prefix, _)) = &original.relative_path_module_source {
entry
.relative_path_module_source
.get_or_insert_with(|| (prefix.clone(), FileData::Memory(vec![])));
}
// Ditto for in-memory source.
if original.in_memory_source.is_some() {
entry
.in_memory_source
.get_or_insert(FileData::Memory(vec![]));
}
}
}
Ok(())
}
/// Defines how a Python resource should be added to a `PythonResourceCollector`.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonResourceAddCollectionContext {
/// Whether the resource should be included in `PythonResourceCollection`.
pub include: bool,
/// The location the resource should be loaded from.
pub location: ConcreteResourceLocation,
/// Optional fallback location from which to load the resource from.
///
/// If adding the resource to `location` fails, and this is defined,
/// we will fall back to adding the resource to this location.
pub location_fallback: Option<ConcreteResourceLocation>,
/// Whether to store Python source code for a `PythonModuleSource`.
///
/// When handling a `PythonModuleSource`, sometimes you want to
/// write just bytecode or source + bytecode. This flags allows
/// controlling this behavior.
pub store_source: bool,
/// Whether to store Python bytecode for optimization level 0.
pub optimize_level_zero: bool,
/// Whether to store Python bytecode for optimization level 1.
pub optimize_level_one: bool,
/// Whether to store Python bytecode for optimization level 2.
pub optimize_level_two: bool,
}
impl PythonResourceAddCollectionContext {
/// Replace the content of `self` with content of `other`.
pub fn replace(&mut self, other: &Self) {
self.include = other.include;
self.location = other.location.clone();
self.location_fallback = other.location_fallback.clone();
self.store_source = other.store_source;
self.optimize_level_zero = other.optimize_level_zero;
self.optimize_level_one = other.optimize_level_one;
self.optimize_level_two = other.optimize_level_two;
}
}
/// Describes the state of licensing for resources in a given resources collection.
#[derive(Clone, Debug, Default)]
pub struct ResourcesLicenseReport {
/// Packages without any licensing info.
pub no_license_packages: BTreeSet<String>,
/// Packages using an SPDX license. Maps license to package names.
pub spdx_by_package: BTreeMap<String, BTreeSet<String>>,
/// Packages using non-SPDX license. Maps license to package names.
pub non_spdx_by_package: BTreeMap<String, BTreeSet<String>>,
}
/// Represents a finalized collection of Python resources.
///
/// Instances are produced from a `PythonResourceCollector` and a
/// `PythonBytecodeCompiler` to produce bytecode.
#[derive(Clone, Debug, Default)]
pub struct CompiledResourcesCollection<'a> {
/// All indexes resources.
pub resources: BTreeMap<String, Resource<'a, u8>>,
/// Extra file installs that must be performed so referenced files are available.
pub extra_files: Vec<FileInstall>,
}
impl<'a> CompiledResourcesCollection<'a> {
/// Write resources to packed resources data, version 1.
pub fn write_packed_resources<W: std::io::Write>(&self, writer: &mut W) -> Result<()> {
python_packed_resources::write_packed_resources_v3(
&self
.resources
.values()
.cloned()
.collect::<Vec<Resource<'a, u8>>>(),
writer,
None,
)
}
/// Convert the file installs to a [FileManifest].
pub fn extra_files_manifest(&self) -> Result<FileManifest> {
let mut m = FileManifest::default();
for (path, location, executable) in &self.extra_files {
m.add_file_entry(
path,
FileEntry::new_from_data(location.resolve_content()?, *executable),
)?;
}
Ok(m)
}
}
/// Type used to collect Python resources so they can be serialized.
///
/// We often want to turn Python resource primitives (module source,
/// bytecode, etc) into a collection of `Resource` so they can be
/// serialized to the *Python packed resources* format. This type
/// exists to facilitate doing this.
///
/// This type is not only responsible for tracking resources but also for
/// enforcing policies on where those resources can be loaded from and
/// what types of resources are allowed. This includes tracking the
/// licensing metadata for indexed resources.
#[derive(Debug, Clone)]
pub struct PythonResourceCollector {
/// Where resources can be placed.
allowed_locations: Vec<AbstractResourceLocation>,
/// Allowed locations for extension modules.
///
/// This is applied in addition to `allowed_locations` and can be
/// more strict.
allowed_extension_module_locations: Vec<AbstractResourceLocation>,
/// Whether builtin extension modules outside the standard library are allowed.
///
/// This is effectively "are we building a custom libpython." If true,
/// we can take object files / static libraries from adding extension
/// modules are add the extension module as a built-in. If false, only
/// builtin extension modules already in libpython can be added as a
/// built-in.
allow_new_builtin_extension_modules: bool,
/// Whether untyped files (`File`) can be added.
allow_files: bool,
/// Named resources that have been collected.
resources: BTreeMap<String, PrePackagedResource>,
/// Bytecode cache tag to use for compiled bytecode modules.
cache_tag: String,
/// Collection of software components which are licensed.
licensed_components: LicensedComponents,
}
impl PythonResourceCollector {
/// Construct a new instance of the collector.
///
/// The instance is associated with a resources policy to validate that
/// added resources conform with rules.
///
/// We also pass a Python bytecode cache tag, which is used to
/// derive filenames.
pub fn new(
allowed_locations: Vec<AbstractResourceLocation>,
allowed_extension_module_locations: Vec<AbstractResourceLocation>,
allow_new_builtin_extension_modules: bool,
allow_files: bool,
cache_tag: &str,
) -> Self {
Self {
allowed_locations,
allowed_extension_module_locations,
allow_new_builtin_extension_modules,
allow_files,
resources: BTreeMap::new(),
cache_tag: cache_tag.to_string(),
licensed_components: LicensedComponents::default(),
}
}
/// Obtain locations that resources can be loaded from.
pub fn allowed_locations(&self) -> &Vec<AbstractResourceLocation> {
&self.allowed_locations
}
/// Obtain a set of all top-level Python module names registered with the collector.
///
/// The returned values correspond to packages or single file modules without
/// children modules.
pub fn all_top_level_module_names(&self) -> BTreeSet<String> {
self.resources
.values()
.filter_map(|r| {
if r.is_python_resource() {
let name = if let Some(idx) = r.name.find('.') {
&r.name[0..idx]
} else {
&r.name
};
Some(name.to_string())
} else {
None
}
})
.collect::<BTreeSet<_>>()
}
/// Validate that a resource add in the specified location is allowed.
pub fn check_policy(&self, location: AbstractResourceLocation) -> Result<()> {
if self.allowed_locations.contains(&location) {
Ok(())
} else {
Err(anyhow!(
"resource collector does not allow resources in {}",
(&location).to_string()
))
}
}
/// Apply a filter function on resources in this collection and mutate in place.
///
/// If the filter function returns true, the item will be preserved.
pub fn filter_resources_mut<F>(&mut self, filter: F) -> Result<()>
where
F: Fn(&PrePackagedResource) -> bool,
{
self.resources = self
.resources
.iter()
.filter_map(|(k, v)| {
if filter(v) {
Some((k.clone(), v.clone()))
} else {
None
}
})
.collect();
Ok(())
}
/// Obtain an iterator over the resources in this collector.
pub fn iter_resources(&self) -> impl Iterator<Item = (&String, &PrePackagedResource)> {
Box::new(self.resources.iter())
}
/// Generate a summary of licensing information for resources in the collection.
pub fn generate_license_report(&self) -> Result<ResourcesLicenseReport> {
let mut report = ResourcesLicenseReport::default();
let all_packages = self.all_top_level_module_names();
for package in &all_packages {
// Only care about top-level packages.
if package.contains('.') {
continue;
}
if !self
.licensed_components
.iter_components()
.any(|c| c.name() == package && c.flavor() == &ComponentFlavor::PythonPackage)
{
report.no_license_packages.insert(package.clone());
}
}
for component in self.licensed_components.iter_components() {
// We don't care about license metadata belonging to packages not
// in our collection.
if !all_packages.contains(component.name()) {
continue;
}
if let Some(expression) = component.spdx_expression() {
for req in expression.requirements() {
if let Some(id) = &req.req.license.id() {
report
.spdx_by_package
.entry(id.name.to_string())
.or_insert_with(BTreeSet::new)
.insert(component.name().to_string());
} else {
report
.non_spdx_by_package
.entry(req.req.license.to_string())
.or_insert_with(BTreeSet::new)
.insert(component.name().to_string());
}
}
}
}
Ok(report)
}
/// Register a licensed software component to this collection.
pub fn add_licensed_component(&mut self, component: LicensedComponent) -> Result<()> {
self.licensed_components.add_component(component);
Ok(())
}
/// Add Python module source with a specific location.
pub fn add_python_module_source(
&mut self,
module: &PythonModuleSource,
location: &ConcreteResourceLocation,
) -> Result<()> {
self.check_policy(location.into())?;
let entry = self
.resources
.entry(module.name.clone())
.or_insert_with(|| PrePackagedResource {
name: module.name.clone(),
..PrePackagedResource::default()
});
entry.is_module = true;
entry.is_package = module.is_package;
match location {
ConcreteResourceLocation::InMemory => {
entry.in_memory_source = Some(module.source.clone());
}
ConcreteResourceLocation::RelativePath(prefix) => {
entry.relative_path_module_source =
Some((prefix.to_string(), module.source.clone()));
}
}
Ok(())
}
/// Add Python module source using an add context to influence operation.
///
/// All of the context's properties are respected. This includes doing
/// nothing if `include` is false, not adding source if `store_source` is
/// false, and automatically deriving a bytecode request if the
/// `optimize_level_*` fields are set.
///
/// This method is a glorified proxy to other `add_*` methods: it
/// simply contains the logic for expanding the context's wishes into
/// function calls.
pub fn add_python_module_source_with_context(
&mut self,
module: &PythonModuleSource,
add_context: &PythonResourceAddCollectionContext,
) -> Result<()> {
if !add_context.include {
return Ok(());
}
if add_context.store_source {
self.add_python_resource_with_locations(
&module.into(),
&add_context.location,
&add_context.location_fallback,
)?;
}
// Derive bytecode as requested.
if add_context.optimize_level_zero {
self.add_python_resource_with_locations(
&module
.as_bytecode_module(BytecodeOptimizationLevel::Zero)
.into(),
&add_context.location,
&add_context.location_fallback,
)?;
}
if add_context.optimize_level_one {
self.add_python_resource_with_locations(
&module
.as_bytecode_module(BytecodeOptimizationLevel::One)
.into(),
&add_context.location,
&add_context.location_fallback,
)?;
}
if add_context.optimize_level_two {
self.add_python_resource_with_locations(
&module
.as_bytecode_module(BytecodeOptimizationLevel::Two)
.into(),
&add_context.location,
&add_context.location_fallback,
)?;
}
Ok(())
}
/// Add Python module bytecode to the specified location.
pub fn add_python_module_bytecode(
&mut self,
module: &PythonModuleBytecode,
location: &ConcreteResourceLocation,
) -> Result<()> {
self.check_policy(location.into())?;
let entry = self
.resources
.entry(module.name.clone())
.or_insert_with(|| PrePackagedResource {
name: module.name.clone(),
..PrePackagedResource::default()
});
entry.is_module = true;
entry.is_package = module.is_package;
// TODO having to resolve the FileData here is a bit unfortunate.
// We could invent a better type to allow the I/O to remain lazy.
let bytecode =
PythonModuleBytecodeProvider::Provided(FileData::Memory(module.resolve_bytecode()?));
match location {
ConcreteResourceLocation::InMemory => match module.optimize_level {
BytecodeOptimizationLevel::Zero => {
entry.in_memory_bytecode = Some(bytecode);
}
BytecodeOptimizationLevel::One => {
entry.in_memory_bytecode_opt1 = Some(bytecode);
}
BytecodeOptimizationLevel::Two => {
entry.in_memory_bytecode_opt2 = Some(bytecode);
}
},
ConcreteResourceLocation::RelativePath(prefix) => match module.optimize_level {
BytecodeOptimizationLevel::Zero => {
entry.relative_path_bytecode =
Some((prefix.to_string(), module.cache_tag.clone(), bytecode));
}
BytecodeOptimizationLevel::One => {
entry.relative_path_bytecode_opt1 =
Some((prefix.to_string(), module.cache_tag.clone(), bytecode));
}
BytecodeOptimizationLevel::Two => {
entry.relative_path_bytecode_opt2 =
Some((prefix.to_string(), module.cache_tag.clone(), bytecode));
}
},
}
Ok(())
}
/// Add Python module bytecode using an add context.
///
/// This takes the context's fields into consideration when adding
/// the resource. If `include` is false, this is a no-op. The context
/// must also have an `optimize_level_*` field set corresponding with