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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// Copyright (C) 2015 Steven Allen
//
// This file is part of gazetta.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation version 3 of the
// License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program. If
// not, see <http://www.gnu.org/licenses/>.
//
use std::fs::{self, File};
use std::io::{self, BufWriter};
use std::path::Path;
use horrorshow::prelude::*;
use horrorshow::{html, xml};
use std::collections::hash_map::DefaultHasher;
use str_stack::StrStack;
use crate::error::{AnnotatedError, RenderError};
use crate::model::{IndexedSource, Meta};
use crate::util::{self, StreamHasher};
use crate::view::{BasePage, Context, Index, Page, Paginate, Site};
/// Compiles a set of files into a single asset by concatinating them. This
/// function also hashes the files so they can be cached.
fn compile_asset<P>(
paths: &[P],
target: &Path,
prefix: &str,
ext: &str,
) -> Result<String, AnnotatedError<io::Error>>
where
P: AsRef<Path>,
{
let mut tmp_path = target.join("assets");
tmp_path.push(prefix);
tmp_path.set_extension(ext);
let hash = {
let output = try_annotate!(File::create(&tmp_path), tmp_path);
let mut output = StreamHasher::<_, DefaultHasher>::new(output);
util::concat(paths, &mut output)?;
output.finish()
};
let href = format!("assets/{prefix}-{hash:x}.{ext}");
let final_path = target.join(&href);
try_annotate!(fs::rename(tmp_path, &final_path), final_path);
Ok(href)
}
pub trait Gazetta: Sized {
type SiteMeta: Meta;
type PageMeta: Meta;
/// The page rendering function.
fn render_page(&self, context: &Context<Self>, tmpl: &mut TemplateBuffer);
/// Render static content.
///
/// By default, this just copies. Override to compile.
#[allow(unused_variables)]
fn render_static(&self, site: &Site<Self>, source: &Path, output: &Path) -> io::Result<()> {
util::copy_recursive(source, output)
}
/// Render any additional feed "head" elements (usually author information, etc.). All the
/// necessary fields (title, id, updated, link, etc.) will already have been included.
#[allow(unused_variables)]
fn render_feed_head(&self, context: &Context<Self>, tmpl: &mut TemplateBuffer) {}
/// Render a page for syndication as a feed entry. By default, only the page summary
/// (description) is included in the feed but this method can be overridden to include
/// additional elements such as authorship information, the feed content, etc.
#[allow(unused_variables)]
fn render_feed_entry(&self, context: &Context<Self>, tmpl: &mut TemplateBuffer) {}
/// Render the feed for a page. In general, you'll want to override
/// [`Gazetta::render_feed_entry`] and [`Gazetta::render_feed_head`], not this method, unless
/// you want to override how the entire feed is rendered.
fn render_feed(&self, context: &Context<Self>, tmpl: &mut TemplateBuffer) {
let Some(index) = context.page.index else {
return;
};
let Some(feed_url) = index.feed else { return };
tmpl << xml! {
feed(xmlns="http://www.w3.org/2005/Atom", xml:base=context.site.base()) {
id : context.canonical_url();
title : &context.page.title;
link(href = context.canonical_url());
link(rel = "self", href = feed_url);
updated : context.page.updated.to_rfc3339();
@ if let Some(icon) = &context.site.icon {
icon : icon;
}
|tmpl| self.render_feed_head(context, tmpl);
@ for pctx in index.entries.iter().map(|page| Context{site: context.site, page}) {
entry {
id : pctx.canonical_url();
title : &pctx.page.title;
link(href = pctx.canonical_url(), rel="alternate");
updated : pctx.page.updated.to_rfc3339();
@ if let Some(date) = pctx.page.date {
published : date.to_rfc3339();
}
@ if let Some(summary) = pctx.page.description {
summary(type="text") : summary;
}
|tmpl| self.render_feed_entry(&pctx, tmpl);
}
}
}
}
}
/// Creates pages from a site defined by a source and renders them into output.
///
/// Call this to render your site.
///
/// Note: You *can* override this but you **really** shouldn't. This function contains pretty
/// much all of the provided render logic.
fn render<P: AsRef<Path>>(
&self,
source: &IndexedSource<Self::SiteMeta, Self::PageMeta>,
output: P,
) -> Result<(), AnnotatedError<RenderError>> {
let output = output.as_ref();
{
let assets_path = output.join("assets");
try_annotate!(fs::create_dir_all(&assets_path), assets_path);
}
let js_href = if !source.javascript.is_empty() {
Some(compile_asset(&source.javascript, output, "main", "js")?)
} else {
None
};
let css_href = if !source.stylesheets.is_empty() {
Some(compile_asset(&source.stylesheets, output, "main", "css")?)
} else {
None
};
let icon_href = if let Some(ref icon) = source.icon {
Some(compile_asset(&[&icon], output, "icon", "png")?)
} else {
None
};
if let Some(ref src) = source.well_known {
let dst = output.join(".well-known");
try_annotate!(util::copy_recursive(src, &dst), src)
}
let site = Site {
title: &source.title,
origin: &source.origin,
prefix: &source.prefix,
meta: &source.meta,
javascript: js_href.as_ref().map(|s| &s[..]),
stylesheets: css_href.as_ref().map(|s| &s[..]),
icon: icon_href.as_ref().map(|s| &s[..]),
};
for static_entry in &source.static_entries {
let dst = output.join(&static_entry.name);
if let Some(parent) = dst.parent() {
try_annotate!(fs::create_dir_all(parent), parent);
}
try_annotate!(
self.render_static(&site, &static_entry.source, &dst),
static_entry.source.clone()
);
}
for entry in &source.entries {
let dest_dir = output.join(&entry.name);
try_annotate!(fs::create_dir_all(&dest_dir), dest_dir);
let references: Vec<_> = source
.references(&entry.name)
.iter()
.copied()
.map(BasePage::for_entry)
.collect();
let page = Page {
base: BasePage::for_entry(entry),
references: &references,
index: None,
};
if let Some(ref index) = entry.index {
let child_entries = source.children(&entry.name);
let grandchildren: Vec<_> = child_entries
.iter()
.flat_map(|e| source.references(&e.name))
.copied()
.map(BasePage::for_entry)
.collect();
let mut remaining_grandchildren = &*grandchildren;
let children: Vec<_> = child_entries
.iter()
.copied()
.map(|e| {
let refs;
(refs, remaining_grandchildren) =
remaining_grandchildren.split_at(e.cc.len());
Page {
base: BasePage::for_entry(e),
references: refs,
index: None,
}
})
.collect();
let feed_path = if let Some(syndicate) = &index.syndicate {
let mut atom_file_path = dest_dir.clone();
atom_file_path.push("atom.xml");
let atom_file = try_annotate!(File::create(&atom_file_path), atom_file_path);
let to_syndicate = syndicate
.max
.map(|m| &children[..m as usize])
.unwrap_or(&children);
let feed_path = format!("{}/atom.xml", page.href);
try_annotate!(
xml! {
: Raw("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
|tmpl| self.render_feed(&Context{
site: &site,
page: &Page {
index: Some(Index {
compact: index.compact,
paginate: None,
feed: Some(&feed_path),
entries: to_syndicate,
}),
..page
},
}, tmpl);
}
.write_to_io(&mut BufWriter::new(atom_file)),
atom_file_path
);
Some(feed_path)
} else {
None
};
if let Some(paginate) = index.paginate {
// TODO: Assert that these casts are correct!
let paginate = paginate as usize;
let num_pages = (children.len() / paginate)
+ if children.len() % paginate == 0 { 0 } else { 1 };
if num_pages == 0 {
let mut index_file_path = dest_dir;
index_file_path.push("index.html");
let index_file =
try_annotate!(File::create(&index_file_path), index_file_path);
try_annotate!(
html! {
|tmpl| self.render_page(&Context{
site: &site,
page: &Page {
index: Some(Index {
compact: index.compact,
paginate: Some(Paginate {
pages: &[page.href],
current: 0,
}),
feed: feed_path.as_deref(),
entries: &[],
}),
..page
},
}, tmpl);
}
.write_to_io(&mut BufWriter::new(index_file)),
index_file_path
);
} else {
let mut page_stack = StrStack::with_capacity(
(num_pages - 1) * (entry.name.len() + 10),
num_pages,
);
for page_num in 1..num_pages {
let _ = write!(page_stack, "{}/index/{}", &entry.name, page_num);
}
let mut pages = Vec::with_capacity(num_pages);
pages.push(&*entry.name);
pages.extend(&page_stack);
for (page_num, (children_range, href)) in
children.chunks(paginate).zip(&pages).enumerate()
{
let mut index_file_path = output.join(href);
try_annotate!(fs::create_dir_all(&index_file_path), index_file_path);
index_file_path.push("index.html");
let index_file =
try_annotate!(File::create(&index_file_path), index_file_path);
try_annotate!(
html! {
|tmpl| self.render_page(&Context{
site: &site,
page: &Page {
index: Some(Index {
feed: feed_path.as_deref(),
compact: index.compact,
paginate: Some(Paginate {
pages: &pages,
current: page_num,
}),
entries: children_range,
}),
base: BasePage {
href,
..page.base
},
..page
},
}, tmpl);
}
.write_to_io(&mut BufWriter::new(index_file)),
index_file_path
);
}
}
} else {
let mut index_file_path = dest_dir;
index_file_path.push("index.html");
let index_file = try_annotate!(File::create(&index_file_path), index_file_path);
try_annotate!(
html! {
|tmpl| self.render_page(&Context {
site: &site,
page: &Page {
index: Some(Index {
feed: feed_path.as_deref(),
compact: index.compact,
paginate: None,
entries: &children[..],
}),
..page
},
}, tmpl);
}
.write_to_io(&mut BufWriter::new(index_file)),
index_file_path
);
}
} else {
let mut index_file_path = dest_dir;
index_file_path.push("index.html");
let index_file = try_annotate!(File::create(&index_file_path), index_file_path);
try_annotate!(
html! {
|tmpl| self.render_page(&Context{
site: &site,
page: &page,
}, tmpl);
}
.write_to_io(&mut BufWriter::new(index_file)),
index_file_path
);
}
}
Ok(())
}
}