aboutsummaryrefslogtreecommitdiff
path: root/crates/vfs-notify/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/vfs-notify/src/lib.rs')
-rw-r--r--crates/vfs-notify/src/lib.rs244
1 files changed, 244 insertions, 0 deletions
diff --git a/crates/vfs-notify/src/lib.rs b/crates/vfs-notify/src/lib.rs
new file mode 100644
index 000000000..a2f4e0c5b
--- /dev/null
+++ b/crates/vfs-notify/src/lib.rs
@@ -0,0 +1,244 @@
1//! An implementation of `loader::Handle`, based on `walkdir` and `notify`.
2//!
3//! The file watching bits here are untested and quite probably buggy. For this
4//! reason, by default we don't watch files and rely on editor's file watching
5//! capabilities.
6//!
7//! Hopefully, one day a reliable file watching/walking crate appears on
8//! crates.io, and we can reduce this to trivial glue code.
9mod include;
10
11use std::convert::{TryFrom, TryInto};
12
13use crossbeam_channel::{select, unbounded, Receiver};
14use notify::{RecommendedWatcher, RecursiveMode, Watcher};
15use paths::{AbsPath, AbsPathBuf};
16use rustc_hash::FxHashSet;
17use vfs::loader;
18use walkdir::WalkDir;
19
20use crate::include::Include;
21
22#[derive(Debug)]
23pub struct LoaderHandle {
24 // Relative order of fields below is significant.
25 sender: crossbeam_channel::Sender<Message>,
26 _thread: jod_thread::JoinHandle,
27}
28
29#[derive(Debug)]
30enum Message {
31 Config(loader::Config),
32 Invalidate(AbsPathBuf),
33}
34
35impl loader::Handle for LoaderHandle {
36 fn spawn(sender: loader::Sender) -> LoaderHandle {
37 let actor = LoaderActor::new(sender);
38 let (sender, receiver) = unbounded::<Message>();
39 let thread = jod_thread::spawn(move || actor.run(receiver));
40 LoaderHandle { sender, _thread: thread }
41 }
42 fn set_config(&mut self, config: loader::Config) {
43 self.sender.send(Message::Config(config)).unwrap()
44 }
45 fn invalidate(&mut self, path: AbsPathBuf) {
46 self.sender.send(Message::Invalidate(path)).unwrap();
47 }
48 fn load_sync(&mut self, path: &AbsPath) -> Option<Vec<u8>> {
49 read(path)
50 }
51}
52
53type NotifyEvent = notify::Result<notify::Event>;
54
55struct LoaderActor {
56 config: Vec<(AbsPathBuf, Include, bool)>,
57 watched_paths: FxHashSet<AbsPathBuf>,
58 sender: loader::Sender,
59 // Drop order of fields bellow is significant,
60 watcher: Option<RecommendedWatcher>,
61 watcher_receiver: Receiver<NotifyEvent>,
62}
63
64#[derive(Debug)]
65enum Event {
66 Message(Message),
67 NotifyEvent(NotifyEvent),
68}
69
70impl LoaderActor {
71 fn new(sender: loader::Sender) -> LoaderActor {
72 let (watcher_sender, watcher_receiver) = unbounded();
73 let watcher = log_notify_error(Watcher::new_immediate(move |event| {
74 watcher_sender.send(event).unwrap()
75 }));
76
77 LoaderActor {
78 watcher,
79 watcher_receiver,
80 watched_paths: FxHashSet::default(),
81 sender,
82 config: Vec::new(),
83 }
84 }
85
86 fn run(mut self, receiver: Receiver<Message>) {
87 while let Some(event) = self.next_event(&receiver) {
88 log::debug!("vfs-notify event: {:?}", event);
89 match event {
90 Event::Message(msg) => match msg {
91 Message::Config(config) => {
92 let n_total = config.load.len();
93 self.send(loader::Message::Progress { n_total, n_done: 0 });
94
95 self.unwatch_all();
96 self.config.clear();
97
98 for (i, entry) in config.load.into_iter().enumerate() {
99 let watch = config.watch.contains(&i);
100 let files = self.load_entry(entry, watch);
101 self.send(loader::Message::Loaded { files });
102 self.send(loader::Message::Progress { n_total, n_done: i + 1 });
103 }
104 self.config.sort_by(|x, y| x.0.cmp(&y.0));
105 }
106 Message::Invalidate(path) => {
107 let contents = read(path.as_path());
108 let files = vec![(path, contents)];
109 self.send(loader::Message::Loaded { files });
110 }
111 },
112 Event::NotifyEvent(event) => {
113 if let Some(event) = log_notify_error(event) {
114 let files = event
115 .paths
116 .into_iter()
117 .map(|path| AbsPathBuf::try_from(path).unwrap())
118 .filter_map(|path| {
119 let is_dir = path.is_dir();
120 let is_file = path.is_file();
121
122 let config_idx =
123 match self.config.binary_search_by(|it| it.0.cmp(&path)) {
124 Ok(it) => it,
125 Err(it) => it.saturating_sub(1),
126 };
127 let include = self.config.get(config_idx).and_then(|it| {
128 let rel_path = path.strip_prefix(&it.0)?;
129 Some((rel_path, &it.1))
130 });
131
132 if let Some((rel_path, include)) = include {
133 if is_dir && include.exclude_dir(&rel_path)
134 || is_file && !include.include_file(&rel_path)
135 {
136 return None;
137 }
138 }
139
140 if is_dir {
141 self.watch(path);
142 return None;
143 }
144 if !is_file {
145 return None;
146 }
147 let contents = read(&path);
148 Some((path, contents))
149 })
150 .collect();
151 self.send(loader::Message::Loaded { files })
152 }
153 }
154 }
155 }
156 }
157 fn next_event(&self, receiver: &Receiver<Message>) -> Option<Event> {
158 select! {
159 recv(receiver) -> it => it.ok().map(Event::Message),
160 recv(&self.watcher_receiver) -> it => Some(Event::NotifyEvent(it.unwrap())),
161 }
162 }
163 fn load_entry(
164 &mut self,
165 entry: loader::Entry,
166 watch: bool,
167 ) -> Vec<(AbsPathBuf, Option<Vec<u8>>)> {
168 match entry {
169 loader::Entry::Files(files) => files
170 .into_iter()
171 .map(|file| {
172 if watch {
173 self.watch(file.clone())
174 }
175 let contents = read(file.as_path());
176 (file, contents)
177 })
178 .collect::<Vec<_>>(),
179 loader::Entry::Directory { path, include } => {
180 let include = Include::new(include);
181 self.config.push((path.clone(), include.clone(), watch));
182
183 let files = WalkDir::new(&path)
184 .into_iter()
185 .filter_entry(|entry| {
186 let abs_path: &AbsPath = entry.path().try_into().unwrap();
187 match abs_path.strip_prefix(&path) {
188 Some(rel_path) => {
189 !(entry.file_type().is_dir() && include.exclude_dir(rel_path))
190 }
191 None => false,
192 }
193 })
194 .filter_map(|entry| entry.ok())
195 .filter_map(|entry| {
196 let is_dir = entry.file_type().is_dir();
197 let is_file = entry.file_type().is_file();
198 let abs_path = AbsPathBuf::try_from(entry.into_path()).unwrap();
199 if is_dir && watch {
200 self.watch(abs_path.clone());
201 }
202 let rel_path = abs_path.strip_prefix(&path)?;
203 if is_file && include.include_file(&rel_path) {
204 Some(abs_path)
205 } else {
206 None
207 }
208 });
209
210 files
211 .map(|file| {
212 let contents = read(file.as_path());
213 (file, contents)
214 })
215 .collect()
216 }
217 }
218 }
219
220 fn watch(&mut self, path: AbsPathBuf) {
221 if let Some(watcher) = &mut self.watcher {
222 log_notify_error(watcher.watch(&path, RecursiveMode::NonRecursive));
223 self.watched_paths.insert(path);
224 }
225 }
226 fn unwatch_all(&mut self) {
227 if let Some(watcher) = &mut self.watcher {
228 for path in self.watched_paths.drain() {
229 log_notify_error(watcher.unwatch(path));
230 }
231 }
232 }
233 fn send(&mut self, msg: loader::Message) {
234 (self.sender)(msg)
235 }
236}
237
238fn read(path: &AbsPath) -> Option<Vec<u8>> {
239 std::fs::read(path).ok()
240}
241
242fn log_notify_error<T>(res: notify::Result<T>) -> Option<T> {
243 res.map_err(|err| log::warn!("notify error: {}", err)).ok()
244}