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
use std::sync::mpsc::{channel, Receiver};
use std::{path::PathBuf, sync::mpsc::Sender};

use anyhow::Result;
use notify::{Event, EventHandler, Watcher};

use crate::{WaitOptions, Waitable};

pub struct FileWaiter {
    pub path: PathBuf,
}

impl FileWaiter {
    pub fn new(path: PathBuf) -> Self {
        Self { path }
    }
}

impl Waitable for FileWaiter {
    async fn wait(self, _: WaitOptions) -> Result<()> {
        let (file_exists_handler, rx) = FileExistsHandler::new();
        let mut watcher = notify::recommended_watcher(file_exists_handler).unwrap();
        let parent = self.path.parent().unwrap();

        watcher
            .watch(parent, notify::RecursiveMode::NonRecursive)
            .unwrap();

        if rx.recv().is_ok() {
            watcher.unwatch(parent).unwrap();
        }

        Ok(())
    }
}

struct FileExistsHandler {
    tx: Sender<()>,
}

impl FileExistsHandler {
    pub fn new() -> (Self, Receiver<()>) {
        let (tx, rx) = channel();

        (Self { tx }, rx)
    }
}

impl EventHandler for FileExistsHandler {
    fn handle_event(&mut self, event: notify::Result<Event>) {
        if let Ok(event) = event {
            if let notify::EventKind::Create(_) = event.kind {
                self.tx.send(()).unwrap();
            }
        }
    }
}