added front matter parser for markdown
This commit is contained in:
parent
a742dd7f12
commit
44be4ab04a
55
backend/task/src/utils/front_matter.rs
Normal file
55
backend/task/src/utils/front_matter.rs
Normal 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"),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
1
backend/task/src/utils/mod.rs
Normal file
1
backend/task/src/utils/mod.rs
Normal file
@ -0,0 +1 @@
|
|||||||
|
pub mod front_matter;
|
Loading…
Reference in New Issue
Block a user