-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathfiles.ts
More file actions
312 lines (273 loc) · 7.91 KB
/
files.ts
File metadata and controls
312 lines (273 loc) · 7.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import ignore, { Ignore } from "ignore";
import { existsSync, readFileSync, promises as fsPromises } from "fs";
import * as path from "path";
const PROJECT_MARKERS = [
".git",
"package.json",
"Cargo.toml",
"go.mod",
"pyproject.toml",
"setup.py",
"requirements.txt",
"Gemfile",
"composer.json",
"pom.xml",
"build.gradle",
"CMakeLists.txt",
"Makefile",
".opencode",
];
export function hasProjectMarker(projectRoot: string): boolean {
for (const marker of PROJECT_MARKERS) {
if (existsSync(path.join(projectRoot, marker))) {
return true;
}
}
return false;
}
export interface SkippedFile {
path: string;
reason: "too_large" | "excluded" | "gitignore" | "no_match";
}
export interface CollectFilesResult {
files: Array<{ path: string; size: number }>;
skipped: SkippedFile[];
}
export function createIgnoreFilter(projectRoot: string): Ignore {
const ig = ignore();
const defaultIgnores = [
"node_modules",
".git",
"dist",
"build",
".next",
".nuxt",
"coverage",
"__pycache__",
"target",
"vendor",
".opencode",
".*",
"**/.*",
"**/.*/**",
"**/*build*/**",
];
ig.add(defaultIgnores);
const gitignorePath = path.join(projectRoot, ".gitignore");
if (existsSync(gitignorePath)) {
const gitignoreContent = readFileSync(gitignorePath, "utf-8");
ig.add(gitignoreContent);
}
return ig;
}
export function shouldIncludeFile(
filePath: string,
projectRoot: string,
includePatterns: string[],
excludePatterns: string[],
ignoreFilter: Ignore
): boolean {
const relativePath = path.relative(projectRoot, filePath);
// Exclude hidden files/folders (starting with .)
const pathParts = relativePath.split(path.sep);
for (const part of pathParts) {
if (part.startsWith(".") && part !== "." && part !== "..") {
return false;
}
// Exclude folders containing "build" in their name
if (part.toLowerCase().includes("build")) {
return false;
}
}
if (ignoreFilter.ignores(relativePath)) {
return false;
}
for (const pattern of excludePatterns) {
if (matchGlob(relativePath, pattern)) {
return false;
}
}
for (const pattern of includePatterns) {
if (matchGlob(relativePath, pattern)) {
return true;
}
}
return false;
}
function matchGlob(filePath: string, pattern: string): boolean {
if (pattern.startsWith("**/")) {
const withoutPrefix = pattern.slice(3);
if (withoutPrefix && matchGlob(filePath, withoutPrefix)) {
return true;
}
}
const escapedPattern = pattern.replace(/[.+^$()|[\]\\]/g, "\\$&");
let regexPattern = escapedPattern
.replace(/\*\*/g, "<<<DOUBLESTAR>>>")
.replace(/\*/g, "[^/]*")
.replace(/<<<DOUBLESTAR>>>/g, ".*")
.replace(/\?/g, ".")
.replace(/\{([^}]+)\}/g, (_, p1) => `(${p1.split(",").join("|")})`);
// **/*.js → matches both root "file.js" and nested "dir/file.js"
if (regexPattern.startsWith(".*/")) {
regexPattern = `(.*\\/)?${regexPattern.slice(3)}`;
}
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filePath);
}
export interface WalkOptions {
maxDepth: number;
maxFilesPerDirectory: number;
}
export async function* walkDirectory(
dir: string,
projectRoot: string,
includePatterns: string[],
excludePatterns: string[],
ignoreFilter: Ignore,
maxFileSize: number,
skipped: SkippedFile[],
options: WalkOptions,
currentDepth: number = 0
): AsyncGenerator<{ path: string; size: number }> {
const entries = await fsPromises.readdir(dir, { withFileTypes: true });
const filesInDir: Array<{ path: string; size: number }> = [];
const subdirs: Array<{ fullPath: string; relativePath: string }> = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(projectRoot, fullPath);
// Skip hidden files/folders (starting with .)
if (entry.name.startsWith(".") && entry.name !== "." && entry.name !== "..") {
if (entry.isDirectory()) {
skipped.push({ path: relativePath, reason: "excluded" });
}
continue;
}
// Skip folders containing "build" in their name
if (entry.isDirectory() && entry.name.toLowerCase().includes("build")) {
skipped.push({ path: relativePath, reason: "excluded" });
continue;
}
if (ignoreFilter.ignores(relativePath)) {
if (entry.isFile()) {
skipped.push({ path: relativePath, reason: "gitignore" });
}
continue;
}
if (entry.isDirectory()) {
subdirs.push({ fullPath, relativePath });
} else if (entry.isFile()) {
const stat = await fsPromises.stat(fullPath);
if (stat.size > maxFileSize) {
skipped.push({ path: relativePath, reason: "too_large" });
continue;
}
for (const pattern of excludePatterns) {
if (matchGlob(relativePath, pattern)) {
skipped.push({ path: relativePath, reason: "excluded" });
continue;
}
}
let matched = false;
for (const pattern of includePatterns) {
if (matchGlob(relativePath, pattern)) {
matched = true;
break;
}
}
if (matched) {
filesInDir.push({ path: fullPath, size: stat.size });
}
}
}
// Sort by size ascending, keep only the smallest maxFilesPerDirectory files
filesInDir.sort((a, b) => a.size - b.size);
const limitedFiles = filesInDir.slice(0, options.maxFilesPerDirectory);
for (const f of limitedFiles) {
yield f;
}
for (let i = options.maxFilesPerDirectory; i < filesInDir.length; i++) {
skipped.push({ path: path.relative(projectRoot, filesInDir[i].path), reason: "excluded" });
}
// Recurse into subdirectories respecting depth limit
const canRecurse = options.maxDepth === -1 || currentDepth < options.maxDepth;
if (canRecurse) {
for (const sub of subdirs) {
yield* walkDirectory(
sub.fullPath,
projectRoot,
includePatterns,
excludePatterns,
ignoreFilter,
maxFileSize,
skipped,
options,
currentDepth + 1
);
}
}
}
export async function collectFiles(
projectRoot: string,
includePatterns: string[],
excludePatterns: string[],
maxFileSize: number,
additionalRoots?: string[],
walkOptions?: WalkOptions
): Promise<CollectFilesResult> {
const opts: WalkOptions = walkOptions ?? { maxDepth: 5, maxFilesPerDirectory: 100 };
const ignoreFilter = createIgnoreFilter(projectRoot);
const files: Array<{ path: string; size: number }> = [];
const skipped: SkippedFile[] = [];
// Collect from project root
for await (const file of walkDirectory(
projectRoot,
projectRoot,
includePatterns,
excludePatterns,
ignoreFilter,
maxFileSize,
skipped,
opts,
0
)) {
files.push(file);
}
// Collect from additional knowledge base directories
if (additionalRoots && additionalRoots.length > 0) {
// Normalize and deduplicate knowledge base paths
const normalizedRoots = new Set<string>();
for (const kbRoot of additionalRoots) {
const resolved = path.normalize(
path.isAbsolute(kbRoot) ? kbRoot : path.resolve(projectRoot, kbRoot)
);
normalizedRoots.add(resolved);
}
for (const resolvedKbRoot of normalizedRoots) {
try {
const stat = await fsPromises.stat(resolvedKbRoot);
if (!stat.isDirectory()) {
skipped.push({ path: resolvedKbRoot, reason: "excluded" });
continue;
}
const kbIgnoreFilter = createIgnoreFilter(resolvedKbRoot);
for await (const file of walkDirectory(
resolvedKbRoot,
resolvedKbRoot,
includePatterns,
excludePatterns,
kbIgnoreFilter,
maxFileSize,
skipped,
opts,
0
)) {
files.push(file);
}
} catch {
skipped.push({ path: resolvedKbRoot, reason: "excluded" });
}
}
}
return { files, skipped };
}