rustlings/src/watch/notify_event.rs

53 lines
1.8 KiB
Rust
Raw Normal View History

2024-04-10 17:02:12 +03:00
use notify_debouncer_mini::{DebounceEventResult, DebouncedEventKind};
2024-04-14 03:41:19 +03:00
use std::sync::mpsc::Sender;
2024-04-10 17:02:12 +03:00
use super::WatchEvent;
2024-05-14 02:49:22 +03:00
pub struct NotifyEventHandler {
2024-04-10 17:02:12 +03:00
pub tx: Sender<WatchEvent>,
2024-05-14 02:49:22 +03:00
/// Used to report which exercise was modified.
2024-04-25 15:44:12 +03:00
pub exercise_names: &'static [&'static [u8]],
2024-04-10 17:02:12 +03:00
}
2024-05-14 02:49:22 +03:00
impl notify_debouncer_mini::DebounceEventHandler for NotifyEventHandler {
2024-05-13 17:44:48 +03:00
fn handle_event(&mut self, input_event: DebounceEventResult) {
let output_event = match input_event {
Ok(input_event) => {
let Some(exercise_ind) = input_event
2024-04-10 17:02:12 +03:00
.iter()
2024-05-13 17:44:48 +03:00
.filter_map(|input_event| {
if input_event.kind != DebouncedEventKind::Any {
2024-04-10 17:02:12 +03:00
return None;
}
2024-05-13 17:44:48 +03:00
let file_name = input_event.path.file_name()?.to_str()?.as_bytes();
2024-04-25 15:44:12 +03:00
if file_name.len() < 4 {
return None;
}
let (file_name_without_ext, ext) = file_name.split_at(file_name.len() - 3);
if ext != b".rs" {
return None;
}
self.exercise_names
2024-04-10 17:02:12 +03:00
.iter()
2024-04-25 15:44:12 +03:00
.position(|exercise_name| *exercise_name == file_name_without_ext)
2024-04-10 17:02:12 +03:00
})
.min()
else {
return;
};
WatchEvent::FileChange { exercise_ind }
}
Err(e) => WatchEvent::NotifyErr(e),
};
// An error occurs when the receiver is dropped.
// After dropping the receiver, the debouncer guard should also be dropped.
2024-05-13 17:44:48 +03:00
let _ = self.tx.send(output_event);
2024-04-10 17:02:12 +03:00
}
}