-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·644 lines (548 loc) · 22.8 KB
/
index.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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
var _ = require('lodash');
var Q = require('q');
var frontMatter = require("front-matter");
var path = require("path");
var fs = require("fs-extra");
var parsers = require('gitbook-parsers');
var extend = require('extend');
var cheerio = require('cheerio');
var domSerializer = require('dom-serializer');
var url = require('url');
var strftime = require('strftime');
var sprintf = require('sprintf-js').sprintf;
var jimp = require("jimp");
var highlight = require("highlight.js");
// Skanktastic
var generators = require(path.join(path.dirname(require.resolve("gitbook")), "generators"));
var gitbookfs = require(path.join(path.dirname(require.resolve("gitbook")), "utils/fs"));
function blogStructure(book, files) {
var options = book ? book.options.pluginsConfig.plasma : {
tags: {},
categories: {},
title: "",
author: {},
server: "",
feeds: {}
}
var blog = {
// Index of pages by path
pages: {
},
taxonomy: {
// Index of tags (by name)
tags: {
},
// Index of categories (by slug)
categories: {
}
},
site: {
author: options.author,
title: options.title,
server: options.server
},
feeds: _.clone(options.feeds)
}
var tagDefaults = options.tags;
var catDefaults = options.categories;
_.each(files, function(f) {
if (_.includes(parsers.extensions, path.extname(f))) {
var pagePublishPath = path.dirname(contentPath(f));
var pathComponents = pagePublishPath.split(path.sep);
var catPath = pathComponents.slice(0, pathComponents.length - 1).join(path.sep);
var catName = path.basename(catPath);
var pageName = pathComponents[pathComponents.length - 1];
// Extract frontMatter if found
var content = book ? fs.readFileSync(book.resolve(f), { encoding: 'utf8' }) : null;
var frontmatter = content && frontMatter.test(content) ? frontMatter(content).attributes : {};
// This is the default metadata for a page
var defaults = {
title: pageName,
draft: false,
publish: true,
tags: []
};
// These are page properties that cannot be overridden by frontmatter
var pageInfo = {
slug: pageName,
path: f,
url: "/" + pagePublishPath
};
// Read frontmatter, fall back on defaults, and add a dash of page info
pageInfo = _.extend(defaults, frontmatter, pageInfo);
// Ignore draft pages
if (!pageInfo.draft && pageInfo.publish) {
// Create the category if needed
if (!(catPath in blog.taxonomy.categories)) {
blog.taxonomy.categories[catPath] = _.extend({
name: catName
}, catDefaults[catPath], {
slug: catName,
related: [],
path: catPath,
url: "/" + catPath,
pages: []
});
}
var catInfo = blog.taxonomy.categories[catPath];
catInfo.pages.push(pageInfo);
pageInfo.category = catInfo;
// Create tags as needed
var pageTags = pageInfo.tags;
pageInfo.tags = []
_.each(pageTags, function(tag) {
if (!(tag in blog.taxonomy.tags)) {
blog.taxonomy.tags[tag] = _.extend({}, tagDefaults[tag], {
"title": tag,
"related": [],
"pages": []
});
blog.taxonomy.tags[tag].url = "/" + blog.taxonomy.tags[tag].slug;
}
var tagInfo = blog.taxonomy.tags[tag];
tagInfo.pages.push(pageInfo);
pageInfo.tags.push(tagInfo);
// Connect tags and category through related
tagInfo.related.push(catInfo);
tagInfo.related = _.uniq(tagInfo.related);
catInfo.related.push(blog.taxonomy.tags[tag]);
catInfo.related = _.uniq(catInfo.related);
});
blog.pages[f] = pageInfo;
}
}
});
_.each(blog.taxonomy.tags, function(tag) {
tag.pages.sort(pageCompare);
});
_.each(blog.taxonomy.categories, function(category) {
if (category.slug != "") {
category.pages.sort(pageCompare);
}
});
_.each(blog.feeds, function(feed, type) {
var feedInfo = {
url: feed,
pages: _.filter(blog.pages, function(page) {
return !_.isUndefined(page.date);
}),
date: new Date(Date.now())
};
feedInfo.pages.sort(pageCompare);
blog.feeds[type] = feedInfo;
});
blog.site.categories = blog.taxonomy.categories;
return blog;
}
function pageCompare(page1, page2) {
return page2.date.valueOf() - page1.date.valueOf();
}
function categoryCompare(cat1, cat2) {
return cat1.name.localeCompare(cat2.name);
}
function tagCompare(tag1, tag2) {
return tag1.name.localeCompare(tag2.name);
}
function contentPath(link) {
// Decide where to render the page
var ext = path.extname(link);
var name = path.basename(link, ext);
var parent = path.dirname(link);
var parentExt = path.extname(parent);
var parentName = path.basename(parent, parentExt);
if (name != "index") {
if (name == parentName) {
link = path.join(parent, "index" + ext);
} else {
link = path.join(parent, name, "index" + ext);
}
}
return link
}
function blogNavigation(blog) {
var navigation = {};
var index = 1;
_.each(blog.taxonomy.categories, function(category) {
addCategoryToNavigation(category, navigation, index);
index += 1;
});
return navigation;
}
function addCategoryToNavigation(category, navigation, index) {
var i = 1;
_.each(category.pages, function(page) {
var pageNavigation = {
introduction: false,
level: [index, i].join("."),
index: i,
title: page.title
};
navigation[page.path] = pageNavigation;
i += 1;
});
}
function blogSummary(blog) {
var summary = {
"chapters": []
};
var index = 1;
_.each(blog.taxonomy.categories, function(category) {
addCategoryToSummary(category, summary.chapters, index);
index += 1;
});
return summary;
}
function addCategoryToSummary(category, summary, index) {
var i = 1;
_.each(category.pages, function(page) {
var pageSummary = {
"articles": [],
exists: true,
external: false,
introduction: false,
path: page.path,
level: [index, i].join("."),
title: page.title
};
summary.push(pageSummary);
i += 1;
});
}
function templateContentAdditions(book, content) {
var renderState = book._plugin_plasma_render_state;
return {
functions: {
strftime: function(date, format) {
return strftime(format, date);
},
imageFit: function(image, w, h) {
var ext = path.extname(image);
var name = path.basename(image, ext);
var dir = path.dirname(image);
name = sprintf("%s-fit-%d-%d%s", name, w, h, ext);
renderState.images.push({
transform: "fit",
base: content.path,
original: image,
derived: name,
width: w,
height: h
});
return path.join(dir, name);
},
imageFill: function(image, w, h) {
var ext = path.extname(image);
var name = path.basename(image, ext);
var dir = path.dirname(image);
name = sprintf("%s-fill-%d-%d%s", name, w, h, ext);
renderState.images.push({
transform: "fill",
base: content.path,
original: image,
derived: name,
width: w,
height: h
});
return path.join(dir, name);
}
}
};
}
function renderThemeTemplate(book, template, output, content) {
var Generator = generators[book.options.generator];
var generator = new Generator(book);
var ext = path.extname(output);
var relativeOutput;
// Book.contentPath breaks filenames that don't generate HTML (such as feeds)
if (_.includes(parsers.extensions, ext)) {
relativeOutput = book.contentPath(output);
} else {
relativeOutput = output;
}
var output = path.join(book.options.output, relativeOutput);
var basePath = path.relative(path.dirname(output), book.options.output) || '.';
if (process.platform === 'win32') basePath = basePath.replace(/\\/g, '/');
book.log.info.ln('generating', relativeOutput);
// Make sure that the parent directory exists
fs.mkdirpSync(path.dirname(output));
return generator.prepare()
.then(function() {
return generator._writeTemplate(template, _.extend({}, content, {
basePath: basePath,
staticBase: path.join(basePath, 'gitbook')
}), output)
});
}
module.exports = {
// Extend website resources and html
website: {
assets: "./book",
js: [
],
css: [
],
html: {
}
},
// Extend templating blocks
blocks: {
// Because the built-in is broken and generates unescaped garbage if code block contains <
code: {
process: function(block) {
return {
html: false,
body: block.body
}
}
}
},
// Extend templating filters
filters: {
},
// Hook process during build
hooks: {
// For all the hooks, this represent the current generator
// This is called before the book is generated
"init": function() {
var that = this;
if (!that.hasOwnProperty("_plugin_plasma_inited")) {
return Q()
.then(function() {
// Swizzle in override for Book.contentPath (adjusts paths from foo.html to foo/index.html)
that._plugin_plasma_original_contentPath = that.contentPath;
that.contentPath = function(link) {
var p = contentPath(this._plugin_plasma_original_contentPath(link));
// Make sure that the parent directory exists
var destDir = path.dirname(path.join(this.config.options.output, p));
fs.mkdirpSync(destDir);
return p;
};
// Swizzle in override for Book.contentLink
that._plugin_plasma_original_contentLink = that.contentLink;
that.contentLink = function(link) {
var newLink = this._plugin_plasma_original_contentLink(link);
if (path.basename(newLink) == "index.html") {
return path.dirname(newLink);
} else {
return newLink;
}
};
// Swizzle in override for Book.listAllFiles to leave PDFs and eBooks in the output
that._plugin_plasma_original_listAllFiles = that.listAllFiles;
that.listAllFiles = function() {
var that = this;
return gitbookfs.list(this.root, {
ignoreFiles: ['.ignore', '.gitignore', '.bookignore'],
ignoreRules: [
// Skip Git stuff
'.git/',
'.gitignore',
// Skip OS X meta data
'.DS_Store',
// Skip stuff installed by plugins
'node_modules',
// Skip book outputs
'_book',
// Skip config files
'.ignore',
'.bookignore',
'book.json',
]
})
.then(function(_files) {
that.files = _files;
});
};
}).then(function() {
return that.listAllFiles();
}).then(function() {
// Parse the blog page structure and taxonomy
that._plugin_plasma_blog = blogStructure(that, that.files);
that._plugin_plasma_render_state = {
images: []
};
// Replace navigation with bloggy navigation
that.navigation = blogNavigation(that._plugin_plasma_blog);
that.summary = blogSummary(that._plugin_plasma_blog);
that._plugin_plasma_inited = true;
});
}
},
"config": function(config) {
return config;
},
"page": function(page) {
console.log("Generating %j", page.path);
// At this point, HTML for page content has been assembled, but since we changed the location of some files, we may need to adjust some links
var that = this;
var src = path.dirname(page.path);
var dst = path.dirname(that.contentPath(page.path));
if (src != dst) {
_.each(page.sections, function(section) {
if (section.type == "normal") {
var $ = cheerio.load(section.content, {
// We should parse html without trying to normalize too much
xmlMode: false,
// SVG need some attributes to use uppercases
lowerCaseAttributeNames: false,
lowerCaseTags: false
});
$('img').each(function() {
var src = $(this).attr('src');
if (!src) return;
if (isRelative(src)) {
$(this).attr('src', "../" + src);
}
});
$('a').each(function() {
var href = $(this).attr('href');
if (!href) return;
if (isRelative(href)) {
$(this).attr('href', "../" + href);
}
if ($(this).attr('target') == "_blank") {
$(this).removeAttr('target');
}
});
$('pre code').each(function(index, block) {
var lang = _.chain(
($(this).attr('class') || '').split(' ')
)
.map(function(cl) {
// Markdown
if (cl.search('lang-') === 0) return cl.slice('lang-'.length);
// Asciidoc
if (cl.search('language-') === 0) return cl.slice('language-'.length);
return null;
})
.compact()
.first()
.value();
if (_.isUndefined(lang)) {
return {
html: true,
body: highlight.highlightAuto($(this).text()).value
}
} else {
return {
html: true,
body: highlight.highlight(lang, $(this).text(), true).value
}
}
});
section.content = renderDom($)
}
})
}
var pageContent = that._plugin_plasma_blog.pages[page.path];
page.sections = _.extend(page.sections, {
this: pageContent,
site: that._plugin_plasma_blog.site
}, templateContentAdditions(that, pageContent));
page.sections.this.content = _.map(page.sections, function(section) {
return section.content;
}).join("\n");
return page;
},
"page:before": function(page) {
// Extract frontmatter if found
if (frontMatter.test(page.content)) {
var fm = frontMatter(page.content);
page.content = fm.body;
}
return page;
},
"finish:before": function() {
var that = this;
// Website content has been generated. Let's generate category and tag indices
return Q()
.then(function() {
that.log.info.ln('generating indices');
return Q.all(
_.map(that._plugin_plasma_blog.taxonomy.categories, function(category) {
if (category.slug != "") {
that.log.info.ln('category index for', category.slug, 'with', that.options.generator, 'generator');
return renderThemeTemplate(that, "category.html", path.join(category.slug, "index.html"), {
content: _.extend({
site: that._plugin_plasma_blog.site,
this: category
}, templateContentAdditions(that, category))
});
}
})
);
})
.then(function() {
return Q.all(
_.map(that._plugin_plasma_blog.taxonomy.tags, function(tag) {
that.log.info.ln('tag index for', tag.name, 'with', that.options.generator, 'generator');
return renderThemeTemplate(that, "tag.html", path.join(tag.slug, "index.html"), {
content: _.extend({
site: that._plugin_plasma_blog.site,
this: tag
}, templateContentAdditions(that, tag))
});
})
);
})
.then(function() {
that.log.info.ln('generating feeds');
return Q.all(
_.map(that._plugin_plasma_blog.feeds, function(feed, type) {
that.log.info.ln(type, 'feed', feed.url, 'with', that.options.generator, 'generator');
return renderThemeTemplate(that, type + ".xml", feed.url, {
content: _.extend({
site: that._plugin_plasma_blog.site,
this: feed
}, templateContentAdditions(that, feed))
});
})
)
}).then(function() {
that.log.info.ln('generating images');
return Q.all(
_.map(that._plugin_plasma_render_state.images, function(imageTransform) {
var base = path.dirname(that.contentPath(imageTransform.base));
var original = path.join(base, imageTransform.original);
var derived = path.join(base, imageTransform.derived);
that.log.info.ln('generating', derived);
original = path.join(that.options.output, original);
derived = path.join(that.options.output, derived);
return jimp.read(original)
.then(function(image) {
if (imageTransform.transform == "fit") {
return image.contain(imageTransform.width, imageTransform.height);
} else if (imageTransform.transform == "fill") {
return image.cover(imageTransform.width, imageTransform.height);
} else {
return image;
}
}).then(function(image) {
return image.write(derived);
});
})
);
});
},
"finish": function() {
this.log.info.ln('done');
}
},
// Export these for unit testing
blogStructure: blogStructure
};
// Assorted utilities snagged from elsewhere
var isRelative = function(href) {
try {
var parsed = url.parse(href);
return !!(!parsed.protocol && parsed.path);
} catch(err) {}
return true;
};
function renderDom($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
}