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
use std::fs::File;
use std::io::prelude::Read;
use std::path;

use error::{Error, Result};

pub trait Include: Send + Sync + IncludeClone {
    fn include(&self, path: &str) -> Result<String>;
}

pub trait IncludeClone {
    fn clone_box(&self) -> Box<Include>;
}

impl<T> IncludeClone for T
    where T: 'static + Include + Clone
{
    fn clone_box(&self) -> Box<Include> {
        Box::new(self.clone())
    }
}

impl Clone for Box<Include> {
    fn clone(&self) -> Box<Include> {
        self.clone_box()
    }
}

/// `Include` no files
#[derive(Clone, Debug, Default)]
pub struct NullInclude {}

impl NullInclude {
    pub fn new() -> Self {
        Self {}
    }
}

impl Include for NullInclude {
    fn include(&self, relative_path: &str) -> Result<String> {
        Err(Error::from(&*format!("{:?} does not exist", relative_path)))
    }
}

/// `Include` files relative to the root.
#[derive(Clone, Debug)]
pub struct FilesystemInclude {
    root: path::PathBuf,
}

impl FilesystemInclude {
    pub fn new<P: Into<path::PathBuf>>(root: P) -> Self {
        let root: path::PathBuf = root.into();
        Self { root }
    }
}

impl Include for FilesystemInclude {
    fn include(&self, relative_path: &str) -> Result<String> {
        let root = self.root.canonicalize()?;
        let mut path = root.clone();
        path.extend(relative_path.split('/'));
        if !path.exists() {
            return Err(Error::from(&*format!("{:?} does not exist", path)));
        }
        let path = path.canonicalize()?;
        if !path.starts_with(&root) {
            return Err(Error::from(&*format!("{:?} is outside the include path", path)));
        }

        let mut file = File::open(path)?;
        let mut content = String::new();
        file.read_to_string(&mut content)?;
        Ok(content)
    }
}