1#[derive(Clone, Debug, Default, PartialEq, Eq)]
6pub struct Front {
7 pub title: Option<String>,
8 pub author: Option<String>,
9 pub date: Option<String>,
10}
11
12impl Front {
13 pub fn is_empty(&self) -> bool {
14 self.title.is_none() && self.author.is_none() && self.date.is_none()
15 }
16}
17
18pub fn split(markdown: &str) -> (Front, &str) {
20 let Some(rest) = markdown.strip_prefix("---\n") else {
21 return (Front::default(), markdown);
22 };
23 let Some(end) = rest.find("\n---") else {
24 return (Front::default(), markdown);
25 };
26 let after = &rest[end + 4..];
27 let after = after.strip_prefix('\n').unwrap_or(after);
28 let mut front = Front::default();
29 for line in rest[..end].lines() {
30 let Some((key, value)) = line.split_once(':') else {
31 continue;
32 };
33 let value = value
34 .trim()
35 .trim_matches(|c| c == '"' || c == '\'')
36 .to_string();
37 if value.is_empty() {
38 continue;
39 }
40 match key.trim() {
41 "title" => front.title = Some(value),
42 "author" | "authors" => front.author = Some(value),
43 "date" => front.date = Some(value),
44 _ => {}
45 }
46 }
47 (front, after)
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn front_matter_gives_a_title_and_the_rest() {
56 let text = "---\ntitle: \"An RFC\"\nauthor: Ada\ntags: [a]\n---\n\n# Body\n";
57 let (front, rest) = split(text);
58 assert_eq!(front.title.as_deref(), Some("An RFC"));
59 assert_eq!(front.author.as_deref(), Some("Ada"));
60 assert_eq!(rest, "\n# Body\n");
61 }
62
63 #[test]
64 fn a_document_without_it_is_left_alone() {
65 let text = "# Title\n\n---\n\nmore\n";
66 assert_eq!(split(text), (Front::default(), text));
67 }
68}