rust/crates/ra_vfs/src/io.rs

70 lines
1.9 KiB
Rust
Raw Normal View History

2018-12-18 10:29:14 +01:00
use std::{
fs,
path::{Path, PathBuf},
};
2018-12-18 11:35:05 +01:00
use walkdir::{DirEntry, WalkDir};
use thread_worker::{WorkerHandle};
2018-12-18 14:38:05 +01:00
use relative_path::RelativePathBuf;
2018-12-18 11:35:05 +01:00
use crate::VfsRoot;
2018-12-18 14:38:05 +01:00
pub(crate) struct Task {
pub(crate) root: VfsRoot,
2018-12-18 11:35:05 +01:00
pub(crate) path: PathBuf,
2018-12-18 14:38:05 +01:00
pub(crate) filter: Box<Fn(&DirEntry) -> bool + Send>,
2018-12-18 11:18:55 +01:00
}
2018-12-18 10:29:14 +01:00
2018-12-18 14:38:05 +01:00
pub struct TaskResult {
pub(crate) root: VfsRoot,
pub(crate) files: Vec<(RelativePathBuf, String)>,
2018-12-18 11:18:55 +01:00
}
2018-12-18 10:29:14 +01:00
2018-12-18 14:38:05 +01:00
pub(crate) type Worker = thread_worker::Worker<Task, TaskResult>;
2018-12-18 11:35:05 +01:00
pub(crate) fn start() -> (Worker, WorkerHandle) {
thread_worker::spawn("vfs", 128, |input_receiver, output_sender| {
input_receiver
.map(handle_task)
.for_each(|it| output_sender.send(it))
})
}
2018-12-18 11:23:23 +01:00
2018-12-18 14:38:05 +01:00
fn handle_task(task: Task) -> TaskResult {
let Task { root, path, filter } = task;
2018-12-18 11:35:05 +01:00
log::debug!("loading {} ...", path.as_path().display());
2018-12-18 14:38:05 +01:00
let files = load_root(path.as_path(), &*filter);
2018-12-18 11:35:05 +01:00
log::debug!("... loaded {}", path.as_path().display());
2018-12-18 14:38:05 +01:00
TaskResult { root, files }
2018-12-18 11:18:55 +01:00
}
2018-12-18 10:29:14 +01:00
2018-12-18 14:38:05 +01:00
fn load_root(root: &Path, filter: &dyn Fn(&DirEntry) -> bool) -> Vec<(RelativePathBuf, String)> {
2018-12-18 11:18:55 +01:00
let mut res = Vec::new();
2018-12-18 14:38:05 +01:00
for entry in WalkDir::new(root).into_iter().filter_entry(filter) {
2018-12-18 11:18:55 +01:00
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();
if path.extension().and_then(|os| os.to_str()) != Some("rs") {
continue;
}
let text = match fs::read_to_string(path) {
Ok(text) => text,
Err(e) => {
log::warn!("watcher error: {}", e);
continue;
}
};
2018-12-18 14:38:05 +01:00
let path = RelativePathBuf::from_path(path.strip_prefix(root).unwrap()).unwrap();
res.push((path.to_owned(), text))
2018-12-18 11:18:55 +01:00
}
res
}