aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_vfs/src/io.rs
blob: 25acec9b1da4bf897256447b2995f233e929ab18 (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
201
202
203
204
205
206
207
208
209
use std::{
    fmt, fs,
    path::{Path, PathBuf},
    sync::Arc,
    thread,
};

use crossbeam_channel::{Receiver, Sender};
use parking_lot::Mutex;
use relative_path::RelativePathBuf;
use thread_worker::WorkerHandle;
use walkdir::{DirEntry, WalkDir};

use crate::{
    watcher::{Watcher, WatcherChange},
    VfsRoot,
};

pub(crate) enum Task {
    AddRoot {
        root: VfsRoot,
        path: PathBuf,
        filter: Box<Fn(&DirEntry) -> bool + Send>,
    },
    HandleChange(WatcherChange),
    LoadChange(WatcherChange),
    Watch {
        dir: PathBuf,
        filter: Box<Fn(&DirEntry) -> bool + Send>,
    },
}

#[derive(Debug)]
pub struct AddRootResult {
    pub(crate) root: VfsRoot,
    pub(crate) files: Vec<(RelativePathBuf, String)>,
}

#[derive(Debug)]
pub enum WatcherChangeData {
    Create { path: PathBuf, text: String },
    Write { path: PathBuf, text: String },
    Remove { path: PathBuf },
}

pub enum TaskResult {
    AddRoot(AddRootResult),
    HandleChange(WatcherChange),
    LoadChange(WatcherChangeData),
    NoOp,
}

impl fmt::Debug for TaskResult {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("TaskResult { ... }")
    }
}

pub(crate) struct Worker {
    worker: thread_worker::Worker<Task, TaskResult>,
    worker_handle: WorkerHandle,
    watcher: Arc<Mutex<Option<Watcher>>>,
}

impl Worker {
    pub(crate) fn start() -> Worker {
        let watcher = Arc::new(Mutex::new(None));
        let watcher_clone = watcher.clone();
        let (worker, worker_handle) =
            thread_worker::spawn("vfs", 128, move |input_receiver, output_sender| {
                let res = input_receiver
                    .into_iter()
                    .map(|t| handle_task(t, &watcher_clone))
                    .try_for_each(|it| output_sender.send(it));
                res.unwrap()
            });
        match Watcher::start(worker.inp.clone()) {
            Ok(w) => {
                watcher.lock().replace(w);
            }
            Err(e) => log::error!("could not start watcher: {}", e),
        };
        Worker {
            worker,
            worker_handle,
            watcher,
        }
    }

    pub(crate) fn sender(&self) -> &Sender<Task> {
        &self.worker.inp
    }

    pub(crate) fn receiver(&self) -> &Receiver<TaskResult> {
        &self.worker.out
    }

    pub(crate) fn shutdown(self) -> thread::Result<()> {
        if let Some(watcher) = self.watcher.lock().take() {
            let _ = watcher.shutdown();
        }
        self.worker_handle.shutdown()
    }
}

fn watch(
    watcher: &Arc<Mutex<Option<Watcher>>>,
    dir: &Path,
    filter_entry: impl Fn(&DirEntry) -> bool,
    emit_for_existing: bool,
) {
    let mut watcher = watcher.lock();
    let watcher = match *watcher {
        Some(ref mut w) => w,
        None => {
            // watcher dropped or couldn't start
            return;
        }
    };
    watcher.watch_recursive(dir, filter_entry, emit_for_existing)
}

fn handle_task(task: Task, watcher: &Arc<Mutex<Option<Watcher>>>) -> TaskResult {
    match task {
        Task::AddRoot { root, path, filter } => {
            watch(watcher, &path, &*filter, false);
            log::debug!("loading {} ...", path.as_path().display());
            let files = load_root(path.as_path(), &*filter);
            log::debug!("... loaded {}", path.as_path().display());
            TaskResult::AddRoot(AddRootResult { root, files })
        }
        Task::HandleChange(change) => {
            // forward as is because Vfs has to decide if we should load it
            TaskResult::HandleChange(change)
        }
        Task::LoadChange(change) => {
            log::debug!("loading {:?} ...", change);
            match load_change(change) {
                Some(data) => TaskResult::LoadChange(data),
                None => TaskResult::NoOp,
            }
        }
        Task::Watch { dir, filter } => {
            watch(watcher, &dir, &*filter, true);
            TaskResult::NoOp
        }
    }
}

fn load_root(root: &Path, filter: &dyn Fn(&DirEntry) -> bool) -> Vec<(RelativePathBuf, String)> {
    let mut res = Vec::new();
    for entry in WalkDir::new(root).into_iter().filter_entry(filter) {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                log::warn!("watcher error: {}", e);
                continue;
            }
        };
        if !entry.file_type().is_file() {
            continue;
        }
        let path = entry.path();
        let text = match fs::read_to_string(path) {
            Ok(text) => text,
            Err(e) => {
                log::warn!("watcher error: {}", e);
                continue;
            }
        };
        let path = RelativePathBuf::from_path(path.strip_prefix(root).unwrap()).unwrap();
        res.push((path.to_owned(), text))
    }
    res
}

fn load_change(change: WatcherChange) -> Option<WatcherChangeData> {
    let data = match change {
        WatcherChange::Create(path) => {
            if path.is_dir() {
                return None;
            }
            let text = match fs::read_to_string(&path) {
                Ok(text) => text,
                Err(e) => {
                    log::warn!("watcher error \"{}\": {}", path.display(), e);
                    return None;
                }
            };
            WatcherChangeData::Create { path, text }
        }
        WatcherChange::Write(path) => {
            let text = match fs::read_to_string(&path) {
                Ok(text) => text,
                Err(e) => {
                    log::warn!("watcher error \"{}\": {}", path.display(), e);
                    return None;
                }
            };
            WatcherChangeData::Write { path, text }
        }
        WatcherChange::Remove(path) => WatcherChangeData::Remove { path },
        WatcherChange::Rescan => {
            // this should be handled by Vfs::handle_task
            return None;
        }
    };
    Some(data)
}