detect mermaid diagram
Some checks are pending
ci/woodpecker/push/publish Pipeline is pending
ci/woodpecker/pr/publish Pipeline is pending

This commit is contained in:
Mylloon 2023-04-10 20:05:57 +02:00
parent 2215f3e4e8
commit 52df4bd9c3
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

View file

@ -22,7 +22,7 @@ enum FrontMatter<'a> {
} }
impl FrontMatter<'_> { impl FrontMatter<'_> {
fn parse(&self) -> Option<Metadata> { fn parse(&self) -> Metadata {
match self { match self {
Self::Yaml(val) => serde_yaml::from_str(val).unwrap_or_default(), Self::Yaml(val) => serde_yaml::from_str(val).unwrap_or_default(),
Self::Toml(_val) => todo!(), Self::Toml(_val) => todo!(),
@ -31,12 +31,13 @@ impl FrontMatter<'_> {
} }
} }
#[derive(Deserialize)] #[derive(Default, Deserialize)]
pub struct Metadata { pub struct Metadata {
pub title: Option<String>, pub title: Option<String>,
pub mermaid: bool,
} }
pub fn read_md(filename: &str) -> (Option<Metadata>, String) { pub fn read_md(filename: &str) -> (Metadata, String) {
// Read markdown file // Read markdown file
let mut text = std::fs::read_to_string(filename).unwrap(); let mut text = std::fs::read_to_string(filename).unwrap();
@ -59,11 +60,12 @@ pub fn read_md(filename: &str) -> (Option<Metadata>, String) {
}; };
let md_tree = markdown::to_mdast(&text, &parse_option).unwrap(); let md_tree = markdown::to_mdast(&text, &parse_option).unwrap();
let metadata = match &md_tree.children().unwrap()[0] { let md_nodes = md_tree.children().unwrap();
let metadata = match &md_nodes[0] {
markdown::mdast::Node::Yaml(v) => FrontMatter::Yaml(&v.value).parse(), markdown::mdast::Node::Yaml(v) => FrontMatter::Yaml(&v.value).parse(),
markdown::mdast::Node::Toml(v) => FrontMatter::Toml(&v.value).parse(), markdown::mdast::Node::Toml(v) => FrontMatter::Toml(&v.value).parse(),
markdown::mdast::Node::MdxjsEsm(v) => FrontMatter::Json(&v.value).parse(), markdown::mdast::Node::MdxjsEsm(v) => FrontMatter::Json(&v.value).parse(),
_ => None, _ => Metadata::default(),
}; };
// Convert to HTML // Convert to HTML
@ -76,5 +78,23 @@ pub fn read_md(filename: &str) -> (Option<Metadata>, String) {
) )
.unwrap(); .unwrap();
(metadata, html) // Find if document contains mermaid diagram
let presence_mermaid = md_nodes.iter().fold(false, |acc, x| {
if !acc {
match x {
markdown::mdast::Node::Code(code) => code.lang == Some(String::from("mermaid")),
_ => false,
}
} else {
false
}
});
(
Metadata {
mermaid: presence_mermaid,
..metadata
},
html,
)
} }