getConfigForFile.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const configurationError = require('./utils/configurationError');
  3. const path = require('path');
  4. const { augmentConfigFull } = require('./augmentConfig');
  5. const { cosmiconfig } = require('cosmiconfig');
  6. const IS_TEST = process.env.NODE_ENV === 'test';
  7. const STOP_DIR = IS_TEST ? process.cwd() : undefined;
  8. /** @typedef {import('stylelint').InternalApi} StylelintInternalApi */
  9. /** @typedef {import('stylelint').Config} StylelintConfig */
  10. /** @typedef {import('stylelint').CosmiconfigResult} StylelintCosmiconfigResult */
  11. /**
  12. * @param {StylelintInternalApi} stylelint
  13. * @param {string} [searchPath]
  14. * @param {string} [filePath]
  15. * @returns {Promise<StylelintCosmiconfigResult>}
  16. */
  17. module.exports = async function getConfigForFile(
  18. stylelint,
  19. searchPath = stylelint._options.cwd,
  20. filePath,
  21. ) {
  22. const optionsConfig = stylelint._options.config;
  23. const cwd = stylelint._options.cwd;
  24. if (optionsConfig !== undefined) {
  25. const cached = stylelint._specifiedConfigCache.get(optionsConfig);
  26. // If config has overrides the resulting config might be different for some files.
  27. // Cache results only if resulted config is the same for all linted files.
  28. if (cached && !optionsConfig.overrides) {
  29. return cached;
  30. }
  31. const augmentedResult = augmentConfigFull(stylelint, filePath, {
  32. config: optionsConfig,
  33. // Add the extra path part so that we can get the directory without being
  34. // confused
  35. filepath: path.join(cwd, 'argument-config'),
  36. });
  37. stylelint._specifiedConfigCache.set(optionsConfig, augmentedResult);
  38. return augmentedResult;
  39. }
  40. const configExplorer = cosmiconfig('stylelint', {
  41. transform: (cosmiconfigResult) => augmentConfigFull(stylelint, filePath, cosmiconfigResult),
  42. stopDir: STOP_DIR,
  43. });
  44. let config = stylelint._options.configFile
  45. ? await configExplorer.load(stylelint._options.configFile)
  46. : await configExplorer.search(searchPath);
  47. if (!config) {
  48. config = await configExplorer.search(cwd);
  49. }
  50. if (!config) {
  51. return Promise.reject(
  52. configurationError(`No configuration provided${searchPath ? ` for ${searchPath}` : ''}`),
  53. );
  54. }
  55. return config;
  56. };