| 46 | let matchCount = 0 |
| 47 | |
| 48 | const walk = (dir: string): void => { |
| 49 | if (matchCount >= MAX_RESULTS) return |
| 50 | let dirents: fs.Dirent[] |
| 51 | try { |
| 52 | dirents = fs.readdirSync(dir, { withFileTypes: true }) |
| 53 | } catch { |
| 54 | return |
| 55 | } |
| 56 | for (const dirent of dirents) { |
| 57 | if (matchCount >= MAX_RESULTS) return |
| 58 | const full = path.join(dir, dirent.name) |
| 59 | if (dirent.isDirectory()) { |
| 60 | if (!IGNORED_DIRS.has(dirent.name) && !dirent.name.startsWith(".")) walk(full) |
| 61 | continue |
| 62 | } |
| 63 | // picomatch only understands forward slashes, so normalize Windows paths. |
| 64 | const rel = path.relative(dirPath, full).split(path.sep).join("/") |
| 65 | if (!isMatch(rel)) continue |
| 66 | let stat: fs.Stats |
| 67 | try { |
| 68 | stat = fs.statSync(full) |
| 69 | } catch { |
| 70 | continue |
| 71 | } |
| 72 | if (stat.size > MAX_FILE_SIZE) continue |
| 73 | |
| 74 | let content: string |
| 75 | try { |
| 76 | content = fs.readFileSync(full, "utf8") |
| 77 | } catch { |
| 78 | continue |
| 79 | } |
| 80 | if (content.includes("\u0000")) continue // binary |
| 81 | |
| 82 | const lines = content.split("\n") |
| 83 | const fileMatches: string[] = [] |
| 84 | for (let i = 0; i < lines.length && matchCount < MAX_RESULTS; i++) { |
| 85 | if (regex.test(lines[i])) { |
| 86 | matchCount++ |
| 87 | const lineText = lines[i].length > MAX_LINE_LENGTH ? lines[i].slice(0, MAX_LINE_LENGTH) + "…" : lines[i] |
| 88 | fileMatches.push(` ${i + 1}: ${lineText}`) |
| 89 | } |
| 90 | } |
| 91 | if (fileMatches.length > 0) { |
| 92 | results.push(`${rel}\n${fileMatches.join("\n")}`) |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | walk(dirPath) |
| 98 | |