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
use std::path::Path;

use futures::{
    channel::mpsc::{channel, Receiver},
    executor::block_on,
    SinkExt,
};
use notify::{Config, Error, Event, RecommendedWatcher, RecursiveMode, Watcher};

use crate::{XError, XErrorKind, XResult};

impl From<Error> for XError {
    fn from(e: Error) -> Self {
        XError {
            kind: Box::new(XErrorKind::RuntimeError { message: e.to_string() }),
            path: None,
            position: None,
            source: Some(Box::new(e)),
        }
    }
}

pub fn file_watcher(path: &Path) -> XResult<Receiver<Result<Event, Error>>> {
    let config = Config::default().with_compare_contents(true);
    let (mut tx, receiver) = channel(1);
    let mut watcher = RecommendedWatcher::new(
        move |res| {
            block_on(async {
                //
                tx.send(res).await.ok().unwrap_or_default()
            })
        },
        config,
    )?;
    watcher.watch(path, RecursiveMode::Recursive)?;
    Ok(receiver)
}