0
0
mirror of https://github.com/nodejs/node.git synced 2024-12-01 16:10:02 +01:00
nodejs/tools/doc/preprocess.js
Anna Henningsen b140bad391
tools: make sure doctool anchors respect includes
Previously, output files which were created using includes (notably,
the single-page all.html) had basically broken internal links all
over the place because references like `errors.html#errors_class_error`
are being used, yet `id` attributes were generated that looked like
`all_class_error`.

This PR adds generation of comments from the include preprocessor
that indicate from which file the current markdown bits come and
lets the HTML output generation take advantage of that so that more
appropriate `id` attributes can be generated.

PR-URL: https://github.com/nodejs/node/pull/6943
Reviewed-By: Robert Jefe Lindstaedt <robert.lindstaedt@gmail.com>
Reviewed-By: Daniel Wang <wangyang0123@gmail.com>
2016-05-26 00:49:34 +02:00

64 lines
1.8 KiB
JavaScript

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