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
use crate::ModuleScriptLoader;
use std::path::{Path, PathBuf};

pub struct NullLoader;
impl ModuleScriptLoader for NullLoader {
    fn load_script(&mut self, _: String) -> Option<String> {
        None
    }
}

#[derive(Debug, Clone)]
pub struct BasicFileLoader {
    base_dir: PathBuf,
}

impl Default for BasicFileLoader {
    fn default() -> Self {
        Self::new()
    }
}

impl BasicFileLoader {
    pub fn new() -> BasicFileLoader {
        BasicFileLoader {
            base_dir: ".".into(),
        }
    }
    pub fn base_dir<P: AsRef<Path>>(mut self, base_dir: P) -> Self {
        self.base_dir = base_dir.as_ref().into();
        self
    }
}
/// Enable to load wren scripts from a base directory
impl ModuleScriptLoader for BasicFileLoader {
    fn load_script(&mut self, module: String) -> Option<String> {
        use std::fs::File;
        let module_path = self.base_dir.join(module).with_extension("wren");
        let mut contents = String::new();
        match File::open(module_path) {
            Ok(mut file) => {
                use std::io::Read;
                match file.read_to_string(&mut contents) {
                    Ok(_) => Some(contents),
                    Err(file) => {
                        eprintln!("failed to read file {:?}", file);
                        None
                    }
                }
            }
            Err(file) => {
                eprintln!("failed to open file {:?}", file);
                None
            }
        }
    }
}