use markdown::{to_html_with_options, CompileOptions, Options};
use regex::Regex;
use std::collections::HashMap;
use std::{env, fs::read_to_string};
use tera::{Tera, Context};
fn main() {
let args: Vec = env::args().collect();
if args.len() < 2 {
panic!("Please provide md file");
}
let mut markdown = read_to_string(args.get(1).unwrap()).expect("File does not exist");
let mut tera = Tera::new("templates/*").unwrap();
tera.autoescape_on(vec![]);
let re_key_value = Regex::new(r"(?ms)---(.*)---(?:\n)").unwrap();
let binding_markdown = markdown.clone();
let key_value_string = re_key_value
.find(binding_markdown.as_str())
.expect("Can't find key value map in markdown");
markdown = re_key_value
.replace(markdown.clone().as_str(), "")
.to_string();
let mut key_value: HashMap<&str, &str> = HashMap::new();
for line in key_value_string.as_str().lines() {
if line == "---" {
continue;
}
key_value.insert(
line.split(":")
.collect::>()
.get(0)
.unwrap()
.trim(),
line.split(":")
.collect::>()
.get(1)
.unwrap()
.trim(),
);
}
let html_markdown = to_html_with_options(
&markdown,
&Options {
compile: CompileOptions {
allow_dangerous_html: true,
allow_dangerous_protocol: true,
..CompileOptions::default()
},
..Options::default()
},
)
.unwrap();
key_value.insert("blog_content", &html_markdown);
let context = Context::from_serialize(key_value).unwrap();
let output = tera.render("blog.html", &context).unwrap();
println!("{output}");
}