UNPKG

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