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 loader;
93pub mod matcher;
94pub mod membership;
95pub mod watcher;
96
97mod operation;
98
99#[derive(Debug, Clone)]
101#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
102pub struct DatabaseConfiguration<'config> {
103 pub workspace: Cow<'config, Path>,
104 pub paths: Vec<Cow<'config, [u8]>>,
107 pub includes: Vec<Cow<'config, [u8]>>,
110 pub patches: Vec<Cow<'config, [u8]>>,
111 pub excludes: Vec<Exclusion<'config>>,
112 pub extensions: Vec<Cow<'config, [u8]>>,
113 pub glob: GlobSettings,
115}
116
117#[derive(Debug, Clone, Copy)]
121#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
122pub struct GlobSettings {
123 pub case_insensitive: bool,
127 pub literal_separator: bool,
133 pub backslash_escape: bool,
137 pub empty_alternates: bool,
141}
142
143impl Default for GlobSettings {
144 #[inline]
145 fn default() -> Self {
146 Self {
147 case_insensitive: false,
148 literal_separator: false,
149 backslash_escape: !std::path::is_separator('\\'),
150 empty_alternates: false,
151 }
152 }
153}
154
155impl<'config> DatabaseConfiguration<'config> {
156 #[inline]
157 #[must_use]
158 pub fn new(
159 workspace: &'config Path,
160 paths: Vec<&'config [u8]>,
161 includes: Vec<&'config [u8]>,
162 excludes: Vec<Exclusion<'config>>,
163 extensions: Vec<&'config [u8]>,
164 ) -> Self {
165 let paths = paths.into_iter().map(Cow::Borrowed).collect();
166 let includes = includes.into_iter().map(Cow::Borrowed).collect();
167
168 let excludes = excludes
169 .into_iter()
170 .filter_map(|exclusion| match exclusion {
171 Exclusion::Path(p) => Some(if p.is_absolute() {
172 Exclusion::Path(p)
173 } else {
174 workspace.join(p).canonicalize().ok().map(Cow::Owned).map(Exclusion::Path)?
175 }),
176 Exclusion::Pattern(pat) => Some(Exclusion::Pattern(pat)),
177 })
178 .collect();
179
180 let extensions = extensions.into_iter().map(Cow::Borrowed).collect();
181
182 Self {
183 workspace: Cow::Borrowed(workspace),
184 paths,
185 includes,
186 patches: Vec::new(),
187 excludes,
188 extensions,
189 glob: GlobSettings::default(),
190 }
191 }
192
193 #[inline]
194 #[must_use]
195 pub fn into_static(self) -> DatabaseConfiguration<'static> {
196 DatabaseConfiguration {
197 workspace: Cow::Owned(self.workspace.into_owned()),
198 paths: self.paths.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
199 includes: self.includes.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
200 patches: self.patches.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
201 excludes: self
202 .excludes
203 .into_iter()
204 .map(|e| match e {
205 Exclusion::Path(p) => Exclusion::Path(Cow::Owned(p.into_owned())),
206 Exclusion::Pattern(pat) => Exclusion::Pattern(Cow::Owned(pat.into_owned())),
207 })
208 .collect(),
209 extensions: self.extensions.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
210 glob: self.glob,
211 }
212 }
213}
214
215#[derive(Debug, Clone)]
217#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
218#[allow(clippy::field_scoped_visibility_modifiers)]
219pub struct Database<'config> {
220 files: HashMap<Cow<'static, [u8]>, Arc<File>>,
221 id_to_name: HashMap<FileId, Cow<'static, [u8]>>,
222 pub(crate) configuration: DatabaseConfiguration<'config>,
223}
224
225#[derive(Debug)]
227pub struct ReadDatabase {
228 files: Vec<Arc<File>>,
229 id_to_index: HashMap<FileId, usize>,
230 name_to_index: OnceLock<HashMap<Cow<'static, [u8]>, usize>>,
231 path_to_index: OnceLock<HashMap<PathBuf, usize>>,
232}
233
234impl<'config> Database<'config> {
235 #[inline]
236 #[must_use]
237 pub fn new(configuration: DatabaseConfiguration<'config>) -> Self {
238 Self { files: HashMap::default(), id_to_name: HashMap::default(), configuration }
239 }
240
241 #[inline]
242 #[must_use]
243 pub fn single(file: File, configuration: DatabaseConfiguration<'config>) -> Self {
244 let mut db = Self::new(configuration);
245 db.add(file);
246 db
247 }
248
249 #[inline]
251 pub fn reserve(&mut self, additional: usize) {
252 self.files.reserve(additional);
253 self.id_to_name.reserve(additional);
254 }
255
256 #[inline]
261 pub fn merge_base(&mut self, base: Database<'_>) {
262 let Database { files, mut id_to_name, configuration: _ } = base;
263 self.reserve(files.len());
264
265 for (name, file) in files {
266 if self.files.contains_key(name.as_ref()) {
267 continue;
268 }
269
270 let id = file.id;
271 let id_name = id_to_name.remove(&id).unwrap_or_else(|| name.clone());
272 self.files.insert(name, file);
273 self.id_to_name.insert(id, id_name);
274 }
275 }
276
277 #[inline]
278 pub fn add(&mut self, file: File) -> FileId {
279 let name = file.name.clone();
280 let id = file.id;
281
282 if let Some(old_file) = self.files.insert(name.clone(), Arc::new(file)) {
283 self.id_to_name.remove(&old_file.id);
284 }
285
286 self.id_to_name.insert(id, name);
287
288 id
289 }
290
291 #[inline]
299 pub fn update(&mut self, id: FileId, new_contents: Cow<'static, [u8]>) -> bool {
300 let Some(name) = self.id_to_name.get(&id) else {
301 return false;
302 };
303
304 let Some(arc) = self.files.get_mut(name) else {
305 return false;
306 };
307
308 if let Some(file) = Arc::get_mut(arc) {
309 file.contents = new_contents;
310 file.size = file.contents.len() as u32;
311 file.lines = line_starts(file.contents.as_ref());
312 } else {
313 let old = &**arc;
316 *arc = Arc::new(File::new(old.name.clone(), old.file_type, old.path.clone(), new_contents));
317 }
318
319 true
320 }
321
322 #[inline]
326 pub fn delete(&mut self, id: FileId) -> bool {
327 if let Some(name) = self.id_to_name.remove(&id) { self.files.remove(&name).is_some() } else { false }
328 }
329
330 #[inline]
344 pub fn commit(&mut self, change_log: ChangeLog, write_to_disk: bool) -> Result<(), DatabaseError> {
345 let changes = change_log.into_inner()?;
346 let mut fs_operations = Vec::new();
347
348 for change in changes {
349 match change {
350 Change::Add(file) => {
351 if write_to_disk && let Some(path) = &file.path {
352 fs_operations.push(FilesystemOperation::Write(path.clone(), file.contents.clone()));
353 }
354
355 self.add(file);
356 }
357 Change::Update(id, contents) => {
358 if write_to_disk
359 && let Ok(file) = self.get(&id)
360 && let Some(path) = &file.path
361 {
362 fs_operations.push(FilesystemOperation::Write(path.clone(), contents.clone()));
363 }
364
365 self.update(id, contents);
366 }
367 Change::Delete(id) => {
368 if write_to_disk
369 && let Ok(file) = self.get(&id)
370 && let Some(path) = &file.path
371 {
372 fs_operations.push(FilesystemOperation::Delete(path.clone()));
373 }
374
375 self.delete(id);
376 }
377 }
378 }
379
380 if write_to_disk {
381 fs_operations.into_par_iter().try_for_each(|op| -> Result<(), DatabaseError> { op.execute() })?;
382 }
383
384 Ok(())
385 }
386
387 #[inline]
392 #[must_use]
393 pub fn read_only(&self) -> ReadDatabase {
394 let mut files_vec: Vec<Arc<File>> = self.files.values().cloned().collect();
395 files_vec.sort_unstable_by_key(|f| f.id);
396
397 let mut id_to_index = HashMap::with_capacity(files_vec.len());
398 for (index, file) in files_vec.iter().enumerate() {
399 id_to_index.insert(file.id, index);
400 }
401
402 ReadDatabase { files: files_vec, id_to_index, name_to_index: OnceLock::new(), path_to_index: OnceLock::new() }
403 }
404}
405
406impl ReadDatabase {
407 #[inline]
408 #[must_use]
409 pub fn empty() -> Self {
410 Self {
411 files: Vec::new(),
412 id_to_index: HashMap::new(),
413 name_to_index: OnceLock::new(),
414 path_to_index: OnceLock::new(),
415 }
416 }
417
418 #[inline]
428 #[must_use]
429 pub fn single(file: File) -> Self {
430 let mut id_to_index = HashMap::with_capacity(1);
431 id_to_index.insert(file.id, 0);
432
433 Self {
434 files: vec![Arc::new(file)],
435 id_to_index,
436 name_to_index: OnceLock::new(),
437 path_to_index: OnceLock::new(),
438 }
439 }
440
441 fn name_index(&self) -> &HashMap<Cow<'static, [u8]>, usize> {
442 self.name_to_index
443 .get_or_init(|| self.files.iter().enumerate().map(|(index, file)| (file.name.clone(), index)).collect())
444 }
445
446 fn path_index(&self) -> &HashMap<PathBuf, usize> {
447 self.path_to_index.get_or_init(|| {
448 self.files
449 .iter()
450 .enumerate()
451 .filter_map(|(index, file)| file.path.as_ref().map(|path| (path.clone(), index)))
452 .collect()
453 })
454 }
455}
456
457pub trait DatabaseReader {
463 fn get_id(&self, name: &[u8]) -> Option<FileId>;
465
466 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError>;
472
473 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError>;
479
480 fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError>;
486
487 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError>;
493
494 fn files(&self) -> impl Iterator<Item = Arc<File>>;
499
500 #[inline]
502 fn files_with_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
503 self.files().filter(move |file| file.file_type == file_type)
504 }
505
506 #[inline]
508 fn files_without_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
509 self.files().filter(move |file| file.file_type != file_type)
510 }
511
512 #[inline]
514 fn file_ids(&self) -> impl Iterator<Item = FileId> {
515 self.files().map(|file| file.id)
516 }
517
518 #[inline]
520 fn file_ids_with_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
521 self.files_with_type(file_type).map(|file| file.id)
522 }
523
524 #[inline]
526 fn file_ids_without_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
527 self.files_without_type(file_type).map(|file| file.id)
528 }
529
530 fn len(&self) -> usize;
532
533 #[inline]
535 fn is_empty(&self) -> bool {
536 self.len() == 0
537 }
538}
539
540impl DatabaseReader for Database<'_> {
541 #[inline]
542 fn get_id(&self, name: &[u8]) -> Option<FileId> {
543 self.files.get(name).map(|f| f.id)
544 }
545
546 #[inline]
547 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
548 let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
549 let file = self.files.get(name).ok_or(DatabaseError::FileNotFound)?;
550
551 Ok(Arc::clone(file))
552 }
553
554 #[inline]
555 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
556 let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
557 self.files.get(name).map(std::convert::AsRef::as_ref).ok_or(DatabaseError::FileNotFound)
558 }
559
560 #[inline]
561 fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError> {
562 self.files.get(name).cloned().ok_or(DatabaseError::FileNotFound)
563 }
564
565 #[inline]
566 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
567 self.files.values().find(|file| file.path.as_deref() == Some(path)).cloned().ok_or(DatabaseError::FileNotFound)
568 }
569
570 #[inline]
571 fn files(&self) -> impl Iterator<Item = Arc<File>> {
572 self.files.values().cloned()
573 }
574
575 #[inline]
576 fn len(&self) -> usize {
577 self.files.len()
578 }
579}
580
581impl DatabaseReader for ReadDatabase {
582 #[inline]
583 fn get_id(&self, name: &[u8]) -> Option<FileId> {
584 self.name_index().get(name).and_then(|&i| self.files.get(i)).map(|f| f.id)
585 }
586
587 #[inline]
588 fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
589 let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
590
591 self.files.get(*index).cloned().ok_or(DatabaseError::FileNotFound)
592 }
593
594 #[inline]
595 fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
596 let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
597
598 self.files.get(*index).map(std::convert::AsRef::as_ref).ok_or(DatabaseError::FileNotFound)
599 }
600
601 #[inline]
602 fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError> {
603 self.name_index().get(name).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
604 }
605
606 #[inline]
607 fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
608 self.path_index().get(path).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
609 }
610
611 #[inline]
612 fn files(&self) -> impl Iterator<Item = Arc<File>> {
613 self.files.iter().cloned()
614 }
615
616 #[inline]
617 fn len(&self) -> usize {
618 self.files.len()
619 }
620}
621
622#[cfg(test)]
623#[allow(clippy::unwrap_used)]
624mod tests {
625 use super::*;
626
627 fn configuration() -> DatabaseConfiguration<'static> {
628 DatabaseConfiguration::new(Path::new("/"), vec![], vec![], vec![], vec![]).into_static()
629 }
630
631 #[test]
632 fn merge_base_adds_missing_files_without_replacing_project_files() {
633 let mut base = Database::new(configuration());
634 base.add(File::new(Cow::Borrowed(b"shared.php"), FileType::Builtin, None, Cow::Borrowed(b"base")));
635 base.add(File::new(Cow::Borrowed(b"builtin.php"), FileType::Builtin, None, Cow::Borrowed(b"builtin")));
636
637 let mut project = Database::new(configuration());
638 project.add(File::new(Cow::Borrowed(b"shared.php"), FileType::Host, None, Cow::Borrowed(b"project")));
639 project.add(File::new(Cow::Borrowed(b"project.php"), FileType::Host, None, Cow::Borrowed(b"project-only")));
640
641 project.merge_base(base);
642
643 assert_eq!(project.len(), 3);
644 let shared = project.get_by_name(b"shared.php").unwrap();
645 assert_eq!(shared.file_type, FileType::Host);
646 assert_eq!(shared.contents.as_ref(), b"project");
647
648 let builtin = project.get_by_name(b"builtin.php").unwrap();
649 assert_eq!(builtin.file_type, FileType::Builtin);
650 assert_eq!(project.get(&builtin.id).unwrap().name.as_ref(), b"builtin.php");
651 }
652}