UNPKG

2.57 kBJavaScriptView Raw
1import cliTruncate from 'cli-truncate'
2import debug from 'debug'
3
4import { configurationError } from './messages.js'
5import { resolveTaskFn } from './resolveTaskFn.js'
6
7const debugLog = debug('lint-staged:makeCmdTasks')
8
9const STDOUT_COLUMNS_DEFAULT = 80
10
11const listrPrefixLength = {
12 update: ` X `.length, // indented task title where X is a checkmark or a cross (failure)
13 verbose: `[STARTED] `.length, // verbose renderer uses 7-letter STARTED/SUCCESS prefixes
14}
15
16/**
17 * Get length of title based on the number of available columns prefix length
18 * @param {string} renderer The name of the Listr renderer
19 * @returns {number}
20 */
21const getTitleLength = (renderer, columns = process.stdout.columns) => {
22 const prefixLength = listrPrefixLength[renderer] || 0
23 return (columns || STDOUT_COLUMNS_DEFAULT) - prefixLength
24}
25
26/**
27 * Creates and returns an array of listr tasks which map to the given commands.
28 *
29 * @param {object} options
30 * @param {Array<string|Function>|string|Function} options.commands
31 * @param {string} options.cwd
32 * @param {Array<string>} options.files
33 * @param {string} options.gitDir
34 * @param {string} options.renderer
35 * @param {Boolean} shell
36 * @param {Boolean} verbose
37 */
38export const makeCmdTasks = async ({ commands, cwd, files, gitDir, renderer, shell, verbose }) => {
39 debugLog('Creating listr tasks for commands %o', commands)
40 const commandArray = Array.isArray(commands) ? commands : [commands]
41 const cmdTasks = []
42
43 for (const cmd of commandArray) {
44 // command function may return array of commands that already include `stagedFiles`
45 const isFn = typeof cmd === 'function'
46 const resolved = isFn ? await cmd(files) : cmd
47
48 const resolvedArray = Array.isArray(resolved) ? resolved : [resolved] // Wrap non-array command as array
49
50 for (const command of resolvedArray) {
51 // If the function linter didn't return string | string[] it won't work
52 // Do the validation here instead of `validateConfig` to skip evaluating the function multiple times
53 if (isFn && typeof command !== 'string') {
54 throw new Error(
55 configurationError(
56 '[Function]',
57 'Function task should return a string or an array of strings',
58 resolved
59 )
60 )
61 }
62
63 // Truncate title to single line based on renderer
64 const title = cliTruncate(command, getTitleLength(renderer))
65 const task = resolveTaskFn({ command, cwd, files, gitDir, isFn, shell, verbose })
66 cmdTasks.push({ title, command, task })
67 }
68 }
69
70 return cmdTasks
71}