tools: simplify tools/doc/preprocess.js

PR-URL: https://github.com/nodejs/node/pull/19539
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Daijiro Wachi <daijiro.wachi@gmail.com>
This commit is contained in:
Vse Mozhet Byt 2018-03-22 22:39:49 +02:00
parent 50e5eff12a
commit cde98ce147

View File

@ -1,58 +1,38 @@
'use strict'; 'use strict';
module.exports = preprocess; module.exports = processIncludes;
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
const includeExpr = /^@include\s+[\w-]+\.?[a-zA-Z]*$/gmi; const includeExpr = /^@include\s+([\w-]+)(?:\.md)?$/gmi;
const includeData = {}; const commentExpr = /^@\/\/.*$/gmi;
function preprocess(inputFile, input, cb) {
input = stripComments(input);
processIncludes(inputFile, input, cb);
}
function stripComments(input) {
return input.replace(/^@\/\/.*$/gmi, '');
}
function processIncludes(inputFile, input, cb) { function processIncludes(inputFile, input, cb) {
const includes = input.match(includeExpr); const includes = input.match(includeExpr);
if (includes === null) return cb(null, input); if (includes === null)
return cb(null, input.replace(commentExpr, ''));
let errState = null; let errState = null;
let incCount = includes.length; let incCount = includes.length;
includes.forEach((include) => { includes.forEach((include) => {
let fname = include.replace(/^@include\s+/, ''); const fname = include.replace(includeExpr, '$1.md');
if (!/\.md$/.test(fname)) fname = `${fname}.md`;
if (includeData.hasOwnProperty(fname)) {
input = input.split(include).join(includeData[fname]);
incCount--;
if (incCount === 0) {
return cb(null, input);
}
}
const fullFname = path.resolve(path.dirname(inputFile), fname); const fullFname = path.resolve(path.dirname(inputFile), fname);
fs.readFile(fullFname, 'utf8', function(er, inc) { fs.readFile(fullFname, 'utf8', function(er, inc) {
if (errState) return; if (errState) return;
if (er) return cb(errState = er); if (er) return cb(errState = er);
preprocess(inputFile, inc, function(er, inc) { incCount--;
if (errState) return;
if (er) return cb(errState = er);
incCount--;
// Add comments to let the HTML generator know how the anchors for // Add comments to let the HTML generator know
// headings should look like. // how the anchors for headings should look like.
includeData[fname] = `<!-- [start-include:${fname}] -->\n` + inc = `<!-- [start-include:${fname}] -->\n` +
`${inc}\n<!-- [end-include:${fname}] -->\n`; `${inc}\n<!-- [end-include:${fname}] -->\n`;
input = input.split(`${include}\n`).join(`${includeData[fname]}\n`); input = input.split(`${include}\n`).join(`${inc}\n`);
if (incCount === 0) {
return cb(null, input); if (incCount === 0)
} return cb(null, input.replace(commentExpr, ''));
});
}); });
}); });
} }