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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use crate::{
    check_ignore,
    error::{Error, Result},
    IgnoreRules, MatchResult,
};
use notify::{Event, EventHandler, RecommendedWatcher, RecursiveMode, Watcher};
use std::fs::Metadata;
use std::path::PathBuf;
use xvc_logging::watch;

use crossbeam_channel::{bounded, Receiver, Sender};
use log::{debug, warn};

#[derive(Debug)]
pub enum PathEvent {
    Create { path: PathBuf, metadata: Metadata },
    Update { path: PathBuf, metadata: Metadata },
    Delete { path: PathBuf },
}

struct PathEventHandler {
    sender: Sender<PathEvent>,
    ignore_rules: IgnoreRules,
}

impl EventHandler for PathEventHandler {
    fn handle_event(&mut self, event: notify::Result<Event>) {
        if let Ok(event) = event {
            match event.kind {
                notify::EventKind::Create(_) => self.create_event(event.paths[0].clone()),
                notify::EventKind::Modify(mk) => match mk {
                    notify::event::ModifyKind::Any => todo!(),
                    notify::event::ModifyKind::Data(_) => self.write_event(event.paths[0].clone()),
                    notify::event::ModifyKind::Metadata(_) => {
                        self.write_event(event.paths[0].clone())
                    }
                    notify::event::ModifyKind::Name(rk) => match rk {
                        notify::event::RenameMode::Any => {}
                        notify::event::RenameMode::To => self.create_event(event.paths[0].clone()),
                        notify::event::RenameMode::From => {
                            self.remove_event(event.paths[0].clone())
                        }
                        notify::event::RenameMode::Both => {
                            self.rename_event(event.paths[0].clone(), event.paths[1].clone())
                        }
                        notify::event::RenameMode::Other => {}
                    },
                    notify::event::ModifyKind::Other => {}
                },
                notify::EventKind::Remove(_) => self.remove_event(event.paths[0].clone()),
                notify::EventKind::Any => {}
                notify::EventKind::Access(_) => {}
                notify::EventKind::Other => {}
            }
        } else {
            debug!("{:?}", event);
        }
    }
}

impl PathEventHandler {
    fn write_event(&mut self, path: PathBuf) {
        match check_ignore(&self.ignore_rules, &path) {
            MatchResult::Whitelist | MatchResult::NoMatch => {
                self.sender
                    .send(PathEvent::Create {
                        path: path.clone(),
                        metadata: path.metadata().map_err(Error::from).unwrap(),
                    })
                    .unwrap_or_else(|e| warn!("{}", e));
            }
            MatchResult::Ignore => {
                debug!("FS Notification Ignored: {}", path.to_string_lossy());
            }
        }
    }

    fn create_event(&mut self, path: PathBuf) {
        match check_ignore(&self.ignore_rules, &path) {
            MatchResult::Whitelist | MatchResult::NoMatch => {
                self.sender
                    .send(PathEvent::Create {
                        path: path.clone(),
                        metadata: path.metadata().map_err(Error::from).unwrap(),
                    })
                    .unwrap_or_else(|e| {
                        Error::from(e).warn();
                    });
            }
            MatchResult::Ignore => {
                debug!("FS Notification Ignored: {}", path.to_string_lossy());
            }
        }
    }

    fn remove_event(&mut self, path: PathBuf) {
        match check_ignore(&self.ignore_rules, &path) {
            MatchResult::Whitelist | MatchResult::NoMatch => {
                self.sender
                    .send(PathEvent::Delete { path })
                    .unwrap_or_else(|e| warn!("{}", e));
            }
            MatchResult::Ignore => {
                debug!("FS Notification Ignored: {}", path.to_string_lossy());
            }
        }
    }

    fn rename_event(&mut self, from: PathBuf, to: PathBuf) {
        self.remove_event(from);
        self.create_event(to);
    }
}

pub fn make_watcher(
    ignore_rules: IgnoreRules,
) -> Result<(RecommendedWatcher, Receiver<PathEvent>)> {
    let (sender, receiver) = bounded(10000);
    let root = ignore_rules.root.clone();
    watch!(ignore_rules);
    let mut watcher = notify::recommended_watcher(PathEventHandler {
        ignore_rules,
        sender,
    })?;
    watcher.watch(&root, RecursiveMode::Recursive)?;
    watch!(watcher);
    watch!(receiver);
    Ok((watcher, receiver))
}