nodoc
Version:
A simple and 'low-level' source code comments parser and gitHub flavored markdown API documentation generator.
108 lines (107 loc) • 3.17 kB
JavaScript
var _, commentFilter, defaultTemplate, fs, generate, getTag, hasTag, parser, path, removeTag;
parser = require('./parser');
_ = require('underscore');
fs = require('fs');
path = require('path');
defaultTemplate = '' + fs.readFileSync(path.join(__dirname, 'template/markdown.tpl'));
removeTag = function(comment, tagName) {
comment.tags = comment.tags.filter(function(tag) {
return tag.tagName !== tagName;
});
return comment;
};
getTag = function(comment, tagName) {
var tag;
tag = comment.tags.filter(function(tag) {
return tag.tagName === tagName;
});
return tag;
};
hasTag = function(comment, tagName) {
return !!getTag(comment, tagName).length;
};
commentFilter = function(comments) {
var cos;
cos = comments.filter(function(comment) {
return !(hasTag(comment, 'private') || hasTag(comment, 'nodoc'));
});
cos.forEach(function(comment) {
var alias, aliasTag, defStr, prefixTag;
if (hasTag(comment, 'noPrefix')) {
comment.name = comment.name.split('.').slice(-1)[0];
removeTag(comment, 'noPrefix');
}
defStr = '';
getTag(comment, 'param').forEach(function(param) {
var defaultVal, ref, type;
if (!param.type && !param.name) {
return defStr += ' ';
}
ref = param.type.split('='), type = ref[0], defaultVal = ref[1];
return defStr += defaultVal ? param.name + " = " + defaultVal + ", " : param.name + ", ";
});
if (defStr) {
comment.sign = "(" + (defStr.slice(0, -2)) + ")";
if (defStr.trim() === '') {
removeTag(comment, 'param');
}
} else if (hasTag(comment, 'return')) {
comment.sign = '()';
}
aliasTag = getTag(comment, 'alias');
if (aliasTag.length) {
alias = aliasTag.reduce(function(str, a) {
return str += a.description + ' ';
}, '');
if (alias) {
comment.alias = alias.trim();
}
removeTag(comment, 'alias');
}
prefixTag = getTag(comment, 'prefix')[0];
if (prefixTag) {
comment.name = (prefixTag.description || '') + comment.name;
return removeTag(comment, 'prefix');
}
});
return cos;
};
generate = function(srcPath, opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
moduleName: void 0,
moduleDesc: '',
tplData: {},
template: defaultTemplate
});
return parser.parseFile(srcPath, opts).then(function(comments) {
var moduleName;
moduleName = (function() {
var baseName, dirName;
if (opts.moduleName != null) {
return opts.moduleName;
}
baseName = path.basename(srcPath, path.extname(srcPath));
dirName = path.dirname(srcPath).split(path.sep).slice(-1)[0];
if (baseName === 'index') {
return dirName;
} else {
return baseName;
}
})();
_.extend(opts.tplData, {
moduleDesc: opts.moduleDesc,
moduleName: moduleName,
comments: commentFilter(comments),
srcPath: srcPath
});
return _.template(opts.template + '')(opts.tplData).replace(/(\r\n|\n)(\ |\r\n|\n)*(\r\n|\n)/g, '\n\n');
});
};
module.exports = {
parser: parser,
generate: generate,
render: generate
};