about summary refs log tree commit diff
path: root/paige/src/templated.rs
blob: 2cbb1b9622cf54dbdf2ab440353e6c1271a6b24d (plain)
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
use std::fmt;

/// The content part of a file that fills in a template.
pub struct Templated<'r> {
	pub frontmatter: Frontmatter<'r>,
	pub content: &'r str,
}

impl<'r> Templated<'r> {
	pub fn parse(raw: &'r str) -> Result<Self, TemplateError> {
		tracing::trace!("parsing Templated");

		let (front, content) = match raw.strip_prefix("---\n") {
			None => return Err(TemplateError::MissingFrontmatter),
			Some(no_start) => match no_start.split_once("\n---\n") {
				None => return Err(TemplateError::MissingFrontmatter),
				Some((front, content)) => (front, content),
			},
		};

		tracing::trace!("isolated frontmatter");

		Ok(Self {
			frontmatter: Frontmatter::parse(front)?,
			content,
		})
	}
}

/// frontmatter from a template
///
/// Frontmatter must always be at the top of the file bounded by `---`
///
/// ```plain
/// ---
/// title=Page Title
/// description=OpenGraph description
/// ---
///
/// Page content
/// ```
pub struct Frontmatter<'r> {
	entries: Vec<(&'r str, &'r str)>,
}

impl<'r> Frontmatter<'r> {
	pub fn parse(raw: &'r str) -> Result<Self, TemplateError> {
		let mut entries = vec![];

		for line in raw.lines() {
			let trimmed = line.trim();
			if trimmed.is_empty() || trimmed.starts_with('#') {
				// Skip over blank lines and comments
				continue;
			}

			let (key, value) = match trimmed.split_once('=') {
				None => {
					return Err(TemplateError::MalformedFrontmatterEntry {
						line: trimmed.to_owned(),
					});
				}
				Some(tup) => tup,
			};

			entries.push((key.trim(), value.trim()));
			tracing::trace!("pushed frontmatter entry {} successfully", key.trim());
		}

		Ok(Self { entries })
	}

	pub fn get(&self, key: &str) -> Option<&str> {
		self.entries
			.iter()
			.find(|(k, _)| *k == key)
			.map(|(_, v)| *v)
	}

	/// Convenience for `[Frontmatter::get()]` and `to_owned()`
	pub fn get_owned(&self, key: &str) -> Option<String> {
		self.entries
			.iter()
			.find(|(k, _)| *k == key)
			.map(|(_, v)| (*v).to_owned())
	}

	pub fn get_many(&self, key: &str) -> Vec<&str> {
		// this could probably be a filter_map() but the explicit filter and
		// then map seems cleaner
		self.entries
			.iter()
			.filter(|(k, _)| *k == key)
			.map(|(_, v)| *v)
			.collect()
	}
}

#[derive(Debug)]
pub enum TemplateError {
	MissingFrontmatter,
	MalformedFrontmatterEntry { line: String },
}
impl std::error::Error for TemplateError {}

impl fmt::Display for TemplateError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::MissingFrontmatter => write!(f, "the template does not have frontmatter"),
			Self::MalformedFrontmatterEntry { line } => {
				write!(f, "this frontmatter is malformed: {line}")
			}
		}
	}
}

#[cfg(test)]
mod test {
	use crate::templated::{Frontmatter, Templated};

	#[test]
	fn frontmatter_parse() {
		let frntmtr = "key=value\nkey2=value2";
		assert!(Frontmatter::parse(frntmtr).is_ok())
	}

	#[test]
	fn frontmatter_fails_on_invalid_line() {
		let front = "key1=value1\nincorrect line";
		assert!(Frontmatter::parse(front).is_err())
	}

	#[test]
	fn templated_parse() {
		let tempalted = "---\ntitle=Title!\n---\nContent line!";
		assert!(Templated::parse(tempalted).is_ok())
	}

	#[test]
	fn templated_doesnt_eat_frontmatter_line() {
		let templated = "---\ntitle=Title---\nContent";
		assert!(Templated::parse(templated).is_err());
	}

	#[test]
	fn templated_parses_correct() {
		let raw = "---\ntitle=Title!\n---\n<p>Paragraph!</p>";
		let tmpl = Templated::parse(raw).unwrap();
		assert_eq!(tmpl.frontmatter.get("title").unwrap(), "Title!");
		assert_eq!(tmpl.content, "<p>Paragraph!</p>")
	}
}