Skip to content

Commit

Permalink
Add helper method to construct a new Post instance from a dir path
Browse files Browse the repository at this point in the history
  • Loading branch information
tjk committed Nov 26, 2024
1 parent d25620d commit 6ce21db
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 17 deletions.
17 changes: 2 additions & 15 deletions src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl SiteGenerator {
println!("Output directory: {}", config.output_dir().display());
}

println!("{}", ACCENT_STYLE.apply_to("\nGenerating site..."));
println!("{}", Style::new().cyan().apply_to("\nGenerating site..."));

// Create output directory if it doesn't exist
fs::create_dir_all(config.output_dir())?;
Expand Down Expand Up @@ -60,20 +60,7 @@ impl SiteGenerator {
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map_or(false, |ext| ext == "md"))
{
let content = fs::read_to_string(entry.path())?;
let file_name = entry.path().display().to_string();

let doc: Document<PostMetadata> =
YamlFrontMatter::parse(&content).map_err(|e| Error::Frontmatter {
file: file_name,
message: e.to_string(),
})?;

posts.push(Post {
metadata: doc.metadata,
content: doc.content.clone(),
html_content: self.markdown.render(&doc.content),
});
posts.push(Post::new_from_path(entry.path(), &self.markdown)?);
}

Ok(posts)
Expand Down
22 changes: 20 additions & 2 deletions src/post.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use crate::config::Config;
use crate::errors::Error;
use crate::markdown::MarkdownProcessor;
use chrono::{Local, NaiveDate};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use yaml_front_matter::Document;
use yaml_front_matter::YamlFrontMatter;

#[derive(Debug, Serialize)]
pub struct Post {
Expand All @@ -13,6 +16,22 @@ pub struct Post {
}

impl Post {
pub fn new_from_path(path: &Path, md_proc: &MarkdownProcessor) -> Result<Self, Error> {
let content = fs::read_to_string(path)?;
let file_name = path.display().to_string();

let doc: Document<PostMetadata> =
YamlFrontMatter::parse(&content).map_err(|e| Error::Frontmatter {
file: file_name,
message: e.to_string(),
})?;

Ok(Self {
metadata: doc.metadata,
content: doc.content.clone(),
html_content: md_proc.render(&content),
})
}
// Get the assets directory for this post
pub fn assets_dir(&self, config: &Config) -> PathBuf {
config
Expand Down Expand Up @@ -56,7 +75,6 @@ impl Post {
);
}
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct PostMetadata {
pub title: String,
Expand Down

0 comments on commit 6ce21db

Please sign in to comment.