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
use chrono::prelude::*;
use gray_matter::{
    engine::{Engine, TOML, YAML},
    Matter,
};
use lazy_regex::regex;
use mdbook::{
    book::{Book, BookItem},
    errors::*,
    preprocess::{Preprocessor, PreprocessorContext},
};
use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Config {
    title: Option<String>,
    date: Option<String>,
    draft: Option<bool>,
}

pub struct FrontMatter;

impl Preprocessor for FrontMatter {
    fn name(&self) -> &str {
        "front_matter"
    }

    fn run(&self, _: &PreprocessorContext, mut book: Book) -> Result<Book, Error> {
        let re = regex!(r"(?sm)^\s*---(.*)---\s*$");
        book.for_each_mut(|item| {
            if let BookItem::Chapter(ch) = item {
                let content = ch.content.clone();

                let mut handle_front_matter = |config: Config| {
                    // Set as draft chapter
                    if let Some(true) = config.draft {
                        ch.path = None
                    }

                    // Remove metadata from content
                    ch.content = re.replace_all(&ch.content, "").to_string();

                    // Set title
                    if let Some(title) = config.title {
                        ch.name = title;
                    }

                    // Set date
                    if let Some(datestring) = config.date {
                        let format = "%H:%M %A %d %B %Y";

                        // Parse the supplied datestring (NOTE: Very verbose. There should be a more elegant way)
                        let formatted_date = if let Ok(datetime) = datestring.parse::<DateTime<FixedOffset>>() {
                            // Timezone is specified in datestring. Use that timezone
                            datetime.format(format).to_string()
                        } else if let Ok(naive_datetime) = datestring.parse::<NaiveDateTime>() {
                            // Timezone is not specified, use local timezone
                            let datetime = Local.from_local_datetime(&naive_datetime).unwrap();
                            datetime.format(format).to_string()
                        } else if let Ok(naive_datetime) = NaiveDateTime::parse_from_str(&datestring, "%Y-%m-%dT%H:%M") {
                            // Timezone and seconds are not specified.
                            let datetime = Local.from_local_datetime(&naive_datetime).unwrap();
                            datetime.format(format).to_string()
                        } else {
                            // Could not parse date
                            "Unknown date format".to_string()
                        };

                        ch.content = format!(
                            "{}\n\n<div class=\"datetime\" style=\"text-align: center; color: gray; font-style: italic; font-size: 90%;\">{}</div>\n\n",
                            ch.content,
                            &formatted_date,
                        );
                    }
                };

                if let Some(config) = parse_matter::<YAML>(&content) {
                    handle_front_matter(config);
                } else if let Some(config) = parse_matter::<TOML>(&content) {
                    handle_front_matter(config);
                }
            }
        });

        Ok(book)
    }
}

fn parse_matter<T: Engine>(content: &str) -> Option<Config> {
    let matter: Matter<T> = Matter::new();
    Some(matter.parse_with_struct::<Config>(content)?.data)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_yaml() {
        let yaml_parsable_content = r#"---
title: Title
date: 2001-01-01T01:01
---

Markdown content."#;

        let yaml_unparsable_content = r#"---
title = "Title"
wrong_key: 42
---

Markdown content."#;

        let parsed = parse_matter::<YAML>(&yaml_parsable_content).unwrap();
        assert_eq!(parsed.title.unwrap(), "Title");
        assert!(parse_matter::<YAML>(&yaml_unparsable_content).is_none())
    }

    #[test]
    fn test_parse_toml() {
        let toml_parsable_content = r#"---
title = "Title"
date = "2001-01-01T01:01"
---

Markdown content."#;

        let toml_unparsable_content = r#"---
title: Title
wrong_key = 42
---

Markdown content."#;

        let parsed = parse_matter::<TOML>(&toml_parsable_content).unwrap();
        assert_eq!(parsed.title.unwrap(), "Title");
        assert!(parse_matter::<TOML>(&toml_unparsable_content).is_none())
    }
}