Skip to main content

compmd_host/
packs.rs

1//! The processor's packs over the bundle and the store ([hosting], decision 7): a host that processes documents in Rust
2//! resolves imports from exactly the files the frames load.
3//!
4//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
5
6use std::sync::Arc;
7
8use compmd::host::{Packs, Release};
9use compmd_pack::{PackName, Place};
10
11use crate::bundle::Bundle;
12use crate::store::Store;
13
14/// The bundle's packs, then the store's, as `compmd::host::Packs`. It shares the bundle and the store, which the host
15/// keeps, so the processor, which keeps its packs while it processes, can be given it.
16///
17/// ```
18/// # use std::sync::Arc;
19/// # use compmd::{Ambient, ParseOptions, Processor};
20/// # use compmd_host::{Bundle, HostPacks, NoStore};
21/// # let bundle = Bundle::from_files([("manifest.json", br#"{"format": 1, "frames": {"hash": "1df336e75685de8c"}}"#.to_vec())])?;
22/// let packs = HostPacks::new(Arc::new(bundle), Arc::new(NoStore));
23/// let resolved = Processor::new("a.comp.md", "# A\n").parse(&ParseOptions::default()).resolve((), packs, &Ambient::default());
24/// # drop(resolved);
25/// # Ok::<(), compmd_host::BundleError>(())
26/// ```
27#[derive(Clone)]
28pub struct HostPacks {
29    bundle: Arc<Bundle>,
30    store: Arc<dyn Store>,
31}
32
33impl HostPacks {
34    /// The packs of `bundle`, then of `store`.
35    #[must_use]
36    pub fn new(bundle: Arc<Bundle>, store: Arc<dyn Store>) -> Self {
37        Self { bundle, store }
38    }
39}
40
41impl Packs for HostPacks {
42    fn releases(&self, pack: &PackName) -> Vec<Release> {
43        let bundled = self
44            .bundle
45            .manifest()
46            .packs
47            .iter()
48            .filter(|bundled| bundled.release.pack == *pack)
49            .map(|bundled| Release {
50                version: bundled.release.version.clone(),
51                integrity: bundled.integrity.clone(),
52                broken: None,
53            });
54        let mut releases: Vec<Release> = bundled.collect();
55        for stored in self.store.releases(pack) {
56            if !releases
57                .iter()
58                .any(|release| release.version == stored.release.version)
59            {
60                releases.push(Release {
61                    version: stored.release.version,
62                    integrity: Some(stored.integrity),
63                    broken: None,
64                });
65            }
66        }
67        releases
68    }
69
70    fn pack_file(&self, place: &Place) -> Option<String> {
71        let bytes = self
72            .bundle
73            .pack_file(place)
74            .or_else(|| self.store.file(place))?;
75        String::from_utf8(bytes).ok()
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use compmd_pack::ReleaseId;
82
83    use super::*;
84    use crate::bundle::tests::{bundle, place};
85    use crate::store::{NoStore, StoredRelease};
86
87    /// A store holding `@kit/mermaid` 1.2.0 (the bundle's too) and 1.3.0, and a binary file.
88    struct Kept;
89
90    impl Store for Kept {
91        fn releases(&self, pack: &PackName) -> Vec<StoredRelease> {
92            if *pack != "@kit/mermaid" {
93                return Vec::new();
94            }
95            [2, 3]
96                .into_iter()
97                .map(|minor| StoredRelease {
98                    release: format!("@kit/mermaid@1.{minor}.0")
99                        .parse::<ReleaseId>()
100                        .expect("a release"),
101                    integrity: format!("sha512-{minor}").parse().expect("an integrity"),
102                })
103                .collect()
104        }
105
106        fn file(&self, place: &Place) -> Option<Vec<u8>> {
107            match place.to_string().as_str() {
108                "@kit/mermaid@1.3.0/package.json" => Some(b"{}".to_vec()),
109                "@kit/mermaid@1.3.0/logo.png" => Some(vec![0xff, 0xfe]),
110                _ => None,
111            }
112        }
113    }
114
115    #[test]
116    fn the_bundles_release_comes_first_and_the_stores_others_after() {
117        let packs = HostPacks::new(Arc::new(bundle()), Arc::new(Kept));
118        let releases = packs.releases(&"@kit/mermaid".parse().expect("a name"));
119        let versions: Vec<String> = releases
120            .iter()
121            .map(|release| release.version.to_string())
122            .collect();
123        assert_eq!(versions, ["1.2.0", "1.3.0"]);
124        let integrity = |text: &str| Some(text.parse().expect("an integrity"));
125        assert_eq!(
126            releases[0].integrity,
127            integrity("sha512-abc"),
128            "the bundle's integrity"
129        );
130        assert_eq!(releases[1].integrity, integrity("sha512-3"));
131        assert_eq!(packs.releases(&"@kit/none".parse().expect("a name")), []);
132    }
133
134    #[test]
135    fn a_file_is_read_from_the_bundle_or_the_store_as_text() {
136        let bundle = Arc::new(bundle());
137        let packs = HostPacks::new(Arc::clone(&bundle), Arc::new(Kept));
138        assert_eq!(
139            packs
140                .pack_file(&place("@kit/mermaid@1.2.0/package.json"))
141                .as_deref(),
142            Some(r#"{"name": "@kit/mermaid"}"#)
143        );
144        assert_eq!(
145            packs
146                .pack_file(&place("@kit/mermaid@1.3.0/package.json"))
147                .as_deref(),
148            Some("{}")
149        );
150        assert_eq!(
151            packs.pack_file(&place("@kit/mermaid@1.3.0/logo.png")),
152            None,
153            "not text"
154        );
155        assert_eq!(
156            HostPacks::new(bundle, Arc::new(NoStore))
157                .pack_file(&place("@kit/mermaid@1.3.0/package.json")),
158            None
159        );
160    }
161}