Elffuss BraidHub

kikocis/continue public

9c7524424566 · 6.3 KiBRawPermalink
1import * as fs from "fs";
2import * as path from "path";
3
4import { FILE_IGNORE_PATTERNS } from "./filePatterns.js";
5
6interface FileWatcherOptions {
7 ignore?: string[];
8 debounceMs?: number;
9 maxDepth?: number;
10}
11
12export class FileWatcher {
13 private watchers: fs.FSWatcher[] = [];
14 private callbacks: Set<() => void> = new Set();
15 private debounceTimer: NodeJS.Timeout | null = null;
16 private options: Required<FileWatcherOptions>;
17 private watchedDirs: Set<string> = new Set();
18 private isInitializing: boolean = false;
19
20 constructor(options: FileWatcherOptions = {}) {
21 this.options = {
22 ignore: [...FILE_IGNORE_PATTERNS, ...(options.ignore || [])],
23 debounceMs: options.debounceMs || 1000,
24 maxDepth: options.maxDepth || 10,
25 };
26 }
27
28 private shouldIgnorePath(filePath: string): boolean {
29 const normalizedPath = path.normalize(filePath).replace(/\\/g, "/");
30
31 return this.options.ignore.some((pattern) => {
32 if (pattern.startsWith("**/")) {
33 const suffix = pattern.slice(3);
34 if (suffix.endsWith("/**")) {
35 // Directory pattern like **/node_modules/**
36 const dirName = suffix.slice(0, -3);
37 return (
38 normalizedPath.includes(`/${dirName}/`) ||
39 normalizedPath.endsWith(`/${dirName}`) ||
40 normalizedPath === dirName
41 );
42 } else if (suffix.startsWith("*")) {
43 // File pattern like **/*.tmp
44 const extension = suffix.slice(1); // Remove the '*' to get the extension
45 return normalizedPath.endsWith(extension);
46 } else {
47 // File pattern like **/package.json
48 return (
49 normalizedPath.endsWith(`/${suffix}`) ||
50 normalizedPath.endsWith(suffix)
51 );
52 }
53 }
54 return normalizedPath.includes(pattern);
55 });
56 }
57
58 private triggerCallbacks(): void {
59 // Don't trigger callbacks during initialization
60 if (this.isInitializing) {
61 return;
62 }
63
64 if (this.debounceTimer) {
65 clearTimeout(this.debounceTimer);
66 }
67
68 this.debounceTimer = setTimeout(() => {
69 this.callbacks.forEach((callback) => {
70 try {
71 callback();
72 } catch (error) {
73 console.error("Error in file watcher callback:", error);
74 }
75 });
76 }, this.options.debounceMs);
77 }
78
79 private handleFileChange = (
80 eventType: string,
81 filename: string | null,
82 dirPath: string,
83 depth: number,
84 ): void => {
85 if (!filename) return;
86
87 const fullPath = path.join(dirPath, filename);
88
89 // Skip if path should be ignored
90 if (this.shouldIgnorePath(fullPath)) {
91 return;
92 }
93
94 // Check if it's a directory and we should watch it
95 if (eventType === "rename") {
96 this.handleNewDirectory(fullPath, depth);
97 }
98
99 this.triggerCallbacks();
100 };
101
102 private handleNewDirectory(fullPath: string, depth: number): void {
103 try {
104 const stats = fs.statSync(fullPath);
105 if (stats.isDirectory() && depth < this.options.maxDepth) {
106 // New directory created, start watching it
107 this.watchDirectory(fullPath, depth + 1);
108 }
109 } catch {
110 // File/directory was deleted or not accessible
111 }
112 }
113
114 private setupWatcher(dirPath: string, depth: number): void {
115 const watcher = fs.watch(
116 dirPath,
117 { persistent: false },
118 (eventType, filename) => {
119 this.handleFileChange(eventType, filename, dirPath, depth);
120 },
121 );
122
123 watcher.on("error", (error) => {
124 console.error(`File watcher error for ${dirPath}:`, error);
125 });
126
127 this.watchers.push(watcher);
128 }
129
130 private watchSubdirectories(dirPath: string, depth: number): void {
131 try {
132 const entries = fs.readdirSync(dirPath);
133 for (const entry of entries) {
134 const entryPath = path.join(dirPath, entry);
135 if (this.shouldIgnorePath(entryPath)) {
136 continue;
137 }
138
139 try {
140 const stats = fs.statSync(entryPath);
141 if (stats.isDirectory()) {
142 this.watchDirectory(entryPath, depth + 1);
143 }
144 } catch {
145 // Skip inaccessible entries
146 }
147 }
148 } catch {
149 // Skip if can't read directory
150 }
151 }
152
153 private watchDirectory(dirPath: string, depth: number = 0): void {
154 if (
155 depth > this.options.maxDepth ||
156 this.shouldIgnorePath(dirPath) ||
157 this.watchedDirs.has(dirPath)
158 ) {
159 return;
160 }
161
162 try {
163 // Check if directory exists and is accessible
164 const stats = fs.statSync(dirPath);
165 if (!stats.isDirectory()) {
166 return;
167 }
168
169 this.watchedDirs.add(dirPath);
170 this.setupWatcher(dirPath, depth);
171 this.watchSubdirectories(dirPath, depth);
172 } catch (error) {
173 console.error(`Failed to watch directory ${dirPath}:`, error);
174 }
175 }
176
177 public startWatching(rootPath: string = process.cwd()): void {
178 this.stopWatching();
179 this.isInitializing = true;
180 this.watchDirectory(rootPath);
181
182 // Allow a small delay for initial file system events to settle
183 // before enabling callbacks
184 setTimeout(() => {
185 this.isInitializing = false;
186 }, 50);
187 }
188
189 public stopWatching(): void {
190 this.isInitializing = false;
191 this.watchers.forEach((watcher) => {
192 try {
193 watcher.close();
194 } catch (error) {
195 console.error("Error closing file watcher:", error);
196 }
197 });
198 this.watchers = [];
199 this.watchedDirs.clear();
200
201 if (this.debounceTimer) {
202 clearTimeout(this.debounceTimer);
203 this.debounceTimer = null;
204 }
205 }
206
207 public onChange(callback: () => void): () => void {
208 this.callbacks.add(callback);
209
210 // Return unsubscribe function
211 return () => {
212 this.callbacks.delete(callback);
213 };
214 }
215
216 public destroy(): void {
217 this.stopWatching();
218 this.callbacks.clear();
219 }
220}
221
222// Singleton instance for the entire application
223let globalFileWatcher: FileWatcher | null = null;
224
225export function getFileWatcher(): FileWatcher {
226 if (!globalFileWatcher) {
227 globalFileWatcher = new FileWatcher({
228 debounceMs: 1000, // 1 second debounce
229 maxDepth: 10,
230 });
231 }
232 return globalFileWatcher;
233}
234
235export function startFileWatching(): void {
236 const watcher = getFileWatcher();
237 watcher.startWatching();
238}
239
240export function stopFileWatching(): void {
241 if (globalFileWatcher) {
242 globalFileWatcher.destroy();
243 globalFileWatcher = null;
244 }
245}