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 (name, data_type_str) = split_path(&root, entry.path());
57                if let Some(info) = templates.get(&*name) {
58                    warn_!("Template name '{}' does not have a unique source.", name);
59                    match info.path {
60                        Some(ref path) => info_!("Existing path: {:?}", path),
61                        None => info_!("Existing Content-Type: {}", info.data_type),
62                    }
63
64                    info_!("Additional path: {:?}", entry.path());
65                    warn_!("Keeping existing template '{}'.", name);
66                    continue;
67                }
68
69                let data_type = data_type_str.as_ref()
70                    .and_then(|ext| ContentType::from_extension(ext))
71                    .unwrap_or(ContentType::Text);
72
73                templates.insert(name, TemplateInfo {
74                    path: Some(entry.into_path()),
75                    engine_ext: ext,
76                    data_type,
77                });
78            }
79        }
80
81        let mut engines = Engines::init(&templates);
82        if let Some(init) = init {
83            if let Err(e) = init(&mut engines) {
84                error_!("Template initialization callback failed.");
85                error_!("{}", e);
86                return None;
87            }
88        }
89
90        engines.load(&templates)?;
91        if let Some(load) = load {
92            if let Err(e) = load(&mut engines) {
93                error_!("Template loading callback failed.");
94                error_!("{}", e);
95                return None;
96            }
97        }
98
99        for (name, engine_ext) in engines.templates() {
100            if !templates.contains_key(name) {
101                let data_type = Path::new(name).extension()
102                    .and_then(|osstr| osstr.to_str())
103                    .and_then(|ext| ContentType::from_extension(ext))
104                    .unwrap_or(ContentType::Text);
105
106                let info = TemplateInfo { path: None, engine_ext, data_type };
107                templates.insert(name.to_string(), info);
108            }
109        }
110
111        Some(Context { root, templates, engines })
112    }
113}
114
115#[cfg(not(debug_assertions))]
116mod manager {
117    use std::ops::Deref;
118    use super::Context;
119
120    /// Wraps a Context. With `cfg(debug_assertions)` active, this structure
121    /// additionally provides a method to reload the context at runtime.
122    pub(crate) struct ContextManager(Context);
123
124    impl ContextManager {
125        pub fn new(ctxt: Context) -> ContextManager {
126            ContextManager(ctxt)
127        }
128
129        pub fn context<'a>(&'a self) -> impl Deref<Target=Context> + 'a {
130            &self.0
131        }
132
133        pub fn is_reloading(&self) -> bool {
134            false
135        }
136    }
137}
138
139#[cfg(debug_assertions)]
140mod manager {
141    use std::ops::{Deref, DerefMut};
142    use std::sync::{RwLock, Mutex};
143    use std::sync::mpsc::{channel, Receiver};
144
145    use notify::{recommended_watcher, Error, Event, RecommendedWatcher, RecursiveMode, Watcher};
146
147    use super::{Callback, Context};
148
149    /// Wraps a Context. With `cfg(debug_assertions)` active, this structure
150    /// additionally provides a method to reload the context at runtime.
151    pub(crate) struct ContextManager {
152        /// The current template context, inside an RwLock so it can be updated.
153        context: RwLock<Context>,
154        /// A filesystem watcher and the receive queue for its events.
155        watcher: Option<(RecommendedWatcher, Mutex<Receiver<Result<Event, Error>>>)>,
156    }
157
158    impl ContextManager {
159        pub fn new(ctxt: Context) -> ContextManager {
160            let (tx, rx) = channel();
161            let watcher = recommended_watcher(tx).and_then(|mut watcher| {
162                watcher.watch(&ctxt.root.canonicalize()?, RecursiveMode::Recursive)?;
163                Ok(watcher)
164            });
165
166            let watcher = match watcher {
167                Ok(watcher) => Some((watcher, Mutex::new(rx))),
168                Err(e) => {
169                    warn!("Failed to enable live template reloading: {}", e);
170                    debug_!("Reload error: {:?}", e);
171                    warn_!("Live template reloading is unavailable.");
172                    None
173                }
174            };
175
176            ContextManager { watcher, context: RwLock::new(ctxt), }
177        }
178
179        pub fn context(&self) -> impl Deref<Target=Context> + '_ {
180            self.context.read().unwrap()
181        }
182
183        pub fn is_reloading(&self) -> bool {
184            self.watcher.is_some()
185        }
186
187        fn context_mut(&self) -> impl DerefMut<Target=Context> + '_ {
188            self.context.write().unwrap()
189        }
190
191        /// Checks whether any template files have changed on disk. If there
192        /// have been changes since the last reload, all templates are
193        /// reinitialized from disk and the user's customization callbacks are
194        /// run again.
195        pub fn reload_if_needed(&self, init: Option<&Callback>, load: Option<&Callback>) {
196            let templates_changes = self.watcher.as_ref()
197                .map(|(_, rx)| rx.lock().expect("fsevents lock").try_iter().count() > 0);
198
199            if let Some(true) = templates_changes {
200                info_!("Change detected: reloading templates.");
201                let root = self.context().root.clone();
202                if let Some(new_ctxt) = Context::initialize(&root, init, load) {
203                    *self.context_mut() = new_ctxt;
204                } else {
205                    warn_!("An error occurred while reloading templates.");
206                    warn_!("Existing templates will remain active.");
207                };
208            }
209        }
210    }
211}
212
213/// Removes the file path's extension or does nothing if there is none.
214fn remove_extension(path: &Path) -> PathBuf {
215    let stem = match path.file_stem() {
216        Some(stem) => stem,
217        None => return path.to_path_buf()
218    };
219
220    match path.parent() {
221        Some(parent) => parent.join(stem),
222        None => PathBuf::from(stem)
223    }
224}
225
226/// Splits a path into a name that may be used to identify the template, and the
227/// template's data type, if any.
228fn split_path(root: &Path, path: &Path) -> (String, Option<String>) {
229    let rel_path = path.strip_prefix(root).unwrap();
230    let path_no_ext = remove_extension(rel_path);
231    let data_type = path_no_ext.extension();
232    let mut name = path_no_ext.to_string_lossy().into_owned();
233
234    // Ensure template name consistency on Windows systems
235    if cfg!(windows) {
236        name = name.replace("\\", "/");
237    }
238
239    (name, data_type.map(|d| d.to_string_lossy().into_owned()))
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn template_path_index_html() {
248        for root in &["/", "/a/b/c/", "/a/b/c/d/", "/a/"] {
249            for filename in &["index.html.hbs", "index.html.tera"] {
250                let path = Path::new(root).join(filename);
251                let (name, data_type) = split_path(Path::new(root), &path);
252
253                assert_eq!(name, "index.html");
254                assert_eq!(data_type, Some("html".into()));
255            }
256        }
257    }
258
259    #[test]
260    fn template_path_subdir_index_html() {
261        for root in &["/", "/a/b/c/", "/a/b/c/d/", "/a/"] {
262            for sub in &["a/", "a/b/", "a/b/c/", "a/b/c/d/"] {
263                for filename in &["index.html.hbs", "index.html.tera"] {
264                    let path = Path::new(root).join(sub).join(filename);
265                    let (name, data_type) = split_path(Path::new(root), &path);
266
267                    let expected_name = format!("{}index.html", sub);
268                    assert_eq!(name, expected_name.as_str());
269                    assert_eq!(data_type, Some("html".into()));
270                }
271            }
272        }
273    }
274
275    #[test]
276    fn template_path_doc_examples() {
277        fn name_for(path: &str) -> String {
278            split_path(Path::new("templates/"), &Path::new("templates/").join(path)).0
279        }
280
281        assert_eq!(name_for("index.html.hbs"), "index.html");
282        assert_eq!(name_for("index.tera"), "index");
283        assert_eq!(name_for("index.hbs"), "index");
284        assert_eq!(name_for("dir/index.hbs"), "dir/index");
285        assert_eq!(name_for("dir/index.html.tera"), "dir/index.html");
286        assert_eq!(name_for("index.template.html.hbs"), "index.template.html");
287        assert_eq!(name_for("subdir/index.template.html.hbs"), "subdir/index.template.html");
288    }
289}