UNPKG

1.74 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.gitDir
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, gitDir, maxArgLength = null, relative = false }) {
36 if (!maxArgLength) {
37 debug('Skip chunking files because of undefined maxArgLength')
38 return [files]
39 }
40
41 const normalizedFiles = files.map(file => normalize(relative ? file : path.resolve(gitDir, file)))
42 const fileListLength = normalizedFiles.join(' ').length
43 debug(
44 `Resolved an argument string length of ${fileListLength} characters from ${normalizedFiles.length} files`
45 )
46 const chunkCount = Math.min(Math.ceil(fileListLength / maxArgLength), normalizedFiles.length)
47 debug(`Creating ${chunkCount} chunks for maxArgLength of ${maxArgLength}`)
48 return chunkArray(files, chunkCount)
49}