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
use crate::{to_hash_path, FsModuleStore, ModuleStore};
use async_trait::async_trait;
use deno_core::{anyhow::bail, error::AnyError};
use dirs::home_dir;
use std::{
    fs,
    io::{Read, Write},
    path::PathBuf,
};

impl Default for FsModuleStore {
    fn default() -> Self {
        let base = home_dir().unwrap().join(".cache/deno_fs_store");
        fs::create_dir_all(&base).unwrap();
        FsModuleStore { base }
    }
}

impl FsModuleStore {
    pub fn new(base: impl Into<PathBuf>) -> Self {
        let base = base.into();
        fs::create_dir_all(&base).unwrap();
        FsModuleStore { base }
    }
}

#[async_trait]
impl ModuleStore for FsModuleStore {
    async fn get(&self, key: &str) -> Result<String, AnyError> {
        let path = to_hash_path(&self.base, key);
        if !path.exists() {
            bail!("Module not found: {}", key);
        }
        let mut file = fs::File::open(&path)?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)?;
        Ok(contents)
    }

    async fn put(&self, key: String, value: String) -> Result<(), AnyError> {
        let path = to_hash_path(&self.base, &key);
        fs::create_dir_all(path.parent().unwrap())?;
        let mut file = fs::File::create(&path)?;
        file.write_all(value.as_bytes())?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{FsModuleStore, ModuleStore};
    use std::path::PathBuf;

    #[tokio::test]
    async fn module_store_should_work() {
        let base = PathBuf::from("/tmp/deno_fs_store");
        let store = FsModuleStore::new(base);
        store
            .put("foo".to_string(), "bar".to_string())
            .await
            .unwrap();
        let contents = store.get("foo").await.unwrap();
        assert_eq!(contents, "bar");
    }
}