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
use std::fmt;

use crate::Frontmatter;
use crate::Result;
use crate::Status;

#[derive(Debug, Eq, PartialEq, Default, Clone)]
pub struct Document {
    front: crate::Frontmatter,
    content: liquid_core::model::KString,
}

impl Document {
    pub fn new(front: Frontmatter, content: liquid_core::model::KString) -> Self {
        Self { front, content }
    }

    pub fn parse(content: &str) -> Result<Self> {
        let (front, content) = split_document(content);
        let front = front
            .map(parse_frontmatter)
            .map_or(Ok(None), |r| r.map(Some))?
            .unwrap_or_default();
        let content = liquid_core::model::KString::from_ref(content);
        Ok(Self { front, content })
    }

    pub fn into_parts(self) -> (Frontmatter, liquid_core::model::KString) {
        let Self { front, content } = self;
        (front, content)
    }
}

impl fmt::Display for Document {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let front = self.front.to_string();
        if front.is_empty() {
            write!(f, "{}", self.content)
        } else {
            write!(f, "---\n{}\n---\n{}", front, self.content)
        }
    }
}

fn parse_frontmatter(front: &str) -> Result<Frontmatter> {
    let front: Frontmatter = serde_yaml::from_str(front)
        .map_err(|e| Status::new("Failed to parse frontmatter").with_source(e))?;
    Ok(front)
}

#[cfg(feature = "preview_unstable")]
static FRONT_MATTER: once_cell::sync::Lazy<regex::Regex> = once_cell::sync::Lazy::new(|| {
    regex::RegexBuilder::new(r"\A---\s*\r?\n([\s\S]*\n)?---\s*\r?\n(.*)")
        .dot_matches_new_line(true)
        .build()
        .unwrap()
});

#[cfg(feature = "preview_unstable")]
fn split_document(content: &str) -> (Option<&str>, &str) {
    if let Some(captures) = FRONT_MATTER.captures(content) {
        let front_split = captures.get(1).map(|m| m.as_str()).unwrap_or_default();
        let content_split = captures.get(2).unwrap().as_str();

        if front_split.is_empty() {
            (None, content_split)
        } else {
            (Some(front_split), content_split)
        }
    } else {
        (None, content)
    }
}

#[cfg(not(feature = "preview_unstable"))]
fn split_document(content: &str) -> (Option<&str>, &str) {
    static FRONT_MATTER_DIVIDE: once_cell::sync::Lazy<regex::Regex> =
        once_cell::sync::Lazy::new(|| {
            regex::RegexBuilder::new(r"---\s*\r?\n")
                .dot_matches_new_line(true)
                .build()
                .unwrap()
        });
    static FRONT_MATTER: once_cell::sync::Lazy<regex::Regex> = once_cell::sync::Lazy::new(|| {
        regex::RegexBuilder::new(r"\A---\s*\r?\n([\s\S]*\n)?---\s*\r?\n")
            .dot_matches_new_line(true)
            .build()
            .unwrap()
    });

    if FRONT_MATTER.is_match(content) {
        // skip first empty string
        let mut splits = FRONT_MATTER_DIVIDE.splitn(content, 3).skip(1);

        // split between dividers
        let front_split = splits.next().unwrap_or("");

        // split after second divider
        let content_split = splits.next().unwrap_or("");

        if front_split.is_empty() {
            (None, content_split)
        } else {
            (Some(front_split), content_split)
        }
    } else {
        deprecated_split_front_matter(content)
    }
}

#[cfg(not(feature = "preview_unstable"))]
fn deprecated_split_front_matter(content: &str) -> (Option<&str>, &str) {
    static FRONT_MATTER_DIVIDE: once_cell::sync::Lazy<regex::Regex> =
        once_cell::sync::Lazy::new(|| {
            regex::RegexBuilder::new(r"(\A|\n)---\s*\r?\n")
                .dot_matches_new_line(true)
                .build()
                .unwrap()
        });
    if FRONT_MATTER_DIVIDE.is_match(content) {
        log::warn!("Trailing separators are deprecated. We recommend frontmatters be surrounded, above and below, with ---");

        let mut splits = FRONT_MATTER_DIVIDE.splitn(content, 2);

        // above the split are the attributes
        let front_split = splits.next().unwrap_or("");

        // everything below the split becomes the new content
        let content_split = splits.next().unwrap_or("");

        if front_split.is_empty() {
            (None, content_split)
        } else {
            (Some(front_split), content_split)
        }
    } else {
        (None, content)
    }
}

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

    #[test]
    fn split_document_empty() {
        let input = "";
        let (cobalt_model, content) = split_document(input);
        assert!(cobalt_model.is_none());
        assert_eq!(content, "");
    }

    #[test]
    fn split_document_no_front_matter() {
        let input = "Body";
        let (cobalt_model, content) = split_document(input);
        assert!(cobalt_model.is_none());
        assert_eq!(content, "Body");
    }

    #[test]
    fn split_document_empty_front_matter() {
        let input = "---\n---\nBody";
        let (cobalt_model, content) = split_document(input);
        assert!(cobalt_model.is_none());
        assert_eq!(content, "Body");
    }

    #[test]
    fn split_document_empty_body() {
        let input = "---\ncobalt_model\n---\n";
        let (cobalt_model, content) = split_document(input);
        assert_eq!(cobalt_model.unwrap(), "cobalt_model\n");
        assert_eq!(content, "");
    }

    #[test]
    fn split_document_front_matter_and_body() {
        let input = "---\ncobalt_model\n---\nbody";
        let (cobalt_model, content) = split_document(input);
        assert_eq!(cobalt_model.unwrap(), "cobalt_model\n");
        assert_eq!(content, "body");
    }

    #[test]
    fn split_document_no_new_line_after_front_matter() {
        let input = "invalid_front_matter---\nbody";
        let (cobalt_model, content) = split_document(input);
        println!("{:?}", cobalt_model);
        assert!(cobalt_model.is_none());
        assert_eq!(content, input);
    }

    #[test]
    fn split_document_multiline_body() {
        let input = "---\ncobalt_model\n---\nfirst\nsecond";
        let (cobalt_model, content) = split_document(input);
        println!("{:?}", cobalt_model);
        assert_eq!(cobalt_model.unwrap(), "cobalt_model\n");
        assert_eq!(content, "first\nsecond");
    }

    #[test]
    fn display_empty() {
        let front = Frontmatter::empty();
        let doc = Document::new(front, liquid_core::model::KString::new());
        assert_eq!(&doc.to_string(), "");
    }

    #[test]
    fn display_empty_front() {
        let front = Frontmatter::empty();
        let doc = Document::new(front, "body".into());
        assert_eq!(&doc.to_string(), "body");
    }

    #[test]
    fn display_empty_body() {
        let front = Frontmatter {
            slug: Some("foo".into()),
            ..Default::default()
        };
        let doc = Document::new(front, liquid_core::model::KString::new());
        assert_eq!(&doc.to_string(), "---\nslug: foo\n---\n");
    }

    #[test]
    fn display_both() {
        let front = Frontmatter {
            slug: Some("foo".into()),
            ..Default::default()
        };
        let doc = Document::new(front, "body".into());
        assert_eq!(&doc.to_string(), "---\nslug: foo\n---\nbody");
    }
}