This repository has been archived by the owner on Apr 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbuild-pdf.js
79 lines (73 loc) · 1.85 KB
/
build-pdf.js
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
/*
* # DEPENDENCIES #
*/
var Metalsmith = require('metalsmith')
var changed = require('metalsmith-changed')
var pdf = require('metalsmith-phantomjs-pdf')
var fs = require('fs');
var path = require('path');
// get configuration variables
var config = require('./config.js')
var ctimes = 'metalsmith-changed-ctimes-html.json';
/*
* # EXPORT #
* build-function which takes a callback
*/
module.exports = function build (callback) {
// do the building
Metalsmith(config.lessonRoot)
.source('build')
.clean(false) // do not delete any files
.use(onlyLessonHTML)
.use(changed({ ctimes: ctimes }))
.use(deleteOldPDF)
.use(pdf())
.use(onlyCtimes)
// build
.destination('build')
.build(callback)
}
/**
* PDF only for files ending in .html
*/
function onlyLessonHTML (files, _, done) {
Object.keys(files).forEach(function (file) {
// assume index.html are only course indexes
if (file.search(/\.html$/i) === -1 || file.search(/index\.html$/) !== -1) {
delete files[file];
}
});
done();
}
/**
* Delete old PDF files (not depending on phantomjs overwriting)
*/
function deleteOldPDF (files, metalsmith, done) {
Object.keys(files).forEach(function (file) {
if (file !== ctimes) {
var oldPDF = path.join(metalsmith.source(),
file.replace(/\.html$/i, '.pdf'));
try {
fs.unlinkSync(oldPDF);
} catch (err) {
if(err.code !== 'ENOENT'){
console.error('Unable to remove PDF: ' + oldPDF);
console.error(err);
}
}
}
});
done();
}
/**
* Remove HTML-files from build, such that they are not overwritten,
* as we are only reading them to get file URLs
*/
function onlyCtimes (files, _, done) {
Object.keys(files).forEach(function (file) {
if (file !== ctimes) {
delete files[file];
}
});
done();
}