getFileIgnorer.mjs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { existsSync, readFileSync } from 'node:fs';
  2. import { isAbsolute, resolve } from 'node:path';
  3. import ignore from 'ignore';
  4. import { DEFAULT_IGNORE_FILENAME } from '../constants.mjs';
  5. /**
  6. * @typedef {import('stylelint').LinterOptions} LinterOptions
  7. *
  8. * @param {Pick<LinterOptions, 'ignorePath' | 'ignorePattern'> & { cwd: string }} options
  9. * @returns {import('ignore').Ignore}
  10. */
  11. export default function getFileIgnorer({ ignorePath, ignorePattern, cwd }) {
  12. const ignorer = ignore();
  13. const ignorePaths = [ignorePath || []].flat();
  14. if (ignorePaths.length === 0) {
  15. ignorePaths.push(DEFAULT_IGNORE_FILENAME);
  16. }
  17. for (const ignoreFilePath of ignorePaths) {
  18. const absoluteIgnoreFilePath = isAbsolute(ignoreFilePath)
  19. ? ignoreFilePath
  20. : resolve(cwd, ignoreFilePath);
  21. if (!existsSync(absoluteIgnoreFilePath)) continue;
  22. const ignoreText = readFileSync(absoluteIgnoreFilePath, {
  23. // utf must remain lowercased to hit the fast path
  24. // see nodejs/node#49888
  25. encoding: 'utf8',
  26. flag: 'r',
  27. });
  28. ignorer.add(ignoreText);
  29. }
  30. if (ignorePattern) ignorer.add(ignorePattern);
  31. return ignorer;
  32. }