1 | import path from 'path'
|
2 |
|
3 | import debug from 'debug'
|
4 |
|
5 | import { ConfigObjectSymbol } from './searchConfigs.js'
|
6 |
|
7 | const debugLog = debug('lint-staged:groupFilesByConfig')
|
8 |
|
9 | export const groupFilesByConfig = async ({ configs, files }) => {
|
10 | debugLog('Grouping %d files by %d configurations', files.length, Object.keys(configs).length)
|
11 |
|
12 | const filesSet = new Set(files)
|
13 | const filesByConfig = {}
|
14 |
|
15 |
|
16 | for (const filepath of Reflect.ownKeys(configs)) {
|
17 | const config = configs[filepath]
|
18 |
|
19 |
|
20 | if (filepath === ConfigObjectSymbol) {
|
21 | filesByConfig[filepath] = { config, files }
|
22 | break
|
23 | }
|
24 |
|
25 | const dir = path.normalize(path.dirname(filepath))
|
26 |
|
27 |
|
28 | const isInsideDir = (file) => {
|
29 | const relative = path.relative(dir, file)
|
30 | return relative && !relative.startsWith('..') && !path.isAbsolute(relative)
|
31 | }
|
32 |
|
33 |
|
34 | const includeAllFiles = Object.keys(config).some((glob) => glob.startsWith('..'))
|
35 |
|
36 | const scopedFiles = new Set(includeAllFiles ? filesSet : undefined)
|
37 |
|
38 | |
39 |
|
40 |
|
41 |
|
42 | if (!includeAllFiles) {
|
43 | filesSet.forEach((file) => {
|
44 | if (isInsideDir(file)) {
|
45 | scopedFiles.add(file)
|
46 | }
|
47 | })
|
48 | }
|
49 |
|
50 |
|
51 | scopedFiles.forEach((file) => {
|
52 | filesSet.delete(file)
|
53 | })
|
54 |
|
55 | filesByConfig[filepath] = { config, files: Array.from(scopedFiles) }
|
56 | }
|
57 |
|
58 | return filesByConfig
|
59 | }
|