1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::error::Error as StdError;
use chrono::{DateTime, Local, TimeZone};
use pulldown_cmark::{html, Options, Parser, OPTION_ENABLE_TABLES};
use serde_json::{Map, Value};
use errors::{Error, Result};
pub struct Post {
root: PathBuf,
pub path: PathBuf,
head: String,
body: String,
metadata: HashMap<String, String>,
}
impl Post {
pub fn new<P: AsRef<Path>>(root: P, path: P) -> Post {
Post {
root: root.as_ref().to_owned(),
path: path.as_ref().to_owned(),
head: String::new(),
body: String::new(),
metadata: HashMap::new(),
}
}
pub fn src(&self) -> PathBuf {
self.root.join(&self.path)
}
pub fn dest(&self) -> PathBuf {
self.root
.join("_builds/blog")
.join(self.path.with_extension("html"))
}
pub fn title(&self) -> &str {
self.path
.file_stem()
.and_then(|x| x.to_str())
.expect(&format!("post filename format error: {}", self.path.display()))
}
pub fn datetime(&self) -> DateTime<Local> {
let date_value = self.metadata
.get("date")
.expect(&format!("post({}) require date header",
&self.path.display()));
match Local.datetime_from_str(&date_value, "%Y-%m-%d %H:%M:%S") {
Ok(datetime) => datetime,
Err(why) => panic!("post({}) date header parse error: {}",
&self.path.display(),
why.description()),
}
}
pub fn is_hidden(&self) -> bool {
let hidden_value = self.metadata
.get("hidden")
.unwrap_or(&"false".to_string())
.to_lowercase();
match hidden_value.as_ref() {
"true" | "t" => true,
_ => false,
}
}
pub fn url(&self) -> PathBuf {
Path::new("/blog").join(&self.path).with_extension("html")
}
pub fn content(&self) -> String {
let mut opts = Options::empty();
opts.insert(OPTION_ENABLE_TABLES);
let mut s = String::with_capacity(self.body.len() * 3 / 2);
let p = Parser::new_ext(&self.body, opts);
html::push_html(&mut s, p);
s
}
pub fn tags(&self) -> Vec<&str> {
if let Some(tag_str) = self.metadata.get("tags") {
let mut res = tag_str.split(',')
.map(|x| x.trim())
.filter(|x| x.len() != 0)
.collect::<Vec<&str>>();
res.sort();
res
} else {
Vec::new()
}
}
pub fn map(&self) -> Map<String, Value> {
let mut map = Map::new();
map.insert("title".to_string(), Value::String(self.title().to_string()));
map.insert("url".to_string(),
Value::String(format!("{}", self.url().display())));
map.insert("datetime".to_string(),
Value::String(self.datetime().format("%Y-%m-%d").to_string()));
map
}
pub fn load(&mut self) -> Result<()> {
debug!("loading post: {}", self.path.display());
let mut pf = File::open(self.src())?;
let mut content = String::new();
pf.read_to_string(&mut content)?;
let v: Vec<&str> = content.splitn(2, "\n\n").collect();
if v.len() != 2 {
return Err(Error::PostNoBody(self.path.clone()));
}
if v[0].trim().is_empty() {
return Err(Error::PostHead(self.path.clone()));
}
if v[1].trim().is_empty() {
return Err(Error::PostNoBody(self.path.clone()));
}
self.head = v[0].to_string();
self.body = v[1].to_string();
for line in self.head.lines() {
let pair: Vec<&str> = line.splitn(2, ':').collect();
if pair.len() != 2 {
return Err(Error::PostHead(self.path.clone()));
}
self.metadata.insert(pair[0].trim().to_owned(), pair[1].trim().to_owned());
}
Ok(())
}
}