| 1 | import { glob, GlobOptionsWithFileTypesFalse } from "glob"; |
| 2 | |
| 3 | import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js"; |
| 4 | import { getFileWatcher } from "../util/fileWatcher.js"; |
| 5 | import { isGitRepo } from "../util/git.js"; |
| 6 | |
| 7 | import { BaseService } from "./BaseService.js"; |
| 8 | import { serviceContainer } from "./ServiceContainer.js"; |
| 9 | |
| 10 | export interface FileItem { |
| 11 | path: string; |
| 12 | displayName: string; |
| 13 | } |
| 14 | |
| 15 | export interface FileIndexServiceState { |
| 16 | files: FileItem[]; |
| 17 | isIndexing: boolean; |
| 18 | error: string | null; |
| 19 | } |
| 20 | |
| 21 | export 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 | // Only enable file watching in git repositories |
| 102 | // Outside git repos (like home directory), file watching causes performance issues |
| 103 | // and provides little value since files change less predictably |
| 104 | const inGitRepo = isGitRepo(); |
| 105 | if (!inGitRepo) { |
| 106 | console.log("Skipping file watcher: not in a git repository"); |
| 107 | return; |
| 108 | } |
| 109 | |
| 110 | this.fileWatcherInitialized = true; |
| 111 | const watcher = getFileWatcher(); |
| 112 | |
| 113 | // Start watching the current directory |
| 114 | watcher.startWatching(); |
| 115 | |
| 116 | // Set up callback for incremental updates |
| 117 | this.fileWatcherUnsubscribe = watcher.onChange(() => { |
| 118 | this.handleFileSystemChange(); |
| 119 | }); |
| 120 | } |
| 121 | |
| 122 | private async handleFileSystemChange(): Promise<void> { |
| 123 | try { |
| 124 | // Get current files from file system |
| 125 | const inGitRepo = isGitRepo(); |
| 126 | const allMatches = await this.throttledGlob(FILE_PATTERNS, { |
| 127 | maxDepth: inGitRepo ? 15 : 3, |
| 128 | ignore: FILE_IGNORE_PATTERNS, |
| 129 | dot: true, |
| 130 | absolute: false, |
| 131 | }); |
| 132 | |
| 133 | const currentFiles = new Set(allMatches); |
| 134 | const previousFiles = this.fileSet; |
| 135 | |
| 136 | // Find added and removed files |
| 137 | const addedFiles = [...currentFiles].filter( |
| 138 | (file) => !previousFiles.has(file), |
| 139 | ); |
| 140 | const removedFiles = [...previousFiles].filter( |
| 141 | (file) => !currentFiles.has(file), |
| 142 | ); |
| 143 | |
| 144 | // Only update if there are actual changes |
| 145 | if (addedFiles.length > 0 || removedFiles.length > 0) { |
| 146 | // Update internal file set |
| 147 | this.fileSet = currentFiles; |
| 148 | |
| 149 | // Create new files array |
| 150 | const files = [...currentFiles].map((path) => ({ |
| 151 | path, |
| 152 | displayName: path, |
| 153 | })); |
| 154 | |
| 155 | this.setState({ files }); |
| 156 | |
| 157 | console.log( |
| 158 | `File index updated: +${addedFiles.length} -${removedFiles.length} files`, |
| 159 | ); |
| 160 | } |
| 161 | } catch (error) { |
| 162 | console.error("Error handling file system change:", error); |
| 163 | const errorMessage = |
| 164 | error instanceof Error ? error.message : String(error); |
| 165 | this.setState({ error: errorMessage }); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | private async throttledGlob( |
| 170 | patterns: string[], |
| 171 | options: GlobOptionsWithFileTypesFalse, |
| 172 | batchSize = 100, |
| 173 | delay = 20, |
| 174 | ): Promise<string[]> { |
| 175 | return new Promise<string[]>((resolve, reject) => { |
| 176 | const allMatches: string[] = []; |
| 177 | let processed = 0; |
| 178 | let streamEnded = false; |
| 179 | |
| 180 | const globStream = glob.stream(patterns, options); |
| 181 | |
| 182 | globStream.on("data", (file: string) => { |
| 183 | allMatches.push(file); |
| 184 | processed++; |
| 185 | |
| 186 | if (processed % batchSize === 0) { |
| 187 | if (streamEnded) { |
| 188 | return; |
| 189 | } |
| 190 | globStream.pause(); |
| 191 | |
| 192 | setTimeout(() => { |
| 193 | if (streamEnded) { |
| 194 | return; |
| 195 | } |
| 196 | globStream.resume(); |
| 197 | }, delay); |
| 198 | } |
| 199 | }); |
| 200 | |
| 201 | globStream.on("end", () => { |
| 202 | streamEnded = true; |
| 203 | resolve(allMatches); |
| 204 | }); |
| 205 | |
| 206 | globStream.on("error", (err) => { |
| 207 | streamEnded = true; |
| 208 | reject(err); |
| 209 | }); |
| 210 | }); |
| 211 | } |
| 212 | |
| 213 | // Public API methods |
| 214 | public getFiles(): FileItem[] { |
| 215 | return this.getState().files; |
| 216 | } |
| 217 | |
| 218 | public isIndexing(): boolean { |
| 219 | return this.getState().isIndexing; |
| 220 | } |
| 221 | |
| 222 | public getError(): string | null { |
| 223 | return this.getState().error; |
| 224 | } |
| 225 | |
| 226 | public async refreshIndex(): Promise<void> { |
| 227 | await this.performFullIndex(); |
| 228 | } |
| 229 | |
| 230 | public filterFiles(filterText: string, limit: number = 10): FileItem[] { |
| 231 | const files = this.getFiles(); |
| 232 | |
| 233 | if (filterText.length === 0) { |
| 234 | // Show files sorted alphabetically when no filter |
| 235 | return [...files] |
| 236 | .sort((a, b) => { |
| 237 | const aFileName = a.path.split("/").pop() || a.path; |
| 238 | const bFileName = b.path.split("/").pop() || b.path; |
| 239 | return aFileName.localeCompare(bFileName); |
| 240 | }) |
| 241 | .slice(0, limit); |
| 242 | } |
| 243 | |
| 244 | const lowerFilter = filterText.toLowerCase(); |
| 245 | |
| 246 | return files |
| 247 | .filter((file) => { |
| 248 | return ( |
| 249 | file.displayName.toLowerCase().includes(lowerFilter) || |
| 250 | file.path.toLowerCase().includes(lowerFilter) |
| 251 | ); |
| 252 | }) |
| 253 | .sort((a, b) => { |
| 254 | const aFileName = a.path.split("/").pop() || a.path; |
| 255 | const bFileName = b.path.split("/").pop() || b.path; |
| 256 | |
| 257 | // Prioritize exact matches in file name |
| 258 | const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); |
| 259 | const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); |
| 260 | |
| 261 | if (aNameMatch && !bNameMatch) return -1; |
| 262 | if (!aNameMatch && bNameMatch) return 1; |
| 263 | |
| 264 | // Then prioritize files that start with the filter |
| 265 | const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); |
| 266 | const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); |
| 267 | |
| 268 | if (aStartsWith && !bStartsWith) return -1; |
| 269 | if (!aStartsWith && bStartsWith) return 1; |
| 270 | |
| 271 | // Finally, sort by file name |
| 272 | return aFileName.localeCompare(bFileName); |
| 273 | }) |
| 274 | .slice(0, limit); |
| 275 | } |
| 276 | } |