UNPKG

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