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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Defines the [`TemplateRaw`] and [`TemplatePartialRaw`] and
//! [`TemplateRender`] structs and various helper structs and enums to
//! represent a template's content and metadata.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use tera::{Context, Tera};

use crate::models::annotation::Annotation;
use crate::models::book::Book;
use crate::models::datetime::DateTimeUtc;
use crate::models::entry::Entry;
use crate::result::{Error, Result};

use super::defaults::{CONFIG_TAG_CLOSE, CONFIG_TAG_OPEN};

/// A struct representing a fully configured template.
#[derive(Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct TemplateRaw {
    /// The template's id.
    ///
    /// This is typically a file path relative to the templates directory. It
    /// serves to identify a template within the registry when rendering. This
    /// is one of two fields that are passed to Tera when registering the
    /// template. The other one being [`Template.contents`].
    ///
    /// ```plaintext
    /// --> /path/to/templates/nested/template.md
    /// -->                    nested/template.md
    /// ```
    #[serde(skip_deserializing)]
    pub id: String,

    /// The unparsed contents of the template.
    ///
    /// This gets parsed and validated during registration. This is one of two
    /// fields that are passed to Tera when registering the template. The other
    /// one being [`Template.id`].
    #[serde(skip_deserializing)]
    pub contents: String,

    /// The template's group name.
    ///
    /// See [`StructureMode::FlatGrouped`] and [`StructureMode::NestedGrouped`]
    /// for more information.
    #[serde(deserialize_with = "super::utils::deserialize_and_sanitize")]
    pub group: String,

    /// The template's context mode i.e what the template intends to render.
    ///
    /// See [`ContextMode`] for more information.
    #[serde(rename = "context")]
    pub context_mode: ContextMode,

    /// The template's structure mode i.e. how the output should be structured.
    ///
    /// See [`StructureMode`] for more information.
    #[serde(rename = "structure")]
    pub structure_mode: StructureMode,

    /// The template's file extension.
    pub extension: String,

    /// The template strings for generating output file and directory names.
    /// This is converted into a [`NamesRender`] struct once an [`Entry`] is
    /// provided.
    #[serde(default)]
    names: NamesRaw,
}

impl TemplateRaw {
    /// Creates a new instance of [`TemplateRaw`].
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the template relative to the templates directory.
    /// * `string` - The contents of the template file.
    ///
    /// # Errors
    ///
    /// Will return `Err` if:
    /// * The template's opening and closing config tags have syntax errors.
    /// * The tempalte's config has syntax errors or is missing required fields.
    pub fn new<P>(path: P, string: &str) -> Result<Self>
    where
        P: AsRef<Path>,
    {
        let path = path.as_ref();

        let (config, contents) = Self::parse(string).ok_or(Error::InvalidTemplateConfig {
            path: path.display().to_string(),
        })?;

        let mut template: Self = serde_yaml::from_str(config)?;

        template.id = path.display().to_string();
        template.contents = contents;

        Ok(template)
    }

    /// Returns a tuple containing the template's configuration and its contents
    /// respectively.
    ///
    /// Returns `None` if the template's config block is formatted incorrectly.
    fn parse(string: &str) -> Option<(&str, String)> {
        // Find where the opening tag starts...
        let mut config_start = string.find(CONFIG_TAG_OPEN)?;

        // (Save the pre-config contents.)
        let pre_config_contents = &string[0..config_start];

        // ...and offset it by the length of the config opening tag.
        config_start += CONFIG_TAG_OPEN.len();

        // Starting from where we found the opening tag, search for a closing
        // tag. If we don't offset the starting point we might find another
        // closing tag located before the opening tag.
        let mut config_end = string[config_start..].find(CONFIG_TAG_CLOSE)?;
        // Remove the offset we just used.
        config_end += config_start;

        let config = &string[config_start..config_end];

        // The template's post-config contents start after the closiong tag.
        let post_config_contents = config_end + CONFIG_TAG_CLOSE.len();
        let mut post_config_contents = &string[post_config_contents..];

        // Trim a single linebreak if its present.
        if post_config_contents.starts_with('\n') {
            post_config_contents = &post_config_contents[1..];
        }

        let contents = format!("{pre_config_contents}{post_config_contents}",);

        Some((config, contents))
    }
}

impl std::fmt::Debug for TemplateRaw {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TemplateRaw")
            .field("id", &self.id)
            .field("group", &self.group)
            .field("context_mode", &self.context_mode)
            .field("structure_mode", &self.structure_mode)
            .finish()
    }
}

/// A struct representing a unconfigured partial template.
///
/// Partial templates get their configuration from the normal templates that
/// `include` them.
#[derive(Clone)]
pub struct TemplatePartialRaw {
    /// The template's id.
    ///
    /// This is typically a file path relative to the templates directory.
    /// It serves to identify a partial template when called in an `include`
    /// tag from within a normal template. This field is passed to Tera when
    /// registering the template.
    ///
    /// ```plaintext
    /// --> /path/to/templates/nested/template.md
    /// -->                    nested/template.md
    /// --> {% include "nested/template.md" %}
    /// ````
    pub id: String,

    /// The unparsed contents of the template.
    ///
    /// This gets parsed and validated only when a normal template that includes
    /// it is being parsed and valiated. This field is passed to Tera when
    /// registering the template.
    pub contents: String,
}

impl TemplatePartialRaw {
    /// Creates a new instance of [`TemplatePartialRaw`].
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the template relative to the templates directory.
    /// * `string` - The contents of the template file.
    pub fn new<P>(path: P, string: &str) -> Self
    where
        P: AsRef<Path>,
    {
        Self {
            id: path.as_ref().display().to_string(),
            contents: string.to_owned(),
        }
    }
}

impl std::fmt::Debug for TemplatePartialRaw {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TemplatePartialRaw")
            .field("id", &self.id)
            .finish()
    }
}

/// A struct representing a rendered template.
#[derive(Default)]
pub struct TemplateRender {
    /// The path to where the template will be written to.
    ///
    /// This path should be relative to the final output directory as this path
    /// is appended to it to determine the the full output path.
    pub path: PathBuf,

    /// The final output filename.
    pub filename: String,

    /// The rendered content.
    pub contents: String,
}

impl TemplateRender {
    /// Creates a new instance of [`TemplateRender`].
    #[must_use]
    pub fn new(path: PathBuf, filename: String, contents: String) -> Self {
        Self {
            path,
            filename,
            contents,
        }
    }
}

impl std::fmt::Debug for TemplateRender {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TemplateRender")
            .field("path", &self.path)
            .field("filename", &self.filename)
            .finish()
    }
}

/// An enum representing the ways to structure a template's rendered files.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StructureMode {
    /// When selected, the template is rendered to the output directory without
    /// any structure.
    ///
    /// ```yaml
    /// output-mode: flat
    /// ```
    ///
    /// ```plaintext
    /// [ouput-directory]
    ///  │
    ///  ├─ [template-name-01].[extension]
    ///  ├─ [template-name-01].[extension]
    ///  └─ ...
    /// ```
    Flat,

    /// When selected, the template is rendered to the output directory and
    /// placed inside a directory named after its `group`. This useful if there
    /// are multiple related and unrelated templates being rendered to the same
    /// directory.
    ///
    /// ```yaml
    /// output-mode: flat-grouped
    /// ```
    ///
    /// ```plaintext
    /// [ouput-directory]
    ///  │
    ///  ├─ [template-group-01]
    ///  │   ├─ [template-name-01].[extension]
    ///  │   ├─ [template-name-01].[extension]
    ///  │   └─ ...
    ///  │
    ///  ├─ [template-group-02]
    ///  │   └─ ...
    ///  └─ ...
    /// ```
    FlatGrouped,

    /// When selected, the template is rendered to the output directory and
    /// placed inside a directory named after its `nested-directory-template`.
    /// This useful if multiple templates are used to represent a single book
    /// i.e. a book template used to render a book's information to a single
    /// file and an annotation template used to render each annotation to a
    /// separate file.
    ///
    /// ```yaml
    /// output-mode: nested
    /// ```
    ///
    /// ```plaintext
    /// [ouput-directory]
    ///  │
    ///  ├─ [author-title-01]
    ///  │   ├─ [template-name-01].[extension]
    ///  │   ├─ [template-name-01].[extension]
    ///  │   └─ ...
    ///  │
    ///  ├─ [author-title-02]
    ///  │   └─ ...
    ///  └─ ...
    /// ```
    Nested,

    /// When selected, the template is rendered to the output directory and
    /// placed inside a directory named after its `group` and another named
    /// after its `nested-directory-template`. This useful if multiple templates
    /// are used to represent a single book i.e. a book template and an
    /// annotation template and there are multiple related and unrelated
    /// templates being rendered to the same directory.
    ///
    ///
    /// ```yaml
    /// output-mode: nested-grouped
    /// ```
    ///
    /// ```plaintext
    /// [ouput-directory]
    ///  │
    ///  ├─ [template-group-01]
    ///  │   │
    ///  │   ├─ [author-title-01]
    ///  │   │   ├─ [template-name-01].[extension]
    ///  │   │   ├─ [template-name-01].[extension]
    ///  │   │   └─ ...
    ///  │   │   
    ///  │   ├─ [author-title-02]
    ///  │   │   ├─ [template-name-02].[extension]
    ///  │   │   ├─ [template-name-02].[extension]
    ///  │   │   └─ ...
    ///  │   └─ ...
    ///  │
    ///  ├─ [template-group-02]
    ///  │   ├─ [author-title-01]
    ///  │   │   └─ ...
    ///  │   └─ ...
    ///  └─ ...
    /// ```
    NestedGrouped,
}

/// An enum representing what a template intends to render.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ContextMode {
    /// When selected, the template is rendered to a single file containing a
    /// [`Book`] and all its [`Annotation`]s.
    ///
    /// ```yaml
    /// render-context: book
    /// ```
    ///
    /// ```plaintext
    /// [ouput-directory]
    ///  └─ [template-name].[extension]
    /// ```
    Book,

    /// When selected, the template is rendered to multiple files containing a
    /// [`Book`] and only one its [`Annotation`]s.
    ///
    /// ```yaml
    /// render-context: annotation
    /// ```
    ///
    /// ```plaintext
    /// [ouput-directory]
    ///  ├─ [template-name].[extension]
    ///  ├─ [template-name].[extension]
    ///  ├─ [template-name].[extension]
    ///  └─ ...
    /// ```
    Annotation,
}

/// A struct representing the raw template strings for generating output file
/// and directory names.
#[derive(Debug, Clone, Deserialize)]
struct NamesRaw {
    /// The default template used when generating an output filename for the
    /// template when its context mode is [`ContextMode::Book`].
    #[serde(default = "NamesRaw::default_book")]
    book: String,

    /// The default template used when generating an output filename for the
    /// template when its context mode is [`ContextMode::Annotation`].
    #[serde(default = "NamesRaw::default_annotation")]
    annotation: String,

    /// The default template used when generating a nested output directory for
    /// the template when its structure mode is either [`StructureMode::Nested`]
    /// or [`StructureMode::NestedGrouped`].
    #[serde(default = "NamesRaw::default_directory")]
    directory: String,
}

impl Default for NamesRaw {
    fn default() -> Self {
        Self {
            book: Self::default_book(),
            annotation: Self::default_annotation(),
            directory: Self::default_directory(),
        }
    }
}

impl NamesRaw {
    fn default_book() -> String {
        super::defaults::FILENAME_TEMPLATE_BOOK.to_owned()
    }

    fn default_annotation() -> String {
        super::defaults::FILENAME_TEMPLATE_ANNOTATION.to_owned()
    }

    fn default_directory() -> String {
        super::defaults::DIRECTORY_TEMPLATE.to_owned()
    }
}

/// A struct representing the rendered template strings for all the output file
/// and directory names for a given template.
///
/// This is used to (1) name files and directories when rendering templates to
/// disk and (2) is included in the template's context so that files/direcories
/// related to the template can be references within the tenplate.
///
/// See [`Templates::render()`][render] for more information.
///
/// [render]: super::manager::Templates::render()
#[derive(Debug, Default, Clone, Serialize)]
pub struct NamesRender {
    /// The output filename for a template with [`ContextMode::Book`].
    pub book: String,

    /// The output filenames for a template with [`ContextMode::Annotation`].
    ///
    /// Internally this field is stored as a `HashMap` but is converted into a
    /// `Vec` before it's injected into a template.
    #[serde(serialize_with = "super::utils::serialize_hashmap_to_vec")]
    pub annotations: HashMap<String, AnnotationNameAttributes>,

    /// The directory name for a template with [`StructureMode::Nested`] or
    /// [`StructureMode::NestedGrouped`].
    pub directory: String,
}

impl NamesRender {
    /// Creates a new instance of [`NamesRender`] given an [`Entry`] and
    /// a [`TemplateRaw`].
    ///
    /// Note that all names are generated regardless of the template's
    /// [`ContextMode`]. For example, when a separate template is used to render
    /// a [`Book`] and another for its [`Annotation`]s, it's important that both
    /// templates have access to the other's filenames so they can link to one
    /// another if the user desires.
    ///
    /// # Arguments
    ///
    /// * `entry` - The [`Entry`] injected into the filename templates.
    /// * `template` - The [`TemplateRaw`] containing the filename templates.
    ///
    /// # Errors
    ///
    /// Will return `Err` if:
    /// * Any templates have syntax errors or are referencing non-existent
    /// fields in their respective contexts.
    pub fn new(entry: &Entry, template: &TemplateRaw) -> Result<Self> {
        let names = Self {
            book: Self::render_book_filename(entry, template)?,
            annotations: Self::render_annotation_filenames(entry, template)?,
            directory: Self::render_directory_name(entry, template)?,
        };

        Ok(names)
    }

    fn render_book_filename(entry: &Entry, template: &TemplateRaw) -> Result<String> {
        let context = TemplateContext::name_book(entry);

        let mut filename = Tera::one_off(
            &template.names.book,
            &Context::from_serialize(context)?,
            false,
        )?;

        filename = crate::utils::sanitize_string(&filename);

        Ok(format!("{filename}.{}", template.extension))
    }

    fn render_annotation_filenames(
        entry: &Entry,
        template: &TemplateRaw,
    ) -> Result<HashMap<String, AnnotationNameAttributes>> {
        let mut annotations = HashMap::new();

        for annotation in &entry.annotations {
            let context = TemplateContext::name_annotation(&entry.book, annotation);

            let mut filename = Tera::one_off(
                &template.names.annotation,
                &Context::from_serialize(context)?,
                false,
            )?;

            filename = crate::utils::sanitize_string(&filename);
            filename = format!("{filename}.{}", template.extension);

            annotations.insert(
                annotation.metadata.id.clone(),
                AnnotationNameAttributes::new(annotation, filename),
            );
        }

        Ok(annotations)
    }

    fn render_directory_name(entry: &Entry, template: &TemplateRaw) -> Result<String> {
        let context = TemplateContext::name_book(entry);

        let mut directory_name = Tera::one_off(
            &template.names.directory,
            &Context::from_serialize(context)?,
            false,
        )?;

        directory_name = crate::utils::sanitize_string(&directory_name);

        Ok(directory_name)
    }
}

/// A struct representing the rendered filename for a template with
/// [`ContextMode::Annotation`] along with various other fields used for
/// sorting within a template. See [`NamesRender::annotations`][names-render]
/// for more information.
///
/// See [`AnnotationMetadata`][annotation-metadata] for information on
/// undocumented fields.
///
/// [annotation-metadata]: crate::models::annotation::AnnotationMetadata
/// [names-render]: NamesRender#structfield.annotations
#[allow(missing_docs)]
#[derive(Debug, Default, Clone, Serialize)]
pub struct AnnotationNameAttributes {
    /// The rendered filename for a template with [`ContextMode::Annotation`].
    pub filename: String,
    pub created: DateTimeUtc,
    pub modified: DateTimeUtc,
    pub location: String,
}

impl AnnotationNameAttributes {
    /// Creates a new instance of [`AnnotationNameAttributes`].
    fn new(annotation: &Annotation, filename: String) -> Self {
        Self {
            filename,
            created: annotation.metadata.created,
            modified: annotation.metadata.modified,
            location: annotation.metadata.location.clone(),
        }
    }
}

/// An enum representing all possible template contexts.
///
/// This primarily used to shuffle data to fit a certain shape before it's
/// injected into a template.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum TemplateContext<'a> {
    /// Used when rendering both a [`Book`] and its [`Annotation`]s in a
    /// template. Includes all the output filenames and the nested directory
    /// name.
    Book {
        /// The [`Book`] being injected into the template.
        book: &'a Book,

        /// The [`Annotation`]s being injected into the template.
        annotations: &'a [Annotation],

        /// The filenames and nested directory name.
        names: &'a NamesRender,
    },
    /// Used when rendering a single annotation in a template. Includes all the
    /// output filenames and the nested directory name.
    Annotation {
        /// The [`Book`] being injected into the template.
        book: &'a Book,

        /// The [`Annotation`] being injected into the template.
        annotation: &'a Annotation,

        /// The filenames and nested directory name.
        names: &'a NamesRender,
    },
    /// Used when rendering the output filename for a template with
    /// [`ContextMode::Book`].
    NameBook {
        /// The [`Book`] being injected into the template.
        book: &'a Book,

        /// The [`Annotation`] being injected into the template.
        annotations: &'a [Annotation],
    },
    /// Used when rendering the output filename for a template with
    /// [`ContextMode::Annotation`].
    NameAnnotation {
        /// The [`Book`] being injected into the template.
        book: &'a Book,

        /// The [`Annotation`] being injected into the template.
        annotation: &'a Annotation,
    },
}

#[allow(missing_docs)]
impl<'a> TemplateContext<'a> {
    #[must_use]
    pub fn book(entry: &'a Entry, names: &'a NamesRender) -> Self {
        Self::Book {
            book: &entry.book,
            annotations: &entry.annotations,
            names,
        }
    }

    #[must_use]
    pub fn annotation(book: &'a Book, annotation: &'a Annotation, names: &'a NamesRender) -> Self {
        Self::Annotation {
            book,
            annotation,
            names,
        }
    }

    #[must_use]
    pub fn name_book(entry: &'a Entry) -> Self {
        Self::NameBook {
            book: &entry.book,
            annotations: &entry.annotations,
        }
    }

    #[must_use]
    pub fn name_annotation(book: &'a Book, annotation: &'a Annotation) -> Self {
        Self::NameAnnotation { book, annotation }
    }
}

#[cfg(test)]
mod test_templates {

    use crate::defaults::TEST_TEMPLATES;

    use super::*;

    fn load_template_string(directory: &str, filename: &str) -> String {
        let path = TEST_TEMPLATES.join(directory).join(filename);
        std::fs::read_to_string(path).unwrap()
    }

    // https://stackoverflow.com/a/68919527/16968574
    fn test_invalid_template_config(directory: &str, filename: &str) {
        let string = load_template_string(directory, filename);
        let result = TemplateRaw::parse(&string).ok_or(Error::InvalidTemplateConfig {
            path: filename.to_string(),
        });

        assert!(matches!(
            result,
            Err(Error::InvalidTemplateConfig { path: _ })
        ));
    }

    // https://stackoverflow.com/a/68919527/16968574
    fn test_valid_template_config(directory: &str, filename: &str) {
        let string = load_template_string(directory, filename);
        let result = TemplateRaw::parse(&string).ok_or(Error::InvalidTemplateConfig {
            path: filename.to_string(),
        });

        assert!(matches!(result, Ok(_)));
    }

    mod invalid_config {

        use super::*;

        const DIRECTORY: &str = "invalid-config";

        // Tests that a missing config block returns an error.
        #[test]
        fn missing_config() {
            test_invalid_template_config(DIRECTORY, "missing-config.txt");
        }

        // Tests that a missing closing tag returns an error.
        #[test]
        fn missing_closing_tag() {
            test_invalid_template_config(DIRECTORY, "missing-closing-tag.txt");
        }

        // Tests that missing `readstor` in the opening tag returns an error.
        #[test]
        fn incomplete_opening_tag_01() {
            test_invalid_template_config(DIRECTORY, "incomplete-opening-tag-01.txt");
        }

        // Tests that missing the `!` in the opening tag returns an error.
        #[test]
        fn incomplete_opening_tag_02() {
            test_invalid_template_config(DIRECTORY, "incomplete-opening-tag-02.txt");
        }

        // Tests that no linebreak after `readstor` returns an error.
        #[test]
        fn missing_linebreak_01() {
            test_invalid_template_config(DIRECTORY, "missing-linebreak-01.txt");
        }

        // Tests that no linebreak after the config body returns an error.
        #[test]
        fn missing_linebreak_02() {
            test_invalid_template_config(DIRECTORY, "missing-linebreak-02.txt");
        }

        // Tests that no linebreak after the closing tag returns an error.
        #[test]
        fn missing_linebreak_03() {
            test_invalid_template_config(DIRECTORY, "missing-linebreak-03.txt");
        }

        // Tests that no linebreak before the opening tag returns an error.
        #[test]
        fn missing_linebreak_04() {
            test_invalid_template_config(DIRECTORY, "missing-linebreak-04.txt");
        }
    }

    mod valid_config {

        use super::*;

        const DIRECTORY: &str = "valid-config";

        // Test the minimum required keys.
        #[test]
        fn minimum_required_keys() {
            let filename = "minimum-required-keys.txt";
            let string = load_template_string(DIRECTORY, filename);
            let result = TemplateRaw::new(filename, &string);

            assert!(matches!(result, Ok(_)));
        }

        // Tests that a template with pre- and post-config-content returns no error.
        #[test]
        fn pre_and_post_config_content() {
            test_valid_template_config(DIRECTORY, "pre-and-post-config-content.txt");
        }

        // Tests that a template with pre-config-content returns no error.
        #[test]
        fn pre_config_content() {
            test_valid_template_config(DIRECTORY, "pre-config-content.txt");
        }

        // Tests that a template with post-config-content returns no error.
        #[test]
        fn post_config_content() {
            test_valid_template_config(DIRECTORY, "post-config-content.txt");
        }
    }
}