UNPKG

1.73 kBJavaScriptView Raw
1'use strict'
2
3const micromatch = require('micromatch')
4const path = require('path')
5
6const debug = require('debug')('lint-staged:gen-tasks')
7
8/**
9 * Test if `child` path is inside `parent` path
10 * https://stackoverflow.com/a/45242825
11 *
12 * @param {String} parent
13 * @param {String} child
14 * @returns {Boolean}
15 */
16const isPathInside = (parent, child) => {
17 const relative = path.relative(parent, child)
18 return relative && !relative.startsWith('..') && !path.isAbsolute(relative)
19}
20
21module.exports = async function generateTasks(linters, gitDir, stagedRelFiles) {
22 debug('Generating linter tasks')
23
24 const cwd = process.cwd()
25 const stagedFiles = stagedRelFiles.map(file => path.resolve(gitDir, file))
26
27 return Object.keys(linters).map(pattern => {
28 const isParentDirPattern = pattern.startsWith('../')
29 const commands = linters[pattern]
30
31 const fileList = micromatch(
32 stagedFiles
33 // Only worry about children of the CWD unless the pattern explicitly
34 // specifies that it concerns a parent directory.
35 .filter(file => isParentDirPattern || isPathInside(cwd, file))
36 // Make the paths relative to CWD for filtering
37 .map(file => path.relative(cwd, file)),
38 pattern,
39 {
40 // If pattern doesn't look like a path, enable `matchBase` to
41 // match against filenames in every directory. This makes `*.js`
42 // match both `test.js` and `subdirectory/test.js`.
43 matchBase: !pattern.includes('/'),
44 dot: true
45 }
46 ).map(file =>
47 // Return absolute path after the filter is run
48 path.resolve(cwd, file)
49 )
50
51 const task = { pattern, commands, fileList }
52 debug('Generated task: \n%O', task)
53
54 return task
55 })
56}