forked from CodebuffAI/codebuff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject-file-tree.ts
More file actions
318 lines (277 loc) · 9.02 KB
/
Copy pathproject-file-tree.ts
File metadata and controls
318 lines (277 loc) · 9.02 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
313
314
315
316
317
318
import path from 'path'
import * as ignore from 'ignore'
import { sortBy } from 'lodash'
import { DEFAULT_IGNORED_PATHS } from './constants/paths'
import { fileExists, isValidProjectRoot } from './util/file'
import type { CodebuffFileSystem } from './types/filesystem'
import type { DirectoryNode, FileTreeNode } from './util/file'
/**
* Logs file tree errors in debug mode only.
* Errors are logged but not thrown to preserve tree-building behavior.
*
* File tree operations commonly encounter expected errors (permissions,
* deleted files) that are not fatal. We only log in debug mode to avoid
* noisy output during normal operation.
*/
function logFileTreeError(
operation: string,
filePath: string,
error: unknown,
): void {
// Only log in debug mode to avoid noisy output
if (!process.env.DEBUG && !process.env.CODEBUFF_DEBUG) {
return
}
const err = error as { code?: string } | undefined
const code = err?.code
const errorMessage = error instanceof Error ? error.message : String(error)
console.debug(
`[FileTree] ${operation} failed for "${filePath}"${
code ? ` (${code})` : ''
}: ${errorMessage}`,
)
}
export const DEFAULT_MAX_FILES = 10_000
export async function getProjectFileTree(params: {
projectRoot: string
maxFiles?: number
fs: CodebuffFileSystem
}): Promise<FileTreeNode[]> {
const withDefaults = { maxFiles: DEFAULT_MAX_FILES, ...params }
const { projectRoot, fs } = withDefaults
let { maxFiles } = withDefaults
const _start = Date.now()
const defaultIgnore = ignore.default()
for (const pattern of DEFAULT_IGNORED_PATHS) {
defaultIgnore.add(pattern)
}
if (!isValidProjectRoot(projectRoot)) {
defaultIgnore.add('.*')
maxFiles = 0
}
const root: DirectoryNode = {
name: path.basename(projectRoot),
type: 'directory',
children: [],
filePath: '',
}
const queue: {
node: DirectoryNode
fullPath: string
ignore: ignore.Ignore
}[] = [
{
node: root,
fullPath: projectRoot,
ignore: defaultIgnore,
},
]
let totalFiles = 0
while (queue.length > 0 && totalFiles < maxFiles) {
const { node, fullPath, ignore: currentIgnore } = queue.shift()!
const parsedIgnore = await parseGitignore({
fullDirPath: fullPath,
projectRoot,
fs,
})
const mergedIgnore = ignore
.default()
.add(currentIgnore)
.add(parsedIgnore)
try {
const files = await fs.readdir(fullPath)
for (const file of files) {
if (totalFiles >= maxFiles) break
const filePath = path.join(fullPath, file)
const relativeFilePath = path.relative(projectRoot, filePath)
if (mergedIgnore.ignores(relativeFilePath)) continue
try {
const stats = await fs.stat(filePath)
if (stats.isDirectory()) {
const childNode: DirectoryNode = {
name: file,
type: 'directory',
children: [],
filePath: relativeFilePath,
}
node.children.push(childNode)
queue.push({
node: childNode,
fullPath: filePath,
ignore: mergedIgnore,
})
} else {
const lastReadTime = stats.atimeMs
node.children.push({
name: file,
type: 'file',
lastReadTime,
filePath: relativeFilePath,
})
totalFiles++
}
} catch (error: unknown) {
// File may be inaccessible due to permissions or may have been deleted.
// Log with context for debugging, but continue building the tree.
logFileTreeError('fs.stat', filePath, error)
}
}
} catch (error: unknown) {
// Directory may be inaccessible due to permissions.
// Log with context for debugging, but continue building the tree.
logFileTreeError('fs.readdir', fullPath, error)
}
}
return root.children
}
function rebaseGitignorePattern(
rawPattern: string,
relativeDirPath: string,
): string {
// Preserve negation and directory-only flags
const isNegated = rawPattern.startsWith('!')
let pattern = isNegated ? rawPattern.slice(1) : rawPattern
const dirOnly = pattern.endsWith('/')
// Strip the trailing slash for slash-detection only
const core = dirOnly ? pattern.slice(0, -1) : pattern
const anchored = core.startsWith('/') // anchored to .gitignore dir
// Detect if the "meaningful" part (minus optional leading '/' and trailing '/')
// contains a slash. If not, git treats it as recursive.
const coreNoLead = anchored ? core.slice(1) : core
const hasSlash = coreNoLead.includes('/')
// Build the base (where this .gitignore lives relative to projectRoot)
const base = relativeDirPath.replace(/\\/g, '/') // normalize
let rebased: string
if (anchored) {
// "/foo" from evals/.gitignore -> "evals/foo"
rebased = base ? `${base}/${coreNoLead}` : coreNoLead
} else if (!hasSlash) {
// "logs" or "logs/" should recurse from evals/: "evals/**/logs[/]"
if (base) {
rebased = `${base}/**/${coreNoLead}`
} else {
// At project root already; "logs" stays "logs" to keep recursive semantics
rebased = coreNoLead
}
} else {
// "foo/bar" relative to evals/: "evals/foo/bar"
rebased = base ? `${base}/${coreNoLead}` : coreNoLead
}
if (dirOnly && !rebased.endsWith('/')) {
rebased += '/'
}
// Normalize to forward slashes
rebased = rebased.replace(/\\/g, '/')
return isNegated ? `!${rebased}` : rebased
}
export async function parseGitignore(params: {
fullDirPath: string
projectRoot: string
fs: CodebuffFileSystem
}): Promise<ignore.Ignore> {
const { fullDirPath, projectRoot, fs } = params
const ig = ignore.default()
const relativeDirPath = path.relative(projectRoot, fullDirPath)
const ignoreFiles = [
path.join(fullDirPath, '.gitignore'),
path.join(fullDirPath, '.codebuffignore'),
path.join(fullDirPath, '.manicodeignore'), // Legacy support
]
for (const ignoreFilePath of ignoreFiles) {
const ignoreFileExists = await fileExists({ filePath: ignoreFilePath, fs })
if (!ignoreFileExists) continue
let ignoreContent: string
try {
ignoreContent = await fs.readFile(ignoreFilePath, 'utf8')
} catch (error: unknown) {
// Ignore file may be inaccessible or deleted after existence check.
// Log with context for debugging, but continue without these ignore rules.
logFileTreeError('fs.readFile (ignore file)', ignoreFilePath, error)
continue
}
const lines = ignoreContent.split('\n')
for (let line of lines) {
line = line.trim()
if (line === '' || line.startsWith('#')) continue
const finalPattern = rebaseGitignorePattern(line, relativeDirPath)
ig.add(finalPattern)
}
}
return ig
}
export function getAllFilePaths(
nodes: FileTreeNode[],
basePath: string = '',
): string[] {
return nodes.flatMap((node) => {
if (node.type === 'file') {
return [path.join(basePath, node.name)]
}
return getAllFilePaths(node.children || [], path.join(basePath, node.name))
})
}
export interface PathInfo {
path: string
isDirectory: boolean
}
export function getAllPathsWithDirectories(
nodes: FileTreeNode[],
basePath: string = '',
): PathInfo[] {
return nodes.flatMap((node) => {
const nodePath = basePath ? path.join(basePath, node.name) : node.name
if (node.type === 'file') {
return [{ path: nodePath, isDirectory: false }]
}
// Include the directory itself, plus recurse into children
const dirEntry: PathInfo = { path: nodePath, isDirectory: true }
const children = getAllPathsWithDirectories(node.children || [], nodePath)
return [dirEntry, ...children]
})
}
export function flattenTree(nodes: FileTreeNode[]): FileTreeNode[] {
return nodes.flatMap((node) => {
if (node.type === 'file') {
return [node]
}
return flattenTree(node.children ?? [])
})
}
export function getLastReadFilePaths(
flattenedNodes: FileTreeNode[],
count: number,
) {
return sortBy(
flattenedNodes.filter((node) => node.lastReadTime),
'lastReadTime',
)
.reverse()
.slice(0, count)
.map((node) => node.filePath)
}
export async function isFileIgnored(params: {
filePath: string
projectRoot: string
fs: CodebuffFileSystem
}): Promise<boolean> {
const { filePath, projectRoot, fs } = params
const defaultIgnore = ignore.default()
for (const pattern of DEFAULT_IGNORED_PATHS) {
defaultIgnore.add(pattern)
}
const relativeFilePath = path.relative(
projectRoot,
path.join(projectRoot, filePath),
)
const dirPath = path.dirname(path.join(projectRoot, filePath))
// Get ignore patterns from the directory containing the file and all parent directories
const mergedIgnore = ignore.default().add(defaultIgnore)
let currentDir = dirPath
while (currentDir.startsWith(projectRoot)) {
mergedIgnore.add(
await parseGitignore({ fullDirPath: currentDir, projectRoot, fs }),
)
currentDir = path.dirname(currentDir)
}
return mergedIgnore.ignores(relativeFilePath)
}