Skip to content

Commit b392a9f

Browse files
committed
refactor: extract matchFiles and add unit tests
1 parent 687fc90 commit b392a9f

3 files changed

Lines changed: 454 additions & 20 deletions

File tree

lib/generateTasks.js

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import path from 'node:path'
22

3-
import picomatch from 'picomatch'
4-
53
import { createDebug } from './debug.js'
4+
import { matchFiles } from './matchFiles.js'
65
import { normalizePath } from './normalizePath.js'
76

87
const debugLog = createDebug('lint-staged:generateTasks')
@@ -30,28 +29,15 @@ export const generateTasks = ({ config, cwd = process.cwd(), files, relative = f
3029

3130
// Only worry about children of the CWD unless the pattern explicitly
3231
// specifies that it concerns a parent directory.
33-
const filteredFiles = relativeFiles.filter((file) => {
32+
const includedFiles = relativeFiles.filter((file) => {
3433
if (isParentDirPattern) return true
3534
return !file.filepath.startsWith('..') && !path.isAbsolute(file.filepath)
3635
})
3736

38-
const isMatch = picomatch(pattern, {
39-
cwd,
40-
dot: true,
41-
// If the pattern doesn't look like a path, enable `matchBase` to
42-
// match against filenames in every directory. This makes `*.js`
43-
// match both `test.js` and `subdirectory/test.js`.
44-
matchBase: !pattern.includes('/'),
45-
posixSlashes: true,
46-
strictBrackets: true,
47-
})
48-
49-
const fileList = filteredFiles
50-
.filter((file) => isMatch(file.filepath))
51-
.map((file) => ({
52-
filepath: normalizePath(relative ? file.filepath : path.resolve(cwd, file.filepath)),
53-
status: file.status,
54-
}))
37+
const fileList = matchFiles(includedFiles, pattern, cwd).map((file) => ({
38+
filepath: normalizePath(relative ? file.filepath : path.resolve(cwd, file.filepath)),
39+
status: file.status,
40+
}))
5541

5642
const task = { pattern, commands, fileList }
5743
debugLog('Generated task: \n%O', task)

lib/matchFiles.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import picomatch from 'picomatch'
2+
3+
/**
4+
* Match list of files against a pattern.
5+
*
6+
* @param {string} pattern
7+
* @param {import('./getStagedFiles.js').StagedFile[]} files
8+
*/
9+
export const matchFiles = (files, pattern, cwd = process.cwd()) => {
10+
const isMatch = picomatch(pattern, {
11+
cwd,
12+
dot: true,
13+
// If the pattern doesn't look like a path, enable `matchBase` to
14+
// match against filenames in every directory. This makes `*.js`
15+
// match both `test.js` and `subdirectory/test.js`.
16+
matchBase: !pattern.includes('/'),
17+
posixSlashes: true,
18+
strictBrackets: true,
19+
})
20+
21+
return files.filter((file) => isMatch(file.filepath))
22+
}

0 commit comments

Comments
 (0)