|
| 1 | +use std::{path::PathBuf, sync::Arc, time::Duration}; |
| 2 | + |
| 3 | +use anyhow::Result; |
| 4 | +use async_lsp::{LanguageServer, ServerSocket}; |
| 5 | +use lsp_types::{DidChangeWatchedFilesParams, FileChangeType, FileEvent}; |
| 6 | +use notify_debouncer_mini::{ |
| 7 | + DebounceEventResult, DebouncedEvent, Debouncer, new_debouncer, notify::*, |
| 8 | +}; |
| 9 | +use tokio::{runtime::Handle, sync::Mutex}; |
| 10 | +use url::Url; |
| 11 | + |
| 12 | +use crate::project::Project; |
| 13 | + |
| 14 | +#[derive(Debug)] |
| 15 | +pub struct ChangeNotifier { |
| 16 | + #[allow(dead_code)] // Keep the handle to ensure the change notifier runs |
| 17 | + debouncer: Debouncer<FsEventWatcher>, |
| 18 | +} |
| 19 | + |
| 20 | +impl ChangeNotifier { |
| 21 | + pub fn new( |
| 22 | + server: Arc<Mutex<ServerSocket>>, |
| 23 | + project: &Project, |
| 24 | + handle: Handle, |
| 25 | + ) -> Result<Self> { |
| 26 | + let handle_clone = handle.clone(); |
| 27 | + let target_path = project.root().join("target"); |
| 28 | + let mut debouncer = new_debouncer( |
| 29 | + Duration::from_secs(2), |
| 30 | + move |res: DebounceEventResult| match res { |
| 31 | + Ok(events) => events.iter().for_each(|e| { |
| 32 | + handle_event(e, server.clone(), handle_clone.clone(), target_path.clone()) |
| 33 | + }), |
| 34 | + Err(e) => tracing::error!("Error {:?}", e), |
| 35 | + }, |
| 36 | + )?; |
| 37 | + |
| 38 | + // We watch the root folder |
| 39 | + debouncer |
| 40 | + .watcher() |
| 41 | + .watch(project.root(), RecursiveMode::Recursive)?; |
| 42 | + Ok(Self { debouncer }) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +fn handle_event( |
| 47 | + event: &DebouncedEvent, |
| 48 | + server: Arc<Mutex<ServerSocket>>, |
| 49 | + handle: Handle, |
| 50 | + target_path: PathBuf, |
| 51 | +) { |
| 52 | + // Don't trigger lsp on target files. Otherwise it will trigger itself. |
| 53 | + if event.path.starts_with(&target_path) { |
| 54 | + return; |
| 55 | + } |
| 56 | + tracing::trace!("Event {:?} for {:?}", event.kind, event.path); |
| 57 | + let url = match Url::from_file_path(event.path.clone()) { |
| 58 | + Ok(url) => url, |
| 59 | + Err(e) => { |
| 60 | + tracing::error!("Failed to convert file path to URL: {:?}", e); |
| 61 | + return; |
| 62 | + } |
| 63 | + }; |
| 64 | + handle.spawn(async move { |
| 65 | + match server |
| 66 | + .lock() |
| 67 | + .await |
| 68 | + .did_change_watched_files(DidChangeWatchedFilesParams { |
| 69 | + changes: vec![FileEvent::new(url, FileChangeType::CHANGED)], |
| 70 | + }) { |
| 71 | + Ok(_) => (), |
| 72 | + Err(e) => tracing::error!("Failed to send DidChangeWatchedFiles notification: {:?}", e), |
| 73 | + } |
| 74 | + }); |
| 75 | +} |
0 commit comments