-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
59 lines (49 loc) · 1.61 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
var path = require('path');
var fs = require('fs');
var Q = require('q');
module.exports = {
hooks: {
"page:before": function(page) {
// page.content is a string with the file markdown content
// page.path is the path to the page in the gitbook
// page.rawPath is the path to the raw file
// use multiline flag to grok every line, and global flag to
// find all matches -- finds '' and "" filenames
// TODO: add initial \s* to eat up whitespace?
var re = /^!INCLUDE\s+(?:\"([^\"]+)\"|'([^']+)')\s*$/gm;
var dir = path.dirname(page.rawPath);
// construct path from gitbook binary to target include
var makePath = function(filename) {
return path.join(dir, filename);
};
var files = {};
// return a closure for saving the passed text
var cacheFile = function(filepath) {
return function(text) {
files[filepath] = text;
};
};
var readFiles = []; // file promises
// find all !INCLUDE statements.
// read and cache target files
var res;
while (res = re.exec(page.content)) {
var filepath = makePath(res[1] || res[2]);
readFiles.push(
Q.nfcall(fs.readFile, filepath)
.then(cacheFile(filepath))
);
}
// once all files are read, replace !INCLUDE statements with
// appropriate file content
return Q.all(readFiles)
.then(function() {
page.content = page.content.replace(re, function(match, p1, p2) {
var filepath = makePath(p1 || p2);
return files[filepath].toString().trim(); // strip whitespace
});
return page;
})
}
}
};