lib/
post_parser.rs

1use pulldown_cmark::{html::push_html, Options, Parser};
2use regex::Regex;
3
4pub struct PostParser {
5    markdown_text: String,
6}
7
8impl PostParser {
9    pub fn new(markdown_text: &str) -> PostParser {
10        PostParser {
11            markdown_text: markdown_text.to_string(),
12        }
13    }
14
15    fn seperate_header(&self) -> (String, String) {
16        let re = Regex::new(r"\A---\n((.|\n)*?)---\n((.|\n)*)").unwrap();
17
18        let captures = re
19            .captures(&self.markdown_text)
20            .expect("Could not split header and body");
21
22        (captures[1].to_string(), captures[3].to_string())
23    }
24
25    pub fn parse_header(&self) -> serde_yaml::Value {
26        let yaml: serde_yaml::Value = serde_yaml::from_str(&self.seperate_header().0)
27            .expect("Could not parse the yaml header");
28
29        yaml
30    }
31
32    pub fn parse_md(&self) -> String {
33        let md = self.seperate_header().1;
34        let parser = Parser::new_ext(&md, Options::all());
35
36        let mut html = String::new();
37
38        push_html(&mut html, parser);
39
40        html
41    }
42}