getFileIgnorer.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. // Try to get file ignorer from '.stylelintignore'
  3. const fs = require('fs');
  4. const path = require('path');
  5. const { default: ignore } = require('ignore');
  6. const isPathNotFoundError = require('./isPathNotFoundError');
  7. const DEFAULT_IGNORE_FILENAME = '.stylelintignore';
  8. /**
  9. * @typedef {import('stylelint').LinterOptions} LinterOptions
  10. *
  11. * @param {Pick<LinterOptions, 'ignorePath' | 'ignorePattern'> & { cwd: string }} options
  12. * @return {import('ignore').Ignore}
  13. */
  14. module.exports = function getFileIgnorer({ ignorePath, ignorePattern, cwd }) {
  15. const ignorer = ignore();
  16. const ignorePaths = [ignorePath || []].flat();
  17. if (ignorePaths.length === 0) {
  18. ignorePaths.push(DEFAULT_IGNORE_FILENAME);
  19. }
  20. for (const ignoreFilePath of ignorePaths) {
  21. const absoluteIgnoreFilePath = path.isAbsolute(ignoreFilePath)
  22. ? ignoreFilePath
  23. : path.resolve(cwd, ignoreFilePath);
  24. try {
  25. const ignoreText = fs.readFileSync(absoluteIgnoreFilePath, 'utf8');
  26. ignorer.add(ignoreText);
  27. } catch (readError) {
  28. if (!isPathNotFoundError(readError)) {
  29. throw readError;
  30. }
  31. }
  32. }
  33. if (ignorePattern) ignorer.add(ignorePattern);
  34. return ignorer;
  35. };