1#![allow(clippy::exhaustive_enums)]
2
3use std::borrow::Cow;
66use std::path::Path;
67use std::path::PathBuf;
68use std::sync::Arc;
69use std::sync::OnceLock;
70
71use foldhash::HashMap;
72use foldhash::HashMapExt;
73use rayon::iter::IntoParallelIterator;
74use rayon::iter::ParallelIterator;
75
76use crate::change::Change;
77use crate::change::ChangeLog;
78use crate::error::DatabaseError;
79use crate::exclusion::Exclusion;
80use crate::file::File;
81use crate::file::FileId;
82use crate::file::FileType;
83use crate::file::line_starts;
84use crate::operation::FilesystemOperation;
85
86mod utils;
87
88pub mod change;
89pub mod error;
90pub mod exclusion;
91pub mod file;
92pub mod git;
93pub mod loader;
94pub mod matcher;
95pub mod membership;
96pub mod watcher;
97
98mod operation;
99
100#[derive(Debug, Clone)]
102#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
103pub struct DatabaseConfiguration<'config> {
104 pub workspace: Cow<'config, Path>,
105 pub paths: Vec<Cow<'config, [u8]>>,
108 pub includes: Vec<Cow<'config, [u8]>>,
111 pub patches: Vec<Cow<'config, [u8]>>,
112 pub excludes: Vec<Exclusion<'config>>,
113 pub extensions: Vec<Cow<'config, [u8]>>,
114 pub glob: GlobSettings,
116}
117
118#[derive(Debug, Clone, Copy)]
122#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
123pub struct GlobSettings {
124 pub case_insensitive: bool,
128 pub literal_separator: bool,
134 pub backslash_escape: bool,
138 pub empty_alternates: bool,
142}
143
144impl Default for GlobSettings {
145 #[inline]
146 fn default() -> Self {
147 Self {
148 case_insensitive: false,
149 literal_separator: false,
150 backslash_escape: !std::path::is_separator('\\'),
151 empty_alternates: false,
152 }
153 }
154}
155
156impl<'config> DatabaseConfiguration<'config> {
157 #[inline]
158 #[must_use]
159 pub fn new(
160 workspace: &'config Path,
161 paths: Vec<&'config [u8]>,
162 includes: Vec<&'config [u8]>,
163 excludes: Vec<Exclusion<'config>>,
164 extensions: Vec<&'config [u8]>,
165 ) -> Self {
166 let paths = paths.into_iter().map(Cow::Borrowed).collect();
167 let includes = includes.into_iter().map(Cow::Borrowed).collect();
168
169 let excludes = excludes
170 .into_iter()
171 .filter_map(|exclusion| match exclusion {
172 Exclusion::Path(p) => Some(if p.is_absolute() {
173 Exclusion::Path(p)
174 } else {
175 workspace.join(p).canonicalize().ok().map(Cow::Owned).map(Exclusion::Path)?
176 }),
177 Exclusion::Pattern(pat) => Some(Exclusion::Pattern(pat)),
178 })
179 .collect();
180
181 let extensions = extensions.into_iter().map(Cow::Borrowed).collect();
182
183 Self {
184 workspace: Cow::Borrowed(workspace),
185 paths,
186 includes,
187 patches: Vec::new(),
188 excludes,
189 extensions,
190 glob: GlobSettings::default(),
191 }
192 }
193
194 #[inline]
195 #[must_use]
196 pub fn into_static(self) -> DatabaseConfiguration<'static> {
197 DatabaseConfiguration {
198 workspace: Cow::Owned(self.workspace.into_owned()),
199 paths: self.paths.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
200 includes: self.includes.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
201 patches: self.patches.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
202 excludes: self
203 .excludes
204 .into_iter()
205 .map(|e| match e {
206 Exclusion::Path(p) => Exclusion::Path(Cow::Owned(p.into_owned())),
207 Exclusion::Pattern(pat) => Exclusion::Pattern(Cow::Owned(pat.into_owned())),
208 })
209 .collect(),
210 extensions: self.extensions.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
211 glob: self.glob,
212 }
213 }
214}
215
216#[derive(Debug, Clone)]
218#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
219#[allow(clippy::field_scoped_visibility_modifiers)]
220pub struct Database<'config> {
221 files: HashMap<Cow<'static, [u8]>, Arc<File>>,
222 id_to_name: HashMap<FileId, Cow<'static, [u8]>>,
223 pub(crate) configuration: DatabaseConfiguration<'config>,
224}
225
226#[derive(Debug)]
228pub struct ReadDatabase {
229 files: Vec<Arc<File>>,
230 id_to_index: HashMap<FileId, usize>,
231 name_to_index: OnceLock<HashMap<Cow<'static, [u8]>, usize>>,
232 path_to_index: OnceLock<HashMap<PathBuf, usize>>,
233}
234
235impl<'config> Database<'config> {
236 #[inline]
237 #[must_use]
238 pub fn new(configuration: DatabaseConfiguration<'config>) -> Self {
239 Self { files: HashMap::default(), id_to_name: HashMap::default(), configuration }
240 }
241
242 #[inline]
243 #[must_use]
244 pub fn single(file: File, configuration: DatabaseConfiguration<'config>) -> Self {
245 let mut db = Self::new(configuration);
246 db.add(file);
247 db
248 }
249
250 #[inline]
252 #[must_use]
253 pub fn into_static(self) -> Database<'static> {
254 Database { files: self.files, id_to_name: self.id_to_name, configuration: self.configuration.into_static() }
255 }
256
257 #[inline]
259 pub fn reserve(&mut self, additional: usize) {
260 self.files.reserve(additional);
261 self.id_to_name.reserve(additional);
262 }
263
264 #[inline]
269 pub fn merge_base(&mut self, base: Database<'_>) {
270 let Database { files, mut id_to_name, configuration: _ } = base;
271 self.reserve(files.len());
272
273 for (name, file) in files {
274 if self.files.contains_key(name.as_ref()) {
275 continue;
276 }
277
278 let id = file.id;
279 let id_name = id_to_name.remove(&id).unwrap_or_else(|| name.clone());
280 self.files.insert(name, file);
281 self.id_to_name.insert(id, id_name);
282 }
283 }
284
285 #[inline]
286 pub fn add(&mut self, file: File) -> FileId {
287 let name = file.name.clone();
288 let id = file.id;
289
290 if let Some(old_file) = self.files.insert(name.clone(), Arc::new(file)) {
291 self.id_to_name.remove(&old_file.id);
292 }
293
294 self.id_to_name.insert(id, name);
295
296 id
297 }
298
299 #[inline]
307 pub fn update(&mut self, id: FileId, new_contents: Cow<'static, [u8]>) -> bool {
308 let Some(name) = self.id_to_name.get(&id) else {
309 return false;
310 };
311
312 let Some(arc) = self.files.get_mut(name) else {
313 return false;
314 };
315
316 if let Some(file) = Arc::get_mut(arc) {
317 file.contents = new_contents;
318 file.size = file.contents.len() as u32;
319 file.lines = line_starts(file.contents.as_ref());
320 } else {
321 let old = &**arc;
324 *arc = Arc::new(File::new(old.name.clone(), old.file_type, old.path.clone(), new_contents));
325 }
326
327 true
328 }
329
330 #[inline]
334 pub fn delete(&mut self, id: FileId) -> bool {
335 if let Some(name) = self.id_to_name.remove(&id) { self.files.remove(&name).is_some() } else { false }
336 }
337
338 #[inline]
352 pub fn commit(&mut self, change_log: ChangeLog, write_to_disk: bool) -> Result<(), DatabaseError> {
353 let changes = change_log.into_inner()?;
354 let mut fs_operations = Vec::new();
355
356 for change in changes {
357 match change {
358 Change::Add(file) => {
359 if write_to_disk && let Some(path) = &file.path {
360 fs_operations.push(FilesystemOperation::Write(path.clone(), file.contents.clone()));
361 }
362
363 self.add(file);
364 }
365 Change::Update(id, contents) => {
366 if write_to_disk
367 && let Ok(file) = self.get(&id)
368 && let Some(path) = &file.path
369 {
370 fs_operations.push(FilesystemOperation::Write(path.clone(), contents.clone()));
371 }
372
373 self.update(id, contents);
374 }
375 Change::Delete(id) => {
376 if write_to_disk
377 && let Ok(file) = self.get(&id)
378 && let Some(path) = &file.path
379 {
380 fs_operations.push(FilesystemOperation::Delete(path.clone()));
381 }
382
383 self.delete(id);
384 }
385 }
386 }
387
388 if write_to_disk {
389 fs_operations.into_par_iter().try_for_each(|op| -> Result<(), DatabaseError> { op.execute() })?;
390 }
391
392 Ok(())
393 }
394
395 #[inline]
400 #[must_use]
401 pub fn read_only(&self) -> ReadDatabase {
402 let mut entries: Vec<(FileId, &Arc<File>)> = self.files.values().map(|file| (file.id, file)).collect();
403 entries.sort_unstable_by_key(|(id, _)| *id);
404
405 let mut files = Vec::with_capacity(entries.len());
406 let mut id_to_index = HashMap::with_capacity(entries.len());
407 for (index, (id, file)) in entries.into_iter().enumerate() {
408 files.push(Arc::clone(file));
409 id_to_index.insert(id, index);
410 }
411
412 ReadDatabase { files, id_to_index, name_to_index: OnceLock::new(), path_to_index: OnceLock::new() }
413 }
414}
415
416impl ReadDatabase {
417 #[inline]
418 #[must_use]
419 pub fn empty() -> Self {
420 Self {
421 files: Vec::new(),
422 id_to_index: HashMap::new(),
423 name_to_index: OnceLock::new(),
424 path_to_index: OnceLock::new(),
425 }
426 }
427
428 #[inline]
438 #[must_use]
439 pub fn single(file: File) -> Self {
440 let mut id_to_index = HashMap::with_capacity(1);
441 id_to_index.insert(file.id, 0);
442
443 Self {
444 files: vec![Arc::new(file)],
445 id_to_index,
446 name_to_index: OnceLock::new(),
447 path_to_index: OnceLock::new(),
448 }
449 }
450
451 fn name_index(&self) -> &HashMap<Cow<'static, [u8]>, usize> {
452 self.name_to_index
453 .get_or_init(|| self.files.iter().enumerate().map(|(index, file)| (file.name.clone(), index)).collect())
454 }
455
456 fn path_index(&self) -> &HashMap<PathBuf, usize> {
457 self.path_to_index.get_or_init(|| {
458 self.files
459 .iter()
460 .enumerate()
461 .filter_map(|(index, file)| file.path.as_ref().map(|path| (path.clone(), index)))
462 .collect()
463 })
464 }
465}
466
467pub trait DatabaseReader {
473 fn get_id(&self, name: &[u8]) -> Option<FileId>;
475
476 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError>;
482
483 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError>;
489
490 fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError>;
496
497 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError>;
503
504 fn files(&self) -> impl Iterator<Item = Arc<File>>;
509
510 #[inline]
512 fn files_with_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
513 self.files().filter(move |file| file.file_type == file_type)
514 }
515
516 #[inline]
518 fn files_without_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
519 self.files().filter(move |file| file.file_type != file_type)
520 }
521
522 #[inline]
524 fn file_ids(&self) -> impl Iterator<Item = FileId> {
525 self.files().map(|file| file.id)
526 }
527
528 #[inline]
530 fn file_ids_with_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
531 self.files_with_type(file_type).map(|file| file.id)
532 }
533
534 #[inline]
536 fn file_ids_without_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
537 self.files_without_type(file_type).map(|file| file.id)
538 }
539
540 fn len(&self) -> usize;
542
543 #[inline]
545 fn is_empty(&self) -> bool {
546 self.len() == 0
547 }
548}
549
550impl DatabaseReader for Database<'_> {
551 #[inline]
552 fn get_id(&self, name: &[u8]) -> Option<FileId> {
553 self.files.get(name).map(|f| f.id)
554 }
555
556 #[inline]
557 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
558 let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
559 let file = self.files.get(name).ok_or(DatabaseError::FileNotFound)?;
560
561 Ok(Arc::clone(file))
562 }
563
564 #[inline]
565 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
566 let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
567 self.files.get(name).map(std::convert::AsRef::as_ref).ok_or(DatabaseError::FileNotFound)
568 }
569
570 #[inline]
571 fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError> {
572 self.files.get(name).cloned().ok_or(DatabaseError::FileNotFound)
573 }
574
575 #[inline]
576 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
577 self.files.values().find(|file| file.path.as_deref() == Some(path)).cloned().ok_or(DatabaseError::FileNotFound)
578 }
579
580 #[inline]
581 fn files(&self) -> impl Iterator<Item = Arc<File>> {
582 self.files.values().cloned()
583 }
584
585 #[inline]
586 fn len(&self) -> usize {
587 self.files.len()
588 }
589}
590
591impl DatabaseReader for ReadDatabase {
592 #[inline]
593 fn get_id(&self, name: &[u8]) -> Option<FileId> {
594 self.name_index().get(name).and_then(|&i| self.files.get(i)).map(|f| f.id)
595 }
596
597 #[inline]
598 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
599 let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
600
601 self.files.get(*index).cloned().ok_or(DatabaseError::FileNotFound)
602 }
603
604 #[inline]
605 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
606 let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
607
608 self.files.get(*index).map(std::convert::AsRef::as_ref).ok_or(DatabaseError::FileNotFound)
609 }
610
611 #[inline]
612 fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError> {
613 self.name_index().get(name).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
614 }
615
616 #[inline]
617 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
618 self.path_index().get(path).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
619 }
620
621 #[inline]
622 fn files(&self) -> impl Iterator<Item = Arc<File>> {
623 self.files.iter().cloned()
624 }
625
626 #[inline]
627 fn len(&self) -> usize {
628 self.files.len()
629 }
630}
631
632#[cfg(test)]
633#[allow(clippy::unwrap_used)]
634mod tests {
635 use super::*;
636
637 fn configuration() -> DatabaseConfiguration<'static> {
638 DatabaseConfiguration::new(Path::new("/"), vec![], vec![], vec![], vec![]).into_static()
639 }
640
641 #[test]
642 fn merge_base_adds_missing_files_without_replacing_project_files() {
643 let mut base = Database::new(configuration());
644 base.add(File::new(Cow::Borrowed(b"shared.php"), FileType::Builtin, None, Cow::Borrowed(b"base")));
645 base.add(File::new(Cow::Borrowed(b"builtin.php"), FileType::Builtin, None, Cow::Borrowed(b"builtin")));
646
647 let mut project = Database::new(configuration());
648 project.add(File::new(Cow::Borrowed(b"shared.php"), FileType::Host, None, Cow::Borrowed(b"project")));
649 project.add(File::new(Cow::Borrowed(b"project.php"), FileType::Host, None, Cow::Borrowed(b"project-only")));
650
651 project.merge_base(base);
652
653 assert_eq!(project.len(), 3);
654 let shared = project.get_by_name(b"shared.php").unwrap();
655 assert_eq!(shared.file_type, FileType::Host);
656 assert_eq!(shared.contents.as_ref(), b"project");
657
658 let builtin = project.get_by_name(b"builtin.php").unwrap();
659 assert_eq!(builtin.file_type, FileType::Builtin);
660 assert_eq!(project.get(&builtin.id).unwrap().name.as_ref(), b"builtin.php");
661 }
662}