diff --git a/backend/task/src/utils/front_matter.rs b/backend/task/src/utils/front_matter.rs new file mode 100644 index 0000000..8379914 --- /dev/null +++ b/backend/task/src/utils/front_matter.rs @@ -0,0 +1,55 @@ +// derived from https://github.com/EstebanBorai/yaml-front-matter +use serde::de::DeserializeOwned; + +pub struct Document { + pub metadata: T, + pub content: String, +} + +pub struct YamlFrontMatter; +impl YamlFrontMatter { + pub fn parse( + markdown: &str, + ) -> Result, Box> { + let yaml = YamlFrontMatter::extract(markdown)?; + let metadata = serde_yaml::from_str::(yaml.0.as_str())?; + + Ok(Document { + metadata, + content: yaml.1, + }) + } + + fn extract(markdown: &str) -> Result<(String, String), Box> { + 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::>() + .join("\n"), + )) + } +} diff --git a/backend/task/src/utils/mod.rs b/backend/task/src/utils/mod.rs new file mode 100644 index 0000000..30dc886 --- /dev/null +++ b/backend/task/src/utils/mod.rs @@ -0,0 +1 @@ +pub mod front_matter;