UNPKG

1.89 kBJavaScriptView Raw
1'use strict'
2
3const debug = require('debug')('lint-staged:chunkFiles')
4const normalize = require('normalize-path')
5const path = require('path')
6
7/**
8 * Chunk array into sub-arrays
9 * @param {Array} arr
10 * @param {Number} chunkCount
11 * @retuns {Array<Array>}
12 */
13function chunkArray(arr, chunkCount) {
14 if (chunkCount === 1) return [arr]
15 const chunked = []
16 let position = 0
17 for (let i = 0; i < chunkCount; i++) {
18 const chunkLength = Math.ceil((arr.length - position) / (chunkCount - i))
19 chunked.push([])
20 chunked[i] = arr.slice(position, chunkLength + position)
21 position += chunkLength
22 }
23 return chunked
24}
25
26/**
27 * Chunk files into sub-arrays based on the length of the resulting argument string
28 * @param {Object} opts
29 * @param {Array<String>} opts.files
30 * @param {String} [opts.baseDir] The optional base directory to resolve relative paths.
31 * @param {number} [opts.maxArgLength] the maximum argument string length
32 * @param {Boolean} [opts.relative] whether files are relative to `gitDir` or should be resolved as absolute
33 * @returns {Array<Array<String>>}
34 */
35module.exports = function chunkFiles({ files, baseDir, maxArgLength = null, relative = false }) {
36 const normalizedFiles = files.map((file) =>
37 normalize(relative || !baseDir ? file : path.resolve(baseDir, file))
38 )
39
40 if (!maxArgLength) {
41 debug('Skip chunking files because of undefined maxArgLength')
42 return [normalizedFiles] // wrap in an array to return a single chunk
43 }
44
45 const fileListLength = normalizedFiles.join(' ').length
46 debug(
47 `Resolved an argument string length of ${fileListLength} characters from ${normalizedFiles.length} files`
48 )
49 const chunkCount = Math.min(Math.ceil(fileListLength / maxArgLength), normalizedFiles.length)
50 debug(`Creating ${chunkCount} chunks for maxArgLength of ${maxArgLength}`)
51 return chunkArray(normalizedFiles, chunkCount)
52}