/
loadConfig.js
69 lines (61 loc) Β· 1.62 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
import { lilconfig } from 'lilconfig'
import YAML from 'yaml'
/**
* 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(path)
.then((module) => module.default)
.catch((error) => {
console.error(error)
throw error
})
const jsonParse = (path, content) => JSON.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': YAML.parse,
'.yml': YAML.parse,
noExt: YAML.parse,
}
const resolveConfig = (configPath) => {
try {
return require.resolve(configPath)
} catch {
return configPath
}
}
/**
* @param {string} [configPath]
*/
export const loadConfig = async (configPath) => {
const explorer = lilconfig('lint-staged', { searchPlaces, loaders })
const result = await (configPath ? explorer.load(resolveConfig(configPath)) : explorer.search())
if (!result) return null
const { config, filepath } = result
// config is a promise when using the `dynamicImport` loader
return { config: await config, filepath }
}