|
3 | 3 | import fs from "node:fs"; |
4 | 4 | import path from "node:path"; |
5 | 5 |
|
| 6 | +const DEFAULT_MAX_BYTES = 256 * 1024; |
| 7 | +const DEFAULT_MAX_FILES = 50; |
| 8 | + |
| 9 | +function isGitignored(filePath, cwd) { |
| 10 | + try { |
| 11 | + const result = fs.statSync(filePath); |
| 12 | + if (!result.isFile()) return false; |
| 13 | + const dir = path.dirname(filePath); |
| 14 | + const gitignorePath = path.join(dir, ".gitignore"); |
| 15 | + if (!fs.existsSync(gitignorePath)) { |
| 16 | + return isGitignored(dir, cwd); |
| 17 | + } |
| 18 | + const patterns = fs.readFileSync(gitignorePath, "utf8").split("\n"); |
| 19 | + const relativePath = path.relative(cwd, filePath); |
| 20 | + for (const pattern of patterns) { |
| 21 | + const trimmed = pattern.trim(); |
| 22 | + if (!trimmed || trimmed.startsWith("#")) continue; |
| 23 | + const glob = trimmed.replace(/\/$/, ""); |
| 24 | + if (glob === relativePath || relativePath.startsWith(glob + "/")) { |
| 25 | + return true; |
| 26 | + } |
| 27 | + } |
| 28 | + return false; |
| 29 | + } catch { |
| 30 | + return false; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +function isBinaryFile(filePath) { |
| 35 | + try { |
| 36 | + const buffer = Buffer.alloc(8192); |
| 37 | + const fd = fs.openSync(filePath, "r"); |
| 38 | + const bytesRead = fs.readSync(fd, buffer, 0, 8192, 0); |
| 39 | + fs.closeSync(fd); |
| 40 | + for (let i = 0; i < bytesRead; i++) { |
| 41 | + if (buffer[i] === 0) return true; |
| 42 | + } |
| 43 | + return false; |
| 44 | + } catch { |
| 45 | + return false; |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Collect file contents for a set of paths within cwd. |
| 51 | + * Respects per-file and total size caps, skips binary files and broken symlinks. |
| 52 | + * |
| 53 | + * @param {string} cwd - Working directory |
| 54 | + * @param {string[]} targetPaths - Relative paths to include |
| 55 | + * @param {{ maxBytes?: number, maxFiles?: number }} opts |
| 56 | + * @returns {Promise<{ content: string, files: string[], totalBytes: number, overflowed: boolean }>} |
| 57 | + */ |
| 58 | +export async function collectFolderContext(cwd, targetPaths, opts = {}) { |
| 59 | + const maxBytes = Number.isFinite(opts.maxBytes) ? opts.maxBytes : DEFAULT_MAX_BYTES; |
| 60 | + const maxFiles = Number.isFinite(opts.maxFiles) ? opts.maxFiles : DEFAULT_MAX_FILES; |
| 61 | + |
| 62 | + const result = { |
| 63 | + content: "", |
| 64 | + files: [], |
| 65 | + totalBytes: 0, |
| 66 | + overflowed: false, |
| 67 | + }; |
| 68 | + |
| 69 | + const visited = new Set(); |
| 70 | + |
| 71 | + for (const targetPath of targetPaths) { |
| 72 | + const resolvedPath = path.resolve(cwd, targetPath); |
| 73 | + |
| 74 | + if (!resolvedPath.startsWith(path.resolve(cwd))) { |
| 75 | + continue; |
| 76 | + } |
| 77 | + |
| 78 | + if (visited.has(resolvedPath)) continue; |
| 79 | + visited.add(resolvedPath); |
| 80 | + |
| 81 | + try { |
| 82 | + const stat = fs.lstatSync(resolvedPath); |
| 83 | + |
| 84 | + if (stat.isSymbolicLink()) { |
| 85 | + try { |
| 86 | + fs.statSync(resolvedPath); |
| 87 | + } catch { |
| 88 | + continue; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + if (stat.isDirectory()) { |
| 93 | + const entries = fs.readdirSync(resolvedPath, { withFileTypes: true }); |
| 94 | + for (const entry of entries) { |
| 95 | + if (result.files.length >= maxFiles) break; |
| 96 | + const entryPath = path.join(resolvedPath, entry.name); |
| 97 | + if (visited.has(entryPath)) continue; |
| 98 | + visited.add(entryPath); |
| 99 | + } |
| 100 | + } else if (stat.isFile()) { |
| 101 | + if (isBinaryFile(resolvedPath)) continue; |
| 102 | + |
| 103 | + const relativePath = path.relative(cwd, resolvedPath); |
| 104 | + if (isGitignored(resolvedPath, cwd)) continue; |
| 105 | + |
| 106 | + const content = fs.readFileSync(resolvedPath, "utf8"); |
| 107 | + const fileBytes = Buffer.byteLength(content, "utf8"); |
| 108 | + |
| 109 | + if (result.totalBytes + fileBytes > maxBytes) { |
| 110 | + result.overflowed = true; |
| 111 | + const remaining = maxBytes - result.totalBytes; |
| 112 | + if (remaining > 0) { |
| 113 | + const truncated = truncateUtf8(content, remaining); |
| 114 | + result.content += `// File: ${relativePath} (truncated)\n${truncated}\n\n`; |
| 115 | + result.totalBytes += Buffer.byteLength(truncated, "utf8"); |
| 116 | + } |
| 117 | + break; |
| 118 | + } |
| 119 | + |
| 120 | + result.content += `// File: ${relativePath}\n${content}\n\n`; |
| 121 | + result.totalBytes += fileBytes; |
| 122 | + result.files.push(relativePath); |
| 123 | + |
| 124 | + if (result.files.length >= maxFiles) { |
| 125 | + break; |
| 126 | + } |
| 127 | + } |
| 128 | + } catch (err) { |
| 129 | + if (err?.code !== "ENOENT") { |
| 130 | + // Skip files that don't exist |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + return result; |
| 136 | +} |
| 137 | + |
| 138 | +function truncateUtf8(text, maxBytes) { |
| 139 | + if (!text) return text; |
| 140 | + const buf = Buffer.from(text, "utf8"); |
| 141 | + if (buf.length <= maxBytes) return text; |
| 142 | + return buf.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD$/, ""); |
| 143 | +} |
| 144 | + |
6 | 145 | /** |
7 | 146 | * Ensure a directory exists (recursive mkdir). |
8 | 147 | * @param {string} dirPath |
|
0 commit comments