watcher.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. use std::{path::Path, time::Duration};
  2. use super::Event;
  3. use crate::path;
  4. use async_std::task::{sleep, spawn_blocking};
  5. use crossbeam_channel::{bounded, Sender};
  6. use notify::{Config, RecommendedWatcher, RecursiveMode, Result, Watcher};
  7. pub async fn create(sender: Sender<Event>) {
  8. loop {
  9. let watch_sender = sender.clone();
  10. match spawn_blocking(|| {
  11. watch(
  12. format!("{}/logs/", path().to_str().unwrap_or_default()),
  13. watch_sender,
  14. )
  15. })
  16. .await
  17. {
  18. Ok(_) => (),
  19. Err(e) => println!("error: {e}"),
  20. }
  21. sleep(Duration::from_secs(1)).await;
  22. }
  23. }
  24. fn watch<P: AsRef<Path>>(path: P, sender: Sender<Event>) -> Result<()> {
  25. let (tx, rx) = bounded(10);
  26. let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
  27. watcher.watch(path.as_ref(), RecursiveMode::Recursive)?;
  28. for res in rx {
  29. let event = res?;
  30. for p in event.paths {
  31. let path = p
  32. .file_name()
  33. .unwrap_or_default()
  34. .to_str()
  35. .unwrap_or_default()
  36. .to_owned();
  37. if path.len() > 0 {
  38. sender.send(Event::FileChange(path)).unwrap_or_default();
  39. }
  40. }
  41. }
  42. Ok(())
  43. }