Elffuss BraidHub

kikocis/continue public

a5fcde5311cf · 7.5 KiBRawPermalink
1import { glob, GlobOptionsWithFileTypesFalse } from "glob";
2
3import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js";
4import { getFileWatcher } from "../util/fileWatcher.js";
5import { isGitRepo } from "../util/git.js";
6import { logger } from "../util/logger.js";
7
8import { BaseService } from "./BaseService.js";
9import { serviceContainer } from "./ServiceContainer.js";
10
11export interface FileItem {
12 path: string;
13 displayName: string;
14}
15
16export interface FileIndexServiceState {
17 files: FileItem[];
18 isIndexing: boolean;
19 error: string | null;
20}
21
22export class FileIndexService extends BaseService<FileIndexServiceState> {
23 private fileSet = new Set<string>();
24 private fileWatcherInitialized = false;
25 private fileWatcherUnsubscribe: (() => void) | null = null;
26
27 constructor() {
28 super("FileIndexService", {
29 files: [],
30 isIndexing: false,
31 error: null,
32 });
33 }
34
35 async doInitialize(): Promise<FileIndexServiceState> {
36 await this.performFullIndex();
37 this.setupFileWatcher();
38 return this.getState();
39 }
40
41 async cleanup(): Promise<void> {
42 if (this.fileWatcherUnsubscribe) {
43 this.fileWatcherUnsubscribe();
44 this.fileWatcherUnsubscribe = null;
45 }
46
47 // Stop the file watcher to prevent resource leaks
48 if (this.fileWatcherInitialized) {
49 const watcher = getFileWatcher();
50 watcher.stopWatching();
51 }
52
53 this.fileWatcherInitialized = false;
54 }
55
56 /**
57 * Override setState to also notify the ServiceContainer
58 */
59 protected setState(newState: Partial<FileIndexServiceState>): void {
60 super.setState(newState);
61
62 // Also notify the ServiceContainer so UI components get updated
63 const currentState = this.getState();
64 serviceContainer.set("fileIndex", currentState);
65 }
66
67 private async performFullIndex(): Promise<void> {
68 this.setState({ isIndexing: true, error: null });
69
70 try {
71 const inGitRepo = isGitRepo();
72 const allMatches = await this.throttledGlob(FILE_PATTERNS, {
73 maxDepth: inGitRepo ? 15 : 3,
74 ignore: FILE_IGNORE_PATTERNS,
75 dot: true,
76 absolute: false,
77 });
78
79 const uniqueFiles = [...new Set(allMatches)];
80 this.fileSet.clear();
81 uniqueFiles.forEach((file) => this.fileSet.add(file));
82
83 const files = uniqueFiles.map((path) => ({
84 path,
85 displayName: path,
86 }));
87
88 this.setState({ files, isIndexing: false });
89 } catch (error) {
90 const errorMessage =
91 error instanceof Error ? error.message : String(error);
92 logger.error("Error performing full file index:", error);
93 this.setState({ isIndexing: false, error: errorMessage });
94 }
95 }
96
97 private setupFileWatcher(): void {
98 if (this.fileWatcherInitialized) {
99 return;
100 }
101
102 // Only enable file watching in git repositories
103 // Outside git repos (like home directory), file watching causes performance issues
104 // and provides little value since files change less predictably
105 const inGitRepo = isGitRepo();
106 if (!inGitRepo) {
107 logger.debug("Skipping file watcher: not in a git repository");
108 return;
109 }
110
111 this.fileWatcherInitialized = true;
112 const watcher = getFileWatcher();
113
114 // Start watching the current directory
115 watcher.startWatching();
116
117 // Set up callback for incremental updates
118 this.fileWatcherUnsubscribe = watcher.onChange(() => {
119 this.handleFileSystemChange();
120 });
121 }
122
123 private async handleFileSystemChange(): Promise<void> {
124 try {
125 // Get current files from file system
126 const inGitRepo = isGitRepo();
127 const allMatches = await this.throttledGlob(FILE_PATTERNS, {
128 maxDepth: inGitRepo ? 15 : 3,
129 ignore: FILE_IGNORE_PATTERNS,
130 dot: true,
131 absolute: false,
132 });
133
134 const currentFiles = new Set(allMatches);
135 const previousFiles = this.fileSet;
136
137 // Find added and removed files
138 const addedFiles = [...currentFiles].filter(
139 (file) => !previousFiles.has(file),
140 );
141 const removedFiles = [...previousFiles].filter(
142 (file) => !currentFiles.has(file),
143 );
144
145 // Only update if there are actual changes
146 if (addedFiles.length > 0 || removedFiles.length > 0) {
147 // Update internal file set
148 this.fileSet = currentFiles;
149
150 // Create new files array
151 const files = [...currentFiles].map((path) => ({
152 path,
153 displayName: path,
154 }));
155
156 this.setState({ files });
157 }
158 } catch (error) {
159 logger.error("Error handling file system change:", error);
160 const errorMessage =
161 error instanceof Error ? error.message : String(error);
162 this.setState({ error: errorMessage });
163 }
164 }
165
166 private async throttledGlob(
167 patterns: string[],
168 options: GlobOptionsWithFileTypesFalse,
169 batchSize = 100,
170 delay = 20,
171 ): Promise<string[]> {
172 return new Promise<string[]>((resolve, reject) => {
173 const allMatches: string[] = [];
174 let processed = 0;
175 let streamEnded = false;
176
177 const globStream = glob.stream(patterns, options);
178
179 globStream.on("data", (file: string) => {
180 allMatches.push(file);
181 processed++;
182
183 if (processed % batchSize === 0) {
184 if (streamEnded) {
185 return;
186 }
187 globStream.pause();
188
189 setTimeout(() => {
190 if (streamEnded) {
191 return;
192 }
193 globStream.resume();
194 }, delay);
195 }
196 });
197
198 globStream.on("end", () => {
199 streamEnded = true;
200 resolve(allMatches);
201 });
202
203 globStream.on("error", (err) => {
204 streamEnded = true;
205 reject(err);
206 });
207 });
208 }
209
210 // Public API methods
211 public getFiles(): FileItem[] {
212 return this.getState().files;
213 }
214
215 public isIndexing(): boolean {
216 return this.getState().isIndexing;
217 }
218
219 public getError(): string | null {
220 return this.getState().error;
221 }
222
223 public async refreshIndex(): Promise<void> {
224 await this.performFullIndex();
225 }
226
227 public filterFiles(filterText: string, limit: number = 10): FileItem[] {
228 const files = this.getFiles();
229
230 if (filterText.length === 0) {
231 // Show files sorted alphabetically when no filter
232 return [...files]
233 .sort((a, b) => {
234 const aFileName = a.path.split("/").pop() || a.path;
235 const bFileName = b.path.split("/").pop() || b.path;
236 return aFileName.localeCompare(bFileName);
237 })
238 .slice(0, limit);
239 }
240
241 const lowerFilter = filterText.toLowerCase();
242
243 return files
244 .filter((file) => {
245 return (
246 file.displayName.toLowerCase().includes(lowerFilter) ||
247 file.path.toLowerCase().includes(lowerFilter)
248 );
249 })
250 .sort((a, b) => {
251 const aFileName = a.path.split("/").pop() || a.path;
252 const bFileName = b.path.split("/").pop() || b.path;
253
254 // Prioritize exact matches in file name
255 const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
256 const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
257
258 if (aNameMatch && !bNameMatch) return -1;
259 if (!aNameMatch && bNameMatch) return 1;
260
261 // Then prioritize files that start with the filter
262 const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
263 const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
264
265 if (aStartsWith && !bStartsWith) return -1;
266 if (!aStartsWith && bStartsWith) return 1;
267
268 // Finally, sort by file name
269 return aFileName.localeCompare(bFileName);
270 })
271 .slice(0, limit);
272 }
273}