added front matter parser for markdown

This commit is contained in:
Wyatt J. Miller 2024-09-29 21:15:42 -04:00
parent a742dd7f12
commit 44be4ab04a
2 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,55 @@
// derived from https://github.com/EstebanBorai/yaml-front-matter
use serde::de::DeserializeOwned;
pub struct Document<T: DeserializeOwned> {
pub metadata: T,
pub content: String,
}
pub struct YamlFrontMatter;
impl YamlFrontMatter {
pub fn parse<T: DeserializeOwned>(
markdown: &str,
) -> Result<Document<T>, Box<dyn std::error::Error>> {
let yaml = YamlFrontMatter::extract(markdown)?;
let metadata = serde_yaml::from_str::<T>(yaml.0.as_str())?;
Ok(Document {
metadata,
content: yaml.1,
})
}
fn extract(markdown: &str) -> Result<(String, String), Box<dyn std::error::Error>> {
let mut front_matter = String::default();
let mut sentinel = false;
let mut front_matter_lines = 0;
let lines = markdown.lines();
for line in lines.clone() {
front_matter_lines += 1;
if line.trim() == "---" {
if sentinel {
break;
}
sentinel = true;
continue;
}
if sentinel {
front_matter.push_str(line);
front_matter.push('\n');
}
}
Ok((
front_matter,
lines
.skip(front_matter_lines)
.collect::<Vec<&str>>()
.join("\n"),
))
}
}

View File

@ -0,0 +1 @@
pub mod front_matter;