ignoreFiles.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const fs = require('fs');
  3. const mm = require('micromatch');
  4. const matchers = [];
  5. /**
  6. * Add glob patterns to ignore matched files and folders.
  7. * Creates glob patterns to approximate gitignore patterns.
  8. * @param {String} val - the glob or gitignore-style pattern to ignore
  9. * @see {@linkplain https://git-scm.com/docs/gitignore#_pattern_format}
  10. */
  11. function addIgnorePattern(val) {
  12. if (val && typeof val === 'string' && val[0] !== '#') {
  13. let pattern = val;
  14. if (pattern.indexOf('/') === -1) {
  15. matchers.push('**/' + pattern);
  16. } else if (pattern[pattern.length-1] === '/') {
  17. matchers.push('**/' + pattern + '**');
  18. matchers.push(pattern + '**');
  19. }
  20. matchers.push(pattern);
  21. }
  22. }
  23. /**
  24. * Adds ignore patterns directly from function input
  25. * @param {String|Array<String>} input - the ignore patterns
  26. */
  27. function addIgnoreFromInput(input) {
  28. let patterns = [];
  29. if (input) {
  30. patterns = patterns.concat(input);
  31. }
  32. patterns.forEach(addIgnorePattern);
  33. }
  34. /**
  35. * Adds ignore patterns by reading files
  36. * @param {String|Array<String>} input - the paths to the ignore config files
  37. */
  38. function addIgnoreFromFile(input) {
  39. let lines = [];
  40. let files = [];
  41. if (input) {
  42. files = files.concat(input);
  43. }
  44. files.forEach(function(config) {
  45. const stats = fs.statSync(config);
  46. if (stats.isFile()) {
  47. const content = fs.readFileSync(config, 'utf8');
  48. lines = lines.concat(content.split(/\r?\n/));
  49. }
  50. });
  51. lines.forEach(addIgnorePattern);
  52. }
  53. function shouldIgnore(path) {
  54. const matched = matchers.length ? mm.isMatch(path, matchers, { dot:true }) : false;
  55. return matched;
  56. }
  57. exports.add = addIgnoreFromInput;
  58. exports.addFromFile = addIgnoreFromFile;
  59. exports.shouldIgnore = shouldIgnore;