UNPKG

fedtools-utilities

Version:
108 lines (93 loc) 2.48 kB
/** * List all files under current folder. * Heavily inspered from https://github.com/jergason/recursive-readdir * * Additions: * - ignore errors on non-files (ENOENT on links for example) * - fixes to follow our eslint rules */ var fs = require('fs-extra'), p = require('path'), minimatch = require('minimatch'); function patternMatcher(pattern) { return function (path, stats) { var minimatcher = new minimatch.Minimatch(pattern, { matchBase: true }); return (!minimatcher.negate || stats.isFile()) && minimatcher.match(path); }; } function toMatcherFunction(ignoreEntry) { if (typeof ignoreEntry == 'function') { return ignoreEntry; } else { return patternMatcher(ignoreEntry); } } function readdir(path, ignores, callback) { var list = []; if (typeof ignores == 'function') { callback = ignores; ignores = []; } ignores = ignores.map(toMatcherFunction); fs.readdir(path, function (err, files) { var pending; if (err) { return callback(err); } pending = files.length; if (!pending) { // we are done, woop woop return callback(null, list); } files.forEach(function (file) { var filePath = p.join(path, file); fs.stat(filePath, function (_err, stats) { if (_err && _err.code === 'ENOENT') { // just ignore the error if the FS says that the file // does not exist... broken symlink? pending -= 1; if (!pending) { return callback(null, list); } return null; } else if (_err) { return callback(_err); } function _ignoreMatcher(matcher) { return matcher(filePath, stats); } if (ignores.some(_ignoreMatcher)) { pending -= 1; if (!pending) { return callback(null, list); } return null; } if (stats.isDirectory()) { readdir(filePath, ignores, function (__err, res) { if (__err) { return callback(__err); } list = list.concat(res); pending -= 1; if (!pending) { return callback(null, list); } }); } else { list.push(filePath); pending -= 1; if (!pending) { return callback(null, list); } } }); }); }); } module.exports = readdir;