use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Local};
use log::debug;
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
use crate::utils::markdown_to_html;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostHeaders {
pub created: Option<DateTime<Local>>,
#[serde(default)]
pub hidden: bool,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub description: String,
#[serde(default)]
pub title: String,
}
#[derive(Serialize)]
pub struct Post {
root: PathBuf,
pub path: PathBuf,
pub title: String,
pub url: PathBuf,
pub headers: PostHeaders,
pub content: String,
}
impl Post {
pub fn new<P: AsRef<Path>>(root: P, path: P) -> Result<Post> {
let root = root.as_ref();
let path = path.as_ref();
debug!("loading post: {}", path.display());
let fp = root.join(&path);
let mut fo = File::open(fp)?;
let mut content = String::new();
fo.read_to_string(&mut content)?;
let v: Vec<&str> = content.splitn(2, "\n\n").collect();
if v.len() != 2 {
return Err(Error::PostOnlyOnePart(path.into()));
}
let head = v[0].trim();
let body = v[1].trim();
if head.is_empty() {
return Err(Error::PostNoHead(path.into()));
}
if head.is_empty() {
return Err(Error::PostNoBody(path.into()));
}
let title = path
.file_stem()
.and_then(|x| x.to_str())
.expect(&format!("post filename format error: {}", path.display()));
let url = Path::new("/").join(path).with_extension("html");
let mut headers: PostHeaders = toml::from_str(head)?;
if headers.description.is_empty() {
let desc = body
.split("\n\n")
.take(1)
.next()
.unwrap_or("")
.split_whitespace()
.take(100)
.collect::<Vec<_>>()
.join(" ");
headers.description.push_str(&desc);
if !headers.description.is_empty() {
headers.description.push_str("...");
}
}
let content = markdown_to_html(body);
Ok(Post {
root: root.to_owned(),
path: path.to_owned(),
title: if headers.title.is_empty() {
title.to_owned()
} else {
headers.title.clone()
},
url,
headers,
content,
})
}
pub fn src(&self) -> PathBuf {
self.root.join(&self.path)
}
pub fn dest(&self) -> PathBuf {
self.path.with_extension("html")
}
}