|
1 | 1 | 'use strict'; |
2 | 2 |
|
3 | | -module.exports = preprocess; |
| 3 | +module.exports = processIncludes; |
4 | 4 |
|
5 | 5 | const path = require('path'); |
6 | 6 | const fs = require('fs'); |
7 | 7 |
|
8 | | -const includeExpr = /^@include\s+[\w-]+\.?[a-zA-Z]*$/gmi; |
9 | | -const includeData = {}; |
10 | | - |
11 | | -function preprocess(inputFile, input, cb) { |
12 | | - input = stripComments(input); |
13 | | - processIncludes(inputFile, input, cb); |
14 | | -} |
15 | | - |
16 | | -function stripComments(input) { |
17 | | - return input.replace(/^@\/\/.*$/gmi, ''); |
18 | | -} |
| 8 | +const includeExpr = /^@include\s+([\w-]+)(?:\.md)?$/gmi; |
| 9 | +const commentExpr = /^@\/\/.*$/gmi; |
19 | 10 |
|
20 | 11 | function processIncludes(inputFile, input, cb) { |
21 | 12 | const includes = input.match(includeExpr); |
22 | | - if (includes === null) return cb(null, input); |
| 13 | + if (includes === null) |
| 14 | + return cb(null, input.replace(commentExpr, '')); |
| 15 | + |
23 | 16 | let errState = null; |
24 | 17 | let incCount = includes.length; |
25 | 18 |
|
26 | 19 | includes.forEach((include) => { |
27 | | - let fname = include.replace(/^@include\s+/, ''); |
28 | | - if (!/\.md$/.test(fname)) fname = `${fname}.md`; |
29 | | - |
30 | | - if (includeData.hasOwnProperty(fname)) { |
31 | | - input = input.split(include).join(includeData[fname]); |
32 | | - incCount--; |
33 | | - if (incCount === 0) { |
34 | | - return cb(null, input); |
35 | | - } |
36 | | - } |
37 | | - |
| 20 | + const fname = include.replace(includeExpr, '$1.md'); |
38 | 21 | const fullFname = path.resolve(path.dirname(inputFile), fname); |
| 22 | + |
39 | 23 | fs.readFile(fullFname, 'utf8', function(er, inc) { |
40 | 24 | if (errState) return; |
41 | 25 | if (er) return cb(errState = er); |
42 | | - preprocess(inputFile, inc, function(er, inc) { |
43 | | - if (errState) return; |
44 | | - if (er) return cb(errState = er); |
45 | | - incCount--; |
46 | | - |
47 | | - // Add comments to let the HTML generator know how the anchors for |
48 | | - // headings should look like. |
49 | | - includeData[fname] = `<!-- [start-include:${fname}] -->\n` + |
50 | | - `${inc}\n<!-- [end-include:${fname}] -->\n`; |
51 | | - input = input.split(`${include}\n`).join(`${includeData[fname]}\n`); |
52 | | - if (incCount === 0) { |
53 | | - return cb(null, input); |
54 | | - } |
55 | | - }); |
| 26 | + incCount--; |
| 27 | + |
| 28 | + // Add comments to let the HTML generator know |
| 29 | + // how the anchors for headings should look like. |
| 30 | + inc = `<!-- [start-include:${fname}] -->\n` + |
| 31 | + `${inc}\n<!-- [end-include:${fname}] -->\n`; |
| 32 | + input = input.split(`${include}\n`).join(`${inc}\n`); |
| 33 | + |
| 34 | + if (incCount === 0) |
| 35 | + return cb(null, input.replace(commentExpr, '')); |
56 | 36 | }); |
57 | 37 | }); |
58 | 38 | } |
0 commit comments