]> git.r.bdr.sh - rbdr/blog/blob - src/command/generate.rs
Add tokenizer
[rbdr/blog] / src / command / generate.rs
1 use std::fs::{create_dir_all, read_dir, remove_dir_all, File};
2 use std::io::{Read, Result};
3 use std::path::PathBuf;
4 use crate::configuration::Configuration;
5 use crate::constants::METADATA_FILENAME;
6 use crate::gemini_parser::parse;
7 use crate::generator::generate;
8 use crate::metadata::Metadata;
9 use crate::post::Post;
10
11 pub struct Generate;
12
13 impl Generate {
14 pub fn new() -> Self {
15 Generate
16 }
17
18 fn read_posts(&self, posts_directory: &PathBuf, max_posts: u8) -> Vec<Post> {
19 let mut posts = Vec::new();
20
21 for i in 0..max_posts - 1 {
22 let post_directory = posts_directory.join(i.to_string());
23 match self.read_post(&post_directory, i) {
24 Some(post) => posts.push(post),
25 None => continue
26 }
27 }
28
29 posts
30 }
31
32 fn find_blog_content(&self, post_directory: &PathBuf) -> Option<String> {
33 let entries = read_dir(&post_directory).ok()?;
34 for entry in entries.filter_map(Result::ok) {
35 let entry_path = entry.path();
36 match entry_path.extension() {
37 Some(extension) => {
38 if extension == "gmi" {
39 let mut file = File::open(entry_path).ok()?;
40 let mut contents = String::new();
41 file.read_to_string(&mut contents).ok()?;
42 return Some(contents);
43 }
44 },
45 None => continue
46 }
47 }
48 None
49 }
50
51 fn read_post(&self, post_directory: &PathBuf, index: u8) -> Option<Post> {
52 let metadata_path = post_directory.join(METADATA_FILENAME);
53 let metadata = Metadata::read_or_create(&metadata_path);
54 let raw = self.find_blog_content(&post_directory)?;
55 let html = parse(&raw);
56
57 Some(Post {
58 metadata,
59 index,
60 html,
61 raw
62 })
63 }
64 }
65
66 impl super::Command for Generate {
67 fn before_dependencies(&self) -> Vec<Box<dyn super::Command>> {
68 vec![]
69 }
70
71 fn execute(&self, _: Option<&String>, configuration: &Configuration, _: &String) -> Result<()> {
72 let _ = remove_dir_all(&configuration.blog_output_directory);
73 create_dir_all(&configuration.blog_output_directory)?;
74
75 let posts = self.read_posts(&configuration.posts_directory, configuration.max_posts);
76 generate(
77 &configuration.static_directory,
78 &configuration.templates_directory,
79 &configuration.blog_output_directory,
80 &posts
81 )?;
82
83 let _ = remove_dir_all(&configuration.archive_output_directory);
84 create_dir_all(&configuration.archive_output_directory)?;
85 return Ok(())
86 }
87
88 fn after_dependencies(&self) -> Vec<Box<dyn super::Command>> {
89 vec![]
90 }
91
92 fn command(&self) -> &'static str {
93 "generate"
94 }
95
96 fn help(&self) -> &'static str {
97 "\t\t\t\tGenerates the blog assets"
98 }
99 }