rust/crates/ra_vfs/src/io.rs

72 lines
1.8 KiB
Rust
Raw Normal View History

2018-12-18 10:29:14 +01:00
use std::{
fs,
path::{Path, PathBuf},
thread::JoinHandle,
};
use walkdir::WalkDir;
use crossbeam_channel::{Sender, Receiver};
2018-12-18 11:18:55 +01:00
use thread_worker::{WorkerHandle, Worker};
2018-12-18 10:29:14 +01:00
2018-12-18 11:18:55 +01:00
#[derive(Debug)]
pub struct FileEvent {
pub path: PathBuf,
pub kind: FileEventKind,
}
2018-12-18 10:29:14 +01:00
2018-12-18 11:18:55 +01:00
#[derive(Debug)]
pub enum FileEventKind {
Add(String),
}
2018-12-18 10:29:14 +01:00
2018-12-18 11:23:23 +01:00
pub(crate) type FsWorker = Worker<PathBuf, (PathBuf, Vec<FileEvent>)>;
pub(crate) fn start() -> (FsWorker, WorkerHandle) {
2018-12-18 11:18:55 +01:00
thread_worker::spawn::<PathBuf, (PathBuf, Vec<FileEvent>), _>(
"vfs",
128,
|input_receiver, output_sender| {
input_receiver
.map(|path| {
log::debug!("loading {} ...", path.as_path().display());
let events = load_root(path.as_path());
log::debug!("... loaded {}", path.as_path().display());
(path, events)
})
.for_each(|it| output_sender.send(it))
},
)
}
2018-12-18 10:29:14 +01:00
2018-12-18 11:18:55 +01:00
fn load_root(path: &Path) -> Vec<FileEvent> {
let mut res = Vec::new();
for entry in WalkDir::new(path) {
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;
}
};
res.push(FileEvent {
path: path.to_owned(),
kind: FileEventKind::Add(text),
})
}
res
}