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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
extern crate base64;
extern crate md5;
#[macro_use]
extern crate nom;
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "sass")]
extern crate rsass;
mod spacelike;
mod expression;
#[macro_use]
mod errors;
#[macro_use]
mod templateexpression;
mod template;
pub mod Template_syntax;
use errors::get_error;
use nom::{ErrorKind, prepare_errors};
use nom::IResult::*;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{File, create_dir_all, read_dir};
use std::io::{self, Read, Write};
use std::path::Path;
use std::str::from_utf8;
use template::template;
pub fn compile_static_files(indir: &Path, outdir: &Path) -> io::Result<()> {
let mut out = StaticFiles::new(outdir)?;
out.add_files(indir)
}
pub struct StaticFiles {
src: File,
names: BTreeMap<String, String>,
statics: BTreeSet<String>,
}
impl StaticFiles {
pub fn new(outdir: &Path) -> io::Result<Self> {
let outdir = outdir.join("templates");
try!(create_dir_all(&outdir));
let mut src = File::create(outdir.join("statics.rs"))?;
write!(src,
"{}\n",
include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/src/statics_utils.rs")))?;
Ok(StaticFiles {
src: src,
names: BTreeMap::new(),
statics: BTreeSet::new(),
})
}
pub fn add_files(&mut self, indir: &Path) -> io::Result<()> {
for entry in read_dir(indir)? {
let entry = entry?;
if entry.file_type()?.is_file() {
self.add_file(&entry.path())?;
}
}
Ok(())
}
pub fn add_file(&mut self, path: &Path) -> io::Result<()> {
if let Some((name, ext)) = name_and_ext(path) {
println!("cargo:rerun-if-changed={}", path.to_string_lossy());
let mut input = File::open(&path)?;
let mut buf = Vec::new();
input.read_to_end(&mut buf)?;
let from_name = format!("{}_{}", name, ext);
let to_name = format!("{}-{}.{}", name, checksum_slug(&buf), &ext);
self.write_static_file(path, name, &buf, ext)?;
self.names.insert(from_name.clone(), to_name);
self.statics.insert(from_name);
}
Ok(())
}
pub fn add_file_data(&mut self,
path: &Path,
data: &[u8])
-> io::Result<()> {
if let Some((name, ext)) = name_and_ext(path) {
let from_name = format!("{}_{}", name, ext);
let to_name = format!("{}-{}.{}", name, checksum_slug(&data), &ext);
self.write_static_file(&path, name, &data, &ext)?;
self.names.insert(from_name.clone(), to_name);
self.statics.insert(from_name);
}
Ok(())
}
#[cfg(feature = "sass")]
pub fn add_sass_file(&mut self, src: &Path) -> io::Result<()> {
use rsass::*;
use std::sync::Arc;
let mut scope = GlobalScope::new();
println!("cargo:rerun-if-changed={}", src.to_string_lossy());
let existing_statics = Arc::new(self.get_names().clone());
scope.define_function("static_name",
SassFunction::builtin(vec![("name".into(),
Value::Null)],
false,
Arc::new(move |s| {
match s.get("name") {
Value::Literal(name, _) => {
let name = name.replace('-', "_").replace('.', "_");
for (n, v) in existing_statics.as_ref() {
if name == *n {
return Ok(Value::Literal(v.clone(),
Quotes::Double));
}
}
Err(Error::S(format!("Static file {} not found", name)))
}
name => Err(Error::badarg("string", &name)),
}
})));
let scss = parse_scss_file(src).unwrap();
let style = OutputStyle::Compressed;
let file_context = FileContext::new();
let css = style.write_root(&scss, &mut scope, file_context).unwrap();
self.add_file_data(&src.with_extension("css"), &css)
}
fn write_static_file(&mut self,
path: &Path,
name: &str,
content: &[u8],
suffix: &str)
-> io::Result<()> {
write!(self.src,
"\n/// From {path:?}\n\
#[allow(non_upper_case_globals)]\n\
pub static {name}_{suf}: StaticFile = \
StaticFile {{\n \
content: &{content:?},\n \
name: \"{name}-{hash}.{suf}\",\n\
}};\n",
path = path,
name = name,
content = content,
hash = checksum_slug(&content),
suf = suffix)
}
pub fn get_names(&self) -> &BTreeMap<String, String> {
&self.names
}
}
impl Drop for StaticFiles {
fn drop(&mut self) {
let _ = write!(self.src,
"\npub static STATICS: &'static [&'static StaticFile] \
= &[{}];\n",
self.statics
.iter()
.map(|s| format!("&{}", s))
.collect::<Vec<_>>()
.join(", "));
}
}
fn name_and_ext(path: &Path) -> Option<(&str, &str)> {
if let (Some(name), Some(ext)) = (path.file_name(), path.extension()) {
if let (Some(name), Some(ext)) = (name.to_str(), ext.to_str()) {
return Some((&name[..name.len() - ext.len() - 1], ext));
}
}
None
}
fn checksum_slug(data: &[u8]) -> String {
base64::encode_mode(&md5::compute(data)[..6], base64::Base64Mode::UrlSafe)
}
pub fn compile_templates(indir: &Path, outdir: &Path) -> io::Result<()> {
File::create(outdir.join("templates.rs")).and_then(|mut f| {
try!(write!(f,
"pub mod templates {{\n\
use std::io::{{self, Write}};\n\
use std::fmt::Display;\n\n"));
let outdir = outdir.join("templates");
try!(create_dir_all(&outdir));
try!(handle_entries(&mut f, indir, &outdir));
if outdir.join("statics.rs").exists() {
try!(write!(f, "pub mod statics;\n"));
}
write!(f,
"{}\n}}\n",
include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/src/template_utils.rs")))
})
}
fn handle_entries(f: &mut Write,
indir: &Path,
outdir: &Path)
-> io::Result<()> {
println!("cargo:rerun-if-changed={}", indir.to_string_lossy());
let suffix = ".rs.html";
for entry in try!(read_dir(indir)) {
let entry = try!(entry);
let path = entry.path();
if try!(entry.file_type()).is_dir() {
if let Some(filename) = entry.file_name().to_str() {
let outdir = outdir.join(filename);
try!(create_dir_all(&outdir));
try!(File::create(outdir.join("mod.rs"))
.and_then(|mut f| handle_entries(&mut f, &path, &outdir)));
try!(write!(f, "pub mod {name};\n\n", name = filename));
}
} else if let Some(filename) = entry.file_name().to_str() {
if filename.ends_with(suffix) {
println!("cargo:rerun-if-changed={}", path.to_string_lossy());
let name = &filename[..filename.len() - suffix.len()];
if try!(handle_template(name, &path, &outdir)) {
try!(write!(f,
"mod template_{name};\npub use \
self::template_{name}\
::{name};\n\n",
name = name));
}
}
}
}
Ok(())
}
fn handle_template(name: &str, path: &Path, outdir: &Path) -> io::Result<bool> {
let mut input = try!(File::open(path));
let mut buf = Vec::new();
try!(input.read_to_end(&mut buf));
match template(&buf) {
Done(_, t) => {
let fname = outdir.join(format!("template_{}.rs", name));
File::create(fname).and_then(|mut f| t.write_rust(&mut f, name))?;
Ok(true)
}
result => {
println!("cargo:warning=\
Template parse error in {:?}:",
path);
show_errors(&mut io::stdout(), &buf, result, "cargo:warning=");
Ok(false)
}
}
}
fn show_errors<E>(out: &mut Write,
buf: &[u8],
result: nom::IResult<&[u8], E>,
prefix: &str) {
if let Some(errors) = prepare_errors(buf, result) {
for &(ref kind, ref from, ref _to) in &errors {
show_error(out, buf, *from, &get_message(kind), prefix);
}
}
}
fn get_message(err: &ErrorKind) -> String {
match err {
&ErrorKind::Custom(n) => {
match get_error(n) {
Some(msg) => msg,
None => format!("Unknown error #{}", n),
}
}
err => format!("{:?}", err),
}
}
fn show_error(out: &mut Write,
buf: &[u8],
pos: usize,
msg: &str,
prefix: &str) {
let mut line_start = buf[0..pos].rsplitn(2, |c| *c == b'\n');
let _ = line_start.next();
let line_start =
line_start.next().map(|bytes| bytes.len() + 1).unwrap_or(0);
let line = buf[line_start..]
.splitn(2, |c| *c == b'\n')
.next()
.and_then(|s| from_utf8(s).ok())
.unwrap_or("(Failed to display line)");
let line_no = what_line(buf, line_start);
let pos_in_line =
from_utf8(&buf[line_start..pos]).unwrap().chars().count() + 1;
writeln!(out,
"{prefix}{:>4}:{}\n\
{prefix} {:>pos$} {}",
line_no,
line,
"^",
msg,
pos = pos_in_line,
prefix = prefix)
.unwrap();
}
fn what_line(buf: &[u8], pos: usize) -> usize {
1 + buf[0..pos].iter().filter(|c| **c == b'\n').count()
}
pub mod templates {
use std::fmt::Display;
use std::io::{self, Write};
include!("template_utils.rs");
pub mod statics {
include!("statics_utils.rs");
pub static STATICS: &'static [&'static StaticFile] = &[];
}
#[test]
fn encoded() {
let mut buf = Vec::new();
"a < b".to_html(&mut buf).unwrap();
assert_eq!(b"a < b", &buf[..]);
}
#[test]
fn raw_html() {
let mut buf = Vec::new();
Html("a<b>c</b>").to_html(&mut buf).unwrap();
assert_eq!(b"a<b>c</b>", &buf[..]);
}
}