* Process files for search or replace operations. * * @param {object} data - The data containing files, search, replace, and options. * @param {'search' | 'replace'} [mode='search'] - The mode of operation (search or replace).
(data, mode = "search")
| 36 | * @param {'search' | 'replace'} [mode='search'] - The mode of operation (search or replace). |
| 37 | */ |
| 38 | function processFiles(data, mode = "search") { |
| 39 | const process = mode === "search" ? searchInFile : replaceInFile; |
| 40 | const { files, search, replace, options } = data; |
| 41 | const { test: skip } = Skip(options); |
| 42 | const total = files.length; |
| 43 | let count = 0; |
| 44 | let cursor = 0; |
| 45 | let active = 0; |
| 46 | let pumpScheduled = false; |
| 47 | |
| 48 | if (!total) { |
| 49 | done(1, mode); |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | pump(); |
| 54 | |
| 55 | /** |
| 56 | * Starts more file reads without flooding the main thread. |
| 57 | */ |
| 58 | function pump() { |
| 59 | pumpScheduled = false; |
| 60 | while (active < MAX_CONCURRENT_FILE_READS && cursor < total) { |
| 61 | const file = files[cursor++]; |
| 62 | active += 1; |
| 63 | processFile(file); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | function schedulePump() { |
| 68 | if (pumpScheduled) return; |
| 69 | pumpScheduled = true; |
| 70 | Promise.resolve().then(pump); |
| 71 | } |
| 72 | |
| 73 | function finishOne() { |
| 74 | active -= 1; |
| 75 | done(++count / total, mode); |
| 76 | schedulePump(); |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * Process a file for search or replace operation. |
| 81 | * @param {object} file |
| 82 | */ |
| 83 | function processFile(file) { |
| 84 | if (skip(file)) { |
| 85 | finishOne(); |
| 86 | return; |
| 87 | } |
| 88 | |
| 89 | getFile(file.url, (res, err) => { |
| 90 | if (err) { |
| 91 | finishOne(); |
| 92 | return; |
| 93 | } |
| 94 | |
| 95 | process({ file, content: res, search, replace, options }); |