├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── azure-pipelines.yml ├── bors.toml ├── rustfmt.toml ├── src ├── io.rs ├── lib.rs └── roots.rs └── tests └── vfs.rs /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | /target/ 3 | **/*.rs.bk 4 | .idea/* 5 | *.log 6 | *.iml 7 | .vscode/settings.json 8 | 9 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "ra_vfs" 4 | version = "0.6.1" 5 | authors = ["rust-analyzer developers"] 6 | description = "Virtual File System abstraction for rust-analyzer" 7 | license = "Apache-2.0 OR MIT" 8 | repository = "https://github.com/rust-analyzer/ra_vfs" 9 | 10 | [dependencies] 11 | jod-thread = "0.1.0" 12 | walkdir = "2.2.7" 13 | relative-path = "1.0.0" 14 | rustc-hash = "1.0" 15 | crossbeam-channel = "0.4" 16 | log = "0.4.6" 17 | notify = "4.0.9" 18 | parking_lot = "0.10.0" 19 | 20 | [dev-dependencies] 21 | flexi_logger = "0.15.2" 22 | tempfile = "3" 23 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ra_vfs 2 | 3 | [![Build Status](https://dev.azure.com/rust-analyzer/rust-analyzer/_apis/build/status/rust-analyzer.ra_vfs?branchName=master)](https://dev.azure.com/rust-analyzer/rust-analyzer/_build/latest?definitionId=1&branchName=master) 4 | 5 | A virtual file system abstraction for rust-analyzer. 6 | 7 | This lives outside of the main rust-analyzer repository because we want to 8 | separate CI. VFS is hugely platform dependent, so CI for it tends to 9 | be longer and more brittle. 10 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # https://aka.ms/yaml 2 | 3 | trigger: 4 | - master 5 | - staging 6 | - trying 7 | 8 | jobs: 9 | - job: Linux 10 | pool: 11 | vmImage: 'ubuntu-16.04' 12 | steps: 13 | - script: | 14 | curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain stable 15 | echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin" 16 | displayName: 'Install rust' 17 | - script: rustup update stable 18 | - script: rustc --version 19 | - script: cargo test -- --nocapture 20 | - script: cargo test --release -- --nocapture 21 | 22 | - job: macOS 23 | pool: 24 | vmImage: 'macOS-10.13' 25 | steps: 26 | - script: | 27 | curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain stable 28 | echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin" 29 | displayName: 'Install rust' 30 | - script: rustup update stable 31 | - script: rustc --version 32 | - script: cargo test -- --nocapture 33 | - script: cargo test --release -- --nocapture 34 | 35 | - job: Windows 36 | pool: 37 | vmImage: 'vs2017-win2016' 38 | steps: 39 | - script: | 40 | curl -sSf -o rustup-init.exe https://win.rustup.rs 41 | rustup-init.exe -y --default-toolchain stable 42 | echo "##vso[task.setvariable variable=PATH;]%PATH%;%USERPROFILE%\.cargo\bin" 43 | displayName: 'Install rust' 44 | - script: rustup update stable 45 | - script: rustc --version 46 | - script: cargo test -- --nocapture 47 | - script: cargo test --release -- --nocapture 48 | -------------------------------------------------------------------------------- /bors.toml: -------------------------------------------------------------------------------- 1 | status = [ 2 | "rust-analyzer.ra_vfs" 3 | ] 4 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | reorder_imports = false 2 | reorder_modules = false 3 | use_small_heuristics = "Max" 4 | -------------------------------------------------------------------------------- /src/io.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | path::{Path, PathBuf}, 3 | sync::{mpsc, Arc}, 4 | time::Duration, 5 | }; 6 | use crossbeam_channel::{Sender, unbounded, RecvError, select}; 7 | use relative_path::RelativePathBuf; 8 | use walkdir::WalkDir; 9 | use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher as _Watcher}; 10 | 11 | use crate::{Roots, VfsRoot, VfsTask, roots::FileType, LineEndings, read_to_string, Watch}; 12 | 13 | pub(crate) enum Task { 14 | AddRoot { root: VfsRoot }, 15 | NotifyChanged { path: PathBuf }, 16 | } 17 | 18 | /// `TaskResult` transfers files read on the IO thread to the VFS on the main 19 | /// thread. 20 | #[derive(Debug)] 21 | pub(crate) enum TaskResult { 22 | /// Emitted when we've recursively scanned a source root during the initial 23 | /// load. 24 | BulkLoadRoot { root: VfsRoot, files: Vec<(RelativePathBuf, String, LineEndings)> }, 25 | /// Emitted when we've noticed that a single file has changed. 26 | /// 27 | /// Note that this by design does not distinguish between 28 | /// create/delete/write events, and instead specifies the *current* state of 29 | /// the file. The idea is to guarantee that in the quiescent state the sum 30 | /// of all results equals to the current state of the file system, while 31 | /// allowing to skip intermediate events in non-quiescent states. 32 | SingleFile { 33 | root: VfsRoot, 34 | path: RelativePathBuf, 35 | text: Option, 36 | line_endings: LineEndings, 37 | }, 38 | } 39 | 40 | /// The kind of raw notification we've received from the notify library. 41 | /// 42 | /// Note that these are not necessary 100% precise (for example we might receive 43 | /// `Create` instead of `Write`, see #734), but we try do distinguish `Create`s 44 | /// to implement recursive watching of directories. 45 | #[derive(Debug)] 46 | enum ChangeKind { 47 | Create, 48 | Write, 49 | Remove, 50 | } 51 | 52 | const WATCHER_DELAY: Duration = Duration::from_millis(250); 53 | 54 | pub(crate) struct Worker { 55 | // XXX: field order is significant here. 56 | // 57 | // In Rust, fields are dropped in the declaration order, and we rely on this 58 | // here. We must close sender first, so that the `thread` (who holds the 59 | // opposite side of the channel) noticed shutdown. Then, we must join the 60 | // thread, but we must keep receiver alive so that the thread does not 61 | // panic. 62 | sender: Sender, 63 | _thread: jod_thread::JoinHandle<()>, 64 | } 65 | 66 | impl Worker { 67 | pub(crate) fn send(&self, task: Task) { 68 | self.sender.send(task).unwrap() 69 | } 70 | } 71 | 72 | fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> jod_thread::JoinHandle<()> { 73 | jod_thread::Builder::new().name(name.to_string()).spawn(f).expect("failed to spawn a thread") 74 | } 75 | 76 | pub(crate) fn start( 77 | roots: Arc, 78 | mut output_sender: Box, 79 | watch: Watch, 80 | ) -> Worker { 81 | // This is a pretty elaborate setup of threads & channels! It is 82 | // explained by the following concerns: 83 | // * we need to burn a thread translating from notify's mpsc to 84 | // crossbeam_channel. 85 | // * we want to read all files from a single thread, to guarantee that 86 | // we always get fresher versions and never go back in time. 87 | // * we want to tear down everything neatly during shutdown. 88 | let _thread: jod_thread::JoinHandle<()>; 89 | // This are the channels we use to communicate with outside world. 90 | // If `input_receiver` is closed we need to tear ourselves down. 91 | // `output_sender` should not be closed unless the parent died. 92 | let (input_sender, input_receiver) = unbounded(); 93 | 94 | _thread = spawn("vfs", move || { 95 | // Make sure that the destruction order is 96 | // 97 | // * notify_sender 98 | // * _thread 99 | // * watcher_sender 100 | // 101 | // this is required to avoid deadlocks. 102 | 103 | // These are the corresponding crossbeam channels 104 | let (watcher_sender, watcher_receiver) = unbounded(); 105 | let _notify_thread; 106 | { 107 | // These are `std` channels notify will send events to 108 | let (notify_sender, notify_receiver) = mpsc::channel(); 109 | 110 | let mut watcher = if watch.0 { 111 | match notify::watcher(notify_sender, WATCHER_DELAY) { 112 | Ok(watcher) => { 113 | // Start a silly thread to transform between two channels 114 | _notify_thread = spawn("notify-convertor", move || { 115 | notify_receiver 116 | .into_iter() 117 | .for_each(|event| convert_notify_event(event, &watcher_sender)) 118 | }); 119 | Ok(watcher) 120 | } 121 | Err(e) => { 122 | log::error!("failed to spawn notify {}", e); 123 | Err(watcher_sender) 124 | } 125 | } 126 | } else { 127 | Err(watcher_sender) 128 | }; 129 | 130 | // Process requests from the called or notifications from 131 | // watcher until the caller says stop. 132 | loop { 133 | select! { 134 | // Received request from the caller. If this channel is 135 | // closed, we should shutdown everything. 136 | recv(input_receiver) -> t => match t { 137 | Err(RecvError) => { 138 | drop(input_receiver); 139 | break 140 | }, 141 | Ok(Task::AddRoot { root }) => { 142 | watch_root(watcher.as_mut().ok(), &mut output_sender, &*roots, root); 143 | } 144 | Ok(Task::NotifyChanged { path }) => { 145 | handle_notify_changed(&mut output_sender, &*roots, path); 146 | } 147 | }, 148 | // Watcher send us changes. If **this** channel is 149 | // closed, the watcher has died, which indicates a bug 150 | // -- escalate! 151 | recv(watcher_receiver) -> event => match event { 152 | Err(RecvError) => panic!("watcher is dead"), 153 | Ok((path, change)) => { 154 | handle_change(watcher.as_mut().ok(), &mut output_sender, &*roots, path, change); 155 | } 156 | }, 157 | } 158 | } 159 | } 160 | // Drain pending events: we are not interested in them anyways! 161 | watcher_receiver.into_iter().for_each(|_| ()); 162 | }); 163 | Worker { sender: input_sender, _thread } 164 | } 165 | 166 | fn watch_root( 167 | watcher: Option<&mut RecommendedWatcher>, 168 | sender: &mut dyn FnMut(VfsTask), 169 | roots: &Roots, 170 | root: VfsRoot, 171 | ) { 172 | let root_path = roots.path(root); 173 | log::debug!("loading {} ...", root_path.display()); 174 | let files = watch_recursive(watcher, root_path, roots, root) 175 | .into_iter() 176 | .filter_map(|path| { 177 | let abs_path = path.to_path(&root_path); 178 | let (text, line_endings) = read_to_string(&abs_path)?; 179 | Some((path, text, line_endings)) 180 | }) 181 | .collect(); 182 | let res = TaskResult::BulkLoadRoot { root, files }; 183 | sender(VfsTask(res)); 184 | log::debug!("... loaded {}", root_path.display()); 185 | } 186 | 187 | fn convert_notify_event(event: DebouncedEvent, sender: &Sender<(PathBuf, ChangeKind)>) { 188 | // forward relevant events only 189 | match event { 190 | DebouncedEvent::NoticeWrite(_) 191 | | DebouncedEvent::NoticeRemove(_) 192 | | DebouncedEvent::Chmod(_) => { 193 | // ignore 194 | } 195 | DebouncedEvent::Rescan => { 196 | // TODO: rescan all roots 197 | } 198 | DebouncedEvent::Create(path) => { 199 | sender.send((path, ChangeKind::Create)).unwrap(); 200 | } 201 | DebouncedEvent::Write(path) => { 202 | sender.send((path, ChangeKind::Write)).unwrap(); 203 | } 204 | DebouncedEvent::Remove(path) => { 205 | sender.send((path, ChangeKind::Remove)).unwrap(); 206 | } 207 | DebouncedEvent::Rename(src, dst) => { 208 | sender.send((src, ChangeKind::Remove)).unwrap(); 209 | sender.send((dst, ChangeKind::Create)).unwrap(); 210 | } 211 | DebouncedEvent::Error(err, path) => { 212 | // TODO: should we reload the file contents? 213 | log::warn!("watcher error \"{}\", {:?}", err, path); 214 | } 215 | } 216 | } 217 | 218 | fn handle_change( 219 | watcher: Option<&mut RecommendedWatcher>, 220 | sender: &mut dyn FnMut(VfsTask), 221 | roots: &Roots, 222 | path: PathBuf, 223 | kind: ChangeKind, 224 | ) { 225 | let ft = if path.is_file() { FileType::File } else { FileType::Dir }; 226 | let (root, rel_path) = match roots.find(&path, ft) { 227 | None => return, 228 | Some(it) => it, 229 | }; 230 | match kind { 231 | ChangeKind::Create => { 232 | let mut paths = Vec::new(); 233 | if ft.is_dir() { 234 | paths.extend(watch_recursive(watcher, &path, roots, root)); 235 | } else { 236 | paths.push(rel_path); 237 | } 238 | paths.into_iter().for_each(|rel_path| { 239 | let abs_path = rel_path.to_path(&roots.path(root)); 240 | let (text, line_endings) = match read_to_string(&abs_path) { 241 | Some((text, line_endings)) => (Some(text), line_endings), 242 | None => (None, LineEndings::default()), 243 | }; 244 | 245 | let res = TaskResult::SingleFile { root, path: rel_path, text, line_endings }; 246 | sender(VfsTask(res)) 247 | }) 248 | } 249 | ChangeKind::Write | ChangeKind::Remove => { 250 | let (text, line_endings) = match read_to_string(&path) { 251 | Some((text, line_endings)) => (Some(text), line_endings), 252 | None => (None, LineEndings::default()), 253 | }; 254 | let res = TaskResult::SingleFile { root, path: rel_path, text, line_endings }; 255 | sender(VfsTask(res)); 256 | } 257 | } 258 | } 259 | 260 | fn watch_recursive( 261 | mut watcher: Option<&mut RecommendedWatcher>, 262 | dir: &Path, 263 | roots: &Roots, 264 | root: VfsRoot, 265 | ) -> Vec { 266 | let mut files = Vec::new(); 267 | // FIXME: this is broken for symlinks at the moment 268 | for entry in WalkDir::new(dir) 269 | .into_iter() 270 | .filter_entry(|it| roots.contains(root, it.path(), it.file_type().into()).is_some()) 271 | .filter_map(|it| it.map_err(|e| log::warn!("watcher error: {}", e)).ok()) 272 | { 273 | if entry.file_type().is_dir() { 274 | if let Some(watcher) = &mut watcher { 275 | watch_one(watcher, entry.path()); 276 | } 277 | } else if let Some(path) = roots.contains(root, entry.path(), FileType::File) { 278 | files.push(path.to_owned()); 279 | } 280 | } 281 | files 282 | } 283 | 284 | fn watch_one(watcher: &mut RecommendedWatcher, dir: &Path) { 285 | match watcher.watch(dir, RecursiveMode::NonRecursive) { 286 | Ok(()) => log::debug!("watching \"{}\"", dir.display()), 287 | Err(e) => log::warn!("could not watch \"{}\": {}", dir.display(), e), 288 | } 289 | } 290 | 291 | fn handle_notify_changed(sender: &mut dyn FnMut(VfsTask), roots: &Roots, path: PathBuf) { 292 | if !path.is_file() { 293 | return; 294 | }; 295 | let (root, rel_path) = match roots.find(&path, FileType::File) { 296 | None => return, 297 | Some(it) => it, 298 | }; 299 | let (text, line_endings) = match read_to_string(&path) { 300 | Some((text, line_endings)) => (Some(text), line_endings), 301 | None => (None, LineEndings::default()), 302 | }; 303 | 304 | let res = TaskResult::SingleFile { root, path: rel_path, text, line_endings }; 305 | sender(VfsTask(res)) 306 | } 307 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! VFS stands for Virtual File System. 2 | //! 3 | //! When doing analysis, we don't want to do any IO, we want to keep all source 4 | //! code in memory. However, the actual source code is stored on disk, so you 5 | //! need to get it into the memory in the first place somehow. VFS is the 6 | //! component which does this. 7 | //! 8 | //! It is also responsible for watching the disk for changes, and for merging 9 | //! editor state (modified, unsaved files) with disk state. 10 | //! 11 | //! TODO: Some LSP clients support watching the disk, so this crate should to 12 | //! support custom watcher events (related to 13 | //! ) 14 | //! 15 | //! VFS is based on a concept of roots: a set of directories on the file system 16 | //! which are watched for changes. Typically, there will be a root for each 17 | //! Cargo package. 18 | mod roots; 19 | mod io; 20 | 21 | use std::{ 22 | fmt, fs, mem, 23 | path::{Path, PathBuf}, 24 | sync::Arc, 25 | }; 26 | 27 | use rustc_hash::{FxHashMap, FxHashSet}; 28 | 29 | use crate::{ 30 | io::{TaskResult, Worker}, 31 | roots::{Roots, FileType}, 32 | }; 33 | 34 | pub use relative_path::{RelativePath, RelativePathBuf}; 35 | pub use crate::roots::VfsRoot; 36 | 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 38 | pub enum LineEndings { 39 | Unix, 40 | Dos, 41 | } 42 | 43 | impl Default for LineEndings { 44 | fn default() -> Self { 45 | LineEndings::Unix 46 | } 47 | } 48 | 49 | /// a `Filter` is used to determine whether a file or a folder 50 | /// under the specific root is included. 51 | /// 52 | /// *NOTE*: If the parent folder of a file is not included, then 53 | /// `include_file` will not be called. 54 | /// 55 | /// # Example 56 | /// 57 | /// Implementing `Filter` for rust files: 58 | /// 59 | /// ``` 60 | /// use ra_vfs::{Filter, RelativePath}; 61 | /// 62 | /// struct IncludeRustFiles; 63 | /// 64 | /// impl Filter for IncludeRustFiles { 65 | /// fn include_dir(&self, dir_path: &RelativePath) -> bool { 66 | /// // These folders are ignored 67 | /// const IGNORED_FOLDERS: &[&str] = &["node_modules", "target", ".git"]; 68 | /// 69 | /// let is_ignored = dir_path.components().any(|c| IGNORED_FOLDERS.contains(&c.as_str())); 70 | /// 71 | /// !is_ignored 72 | /// } 73 | /// 74 | /// fn include_file(&self, file_path: &RelativePath) -> bool { 75 | /// // Only include rust files 76 | /// file_path.extension() == Some("rs") 77 | /// } 78 | /// } 79 | /// ``` 80 | pub trait Filter: Send + Sync { 81 | fn include_dir(&self, dir_path: &RelativePath) -> bool; 82 | fn include_file(&self, file_path: &RelativePath) -> bool; 83 | } 84 | 85 | /// RootEntry identifies a root folder with a given filter 86 | /// used to determine whether to include or exclude files and folders under it. 87 | pub struct RootEntry { 88 | path: PathBuf, 89 | filter: Box, 90 | } 91 | 92 | impl std::fmt::Debug for RootEntry { 93 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 94 | write!(f, "RootEntry({})", self.path.display()) 95 | } 96 | } 97 | 98 | impl Eq for RootEntry {} 99 | impl PartialEq for RootEntry { 100 | fn eq(&self, other: &Self) -> bool { 101 | // Entries are equal based on their paths 102 | self.path == other.path 103 | } 104 | } 105 | 106 | impl RootEntry { 107 | /// Create a new `RootEntry` with the given `filter` applied to 108 | /// files and folder under it. 109 | pub fn new(path: PathBuf, filter: Box) -> Self { 110 | RootEntry { path, filter } 111 | } 112 | } 113 | /// Opaque wrapper around file-system event. 114 | /// 115 | /// Calling code is expected to just pass `VfsTask` to `handle_task` method. It 116 | /// is exposed as a public API so that the caller can plug vfs events into the 117 | /// main event loop and be notified when changes happen. 118 | pub struct VfsTask(TaskResult); 119 | 120 | impl fmt::Debug for VfsTask { 121 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 122 | f.write_str("VfsTask { ... }") 123 | } 124 | } 125 | 126 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 127 | pub struct VfsFile(pub u32); 128 | 129 | struct VfsFileData { 130 | root: VfsRoot, 131 | path: RelativePathBuf, 132 | is_overlayed: bool, 133 | text: Arc, 134 | line_endings: LineEndings, 135 | } 136 | 137 | pub struct Vfs { 138 | roots: Arc, 139 | files: Vec, 140 | root2files: FxHashMap>, 141 | pending_changes: Vec, 142 | #[allow(unused)] 143 | worker: Worker, 144 | } 145 | 146 | impl fmt::Debug for Vfs { 147 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 148 | f.debug_struct("Vfs") 149 | .field("n_roots", &self.roots.len()) 150 | .field("n_files", &self.files.len()) 151 | .field("n_pending_changes", &self.pending_changes.len()) 152 | .finish() 153 | } 154 | } 155 | 156 | #[derive(Debug, Clone)] 157 | pub enum VfsChange { 158 | AddRoot { root: VfsRoot, files: Vec<(VfsFile, RelativePathBuf, Arc)> }, 159 | AddFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf, text: Arc }, 160 | RemoveFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf }, 161 | ChangeFile { file: VfsFile, text: Arc }, 162 | } 163 | 164 | #[derive(Clone, Copy)] 165 | pub struct Watch(pub bool); 166 | 167 | impl Vfs { 168 | pub fn new( 169 | roots: Vec, 170 | on_task: Box, 171 | watch: Watch, 172 | ) -> (Vfs, Vec) { 173 | let roots = Arc::new(Roots::new(roots)); 174 | let worker = io::start(Arc::clone(&roots), on_task, watch); 175 | let mut root2files = FxHashMap::default(); 176 | 177 | for root in roots.iter() { 178 | root2files.insert(root, Default::default()); 179 | worker.send(io::Task::AddRoot { root }); 180 | } 181 | let res = Vfs { roots, files: Vec::new(), root2files, worker, pending_changes: Vec::new() }; 182 | let vfs_roots = res.roots.iter().collect(); 183 | (res, vfs_roots) 184 | } 185 | 186 | pub fn root2path(&self, root: VfsRoot) -> PathBuf { 187 | self.roots.path(root).to_path_buf() 188 | } 189 | 190 | pub fn path2root(&self, path: &Path) -> Option { 191 | let (root, _path) = self.roots.find(path, FileType::Dir)?; 192 | Some(root) 193 | } 194 | 195 | pub fn path2file(&self, path: &Path) -> Option { 196 | if let Some((_root, _path, Some(file))) = self.find_root(path) { 197 | return Some(file); 198 | } 199 | None 200 | } 201 | 202 | pub fn file2path(&self, file: VfsFile) -> PathBuf { 203 | let rel_path = &self.file(file).path; 204 | let root_path = &self.roots.path(self.file(file).root); 205 | rel_path.to_path(root_path) 206 | } 207 | 208 | pub fn file_line_endings(&self, file: VfsFile) -> LineEndings { 209 | self.file(file).line_endings 210 | } 211 | 212 | pub fn n_roots(&self) -> usize { 213 | self.roots.len() 214 | } 215 | 216 | pub fn load(&mut self, path: &Path) -> Option { 217 | if let Some((root, rel_path, file)) = self.find_root(path) { 218 | return if let Some(file) = file { 219 | Some(file) 220 | } else { 221 | let (text, line_endings) = read_to_string(path).unwrap_or_default(); 222 | let text = Arc::new(text); 223 | let file = self.raw_add_file( 224 | root, 225 | rel_path.clone(), 226 | Arc::clone(&text), 227 | line_endings, 228 | false, 229 | ); 230 | let change = VfsChange::AddFile { file, text, root, path: rel_path }; 231 | self.pending_changes.push(change); 232 | Some(file) 233 | }; 234 | } 235 | None 236 | } 237 | 238 | pub fn notify_changed(&mut self, path: PathBuf) { 239 | self.worker.send(io::Task::NotifyChanged { path }) 240 | } 241 | 242 | pub fn add_file_overlay(&mut self, path: &Path, mut text: String) -> Option { 243 | let line_endings = normalize_newlines(&mut text); 244 | let (root, rel_path, file) = self.find_root(path)?; 245 | if let Some(file) = file { 246 | self.change_file_event(file, text, true); 247 | Some(file) 248 | } else { 249 | self.add_file_event(root, rel_path, text, line_endings, true) 250 | } 251 | } 252 | 253 | pub fn change_file_overlay(&mut self, path: &Path, change: F) { 254 | if let Some((_root, _path, file)) = self.find_root(path) { 255 | let file = file.expect("can't change a file which wasn't added"); 256 | let mut text = self.file(file).text.as_ref().clone(); 257 | change(&mut text); 258 | let _line_endings = normalize_newlines(&mut text); 259 | 260 | self.change_file_event(file, text, true); 261 | } 262 | } 263 | 264 | pub fn remove_file_overlay(&mut self, path: &Path) -> Option { 265 | let (root, rel_path, file) = self.find_root(path)?; 266 | let file = file.expect("can't remove a file which wasn't added"); 267 | let full_path = rel_path.to_path(&self.roots.path(root)); 268 | match fs::read_to_string(&full_path) { 269 | Ok(mut text) => { 270 | let _line_endings = normalize_newlines(&mut text); 271 | self.change_file_event(file, text, false); 272 | } 273 | Err(_) => self.remove_file_event(root, rel_path, file), 274 | } 275 | Some(file) 276 | } 277 | 278 | pub fn commit_changes(&mut self) -> Vec { 279 | // FIXME: ideally we should compact changes here, such that we send at 280 | // most one event per VfsFile. 281 | mem::replace(&mut self.pending_changes, Vec::new()) 282 | } 283 | 284 | pub fn handle_task(&mut self, task: VfsTask) { 285 | match task.0 { 286 | TaskResult::BulkLoadRoot { root, files } => { 287 | let mut cur_files = Vec::new(); 288 | // While we were scanning the root in the background, a file might have 289 | // been open in the editor, so we need to account for that. 290 | let existing = self.root2files[&root] 291 | .iter() 292 | .map(|&file| (self.file(file).path.clone(), file)) 293 | .collect::>(); 294 | for (path, text, line_endings) in files { 295 | if let Some(&file) = existing.get(&path) { 296 | let text = Arc::clone(&self.file(file).text); 297 | cur_files.push((file, path, text)); 298 | continue; 299 | } 300 | let text = Arc::new(text); 301 | let file = self.raw_add_file( 302 | root, 303 | path.clone(), 304 | Arc::clone(&text), 305 | line_endings, 306 | false, 307 | ); 308 | cur_files.push((file, path, text)); 309 | } 310 | 311 | let change = VfsChange::AddRoot { root, files: cur_files }; 312 | self.pending_changes.push(change); 313 | } 314 | TaskResult::SingleFile { root, path, text, line_endings } => { 315 | let existing_file = self.find_file(root, &path); 316 | if existing_file.map(|file| self.file(file).is_overlayed) == Some(true) { 317 | return; 318 | } 319 | match (existing_file, text) { 320 | (Some(file), None) => { 321 | self.remove_file_event(root, path, file); 322 | } 323 | (None, Some(text)) => { 324 | self.add_file_event(root, path, text, line_endings, false); 325 | } 326 | (Some(file), Some(text)) => { 327 | if *self.file(file).text != text { 328 | self.change_file_event(file, text, false); 329 | } 330 | } 331 | (None, None) => (), 332 | } 333 | } 334 | } 335 | } 336 | 337 | // *_event calls change the state of VFS and push a change onto pending 338 | // changes array. 339 | 340 | fn add_file_event( 341 | &mut self, 342 | root: VfsRoot, 343 | path: RelativePathBuf, 344 | text: String, 345 | line_endings: LineEndings, 346 | is_overlay: bool, 347 | ) -> Option { 348 | let text = Arc::new(text); 349 | let file = 350 | self.raw_add_file(root, path.clone(), Arc::clone(&text), line_endings, is_overlay); 351 | self.pending_changes.push(VfsChange::AddFile { file, root, path, text }); 352 | Some(file) 353 | } 354 | 355 | fn change_file_event(&mut self, file: VfsFile, text: String, is_overlay: bool) { 356 | let text = Arc::new(text); 357 | self.raw_change_file(file, text.clone(), is_overlay); 358 | self.pending_changes.push(VfsChange::ChangeFile { file, text }); 359 | } 360 | 361 | fn remove_file_event(&mut self, root: VfsRoot, path: RelativePathBuf, file: VfsFile) { 362 | self.raw_remove_file(file); 363 | self.pending_changes.push(VfsChange::RemoveFile { root, path, file }); 364 | } 365 | 366 | // raw_* calls change the state of VFS, but **do not** emit events. 367 | 368 | fn raw_add_file( 369 | &mut self, 370 | root: VfsRoot, 371 | path: RelativePathBuf, 372 | text: Arc, 373 | line_endings: LineEndings, 374 | is_overlayed: bool, 375 | ) -> VfsFile { 376 | let data = VfsFileData { root, path, text, line_endings, is_overlayed }; 377 | let file = VfsFile(self.files.len() as u32); 378 | self.files.push(data); 379 | self.root2files.get_mut(&root).unwrap().insert(file); 380 | file 381 | } 382 | 383 | fn raw_change_file(&mut self, file: VfsFile, new_text: Arc, is_overlayed: bool) { 384 | let mut file_data = &mut self.file_mut(file); 385 | file_data.text = new_text; 386 | file_data.is_overlayed = is_overlayed; 387 | } 388 | 389 | fn raw_remove_file(&mut self, file: VfsFile) { 390 | // FIXME: use arena with removal 391 | self.file_mut(file).text = Default::default(); 392 | self.file_mut(file).path = Default::default(); 393 | let root = self.file(file).root; 394 | let removed = self.root2files.get_mut(&root).unwrap().remove(&file); 395 | assert!(removed); 396 | } 397 | 398 | fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option)> { 399 | let (root, path) = self.roots.find(&path, FileType::File)?; 400 | let file = self.find_file(root, &path); 401 | Some((root, path, file)) 402 | } 403 | 404 | fn find_file(&self, root: VfsRoot, path: &RelativePath) -> Option { 405 | self.root2files[&root].iter().map(|&it| it).find(|&file| self.file(file).path == path) 406 | } 407 | 408 | fn file(&self, file: VfsFile) -> &VfsFileData { 409 | &self.files[file.0 as usize] 410 | } 411 | 412 | fn file_mut(&mut self, file: VfsFile) -> &mut VfsFileData { 413 | &mut self.files[file.0 as usize] 414 | } 415 | } 416 | 417 | fn read_to_string(path: &Path) -> Option<(String, LineEndings)> { 418 | let mut text = 419 | fs::read_to_string(&path).map_err(|e| log::warn!("failed to read file {}", e)).ok()?; 420 | let line_endings = normalize_newlines(&mut text); 421 | Some((text, line_endings)) 422 | } 423 | 424 | /// Replaces `\r\n` with `\n` in-place in `src`. 425 | pub fn normalize_newlines(src: &mut String) -> LineEndings { 426 | if !src.as_bytes().contains(&b'\r') { 427 | return LineEndings::Unix; 428 | } 429 | 430 | // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. 431 | // While we *can* call `as_mut_vec` and do surgery on the live string 432 | // directly, let's rather steal the contents of `src`. This makes the code 433 | // safe even if a panic occurs. 434 | 435 | let mut buf = std::mem::replace(src, String::new()).into_bytes(); 436 | let mut gap_len = 0; 437 | let mut tail = buf.as_mut_slice(); 438 | loop { 439 | let idx = match find_crlf(&tail[gap_len..]) { 440 | None => tail.len(), 441 | Some(idx) => idx + gap_len, 442 | }; 443 | tail.copy_within(gap_len..idx, 0); 444 | tail = &mut tail[idx - gap_len..]; 445 | if tail.len() == gap_len { 446 | break; 447 | } 448 | gap_len += 1; 449 | } 450 | 451 | // Account for removed `\r`. 452 | // After `set_len`, `buf` is guaranteed to contain utf-8 again. 453 | let new_len = buf.len() - gap_len; 454 | unsafe { 455 | buf.set_len(new_len); 456 | *src = String::from_utf8_unchecked(buf); 457 | } 458 | return LineEndings::Dos; 459 | 460 | fn find_crlf(src: &[u8]) -> Option { 461 | let mut search_idx = 0; 462 | while let Some(idx) = find_cr(&src[search_idx..]) { 463 | if src[search_idx..].get(idx + 1) != Some(&b'\n') { 464 | search_idx += idx + 1; 465 | continue; 466 | } 467 | return Some(search_idx + idx); 468 | } 469 | None 470 | } 471 | 472 | fn find_cr(src: &[u8]) -> Option { 473 | src.iter().enumerate().find_map(|(idx, &b)| if b == b'\r' { Some(idx) } else { None }) 474 | } 475 | } 476 | 477 | #[cfg(test)] 478 | mod tests { 479 | use super::*; 480 | struct NoopFilter; 481 | 482 | impl Filter for NoopFilter { 483 | fn include_dir(&self, _: &RelativePath) -> bool { 484 | true 485 | } 486 | fn include_file(&self, _: &RelativePath) -> bool { 487 | true 488 | } 489 | } 490 | 491 | fn entry(s: &str) -> RootEntry { 492 | RootEntry::new(s.into(), Box::new(NoopFilter)) 493 | } 494 | 495 | #[test] 496 | fn vfs_deduplicates() { 497 | let entries = vec!["/foo", "/bar", "/foo"].into_iter().map(entry).collect(); 498 | let (_, roots) = Vfs::new(entries, Box::new(|_task| ()), Watch(true)); 499 | assert_eq!(roots.len(), 2); 500 | } 501 | } 502 | -------------------------------------------------------------------------------- /src/roots.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | iter, 3 | path::{Path, PathBuf}, 4 | }; 5 | 6 | use relative_path::RelativePathBuf; 7 | 8 | use super::{RootEntry, Filter}; 9 | 10 | /// VfsRoot identifies a watched directory on the file system. 11 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 12 | pub struct VfsRoot(pub u32); 13 | 14 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 15 | pub(crate) enum FileType { 16 | File, 17 | Dir, 18 | } 19 | 20 | impl FileType { 21 | pub(crate) fn is_dir(&self) -> bool { 22 | *self == FileType::Dir 23 | } 24 | } 25 | 26 | impl std::convert::From for FileType { 27 | fn from(v: std::fs::FileType) -> Self { 28 | if v.is_file() { 29 | FileType::File 30 | } else { 31 | FileType::Dir 32 | } 33 | } 34 | } 35 | 36 | /// Describes the contents of a single source root. 37 | /// 38 | /// `RootData` can be thought of as a glob pattern like `src/**.rs` which 39 | /// specifies the source root or as a function which takes a `PathBuf` and 40 | /// returns `true` if path belongs to the source root 41 | struct RootData { 42 | root: PathBuf, 43 | filter: Box, 44 | // result of `root.canonicalize()` if that differs from `root`; `None` otherwise. 45 | canonical_path: Option, 46 | excluded_dirs: Vec, 47 | } 48 | 49 | pub(crate) struct Roots { 50 | roots: Vec, 51 | } 52 | 53 | impl Roots { 54 | pub(crate) fn new(mut paths: Vec) -> Roots { 55 | paths.sort_by(|a, b| a.path.cmp(&b.path)); 56 | paths.dedup(); 57 | 58 | // A hack to make nesting work. 59 | paths.sort_by_key(|it| std::cmp::Reverse(it.path.as_os_str().len())); 60 | 61 | // First gather all the nested roots for each path 62 | let nested_roots = paths 63 | .iter() 64 | .enumerate() 65 | .map(|(i, entry)| { 66 | paths[..i] 67 | .iter() 68 | .filter_map(|it| rel_path(&entry.path, &it.path)) 69 | .collect::>() 70 | }) 71 | .collect::>(); 72 | 73 | // Then combine the entry with the matching nested_roots 74 | let roots = paths 75 | .into_iter() 76 | .zip(nested_roots.into_iter()) 77 | .map(|(entry, nested_roots)| RootData::new(entry, nested_roots)) 78 | .collect::>(); 79 | 80 | Roots { roots } 81 | } 82 | pub(crate) fn find( 83 | &self, 84 | path: &Path, 85 | expected: FileType, 86 | ) -> Option<(VfsRoot, RelativePathBuf)> { 87 | self.iter().find_map(|root| { 88 | let rel_path = self.contains(root, path, expected)?; 89 | Some((root, rel_path)) 90 | }) 91 | } 92 | pub(crate) fn len(&self) -> usize { 93 | self.roots.len() 94 | } 95 | pub(crate) fn iter<'a>(&'a self) -> impl Iterator + 'a { 96 | (0..self.roots.len()).into_iter().map(|idx| VfsRoot(idx as u32)) 97 | } 98 | pub(crate) fn path(&self, root: VfsRoot) -> &Path { 99 | self.root(root).path() 100 | } 101 | 102 | /// Checks if root contains a path with the given `FileType` 103 | /// and returns a root-relative path. 104 | pub(crate) fn contains( 105 | &self, 106 | root: VfsRoot, 107 | path: &Path, 108 | expected: FileType, 109 | ) -> Option { 110 | let data = self.root(root); 111 | iter::once(data.path()) 112 | .chain(data.canonical_path.iter().map(PathBuf::as_path)) 113 | .find_map(|base| to_relative_path(base, path, &data, expected)) 114 | } 115 | 116 | fn root(&self, root: VfsRoot) -> &RootData { 117 | &self.roots[root.0 as usize] 118 | } 119 | } 120 | 121 | impl RootData { 122 | fn new(entry: RootEntry, excluded_dirs: Vec) -> RootData { 123 | let mut canonical_path = entry.path.canonicalize().ok(); 124 | if Some(&entry.path) == canonical_path.as_ref() { 125 | canonical_path = None; 126 | } 127 | RootData { root: entry.path, filter: entry.filter, canonical_path, excluded_dirs } 128 | } 129 | 130 | fn path(&self) -> &Path { 131 | &self.root 132 | } 133 | 134 | /// Returns true if the given `RelativePath` is included inside this `RootData` 135 | fn is_included(&self, rel_path: &RelativePathBuf, expected: FileType) -> bool { 136 | if self.excluded_dirs.iter().any(|d| rel_path.starts_with(d)) { 137 | return false; 138 | } 139 | 140 | let parent_included = 141 | rel_path.parent().map(|d| self.filter.include_dir(&d)).unwrap_or(true); 142 | 143 | if !parent_included { 144 | return false; 145 | } 146 | 147 | match expected { 148 | FileType::File => self.filter.include_file(&rel_path), 149 | FileType::Dir => self.filter.include_dir(&rel_path), 150 | } 151 | } 152 | } 153 | 154 | /// Returns the path relative to `base` 155 | fn rel_path(base: &Path, path: &Path) -> Option { 156 | let path = path.strip_prefix(base).ok()?; 157 | RelativePathBuf::from_path(path).ok() 158 | } 159 | 160 | /// Returns the path relative to `base` with filtering applied based on `data` 161 | fn to_relative_path( 162 | base: &Path, 163 | path: &Path, 164 | data: &RootData, 165 | expected: FileType, 166 | ) -> Option { 167 | let rel_path = rel_path(base, path)?; 168 | 169 | // Apply filtering _only_ if the relative path is non-empty 170 | // if it's empty, it means we are currently processing the root 171 | if rel_path.as_str().is_empty() { 172 | return Some(rel_path); 173 | } 174 | 175 | if data.is_included(&rel_path, expected) { 176 | Some(rel_path) 177 | } else { 178 | None 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /tests/vfs.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashSet, fs, time::Duration}; 2 | 3 | // use flexi_logger::Logger; 4 | use crossbeam_channel::{RecvTimeoutError, Receiver, unbounded}; 5 | use ra_vfs::{Vfs, VfsChange, RootEntry, Filter, RelativePath, VfsTask, Watch}; 6 | use tempfile::tempdir; 7 | 8 | /// Processes exactly `num_tasks` events waiting in the `vfs` message queue. 9 | /// 10 | /// Panics if there are not exactly that many tasks enqueued for processing. 11 | fn process_tasks(vfs: &mut Vfs, task_receiver: &mut Receiver, num_tasks: u32) { 12 | process_tasks_in_range(vfs, task_receiver, num_tasks, num_tasks); 13 | } 14 | 15 | /// Processes up to `max_count` events waiting in the `vfs` message queue. 16 | /// 17 | /// Panics if it cannot process at least `min_count` events. 18 | /// Panics if more than `max_count` events are enqueued for processing. 19 | fn process_tasks_in_range( 20 | vfs: &mut Vfs, 21 | task_receiver: &mut Receiver, 22 | min_count: u32, 23 | max_count: u32, 24 | ) { 25 | for i in 0..max_count { 26 | let task = match task_receiver.recv_timeout(Duration::from_secs(3)) { 27 | Err(RecvTimeoutError::Timeout) if i >= min_count => return, 28 | otherwise => otherwise.unwrap(), 29 | }; 30 | log::debug!("{:?}", task); 31 | vfs.handle_task(task); 32 | } 33 | assert!(task_receiver.is_empty()); 34 | } 35 | 36 | macro_rules! assert_match { 37 | ($x:expr, $pat:pat) => { 38 | assert_match!($x, $pat, ()) 39 | }; 40 | ($x:expr, $pat:pat, $assert:expr) => { 41 | match $x { 42 | $pat => $assert, 43 | x => assert!(false, "Expected {}, got {:?}", stringify!($pat), x), 44 | }; 45 | }; 46 | } 47 | 48 | struct IncludeRustFiles; 49 | 50 | impl IncludeRustFiles { 51 | fn boxed() -> Box { 52 | Box::new(Self {}) 53 | } 54 | } 55 | 56 | impl Filter for IncludeRustFiles { 57 | fn include_dir(&self, dir_path: &RelativePath) -> bool { 58 | const IGNORED_FOLDERS: &[&str] = &["node_modules", "target", ".git"]; 59 | 60 | let is_ignored = dir_path.components().any(|c| IGNORED_FOLDERS.contains(&c.as_str())); 61 | 62 | let hidden = dir_path.file_stem().map(|s| s.starts_with(".")).unwrap_or(false); 63 | 64 | !is_ignored && !hidden 65 | } 66 | 67 | fn include_file(&self, file_path: &RelativePath) -> bool { 68 | file_path.extension() == Some("rs") 69 | } 70 | } 71 | 72 | fn task_chan() -> (Receiver, Box) { 73 | let (sender, receiver) = unbounded(); 74 | (receiver, Box::new(move |task| sender.send(task).unwrap())) 75 | } 76 | 77 | #[test] 78 | fn test_vfs_ignore() -> std::io::Result<()> { 79 | // flexi_logger::Logger::with_str("vfs=debug,ra_vfs=debug").start().unwrap(); 80 | 81 | let files = [ 82 | ("ignore_a/foo.rs", "hello"), 83 | ("ignore_a/bar.rs", "world"), 84 | ("ignore_a/b/baz.rs", "nested hello"), 85 | ("ignore_a/LICENSE", "extensionless file"), 86 | ("ignore_a/b/AUTHOR", "extensionless file"), 87 | ("ignore_a/.hidden.txt", "hidden file"), 88 | ("ignore_a/.hidden_folder/file.rs", "hidden folder containing rust file"), 89 | ( 90 | "ignore_a/.hidden_folder/nested/foo.rs", 91 | "file inside nested folder inside a hidden folder", 92 | ), 93 | ("ignore_a/node_modules/module.js", "hidden file js"), 94 | ("ignore_a/node_modules/module2.rs", "node rust"), 95 | ("ignore_a/node_modules/nested/foo.bar", "hidden file bar"), 96 | ]; 97 | 98 | let dir = tempdir().unwrap(); 99 | for (path, text) in files.iter() { 100 | let file_path = dir.path().join(path); 101 | fs::create_dir_all(file_path.parent().unwrap()).unwrap(); 102 | fs::write(file_path, text)? 103 | } 104 | 105 | let a_root = dir.path().join("ignore_a"); 106 | let b_root = dir.path().join("ignore_a/b"); 107 | 108 | let (mut task_receiver, cb) = task_chan(); 109 | let (mut vfs, _) = Vfs::new( 110 | vec![ 111 | RootEntry::new(a_root, IncludeRustFiles::boxed()), 112 | RootEntry::new(b_root, IncludeRustFiles::boxed()), 113 | ], 114 | cb, 115 | Watch(true), 116 | ); 117 | process_tasks(&mut vfs, &mut task_receiver, 2); 118 | { 119 | let files = vfs 120 | .commit_changes() 121 | .into_iter() 122 | .flat_map(|change| { 123 | let files = match change { 124 | VfsChange::AddRoot { files, .. } => files, 125 | _ => panic!("unexpected change"), 126 | }; 127 | files.into_iter().map(|(_id, path, text)| { 128 | let text: String = (&*text).clone(); 129 | (format!("{}", path), text) 130 | }) 131 | }) 132 | .collect::>(); 133 | 134 | let expected_files = [("foo.rs", "hello"), ("bar.rs", "world"), ("baz.rs", "nested hello")] 135 | .iter() 136 | .map(|(path, text)| (path.to_string(), text.to_string())) 137 | .collect::>(); 138 | 139 | assert_eq!(files, expected_files); 140 | } 141 | 142 | // rust-analyzer#734: fsevents has a bunch of events still sitting around. 143 | process_tasks_in_range( 144 | &mut vfs, 145 | &mut task_receiver, 146 | 0, 147 | if cfg!(target_os = "macos") { 7 } else { 0 }, 148 | ); 149 | assert!(vfs.commit_changes().is_empty()); 150 | 151 | // These will get filtered out 152 | vfs.add_file_overlay(&dir.path().join("ignore_a/node_modules/spam.rs"), "spam".to_string()); 153 | vfs.add_file_overlay(&dir.path().join("ignore_a/node_modules/spam2.rs"), "spam".to_string()); 154 | vfs.add_file_overlay(&dir.path().join("ignore_a/node_modules/spam3.rs"), "spam".to_string()); 155 | vfs.add_file_overlay(&dir.path().join("ignore_a/LICENSE2"), "text".to_string()); 156 | assert_match!(vfs.commit_changes().as_slice(), []); 157 | 158 | fs::create_dir_all(dir.path().join("ignore_a/node_modules/sub1")).unwrap(); 159 | fs::write(dir.path().join("ignore_a/node_modules/sub1/new.rs"), "new hello").unwrap(); 160 | 161 | assert_match!( 162 | task_receiver.recv_timeout(Duration::from_millis(300)), // slightly more than watcher debounce delay 163 | Err(RecvTimeoutError::Timeout) 164 | ); 165 | 166 | Ok(()) 167 | } 168 | 169 | #[test] 170 | fn test_vfs_works() -> std::io::Result<()> { 171 | // Logger::with_str("vfs=debug,ra_vfs=debug").start().unwrap(); 172 | 173 | let files = [ 174 | ("a/foo.rs", "hello"), 175 | ("a/bar.rs", "world"), 176 | ("a/b/baz.rs", "nested hello"), 177 | ("a/LICENSE", "extensionless file"), 178 | ("a/b/AUTHOR", "extensionless file"), 179 | ("a/.hidden.txt", "hidden file"), 180 | ]; 181 | 182 | let dir = tempdir().unwrap(); 183 | for (path, text) in files.iter() { 184 | let file_path = dir.path().join(path); 185 | fs::create_dir_all(file_path.parent().unwrap()).unwrap(); 186 | fs::write(file_path, text)? 187 | } 188 | 189 | let a_root = dir.path().join("a"); 190 | let b_root = dir.path().join("a/b"); 191 | 192 | let (mut task_receiver, cb) = task_chan(); 193 | let (mut vfs, _) = Vfs::new( 194 | vec![ 195 | RootEntry::new(a_root, IncludeRustFiles::boxed()), 196 | RootEntry::new(b_root, IncludeRustFiles::boxed()), 197 | ], 198 | cb, 199 | Watch(true), 200 | ); 201 | process_tasks(&mut vfs, &mut task_receiver, 2); 202 | { 203 | let files = vfs 204 | .commit_changes() 205 | .into_iter() 206 | .flat_map(|change| { 207 | let files = match change { 208 | VfsChange::AddRoot { files, .. } => files, 209 | _ => panic!("unexpected change"), 210 | }; 211 | files.into_iter().map(|(_id, path, text)| { 212 | let text: String = (&*text).clone(); 213 | (format!("{}", path), text) 214 | }) 215 | }) 216 | .collect::>(); 217 | 218 | let expected_files = [("foo.rs", "hello"), ("bar.rs", "world"), ("baz.rs", "nested hello")] 219 | .iter() 220 | .map(|(path, text)| (path.to_string(), text.to_string())) 221 | .collect::>(); 222 | 223 | assert_eq!(files, expected_files); 224 | } 225 | 226 | // rust-analyzer#734: fsevents has a bunch of events still sitting around. 227 | process_tasks_in_range( 228 | &mut vfs, 229 | &mut task_receiver, 230 | 0, 231 | if cfg!(target_os = "macos") { 7 } else { 0 }, 232 | ); 233 | assert!(vfs.commit_changes().is_empty()); 234 | 235 | fs::write(&dir.path().join("a/b/baz.rs"), "quux").unwrap(); 236 | process_tasks(&mut vfs, &mut task_receiver, 1); 237 | assert_match!( 238 | vfs.commit_changes().as_slice(), 239 | [VfsChange::ChangeFile { text, .. }], 240 | assert_eq!(text.as_str(), "quux") 241 | ); 242 | 243 | vfs.add_file_overlay(&dir.path().join("a/b/baz.rs"), "m".to_string()); 244 | assert_match!( 245 | vfs.commit_changes().as_slice(), 246 | [VfsChange::ChangeFile { text, .. }], 247 | assert_eq!(text.as_str(), "m") 248 | ); 249 | 250 | // changing file on disk while overlayed doesn't generate a VfsChange 251 | fs::write(&dir.path().join("a/b/baz.rs"), "corge").unwrap(); 252 | process_tasks(&mut vfs, &mut task_receiver, 1); 253 | assert_match!(vfs.commit_changes().as_slice(), []); 254 | 255 | // removing overlay restores data on disk 256 | vfs.remove_file_overlay(&dir.path().join("a/b/baz.rs")); 257 | assert_match!( 258 | vfs.commit_changes().as_slice(), 259 | [VfsChange::ChangeFile { text, .. }], 260 | assert_eq!(text.as_str(), "corge") 261 | ); 262 | 263 | vfs.add_file_overlay(&dir.path().join("a/b/spam.rs"), "spam".to_string()); 264 | assert_match!(vfs.commit_changes().as_slice(), [VfsChange::AddFile { text, path, .. }], { 265 | assert_eq!(text.as_str(), "spam"); 266 | assert_eq!(path, "spam.rs"); 267 | }); 268 | 269 | vfs.remove_file_overlay(&dir.path().join("a/b/spam.rs")); 270 | assert_match!( 271 | vfs.commit_changes().as_slice(), 272 | [VfsChange::RemoveFile { path, .. }], 273 | assert_eq!(path, "spam.rs") 274 | ); 275 | 276 | fs::create_dir_all(dir.path().join("a/sub1/sub2")).unwrap(); 277 | fs::write(dir.path().join("a/sub1/sub2/new.rs"), "new hello").unwrap(); 278 | process_tasks(&mut vfs, &mut task_receiver, 1); 279 | assert_match!(vfs.commit_changes().as_slice(), [VfsChange::AddFile { text, path, .. }], { 280 | assert_eq!(text.as_str(), "new hello"); 281 | assert_eq!(path, "sub1/sub2/new.rs"); 282 | }); 283 | 284 | fs::rename(&dir.path().join("a/sub1/sub2/new.rs"), &dir.path().join("a/sub1/sub2/new1.rs")) 285 | .unwrap(); 286 | 287 | // rust-analyzer#734: For testing purposes, work-around 288 | // passcod/notify#181 by processing either 1 or 2 events. (In 289 | // particular, Mac can hand back either 1 or 2 events in a 290 | // timing-dependent fashion.) 291 | // 292 | // rust-analyzer#827: Windows generates extra `Write` events when 293 | // renaming? meaning we have extra tasks to process. 294 | process_tasks_in_range(&mut vfs, &mut task_receiver, 1, if cfg!(windows) { 4 } else { 2 }); 295 | match vfs.commit_changes().as_slice() { 296 | [VfsChange::RemoveFile { path: removed_path, .. }, VfsChange::AddFile { text, path: added_path, .. }] => 297 | { 298 | assert_eq!(removed_path, "sub1/sub2/new.rs"); 299 | assert_eq!(added_path, "sub1/sub2/new1.rs"); 300 | assert_eq!(text.as_str(), "new hello"); 301 | } 302 | 303 | // Hopefully passcod/notify#181 will be addressed in some 304 | // manner that will reliably emit an event mentioning 305 | // `sub1/sub2/new.rs`. But until then, must accept that 306 | // debouncing loses information unrecoverably. 307 | [VfsChange::AddFile { text, path: added_path, .. }] => { 308 | assert_eq!(added_path, "sub1/sub2/new1.rs"); 309 | assert_eq!(text.as_str(), "new hello"); 310 | } 311 | 312 | changes => panic!( 313 | "Expected events for rename of {OLD} to {NEW}, got: {GOT:?}", 314 | OLD = "sub1/sub2/new.rs", 315 | NEW = "sub1/sub2/new1.rs", 316 | GOT = changes 317 | ), 318 | } 319 | 320 | fs::remove_file(&dir.path().join("a/sub1/sub2/new1.rs")).unwrap(); 321 | process_tasks(&mut vfs, &mut task_receiver, 1); 322 | assert_match!( 323 | vfs.commit_changes().as_slice(), 324 | [VfsChange::RemoveFile { path, .. }], 325 | assert_eq!(path, "sub1/sub2/new1.rs") 326 | ); 327 | 328 | { 329 | vfs.add_file_overlay(&dir.path().join("a/memfile.rs"), "memfile".to_string()); 330 | assert_match!( 331 | vfs.commit_changes().as_slice(), 332 | [VfsChange::AddFile { text, .. }], 333 | assert_eq!(text.as_str(), "memfile") 334 | ); 335 | fs::write(&dir.path().join("a/memfile.rs"), "ignore me").unwrap(); 336 | process_tasks(&mut vfs, &mut task_receiver, 1); 337 | assert_match!(vfs.commit_changes().as_slice(), []); 338 | } 339 | 340 | // should be ignored 341 | fs::create_dir_all(dir.path().join("a/target")).unwrap(); 342 | fs::write(&dir.path().join("a/target/new.rs"), "ignore me").unwrap(); 343 | 344 | assert_match!( 345 | task_receiver.recv_timeout(Duration::from_millis(300)), // slightly more than watcher debounce delay 346 | Err(RecvTimeoutError::Timeout) 347 | ); 348 | 349 | Ok(()) 350 | } 351 | 352 | #[test] 353 | fn test_disabled_watch() { 354 | let files = [("a/foo.rs", "hello"), ("a/bar.rs", "world")]; 355 | 356 | let dir = tempdir().unwrap(); 357 | for (path, text) in files.iter() { 358 | let file_path = dir.path().join(path); 359 | fs::create_dir_all(file_path.parent().unwrap()).unwrap(); 360 | fs::write(file_path, text).unwrap(); 361 | } 362 | 363 | let a_root = dir.path().join("a"); 364 | 365 | let (mut task_receiver, cb) = task_chan(); 366 | let (mut vfs, _) = 367 | Vfs::new(vec![RootEntry::new(a_root, IncludeRustFiles::boxed())], cb, Watch(false)); 368 | process_tasks(&mut vfs, &mut task_receiver, 1); 369 | assert_eq!(vfs.commit_changes().len(), 1); 370 | 371 | fs::write(dir.path().join("a/foo.rs"), "goodbye").unwrap(); 372 | assert_match!( 373 | task_receiver.recv_timeout(Duration::from_millis(300)), 374 | Err(RecvTimeoutError::Timeout) 375 | ); 376 | vfs.notify_changed(dir.path().join("a/foo.rs")); 377 | process_tasks(&mut vfs, &mut task_receiver, 1); 378 | assert_eq!(vfs.commit_changes().len(), 1); 379 | } 380 | --------------------------------------------------------------------------------