-
-
Notifications
You must be signed in to change notification settings - Fork 412
/
chunkFiles.js
40 lines (37 loc) · 1.36 KB
/
chunkFiles.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'use strict'
const normalize = require('normalize-path')
const path = require('path')
/**
* Chunk array into sub-arrays
* @param {Array} arr
* @param {Number} chunkCount
* @retuns {Array<Array>}
*/
function chunkArray(arr, chunkCount) {
if (chunkCount === 1) return [arr]
const chunked = []
let position = 0
for (let i = 0; i < chunkCount; i++) {
const chunkLength = Math.ceil((arr.length - position) / (chunkCount - i))
chunked.push([])
chunked[i] = arr.slice(position, chunkLength + position)
position += chunkLength
}
return chunked
}
/**
* Chunk files into sub-arrays based on the length of the resulting argument string
* @param {Object} opts
* @param {Array<String>} opts.files
* @param {String} opts.gitDir
* @param {number} [opts.maxArgLength] the maximum argument string length
* @param {Boolean} [opts.relative] whether files are relative to `gitDir` or should be resolved as absolute
* @returns {Array<Array<String>>}
*/
module.exports = function chunkFiles({ files, gitDir, maxArgLength = null, relative = false }) {
if (!maxArgLength) return [files]
const normalizedFiles = files.map(file => normalize(relative ? file : path.resolve(gitDir, file)))
const fileListLength = normalizedFiles.join(' ').length
const chunkCount = Math.min(Math.ceil(fileListLength / maxArgLength), files.length)
return chunkArray(files, chunkCount)
}