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