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
// 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/.

/*! Defines types representing Python resources. */

use {
    crate::{
        bytecode::{CompileMode, PythonBytecodeCompiler},
        module_util::{is_package_from_path, packages_from_module_name, resolve_path_for_module},
        python_source::has_dunder_file,
    },
    anyhow::{anyhow, Result},
    std::{
        borrow::Cow,
        collections::HashMap,
        convert::TryFrom,
        hash::BuildHasher,
        iter::FromIterator,
        path::{Path, PathBuf},
    },
    tugger_file_manifest::{File, FileData},
    tugger_licensing::LicensedComponent,
};

/// An optimization level for Python bytecode.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BytecodeOptimizationLevel {
    Zero,
    One,
    Two,
}

impl BytecodeOptimizationLevel {
    /// Determine hte extra filename tag for bytecode files of this variant.
    pub fn to_extra_tag(&self) -> &'static str {
        match self {
            BytecodeOptimizationLevel::Zero => "",
            BytecodeOptimizationLevel::One => ".opt-1",
            BytecodeOptimizationLevel::Two => ".opt-2",
        }
    }
}

impl TryFrom<i32> for BytecodeOptimizationLevel {
    type Error = &'static str;

    fn try_from(i: i32) -> Result<Self, Self::Error> {
        match i {
            0 => Ok(BytecodeOptimizationLevel::Zero),
            1 => Ok(BytecodeOptimizationLevel::One),
            2 => Ok(BytecodeOptimizationLevel::Two),
            _ => Err("unsupported bytecode optimization level"),
        }
    }
}

impl From<BytecodeOptimizationLevel> for i32 {
    fn from(level: BytecodeOptimizationLevel) -> Self {
        match level {
            BytecodeOptimizationLevel::Zero => 0,
            BytecodeOptimizationLevel::One => 1,
            BytecodeOptimizationLevel::Two => 2,
        }
    }
}

/// A Python module defined via source code.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonModuleSource {
    /// The fully qualified Python module name.
    pub name: String,
    /// Python source code.
    pub source: FileData,
    /// Whether this module is also a package.
    pub is_package: bool,
    /// Tag to apply to bytecode files.
    ///
    /// e.g. `cpython-39`.
    pub cache_tag: String,
    /// Whether this module belongs to the Python standard library.
    ///
    /// Modules with this set are distributed as part of Python itself.
    pub is_stdlib: bool,
    /// Whether this module is a test module.
    ///
    /// Test modules are those defining test code and aren't critical to
    /// run-time functionality of a package.
    pub is_test: bool,
}

impl PythonModuleSource {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            name: self.name.clone(),
            source: self.source.to_memory()?,
            is_package: self.is_package,
            cache_tag: self.cache_tag.clone(),
            is_stdlib: self.is_stdlib,
            is_test: self.is_test,
        })
    }

    /// Resolve the package containing this module.
    ///
    /// If this module is a package, returns the name of self.
    pub fn package(&self) -> String {
        if self.is_package {
            self.name.clone()
        } else if let Some(idx) = self.name.rfind('.') {
            self.name[0..idx].to_string()
        } else {
            self.name.clone()
        }
    }

    /// Obtain the top-level package name this module belongs to.
    pub fn top_level_package(&self) -> &str {
        if let Some(idx) = self.name.find('.') {
            &self.name[0..idx]
        } else {
            &self.name
        }
    }

    /// Convert the instance to a BytecodeModule.
    pub fn as_bytecode_module(
        &self,
        optimize_level: BytecodeOptimizationLevel,
    ) -> PythonModuleBytecodeFromSource {
        PythonModuleBytecodeFromSource {
            name: self.name.clone(),
            source: self.source.clone(),
            optimize_level,
            is_package: self.is_package,
            cache_tag: self.cache_tag.clone(),
            is_stdlib: self.is_stdlib,
            is_test: self.is_test,
        }
    }

    /// Resolve the filesystem path for this source module.
    pub fn resolve_path(&self, prefix: &str) -> PathBuf {
        resolve_path_for_module(prefix, &self.name, self.is_package, None)
    }

    /// Whether the source code for this module has __file__
    pub fn has_dunder_file(&self) -> Result<bool> {
        has_dunder_file(&self.source.resolve_content()?)
    }
}

/// Python module bytecode defined via source code.
///
/// This is essentially a request to generate bytecode from Python module
/// source code.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonModuleBytecodeFromSource {
    pub name: String,
    pub source: FileData,
    pub optimize_level: BytecodeOptimizationLevel,
    pub is_package: bool,
    /// Tag to apply to bytecode files.
    ///
    /// e.g. `cpython-39`.
    pub cache_tag: String,
    /// Whether this module belongs to the Python standard library.
    ///
    /// Modules with this set are distributed as part of Python itself.
    pub is_stdlib: bool,
    /// Whether this module is a test module.
    ///
    /// Test modules are those defining test code and aren't critical to
    /// run-time functionality of a package.
    pub is_test: bool,
}

impl PythonModuleBytecodeFromSource {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            name: self.name.clone(),
            source: self.source.to_memory()?,
            optimize_level: self.optimize_level,
            is_package: self.is_package,
            cache_tag: self.cache_tag.clone(),
            is_stdlib: self.is_stdlib,
            is_test: self.is_test,
        })
    }

    /// Compile source to bytecode using a compiler.
    pub fn compile(
        &self,
        compiler: &mut dyn PythonBytecodeCompiler,
        mode: CompileMode,
    ) -> Result<Vec<u8>> {
        compiler.compile(
            &self.source.resolve_content()?,
            &self.name,
            self.optimize_level,
            mode,
        )
    }

    /// Resolve filesystem path to this bytecode.
    pub fn resolve_path(&self, prefix: &str) -> PathBuf {
        let bytecode_tag = match self.optimize_level {
            BytecodeOptimizationLevel::Zero => self.cache_tag.clone(),
            BytecodeOptimizationLevel::One => format!("{}.opt-1", self.cache_tag),
            BytecodeOptimizationLevel::Two => format!("{}.opt-2", self.cache_tag),
        };

        resolve_path_for_module(prefix, &self.name, self.is_package, Some(&bytecode_tag))
    }

    /// Whether the source for this module has __file__.
    pub fn has_dunder_file(&self) -> Result<bool> {
        has_dunder_file(&self.source.resolve_content()?)
    }
}

/// Compiled Python module bytecode.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonModuleBytecode {
    pub name: String,
    bytecode: FileData,
    pub optimize_level: BytecodeOptimizationLevel,
    pub is_package: bool,
    /// Tag to apply to bytecode files.
    ///
    /// e.g. `cpython-39`.
    pub cache_tag: String,
    /// Whether this module belongs to the Python standard library.
    ///
    /// Modules with this set are distributed as part of Python itself.
    pub is_stdlib: bool,
    /// Whether this module is a test module.
    ///
    /// Test modules are those defining test code and aren't critical to
    /// run-time functionality of a package.
    pub is_test: bool,
}

impl PythonModuleBytecode {
    pub fn new(
        name: &str,
        optimize_level: BytecodeOptimizationLevel,
        is_package: bool,
        cache_tag: &str,
        data: &[u8],
    ) -> Self {
        Self {
            name: name.to_string(),
            bytecode: FileData::Memory(data.to_vec()),
            optimize_level,
            is_package,
            cache_tag: cache_tag.to_string(),
            is_stdlib: false,
            is_test: false,
        }
    }

    pub fn from_path(
        name: &str,
        optimize_level: BytecodeOptimizationLevel,
        cache_tag: &str,
        path: &Path,
    ) -> Self {
        Self {
            name: name.to_string(),
            bytecode: FileData::Path(path.to_path_buf()),
            optimize_level,
            is_package: is_package_from_path(path),
            cache_tag: cache_tag.to_string(),
            is_stdlib: false,
            is_test: false,
        }
    }

    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            name: self.name.clone(),
            bytecode: FileData::Memory(self.resolve_bytecode()?),
            optimize_level: self.optimize_level,
            is_package: self.is_package,
            cache_tag: self.cache_tag.clone(),
            is_stdlib: self.is_stdlib,
            is_test: self.is_test,
        })
    }

    /// Resolve the bytecode data for this module.
    pub fn resolve_bytecode(&self) -> Result<Vec<u8>> {
        match &self.bytecode {
            FileData::Memory(data) => Ok(data.clone()),
            FileData::Path(path) => {
                let data = std::fs::read(path)?;

                if data.len() >= 16 {
                    Ok(data[16..data.len()].to_vec())
                } else {
                    Err(anyhow!("bytecode file is too short"))
                }
            }
        }
    }

    /// Sets the bytecode for this module.
    pub fn set_bytecode(&mut self, data: &[u8]) {
        self.bytecode = FileData::Memory(data.to_vec());
    }

    /// Resolve filesystem path to this bytecode.
    pub fn resolve_path(&self, prefix: &str) -> PathBuf {
        let bytecode_tag = match self.optimize_level {
            BytecodeOptimizationLevel::Zero => self.cache_tag.clone(),
            BytecodeOptimizationLevel::One => format!("{}.opt-1", self.cache_tag),
            BytecodeOptimizationLevel::Two => format!("{}.opt-2", self.cache_tag),
        };

        resolve_path_for_module(prefix, &self.name, self.is_package, Some(&bytecode_tag))
    }
}

/// Python package resource data, agnostic of storage location.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonPackageResource {
    /// The leaf-most Python package this resource belongs to.
    pub leaf_package: String,
    /// The relative path within `leaf_package` to this resource.
    pub relative_name: String,
    /// Location of resource data.
    pub data: FileData,
    /// Whether this resource belongs to the Python standard library.
    ///
    /// Modules with this set are distributed as part of Python itself.
    pub is_stdlib: bool,
    /// Whether this resource belongs to a package that is a test.
    pub is_test: bool,
}

impl PythonPackageResource {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            leaf_package: self.leaf_package.clone(),
            relative_name: self.relative_name.clone(),
            data: self.data.to_memory()?,
            is_stdlib: self.is_stdlib,
            is_test: self.is_test,
        })
    }

    pub fn symbolic_name(&self) -> String {
        format!("{}:{}", self.leaf_package, self.relative_name)
    }

    /// Resolve filesystem path to this bytecode.
    pub fn resolve_path(&self, prefix: &str) -> PathBuf {
        let mut path = PathBuf::from(prefix);

        for p in self.leaf_package.split('.') {
            path = path.join(p);
        }

        path = path.join(&self.relative_name);

        path
    }
}

/// Represents where a Python package distribution resource is materialized.
#[derive(Clone, Debug, PartialEq)]
pub enum PythonPackageDistributionResourceFlavor {
    /// In a .dist-info directory.
    DistInfo,

    /// In a .egg-info directory.
    EggInfo,
}

/// Represents a file defining Python package metadata.
///
/// Instances of this correspond to files in a `<package>-<version>.dist-info`
/// or `.egg-info` directory.
///
/// In terms of `importlib.metadata` terminology, instances correspond to
/// files in a `Distribution`.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonPackageDistributionResource {
    /// Where the resource is materialized.
    pub location: PythonPackageDistributionResourceFlavor,

    /// The name of the Python package this resource is associated with.
    pub package: String,

    /// Version string of Python package.
    pub version: String,

    /// Name of this resource within the distribution.
    ///
    /// Corresponds to the file name in the `.dist-info` directory for this
    /// package distribution.
    pub name: String,

    /// The raw content of the distribution resource.
    pub data: FileData,
}

impl PythonPackageDistributionResource {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            location: self.location.clone(),
            package: self.package.clone(),
            version: self.version.clone(),
            name: self.name.clone(),
            data: self.data.to_memory()?,
        })
    }

    /// Resolve filesystem path to this resource file.
    pub fn resolve_path(&self, prefix: &str) -> PathBuf {
        // The package name has hyphens normalized to underscores when
        // materialized on the filesystem.
        let normalized_package = self.package.to_lowercase().replace('-', "_");

        let p = match self.location {
            PythonPackageDistributionResourceFlavor::DistInfo => {
                format!("{}-{}.dist-info", normalized_package, self.version)
            }
            PythonPackageDistributionResourceFlavor::EggInfo => {
                format!("{}-{}.egg-info", normalized_package, self.version)
            }
        };

        PathBuf::from(prefix).join(p).join(&self.name)
    }
}

/// Represents a dependency on a library.
///
/// The library can be defined a number of ways and multiple variants may be
/// present.
#[derive(Clone, Debug, PartialEq)]
pub struct LibraryDependency {
    /// Name of the library.
    ///
    /// This will be used to tell the linker what to link.
    pub name: String,

    /// Static library version of library.
    pub static_library: Option<FileData>,

    /// The filename the static library should be materialized as.
    pub static_filename: Option<PathBuf>,

    /// Shared library version of library.
    pub dynamic_library: Option<FileData>,

    /// The filename the dynamic library should be materialized as.
    pub dynamic_filename: Option<PathBuf>,

    /// Whether this is a system framework (macOS).
    pub framework: bool,

    /// Whether this is a system library.
    pub system: bool,
}

impl LibraryDependency {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            name: self.name.clone(),
            static_library: if let Some(data) = &self.static_library {
                Some(data.to_memory()?)
            } else {
                None
            },
            static_filename: self.static_filename.clone(),
            dynamic_library: if let Some(data) = &self.dynamic_library {
                Some(data.to_memory()?)
            } else {
                None
            },
            dynamic_filename: self.dynamic_filename.clone(),
            framework: self.framework,
            system: self.system,
        })
    }
}

/// Represents a shared library.
#[derive(Clone, Debug, PartialEq)]
pub struct SharedLibrary {
    /// Name of the library.
    ///
    /// This is the import name, not the full filename.
    pub name: String,

    /// Holds the raw content of the shared library.
    pub data: FileData,

    /// The filename the library should be materialized as.
    pub filename: Option<PathBuf>,
}

impl TryFrom<&LibraryDependency> for SharedLibrary {
    type Error = &'static str;

    fn try_from(value: &LibraryDependency) -> Result<Self, Self::Error> {
        if let Some(data) = &value.dynamic_library {
            Ok(Self {
                name: value.name.clone(),
                data: data.clone(),
                filename: value.dynamic_filename.clone(),
            })
        } else {
            Err("library dependency does not have a shared library")
        }
    }
}

/// Represents a Python extension module.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonExtensionModule {
    /// The module name this extension module is providing.
    pub name: String,
    /// Name of the C function initializing this extension module.
    pub init_fn: Option<String>,
    /// Filename suffix to use when writing extension module data.
    pub extension_file_suffix: String,
    /// File data for linked extension module.
    pub shared_library: Option<FileData>,
    // TODO capture static library?
    /// File data for object files linked together to produce this extension module.
    pub object_file_data: Vec<FileData>,
    /// Whether this extension module is a package.
    pub is_package: bool,
    /// Libraries that this extension depends on.
    pub link_libraries: Vec<LibraryDependency>,
    /// Whether this extension module is part of the Python standard library.
    ///
    /// This is true if the extension is distributed with Python itself.
    pub is_stdlib: bool,
    /// Whether the extension module is built-in by default.
    ///
    /// Some extension modules in Python distributions are always compiled into
    /// libpython. This field will be true for those extension modules.
    pub builtin_default: bool,
    /// Whether the extension must be loaded to initialize Python.
    pub required: bool,
    /// Name of the variant of this extension module.
    ///
    /// This may be set if there are multiple versions of an extension module
    /// available to choose from.
    pub variant: Option<String>,
    /// Licenses that apply to this extension.
    pub license: Option<LicensedComponent>,
}

impl PythonExtensionModule {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            name: self.name.clone(),
            init_fn: self.init_fn.clone(),
            extension_file_suffix: self.extension_file_suffix.clone(),
            shared_library: if let Some(data) = &self.shared_library {
                Some(data.to_memory()?)
            } else {
                None
            },
            object_file_data: self.object_file_data.clone(),
            is_package: self.is_package,
            link_libraries: self
                .link_libraries
                .iter()
                .map(|l| l.to_memory())
                .collect::<Result<Vec<_>, _>>()?,
            is_stdlib: self.is_stdlib,
            builtin_default: self.builtin_default,
            required: self.required,
            variant: self.variant.clone(),
            license: self.license.clone(),
        })
    }

    /// The file name (without parent components) this extension module should be
    /// realized with.
    pub fn file_name(&self) -> String {
        if let Some(idx) = self.name.rfind('.') {
            let name = &self.name[idx + 1..self.name.len()];
            format!("{}{}", name, self.extension_file_suffix)
        } else {
            format!("{}{}", self.name, self.extension_file_suffix)
        }
    }

    /// Resolve the filesystem path for this extension module.
    pub fn resolve_path(&self, prefix: &str) -> PathBuf {
        let mut path = PathBuf::from(prefix);
        path.extend(self.package_parts());
        path.push(self.file_name());

        path
    }

    /// Returns the part strings constituting the package name.
    pub fn package_parts(&self) -> Vec<String> {
        if let Some(idx) = self.name.rfind('.') {
            let prefix = &self.name[0..idx];
            prefix.split('.').map(|x| x.to_string()).collect()
        } else {
            Vec::new()
        }
    }

    /// Whether the extension module requires additional libraries.
    pub fn requires_libraries(&self) -> bool {
        !self.link_libraries.is_empty()
    }

    /// Whether the extension module is minimally required for a Python interpreter.
    ///
    /// This will be true only for extension modules in the standard library that
    /// are builtins part of libpython or are required as part of Python interpreter
    /// initialization.
    pub fn is_minimally_required(&self) -> bool {
        self.is_stdlib && (self.builtin_default || self.required)
    }

    /// Whether this extension module is already in libpython.
    ///
    /// This is true if this is a stdlib extension module and is a core module or no
    /// shared library extension module is available.
    pub fn in_libpython(&self) -> bool {
        self.is_stdlib && (self.builtin_default || self.shared_library.is_none())
    }

    /// Obtain the top-level package name this module belongs to.
    pub fn top_level_package(&self) -> &str {
        if let Some(idx) = self.name.find('.') {
            &self.name[0..idx]
        } else {
            &self.name
        }
    }
}

/// Represents a collection of variants for a given Python extension module.
#[derive(Clone, Debug)]
pub struct PythonExtensionModuleVariants {
    extensions: Vec<PythonExtensionModule>,
}

impl Default for PythonExtensionModuleVariants {
    fn default() -> Self {
        Self { extensions: vec![] }
    }
}

impl FromIterator<PythonExtensionModule> for PythonExtensionModuleVariants {
    fn from_iter<I: IntoIterator<Item = PythonExtensionModule>>(iter: I) -> Self {
        Self {
            extensions: Vec::from_iter(iter),
        }
    }
}

impl PythonExtensionModuleVariants {
    pub fn push(&mut self, em: PythonExtensionModule) {
        self.extensions.push(em);
    }

    pub fn is_empty(&self) -> bool {
        self.extensions.is_empty()
    }

    pub fn iter(&self) -> impl Iterator<Item = &PythonExtensionModule> {
        self.extensions.iter()
    }

    /// Obtains the default / first variant of an extension module.
    pub fn default_variant(&self) -> &PythonExtensionModule {
        &self.extensions[0]
    }

    /// Choose a variant given preferences.
    pub fn choose_variant<S: BuildHasher>(
        &self,
        variants: &HashMap<String, String, S>,
    ) -> &PythonExtensionModule {
        // The default / first item is the chosen one by default.
        let mut chosen = self.default_variant();

        // But it can be overridden if we passed in a hash defining variant
        // preferences, the hash contains a key with the extension name, and the
        // requested variant value exists.
        if let Some(preferred) = variants.get(&chosen.name) {
            for em in self.iter() {
                if em.variant == Some(preferred.to_string()) {
                    chosen = em;
                    break;
                }
            }
        }

        chosen
    }
}

/// Represents a Python .egg file.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonEggFile {
    /// Content of the .egg file.
    pub data: FileData,
}

impl PythonEggFile {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            data: self.data.to_memory()?,
        })
    }
}

/// Represents a Python path extension.
///
/// i.e. a .pth file.
#[derive(Clone, Debug, PartialEq)]
pub struct PythonPathExtension {
    /// Content of the .pth file.
    pub data: FileData,
}

impl PythonPathExtension {
    pub fn to_memory(&self) -> Result<Self> {
        Ok(Self {
            data: self.data.to_memory()?,
        })
    }
}

/// Represents a resource that can be read by Python somehow.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum PythonResource<'a> {
    /// A module defined by source code.
    ModuleSource(Cow<'a, PythonModuleSource>),
    /// A module defined by a request to generate bytecode from source.
    ModuleBytecodeRequest(Cow<'a, PythonModuleBytecodeFromSource>),
    /// A module defined by existing bytecode.
    ModuleBytecode(Cow<'a, PythonModuleBytecode>),
    /// A non-module resource file.
    PackageResource(Cow<'a, PythonPackageResource>),
    /// A file in a Python package distribution metadata collection.
    PackageDistributionResource(Cow<'a, PythonPackageDistributionResource>),
    /// An extension module.
    ExtensionModule(Cow<'a, PythonExtensionModule>),
    /// A self-contained Python egg.
    EggFile(Cow<'a, PythonEggFile>),
    /// A path extension.
    PathExtension(Cow<'a, PythonPathExtension>),
    /// An arbitrary file and its data.
    File(Cow<'a, File>),
}

impl<'a> PythonResource<'a> {
    /// Resolves the fully qualified resource name.
    pub fn full_name(&self) -> String {
        match self {
            PythonResource::ModuleSource(m) => m.name.clone(),
            PythonResource::ModuleBytecode(m) => m.name.clone(),
            PythonResource::ModuleBytecodeRequest(m) => m.name.clone(),
            PythonResource::PackageResource(resource) => {
                format!("{}.{}", resource.leaf_package, resource.relative_name)
            }
            PythonResource::PackageDistributionResource(resource) => {
                format!("{}:{}", resource.package, resource.name)
            }
            PythonResource::ExtensionModule(em) => em.name.clone(),
            PythonResource::EggFile(_) => "".to_string(),
            PythonResource::PathExtension(_) => "".to_string(),
            PythonResource::File(f) => format!("{}", f.path().display()),
        }
    }

    pub fn is_in_packages(&self, packages: &[String]) -> bool {
        let name = match self {
            PythonResource::ModuleSource(m) => &m.name,
            PythonResource::ModuleBytecode(m) => &m.name,
            PythonResource::ModuleBytecodeRequest(m) => &m.name,
            PythonResource::PackageResource(resource) => &resource.leaf_package,
            PythonResource::PackageDistributionResource(resource) => &resource.package,
            PythonResource::ExtensionModule(em) => &em.name,
            PythonResource::EggFile(_) => return false,
            PythonResource::PathExtension(_) => return false,
            PythonResource::File(_) => return false,
        };

        for package in packages {
            // Even though the entity may not be marked as a package, we allow exact
            // name matches through the filter because this makes sense for filtering.
            // The package annotation is really only useful to influence file layout,
            // when __init__.py files need to be materialized.
            if name == package || packages_from_module_name(&name).contains(package) {
                return true;
            }
        }

        false
    }

    /// Create a new instance that is guaranteed to be backed by memory.
    pub fn to_memory(&self) -> Result<Self> {
        Ok(match self {
            PythonResource::ModuleSource(m) => m.to_memory()?.into(),
            PythonResource::ModuleBytecode(m) => m.to_memory()?.into(),
            PythonResource::ModuleBytecodeRequest(m) => m.to_memory()?.into(),
            PythonResource::PackageResource(r) => r.to_memory()?.into(),
            PythonResource::PackageDistributionResource(r) => r.to_memory()?.into(),
            PythonResource::ExtensionModule(m) => m.to_memory()?.into(),
            PythonResource::EggFile(e) => e.to_memory()?.into(),
            PythonResource::PathExtension(e) => e.to_memory()?.into(),
            PythonResource::File(f) => f.to_memory()?.into(),
        })
    }
}

impl<'a> From<PythonModuleSource> for PythonResource<'a> {
    fn from(m: PythonModuleSource) -> Self {
        PythonResource::ModuleSource(Cow::Owned(m))
    }
}

impl<'a> From<&'a PythonModuleSource> for PythonResource<'a> {
    fn from(m: &'a PythonModuleSource) -> Self {
        PythonResource::ModuleSource(Cow::Borrowed(m))
    }
}

impl<'a> From<PythonModuleBytecodeFromSource> for PythonResource<'a> {
    fn from(m: PythonModuleBytecodeFromSource) -> Self {
        PythonResource::ModuleBytecodeRequest(Cow::Owned(m))
    }
}

impl<'a> From<&'a PythonModuleBytecodeFromSource> for PythonResource<'a> {
    fn from(m: &'a PythonModuleBytecodeFromSource) -> Self {
        PythonResource::ModuleBytecodeRequest(Cow::Borrowed(m))
    }
}

impl<'a> From<PythonModuleBytecode> for PythonResource<'a> {
    fn from(m: PythonModuleBytecode) -> Self {
        PythonResource::ModuleBytecode(Cow::Owned(m))
    }
}

impl<'a> From<&'a PythonModuleBytecode> for PythonResource<'a> {
    fn from(m: &'a PythonModuleBytecode) -> Self {
        PythonResource::ModuleBytecode(Cow::Borrowed(m))
    }
}

impl<'a> From<PythonPackageResource> for PythonResource<'a> {
    fn from(r: PythonPackageResource) -> Self {
        PythonResource::PackageResource(Cow::Owned(r))
    }
}

impl<'a> From<&'a PythonPackageResource> for PythonResource<'a> {
    fn from(r: &'a PythonPackageResource) -> Self {
        PythonResource::PackageResource(Cow::Borrowed(r))
    }
}

impl<'a> From<PythonPackageDistributionResource> for PythonResource<'a> {
    fn from(r: PythonPackageDistributionResource) -> Self {
        PythonResource::PackageDistributionResource(Cow::Owned(r))
    }
}

impl<'a> From<&'a PythonPackageDistributionResource> for PythonResource<'a> {
    fn from(r: &'a PythonPackageDistributionResource) -> Self {
        PythonResource::PackageDistributionResource(Cow::Borrowed(r))
    }
}

impl<'a> From<PythonExtensionModule> for PythonResource<'a> {
    fn from(r: PythonExtensionModule) -> Self {
        PythonResource::ExtensionModule(Cow::Owned(r))
    }
}

impl<'a> From<&'a PythonExtensionModule> for PythonResource<'a> {
    fn from(r: &'a PythonExtensionModule) -> Self {
        PythonResource::ExtensionModule(Cow::Borrowed(r))
    }
}

impl<'a> From<PythonEggFile> for PythonResource<'a> {
    fn from(e: PythonEggFile) -> Self {
        PythonResource::EggFile(Cow::Owned(e))
    }
}

impl<'a> From<&'a PythonEggFile> for PythonResource<'a> {
    fn from(e: &'a PythonEggFile) -> Self {
        PythonResource::EggFile(Cow::Borrowed(e))
    }
}

impl<'a> From<PythonPathExtension> for PythonResource<'a> {
    fn from(e: PythonPathExtension) -> Self {
        PythonResource::PathExtension(Cow::Owned(e))
    }
}

impl<'a> From<&'a PythonPathExtension> for PythonResource<'a> {
    fn from(e: &'a PythonPathExtension) -> Self {
        PythonResource::PathExtension(Cow::Borrowed(e))
    }
}

impl<'a> From<File> for PythonResource<'a> {
    fn from(f: File) -> Self {
        PythonResource::File(Cow::Owned(f))
    }
}

impl<'a> From<&'a File> for PythonResource<'a> {
    fn from(f: &'a File) -> Self {
        PythonResource::File(Cow::Borrowed(f))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const DEFAULT_CACHE_TAG: &str = "cpython-39";

    #[test]
    fn test_is_in_packages() {
        let source = PythonResource::ModuleSource(Cow::Owned(PythonModuleSource {
            name: "foo".to_string(),
            source: FileData::Memory(vec![]),
            is_package: false,
            cache_tag: DEFAULT_CACHE_TAG.to_string(),
            is_stdlib: false,
            is_test: false,
        }));
        assert!(source.is_in_packages(&["foo".to_string()]));
        assert!(!source.is_in_packages(&[]));
        assert!(!source.is_in_packages(&["bar".to_string()]));

        let bytecode = PythonResource::ModuleBytecode(Cow::Owned(PythonModuleBytecode {
            name: "foo".to_string(),
            bytecode: FileData::Memory(vec![]),
            optimize_level: BytecodeOptimizationLevel::Zero,
            is_package: false,
            cache_tag: DEFAULT_CACHE_TAG.to_string(),
            is_stdlib: false,
            is_test: false,
        }));
        assert!(bytecode.is_in_packages(&["foo".to_string()]));
        assert!(!bytecode.is_in_packages(&[]));
        assert!(!bytecode.is_in_packages(&["bar".to_string()]));
    }

    #[test]
    fn package_distribution_resources_path_normalization() {
        // Package names are normalized to lowercase and have hyphens replaced
        // by underscores.
        let mut r = PythonPackageDistributionResource {
            location: PythonPackageDistributionResourceFlavor::DistInfo,
            package: "FoO-Bar".into(),
            version: "1.0".into(),
            name: "resource.txt".into(),
            data: vec![42].into(),
        };

        assert_eq!(
            r.resolve_path("prefix"),
            PathBuf::from("prefix")
                .join("foo_bar-1.0.dist-info")
                .join("resource.txt")
        );

        r.location = PythonPackageDistributionResourceFlavor::EggInfo;

        assert_eq!(
            r.resolve_path("prefix"),
            PathBuf::from("prefix")
                .join("foo_bar-1.0.egg-info")
                .join("resource.txt")
        );
    }
}