pleme-codesearch 0.1.142

Fast, local semantic code search powered by Rust — BM25, vector embeddings, tree-sitter AST
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use anyhow::{anyhow, Result};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use notify_debouncer_full::{new_debouncer, DebounceEventResult, Debouncer, FileIdMap};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver};
use std::time::Duration;

use crate::cache::normalize_path;

/// Normalize a path from notify events to a consistent format.
/// Strips UNC prefix (`\\?\`) and converts backslashes to forward slashes
/// so paths match the format used by FileMetaStore and VectorStore.
fn normalize_event_path(path: &Path) -> PathBuf {
    PathBuf::from(normalize_path(path))
}

/// File extensions that should trigger re-indexing (whitelist approach)
/// This includes code files and configuration files
const INDEXABLE_EXTENSIONS: &[&str] = &[
    // Rust
    "rs",
    // JavaScript/TypeScript
    "js",
    "mjs",
    "cjs",
    "jsx",
    "ts",
    "mts",
    "cts",
    "tsx",
    // Python
    "py",
    "pyw",
    "pyi",
    // C/C++
    "c",
    "h",
    "cpp",
    "cc",
    "cxx",
    "hpp",
    "hxx",
    // C#
    "cs",
    "csx",
    // Java/Kotlin
    "java",
    "kt",
    "kts",
    // Go
    "go",
    // Ruby
    "rb",
    "rake",
    // PHP
    "php",
    // Swift
    "swift",
    // Shell/Scripts
    "sh",
    "bash",
    "zsh",
    "fish",
    "ps1",
    "psm1",
    "psd1",
    // Web
    "html",
    "htm",
    "css",
    "scss",
    "sass",
    "less",
    "vue",
    "svelte",
    // Config/Data
    "json",
    "jsonc",
    "json5",
    "yaml",
    "yml",
    "toml",
    "xml",
    "ini",
    "conf",
    "config",
    // .NET
    "csproj",
    "sln",
    "props",
    "targets",
    "razor",
    "cshtml",
    // SQL
    "sql",
    // Markdown/Docs
    "md",
    "markdown",
    "rst",
    // Other
    "graphql",
    "gql",
    "proto",
    "dockerfile",
];

/// Directories that should always be ignored
const IGNORED_DIRS: &[&str] = &[
    ".git",
    ".codesearch.db",
    "node_modules",
    "target",
    ".venv",
    "venv",
    "__pycache__",
    ".cache",
    "dist",
    "build",
    "out",
    "bin",
    "obj",
    ".vs",
    ".idea",
    ".vscode",
    "packages",
    ".nuget",
];

/// Types of file system events we care about
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)] // Renamed variant reserved for future rename detection
pub enum FileEvent {
    /// File was created or modified
    Modified(PathBuf),
    /// File was deleted
    Deleted(PathBuf),
    /// File was renamed (from, to)
    Renamed(PathBuf, PathBuf),
}

/// File watcher for incremental indexing
///
/// Uses notify-debouncer-full for efficient debounced file watching.
/// Improvements over osgrep:
/// 1. Native Rust implementation (faster than Node.js chokidar)
/// 2. Built-in debouncing (configurable)
/// 3. Batched events for efficient processing
pub struct FileWatcher {
    root: PathBuf,
    debouncer: Option<Debouncer<RecommendedWatcher, FileIdMap>>,
    receiver: Option<Receiver<DebounceEventResult>>,
}

impl FileWatcher {
    /// Create a new file watcher for the given root directory
    pub fn new(root: PathBuf) -> Self {
        Self {
            root,
            debouncer: None,
            receiver: None,
        }
    }

    /// Start watching for file changes
    pub fn start(&mut self, debounce_ms: u64) -> Result<()> {
        let (tx, rx) = channel();

        let debouncer = new_debouncer(
            Duration::from_millis(debounce_ms),
            None, // No tick rate
            tx,
        )
        .map_err(|e| anyhow!("Failed to create file watcher: {}", e))?;

        self.receiver = Some(rx);
        self.debouncer = Some(debouncer);

        // Start watching the root directory
        if let Some(ref mut debouncer) = self.debouncer {
            debouncer
                .watcher()
                .watch(&self.root, RecursiveMode::Recursive)
                .map_err(|e| anyhow!("Failed to watch directory: {}", e))?;

            // Also watch with the cache (for file ID tracking)
            debouncer
                .cache()
                .add_root(&self.root, RecursiveMode::Recursive);
        }

        Ok(())
    }

    /// Check if the watcher is currently started (collecting events)
    pub fn is_started(&self) -> bool {
        self.debouncer.is_some()
    }

    /// Stop watching
    pub fn stop(&mut self) {
        if let Some(ref mut debouncer) = self.debouncer {
            let _ = debouncer.watcher().unwatch(&self.root);
        }
        self.debouncer = None;
        self.receiver = None;
    }

    /// Check if a path is in an ignored directory (.git, node_modules, etc.)
    fn is_in_ignored_dir(&self, path: &Path) -> bool {
        for component in path.components() {
            if let Some(name) = component.as_os_str().to_str() {
                if IGNORED_DIRS.contains(&name) {
                    return true;
                }
            }
        }
        false
    }

    /// Check if a path should be watched (whitelist approach)
    /// Only returns true for indexable code/config files
    fn is_watchable(&self, path: &Path) -> bool {
        // Check if path is in an ignored directory
        if self.is_in_ignored_dir(path) {
            return false;
        }

        // Must be a file with an indexable extension
        if let Some(ext) = path.extension() {
            if let Some(ext_str) = ext.to_str() {
                return INDEXABLE_EXTENSIONS.contains(&ext_str.to_lowercase().as_str());
            }
        }

        // Special case: Dockerfile (no extension)
        if let Some(name) = path.file_name() {
            let name_str = name.to_string_lossy().to_lowercase();
            if name_str == "dockerfile" || name_str == "makefile" || name_str == "cmakelists.txt" {
                return true;
            }
        }

        false
    }

    /// Poll for file events (non-blocking)
    /// Returns a batch of deduplicated events
    pub fn poll_events(&self) -> Vec<FileEvent> {
        let Some(ref receiver) = self.receiver else {
            return vec![];
        };

        let mut events = Vec::new();
        let mut seen_paths = HashSet::new();

        // Drain all available events
        while let Ok(result) = receiver.try_recv() {
            match result {
                Ok(debounced_events) => {
                    for event in debounced_events {
                        for raw_path in &event.paths {
                            // Normalize path: strip UNC prefix, convert backslashes
                            let path = normalize_event_path(raw_path);

                            // Skip ignored directories
                            if self.is_in_ignored_dir(&path) || seen_paths.contains(&path) {
                                continue;
                            }
                            seen_paths.insert(path.clone());

                            // Convert to our event type
                            use notify::EventKind;
                            match event.kind {
                                EventKind::Create(_) | EventKind::Modify(_) => {
                                    // For creates/modifies, only process indexable files
                                    if self.is_watchable(&path) && raw_path.exists() {
                                        events.push(FileEvent::Modified(path));
                                    }
                                }
                                EventKind::Remove(_) => {
                                    // For removals, don't filter by extension - directory
                                    // deletions on Windows may only report the directory
                                    // path (no file extension), not individual files
                                    events.push(FileEvent::Deleted(path));
                                }
                                _ => {}
                            }
                        }
                    }
                }
                Err(errors) => {
                    for error in errors {
                        tracing::warn!("File watch error: {:?}", error);
                    }
                }
            }
        }

        events
    }

    /// Block and wait for events (with timeout)
    pub fn wait_for_events(&self, timeout: Duration) -> Vec<FileEvent> {
        let Some(ref receiver) = self.receiver else {
            return vec![];
        };

        let mut events = Vec::new();
        let mut seen_paths = HashSet::new();

        // Wait for first event
        match receiver.recv_timeout(timeout) {
            Ok(result) => {
                self.process_debounce_result(result, &mut events, &mut seen_paths);
            }
            Err(_) => return events, // Timeout or disconnected
        }

        // Drain any additional events that came in
        while let Ok(result) = receiver.try_recv() {
            self.process_debounce_result(result, &mut events, &mut seen_paths);
        }

        events
    }

    fn process_debounce_result(
        &self,
        result: DebounceEventResult,
        events: &mut Vec<FileEvent>,
        seen_paths: &mut HashSet<PathBuf>,
    ) {
        match result {
            Ok(debounced_events) => {
                for event in debounced_events {
                    for raw_path in &event.paths {
                        // Normalize path: strip UNC prefix, convert backslashes
                        let path = normalize_event_path(raw_path);

                        // Skip ignored directories and duplicates
                        if self.is_in_ignored_dir(&path) || seen_paths.contains(&path) {
                            continue;
                        }
                        seen_paths.insert(path.clone());

                        use notify::EventKind;
                        match event.kind {
                            EventKind::Create(_) | EventKind::Modify(_) => {
                                // For creates/modifies, only process indexable files
                                if self.is_watchable(&path) && raw_path.exists() {
                                    events.push(FileEvent::Modified(path));
                                }
                            }
                            EventKind::Remove(_) => {
                                // For removals, don't filter by extension - directory
                                // deletions on Windows may only report the directory
                                // path (no file extension), not individual files
                                events.push(FileEvent::Deleted(path));
                            }
                            _ => {}
                        }
                    }
                }
            }
            Err(errors) => {
                for error in errors {
                    tracing::warn!("File watch error: {:?}", error);
                }
            }
        }
    }
}

impl Drop for FileWatcher {
    fn drop(&mut self) {
        self.stop();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_is_watchable() {
        let watcher = FileWatcher::new(PathBuf::from("/tmp"));

        // Should NOT watch (ignored dirs)
        assert!(!watcher.is_watchable(Path::new("/tmp/.git/config")));
        assert!(!watcher.is_watchable(Path::new("/tmp/node_modules/foo/index.js")));
        assert!(!watcher.is_watchable(Path::new("/tmp/target/debug/main")));
        assert!(!watcher.is_watchable(Path::new("/tmp/.codesearch.db/data")));

        // Should NOT watch (non-indexable extensions)
        assert!(!watcher.is_watchable(Path::new("/tmp/Cargo.lock")));
        assert!(!watcher.is_watchable(Path::new("/tmp/debug.log")));
        assert!(!watcher.is_watchable(Path::new("/tmp/image.png")));
        assert!(!watcher.is_watchable(Path::new("/tmp/data.bin")));

        // SHOULD watch (code files)
        assert!(watcher.is_watchable(Path::new("/tmp/src/main.rs")));
        assert!(watcher.is_watchable(Path::new("/tmp/src/lib.ts")));
        assert!(watcher.is_watchable(Path::new("/tmp/Program.cs")));
        assert!(watcher.is_watchable(Path::new("/tmp/app.py")));

        // SHOULD watch (config files)
        assert!(watcher.is_watchable(Path::new("/tmp/config.json")));
        assert!(watcher.is_watchable(Path::new("/tmp/settings.yaml")));
        assert!(watcher.is_watchable(Path::new("/tmp/Cargo.toml")));
        assert!(watcher.is_watchable(Path::new("/tmp/appsettings.xml")));

        // SHOULD watch (special files)
        assert!(watcher.is_watchable(Path::new("/tmp/Dockerfile")));
        assert!(watcher.is_watchable(Path::new("/tmp/Makefile")));
    }

    #[test]
    #[ignore] // Requires actual filesystem events
    fn test_file_watcher() {
        let dir = tempdir().unwrap();
        let mut watcher = FileWatcher::new(dir.path().to_path_buf());

        watcher.start(100).unwrap();

        // Create a file
        let test_file = dir.path().join("test.rs");
        fs::write(&test_file, "fn main() {}").unwrap();

        // Wait for events
        std::thread::sleep(Duration::from_millis(200));
        let events = watcher.poll_events();

        assert!(!events.is_empty());
    }
}