pochoir 0.15.1

Main crate of the pochoir template engine used to compile and render pochoir files with components
Documentation
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use crate::{
    component_file::ComponentFile, component_not_found, transformers::Transformers, Context, Result,
};
use std::{
    collections::HashMap,
    ffi::OsStr,
    fs,
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
};
use walkdir::{DirEntry, WalkDir};

fn path_to_template_name(path: &Path) -> String {
    path.file_stem()
        .expect("path must be a file")
        .to_os_string()
        .into_string()
        .expect("invalid unicode data")
}

fn is_hidden(entry: &DirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .is_some_and(|s| s.starts_with('.'))
}

fn is_template(entry: &DirEntry, extensions: &[String]) -> bool {
    entry.file_type().is_file()
        && extensions.contains(
            &entry
                .path()
                .extension()
                .unwrap_or(OsStr::new(""))
                .to_str()
                .expect("invalid unicode data")
                .to_string(),
        )
}

fn base_walk_dir(path: &Path) -> impl Iterator<Item = DirEntry> {
    WalkDir::new(path)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| !is_hidden(e))
        .filter_map(std::result::Result::ok)
}

fn find_all_templates(path: &Path, extensions: &[String]) -> Vec<String> {
    base_walk_dir(path)
        .filter_map(|e| {
            if is_template(&e, extensions) {
                Some(path_to_template_name(e.path()))
            } else {
                None
            }
        })
        .collect()
}

fn search_template(name: &str, path: &Path, extensions: &[String]) -> Option<PathBuf> {
    for e in base_walk_dir(path) {
        if is_template(&e, extensions) && path_to_template_name(e.path()) == name {
            return Some(e.path().into());
        }
    }

    None
}

/// A provider reading templates from files on the filesystem.
///
/// It can be used in static content generators, when live-reloading a frontend in development or
/// in a scenario where a lot of reading from files is needed to always render the up-to-date
/// version.
///
/// Template files are searched following two criterias:
/// - The file is part of one of the allowed paths, inserted using [`FilesystemProvider::with_path`] or [`FilesystemProvider::insert_path`]
/// - The file has an extension matching one the allowed extensions, inserted using [`FilesystemProvider::with_extension`] or [`FilesystemProvider::insert_extension`]
///   By default only files with the `.html` extension are allowed. If you want to ignore HTML
///   files, you need to use [`FilesystemProvider::remove_extension`] with `html` as argument
///
/// Besides these criterias, you need to note that:
/// - The search is (of course) recursive: sub-directories of the allowed paths are also searched
/// - Paths are linearly searched, so if you insert the directory "a" containing a file
///   "template.html" then you insert the directory "b" with the same file, the file in the **"a"**
///   directory will be the first found and used
/// - Paths can be directories or files (the file must have one of the allowed extensions)
/// - Hidden directories are ignored
/// - Symbolic links are followed
///
/// To avoid always reading files when they don't change, a cache is available which will store the
/// parsed files in memory instead of always reading them from the filesystem. By default, it is
/// disabled in debug mode and enabled in release mode, but you can override this preference using
/// either [`FilesystemProvider::enable_cache`] or [`FilesystemProvider::disable_cache`]. Keep in
/// mind that the files are still read once from the disk, so it is not equivalent to keeping them
/// in the binary. If you can't afford the small performance overhead or if you don't want to use
/// an external directory, you should use a [`StaticMapProvider`] instead.
///
/// [`StaticMapProvider`]: crate::providers::StaticMapProvider
#[derive(Debug, Clone)]
pub struct FilesystemProvider {
    paths: Vec<PathBuf>,
    extensions: Vec<String>,
    cache: Arc<RwLock<HashMap<String, ComponentFile<'static, 'static>>>>,
    cache_enabled: Option<bool>,
}

impl FilesystemProvider {
    /// Create a new empty [`FilesystemProvider`] searching HTML files (with `.html` extension).
    pub fn new() -> Self {
        Self {
            paths: vec![],
            extensions: vec!["html".to_string()],
            cache: Arc::new(RwLock::new(HashMap::new())),
            cache_enabled: None,
        }
    }

    fn is_cache_enabled(&self) -> bool {
        #[cfg(debug_assertions)]
        let is_release = false;

        #[cfg(not(debug_assertions))]
        let is_release = true;

        self.cache_enabled.unwrap_or(is_release)
    }

    /// Force enabling the cache of read files. All files will be read only once, then they will be
    /// provided from memory.
    ///
    /// In release mode this is enabled by default.
    ///
    /// See [`FilesystemProvider`] for more information.
    #[must_use]
    pub fn enable_cache(mut self) -> Self {
        self.cache_enabled = Some(true);
        self
    }

    /// Force disabling the cache of read files. All files will always be read from the filesystem.
    ///
    /// In debug mode this is enabled by default.
    ///
    /// See [`FilesystemProvider`] for more information.
    #[must_use]
    pub fn disable_cache(mut self) -> Self {
        self.cache_enabled = Some(false);
        self
    }

    /// Add a path to the list of the paths searched to find templates, using the builder pattern.
    ///
    /// It can be a directory or a file having one of the allowed extensions.
    #[must_use]
    pub fn with_path<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.paths.push(path.as_ref().into());
        self
    }

    /// Add a path to the list of the paths searched to find templates.
    ///
    /// It can be a directory or a file having one of the allowed extensions.
    pub fn insert_path<P: AsRef<Path>>(&mut self, path: P) {
        self.paths.push(path.as_ref().into());
    }

    /// Remove a path from the list of the paths searched to find templates.
    pub fn remove_path<P: AsRef<Path>>(&mut self, path: P) {
        if let Some(i) = self.paths.iter().enumerate().find(|p| p.1 == path.as_ref()) {
            self.paths.remove(i.0);
        }
    }

    /// Add an extension to the list of the allowed file extensions that files must have to be compiled, using the builder pattern.
    #[must_use]
    pub fn with_extension<T: Into<String>>(mut self, ext: T) -> Self {
        self.extensions.push(ext.into());
        self
    }

    /// Add an extension to the list of the allowed file extensions that files must have to be compiled.
    pub fn insert_extension<T: Into<String>>(&mut self, ext: T) {
        self.extensions.push(ext.into());
    }

    /// Remove an extension from the list of the allowed file extensions that files must have to be compiled.
    pub fn remove_extension<T: Into<String>>(&mut self, ext: T) {
        let ext = ext.into();

        if let Some(i) = self.extensions.iter().enumerate().find(|e| e.1 == &ext) {
            self.extensions.remove(i.0);
        }
    }

    /// Get a template previously inserted into the provider.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ComponentNotFound`] if the template is not found or another [`Error`] if
    /// the file was not cached and an error happened when parsing it.
    ///
    /// # Panics
    ///
    /// This function panics if the cache lock is poisoned, which can never happen because
    /// insertion or retrieval from a [`HashMap`] cannot fail.
    ///
    /// [`Error::ComponentNotFound`]: crate::Error::ComponentNotFound
    /// [`Error`]: crate::Error
    pub fn get(&self, name: &str) -> Result<ComponentFile<'_, '_>> {
        if self.is_cache_enabled() {
            if let Some(cache_entry) = self
                .cache
                .read()
                .expect("cache lock should not be poisoned")
                .get(name)
            {
                return Ok(cache_entry.clone());
            }
        }

        let Some(template_path) = self
            .paths
            .iter()
            .find_map(|p| search_template(name, p, &self.extensions))
        else {
            return Err(component_not_found(name));
        };

        let Ok(template_contents) = fs::read_to_string(&template_path) else {
            return Err(component_not_found(name));
        };

        if self.is_cache_enabled() {
            self.cache
                .write()
                .expect("cache lock should not be poisoned")
                .insert(
                    name.to_string(),
                    ComponentFile::new(template_path.clone(), template_contents.clone()),
                );
        }

        Ok(ComponentFile::new(template_path, template_contents))
    }

    /// Returns an iterator over the name of all inserted templates.
    ///
    /// **Warning**: this function is expensive because it needs to read the filesystem **each
    /// time** to find all template files (even if the cache is enabled), use it with caution.
    pub fn template_names(&self) -> impl Iterator<Item = String> + '_ {
        self.paths.iter().flat_map(|p| {
            if p.is_file() {
                vec![path_to_template_name(p)]
            } else {
                find_all_templates(p, &self.extensions)
            }
        })
    }

    /// Make a component resolver function from the provider, used in the
    /// [`compile`] function.
    ///
    /// [`compile`]: crate::compile
    pub fn to_resolver_fn<'a, 'b: 'a>(
        &'b self,
    ) -> impl FnMut(&str) -> Result<ComponentFile<'a, 'b>> + 'b {
        move |name| self.get(name)
    }

    /// Compile the specified component using the specified context.
    ///
    /// Manages the component resolver function under the hood unlike [`compile`].
    ///
    /// # Errors
    ///
    /// It is up to you to format runtime errors (e.g using [`error::display_ansi_error`]
    /// or [`error::display_html_error`]).
    ///
    /// For example, to display the error using ANSI escape codes (to be used in shells) you can
    /// call it like this:
    ///
    /// ```no_run
    /// use pochoir::{FilesystemProvider, Context};
    ///
    /// let provider = FilesystemProvider::new()
    ///     .with_path("templates");
    ///
    /// let _compiled = provider.compile("index", &mut Context::new()).map_err(|e| {
    ///     // Runtime error formatting happens here, it uses
    ///     // `pochoir::common::Spanned::component_name` to get
    ///     // the name of the component which raised the error and
    ///     // fetches it from the provider to get the text source of
    ///     // the component
    ///     pochoir::error::display_ansi_error(
    ///         &e,
    ///         &provider.get(
    ///             e.component_name(),
    ///         )
    ///         .expect("component should not be removed from the provider")
    ///         .data,
    ///     )
    /// });
    /// ```
    ///
    /// [`compile`]: crate::compile
    /// [`error::display_ansi_error`]: crate::error::display_ansi_error
    /// [`error::display_html_error`]: crate::error::display_html_error
    pub fn compile<'a: 'b, 'b>(
        &self,
        default_component_name: &str,
        default_context: &mut Context,
    ) -> Result<String> {
        crate::compile(
            default_component_name,
            default_context,
            self.to_resolver_fn(),
        )
    }

    /// Compile each template while applying transformers.
    ///
    /// See [`transformers`](`crate::transformers`) and [`FilesystemProvider::compile`].
    ///
    /// # Errors
    ///
    /// It is up to you to format runtime errors (e.g using [`error::display_ansi_error`]
    /// or [`error::display_html_error`]).
    ///
    /// For example, to display the error using ANSI escape codes (to be used in shells) you can
    /// call it like this:
    ///
    /// ```no_run
    /// use pochoir::{FilesystemProvider, Transformers, Context};
    ///
    /// let provider = FilesystemProvider::new()
    ///     .with_path("templates");
    ///
    /// let _compiled = provider.transform_and_compile("index", &mut Context::new(), &mut Transformers::new()).map_err(|e| {
    ///     // Runtime error formatting happens here, it uses
    ///     // `pochoir::common::Spanned::component_name` to get
    ///     // the name of the component which raised the error and
    ///     // fetches it from the provider to get the text source of
    ///     // the component
    ///     pochoir::error::display_ansi_error(
    ///         &e,
    ///         &provider.get(
    ///             e.component_name(),
    ///         )
    ///         .expect("component should not be removed from the provider")
    ///         .data,
    ///     )
    /// });
    /// ```
    ///
    /// [`error::display_ansi_error`]: crate::error::display_ansi_error
    /// [`error::display_html_error`]: crate::error::display_html_error
    pub fn transform_and_compile<'a: 'b, 'b>(
        &self,
        default_component_name: &str,
        default_context: &mut Context,
        transformers: &mut Transformers,
    ) -> Result<String> {
        crate::transform_and_compile(
            default_component_name,
            default_context,
            self.to_resolver_fn(),
            transformers,
        )
    }
}

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

#[cfg(test)]
mod tests {
    use pochoir_lang::IntoValue;

    use super::*;

    // AssertSendSync is a trait used to make sure `Send + Sync` is implemented on the `StaticMapProvider`
    #[allow(dead_code)]
    trait AssertSendSync: Send + Sync {}
    impl AssertSendSync for FilesystemProvider {}

    const FILES: &[(&str, &str)] = &[
        (
            "templates/index.html",
            r#"<h1>Index</h1><main><my-button color="blue" /></main>"#,
        ),
        (
            "templates/about.html",
            "<h1>About</h1><main><my-button /><manually-added /></main>",
        ),
        (
            "templates/components/my-button.html",
            r#"<button style="color: {{ color == null ? 'green' : color }};">My button</button>"#,
        ),
        (
            "templates/components/other-ext.choir",
            r#"<h1>Component with another {{ ext + "ension" }}</h1>"#,
        ),
        (
            "templates/.components/should-be-ignored.html",
            "Nothing to see here",
        ),
        (
            "templates/.components/manually-added.html",
            "Manually added",
        ),
    ];

    fn helper() -> tempfile::TempDir {
        let dir = tempfile::Builder::new()
            .prefix("pochoir-test")
            .tempdir()
            .unwrap();

        for file in FILES {
            if let Some(parent) = Path::new(file.0).parent() {
                fs::create_dir_all(dir.path().join(parent)).unwrap();
            }

            fs::write(dir.path().join(file.0), file.1).unwrap();
        }

        dir
    }

    #[test]
    fn compile_basic() {
        let dir = helper();
        let provider = FilesystemProvider::new()
            .with_path(dir.path().join("templates"))
            .with_path(dir.path().join("templates/.components/manually-added.html"));
        let mut template_names = provider.template_names().collect::<Vec<String>>();
        template_names.sort();

        assert_eq!(
            template_names,
            vec!["about", "index", "manually-added", "my-button"]
        );

        assert_eq!(
            provider.compile("index", &mut Context::new()),
            Ok(
                r#"<h1>Index</h1><main><button style="color: blue;">My button</button></main>"#
                    .to_string()
            )
        );

        assert_eq!(
            provider.compile("about", &mut Context::new()),
            Ok(
                r#"<h1>About</h1><main><button style="color: green;">My button</button>Manually added</main>"#
                    .to_string()
            )
        );
    }

    #[test]
    fn compile_with_custom_extension() {
        let dir = helper();

        let mut provider = FilesystemProvider::new().with_path(dir.path().join("templates"));
        provider.remove_extension("html");
        provider.insert_extension("choir");

        assert_eq!(
            provider.template_names().collect::<Vec<String>>(),
            vec!["other-ext"],
        );

        assert_eq!(
            provider.compile(
                "other-ext",
                &mut Context::from_iter([("ext".to_string(), "ext".into_value())])
            ),
            Ok("<h1>Component with another extension</h1>".to_string())
        );
    }

    #[test]
    fn compile_with_cache() {
        let dir = helper();

        let provider = FilesystemProvider::new()
            .enable_cache()
            .with_path(dir.path().join("templates"));

        assert_eq!(
            provider.compile("index", &mut Context::new()),
            Ok(
                r#"<h1>Index</h1><main><button style="color: blue;">My button</button></main>"#
                    .to_string()
            )
        );

        drop(dir);

        assert_eq!(
            provider.compile("index", &mut Context::new()),
            Ok(
                r#"<h1>Index</h1><main><button style="color: blue;">My button</button></main>"#
                    .to_string()
            )
        );
    }
}