file-matcher.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright 2012-2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. var async = require('async'),
  6. fileset = require('fileset'),
  7. fs = require('fs'),
  8. path = require('path'),
  9. seq = 0;
  10. function filesFor(options, callback) {
  11. if (!callback && typeof options === 'function') {
  12. callback = options;
  13. options = null;
  14. }
  15. options = options || {};
  16. var root = options.root,
  17. includes = options.includes,
  18. excludes = options.excludes,
  19. realpath = options.realpath,
  20. relative = options.relative,
  21. opts;
  22. root = root || process.cwd();
  23. includes = includes && Array.isArray(includes) ? includes : [ '**/*.js' ];
  24. excludes = excludes && Array.isArray(excludes) ? excludes : [ '**/node_modules/**' ];
  25. opts = { cwd: root, nodir: true, ignore: excludes };
  26. seq += 1;
  27. opts['x' + seq + new Date().getTime()] = true; //cache buster for minimatch cache bug
  28. fileset(includes.join(' '), excludes.join(' '), opts, function (err, files) {
  29. /* istanbul ignore if - untestable */
  30. if (err) { return callback(err); }
  31. if (relative) { return callback(err, files); }
  32. if (!realpath) {
  33. files = files.map(function (file) { return path.resolve(root, file); });
  34. return callback(err, files);
  35. }
  36. var realPathCache = module.constructor._realpathCache || /* istanbul ignore next */ {};
  37. async.map(files, function (file, done) {
  38. fs.realpath(path.resolve(root, file), realPathCache, done);
  39. }, callback);
  40. });
  41. }
  42. function matcherFor(options, callback) {
  43. if (!callback && typeof options === 'function') {
  44. callback = options;
  45. options = null;
  46. }
  47. options = options || {};
  48. options.relative = false; //force absolute paths
  49. options.realpath = true; //force real paths (to match Node.js module paths)
  50. filesFor(options, function (err, files) {
  51. var fileMap = {},
  52. matchFn;
  53. /* istanbul ignore if - untestable */
  54. if (err) { return callback(err); }
  55. files.forEach(function (file) { fileMap[file] = true; });
  56. matchFn = function (file) { return fileMap[file]; };
  57. matchFn.files = Object.keys(fileMap);
  58. return callback(null, matchFn);
  59. });
  60. }
  61. module.exports = {
  62. filesFor: filesFor,
  63. matcherFor: matcherFor
  64. };