UNPKG

1.87 kBJavaScriptView Raw
1'use strict'
2
3const micromatch = require('micromatch')
4const normalize = require('normalize-path')
5const path = require('path')
6
7const debug = require('debug')('lint-staged:gen-tasks')
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 */
19module.exports = function generateTasks({
20 config,
21 cwd = process.cwd(),
22 gitDir,
23 files,
24 relative = false
25}) {
26 debug('Generating linter tasks')
27
28 const absoluteFiles = files.map(file => normalize(path.resolve(gitDir, file)))
29 const relativeFiles = absoluteFiles.map(file => normalize(path.relative(cwd, file)))
30
31 return Object.entries(config).map(([pattern, commands]) => {
32 const isParentDirPattern = pattern.startsWith('../')
33
34 const fileList = micromatch(
35 relativeFiles
36 // Only worry about children of the CWD unless the pattern explicitly
37 // specifies that it concerns a parent directory.
38 .filter(file => {
39 if (isParentDirPattern) return true
40 return !file.startsWith('..') && !path.isAbsolute(file)
41 }),
42 pattern,
43 {
44 cwd,
45 dot: true,
46 // If pattern doesn't look like a path, enable `matchBase` to
47 // match against filenames in every directory. This makes `*.js`
48 // match both `test.js` and `subdirectory/test.js`.
49 matchBase: !pattern.includes('/')
50 }
51 ).map(file => normalize(relative ? file : path.resolve(cwd, file)))
52
53 const task = { pattern, commands, fileList }
54 debug('Generated task: \n%O', task)
55
56 return task
57 })
58}