file-matcher.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. Copyright 2012-2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. const fs = require('fs');
  6. const path = require('path');
  7. const async = require('async');
  8. const fileset = require('fileset');
  9. let seq = 0;
  10. function filesFor(options, callback) {
  11. if (!callback && typeof options === 'function') {
  12. callback = options;
  13. options = null;
  14. }
  15. options = options || {};
  16. let root = options.root;
  17. let includes = options.includes;
  18. let excludes = options.excludes;
  19. const realpath = options.realpath;
  20. const relative = options.relative;
  21. root = root || process.cwd();
  22. includes = includes && Array.isArray(includes) ? includes : ['**/*.js'];
  23. excludes =
  24. excludes && Array.isArray(excludes) ? excludes : ['**/node_modules/**'];
  25. const 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, (err, files) => {
  29. /* istanbul ignore if - untestable */
  30. if (err) {
  31. return callback(err);
  32. }
  33. if (relative) {
  34. return callback(err, files);
  35. }
  36. if (!realpath) {
  37. files = files.map(file => path.resolve(root, file));
  38. return callback(err, files);
  39. }
  40. const realPathCache =
  41. module.constructor._realpathCache || /* istanbul ignore next */ {};
  42. async.map(
  43. files,
  44. (file, done) => {
  45. fs.realpath(path.resolve(root, file), realPathCache, done);
  46. },
  47. callback
  48. );
  49. });
  50. }
  51. function matcherFor(options, callback) {
  52. if (!callback && typeof options === 'function') {
  53. callback = options;
  54. options = null;
  55. }
  56. options = options || {};
  57. options.relative = false; //force absolute paths
  58. options.realpath = true; //force real paths (to match Node.js module paths)
  59. filesFor(options, (err, files) => {
  60. const fileMap = Object.create(null);
  61. /* istanbul ignore if - untestable */
  62. if (err) {
  63. return callback(err);
  64. }
  65. files.forEach(file => {
  66. fileMap[file] = true;
  67. });
  68. const matchFn = function(file) {
  69. return fileMap[file];
  70. };
  71. matchFn.files = Object.keys(fileMap);
  72. return callback(null, matchFn);
  73. });
  74. }
  75. module.exports = {
  76. filesFor,
  77. matcherFor
  78. };