1 |
|
2 |
|
3 | import path from 'path'
|
4 |
|
5 | import debug from 'debug'
|
6 | import objectInspect from 'object-inspect'
|
7 |
|
8 | import { loadConfig } from './loadConfig.js'
|
9 | import { ConfigNotFoundError } from './symbols.js'
|
10 | import { validateConfig } from './validateConfig.js'
|
11 |
|
12 | const debugLog = debug('lint-staged:getConfigGroups')
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | export const getConfigGroups = async (
|
25 | { configObject, configPath, cwd, files },
|
26 | logger = console
|
27 | ) => {
|
28 | debugLog('Grouping configuration files...')
|
29 |
|
30 |
|
31 | if (configObject) {
|
32 | debugLog('Using single direct configuration object...')
|
33 |
|
34 | const config = validateConfig(configObject, 'config object', logger)
|
35 | return { '': { config, files } }
|
36 | }
|
37 |
|
38 |
|
39 | if (configPath) {
|
40 | debugLog('Using single configuration path...')
|
41 |
|
42 | const { config, filepath } = await loadConfig({ configPath }, logger)
|
43 |
|
44 | if (!config) {
|
45 | logger.error(`${ConfigNotFoundError.message}.`)
|
46 | throw ConfigNotFoundError
|
47 | }
|
48 |
|
49 | const validatedConfig = validateConfig(config, filepath, logger)
|
50 | return { [configPath]: { config: validatedConfig, files } }
|
51 | }
|
52 |
|
53 | debugLog('Grouping staged files by their directories...')
|
54 |
|
55 |
|
56 | const filesByDir = files.reduce((acc, file) => {
|
57 | const dir = path.normalize(path.dirname(file))
|
58 |
|
59 | if (dir in acc) {
|
60 | acc[dir].push(file)
|
61 | } else {
|
62 | acc[dir] = [file]
|
63 | }
|
64 |
|
65 | return acc
|
66 | }, {})
|
67 |
|
68 | debugLog('Grouped staged files into %d directories:', Object.keys(filesByDir).length)
|
69 | debugLog(objectInspect(filesByDir, { indent: 2 }))
|
70 |
|
71 |
|
72 |
|
73 | const configGroups = {}
|
74 |
|
75 | debugLog('Searching config files...')
|
76 |
|
77 | const searchConfig = async (cwd, files = []) => {
|
78 | const { config, filepath } = await loadConfig({ cwd }, logger)
|
79 | if (!config) {
|
80 | debugLog('Found no config from "%s"!', cwd)
|
81 | return
|
82 | }
|
83 |
|
84 | if (filepath in configGroups) {
|
85 | debugLog('Found existing config "%s" from "%s"!', filepath, cwd)
|
86 |
|
87 | configGroups[filepath].files.push(...files)
|
88 | } else {
|
89 | debugLog('Found new config "%s" from "%s"!', filepath, cwd)
|
90 |
|
91 | const validatedConfig = validateConfig(config, filepath, logger)
|
92 | configGroups[filepath] = { config: validatedConfig, files }
|
93 | }
|
94 | }
|
95 |
|
96 |
|
97 | await searchConfig(cwd)
|
98 |
|
99 |
|
100 | await Promise.all(Object.entries(filesByDir).map(([dir, files]) => searchConfig(dir, files)))
|
101 |
|
102 | debugLog('Grouped staged files into %d groups!', Object.keys(configGroups).length)
|
103 |
|
104 | return configGroups
|
105 | }
|