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
use std::{
    borrow::Cow,
    collections::BTreeMap,
    fmt::Debug,
    fs::File,
    io::{BufRead, BufReader},
    path::{Path, PathBuf},
};

use anyhow::{Context, Error};
use bytes::Bytes;
use flate2::bufread::GzDecoder;
use shared_buffer::OwnedBuffer;
use tar::Archive;
use tempfile::TempDir;
use wasmer_toml::Manifest as WasmerManifest;

use crate::{
    metadata::Manifest as WebcManifest,
    v2::{
        write::{FileEntry, Writer},
        ChecksumAlgorithm,
    },
    wasmer_package::{manifest::ManifestError, Strictness, Volume},
    PathSegment,
};

/// Errors that may occur while loading a Wasmer package from disk.
#[derive(Debug, thiserror::Error)]
#[allow(clippy::result_large_err)]
#[non_exhaustive]
pub enum WasmerPackageError {
    /// Unable to create a temporary directory.
    #[error("Unable to create a temporary directory")]
    TempDir(#[source] std::io::Error),
    /// Unable to open a file.
    #[error("Unable to open \"{}\"", path.display())]
    FileOpen {
        /// The file being opened.
        path: PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
    /// Unable to read a file.
    #[error("Unable to read \"{}\"", path.display())]
    FileRead {
        /// The file being opened.
        path: PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
    /// Unable to extract the tarball.
    #[error("Unable to extract the tarball")]
    Tarball(#[source] std::io::Error),
    /// Unable to deserialize the `wasmer.toml` file.
    #[error("Unable to deserialize \"{}\"", path.display())]
    DeserializeWasmerToml {
        /// The file being deserialized.
        path: PathBuf,
        /// The underlying error.
        #[source]
        error: toml::de::Error,
    },
    /// Unable to find the `wasmer.toml` file.
    #[error("Unable to find the \"wasmer.toml\"")]
    MissingManifest,
    /// Unable to canonicalize a path.
    #[error("Unable to get the absolute path for \"{}\"", path.display())]
    Canonicalize {
        /// The path being canonicalized.
        path: PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
    /// Unable to load the `wasmer.toml` manifest.
    #[error("Unable to load the \"wasmer.toml\" manifest")]
    Manifest(#[from] ManifestError),
    /// A manifest validation error.
    #[error("The manifest is invalid")]
    Validation(#[from] wasmer_toml::ValidationError),
}

/// A Wasmer package that will be lazily loaded from disk.
#[derive(Debug)]
pub struct Package {
    manifest: WebcManifest,
    original_manifest: WasmerManifest,
    atoms: BTreeMap<String, OwnedBuffer>,
    base_dir: BaseDir,
    strictness: Strictness,
}

impl Package {
    /// Load a [`Package`] from a `*.tar.gz` file on disk.
    ///
    /// # Implementation Details
    ///
    /// This will unpack the tarball to a temporary directory on disk and use
    /// memory-mapped files in order to reduce RAM usage.
    pub fn from_tarball_file(path: impl AsRef<Path>) -> Result<Self, WasmerPackageError> {
        Package::from_tarball_file_with_strictness(path.as_ref(), Strictness::default())
    }
    /// Load a [`Package`] from a `*.tar.gz` file on disk.
    ///
    /// # Implementation Details
    ///
    /// This will unpack the tarball to a temporary directory on disk and use
    /// memory-mapped files in order to reduce RAM usage.
    pub fn from_tarball_file_with_strictness(
        path: impl AsRef<Path>,
        strictness: Strictness,
    ) -> Result<Self, WasmerPackageError> {
        let path = path.as_ref();
        let f = File::open(path).map_err(|error| WasmerPackageError::FileOpen {
            path: path.to_path_buf(),
            error,
        })?;

        Package::from_tarball_with_strictness(BufReader::new(f), strictness)
    }

    /// Load a package from a `*.tar.gz` archive.
    pub fn from_tarball(tarball: impl BufRead) -> Result<Self, WasmerPackageError> {
        Package::from_tarball_with_strictness(tarball, Strictness::default())
    }

    /// Load a package from a `*.tar.gz` archive.
    pub fn from_tarball_with_strictness(
        tarball: impl BufRead,
        strictness: Strictness,
    ) -> Result<Self, WasmerPackageError> {
        let tarball = GzDecoder::new(tarball);
        let temp = tempdir().map_err(WasmerPackageError::TempDir)?;
        let archive = Archive::new(tarball);
        unpack_archive(archive, temp.path()).map_err(WasmerPackageError::Tarball)?;

        let manifest = read_manifest(temp.path())?;

        Package::load(manifest, temp, strictness)
    }

    /// Load a package from a `wasmer.toml` manifest on disk.
    pub fn from_manifest(wasmer_toml: impl AsRef<Path>) -> Result<Self, WasmerPackageError> {
        Package::from_manifest_with_strictness(wasmer_toml, Strictness::default())
    }

    /// Load a package from a `wasmer.toml` manifest on disk.
    pub fn from_manifest_with_strictness(
        wasmer_toml: impl AsRef<Path>,
        strictness: Strictness,
    ) -> Result<Self, WasmerPackageError> {
        let path = wasmer_toml.as_ref();
        let path = path
            .canonicalize()
            .map_err(|error| WasmerPackageError::Canonicalize {
                path: path.to_path_buf(),
                error,
            })?;

        let wasmer_toml =
            std::fs::read_to_string(&path).map_err(|error| WasmerPackageError::FileRead {
                path: path.to_path_buf(),
                error,
            })?;
        let wasmer_toml = toml::from_str(&wasmer_toml).map_err(|error| {
            WasmerPackageError::DeserializeWasmerToml {
                path: path.to_path_buf(),
                error,
            }
        })?;

        let base_dir = path
            .parent()
            .expect("Canonicalizing should always result in a file with a parent directory")
            .to_path_buf();

        Package::load(wasmer_toml, base_dir, strictness)
    }

    fn load(
        wasmer_toml: WasmerManifest,
        base_dir: impl Into<BaseDir>,
        strictness: Strictness,
    ) -> Result<Self, WasmerPackageError> {
        let base_dir = base_dir.into();

        if strictness.is_strict() {
            wasmer_toml.validate()?;
        }

        let (manifest, atoms) = crate::wasmer_package::manifest::wasmer_manifest_to_webc(
            &wasmer_toml,
            base_dir.path(),
            strictness,
        )?;

        Ok(Package {
            manifest,
            original_manifest: wasmer_toml,
            atoms,
            base_dir,
            strictness,
        })
    }

    /// Get the WEBC manifest.
    pub fn manifest(&self) -> &WebcManifest {
        &self.manifest
    }

    /// Get all atoms in this package.
    pub fn atoms(&self) -> &BTreeMap<String, OwnedBuffer> {
        &self.atoms
    }

    /// Serialize the package to a `*.webc` v2 file, ignoring errors due to
    /// missing files.
    pub fn serialize(&self) -> Result<Bytes, Error> {
        let metadata_volume = self.metadata_volume()?;
        let asset_volume = self.asset_volume()?;

        let w = Writer::new(ChecksumAlgorithm::Sha256)
            .write_manifest(self.manifest())?
            .write_atoms(self.atom_entries()?)?
            .with_volume(
                Volume::METADATA,
                metadata_volume.as_directory_tree(self.strictness)?,
            )?
            .with_volume(
                Volume::ASSET,
                asset_volume.as_directory_tree(self.strictness)?,
            )?;

        let serialized = w.finish(crate::v2::SignatureAlgorithm::None)?;

        Ok(serialized)
    }

    fn atom_entries(&self) -> Result<BTreeMap<PathSegment, FileEntry<'_>>, Error> {
        self.atoms()
            .iter()
            .map(|(key, value)| {
                let filename = PathSegment::parse(key)
                    .with_context(|| format!("\"{key}\" isn't a valid atom name"))?;
                Ok((filename, FileEntry::Borrowed(value)))
            })
            .collect()
    }

    /// Get a volume containing the package's metadata.
    pub fn metadata_volume(&self) -> Result<Volume, Error> {
        Volume::new_metadata(&self.original_manifest, self.base_dir().to_path_buf())
    }

    /// Get a volume containing the package's assets.
    pub fn asset_volume(&self) -> Result<Volume, Error> {
        Volume::new_asset(&self.original_manifest, self.base_dir())
    }

    pub(crate) fn get_volume(&self, name: &str) -> Option<Volume> {
        match name {
            Volume::METADATA => Volume::new_metadata(&self.original_manifest, self.base_dir()).ok(),
            Volume::ASSET => Volume::new_asset(&self.original_manifest, self.base_dir()).ok(),
            _ => None,
        }
    }

    pub(crate) fn volume_names(&self) -> Vec<Cow<'static, str>> {
        vec![
            Cow::Borrowed(Volume::METADATA),
            Cow::Borrowed(Volume::ASSET),
        ]
    }

    fn base_dir(&self) -> &Path {
        self.base_dir.path()
    }
}

const IS_WASI: bool = cfg!(all(target_family = "wasm", target_os = "wasi"));

/// A polyfill for [`TempDir::new()`] that will work when compiling to
/// WASI-based targets.
///
/// This works around [`std::env::temp_dir()`][tempdir] panicking
/// unconditionally on WASI.
///
/// [tempdir]: https://github.com/wasix-org/rust/blob/ef19cdcdff77047f1e5ea4d09b4869d6fa456cc7/library/std/src/sys/wasi/os.rs#L228-L230
fn tempdir() -> Result<TempDir, std::io::Error> {
    if !IS_WASI {
        // The happy path.
        return TempDir::new();
    }

    // Note: When compiling to wasm32-wasi, we can't use TempDir::new()
    // because std::env::temp_dir() will unconditionally panic.
    let temp_dir: PathBuf = std::env::var("TMPDIR")
        .unwrap_or_else(|_| "/tmp".to_string())
        .into();

    if temp_dir.exists() {
        TempDir::new_in(temp_dir)
    } else {
        // The temporary directory doesn't exist. A naive create_dir_all()
        // doesn't work when running with "wasmer run" because the root
        // directory is immutable, so let's try to use the current exe's
        // directory as our tempdir.
        // See also: https://github.com/wasmerio/wasmer/blob/482b78890b789f6867a91be9f306385e6255b260/lib/wasix/src/syscalls/wasi/path_create_directory.rs#L30-L32
        if let Ok(current_exe) = std::env::current_exe() {
            if let Some(parent) = current_exe.parent() {
                if let Ok(temp) = TempDir::new_in(parent) {
                    return Ok(temp);
                }
            }
        }

        // Oh well, this will probably fail, but at least we tried.
        std::fs::create_dir_all(&temp_dir)?;
        TempDir::new_in(temp_dir)
    }
}

/// A polyfill for [`Archive::unpack()`] that is WASI-compatible.
///
/// This works around `canonicalize()` being [unsupported][github] on
/// `wasm32-wasi`.
///
/// [github]: https://github.com/rust-lang/rust/blob/5b1dc9de77106cb08ce9a1a8deaa14f52751d7e4/library/std/src/sys/wasi/fs.rs#L654-L658
fn unpack_archive(
    mut archive: Archive<impl std::io::Read>,
    dest: &Path,
) -> Result<(), std::io::Error> {
    if !IS_WASI {
        // The happy path.
        return archive.unpack(dest);
    }

    // A naive version of unpack() that should be good enough for WASI
    // https://github.com/alexcrichton/tar-rs/blob/c77f47cb1b4b47fc4404a170d9d91cb42cc762ea/src/archive.rs#L216-L247

    for entry in archive.entries()? {
        let mut entry = entry?;
        let item_path = entry.path()?;
        let full_path = resolve_archive_path(dest, &item_path);

        match entry.header().entry_type() {
            tar::EntryType::Directory => {
                std::fs::create_dir_all(&full_path)?;
            }
            tar::EntryType::Regular => {
                if let Some(parent) = full_path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                let mut f = File::create(&full_path)?;
                std::io::copy(&mut entry, &mut f)?;
            }
            _ => {}
        }
    }

    Ok(())
}

fn resolve_archive_path(base_dir: &Path, path: &Path) -> PathBuf {
    let mut buffer = base_dir.to_path_buf();

    for component in path.components() {
        match component {
            std::path::Component::Prefix(_)
            | std::path::Component::RootDir
            | std::path::Component::CurDir => continue,
            std::path::Component::ParentDir => {
                buffer.pop();
            }
            std::path::Component::Normal(segment) => {
                buffer.push(segment);
            }
        }
    }

    buffer
}

fn read_manifest(base_dir: &Path) -> Result<WasmerManifest, WasmerPackageError> {
    for path in ["wasmer.toml", "wapm.toml"] {
        let path = base_dir.join(path);

        match std::fs::read_to_string(&path) {
            Ok(s) => {
                return toml::from_str(&s)
                    .map_err(|error| WasmerPackageError::DeserializeWasmerToml { path, error });
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(error) => {
                return Err(WasmerPackageError::FileRead { path, error });
            }
        }
    }

    Err(WasmerPackageError::MissingManifest)
}

#[derive(Debug)]
enum BaseDir {
    /// An existing directory.
    Path(PathBuf),
    /// A temporary directory that will be deleted on drop.
    Temp(TempDir),
}

impl BaseDir {
    fn path(&self) -> &Path {
        match self {
            BaseDir::Path(p) => p.as_path(),
            BaseDir::Temp(t) => t.path(),
        }
    }
}

impl From<TempDir> for BaseDir {
    fn from(v: TempDir) -> Self {
        Self::Temp(v)
    }
}

impl From<PathBuf> for BaseDir {
    fn from(v: PathBuf) -> Self {
        Self::Path(v)
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        metadata::{
            annotations::{FileSystemMapping, VolumeSpecificPath},
            Binding, BindingsExtended, WaiBindings, WitBindings,
        },
        Container,
    };
    use flate2::{write::GzEncoder, Compression};

    use super::*;

    #[test]
    fn nonexistent_files() {
        let temp = TempDir::new().unwrap();

        assert!(Package::from_manifest(temp.path().join("nonexistent.toml")).is_err());
        assert!(Package::from_tarball_file(temp.path().join("nonexistent.tar.gz")).is_err());
    }

    #[test]
    fn load_a_tarball() {
        let coreutils = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("wapm-targz-to-pirita")
            .join("fixtures")
            .join("coreutils-1.0.11.tar.gz");
        assert!(coreutils.exists());

        let package = Package::from_tarball_file(coreutils).unwrap();

        let wapm = package.manifest().wapm().unwrap().unwrap();
        assert_eq!(wapm.name, "sharrattj/coreutils");
        assert_eq!(wapm.version, "1.0.11");
    }

    #[test]
    fn tarball_with_no_manifest() {
        let temp = TempDir::new().unwrap();
        let empty_tarball = temp.path().join("empty.tar.gz");
        let mut f = File::create(&empty_tarball).unwrap();
        tar::Builder::new(GzEncoder::new(&mut f, Compression::fast()))
            .finish()
            .unwrap();

        assert!(Package::from_tarball_file(&empty_tarball).is_err());
    }

    #[test]
    fn empty_package_on_disk() {
        let temp = TempDir::new().unwrap();
        let manifest = temp.path().join("wasmer.toml");
        std::fs::write(
            &manifest,
            r#"
                [package]
                name = "some/package"
                version = "0.0.0"
                description = "A dummy package"
            "#,
        )
        .unwrap();

        let package = Package::from_manifest(&manifest).unwrap();

        let wapm = package.manifest().wapm().unwrap().unwrap();
        assert_eq!(wapm.name, "some/package");
        assert_eq!(wapm.version, "0.0.0");
    }

    #[test]
    fn load_old_cowsay() {
        let tarball = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("wapm-to-webc")
            .join("test")
            .join("fixtures")
            .join("cowsay-0.3.0.tar.gz");

        let pkg = Package::from_tarball_file(tarball).unwrap();

        insta::assert_yaml_snapshot!(pkg.manifest());
        assert_eq!(
            pkg.manifest.commands.keys().collect::<Vec<_>>(),
            ["cowsay", "cowthink"],
        );
    }

    #[test]
    fn serialize_package_with_bundled_directories() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
                [package]
                name = "some/package"
                version = "0.0.0"
                description = "Test package"

                [fs]
                "/first" = "./first"
                second = "nested/dir"
                "second/child" = "./third"
                empty = "empty"
            "#;
        let manifest = temp.path().join("wasmer.toml");
        std::fs::write(&manifest, wasmer_toml).unwrap();
        // Now we want to set up the following filesystem tree:
        //
        // - first/ ("/first")
        //   - file.txt
        // - nested/
        //   - dir/ ("second")
        //     - README.md
        //     - another-dir/
        //       - empty.txt
        // - third/ ("second/child")
        //   - file.txt
        // - empty/ ("empty")
        //
        // The "/first" entry
        let first = temp.path().join("first");
        std::fs::create_dir_all(&first).unwrap();
        std::fs::write(first.join("file.txt"), "File").unwrap();
        // The "second" entry
        let second = temp.path().join("nested").join("dir");
        std::fs::create_dir_all(&second).unwrap();
        std::fs::write(second.join("README.md"), "please").unwrap();
        let another_dir = temp.path().join("nested").join("dir").join("another-dir");
        std::fs::create_dir_all(&another_dir).unwrap();
        std::fs::write(another_dir.join("empty.txt"), "").unwrap();
        // The "second/child" entry
        let third = temp.path().join("third");
        std::fs::create_dir_all(&third).unwrap();
        std::fs::write(third.join("file.txt"), "Hello, World!").unwrap();
        // The "empty" entry
        let empty_dir = temp.path().join("empty");
        std::fs::create_dir_all(empty_dir).unwrap();

        let package = Package::from_manifest(manifest).unwrap();

        let webc = package.serialize().unwrap();
        let webc = Container::from_bytes(webc).unwrap();
        let manifest = webc.manifest();
        let wapm_metadata = manifest.wapm().unwrap().unwrap();
        assert_eq!(wapm_metadata.name, "some/package");
        let fs_table = manifest.filesystem().unwrap().unwrap();
        assert_eq!(
            fs_table,
            [
                FileSystemMapping {
                    from: None,
                    volume_name: "atom".to_string(),
                    original_path: "/first".to_string(),
                    mount_path: "/first".to_string(),
                },
                FileSystemMapping {
                    from: None,
                    volume_name: "atom".to_string(),
                    original_path: "/nested/dir".to_string(),
                    mount_path: "/second".to_string(),
                },
                FileSystemMapping {
                    from: None,
                    volume_name: "atom".to_string(),
                    original_path: "/third".to_string(),
                    mount_path: "/second/child".to_string(),
                },
                FileSystemMapping {
                    from: None,
                    volume_name: "atom".to_string(),
                    original_path: "/empty".to_string(),
                    mount_path: "/empty".to_string(),
                },
            ]
        );

        let atom_volume = webc.get_volume("atom").unwrap();
        assert_eq!(atom_volume.read_file("/first/file.txt").unwrap(), b"File");
        assert_eq!(
            atom_volume.read_file("/nested/dir/README.md").unwrap(),
            b"please"
        );
        assert_eq!(
            atom_volume
                .read_file("/nested/dir/another-dir/empty.txt")
                .unwrap(),
            b""
        );
        assert_eq!(
            atom_volume.read_file("/third/file.txt").unwrap(),
            b"Hello, World!"
        );
        assert_eq!(
            atom_volume.read_dir("/empty").unwrap().len(),
            0,
            "Directories should be included, even if empty"
        );
    }

    #[test]
    fn serialize_package_with_metadata_files() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
                [package]
                name = "some/package"
                version = "0.0.0"
                description = "Test package"
                readme = "README.md"
                license-file = "LICENSE"
            "#;
        let manifest = temp.path().join("wasmer.toml");
        std::fs::write(&manifest, wasmer_toml).unwrap();
        std::fs::write(temp.path().join("README.md"), "readme").unwrap();
        std::fs::write(temp.path().join("LICENSE"), "license").unwrap();

        let serialized = Package::from_manifest(manifest)
            .unwrap()
            .serialize()
            .unwrap();

        let webc = Container::from_bytes(serialized).unwrap();
        let metadata_volume = webc.get_volume("metadata").unwrap();
        assert_eq!(metadata_volume.read_file("/README.md").unwrap(), b"readme");
        assert_eq!(metadata_volume.read_file("/LICENSE").unwrap(), b"license");
    }

    #[test]
    fn load_package_with_wit_bindings() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = ""

            [[module]]
            name = "my-lib"
            source = "./my-lib.wasm"
            abi = "none"
            bindings = { wit-bindgen = "0.1.0", wit-exports = "./file.wit" }
        "#;
        std::fs::write(temp.path().join("wasmer.toml"), wasmer_toml).unwrap();
        std::fs::write(temp.path().join("file.wit"), "file").unwrap();
        std::fs::write(temp.path().join("my-lib.wasm"), b"\0asm...").unwrap();

        let package = Package::from_manifest(temp.path().join("wasmer.toml"))
            .unwrap()
            .serialize()
            .unwrap();
        let webc = Container::from_bytes(package).unwrap();

        assert_eq!(
            webc.manifest().bindings,
            vec![Binding {
                name: "library-bindings".to_string(),
                kind: "wit@0.1.0".to_string(),
                annotations: serde_cbor::value::to_value(BindingsExtended::Wit(WitBindings {
                    exports: "metadata://file.wit".to_string(),
                    module: "my-lib".to_string(),
                }))
                .unwrap(),
            }]
        );
        let metadata_volume = webc.get_volume("metadata").unwrap();
        assert_eq!(metadata_volume.read_file("/file.wit").unwrap(), b"file");
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(webc.manifest()); }
        }
    }

    #[test]
    fn load_package_with_wai_bindings() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = ""

            [[module]]
            name = "my-lib"
            source = "./my-lib.wasm"
            abi = "none"
            bindings = { wai-version = "0.2.0", exports = "./file.wai", imports = ["a.wai", "b.wai"] }
        "#;
        std::fs::write(temp.path().join("wasmer.toml"), wasmer_toml).unwrap();
        std::fs::write(temp.path().join("file.wai"), "file").unwrap();
        std::fs::write(temp.path().join("a.wai"), "a").unwrap();
        std::fs::write(temp.path().join("b.wai"), "b").unwrap();
        std::fs::write(temp.path().join("my-lib.wasm"), b"\0asm...").unwrap();

        let package = Package::from_manifest(temp.path().join("wasmer.toml"))
            .unwrap()
            .serialize()
            .unwrap();
        let webc = Container::from_bytes(package).unwrap();

        assert_eq!(
            webc.manifest().bindings,
            vec![Binding {
                name: "library-bindings".to_string(),
                kind: "wai@0.2.0".to_string(),
                annotations: serde_cbor::value::to_value(BindingsExtended::Wai(WaiBindings {
                    exports: Some("metadata://file.wai".to_string()),
                    module: "my-lib".to_string(),
                    imports: vec![
                        "metadata://a.wai".to_string(),
                        "metadata://b.wai".to_string(),
                    ]
                }))
                .unwrap(),
            }]
        );
        let metadata_volume = webc.get_volume("metadata").unwrap();
        assert_eq!(metadata_volume.read_file("/file.wai").unwrap(), b"file");
        assert_eq!(metadata_volume.read_file("/a.wai").unwrap(), b"a");
        assert_eq!(metadata_volume.read_file("/b.wai").unwrap(), b"b");
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(webc.manifest()); }
        }
    }

    /// See <https://github.com/wasmerio/pirita/issues/105> for more.
    #[test]
    fn absolute_paths_in_wasmer_toml_issue_105() {
        let temp = TempDir::new().unwrap();
        let base_dir = temp.path().canonicalize().unwrap();
        let sep = std::path::MAIN_SEPARATOR;
        let wasmer_toml = format!(
            r#"
                [package]
                name = 'some/package'
                version = '0.0.0'
                description = 'Test package'
                readme = '{BASE_DIR}{sep}README.md'
                license-file = '{BASE_DIR}{sep}LICENSE'

                [[module]]
                name = 'first'
                source = '{BASE_DIR}{sep}target{sep}debug{sep}package.wasm'
                bindings = {{ wai-version = '0.2.0', exports = '{BASE_DIR}{sep}bindings{sep}file.wai', imports = ['{BASE_DIR}{sep}bindings{sep}a.wai'] }}
            "#,
            BASE_DIR = base_dir.display(),
        );
        let manifest = temp.path().join("wasmer.toml");
        std::fs::write(&manifest, &wasmer_toml).unwrap();
        std::fs::write(temp.path().join("README.md"), "readme").unwrap();
        std::fs::write(temp.path().join("LICENSE"), "license").unwrap();
        let bindings = temp.path().join("bindings");
        std::fs::create_dir_all(&bindings).unwrap();
        std::fs::write(bindings.join("file.wai"), "file.wai").unwrap();
        std::fs::write(bindings.join("a.wai"), "a.wai").unwrap();
        let target = temp.path().join("target").join("debug");
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(target.join("package.wasm"), b"\0asm...").unwrap();

        let serialized = Package::from_manifest(manifest)
            .unwrap()
            .serialize()
            .unwrap();

        let webc = Container::from_bytes(serialized).unwrap();
        let manifest = webc.manifest();
        let wapm = manifest.wapm().unwrap().unwrap();

        // we should be able to look up the files using the manifest
        let lookup = |item: VolumeSpecificPath| {
            let volume = webc.get_volume(&item.volume).unwrap();
            let contents = volume.read_file(&item.path).unwrap();
            String::from_utf8(contents.into()).unwrap()
        };
        assert_eq!(lookup(wapm.license_file.unwrap()), "license");
        assert_eq!(lookup(wapm.readme.unwrap()), "readme");

        // The paths for bindings are stored slightly differently, but it's the
        // same general idea
        let lookup = |item: &str| {
            let (volume, path) = item.split_once(":/").unwrap();
            let volume = webc.get_volume(volume).unwrap();
            let content = volume.read_file(path).unwrap();
            String::from_utf8(content.into()).unwrap()
        };
        let bindings = manifest.bindings[0].get_wai_bindings().unwrap();
        assert_eq!(lookup(&bindings.imports[0]), "a.wai");
        assert_eq!(lookup(bindings.exports.unwrap().as_str()), "file.wai");

        // Snapshot tests for good measure
        let mut settings = insta::Settings::clone_current();
        let base_dir = base_dir.display().to_string();
        settings.set_description(wasmer_toml.replace(&base_dir, "[BASE_DIR]"));
        let filter = regex::escape(&base_dir);
        settings.add_filter(&filter, "[BASE_DIR]");
        settings.bind(|| {
            insta::assert_yaml_snapshot!(webc.manifest());
        });
    }

    #[test]
    fn serializing_will_skip_missing_metadata_by_default() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
                [package]
                name = 'some/package'
                version = '0.0.0'
                description = 'Test package'
                readme = '/this/does/not/exist/README.md'
                license-file = 'LICENSE.wtf'
            "#;
        let manifest = temp.path().join("wasmer.toml");
        std::fs::write(&manifest, wasmer_toml).unwrap();
        let pkg = Package::from_manifest(manifest).unwrap();

        let serialized = pkg.serialize().unwrap();

        let webc = Container::from_bytes(serialized).unwrap();
        let manifest = webc.manifest();
        let wapm = manifest.wapm().unwrap().unwrap();
        // We re-wrote the WAPM annotations to just not include the license file
        assert!(wapm.license_file.is_none());
        assert!(wapm.readme.is_none());

        // Note: serializing in strict mode should still fail
        let pkg = Package {
            strictness: Strictness::Strict,
            ..pkg
        };
        assert!(pkg.serialize().is_err());
    }
}