UNPKG

2.18 kBJavaScriptView Raw
1/** @typedef {import('./index').Logger} Logger */
2
3import debug from 'debug'
4import { lilconfig } from 'lilconfig'
5import YAML from 'yaml'
6
7import { dynamicImport } from './dynamicImport.js'
8import { resolveConfig } from './resolveConfig.js'
9
10const debugLog = debug('lint-staged:loadConfig')
11
12/**
13 * The list of files `lint-staged` will read configuration
14 * from, in the declared order.
15 */
16export const searchPlaces = [
17 'package.json',
18 '.lintstagedrc',
19 '.lintstagedrc.json',
20 '.lintstagedrc.yaml',
21 '.lintstagedrc.yml',
22 '.lintstagedrc.mjs',
23 '.lintstagedrc.js',
24 '.lintstagedrc.cjs',
25 'lint-staged.config.mjs',
26 'lint-staged.config.js',
27 'lint-staged.config.cjs',
28]
29
30const jsonParse = (path, content) => JSON.parse(content)
31
32const yamlParse = (path, content) => YAML.parse(content)
33
34/**
35 * `lilconfig` doesn't support yaml files by default,
36 * so we add custom loaders for those. Files without
37 * an extensions are assumed to be yaml — this
38 * assumption is in `cosmiconfig` as well.
39 */
40const loaders = {
41 '.js': dynamicImport,
42 '.json': jsonParse,
43 '.mjs': dynamicImport,
44 '.cjs': dynamicImport,
45 '.yaml': yamlParse,
46 '.yml': yamlParse,
47 noExt: yamlParse,
48}
49
50const explorer = lilconfig('lint-staged', { searchPlaces, loaders })
51
52/**
53 * @param {object} options
54 * @param {string} [options.configPath] - Explicit path to a config file
55 * @param {string} [options.cwd] - Current working directory
56 */
57export const loadConfig = async ({ configPath, cwd }, logger) => {
58 try {
59 if (configPath) {
60 debugLog('Loading configuration from `%s`...', configPath)
61 } else {
62 debugLog('Searching for configuration from `%s`...', cwd)
63 }
64
65 const result = await (configPath
66 ? explorer.load(resolveConfig(configPath))
67 : explorer.search(cwd))
68
69 if (!result) return {}
70
71 // config is a promise when using the `dynamicImport` loader
72 const config = await result.config
73 const filepath = result.filepath
74
75 debugLog('Successfully loaded config from `%s`:\n%O', filepath, config)
76
77 return { config, filepath }
78 } catch (error) {
79 debugLog('Failed to load configuration!')
80 logger.error(error)
81 return {}
82 }
83}