Elffuss BraidHub

kikocis/continue public

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