1use rust_embed::RustEmbed;
2use sailfish::TemplateOnce;
3use chrono::NaiveDate;
4use regex::{Regex};
5use std::str;
6
7const BLOG_REGEX: &str = r"(?P<date>[\d]{4}-[\d]{2}-[\d]{2})(?P<title>[a-zA-Z0-9_]*)";
8
9#[derive(RustEmbed)]
10#[folder = "content/posts/"]
11struct PostAsset;
12
13
14#[derive(TemplateOnce)]
15#[template(path = "index.html")]
16struct IndexTemplate {
17 posts: Vec<BlogEntry>,
18}
19
20#[derive(TemplateOnce)]
21#[template(path = "post.html")]
22struct PostTemplate {
23 content: String,
24 title: String,
25 date: String
26}
27
28pub struct BlogEntry {
29 pub title: String,
30 pub datetime: NaiveDate,
31 pub file: String,
32}
33
34impl BlogEntry {
35 pub fn new(path: &String) -> BlogEntry {
36 let re = Regex::new(BLOG_REGEX).unwrap();
37 let caps = re.captures(path).unwrap();
38 let date = &caps["date"];
39 let title = str::replace(&caps["title"], "_", " ");
40
41 BlogEntry {
42 title: String::from(title),
43 file: String::from(path),
44 datetime: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap()
45 }
46 }
47
48 pub fn read_assets() -> Vec<BlogEntry> {
49 PostAsset::iter()
50 .map(|e| format!("{}", e))
51 .map(|e| BlogEntry::new(&e))
52 .collect()
53 }
54}
55
56fn get_file_content(path: &str) -> String {
57 let buffer = PostAsset::get(path)
58 .unwrap()
59 .data
60 .into_owned();
61
62 return String::from_utf8(buffer).unwrap();
63}
64
65
66pub fn render_post_page(path: &String) -> String {
67 let blog = BlogEntry::new(path);
68
69 PostTemplate {
70 content: get_file_content(path),
71 title: blog.title,
72 date: blog.datetime.format("%Y-%m-%d").to_string()
73 }
74 .render_once()
75 .unwrap()
76}
77
78pub fn render_index_page() -> String {
79 IndexTemplate { posts: BlogEntry::read_assets() }
80 .render_once()
81 .unwrap()
82}