Skip to main content

rocket_dyn_templates/
context.rs

1use std::path::{Path, PathBuf};
2use std::collections::HashMap;
3use std::error::Error;
4
5use crate::engine::Engines;
6use crate::template::TemplateInfo;
7
8use rocket::http::ContentType;
9use normpath::PathExt;
10
11pub(crate) type Callback =
12    Box<dyn Fn(&mut Engines) -> Result<(), Box<dyn Error>> + Send + Sync + 'static>;
13
14pub(crate) struct Context {
15    /// The root of the template directory.
16    pub root: PathBuf,
17    /// Mapping from template name to its information.
18    pub templates: HashMap<String, TemplateInfo>,
19    /// Loaded template engines
20    pub engines: Engines,
21}
22
23pub(crate) use self::manager::ContextManager;
24
25impl Context {
26    /// Load all of the templates at `root`, initialize them using the relevant
27    /// template engine, and store all of the initialized state in a `Context`
28    /// structure, which is returned if all goes well.
29    pub fn initialize(
30        root: &Path,
31        init: Option<&Callback>,
32        load: Option<&Callback>
33    ) -> Option<Context> {
34        fn is_file_with_ext(entry: &walkdir::DirEntry, ext: &str) -> bool {
35            let is_file = entry.file_type().is_file();
36            let has_ext = entry.path().extension().map_or(false, |e| e == ext);
37            is_file && has_ext
38        }
39
40        let root = match root.normalize() {
41            Ok(root) => root.into_path_buf(),
42            Err(e) => {
43                error!("Invalid template directory '{}': {}.", root.display(), e);
44                return None;
45            }
46        };
47
48        let mut templates: HashMap<String, TemplateInfo> = HashMap::new();
49        for &ext in Engines::ENABLED_EXTENSIONS {
50            for entry in walkdir::WalkDir::new(&root).follow_links(true) {
51                let entry = match entry {
52                    Ok(entry) if is_file_with_ext(&entry, ext) => entry,
53                    Ok(_) | Err(_) => continue,
54                };
55
56                let (template, data_type_str) = split_path(&root, entry.path());
57                if let Some(info) = templates.get(&*template) {
58                    warn!(
59                        %template,
60                        first_path = info.path.as_ref().map(|p| display(p.display())),
61                        second_path = %entry.path().display(),
62                        data_type = %info.data_type,
63                        "Template name '{template}' can refer to multiple templates.\n\
64                         First path will be used. Second path is ignored."
65                    );
66
67                    continue;
68                }
69
70                let data_type = data_type_str.as_ref()
71                    .and_then(|ext| ContentType::from_extension(ext))
72                    .unwrap_or(ContentType::Text);
73
74                templates.insert(template, TemplateInfo {
75                    path: Some(entry.into_path()),
76                    engine_ext: ext,
77                    data_type,
78                });
79            }
80        }
81
82        let mut engines = Engines::init(&templates);
83        if let Some(init) = init {
84            if let Err(reason) = init(&mut engines) {
85                error!(%reason, "template initialization callback failed");
86                return None;
87            }
88        }
89
90        engines.load(&templates)?;
91        if let Some(load) = load {
92            if let Err(reason) = load(&mut engines) {
93                error!(%reason, "template loading callback failed");
94                return None;
95            }
96        }
97
98        for (name, engine_ext) in engines.templates() {
99            if !templates.contains_key(name) {
100                let data_type = Path::new(name).extension()
101                    .and_then(|osstr| osstr.to_str())
102                    .and_then(ContentType::from_extension)
103                    .unwrap_or(ContentType::Text);
104
105                let info = TemplateInfo { path: None, engine_ext, data_type };
106                templates.insert(name.to_string(), info);
107            }
108        }
109
110        Some(Context { root, templates, engines })
111    }
112}
113
114#[cfg(not(debug_assertions))]
115mod manager {
116    use std::ops::Deref;
117    use super::Context;
118
119    /// Wraps a Context. With `cfg(debug_assertions)` active, this structure
120    /// additionally provides a method to reload the context at runtime.
121    pub(crate) struct ContextManager(Context);
122
123    impl ContextManager {
124        pub fn new(ctxt: Context) -> ContextManager {
125            ContextManager(ctxt)
126        }
127
128        pub fn context<'a>(&'a self) -> impl Deref<Target=Context> + 'a {
129            &self.0
130        }
131
132        pub fn is_reloading(&self) -> bool {
133            false
134        }
135    }
136}
137
138#[cfg(debug_assertions)]
139mod manager {
140    use std::ops::{Deref, DerefMut};
141    use std::sync::{RwLock, Mutex};
142    use std::sync::mpsc::{channel, Receiver};
143
144    use notify::{recommended_watcher, Error, Event, RecommendedWatcher, RecursiveMode, Watcher};
145
146    use super::{Callback, Context};
147
148    /// Wraps a Context. With `cfg(debug_assertions)` active, this structure
149    /// additionally provides a method to reload the context at runtime.
150    pub(crate) struct ContextManager {
151        /// The current template context, inside an RwLock so it can be updated.
152        context: RwLock<Context>,
153        /// A filesystem watcher and the receive queue for its events.
154        watcher: Option<(RecommendedWatcher, Mutex<Receiver<Result<Event, Error>>>)>,
155    }
156
157    impl ContextManager {
158        pub fn new(ctxt: Context) -> ContextManager {
159            let (tx, rx) = channel();
160            let watcher = recommended_watcher(tx).and_then(|mut watcher| {
161                watcher.watch(&ctxt.root.canonicalize()?, RecursiveMode::Recursive)?;
162                Ok(watcher)
163            });
164
165            let watcher = match watcher {
166                Ok(watcher) => Some((watcher, Mutex::new(rx))),
167                Err(e) => {
168                    warn!("live template reloading initialization failed: {e}\n\
169                        live template reloading is unavailable");
170                    None
171                }
172            };
173
174            ContextManager { watcher, context: RwLock::new(ctxt), }
175        }
176
177        pub fn context(&self) -> impl Deref<Target=Context> + '_ {
178            self.context.read().unwrap()
179        }
180
181        pub fn is_reloading(&self) -> bool {
182            self.watcher.is_some()
183        }
184
185        fn context_mut(&self) -> impl DerefMut<Target=Context> + '_ {
186            self.context.write().unwrap()
187        }
188
189        /// Checks whether any template files have changed on disk. If there
190        /// have been changes since the last reload, all templates are
191        /// reinitialized from disk and the user's customization callbacks are
192        /// run again.
193        pub fn reload_if_needed(&self, init: Option<&Callback>, load: Option<&Callback>) {
194            let templates_changes = self.watcher.as_ref()
195                .map(|(_, rx)| rx.lock().expect("fsevents lock").try_iter().count() > 0);
196
197            if let Some(true) = templates_changes {
198                debug!("template change detected: reloading templates");
199                let root = self.context().root.clone();
200                if let Some(new_ctxt) = Context::initialize(&root, init, load) {
201                    *self.context_mut() = new_ctxt;
202                } else {
203                    warn!("error while reloading template\n\
204                        existing templates will remain active.")
205                };
206            }
207        }
208    }
209}
210
211/// Removes the file path's extension or does nothing if there is none.
212fn remove_extension(path: &Path) -> PathBuf {
213    let stem = match path.file_stem() {
214        Some(stem) => stem,
215        None => return path.to_path_buf()
216    };
217
218    match path.parent() {
219        Some(parent) => parent.join(stem),
220        None => PathBuf::from(stem)
221    }
222}
223
224/// Splits a path into a name that may be used to identify the template, and the
225/// template's data type, if any.
226fn split_path(root: &Path, path: &Path) -> (String, Option<String>) {
227    let rel_path = path.strip_prefix(root).unwrap();
228    let path_no_ext = remove_extension(rel_path);
229    let data_type = path_no_ext.extension();
230    let mut name = path_no_ext.to_string_lossy().into_owned();
231
232    // Ensure template name consistency on Windows systems
233    if cfg!(windows) {
234        name = name.replace('\\', "/");
235    }
236
237    (name, data_type.map(|d| d.to_string_lossy().into_owned()))
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn template_path_index_html() {
246        for root in &["/", "/a/b/c/", "/a/b/c/d/", "/a/"] {
247            for filename in &["index.html.hbs", "index.html.tera"] {
248                let path = Path::new(root).join(filename);
249                let (name, data_type) = split_path(Path::new(root), &path);
250
251                assert_eq!(name, "index.html");
252                assert_eq!(data_type, Some("html".into()));
253            }
254        }
255    }
256
257    #[test]
258    fn template_path_subdir_index_html() {
259        for root in &["/", "/a/b/c/", "/a/b/c/d/", "/a/"] {
260            for sub in &["a/", "a/b/", "a/b/c/", "a/b/c/d/"] {
261                for filename in &["index.html.hbs", "index.html.tera"] {
262                    let path = Path::new(root).join(sub).join(filename);
263                    let (name, data_type) = split_path(Path::new(root), &path);
264
265                    let expected_name = format!("{}index.html", sub);
266                    assert_eq!(name, expected_name.as_str());
267                    assert_eq!(data_type, Some("html".into()));
268                }
269            }
270        }
271    }
272
273    #[test]
274    fn template_path_doc_examples() {
275        fn name_for(path: &str) -> String {
276            split_path(Path::new("templates/"), &Path::new("templates/").join(path)).0
277        }
278
279        assert_eq!(name_for("index.html.hbs"), "index.html");
280        assert_eq!(name_for("index.tera"), "index");
281        assert_eq!(name_for("index.hbs"), "index");
282        assert_eq!(name_for("dir/index.hbs"), "dir/index");
283        assert_eq!(name_for("dir/index.html.tera"), "dir/index.html");
284        assert_eq!(name_for("index.template.html.hbs"), "index.template.html");
285        assert_eq!(name_for("subdir/index.template.html.hbs"), "subdir/index.template.html");
286    }
287}