Add synchronous version of the API, with tests and documentation.

This commit is contained in:
David Anson 2015-03-20 00:09:55 -07:00
parent 200dddf3d1
commit e557f3a97f
6 changed files with 132 additions and 18 deletions

View file

@ -54,8 +54,9 @@ function uniqueFilterForSorted(value, index, array) {
}
// Lints a single file
function lintFile(file, config, callback) {
fs.readFile(file, shared.utf8Encoding, function readFile(err, contents) {
function lintFile(file, config, synchronous, callback) {
// Callback for read file API
function readFile(err, contents) {
if (err) {
callback(err);
} else {
@ -118,28 +119,43 @@ function lintFile(file, config, callback) {
});
callback(null, result);
}
});
}
// Make a/synchronous call to read file
if (synchronous) {
readFile(null, fs.readFileSync(file, shared.utf8Encoding));
} else {
fs.readFile(file, shared.utf8Encoding, readFile);
}
}
// Callback used as a sentinel by markdownlintSync
function markdownlintSynchronousCallback() {
// Unreachable; no code path in the synchronous case passes err
// if (err) {
// throw err; // Synchronous APIs throw
// }
}
/**
* Lint specified Markdown files according to configurable rules.
*
* @param {Object} options Configuration options.
* @param {Function} callback Callback (err, results) function.
* @param {Function} callback Callback (err, result) function.
* @returns {void}
*/
module.exports = function markdownlint(options, callback) {
function markdownlint(options, callback) {
// Normalize inputs
options = options || {};
callback = callback || function noop() {};
var files = (options.files || []).slice();
var config = options.config || { "default": true };
var synchronous = (callback === markdownlintSynchronousCallback);
var results = new Results();
// Lint each input file
function lintFiles() {
var file = files.shift();
if (file) {
lintFile(file, config, function lintFileCallback(err, result) {
lintFile(file, config, synchronous, function lintedFile(err, result) {
if (err) {
callback(err);
} else {
@ -153,4 +169,21 @@ module.exports = function markdownlint(options, callback) {
}
}
lintFiles();
};
if (synchronous) {
return results;
}
}
/**
* Lint specified Markdown files according to configurable rules.
*
* @param {Object} options Configuration options.
* @returns {Object} Result object.
*/
function markdownlintSync(options) {
return markdownlint(options, markdownlintSynchronousCallback);
}
// Export a/synchronous APIs
module.exports = markdownlint;
module.exports.sync = markdownlintSync;