From e964ec8f74b644d66ca166a7524adcc3a82709c9 Mon Sep 17 00:00:00 2001 From: "Gabriel A. Giovanini" Date: Sat, 14 May 2022 19:56:06 +0200 Subject: feat: Move code to blog - Move most logic of the blog to blog.rs, making it easier to test. - Now the file contains the creation date of the blog post to be parsed. - Add chrono to parse datetime, so later we can order by date. - Refactor gitlab pipeline, move `before_script` to a proper place. --- src/blog.rs | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/blog.rs (limited to 'src/blog.rs') diff --git a/src/blog.rs b/src/blog.rs new file mode 100644 index 0000000..6c190a9 --- /dev/null +++ b/src/blog.rs @@ -0,0 +1,74 @@ +use rust_embed::RustEmbed; +use sailfish::TemplateOnce; +use chrono::NaiveDate; +use regex::{Regex}; +use std::str; + +const BLOG_REGEX: &str = r"(?P[\d]{4}-[\d]{2}-[\d]{2})(?P[a-zA-Z0-9_]*)"; + +#[derive(RustEmbed)] +#[folder = "content/posts/"] +struct PostAsset; + + +#[derive(TemplateOnce)] +#[template(path = "index.html")] +struct IndexTemplate { + posts: Vec<BlogEntry>, +} + +#[derive(TemplateOnce)] +#[template(path = "post.html")] +struct PostTemplate { + content: String, +} + +pub struct BlogEntry { + pub title: String, + pub datetime: NaiveDate, + pub file: String, +} + +impl BlogEntry { + pub fn new(path: &String) -> BlogEntry { + let re = Regex::new(BLOG_REGEX).unwrap(); + let caps = re.captures(path).unwrap(); + let date = &caps["date"]; + let title = str::replace(&caps["title"], "_", " "); + + BlogEntry { + title: String::from(title), + file: String::from(path), + datetime: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap() + } + } + + pub fn read_assets() -> Vec<BlogEntry> { + PostAsset::iter() + .map(|e| format!("{}", e)) + .map(|e| BlogEntry::new(&e)) + .collect() + } +} + +fn get_file_content(path: &str) -> String { + let buffer = PostAsset::get(path) + .unwrap() + .data + .into_owned(); + + return String::from_utf8(buffer).unwrap(); +} + + +pub fn render_post_page(path: &String) -> String { + PostTemplate { content: get_file_content(path) } + .render_once() + .unwrap() +} + +pub fn render_index_page() -> String { + IndexTemplate { posts: BlogEntry::read_assets() } + .render_once() + .unwrap() +} -- cgit v1.2.3