1use std::borrow::Cow;
64use std::path::Path;
65use std::path::PathBuf;
66use std::sync::Arc;
67
68use ahash::HashMap;
69use ahash::HashMapExt;
70use rayon::iter::IntoParallelIterator;
71use rayon::iter::ParallelIterator;
72use serde::Deserialize;
73use serde::Serialize;
74
75use crate::change::Change;
76use crate::change::ChangeLog;
77use crate::error::DatabaseError;
78use crate::exclusion::Exclusion;
79use crate::file::File;
80use crate::file::FileId;
81use crate::file::FileType;
82use crate::file::line_starts;
83use crate::operation::FilesystemOperation;
84
85mod utils;
86
87pub mod change;
88pub mod error;
89pub mod exclusion;
90pub mod file;
91pub mod loader;
92pub mod watcher;
93
94mod operation;
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct DatabaseConfiguration<'a> {
99 pub workspace: Cow<'a, Path>,
100 pub paths: Vec<Cow<'a, str>>,
103 pub includes: Vec<Cow<'a, str>>,
106 pub excludes: Vec<Exclusion<'a>>,
107 pub extensions: Vec<Cow<'a, str>>,
108}
109
110impl<'a> DatabaseConfiguration<'a> {
111 pub fn new(
112 workspace: &'a Path,
113 paths: Vec<&'a str>,
114 includes: Vec<&'a str>,
115 excludes: Vec<Exclusion<'a>>,
116 extensions: Vec<&'a str>,
117 ) -> Self {
118 let paths = paths.into_iter().map(Cow::Borrowed).collect();
119 let includes = includes.into_iter().map(Cow::Borrowed).collect();
120
121 let excludes = excludes
122 .into_iter()
123 .filter_map(|exclusion| match exclusion {
124 Exclusion::Path(p) => Some(if p.is_absolute() {
125 Exclusion::Path(p)
126 } else {
127 workspace.join(p).canonicalize().ok().map(Cow::Owned).map(Exclusion::Path)?
128 }),
129 Exclusion::Pattern(pat) => Some(Exclusion::Pattern(pat)),
130 })
131 .collect();
132
133 let extensions = extensions.into_iter().map(Cow::Borrowed).collect();
134
135 Self { workspace: Cow::Borrowed(workspace), paths, includes, excludes, extensions }
136 }
137
138 pub fn into_static(self) -> DatabaseConfiguration<'static> {
139 DatabaseConfiguration {
140 workspace: Cow::Owned(self.workspace.into_owned()),
141 paths: self.paths.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
142 includes: self.includes.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
143 excludes: self
144 .excludes
145 .into_iter()
146 .map(|e| match e {
147 Exclusion::Path(p) => Exclusion::Path(Cow::Owned(p.into_owned())),
148 Exclusion::Pattern(pat) => Exclusion::Pattern(Cow::Owned(pat.into_owned())),
149 })
150 .collect(),
151 extensions: self.extensions.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
152 }
153 }
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct Database<'a> {
159 files: HashMap<Cow<'static, str>, Arc<File>>,
160 id_to_name: HashMap<FileId, Cow<'static, str>>,
161 pub(crate) configuration: DatabaseConfiguration<'a>,
162}
163
164#[derive(Debug)]
166pub struct ReadDatabase {
167 files: Vec<Arc<File>>,
168 id_to_index: HashMap<FileId, usize>,
169 name_to_index: HashMap<Cow<'static, str>, usize>,
170 path_to_index: HashMap<PathBuf, usize>,
171}
172
173impl<'a> Database<'a> {
174 pub fn new(configuration: DatabaseConfiguration<'a>) -> Self {
175 Self { files: HashMap::default(), id_to_name: HashMap::default(), configuration }
176 }
177
178 pub fn single(file: File, configuration: DatabaseConfiguration<'a>) -> Self {
179 let mut db = Self::new(configuration);
180 db.add(file);
181 db
182 }
183
184 pub fn add(&mut self, file: File) -> FileId {
185 let name = file.name.clone();
186 let id = file.id;
187
188 if let Some(old_file) = self.files.insert(name.clone(), Arc::new(file)) {
189 self.id_to_name.remove(&old_file.id);
190 }
191
192 self.id_to_name.insert(id, name);
193
194 id
195 }
196
197 pub fn update(&mut self, id: FileId, new_contents: Cow<'static, str>) -> bool {
202 if let Some(name) = self.id_to_name.get(&id)
203 && let Some(file) = self.files.get_mut(name)
204 && let Some(file) = Arc::get_mut(file)
205 {
206 file.contents = new_contents;
207 file.size = file.contents.len() as u32;
208 file.lines = line_starts(file.contents.as_ref()).collect();
209 return true;
210 }
211 false
212 }
213
214 pub fn delete(&mut self, id: FileId) -> bool {
218 if let Some(name) = self.id_to_name.remove(&id) { self.files.remove(&name).is_some() } else { false }
219 }
220
221 pub fn commit(&mut self, change_log: ChangeLog, write_to_disk: bool) -> Result<(), DatabaseError> {
235 let changes = change_log.into_inner()?;
236 let mut fs_operations = if write_to_disk { Vec::new() } else { Vec::with_capacity(0) };
237
238 for change in changes {
239 match change {
240 Change::Add(file) => {
241 if write_to_disk && let Some(path) = &file.path {
242 fs_operations.push(FilesystemOperation::Write(path.clone(), file.contents.clone()));
243 }
244
245 self.add(file);
246 }
247 Change::Update(id, contents) => {
248 if write_to_disk
249 && let Ok(file) = self.get(&id)
250 && let Some(path) = &file.path
251 {
252 fs_operations.push(FilesystemOperation::Write(path.clone(), contents.clone()));
253 }
254
255 self.update(id, contents);
256 }
257 Change::Delete(id) => {
258 if write_to_disk
259 && let Ok(file) = self.get(&id)
260 && let Some(path) = &file.path
261 {
262 fs_operations.push(FilesystemOperation::Delete(path.clone()));
263 }
264
265 self.delete(id);
266 }
267 }
268 }
269
270 if write_to_disk {
271 fs_operations.into_par_iter().try_for_each(|op| -> Result<(), DatabaseError> { op.execute() })?;
272 }
273
274 Ok(())
275 }
276
277 pub fn read_only(&self) -> ReadDatabase {
284 let mut files_vec: Vec<Arc<File>> = self.files.values().cloned().collect();
285 files_vec.sort_unstable_by_key(|f| f.id);
286
287 let mut id_to_index = HashMap::with_capacity(files_vec.len());
288 let mut name_to_index = HashMap::with_capacity(files_vec.len());
289 let mut path_to_index = HashMap::with_capacity(files_vec.len());
290
291 for (index, file) in files_vec.iter().enumerate() {
292 id_to_index.insert(file.id, index);
293 name_to_index.insert(file.name.clone(), index);
294 if let Some(path) = &file.path {
295 path_to_index.insert(path.clone(), index);
296 }
297 }
298
299 ReadDatabase { files: files_vec, id_to_index, name_to_index, path_to_index }
300 }
301}
302
303impl ReadDatabase {
304 pub fn empty() -> Self {
305 Self {
306 files: Vec::with_capacity(0),
307 id_to_index: HashMap::with_capacity(0),
308 name_to_index: HashMap::with_capacity(0),
309 path_to_index: HashMap::with_capacity(0),
310 }
311 }
312
313 pub fn single(file: File) -> Self {
323 let mut id_to_index = HashMap::with_capacity(1);
324 let mut name_to_index = HashMap::with_capacity(1);
325 let mut path_to_index = HashMap::with_capacity(1);
326
327 id_to_index.insert(file.id, 0);
328 name_to_index.insert(file.name.clone(), 0);
329 if let Some(path) = &file.path {
330 path_to_index.insert(path.clone(), 0);
331 }
332
333 Self { files: vec![Arc::new(file)], id_to_index, name_to_index, path_to_index }
334 }
335}
336
337pub trait DatabaseReader {
343 fn get_id(&self, name: &str) -> Option<FileId>;
345
346 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError>;
352
353 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError>;
359
360 fn get_by_name(&self, name: &str) -> Result<Arc<File>, DatabaseError>;
366
367 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError>;
373
374 fn files(&self) -> impl Iterator<Item = Arc<File>>;
379
380 fn files_with_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
382 self.files().filter(move |file| file.file_type == file_type)
383 }
384
385 fn files_without_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
387 self.files().filter(move |file| file.file_type != file_type)
388 }
389
390 fn file_ids(&self) -> impl Iterator<Item = FileId> {
392 self.files().map(|file| file.id)
393 }
394
395 fn file_ids_with_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
397 self.files_with_type(file_type).map(|file| file.id)
398 }
399
400 fn file_ids_without_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
402 self.files_without_type(file_type).map(|file| file.id)
403 }
404
405 fn len(&self) -> usize;
407
408 fn is_empty(&self) -> bool {
410 self.len() == 0
411 }
412}
413
414impl<'a> DatabaseReader for Database<'a> {
415 fn get_id(&self, name: &str) -> Option<FileId> {
416 self.files.get(name).map(|f| f.id)
417 }
418
419 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
420 let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
421 let file = self.files.get(name).ok_or(DatabaseError::FileNotFound)?;
422
423 Ok(file.clone())
424 }
425
426 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
427 let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
428 self.files.get(name).map(|file| file.as_ref()).ok_or(DatabaseError::FileNotFound)
429 }
430
431 fn get_by_name(&self, name: &str) -> Result<Arc<File>, DatabaseError> {
432 self.files.get(name).cloned().ok_or(DatabaseError::FileNotFound)
433 }
434
435 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
436 self.files.values().find(|file| file.path.as_deref() == Some(path)).cloned().ok_or(DatabaseError::FileNotFound)
437 }
438
439 fn files(&self) -> impl Iterator<Item = Arc<File>> {
440 self.files.values().cloned()
441 }
442
443 fn len(&self) -> usize {
444 self.files.len()
445 }
446}
447
448impl DatabaseReader for ReadDatabase {
449 fn get_id(&self, name: &str) -> Option<FileId> {
450 self.name_to_index.get(name).and_then(|&i| self.files.get(i)).map(|f| f.id)
451 }
452
453 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
454 let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
455
456 self.files.get(*index).cloned().ok_or(DatabaseError::FileNotFound)
457 }
458
459 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
460 let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
461
462 self.files.get(*index).map(|file| file.as_ref()).ok_or(DatabaseError::FileNotFound)
463 }
464
465 fn get_by_name(&self, name: &str) -> Result<Arc<File>, DatabaseError> {
466 self.name_to_index.get(name).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
467 }
468
469 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
470 self.path_to_index.get(path).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
471 }
472
473 fn files(&self) -> impl Iterator<Item = Arc<File>> {
474 self.files.iter().cloned()
475 }
476
477 fn len(&self) -> usize {
478 self.files.len()
479 }
480}