1use markdoc::IndexMap;
21use markdoc::ast::Node;
22use markdoc::types::Scalar;
23
24pub type Map = IndexMap<String, Scalar>;
26
27pub fn of(doc: &Node) -> Option<&Map> {
29 match doc.attributes.get("frontmatter") {
30 Some(Scalar::Object(map)) => Some(map),
31 _ => None,
32 }
33}
34
35pub fn text(value: &Scalar) -> Option<String> {
43 match value {
44 Scalar::String(s) if !s.trim().is_empty() => Some(s.clone()),
45 Scalar::Number(n) if n.is_finite() && n.fract() == 0.0 => Some(format!("{}", *n as i64)),
46 Scalar::Number(n) => Some(n.to_string()),
47 Scalar::Boolean(b) => Some(b.to_string()),
48 _ => None,
49 }
50}
51
52pub fn field(fm: &Map, key: &str) -> Option<String> {
54 fm.get(key).and_then(text)
55}
56
57pub fn list(fm: &Map, key: &str) -> Vec<String> {
60 match fm.get(key) {
61 Some(Scalar::Array(items)) => items.iter().filter_map(text).collect(),
62 Some(value) => text(value).into_iter().collect(),
63 None => Vec::new(),
64 }
65}
66
67pub fn rows(fm: &Map, key: &str, fields: &[&str]) -> Vec<Vec<Option<String>>> {
72 let Some(Scalar::Array(items)) = fm.get(key) else {
73 return Vec::new();
74 };
75 items
76 .iter()
77 .filter_map(|item| match item {
78 Scalar::Object(entry) => Some(fields.iter().map(|name| field(entry, name)).collect()),
79 _ => None,
80 })
81 .collect()
82}
83
84#[derive(Debug, Clone, PartialEq)]
86pub struct Section {
87 pub path: String,
88 pub subsections: Vec<String>,
89}
90
91pub fn sections(fm: &Map) -> Vec<Section> {
105 let Some(Scalar::Array(items)) = fm.get("sections") else {
106 return Vec::new();
107 };
108 items
109 .iter()
110 .filter_map(|item| match item {
111 Scalar::Array(pair) => {
112 let path = pair.first().and_then(text)?;
113 let subsections = match pair.get(1) {
114 Some(Scalar::Array(subs)) => subs.iter().filter_map(text).collect(),
115 Some(value) => text(value).into_iter().collect(),
116 None => Vec::new(),
117 };
118 Some(Section { path, subsections })
119 }
120 other => text(other).map(|path| Section {
121 path,
122 subsections: Vec::new(),
123 }),
124 })
125 .collect()
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131
132 fn parse(source: &str) -> markdoc::types::Result<Node> {
133 use crate::pipeline;
134 pipeline::parse(
135 source,
136 &pipeline::parse_options(&pipeline::bundle(&[]).unwrap()),
137 )
138 }
139
140 const HISTORY: [&str; 3] = ["version", "date", "description"];
142
143 fn fm(yaml: &str) -> Map {
144 let doc = parse(&format!("---\n{yaml}---\n\nbody\n")).unwrap();
145 of(&doc).cloned().expect("frontmatter")
146 }
147
148 #[test]
149 fn a_manual_reads_whole() {
150 let fm = fm(r#"id: "item-2025-11-04-002"
151doc_type: "manual"
152title: "ProductX Manual"
153status: "published"
154version: "5.3"
155language: "en-us"
156releaseDate: "2024-01-01"
157updateDate: "2025-11-04"
158description: "Everything about ProductX."
159authors: ["A. Writer", "B. Editor"]
160creator: "the pipeline"
161documentHistory:
162 - version: "5.3"
163 date: "2025-11-04"
164 description: "Clarified the safety chapter."
165 - version: "5.2"
166 date: "2025-06-01"
167"#);
168 assert_eq!(field(&fm, "title").as_deref(), Some("ProductX Manual"));
169 assert_eq!(field(&fm, "language").as_deref(), Some("en-us"));
170 assert_eq!(field(&fm, "releaseDate").as_deref(), Some("2024-01-01"));
171 assert_eq!(field(&fm, "updateDate").as_deref(), Some("2025-11-04"));
172 assert_eq!(
173 field(&fm, "description").as_deref(),
174 Some("Everything about ProductX.")
175 );
176 assert_eq!(list(&fm, "authors"), vec!["A. Writer", "B. Editor"]);
177 assert_eq!(field(&fm, "creator").as_deref(), Some("the pipeline"));
178 assert_eq!(
179 rows(&fm, "documentHistory", &HISTORY),
180 vec![
181 vec![
182 Some("5.3".into()),
183 Some("2025-11-04".into()),
184 Some("Clarified the safety chapter.".into()),
185 ],
186 vec![Some("5.2".into()), Some("2025-06-01".into()), None],
187 ]
188 );
189 }
190
191 #[test]
192 fn an_unquoted_version_costs_nothing_else() {
193 let fm = fm(
196 "title: \"Set up the router\"\nversion: 1.13\nlanguage: en\nreleaseDate: 2023-02-01\ndocumentHistory:\n - version: 1.0\n date: 2021-01-01\n",
197 );
198 assert_eq!(field(&fm, "title").as_deref(), Some("Set up the router"));
199 assert_eq!(field(&fm, "language").as_deref(), Some("en"));
200 assert_eq!(field(&fm, "releaseDate").as_deref(), Some("2023-02-01"));
201 assert_eq!(field(&fm, "version").as_deref(), Some("1.13"));
202 let history = rows(&fm, "documentHistory", &HISTORY);
203 assert_eq!(history[0][0].as_deref(), Some("1"));
204 assert_eq!(history[0][1].as_deref(), Some("2021-01-01"));
205 }
206
207 #[test]
208 fn a_field_of_the_wrong_shape_is_absent_not_fatal() {
209 let fm = fm(
210 "title: [\"a\", \"b\"]\nlanguage: \"\"\nauthors: \"Only One\"\ndocumentHistory: \"not a list\"\nsections: 7\n",
211 );
212 assert_eq!(field(&fm, "title"), None, "a list is not a title");
213 assert_eq!(
214 field(&fm, "language"),
215 None,
216 "an empty string is no language"
217 );
218 assert_eq!(list(&fm, "authors"), vec!["Only One"]);
219 assert!(rows(&fm, "documentHistory", &HISTORY).is_empty());
220 assert!(sections(&fm).is_empty());
221 assert_eq!(field(&fm, "creator"), None);
222 }
223
224 #[test]
225 fn sections_read_as_a_tree() {
226 let fm = fm(r#"sections:
227- - "/manual/intro/intro_to_productx"
228 - []
229- - "/manual/safety/intro_to_safety"
230 - - "manual/safety/safety_message_types"
231 - "manual/safety/general_safety_precautions"
232- "manual/appendix"
233- - 42
234"#);
235 assert_eq!(
236 sections(&fm),
237 vec![
238 Section {
239 path: "/manual/intro/intro_to_productx".into(),
240 subsections: vec![],
241 },
242 Section {
243 path: "/manual/safety/intro_to_safety".into(),
244 subsections: vec![
245 "manual/safety/safety_message_types".into(),
246 "manual/safety/general_safety_precautions".into(),
247 ],
248 },
249 Section {
250 path: "manual/appendix".into(),
251 subsections: vec![],
252 },
253 Section {
254 path: "42".into(),
255 subsections: vec![],
256 },
257 ]
258 );
259 }
260
261 #[test]
262 fn rows_read_any_list_of_maps_by_the_names_asked_for() {
263 let fm = fm(r#"changes:
264 - when: "2024"
265 who: "A. Writer"
266 extra: "not asked for"
267 - "not a map"
268 - who: ["a", "list"]
269 - {}
270"#);
271 assert_eq!(
272 rows(&fm, "changes", &["who", "when"]),
273 vec![
274 vec![Some("A. Writer".into()), Some("2024".into())],
275 vec![None, None],
276 vec![None, None],
277 ]
278 );
279 assert!(rows(&fm, "missing", &["who"]).is_empty());
280 assert_eq!(
281 rows(&fm, "changes", &[]),
282 vec![Vec::<Option<String>>::new(); 3]
283 );
284 }
285
286 #[test]
287 fn no_frontmatter_is_no_map() {
288 let doc = parse("# Just a page\n").unwrap();
289 assert!(of(&doc).is_none());
290 }
291}