( rootDir: string, options: BfsFileSearchOptions, )
| 33 | * @returns A promise that resolves to an array of paths where the file was found. |
| 34 | */ |
| 35 | export async function bfsFileSearch( |
| 36 | rootDir: string, |
| 37 | options: BfsFileSearchOptions, |
| 38 | ): Promise<string[]> { |
| 39 | const { |
| 40 | fileName, |
| 41 | ignoreDirs = [], |
| 42 | maxDirs = Infinity, |
| 43 | debug = false, |
| 44 | fileService, |
| 45 | } = options; |
| 46 | const foundFiles: string[] = []; |
| 47 | const queue: string[] = [rootDir]; |
| 48 | const visited = new Set<string>(); |
| 49 | let scannedDirCount = 0; |
| 50 | let queueHead = 0; // Pointer-based queue head to avoid expensive splice operations |
| 51 | |
| 52 | // Convert ignoreDirs array to Set for O(1) lookup performance |
| 53 | const ignoreDirsSet = new Set(ignoreDirs); |
| 54 | |
| 55 | // Process directories in parallel batches for maximum performance |
| 56 | const PARALLEL_BATCH_SIZE = 15; // Parallel processing batch size for optimal performance |
| 57 | |
| 58 | while (queueHead < queue.length && scannedDirCount < maxDirs) { |
| 59 | // Fill batch with unvisited directories up to the desired size |
| 60 | const batchSize = Math.min(PARALLEL_BATCH_SIZE, maxDirs - scannedDirCount); |
| 61 | const currentBatch = []; |
| 62 | while (currentBatch.length < batchSize && queueHead < queue.length) { |
| 63 | const currentDir = queue[queueHead]; |
| 64 | queueHead++; |
| 65 | if (!visited.has(currentDir)) { |
| 66 | visited.add(currentDir); |
| 67 | currentBatch.push(currentDir); |
| 68 | } |
| 69 | } |
| 70 | scannedDirCount += currentBatch.length; |
| 71 | |
| 72 | if (currentBatch.length === 0) continue; |
| 73 | |
| 74 | if (debug) { |
| 75 | logger.debug( |
| 76 | `Scanning [${scannedDirCount}/${maxDirs}]: batch of ${currentBatch.length}`, |
| 77 | ); |
| 78 | } |
| 79 | |
| 80 | // Read directories in parallel instead of one by one |
| 81 | const readPromises = currentBatch.map(async (currentDir) => { |
| 82 | try { |
| 83 | const entries = await fs.readdir(currentDir, { withFileTypes: true }); |
| 84 | return { currentDir, entries }; |
| 85 | } catch (error) { |
| 86 | // Warn user that a directory could not be read, as this affects search results. |
| 87 | const message = (error as Error)?.message ?? 'Unknown error'; |
| 88 | console.warn( |
| 89 | `[WARN] Skipping unreadable directory: ${currentDir} (${message})`, |
| 90 | ); |
| 91 | if (debug) { |
| 92 | logger.debug(`Full error for ${currentDir}:`, error); |
no test coverage detected