UNPKG

2.54 kBJavaScriptView Raw
1'use strict'
2
3const cliTruncate = require('cli-truncate')
4const debug = require('debug')('lint-staged:make-cmd-tasks')
5
6const resolveTaskFn = require('./resolveTaskFn')
7const { createError } = require('./validateConfig')
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 {Array<string>} options.files
32 * @param {string} options.gitDir
33 * @param {string} options.renderer
34 * @param {Boolean} shell
35 * @param {Boolean} verbose
36 */
37const makeCmdTasks = async ({ commands, files, gitDir, renderer, shell, verbose }) => {
38 debug('Creating listr tasks for commands %o', commands)
39 const commandArray = Array.isArray(commands) ? commands : [commands]
40 const cmdTasks = []
41
42 for (const cmd of commandArray) {
43 // command function may return array of commands that already include `stagedFiles`
44 const isFn = typeof cmd === 'function'
45 const resolved = isFn ? await cmd(files) : cmd
46
47 const resolvedArray = Array.isArray(resolved) ? resolved : [resolved] // Wrap non-array command as array
48
49 for (const command of resolvedArray) {
50 // If the function linter didn't return string | string[] it won't work
51 // Do the validation here instead of `validateConfig` to skip evaluating the function multiple times
52 if (isFn && typeof command !== 'string') {
53 throw new Error(
54 createError(
55 '[Function]',
56 'Function task should return a string or an array of strings',
57 resolved
58 )
59 )
60 }
61
62 // Truncate title to single line based on renderer
63 const title = cliTruncate(command, getTitleLength(renderer))
64 const task = resolveTaskFn({ command, files, gitDir, isFn, shell, verbose })
65 cmdTasks.push({ title, command, task })
66 }
67 }
68
69 return cmdTasks
70}
71
72module.exports = makeCmdTasks