/
getConfigGroups.js
75 lines (60 loc) · 2.22 KB
/
getConfigGroups.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
/** @typedef {import('./index').Logger} Logger */
import path from 'path'
import { loadConfig } from './loadConfig.js'
import { ConfigNotFoundError } from './symbols.js'
import { validateConfig } from './validateConfig.js'
/**
* Return matched files grouped by their configuration.
*
* @param {object} options
* @param {Object} [options.configObject] - Explicit config object from the js API
* @param {string} [options.configPath] - Explicit path to a config file
* @param {string} [options.cwd] - Current working directory
* @param {Logger} logger
*/
export const getConfigGroups = async ({ configObject, configPath, files }, logger = console) => {
// Return explicit config object from js API
if (configObject) {
const config = validateConfig(configObject, 'config object', logger)
return { '': { config, files } }
}
// Use only explicit config path instead of discovering multiple
if (configPath) {
const { config, filepath } = await loadConfig({ configPath }, logger)
if (!config) {
logger.error(`${ConfigNotFoundError.message}.`)
throw ConfigNotFoundError
}
const validatedConfig = validateConfig(config, filepath, logger)
return { [configPath]: { config: validatedConfig, files } }
}
// Group files by their base directory
const filesByDir = files.reduce((acc, file) => {
const dir = path.normalize(path.dirname(file))
if (dir in acc) {
acc[dir].push(file)
} else {
acc[dir] = [file]
}
return acc
}, {})
// Group files by their discovered config
// { '.lintstagedrc.json': { config: {...}, files: [...] } }
const configGroups = {}
for (const [dir, files] of Object.entries(filesByDir)) {
// Discover config from the base directory of the file
const { config, filepath } = await loadConfig({ cwd: dir }, logger)
if (!config) {
logger.error(`${ConfigNotFoundError.message}.`)
throw ConfigNotFoundError
}
if (filepath in configGroups) {
// Re-use cached config and skip validation
configGroups[filepath].files.push(...files)
continue
}
const validatedConfig = validateConfig(config, filepath, logger)
configGroups[filepath] = { config: validatedConfig, files }
}
return configGroups
}