UNPKG

1.89 kBJavaScriptView Raw
1'use strict'
2
3const resolveTaskFn = require('./resolveTaskFn')
4const { createError } = require('./validateConfig')
5
6const debug = require('debug')('lint-staged:make-cmd-tasks')
7
8/**
9 * Creates and returns an array of listr tasks which map to the given commands.
10 *
11 * @param {object} options
12 * @param {Array<string|Function>|string|Function} options.commands
13 * @param {Array<string>} options.files
14 * @param {string} options.gitDir
15 * @param {Boolean} shell
16 */
17module.exports = async function makeCmdTasks({ commands, files, gitDir, shell }) {
18 debug('Creating listr tasks for commands %o', commands)
19 const commandArray = Array.isArray(commands) ? commands : [commands]
20 const cmdTasks = []
21
22 for (const cmd of commandArray) {
23 // command function may return array of commands that already include `stagedFiles`
24 const isFn = typeof cmd === 'function'
25 const resolved = isFn ? await cmd(files) : cmd
26
27 const resolvedArray = Array.isArray(resolved) ? resolved : [resolved] // Wrap non-array command as array
28
29 for (const command of resolvedArray) {
30 let title = isFn ? '[Function]' : command
31
32 if (isFn) {
33 // If the function linter didn't return string | string[] it won't work
34 // Do the validation here instead of `validateConfig` to skip evaluating the function multiple times
35 if (typeof command !== 'string') {
36 throw new Error(
37 createError(
38 title,
39 'Function task should return a string or an array of strings',
40 resolved
41 )
42 )
43 }
44
45 const [startOfFn] = command.split(' ')
46 title += ` ${startOfFn} ...` // Append function name, like `[Function] eslint ...`
47 }
48
49 cmdTasks.push({
50 title,
51 command,
52 task: resolveTaskFn({ command, files, gitDir, isFn, shell })
53 })
54 }
55 }
56
57 return cmdTasks
58}