Mathias Bynens | 79e2cf0 | 2020-05-29 16:46:17 +0200 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | const augmentConfigFull = require('./augmentConfig').augmentConfigFull; |
| 4 | const configurationError = require('./utils/configurationError'); |
| 5 | const path = require('path'); |
| 6 | |
| 7 | /** @typedef {import('stylelint').StylelintConfig} StylelintConfig */ |
| 8 | /** @typedef {import('stylelint').CosmiconfigResult} CosmiconfigResult */ |
| 9 | /** @typedef {Promise<CosmiconfigResult | null>} ConfigPromise */ |
| 10 | |
| 11 | /** |
| 12 | * @param {import('stylelint').StylelintInternalApi} stylelint |
| 13 | * @param {string} [searchPath] |
| 14 | * @returns {ConfigPromise} |
| 15 | */ |
| 16 | module.exports = function (stylelint, searchPath = process.cwd()) { |
| 17 | const optionsConfig = stylelint._options.config; |
| 18 | |
| 19 | if (optionsConfig !== undefined) { |
| 20 | const cached = /** @type {ConfigPromise} */ (stylelint._specifiedConfigCache.get( |
| 21 | optionsConfig, |
| 22 | )); |
| 23 | |
| 24 | if (cached) return cached; |
| 25 | |
| 26 | // stylelint._fullExplorer (cosmiconfig) is already configured to |
| 27 | // run augmentConfigFull; but since we're making up the result here, |
| 28 | // we need to manually run the transform |
| 29 | const augmentedResult = augmentConfigFull(stylelint, { |
| 30 | config: optionsConfig, |
| 31 | // Add the extra path part so that we can get the directory without being |
| 32 | // confused |
| 33 | filepath: path.join(process.cwd(), 'argument-config'), |
| 34 | }); |
| 35 | |
| 36 | stylelint._specifiedConfigCache.set(optionsConfig, augmentedResult); |
| 37 | |
| 38 | return augmentedResult; |
| 39 | } |
| 40 | |
| 41 | const searchForConfig = stylelint._options.configFile |
| 42 | ? stylelint._fullExplorer.load(stylelint._options.configFile) |
| 43 | : stylelint._fullExplorer.search(searchPath); |
| 44 | |
| 45 | return /** @type {ConfigPromise} */ (searchForConfig |
| 46 | .then((config) => { |
| 47 | // If no config was found, try looking from process.cwd |
| 48 | if (!config) return stylelint._fullExplorer.search(process.cwd()); |
| 49 | |
| 50 | return config; |
| 51 | }) |
| 52 | .then((config) => { |
| 53 | if (!config) { |
| 54 | const ending = searchPath ? ` for ${searchPath}` : ''; |
| 55 | |
| 56 | throw configurationError(`No configuration provided${ending}`); |
| 57 | } |
| 58 | |
| 59 | return config; |
| 60 | })); |
| 61 | }; |