jonesy 0.10.0

Jonesy is here to help you not panic!
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Native file watching for LSP binary change detection.
//!
//! This module provides platform-agnostic file watching to detect when
//! binaries or config files change, triggering LSP re-analysis.
//!
//! # File Changes That Trigger Re-Analysis
//!
//! ## Binary/Library Changes (in `target/debug/`)
//!
//! | File Type | Pattern | Trigger Reason |
//! |-----------|---------|----------------|
//! | Binary executable | `target/debug/<name>` (no extension) | Main crate binary rebuilt |
//! | Rust library | `target/debug/lib<name>.rlib` | Library crate rebuilt |
//! | Dynamic library | `target/debug/lib<name>.dylib` (macOS) | cdylib/dylib rebuilt |
//! | Dynamic library | `target/debug/lib<name>.so` (Linux) | cdylib/dylib rebuilt |
//! | Static library | `target/debug/lib<name>.a` | staticlib rebuilt |
//!
//! ## Config File Changes
//!
//! | File | Location | Trigger Reason |
//! |------|----------|----------------|
//! | `jonesy.toml` | Workspace root | Allow/deny rules changed |
//! | `Cargo.toml` | Workspace root | Workspace members changed |
//! | `Cargo.toml` | Each member crate | Dependencies or features changed |
//!
//! # Platform Support
//!
//! The `notify` crate provides cross-platform file watching:
//! - **macOS**: FSEvents (efficient, low overhead)
//! - **Linux**: inotify (may require increasing watch limits for large projects)
//! - **Windows**: ReadDirectoryChangesW
//!
//! The design allows for custom platform-specific implementations if needed.

use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::sync::mpsc;

/// Events emitted by the file watcher.
#[derive(Debug, Clone)]
pub enum WatchEvent {
    /// A binary or library file changed (created, modified, or removed).
    BinaryChanged(PathBuf),
    /// A config file changed (jonesy.toml, Cargo.toml).
    ConfigChanged(PathBuf),
    /// The watcher encountered an error.
    Error(String),
}

/// Configuration for the file watcher.
#[derive(Debug, Clone)]
pub struct WatcherConfig {
    /// Directory to watch for binary changes (e.g., target/debug/).
    pub target_dir: PathBuf,
    /// Config files to watch (e.g., jonesy.toml, Cargo.toml).
    pub config_files: Vec<PathBuf>,
    /// Debounce duration - events within this window are coalesced.
    pub debounce: Duration,
}

impl Default for WatcherConfig {
    fn default() -> Self {
        Self {
            target_dir: PathBuf::from("target/debug"),
            config_files: Vec::new(),
            debounce: Duration::from_millis(500),
        }
    }
}

/// A handle to control the file watcher.
///
/// IMPORTANT: This handle must be kept alive for the watcher to function.
/// Dropping this handle stops file watching.
pub struct WatcherHandle {
    /// Receiver for watch events.
    pub events: mpsc::Receiver<WatchEvent>,
    /// Keep the watcher alive - dropping this stops watching.
    pub watcher: RecommendedWatcher,
}

/// Start watching for file changes.
///
/// Returns a handle with an event receiver. The watcher runs until the handle
/// is dropped.
///
/// # Platform Notes
/// - macOS: Uses FSEvents (efficient, low overhead)
/// - Linux: Uses inotify (requires inotify watches, may hit limits)
/// - Windows: Uses ReadDirectoryChangesW
pub fn start_watching(config: WatcherConfig) -> Result<WatcherHandle, String> {
    let (tx, rx) = mpsc::channel(100);

    // Clone paths for the closure
    let target_dir = config.target_dir.clone();
    let config_files: Vec<PathBuf> = config.config_files.clone();

    // Create the notify watcher
    let tx_clone = tx.clone();

    let mut watcher = notify::recommended_watcher(move |result: Result<Event, notify::Error>| {
        match result {
            Ok(event) => {
                // Filter to relevant event kinds
                let dominated_events = matches!(
                    event.kind,
                    EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
                );

                if !dominated_events {
                    return;
                }

                for path in event.paths {
                    let watch_event = categorize_path(&path, &target_dir, &config_files);
                    if let Some(evt) = watch_event {
                        // Non-blocking send - drop events if channel is full
                        let _ = tx_clone.try_send(evt);
                    }
                }
            }
            Err(e) => {
                let _ = tx_clone.try_send(WatchEvent::Error(e.to_string()));
            }
        }
    })
    .map_err(|e| format!("Failed to create file watcher: {}", e))?;

    // Watch target directory (non-recursive - we only care about direct children)
    // If target/debug doesn't exist yet, watch target/ to catch when it's created
    if config.target_dir.exists() {
        watcher
            .watch(&config.target_dir, RecursiveMode::NonRecursive)
            .map_err(|e| format!("Failed to watch {}: {}", config.target_dir.display(), e))?;
    } else if let Some(parent) = config.target_dir.parent() {
        if parent.exists() {
            // Watch parent (target/) to detect when target/debug is created
            let _ = watcher.watch(parent, RecursiveMode::NonRecursive);
        }
    }

    // Watch config files (or their parent directories if files don't exist yet)
    for config_file in &config.config_files {
        // Watch the parent directory since the file might be deleted and recreated
        if let Some(parent) = config_file.parent() {
            if parent.exists() {
                // Ignore errors for config files - they're optional
                let _ = watcher.watch(parent, RecursiveMode::NonRecursive);
            }
        }
    }

    Ok(WatcherHandle {
        events: rx,
        watcher,
    })
}

/// Categorize a changed path into a WatchEvent.
fn categorize_path(path: &Path, target_dir: &Path, config_files: &[PathBuf]) -> Option<WatchEvent> {
    // Check if it's a config file
    for config_file in config_files {
        if path == config_file {
            return Some(WatchEvent::ConfigChanged(path.to_path_buf()));
        }
    }

    // Check if it's in the target directory
    if path.starts_with(target_dir) {
        // Filter to binary-like files (no extension or known library extensions)
        if is_binary_or_library(path) {
            return Some(WatchEvent::BinaryChanged(path.to_path_buf()));
        }
    }

    None
}

/// Check if a path looks like a binary or library file.
fn is_binary_or_library(path: &Path) -> bool {
    let extension = path
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_lowercase());

    match extension.as_deref() {
        // Binary extensions (Windows)
        Some("exe") => true,
        // Library extensions
        Some("rlib") | Some("dylib") | Some("so") | Some("dll") | Some("a") => true,
        // dSYM debug symbols on macOS
        Some("dsym") => false, // Skip dSYM directories
        // No extension - likely a binary on Unix
        None => {
            // But skip common non-binary files
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            !name.starts_with('.') && !name.ends_with(".d") && name != "build" && name != "deps"
        }
        // Skip other extensions (like .d dependency files, .rmeta, etc.)
        _ => false,
    }
}

/// Spawn a debounced event processor.
///
/// This takes raw events and emits debounced analysis triggers.
/// Multiple changes within the debounce window result in a single trigger.
pub async fn debounced_events(
    mut events: mpsc::Receiver<WatchEvent>,
    debounce: Duration,
) -> mpsc::Receiver<()> {
    let (tx, rx) = mpsc::channel(10);

    tokio::spawn(async move {
        let mut pending = false;
        let mut debounce_timer: Option<tokio::time::Instant> = None;

        loop {
            let timeout = debounce_timer
                .map(|t| t.saturating_duration_since(tokio::time::Instant::now()))
                .unwrap_or(Duration::from_secs(3600)); // Long timeout when no pending

            tokio::select! {
                event = events.recv() => {
                    match event {
                        Some(WatchEvent::BinaryChanged(_)) | Some(WatchEvent::ConfigChanged(_)) => {
                            pending = true;
                            debounce_timer = Some(tokio::time::Instant::now() + debounce);
                        }
                        Some(WatchEvent::Error(e)) => {
                            eprintln!("File watcher error: {}", e);
                        }
                        None => break, // Channel closed
                    }
                }
                _ = tokio::time::sleep(timeout), if pending => {
                    pending = false;
                    debounce_timer = None;
                    // Emit analysis trigger
                    if tx.send(()).await.is_err() {
                        break; // Receiver dropped
                    }
                }
            }
        }
    });

    rx
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Test binary detection for all supported file types.
    /// See module docs for the full list of monitored file types.
    #[test]
    fn test_is_binary_or_library() {
        // === BINARY EXECUTABLES (no extension on Unix) ===
        assert!(
            is_binary_or_library(Path::new("target/debug/myapp")),
            "Binary without extension should trigger"
        );
        assert!(
            is_binary_or_library(Path::new("target/debug/jonesy")),
            "Binary without extension should trigger"
        );
        assert!(
            is_binary_or_library(Path::new("target/debug/my-app-name")),
            "Binary with hyphens should trigger"
        );

        // === RUST LIBRARIES (.rlib) ===
        assert!(
            is_binary_or_library(Path::new("target/debug/libfoo.rlib")),
            "Rust library (.rlib) should trigger"
        );
        assert!(
            is_binary_or_library(Path::new("target/debug/libjonesy.rlib")),
            "Rust library (.rlib) should trigger"
        );

        // === DYNAMIC LIBRARIES (macOS: .dylib) ===
        assert!(
            is_binary_or_library(Path::new("target/debug/libfoo.dylib")),
            "Dynamic library (.dylib) should trigger"
        );

        // === DYNAMIC LIBRARIES (Linux: .so) ===
        assert!(
            is_binary_or_library(Path::new("target/debug/libfoo.so")),
            "Shared object (.so) should trigger"
        );

        // === DYNAMIC LIBRARIES (Windows: .dll) ===
        assert!(
            is_binary_or_library(Path::new("target/debug/foo.dll")),
            "DLL (.dll) should trigger"
        );

        // === STATIC LIBRARIES (.a) ===
        assert!(
            is_binary_or_library(Path::new("target/debug/libfoo.a")),
            "Static library (.a) should trigger"
        );

        // === FILES TO SKIP ===

        // Hidden files/directories
        assert!(
            !is_binary_or_library(Path::new("target/debug/.fingerprint")),
            "Hidden directories should be skipped"
        );
        assert!(
            !is_binary_or_library(Path::new("target/debug/.cargo-lock")),
            "Hidden files should be skipped"
        );

        // Cargo build directories
        assert!(
            !is_binary_or_library(Path::new("target/debug/deps")),
            "deps directory should be skipped"
        );
        assert!(
            !is_binary_or_library(Path::new("target/debug/build")),
            "build directory should be skipped"
        );

        // Dependency tracking files
        assert!(
            !is_binary_or_library(Path::new("target/debug/foo.d")),
            "Dependency files (.d) should be skipped"
        );

        // Rust metadata
        assert!(
            !is_binary_or_library(Path::new("target/debug/foo.rmeta")),
            "Rust metadata (.rmeta) should be skipped"
        );

        // dSYM bundles (macOS debug symbols)
        assert!(
            !is_binary_or_library(Path::new("target/debug/myapp.dSYM")),
            "dSYM bundles should be skipped"
        );

        // Other common non-binary files
        assert!(
            !is_binary_or_library(Path::new("target/debug/foo.o")),
            "Object files (.o) should be skipped"
        );
        assert!(
            !is_binary_or_library(Path::new("target/debug/foo.pdb")),
            "PDB files should be skipped"
        );
    }

    /// Test that paths are correctly categorized into watch events.
    #[test]
    fn test_categorize_path_binaries() {
        let target_dir = PathBuf::from("/project/target/debug");
        let config_files = vec![
            PathBuf::from("/project/jonesy.toml"),
            PathBuf::from("/project/Cargo.toml"),
        ];

        // Binary executable
        let evt = categorize_path(
            Path::new("/project/target/debug/myapp"),
            &target_dir,
            &config_files,
        );
        assert!(
            matches!(evt, Some(WatchEvent::BinaryChanged(_))),
            "Binary should trigger BinaryChanged"
        );

        // Rust library (.rlib)
        let evt = categorize_path(
            Path::new("/project/target/debug/libfoo.rlib"),
            &target_dir,
            &config_files,
        );
        assert!(
            matches!(evt, Some(WatchEvent::BinaryChanged(_))),
            "Rust library should trigger BinaryChanged"
        );

        // Dynamic library (.dylib)
        let evt = categorize_path(
            Path::new("/project/target/debug/libfoo.dylib"),
            &target_dir,
            &config_files,
        );
        assert!(
            matches!(evt, Some(WatchEvent::BinaryChanged(_))),
            "Dynamic library should trigger BinaryChanged"
        );

        // Dynamic library (.so)
        let evt = categorize_path(
            Path::new("/project/target/debug/libfoo.so"),
            &target_dir,
            &config_files,
        );
        assert!(
            matches!(evt, Some(WatchEvent::BinaryChanged(_))),
            "Shared object should trigger BinaryChanged"
        );

        // Static library (.a)
        let evt = categorize_path(
            Path::new("/project/target/debug/libfoo.a"),
            &target_dir,
            &config_files,
        );
        assert!(
            matches!(evt, Some(WatchEvent::BinaryChanged(_))),
            "Static library should trigger BinaryChanged"
        );
    }

    /// Test that config files are correctly categorized.
    #[test]
    fn test_categorize_path_config_files() {
        let target_dir = PathBuf::from("/project/target/debug");
        let config_files = vec![
            PathBuf::from("/project/jonesy.toml"),
            PathBuf::from("/project/Cargo.toml"),
            PathBuf::from("/project/crate_a/Cargo.toml"),
        ];

        // jonesy.toml
        let evt = categorize_path(
            Path::new("/project/jonesy.toml"),
            &target_dir,
            &config_files,
        );
        assert!(
            matches!(evt, Some(WatchEvent::ConfigChanged(_))),
            "jonesy.toml should trigger ConfigChanged"
        );

        // Workspace Cargo.toml
        let evt = categorize_path(Path::new("/project/Cargo.toml"), &target_dir, &config_files);
        assert!(
            matches!(evt, Some(WatchEvent::ConfigChanged(_))),
            "Workspace Cargo.toml should trigger ConfigChanged"
        );

        // Member Cargo.toml
        let evt = categorize_path(
            Path::new("/project/crate_a/Cargo.toml"),
            &target_dir,
            &config_files,
        );
        assert!(
            matches!(evt, Some(WatchEvent::ConfigChanged(_))),
            "Member Cargo.toml should trigger ConfigChanged"
        );
    }

    #[test]
    fn test_watcher_config_default() {
        let config = WatcherConfig::default();
        assert_eq!(config.target_dir, PathBuf::from("target/debug"));
        assert!(config.config_files.is_empty());
        assert_eq!(config.debounce, Duration::from_millis(500));
    }

    #[test]
    fn test_start_watching_with_real_directory() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_watcher");
        let _ = std::fs::create_dir_all(&temp_dir);

        let config = WatcherConfig {
            target_dir: temp_dir.clone(),
            config_files: vec![],
            debounce: Duration::from_millis(100),
        };

        let result = start_watching(config);
        assert!(
            result.is_ok(),
            "Should create watcher for existing directory"
        );

        // Drop the handle to stop watching
        drop(result);
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_start_watching_nonexistent_target_dir() {
        let config = WatcherConfig {
            target_dir: PathBuf::from("/nonexistent/target/debug"),
            config_files: vec![],
            debounce: Duration::from_millis(100),
        };

        // Should not error — it watches the parent if target doesn't exist
        let _result = start_watching(config);
    }

    #[test]
    fn test_start_watching_with_config_files() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_watcher_config");
        let _ = std::fs::create_dir_all(&temp_dir);

        let config_file = temp_dir.join("jonesy.toml");
        std::fs::write(&config_file, "# test").unwrap();

        let config = WatcherConfig {
            target_dir: temp_dir.clone(),
            config_files: vec![config_file],
            debounce: Duration::from_millis(100),
        };

        let result = start_watching(config);
        assert!(result.is_ok());

        drop(result);
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_is_binary_or_library_exe() {
        assert!(is_binary_or_library(Path::new("target/debug/foo.exe")));
    }

    /// Test that unrelated files are ignored.
    #[test]
    fn test_categorize_path_unrelated() {
        let target_dir = PathBuf::from("/project/target/debug");
        let config_files = vec![PathBuf::from("/project/jonesy.toml")];

        // Source files
        let evt = categorize_path(
            Path::new("/project/src/main.rs"),
            &target_dir,
            &config_files,
        );
        assert!(evt.is_none(), "Source files should be ignored");

        // Files outside target directory
        let evt = categorize_path(
            Path::new("/other/project/target/debug/myapp"),
            &target_dir,
            &config_files,
        );
        assert!(
            evt.is_none(),
            "Files outside watched target should be ignored"
        );

        // Non-watched config files
        let evt = categorize_path(
            Path::new("/project/rustfmt.toml"),
            &target_dir,
            &config_files,
        );
        assert!(evt.is_none(), "Non-jonesy config files should be ignored");

        // Files in target that aren't binaries
        let evt = categorize_path(
            Path::new("/project/target/debug/foo.d"),
            &target_dir,
            &config_files,
        );
        assert!(
            evt.is_none(),
            "Dependency files in target should be ignored"
        );
    }

    #[tokio::test]
    async fn test_debounced_events_single_event() {
        let (tx, rx) = mpsc::channel(10);
        let mut triggers = debounced_events(rx, Duration::from_millis(50)).await;

        // Send a binary change event
        tx.send(WatchEvent::BinaryChanged(PathBuf::from(
            "target/debug/myapp",
        )))
        .await
        .unwrap();

        // Should get a trigger after debounce
        let result = tokio::time::timeout(Duration::from_millis(200), triggers.recv()).await;
        assert!(result.is_ok(), "Should receive trigger after debounce");
        assert!(result.unwrap().is_some());
    }

    #[tokio::test]
    async fn test_debounced_events_coalesces_multiple() {
        let (tx, rx) = mpsc::channel(10);
        let mut triggers = debounced_events(rx, Duration::from_millis(100)).await;

        // Send multiple events rapidly
        tx.send(WatchEvent::BinaryChanged(PathBuf::from("a")))
            .await
            .unwrap();
        tx.send(WatchEvent::BinaryChanged(PathBuf::from("b")))
            .await
            .unwrap();
        tx.send(WatchEvent::ConfigChanged(PathBuf::from("c")))
            .await
            .unwrap();

        // Should get ONE trigger (coalesced)
        let result = tokio::time::timeout(Duration::from_millis(300), triggers.recv()).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());

        // No second trigger immediately
        let result2 = tokio::time::timeout(Duration::from_millis(50), triggers.recv()).await;
        assert!(result2.is_err(), "Should not get a second trigger");
    }

    #[tokio::test]
    async fn test_debounced_events_error_does_not_trigger() {
        let (tx, rx) = mpsc::channel(10);
        let mut triggers = debounced_events(rx, Duration::from_millis(50)).await;

        // Send an error event — should NOT trigger analysis
        tx.send(WatchEvent::Error("test error".to_string()))
            .await
            .unwrap();

        let result = tokio::time::timeout(Duration::from_millis(150), triggers.recv()).await;
        assert!(result.is_err(), "Error events should not trigger analysis");
    }

    #[tokio::test]
    async fn test_debounced_events_channel_close() {
        let (tx, rx) = mpsc::channel(10);
        let mut triggers = debounced_events(rx, Duration::from_millis(50)).await;

        // Drop sender to close the channel
        drop(tx);

        // Receiver should get None (closed)
        let result = tokio::time::timeout(Duration::from_millis(200), triggers.recv()).await;
        assert!(result.is_ok());
        assert!(
            result.unwrap().is_none(),
            "Should get None when channel closes"
        );
    }
}