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