UNPKG

1.83 kBJavaScriptView Raw
1import path from 'node:path'
2
3import debug from 'debug'
4import micromatch from 'micromatch'
5import normalize from 'normalize-path'
6
7const debugLog = debug('lint-staged:generateTasks')
8
9/**
10 * Generates all task commands, and filelist
11 *
12 * @param {object} options
13 * @param {Object} [options.config] - Task configuration
14 * @param {Object} [options.cwd] - Current working directory
15 * @param {boolean} [options.gitDir] - Git root directory
16 * @param {boolean} [options.files] - Staged filepaths
17 * @param {boolean} [options.relative] - Whether filepaths to should be relative to gitDir
18 */
19export const generateTasks = ({ config, cwd = process.cwd(), files, relative = false }) => {
20 debugLog('Generating linter tasks')
21
22 const relativeFiles = files.map((file) => normalize(path.relative(cwd, file)))
23
24 return Object.entries(config).map(([pattern, commands]) => {
25 const isParentDirPattern = pattern.startsWith('../')
26
27 // Only worry about children of the CWD unless the pattern explicitly
28 // specifies that it concerns a parent directory.
29 const filteredFiles = relativeFiles.filter((file) => {
30 if (isParentDirPattern) return true
31 return !file.startsWith('..') && !path.isAbsolute(file)
32 })
33
34 const matches = micromatch(filteredFiles, pattern, {
35 cwd,
36 dot: true,
37 // If the pattern doesn't look like a path, enable `matchBase` to
38 // match against filenames in every directory. This makes `*.js`
39 // match both `test.js` and `subdirectory/test.js`.
40 matchBase: !pattern.includes('/'),
41 posixSlashes: true,
42 strictBrackets: true,
43 })
44
45 const fileList = matches.map((file) => normalize(relative ? file : path.resolve(cwd, file)))
46
47 const task = { pattern, commands, fileList }
48 debugLog('Generated task: \n%O', task)
49
50 return task
51 })
52}