aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_vfs/src/io/watcher.rs
blob: ff6775f59402cf13c65bebf496d78109aed917f8 (plain)
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use crate::{io, RootFilter, Roots, VfsRoot};
use crossbeam_channel::Sender;
use drop_bomb::DropBomb;
use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher as NotifyWatcher};
use parking_lot::Mutex;
use std::{
    fs,
    path::{Path, PathBuf},
    sync::{mpsc, Arc},
    thread,
    time::Duration,
};
use walkdir::WalkDir;

#[derive(Debug)]
enum ChangeKind {
    Create,
    Write,
    Remove,
}

const WATCHER_DELAY: Duration = Duration::from_millis(250);

pub(crate) struct Watcher {
    thread: thread::JoinHandle<()>,
    bomb: DropBomb,
    watcher: Arc<Mutex<Option<RecommendedWatcher>>>,
}

impl Watcher {
    pub(crate) fn start(
        roots: Arc<Roots>,
        output_sender: Sender<io::TaskResult>,
    ) -> Result<Watcher, Box<std::error::Error>> {
        let (input_sender, input_receiver) = mpsc::channel();
        let watcher = Arc::new(Mutex::new(Some(notify::watcher(
            input_sender,
            WATCHER_DELAY,
        )?)));
        let sender = output_sender.clone();
        let watcher_clone = watcher.clone();
        let thread = thread::spawn(move || {
            let worker = WatcherWorker {
                roots,
                watcher: watcher_clone,
                sender,
            };
            input_receiver
                .into_iter()
                // forward relevant events only
                .try_for_each(|change| worker.handle_debounced_event(change))
                .unwrap()
        });
        Ok(Watcher {
            thread,
            watcher,
            bomb: DropBomb::new(format!("Watcher was not shutdown")),
        })
    }

    pub fn watch_root(&mut self, filter: &RootFilter) {
        for res in WalkDir::new(&filter.root)
            .into_iter()
            .filter_entry(filter.entry_filter())
        {
            match res {
                Ok(entry) => {
                    if entry.file_type().is_dir() {
                        watch_one(self.watcher.as_ref(), entry.path());
                    }
                }
                Err(e) => log::warn!("watcher error: {}", e),
            }
        }
    }

    pub fn shutdown(mut self) -> thread::Result<()> {
        self.bomb.defuse();
        drop(self.watcher.lock().take());
        let res = self.thread.join();
        match &res {
            Ok(()) => log::info!("... Watcher terminated with ok"),
            Err(_) => log::error!("... Watcher terminated with err"),
        }
        res
    }
}

struct WatcherWorker {
    watcher: Arc<Mutex<Option<RecommendedWatcher>>>,
    roots: Arc<Roots>,
    sender: Sender<io::TaskResult>,
}

impl WatcherWorker {
    fn handle_debounced_event(&self, ev: DebouncedEvent) -> Result<(), Box<std::error::Error>> {
        match ev {
            DebouncedEvent::NoticeWrite(_)
            | DebouncedEvent::NoticeRemove(_)
            | DebouncedEvent::Chmod(_) => {
                // ignore
            }
            DebouncedEvent::Rescan => {
                // TODO rescan all roots
            }
            DebouncedEvent::Create(path) => {
                self.handle_change(path, ChangeKind::Create);
            }
            DebouncedEvent::Write(path) => {
                self.handle_change(path, ChangeKind::Write);
            }
            DebouncedEvent::Remove(path) => {
                self.handle_change(path, ChangeKind::Remove);
            }
            DebouncedEvent::Rename(src, dst) => {
                self.handle_change(src, ChangeKind::Remove);
                self.handle_change(dst, ChangeKind::Create);
            }
            DebouncedEvent::Error(err, path) => {
                // TODO should we reload the file contents?
                log::warn!("watcher error \"{}\", {:?}", err, path);
            }
        }
        Ok(())
    }

    fn handle_change(&self, path: PathBuf, kind: ChangeKind) {
        if let Err(e) = self.try_handle_change(path, kind) {
            log::warn!("watcher error: {}", e)
        }
    }

    fn try_handle_change(
        &self,
        path: PathBuf,
        kind: ChangeKind,
    ) -> Result<(), Box<std::error::Error>> {
        let (root, rel_path) = match self.roots.find(&path) {
            Some(x) => x,
            None => return Ok(()),
        };
        match kind {
            ChangeKind::Create => {
                if path.is_dir() {
                    self.watch_recursive(&path, root);
                } else {
                    let text = fs::read_to_string(&path)?;
                    self.sender.send(io::TaskResult::AddSingleFile {
                        root,
                        path: rel_path,
                        text,
                    })?
                }
            }
            ChangeKind::Write => {
                let text = fs::read_to_string(&path)?;
                self.sender.send(io::TaskResult::ChangeSingleFile {
                    root,
                    path: rel_path,
                    text,
                })?
            }
            ChangeKind::Remove => self.sender.send(io::TaskResult::RemoveSingleFile {
                root,
                path: rel_path,
            })?,
        }
        Ok(())
    }

    fn watch_recursive(&self, dir: &Path, root: VfsRoot) {
        let filter = &self.roots[root];
        for res in WalkDir::new(dir)
            .into_iter()
            .filter_entry(filter.entry_filter())
        {
            match res {
                Ok(entry) => {
                    if entry.file_type().is_dir() {
                        watch_one(self.watcher.as_ref(), entry.path());
                    } else {
                        // emit only for files otherwise we will cause watch_recursive to be called again with a dir that we are already watching
                        // emit as create because we haven't seen it yet
                        self.handle_change(entry.path().to_path_buf(), ChangeKind::Create);
                    }
                }
                Err(e) => log::warn!("watcher error: {}", e),
            }
        }
    }
}

fn watch_one(watcher: &Mutex<Option<RecommendedWatcher>>, dir: &Path) {
    if let Some(watcher) = watcher.lock().as_mut() {
        match watcher.watch(dir, RecursiveMode::NonRecursive) {
            Ok(()) => log::debug!("watching \"{}\"", dir.display()),
            Err(e) => log::warn!("could not watch \"{}\": {}", dir.display(), e),
        }
    }
}