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