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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use std::fs::{self, File};
use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use std::ffi::OsStr;
use liquid::Value;
use walkdir::{WalkDir, DirEntry, WalkDirIterator};
use document::Document;
use error::{ErrorKind, Result};
use config::Config;
use chrono::{UTC, FixedOffset};
use chrono::offset::TimeZone;
use rss::{Channel, Rss};
use glob::Pattern;
fn ignore_filter(entry: &DirEntry, source: &Path, ignore: &[Pattern]) -> bool {
if compare_paths(entry.path(), source) {
return true;
}
let path = entry.path().strip_prefix(&source).unwrap_or(entry.path());
let file_name = entry.file_name().to_str().unwrap_or("");
if file_name.starts_with('_') || file_name.starts_with('.') {
return false;
}
!ignore.iter().any(|p| p.matches_path(path))
}
fn compare_paths(a: &Path, b: &Path) -> bool {
match (fs::canonicalize(a), fs::canonicalize(b)) {
(Ok(p), Ok(p2)) => p == p2,
_ => false,
}
}
pub fn build(config: &Config) -> Result<()> {
trace!("Build configuration: {:?}", config);
let source = Path::new(&config.source);
let dest = Path::new(&config.dest);
let template_extensions: Vec<&OsStr> = config.template_extensions
.iter()
.map(OsStr::new)
.collect();
let layouts = source.join(&config.layouts);
let mut layouts_cache = HashMap::new();
let posts_path = source.join(&config.posts);
debug!("Layouts directory: {:?}", layouts);
debug!("Posts directory: {:?}", posts_path);
debug!("Draft mode enabled: {}", config.include_drafts);
if config.include_drafts {
debug!("Draft directory: {:?}", config.drafts);
}
let mut documents = vec![];
let walker = WalkDir::new(&source)
.into_iter()
.filter_entry(|e| {
(ignore_filter(e, source, &config.ignore) || compare_paths(e.path(), &posts_path)) &&
!compare_paths(e.path(), dest)
})
.filter_map(|e| e.ok());
for entry in walker {
let entry_path = entry.path();
let extension = &entry_path.extension().unwrap_or_else(|| OsStr::new(""));
if template_extensions.contains(extension) {
let is_post =
entry_path.parent().map(|p| compare_paths(p, &posts_path)).unwrap_or(false);
let new_path = entry_path.strip_prefix(source).expect("Entry not in source folder");
let doc = try!(Document::parse(&entry_path, new_path, is_post, &config.post_path));
if !doc.is_draft || config.include_drafts {
documents.push(doc);
}
}
}
if config.include_drafts {
let drafts = source.join(&config.drafts);
let walker = WalkDir::new(&drafts)
.into_iter()
.filter_entry(|e| {
(ignore_filter(e, source, &config.ignore) || compare_paths(e.path(), &drafts)) &&
!compare_paths(e.path(), dest)
})
.filter_map(|e| e.ok());
for entry in walker {
let entry_path = entry.path();
let extension = &entry_path.extension().unwrap_or_else(|| OsStr::new(""));
let new_path = posts_path
.join(entry_path.strip_prefix(&drafts).expect("Draft not in draft folder!"));
let new_path = new_path.strip_prefix(source).expect("Entry not in source folder");
if template_extensions.contains(extension) {
let doc = try!(Document::parse(&entry_path, new_path, true, &config.post_path));
documents.push(doc);
}
}
}
let default_date = UTC.timestamp(0, 0).with_timezone(&FixedOffset::east(0));
let (mut posts, documents): (Vec<Document>, Vec<Document>) = documents.into_iter()
.partition(|x| x.is_post);
posts.sort_by(|a, b| b.date.unwrap_or(default_date).cmp(&a.date.unwrap_or(default_date)));
let simple_posts_data: Vec<Value> = posts.iter()
.map(|x| Value::Object(x.attributes.clone()))
.collect();
trace!("Generating posts");
for mut post in &mut posts {
trace!("Generating {}", post.path);
let mut context = post.get_render_context(&simple_posts_data);
try!(post.render_excerpt(&mut context, &source, &config.excerpt_separator));
let post_html = try!(post.render(&mut context, &source, &layouts, &mut layouts_cache));
try!(create_document_file(&post_html, &post.path, dest));
}
if let Some(ref path) = config.rss {
try!(create_rss(path, dest, &config, &posts));
}
let posts_data: Vec<Value> = posts.into_iter()
.map(|x| Value::Object(x.attributes))
.collect();
trace!("Generating other documents");
for mut doc in documents {
trace!("Generating {}", doc.path);
let mut context = doc.get_render_context(&posts_data);
let doc_html = try!(doc.render(&mut context, &source, &layouts, &mut layouts_cache));
try!(create_document_file(&doc_html, &doc.path, dest));
}
if !compare_paths(source, dest) {
info!("Copying remaining assets");
let source_str = try!(source.to_str()
.ok_or(format!("Cannot convert pathname {:?} to UTF-8", source)));
let walker = WalkDir::new(&source)
.into_iter()
.filter_entry(|e| {
ignore_filter(e, source, &config.ignore) &&
!template_extensions.contains(&e.path()
.extension()
.unwrap_or_else(|| OsStr::new(""))) &&
!compare_paths(e.path(), dest)
})
.filter_map(|e| e.ok());
for entry in walker {
let entry_path = try!(entry.path()
.to_str()
.ok_or(format!("Cannot convert pathname {:?} to UTF-8", entry.path())));
let relative = try!(entry_path.split(source_str)
.last()
.map(|s| s.trim_left_matches("/"))
.ok_or("Empty path"));
if try!(entry.metadata()).is_dir() {
try!(fs::create_dir_all(&dest.join(relative)));
debug!("Created new directory {:?}", dest.join(relative));
} else {
if let Some(parent) = Path::new(relative).parent() {
try!(fs::create_dir_all(&dest.join(parent)));
}
try!(fs::copy(entry.path(), &dest.join(relative))
.map_err(|e| format!("Could not copy {:?}: {}", entry.path(), e)));
debug!("Copied {:?} to {:?}", entry.path(), dest.join(relative));
}
}
}
Ok(())
}
fn create_rss(path: &str, dest: &Path, config: &Config, posts: &[Document]) -> Result<()> {
match (&config.name, &config.description, &config.link) {
(&Some(ref name), &Some(ref description), &Some(ref link)) => {
trace!("Generating RSS data");
let items = posts.iter()
.map(|doc| doc.to_rss(link))
.collect();
let channel = Channel {
title: name.to_owned(),
link: link.to_owned(),
description: description.to_owned(),
items: items,
..Default::default()
};
let rss = Rss(channel);
let rss_string = rss.to_string();
trace!("RSS data: {}", rss_string);
let rss_path = dest.join(path);
let mut rss_file = try!(File::create(&rss_path));
try!(rss_file.write_all(&rss_string.into_bytes()));
info!("Created RSS file at {}", rss_path.display());
Ok(())
}
_ => Err(ErrorKind::ConfigFileMissingFields.into()),
}
}
fn create_document_file<T: AsRef<Path>, R: AsRef<Path>>(content: &str,
path: T,
dest: R)
-> Result<()> {
let file_path = dest.as_ref().join(path);
if let Some(parent) = file_path.parent() {
try!(fs::create_dir_all(parent)
.map_err(|e| format!("Could not create {:?}: {}", parent, e)));
}
let mut file = try!(File::create(&file_path)
.map_err(|e| format!("Could not create {:?}: {}", file_path, e)));
try!(file.write_all(&content.as_bytes()));
info!("Created {}", file_path.display());
Ok(())
}