UNPKG

1.83 kBJavaScriptView Raw
1import path from '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(([rawPattern, commands]) => {
25 let pattern = rawPattern
26
27 const isParentDirPattern = pattern.startsWith('../')
28
29 // Only worry about children of the CWD unless the pattern explicitly
30 // specifies that it concerns a parent directory.
31 const filteredFiles = relativeFiles.filter((file) => {
32 if (isParentDirPattern) return true
33 return !file.startsWith('..') && !path.isAbsolute(file)
34 })
35
36 const matches = micromatch(filteredFiles, pattern, {
37 cwd,
38 dot: true,
39 // If the pattern doesn't look like a path, enable `matchBase` to
40 // match against filenames in every directory. This makes `*.js`
41 // match both `test.js` and `subdirectory/test.js`.
42 matchBase: !pattern.includes('/'),
43 strictBrackets: true,
44 })
45
46 const fileList = matches.map((file) => normalize(relative ? file : path.resolve(cwd, file)))
47
48 const task = { pattern, commands, fileList }
49 debugLog('Generated task: \n%O', task)
50
51 return task
52 })
53}