X-Git-Url: https://git.r.bdr.sh/rbdr/blog/blobdiff_plain/2f579cf4c0d8ff95af78103783c7ca8f951cc797..refs/heads/rust:/src/command/generate.rs?ds=sidebyside diff --git a/src/command/generate.rs b/src/command/generate.rs index 59babd5..c8c5673 100644 --- a/src/command/generate.rs +++ b/src/command/generate.rs @@ -1,4 +1,12 @@ -use std::io::Result; +use std::fs::{create_dir_all, read_dir, remove_dir_all, File}; +use std::io::{Read, Result}; +use std::path::PathBuf; +use crate::configuration::Configuration; +use crate::constants::METADATA_FILENAME; +use crate::gemini_parser::parse; +use crate::generator::generate; +use crate::metadata::Metadata; +use crate::post::Post; pub struct Generate; @@ -6,6 +14,53 @@ impl Generate { pub fn new() -> Self { Generate } + + fn read_posts(&self, posts_directory: &PathBuf, max_posts: u8) -> Vec { + let mut posts = Vec::new(); + + for i in 0..max_posts - 1 { + let post_directory = posts_directory.join(i.to_string()); + match self.read_post(&post_directory, i) { + Some(post) => posts.push(post), + None => continue + } + } + + posts + } + + fn find_blog_content(&self, post_directory: &PathBuf) -> Option { + let entries = read_dir(&post_directory).ok()?; + for entry in entries.filter_map(Result::ok) { + let entry_path = entry.path(); + match entry_path.extension() { + Some(extension) => { + if extension == "gmi" { + let mut file = File::open(entry_path).ok()?; + let mut contents = String::new(); + file.read_to_string(&mut contents).ok()?; + return Some(contents); + } + }, + None => continue + } + } + None + } + + fn read_post(&self, post_directory: &PathBuf, index: u8) -> Option { + let metadata_path = post_directory.join(METADATA_FILENAME); + let metadata = Metadata::read_or_create(&metadata_path); + let raw = self.find_blog_content(&post_directory)?; + let html = parse(&raw); + + Some(Post { + metadata, + index, + html, + raw + }) + } } impl super::Command for Generate { @@ -13,8 +68,20 @@ impl super::Command for Generate { vec![] } - fn execute(&self, input: Option<&String>) -> Result<()> { - println!("GENERATE! {:?}", input); + fn execute(&self, _: Option<&String>, configuration: &Configuration, _: &String) -> Result<()> { + let _ = remove_dir_all(&configuration.blog_output_directory); + create_dir_all(&configuration.blog_output_directory)?; + + let posts = self.read_posts(&configuration.posts_directory, configuration.max_posts); + generate( + &configuration.static_directory, + &configuration.templates_directory, + &configuration.blog_output_directory, + &posts + )?; + + let _ = remove_dir_all(&configuration.archive_output_directory); + create_dir_all(&configuration.archive_output_directory)?; return Ok(()) }