-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
322 lines (288 loc) · 7.87 KB
/
app.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
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
var fs = require('fs-extra');
var _ = require('lodash');
var less = require('less');
var mm = require('meta-marked');
var nunjucks = require('nunjucks');
var path = require('path');
var express = require('express');
var argv = require('boring')();
var server = argv['server'];
nunjucks.configure('_layouts', { autoescape: true });
if (fs.existsSync('_site'))
{
fs.removeSync('_site');
}
fs.mkdirSync('_site');
var filters = {
'less': lessFilter,
'md': markdownFilter
};
var map = {};
// Custom renderer for headings. We don't want to make a nasty
// named anchor based on parameters in parentheses. But we do
// need to make sure we don't output the same named anchor twice
// if there are multiple syntaxes. So differentiate with
// numbers if needed.
function newRenderer() {
var renderer = new mm.Renderer();
renderer.slugsSeen = {};
renderer.heading = function (text, level) {
var slug = text.replace(/\(.*/, '');
slug = cssName(slug);
slug = slug.replace(/\-+/g, '-');
slug = slug.replace(/^\-/, '');
slug = slug.replace(/\-$/, '');
if (renderer.slugsSeen[slug]) {
renderer.slugsSeen[slug]++;
slug += renderer.slugsSeen[slug];
} else {
renderer.slugsSeen[slug] = 1;
}
return '<h' + level + '><a name="' +
slug +
'" class="anchor" href="#' +
slug +
'"><span class="header-link"></span></a>' +
text + '</h' + level + '>';
};
return renderer;
}
var browser = require('findit')('.');
browser.on('directory', function(dir, stat, stop) {
if (ignored(dir)) {
return;
}
if (!fs.existsSync('_site/' + dir)) {
fs.mkdirSync('_site/' + dir);
}
});
browser.on('file', function(file, stat) {
// Ignore dotfiles and _ files
if (ignored(file)) {
return;
}
var matches = file.match(/\.(\w+)$/);
if (matches) {
extension = matches[1];
// If there is a filter for this type, invoke that instead of copying
if (_.has(filters, extension)) {
filters[extension](file);
return;
}
}
// Everything else is simply copied
writeToSite(file, fs.readFileSync(file));
});
browser.on('end', function() {
// Sort the filenames so that parent folders come first.
//
// Create an array of children and a pointer to the parent
// for each file.
//
// Set the "previous" and "next" properties of each page so
// it is possible to walk through the entire site in a
// depth-first traversal.
//
// Now we have metadata to build navigation.
var keys = _.keys(map);
keys.sort(function(a, b) {
// Make sure index.md sorts to the top
a = a.replace(/index\.md$/, '');
b = b.replace(/index\.md$/, '');
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
_.each(keys, function(key) {
var parent = getParentKey(key);
if (map[parent] && (parent !== key)) {
map[parent].naturalChildren = (map[parent].naturalChildren || []);
map[parent].naturalChildren.push(map[key]);
map[key].parent = map[parent];
}
});
_.each(keys, function(key) {
var file = map[key];
if (file.children) {
var actualChildren = [];
_.each(file.children, function(childShortName) {
var winner = _.find(file.naturalChildren, function(child) {
return (shortName(child.file) === childShortName);
});
if (!winner) {
throw new Error(key + ' lists ' + childShortName + ' as one of its children but it does not exist');
}
actualChildren.push(winner);
});
file.children = actualChildren;
}
file.ancestors = [];
var ancestor = file;
while (ancestor) {
file.ancestors.unshift(ancestor);
ancestor = ancestor.parent;
}
});
// Set up "previous" and "next" for each page so users can
// walk through the entire site in a depth first traversal,
// like reading through an outline
var home = keys[0];
var previous;
if (home) {
home = map[home];
depthFirst(home);
}
function depthFirst(current) {
current.previous = previous;
if (previous) {
previous.next = current;
}
previous = current;
_.each(current.children, function(child) {
depthFirst(child);
});
}
// The final rendering pass
_.each(map, function(info, file) {
try {
var rendered = nunjucks.render(info.layout + '.html', info);
} catch (e) {
console.error();
console.error('A nunjucks error occurred while processing ' + file + ':\n');
throw e;
}
var htmlFile = file.replace(/\.md$/, '.html');
writeToSite(htmlFile, rendered);
});
if (!server) {
// This should not be necessary, but when habit is run via a globally
// installed "bin" script, it does not exit on completion without this
// in node 0.12.7
process.exit(0);
}
if (server) {
var app = express();
app.use(express.static('_site'));
var port = process.env.PORT || '3000';
var address = process.env.ADDRESS || 'localhost';
server = app.listen(parseInt(port), address);
server.on('error', function(err) {
console.error(err);
process.exit(1);
});
server.on('listening', function() {
console.log('Listening for connections at http://' + address + ':' + port + '/');
});
}
});
function shortName(file) {
file = file.replace(/\/index\.md/, '');
return path.basename(file, '.md');
}
function getParentKey(key) {
key = key.replace(/\/index\.md$/, '');
if (key.match(/\//)) {
key = key.replace(/\/[^\/]+$/, '');
key += '/index.md';
return key;
} else {
return 'index.md';
}
}
function ignored(file) {
// Ignore dotfolders and _ folders, like _site and _layouts
if (file.match(/^(\.|_)/)) {
return true;
}
if (file.match(/\/(\.|_)/)) {
return true;
}
if (file.match(/^node_modules\/?(.*)$/)) {
return true;
}
return false;
}
function writeToSite(name, data)
{
fs.writeFileSync('_site/' + name, data);
}
// Filters for various extensions begin here
function lessFilter(file) {
if (!file.match(/main\.less$/)) {
// LESS files other than "main" are assumed to be imported
// by main so we should not try to compile or copy them separately
return;
}
// Although a callback is used, this is synchronous
less.render(fs.readFileSync(file, 'utf8'), {
filename: file,
paths: [path.dirname(file)],
syncImport: true
}, function(err, result) {
if (err) {
throw err;
}
writeToSite(file.replace(/\.less$/, '.css'), result.css);
});
}
function markdownFilter(file) {
var info;
try {
info = mm(fs.readFileSync(file, 'utf8'), { renderer: newRenderer() });
} catch (e) {
console.error('\nmarkdown error while processing ' + file);
throw e;
}
var meta = info.meta || {};
var html = info.html;
meta.layout = meta.layout || 'default';
var root = './';
var clauses = file.split('/');
var i;
for (i = 1; (i < clauses.length); i++) {
root += '../';
}
var data = meta;
data.content = new nunjucks.runtime.SafeString(info.html);
data.file = file;
data.root = root;
data.url = data.file.replace(/\.md/, '.html');
// Don't write it now; we'll make another pass after
// combining the metadata that builds our navigation
map[file] = data;
}
// Convert a string to look like a typical CSS
// class name, with hypens. Hi There becomes hi-there,
// hiThere also becomes hi-there, etc. Borrowed
// from Apostrophe.
function cssName(name) {
var i;
var css = '';
var dash = false;
for (i = 0; (i < name.length); i++) {
var c = name.charAt(i);
var lower = ((c >= 'a') && (c <= 'z'));
var upper = ((c >= 'A') && (c <= 'Z'));
var digit = ((c >= '0') && (c <= '9'));
if (!(lower || upper || digit)) {
dash = true;
continue;
}
if (upper) {
if (i > 0) {
dash = true;
}
c = c.toLowerCase();
}
if (dash) {
css += '-';
dash = false;
}
css += c;
}
return css;
}