|
2 | 2 |
|
3 | 3 | import fs from "node:fs"; |
4 | 4 | import path from "node:path"; |
| 5 | +import { spawnSync } from "node:child_process"; |
| 6 | + |
| 7 | +const DEFAULT_MAX_BYTES = 256 * 1024; |
| 8 | +const DEFAULT_MAX_FILES = 50; |
| 9 | + |
| 10 | +function toGitPath(filePath) { |
| 11 | + return filePath.split(path.sep).join("/"); |
| 12 | +} |
| 13 | + |
| 14 | +function isInsidePath(parent, candidate) { |
| 15 | + const relative = path.relative(parent, candidate); |
| 16 | + return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); |
| 17 | +} |
| 18 | + |
| 19 | +function isGitignored(filePath, cwd) { |
| 20 | + try { |
| 21 | + const result = fs.statSync(filePath); |
| 22 | + if (!result.isFile()) return false; |
| 23 | + |
| 24 | + const relativePath = path.relative(cwd, filePath); |
| 25 | + if (!isInsidePath(cwd, filePath)) return false; |
| 26 | + |
| 27 | + const checked = spawnSync("git", ["check-ignore", "-q", "--", toGitPath(relativePath)], { |
| 28 | + cwd, |
| 29 | + stdio: "ignore", |
| 30 | + }); |
| 31 | + return checked.status === 0; |
| 32 | + } catch { |
| 33 | + return false; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function isBinaryFile(filePath) { |
| 38 | + let fd = null; |
| 39 | + try { |
| 40 | + const buffer = Buffer.alloc(8192); |
| 41 | + fd = fs.openSync(filePath, "r"); |
| 42 | + const bytesRead = fs.readSync(fd, buffer, 0, 8192, 0); |
| 43 | + for (let i = 0; i < bytesRead; i++) { |
| 44 | + if (buffer[i] === 0) return true; |
| 45 | + } |
| 46 | + return false; |
| 47 | + } catch { |
| 48 | + return false; |
| 49 | + } finally { |
| 50 | + if (fd !== null) { |
| 51 | + try { |
| 52 | + fs.closeSync(fd); |
| 53 | + } catch { |
| 54 | + // best-effort |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Collect file contents for a set of paths within cwd. |
| 62 | + * Respects per-file and total size caps, skips binary files and broken symlinks. |
| 63 | + * |
| 64 | + * @param {string} cwd - Working directory |
| 65 | + * @param {string[]} targetPaths - Relative paths to include |
| 66 | + * @param {{ maxBytes?: number, maxFiles?: number }} opts |
| 67 | + * @returns {Promise<{ content: string, files: string[], totalBytes: number, overflowed: boolean, overflowedBytes: boolean, overflowedFiles: boolean }>} |
| 68 | + */ |
| 69 | +export async function collectFolderContext(cwd, targetPaths, opts = {}) { |
| 70 | + const maxBytes = Number.isFinite(opts.maxBytes) ? opts.maxBytes : DEFAULT_MAX_BYTES; |
| 71 | + const maxFiles = Number.isFinite(opts.maxFiles) ? opts.maxFiles : DEFAULT_MAX_FILES; |
| 72 | + const root = path.resolve(cwd); |
| 73 | + let realRoot; |
| 74 | + try { |
| 75 | + realRoot = fs.realpathSync(root); |
| 76 | + } catch { |
| 77 | + realRoot = root; |
| 78 | + } |
| 79 | + |
| 80 | + const result = { |
| 81 | + content: "", |
| 82 | + files: [], |
| 83 | + totalBytes: 0, |
| 84 | + overflowed: false, |
| 85 | + overflowedBytes: false, |
| 86 | + overflowedFiles: false, |
| 87 | + }; |
| 88 | + |
| 89 | + const visited = new Set(); |
| 90 | + const pending = []; |
| 91 | + |
| 92 | + for (const targetPath of targetPaths) { |
| 93 | + const resolvedPath = path.resolve(cwd, targetPath); |
| 94 | + if (!isInsidePath(root, resolvedPath)) continue; |
| 95 | + pending.push(resolvedPath); |
| 96 | + } |
| 97 | + |
| 98 | + while (pending.length > 0) { |
| 99 | + if (result.files.length >= maxFiles) { |
| 100 | + result.overflowed = true; |
| 101 | + result.overflowedFiles = true; |
| 102 | + break; |
| 103 | + } |
| 104 | + |
| 105 | + const resolvedPath = pending.shift(); |
| 106 | + |
| 107 | + try { |
| 108 | + const stat = fs.lstatSync(resolvedPath); |
| 109 | + let realPath = resolvedPath; |
| 110 | + |
| 111 | + if (stat.isSymbolicLink()) { |
| 112 | + try { |
| 113 | + realPath = fs.realpathSync(resolvedPath); |
| 114 | + } catch { |
| 115 | + continue; |
| 116 | + } |
| 117 | + } else { |
| 118 | + realPath = fs.realpathSync(resolvedPath); |
| 119 | + } |
| 120 | + |
| 121 | + if (!isInsidePath(realRoot, realPath)) continue; |
| 122 | + if (visited.has(realPath)) continue; |
| 123 | + visited.add(realPath); |
| 124 | + if (path.basename(realPath) === ".git") continue; |
| 125 | + |
| 126 | + const realStat = fs.statSync(realPath); |
| 127 | + if (realStat.isDirectory()) { |
| 128 | + const entries = fs.readdirSync(realPath, { withFileTypes: true }) |
| 129 | + .sort((a, b) => a.name.localeCompare(b.name)); |
| 130 | + for (let i = entries.length - 1; i >= 0; i -= 1) { |
| 131 | + pending.unshift(path.join(realPath, entries[i].name)); |
| 132 | + } |
| 133 | + } else if (realStat.isFile()) { |
| 134 | + if (isBinaryFile(realPath)) continue; |
| 135 | + |
| 136 | + const relativePath = path.relative(root, realPath); |
| 137 | + if (!isInsidePath(root, realPath)) continue; |
| 138 | + if (isGitignored(realPath, root)) continue; |
| 139 | + |
| 140 | + const content = fs.readFileSync(realPath, "utf8"); |
| 141 | + const fileBytes = Buffer.byteLength(content, "utf8"); |
| 142 | + |
| 143 | + if (result.totalBytes + fileBytes > maxBytes) { |
| 144 | + result.overflowed = true; |
| 145 | + result.overflowedBytes = true; |
| 146 | + const remaining = maxBytes - result.totalBytes; |
| 147 | + if (remaining > 0) { |
| 148 | + const truncated = truncateUtf8(content, remaining); |
| 149 | + result.content += `// File: ${toGitPath(relativePath)} (truncated)\n${truncated}\n\n`; |
| 150 | + result.totalBytes += Buffer.byteLength(truncated, "utf8"); |
| 151 | + result.files.push(toGitPath(relativePath)); |
| 152 | + } |
| 153 | + break; |
| 154 | + } |
| 155 | + |
| 156 | + result.content += `// File: ${toGitPath(relativePath)}\n${content}\n\n`; |
| 157 | + result.totalBytes += fileBytes; |
| 158 | + result.files.push(toGitPath(relativePath)); |
| 159 | + |
| 160 | + if (result.files.length >= maxFiles) { |
| 161 | + if (pending.length > 0) { |
| 162 | + result.overflowed = true; |
| 163 | + result.overflowedFiles = true; |
| 164 | + } |
| 165 | + break; |
| 166 | + } |
| 167 | + } |
| 168 | + } catch (err) { |
| 169 | + if (err?.code !== "ENOENT") { |
| 170 | + // Skip files that don't exist |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + return result; |
| 176 | +} |
| 177 | + |
| 178 | +function truncateUtf8(text, maxBytes) { |
| 179 | + if (!text) return text; |
| 180 | + const buf = Buffer.from(text, "utf8"); |
| 181 | + if (buf.length <= maxBytes) return text; |
| 182 | + return buf.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD$/, ""); |
| 183 | +} |
5 | 184 |
|
6 | 185 | /** |
7 | 186 | * Ensure a directory exists (recursive mkdir). |
|
0 commit comments