UNPKG

2.1 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(stylelint, searchPath = process.cwd(), filePath) {
22 const optionsConfig = stylelint._options.config;
23
24 if (optionsConfig !== undefined) {
25 const cached = stylelint._specifiedConfigCache.get(optionsConfig);
26
27 // If config has overrides the resulting config might be different for some files.
28 // Cache results only if resulted config is the same for all linted files.
29 if (cached && !optionsConfig.overrides) {
30 return cached;
31 }
32
33 const augmentedResult = augmentConfigFull(stylelint, filePath, {
34 config: optionsConfig,
35 // Add the extra path part so that we can get the directory without being
36 // confused
37 filepath: path.join(process.cwd(), 'argument-config'),
38 });
39
40 stylelint._specifiedConfigCache.set(optionsConfig, augmentedResult);
41
42 return augmentedResult;
43 }
44
45 const configExplorer = cosmiconfig('stylelint', {
46 transform: (cosmiconfigResult) => augmentConfigFull(stylelint, filePath, cosmiconfigResult),
47 stopDir: STOP_DIR,
48 });
49
50 let config = stylelint._options.configFile
51 ? await configExplorer.load(stylelint._options.configFile)
52 : await configExplorer.search(searchPath);
53
54 if (!config) {
55 config = await configExplorer.search(process.cwd());
56 }
57
58 if (!config) {
59 return Promise.reject(
60 configurationError(`No configuration provided${searchPath ? ` for ${searchPath}` : ''}`),
61 );
62 }
63
64 return config;
65};