2079b5f3b4b7354f763a8d9681a02ab08328e41601194eddc857ffaaebdbcd6fdf8f6e374bc3a0f635af2ed37de8680b11f6eaea9fd0d6216c018a3186fa11 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict'
  2. const micromatch = require('micromatch')
  3. const normalize = require('normalize-path')
  4. const path = require('path')
  5. const debug = require('debug')('lint-staged:gen-tasks')
  6. /**
  7. * Generates all task commands, and filelist
  8. *
  9. * @param {object} options
  10. * @param {Object} [options.config] - Task configuration
  11. * @param {Object} [options.cwd] - Current working directory
  12. * @param {boolean} [options.gitDir] - Git root directory
  13. * @param {boolean} [options.files] - Staged filepaths
  14. * @param {boolean} [options.relative] - Whether filepaths to should be relative to gitDir
  15. */
  16. module.exports = function generateTasks({
  17. config,
  18. cwd = process.cwd(),
  19. gitDir,
  20. files,
  21. relative = false,
  22. }) {
  23. debug('Generating linter tasks')
  24. const absoluteFiles = files.map((file) => normalize(path.resolve(gitDir, file)))
  25. const relativeFiles = absoluteFiles.map((file) => normalize(path.relative(cwd, file)))
  26. return Object.entries(config).map(([pattern, commands]) => {
  27. const isParentDirPattern = pattern.startsWith('../')
  28. const fileList = micromatch(
  29. relativeFiles
  30. // Only worry about children of the CWD unless the pattern explicitly
  31. // specifies that it concerns a parent directory.
  32. .filter((file) => {
  33. if (isParentDirPattern) return true
  34. return !file.startsWith('..') && !path.isAbsolute(file)
  35. }),
  36. pattern,
  37. {
  38. cwd,
  39. dot: true,
  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. }
  45. ).map((file) => normalize(relative ? file : path.resolve(cwd, file)))
  46. const task = { pattern, commands, fileList }
  47. debug('Generated task: \n%O', task)
  48. return task
  49. })
  50. }