notify-debouncer-full-0.5.0/.cargo_vcs_info.json0000644000000001630000000000100152520ustar { "git": { "sha1": "48541cb70fd4bcca131f39878194d0a22bb776f6" }, "path_in_vcs": "notify-debouncer-full" }notify-debouncer-full-0.5.0/Cargo.toml0000644000000035360000000000100132570ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.77" name = "notify-debouncer-full" version = "0.5.0" authors = ["Daniel Faust "] description = "notify event debouncer optimized for ease of use" homepage = "https://github.com/notify-rs/notify" documentation = "https://docs.rs/notify-debouncer-full" readme = "README.md" keywords = [ "events", "filesystem", "notify", "watch", ] license = "MIT OR Apache-2.0" repository = "https://github.com/notify-rs/notify.git" [dependencies.crossbeam-channel] version = "0.5.0" optional = true [dependencies.file-id] version = "0.2.2" [dependencies.log] version = "0.4.17" [dependencies.notify] version = "8.0.0" [dependencies.notify-types] version = "2.0.0" [dependencies.walkdir] version = "2.4.0" [dev-dependencies.deser-hjson] version = "2.2.4" [dev-dependencies.pretty_assertions] version = "1.3.0" [dev-dependencies.rand] version = "0.8.5" [dev-dependencies.rstest] version = "0.24.0" [dev-dependencies.serde] version = "1.0.89" features = ["derive"] [dev-dependencies.tempfile] version = "3.10.0" [features] crossbeam-channel = [ "dep:crossbeam-channel", "notify/crossbeam-channel", ] default = ["macos_fsevent"] macos_fsevent = ["notify/macos_fsevent"] macos_kqueue = ["notify/macos_kqueue"] serde = ["notify-types/serde"] serialization-compat-6 = ["notify/serialization-compat-6"] web-time = ["notify-types/web-time"] notify-debouncer-full-0.5.0/Cargo.toml.orig000064400000000000000000000021701046102023000167310ustar 00000000000000[package] name = "notify-debouncer-full" version = "0.5.0" description = "notify event debouncer optimized for ease of use" documentation = "https://docs.rs/notify-debouncer-full" authors = ["Daniel Faust "] keywords = ["events", "filesystem", "notify", "watch"] license = "MIT OR Apache-2.0" readme = "README.md" rust-version.workspace = true edition.workspace = true homepage.workspace = true repository.workspace = true [features] default = ["macos_fsevent"] serde = ["notify-types/serde"] web-time = ["notify-types/web-time"] crossbeam-channel = ["dep:crossbeam-channel", "notify/crossbeam-channel"] macos_fsevent = ["notify/macos_fsevent"] macos_kqueue = ["notify/macos_kqueue"] serialization-compat-6 = ["notify/serialization-compat-6"] [dependencies] notify.workspace = true notify-types.workspace = true crossbeam-channel = { workspace = true, optional = true } file-id.workspace = true walkdir.workspace = true log.workspace = true [dev-dependencies] pretty_assertions.workspace = true rstest.workspace = true serde.workspace = true deser-hjson.workspace = true rand.workspace = true tempfile.workspace = true notify-debouncer-full-0.5.0/LICENSE-APACHE000064400000000000000000000251271046102023000157750ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 Notify Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. notify-debouncer-full-0.5.0/LICENSE-MIT000064400000000000000000000020471046102023000155010ustar 00000000000000Copyright (c) 2023 Notify Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. notify-debouncer-full-0.5.0/README.md000064400000000000000000000016341046102023000153250ustar 00000000000000# Notify Debouncer Full [![ยป Docs](https://flat.badgen.net/badge/api/docs.rs/df3600)][docs] A debouncer for [notify] that is optimized for ease of use. * Only emits a single `Rename` event if the rename `From` and `To` events can be matched * Merges multiple `Rename` events * Takes `Rename` events into account and updates paths for events that occurred before the rename event, but which haven't been emitted, yet * Optionally keeps track of the file system IDs all files and stitches rename events together (FSevents, Windows) * Emits only one `Remove` event when deleting a directory (inotify) * Doesn't emit duplicate create events * Doesn't emit `Modify` events after a `Create` event ## Features - `crossbeam-channel` passed down to notify, off by default - `serialization-compat-6` passed down to notify, off by default [docs]: https://docs.rs/notify-debouncer-full [notify]: https://crates.io/crates/notify notify-debouncer-full-0.5.0/src/cache.rs000064400000000000000000000073141046102023000162470ustar 00000000000000use std::{ collections::HashMap, path::{Path, PathBuf}, }; use file_id::{get_file_id, FileId}; use notify::RecursiveMode; use walkdir::WalkDir; /// The interface of a file ID cache. /// /// This trait can be implemented for an existing cache, if it already holds `FileId`s. pub trait FileIdCache { /// Get a `FileId` from the cache for a given `path`. /// /// If the path is not cached, `None` should be returned and there should not be any attempt to read the file ID from disk. fn cached_file_id(&self, path: &Path) -> Option<&FileId>; /// Add a new path to the cache or update its value. /// /// This will be called if a new file or directory is created or if an existing file is overridden. fn add_path(&mut self, path: &Path, recursive_mode: RecursiveMode); /// Remove a path from the cache. /// /// This will be called if a file or directory is deleted. fn remove_path(&mut self, path: &Path); /// Re-scan all `root_paths`. /// /// This will be called if the notification back-end has dropped events. /// The root paths are passed as argument, so the implementer doesn't have to store them. /// /// The default implementation calls `add_path` for each root path. fn rescan(&mut self, root_paths: &[(PathBuf, RecursiveMode)]) { for (path, recursive_mode) in root_paths { self.add_path(path, *recursive_mode); } } } /// A cache to hold the file system IDs of all watched files. /// /// The file ID cache uses unique file IDs provided by the file system and is used to stich together /// rename events in case the notification back-end doesn't emit rename cookies. #[derive(Debug, Clone, Default)] pub struct FileIdMap { paths: HashMap, } impl FileIdMap { /// Construct an empty cache. pub fn new() -> Self { Default::default() } fn dir_scan_depth(is_recursive: bool) -> usize { if is_recursive { usize::MAX } else { 1 } } } impl FileIdCache for FileIdMap { fn cached_file_id(&self, path: &Path) -> Option<&FileId> { self.paths.get(path) } fn add_path(&mut self, path: &Path, recursive_mode: RecursiveMode) { let is_recursive = recursive_mode == RecursiveMode::Recursive; for (path, file_id) in WalkDir::new(path) .follow_links(true) .max_depth(Self::dir_scan_depth(is_recursive)) .into_iter() .filter_map(|entry| { let path = entry.ok()?.into_path(); let file_id = get_file_id(&path).ok()?; Some((path, file_id)) }) { self.paths.insert(path, file_id); } } fn remove_path(&mut self, path: &Path) { self.paths.retain(|p, _| !p.starts_with(path)); } } /// An implementation of the `FileIdCache` trait that doesn't hold any data. /// /// This pseudo cache can be used to disable the file tracking using file system IDs. #[derive(Debug, Clone, Default)] pub struct NoCache; impl NoCache { /// Construct an empty cache. pub fn new() -> Self { Default::default() } } impl FileIdCache for NoCache { fn cached_file_id(&self, _path: &Path) -> Option<&FileId> { None } fn add_path(&mut self, _path: &Path, _recursive_mode: RecursiveMode) {} fn remove_path(&mut self, _path: &Path) {} } /// The recommended file ID cache implementation for the current platform #[cfg(any(target_os = "linux", target_os = "android"))] pub type RecommendedCache = NoCache; /// The recommended file ID cache implementation for the current platform #[cfg(not(any(target_os = "linux", target_os = "android")))] pub type RecommendedCache = FileIdMap; notify-debouncer-full-0.5.0/src/lib.rs000064400000000000000000000725641046102023000157630ustar 00000000000000//! A debouncer for [notify] that is optimized for ease of use. //! //! * Only emits a single `Rename` event if the rename `From` and `To` events can be matched //! * Merges multiple `Rename` events //! * Takes `Rename` events into account and updates paths for events that occurred before the rename event, but which haven't been emitted, yet //! * Optionally keeps track of the file system IDs all files and stitches rename events together (macOS FS Events, Windows) //! * Emits only one `Remove` event when deleting a directory (inotify) //! * Doesn't emit duplicate create events //! * Doesn't emit `Modify` events after a `Create` event //! //! # Installation //! //! ```toml //! [dependencies] //! notify-debouncer-full = "0.5.0" //! ``` //! //! In case you want to select specific features of notify, //! specify notify as dependency explicitly in your dependencies. //! Otherwise you can just use the re-export of notify from debouncer-full. //! //! ```toml //! notify-debouncer-full = "0.5.0" //! notify = { version = "..", features = [".."] } //! ``` //! //! # Examples //! //! ```rust,no_run //! # use std::path::Path; //! # use std::time::Duration; //! use notify_debouncer_full::{notify::*, new_debouncer, DebounceEventResult}; //! //! // Select recommended watcher for debouncer. //! // Using a callback here, could also be a channel. //! let mut debouncer = new_debouncer(Duration::from_secs(2), None, |result: DebounceEventResult| { //! match result { //! Ok(events) => events.iter().for_each(|event| println!("{event:?}")), //! Err(errors) => errors.iter().for_each(|error| println!("{error:?}")), //! } //! }).unwrap(); //! //! // Add a path to be watched. All files and directories at that path and //! // below will be monitored for changes. //! debouncer.watch(".", RecursiveMode::Recursive).unwrap(); //! ``` //! //! # Features //! //! The following crate features can be turned on or off in your cargo dependency config: //! //! - `serde` passed down to notify-types, off by default //! - `web-time` passed down to notify-types, off by default //! - `crossbeam-channel` passed down to notify, off by default //! - `macos_fsevent` passed down to notify, off by default //! - `macos_kqueue` passed down to notify, off by default //! - `serialization-compat-6` passed down to notify, off by default //! //! # Caveats //! //! As all file events are sourced from notify, the [known problems](https://docs.rs/notify/latest/notify/#known-problems) section applies here too. mod cache; mod time; #[cfg(test)] mod testing; use std::{ cmp::Reverse, collections::{BinaryHeap, HashMap, VecDeque}, path::{Path, PathBuf}, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, time::{Duration, Instant}, }; use time::now; pub use cache::{FileIdCache, FileIdMap, NoCache, RecommendedCache}; pub use file_id; pub use notify; pub use notify_types::debouncer_full::DebouncedEvent; use file_id::FileId; use notify::{ event::{ModifyKind, RemoveKind, RenameMode}, Error, ErrorKind, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher, WatcherKind, }; /// The set of requirements for watcher debounce event handling functions. /// /// # Example implementation /// /// ```rust,no_run /// # use notify::{Event, Result, EventHandler}; /// # use notify_debouncer_full::{DebounceEventHandler, DebounceEventResult}; /// /// /// Prints received events /// struct EventPrinter; /// /// impl DebounceEventHandler for EventPrinter { /// fn handle_event(&mut self, result: DebounceEventResult) { /// match result { /// Ok(events) => events.iter().for_each(|event| println!("{event:?}")), /// Err(errors) => errors.iter().for_each(|error| println!("{error:?}")), /// } /// } /// } /// ``` pub trait DebounceEventHandler: Send + 'static { /// Handles an event. fn handle_event(&mut self, event: DebounceEventResult); } impl DebounceEventHandler for F where F: FnMut(DebounceEventResult) + Send + 'static, { fn handle_event(&mut self, event: DebounceEventResult) { (self)(event); } } #[cfg(feature = "crossbeam-channel")] impl DebounceEventHandler for crossbeam_channel::Sender { fn handle_event(&mut self, event: DebounceEventResult) { let _ = self.send(event); } } impl DebounceEventHandler for std::sync::mpsc::Sender { fn handle_event(&mut self, event: DebounceEventResult) { let _ = self.send(event); } } /// A result of debounced events. /// Comes with either a vec of events or vec of errors. pub type DebounceEventResult = Result, Vec>; type DebounceData = Arc>>; #[derive(Debug, Clone, Default, PartialEq, Eq)] struct Queue { /// Events must be stored in the following order: /// 1. `remove` or `move out` event /// 2. `rename` event /// 3. Other events events: VecDeque, } impl Queue { fn was_created(&self) -> bool { self.events.front().map_or(false, |event| { matches!( event.kind, EventKind::Create(_) | EventKind::Modify(ModifyKind::Name(RenameMode::To)) ) }) } fn was_removed(&self) -> bool { self.events.front().map_or(false, |event| { matches!( event.kind, EventKind::Remove(_) | EventKind::Modify(ModifyKind::Name(RenameMode::From)) ) }) } } #[derive(Debug)] pub(crate) struct DebounceDataInner { queues: HashMap, roots: Vec<(PathBuf, RecursiveMode)>, cache: T, rename_event: Option<(DebouncedEvent, Option)>, rescan_event: Option, errors: Vec, timeout: Duration, } impl DebounceDataInner { pub(crate) fn new(cache: T, timeout: Duration) -> Self { Self { queues: HashMap::new(), roots: Vec::new(), cache, rename_event: None, rescan_event: None, errors: Vec::new(), timeout, } } /// Retrieve a vec of debounced events, removing them if not continuous pub fn debounced_events(&mut self) -> Vec { let now = now(); let mut events_expired = Vec::with_capacity(self.queues.len()); let mut queues_remaining = HashMap::with_capacity(self.queues.len()); if let Some(event) = self.rescan_event.take() { if now.saturating_duration_since(event.time) >= self.timeout { log::trace!("debounced event: {event:?}"); events_expired.push(event); } else { self.rescan_event = Some(event); } } // drain the entire queue, then process the expired events and re-add the rest // TODO: perfect fit for drain_filter https://github.com/rust-lang/rust/issues/59618 for (path, mut queue) in self.queues.drain() { let mut kind_index = HashMap::new(); while let Some(event) = queue.events.pop_front() { if now.saturating_duration_since(event.time) >= self.timeout { // remove previous event of the same kind if let Some(idx) = kind_index.get(&event.kind).copied() { events_expired.remove(idx); kind_index.values_mut().for_each(|i| { if *i > idx { *i -= 1 } }) } kind_index.insert(event.kind, events_expired.len()); events_expired.push(event); } else { queue.events.push_front(event); break; } } if !queue.events.is_empty() { queues_remaining.insert(path, queue); } } self.queues = queues_remaining; sort_events(events_expired) } /// Returns all currently stored errors pub fn errors(&mut self) -> Vec { std::mem::take(&mut self.errors) } /// Add an error entry to re-send later on pub fn add_error(&mut self, error: Error) { log::trace!("raw error: {error:?}"); self.errors.push(error); } /// Add new event to debouncer cache pub fn add_event(&mut self, event: Event) { log::trace!("raw event: {event:?}"); if event.need_rescan() { self.cache.rescan(&self.roots); self.rescan_event = Some(DebouncedEvent { event, time: now() }); return; } let path = &event.paths[0]; match &event.kind { EventKind::Create(_) => { let recursive_mode = self.recursive_mode(path); self.cache.add_path(path, recursive_mode); self.push_event(event, now()); } EventKind::Modify(ModifyKind::Name(rename_mode)) => { match rename_mode { RenameMode::Any => { if event.paths[0].exists() { self.handle_rename_to(event); } else { self.handle_rename_from(event); } } RenameMode::To => { self.handle_rename_to(event); } RenameMode::From => { self.handle_rename_from(event); } RenameMode::Both => { // ignore and handle `To` and `From` events instead } RenameMode::Other => { // unused } } } EventKind::Remove(_) => { self.push_remove_event(event, now()); } EventKind::Other => { // ignore meta events } _ => { if self.cache.cached_file_id(path).is_none() { let recursive_mode = self.recursive_mode(path); self.cache.add_path(path, recursive_mode); } self.push_event(event, now()); } } } fn recursive_mode(&mut self, path: &Path) -> RecursiveMode { self.roots .iter() .find_map(|(root, recursive_mode)| { if path.starts_with(root) { Some(*recursive_mode) } else { None } }) .unwrap_or(RecursiveMode::NonRecursive) } fn handle_rename_from(&mut self, event: Event) { let time = now(); let path = &event.paths[0]; // store event let file_id = self.cache.cached_file_id(path).cloned(); self.rename_event = Some((DebouncedEvent::new(event.clone(), time), file_id)); self.cache.remove_path(path); self.push_event(event, time); } fn handle_rename_to(&mut self, event: Event) { let recursive_mode = self.recursive_mode(&event.paths[0]); self.cache.add_path(&event.paths[0], recursive_mode); let trackers_match = self .rename_event .as_ref() .and_then(|(e, _)| e.tracker()) .and_then(|from_tracker| { event .attrs .tracker() .map(|to_tracker| from_tracker == to_tracker) }) .unwrap_or_default(); let file_ids_match = self .rename_event .as_ref() .and_then(|(_, id)| id.as_ref()) .and_then(|from_file_id| { self.cache .cached_file_id(&event.paths[0]) .map(|to_file_id| from_file_id == to_file_id) }) .unwrap_or_default(); if trackers_match || file_ids_match { // connect rename let (mut rename_event, _) = self.rename_event.take().unwrap(); // unwrap is safe because `rename_event` must be set at this point let path = rename_event.paths.remove(0); let time = rename_event.time; self.push_rename_event(path, event, time); } else { // move in self.push_event(event, now()); } self.rename_event = None; } fn push_rename_event(&mut self, path: PathBuf, event: Event, time: Instant) { self.cache.remove_path(&path); let mut source_queue = self.queues.remove(&path).unwrap_or_default(); // remove rename `from` event source_queue.events.pop_back(); // remove existing rename event let (remove_index, original_path, original_time) = source_queue .events .iter() .enumerate() .find_map(|(index, e)| { if matches!( e.kind, EventKind::Modify(ModifyKind::Name(RenameMode::Both)) ) { Some((Some(index), e.paths[0].clone(), e.time)) } else { None } }) .unwrap_or((None, path, time)); if let Some(remove_index) = remove_index { source_queue.events.remove(remove_index); } // split off remove or move out event and add it back to the events map if source_queue.was_removed() { let event = source_queue.events.pop_front().unwrap(); self.queues.insert( event.paths[0].clone(), Queue { events: [event].into(), }, ); } // update paths for e in &mut source_queue.events { e.paths = vec![event.paths[0].clone()]; } // insert rename event at the front, unless the file was just created if !source_queue.was_created() { source_queue.events.push_front(DebouncedEvent { event: Event { kind: EventKind::Modify(ModifyKind::Name(RenameMode::Both)), paths: vec![original_path, event.paths[0].clone()], attrs: event.attrs, }, time: original_time, }); } if let Some(target_queue) = self.queues.get_mut(&event.paths[0]) { if !target_queue.was_created() { let mut remove_event = DebouncedEvent { event: Event { kind: EventKind::Remove(RemoveKind::Any), paths: vec![event.paths[0].clone()], attrs: Default::default(), }, time: original_time, }; if !target_queue.was_removed() { remove_event.event = remove_event.event.set_info("override"); } source_queue.events.push_front(remove_event); } *target_queue = source_queue; } else { self.queues.insert(event.paths[0].clone(), source_queue); } } fn push_remove_event(&mut self, event: Event, time: Instant) { let path = &event.paths[0]; // remove child queues self.queues.retain(|p, _| !p.starts_with(path) || p == path); // remove cached file ids self.cache.remove_path(path); match self.queues.get_mut(path) { Some(queue) if queue.was_created() => { self.queues.remove(path); } Some(queue) => { queue.events = [DebouncedEvent::new(event, time)].into(); } None => { self.push_event(event, time); } } } fn push_event(&mut self, event: Event, time: Instant) { let path = &event.paths[0]; if let Some(queue) = self.queues.get_mut(path) { // skip duplicate create events and modifications right after creation if match event.kind { EventKind::Modify(ModifyKind::Data(_) | ModifyKind::Metadata(_)) | EventKind::Create(_) => !queue.was_created(), _ => true, } { queue.events.push_back(DebouncedEvent::new(event, time)); } } else { self.queues.insert( path.to_path_buf(), Queue { events: [DebouncedEvent::new(event, time)].into(), }, ); } } } /// Debouncer guard, stops the debouncer on drop. #[derive(Debug)] pub struct Debouncer { watcher: T, debouncer_thread: Option>, data: DebounceData, stop: Arc, } impl Debouncer { /// Stop the debouncer, waits for the event thread to finish. /// May block for the duration of one `tick_rate`. pub fn stop(mut self) { self.set_stop(); if let Some(t) = self.debouncer_thread.take() { let _ = t.join(); } } /// Stop the debouncer, does not wait for the event thread to finish. pub fn stop_nonblocking(self) { self.set_stop(); } fn set_stop(&self) { self.stop.store(true, Ordering::Relaxed); } #[deprecated = "`Debouncer` provides all methods from `Watcher` itself now. Remove `.watcher()` and use those methods directly."] pub fn watcher(&mut self) {} #[deprecated = "`Debouncer` now manages root paths automatically. Remove all calls to `add_root` and `remove_root`."] pub fn cache(&mut self) {} fn add_root(&mut self, path: impl Into, recursive_mode: RecursiveMode) { let path = path.into(); let mut data = self.data.lock().unwrap(); // skip, if the root has already been added if data.roots.iter().any(|(p, _)| p == &path) { return; } data.roots.push((path.clone(), recursive_mode)); data.cache.add_path(&path, recursive_mode); } fn remove_root(&mut self, path: impl AsRef) { let mut data = self.data.lock().unwrap(); data.roots.retain(|(root, _)| !root.starts_with(&path)); data.cache.remove_path(path.as_ref()); } pub fn watch( &mut self, path: impl AsRef, recursive_mode: RecursiveMode, ) -> notify::Result<()> { self.watcher.watch(path.as_ref(), recursive_mode)?; self.add_root(path.as_ref(), recursive_mode); Ok(()) } pub fn unwatch(&mut self, path: impl AsRef) -> notify::Result<()> { self.watcher.unwatch(path.as_ref())?; self.remove_root(path); Ok(()) } pub fn configure(&mut self, option: notify::Config) -> notify::Result { self.watcher.configure(option) } pub fn kind() -> WatcherKind where Self: Sized, { T::kind() } } impl Drop for Debouncer { fn drop(&mut self) { self.set_stop(); } } /// Creates a new debounced watcher with custom configuration. /// /// Timeout is the amount of time after which a debounced event is emitted. /// /// If `tick_rate` is `None`, notify will select a tick rate that is 1/4 of the provided timeout. pub fn new_debouncer_opt( timeout: Duration, tick_rate: Option, mut event_handler: F, file_id_cache: C, config: notify::Config, ) -> Result, Error> { let data = Arc::new(Mutex::new(DebounceDataInner::new(file_id_cache, timeout))); let stop = Arc::new(AtomicBool::new(false)); let tick_div = 4; let tick = match tick_rate { Some(v) => { if v > timeout { return Err(Error::new(ErrorKind::Generic(format!( "Invalid tick_rate, tick rate {:?} > {:?} timeout!", v, timeout )))); } v } None => timeout.checked_div(tick_div).ok_or_else(|| { Error::new(ErrorKind::Generic(format!( "Failed to calculate tick as {:?}/{}!", timeout, tick_div ))) })?, }; let data_c = data.clone(); let stop_c = stop.clone(); let thread = std::thread::Builder::new() .name("notify-rs debouncer loop".to_string()) .spawn(move || loop { if stop_c.load(Ordering::Acquire) { break; } std::thread::sleep(tick); let send_data; let errors; { let mut lock = data_c.lock().unwrap(); send_data = lock.debounced_events(); errors = lock.errors(); } if !send_data.is_empty() { event_handler.handle_event(Ok(send_data)); } if !errors.is_empty() { event_handler.handle_event(Err(errors)); } })?; let data_c = data.clone(); let watcher = T::new( move |e: Result| { let mut lock = data_c.lock().unwrap(); match e { Ok(e) => lock.add_event(e), // can't have multiple TX, so we need to pipe that through our debouncer Err(e) => lock.add_error(e), } }, config, )?; let guard = Debouncer { watcher, debouncer_thread: Some(thread), data, stop, }; Ok(guard) } /// Short function to create a new debounced watcher with the recommended debouncer and the built-in file ID cache. /// /// Timeout is the amount of time after which a debounced event is emitted. /// /// If `tick_rate` is `None`, notify will select a tick rate that is 1/4 of the provided timeout. pub fn new_debouncer( timeout: Duration, tick_rate: Option, event_handler: F, ) -> Result, Error> { new_debouncer_opt::( timeout, tick_rate, event_handler, RecommendedCache::new(), notify::Config::default(), ) } fn sort_events(events: Vec) -> Vec { let mut sorted = Vec::with_capacity(events.len()); // group events by path let mut events_by_path: HashMap<_, VecDeque<_>> = events.into_iter().fold(HashMap::new(), |mut acc, event| { acc.entry(event.paths.last().cloned().unwrap_or_default()) .or_default() .push_back(event); acc }); // push events for different paths in chronological order and keep the order of events with the same path let mut min_time_heap = events_by_path .iter() .map(|(path, events)| Reverse((events[0].time, path.clone()))) .collect::>(); while let Some(Reverse((min_time, path))) = min_time_heap.pop() { // unwrap is safe because only paths from `events_by_path` are added to `min_time_heap` // and they are never removed from `events_by_path`. let events = events_by_path.get_mut(&path).unwrap(); let mut push_next = false; while events.front().is_some_and(|event| event.time <= min_time) { // unwrap is safe because `pop_front` mus return some in order to enter the loop let event = events.pop_front().unwrap(); sorted.push(event); push_next = true; } if push_next { if let Some(event) = events.front() { min_time_heap.push(Reverse((event.time, path))); } } } sorted } #[cfg(test)] mod tests { use std::{fs, path::Path}; use super::*; use pretty_assertions::assert_eq; use rstest::rstest; use tempfile::tempdir; use testing::TestCase; use time::MockTime; #[rstest] fn state( #[values( "add_create_event", "add_create_event_after_remove_event", "add_create_dir_event_twice", "add_modify_content_event_after_create_event", "add_rename_from_event", "add_rename_from_event_after_create_event", "add_rename_from_event_after_modify_event", "add_rename_from_event_after_create_and_modify_event", "add_rename_from_event_after_rename_from_event", "add_rename_to_event", "add_rename_to_dir_event", "add_rename_from_and_to_event", "add_rename_from_and_to_event_after_create", "add_rename_from_and_to_event_after_rename", "add_rename_from_and_to_event_after_modify_content", "add_rename_from_and_to_event_override_created", "add_rename_from_and_to_event_override_modified", "add_rename_from_and_to_event_override_removed", "add_rename_from_and_to_event_with_file_ids", "add_rename_from_and_to_event_with_different_file_ids", "add_rename_from_and_to_event_with_different_tracker", "add_rename_both_event", "add_remove_event", "add_remove_event_after_create_event", "add_remove_event_after_modify_event", "add_remove_event_after_create_and_modify_event", "add_remove_parent_event_after_remove_child_event", "add_errors", "emit_continuous_modify_content_events", "emit_events_in_chronological_order", "emit_events_with_a_prepended_rename_event", "emit_close_events_only_once", "emit_modify_event_after_close_event", "emit_needs_rescan_event", "read_file_id_without_create_event", "sort_events_chronologically", "sort_events_with_reordering" )] file_name: &str, ) { let file_content = fs::read_to_string(Path::new(&format!("./test_cases/{file_name}.hjson"))).unwrap(); let mut test_case = deser_hjson::from_str::(&file_content).unwrap(); let time = now(); MockTime::set_time(time); let mut state = test_case.state.into_debounce_data_inner(time); state.roots = vec![(PathBuf::from("/"), RecursiveMode::Recursive)]; let mut prev_event_time = Duration::default(); for event in test_case.events { let event_time = Duration::from_millis(event.time); let event = event.into_debounced_event(time, None); MockTime::advance(event_time - prev_event_time); prev_event_time = event_time; state.add_event(event.event); } for error in test_case.errors { let error = error.into_notify_error(); state.add_error(error); } let expected_errors = std::mem::take(&mut test_case.expected.errors); let expected_events = std::mem::take(&mut test_case.expected.events); let expected_state = test_case.expected.into_debounce_data_inner(time); assert_eq!( state.queues, expected_state.queues, "queues not as expected" ); assert_eq!( state.rename_event, expected_state.rename_event, "rename event not as expected" ); assert_eq!( state.rescan_event, expected_state.rescan_event, "rescan event not as expected" ); assert_eq!( state.cache.paths, expected_state.cache.paths, "cache not as expected" ); assert_eq!( state .errors .iter() .map(|e| format!("{:?}", e)) .collect::>(), expected_errors .iter() .map(|e| format!("{:?}", e.clone().into_notify_error())) .collect::>(), "errors not as expected" ); let backup_time = now(); let backup_queues = state.queues.clone(); for (delay, events) in expected_events { MockTime::set_time(backup_time); state.queues = backup_queues.clone(); match delay.as_str() { "none" => {} "short" => MockTime::advance(Duration::from_millis(10)), "long" => MockTime::advance(Duration::from_millis(100)), _ => { if let Ok(ts) = delay.parse::() { MockTime::set_time(time + Duration::from_millis(ts)); } } } let events = events .into_iter() .map(|event| event.into_debounced_event(time, None)) .collect::>(); assert_eq!( state.debounced_events(), events, "debounced events after a `{delay}` delay" ); } } #[test] fn integration() -> Result<(), Box> { let dir = tempdir()?; let (tx, rx) = std::sync::mpsc::channel(); let mut debouncer = new_debouncer(Duration::from_millis(10), None, tx)?; debouncer.watch(dir.path(), RecursiveMode::Recursive)?; fs::write(dir.path().join("file.txt"), b"Lorem ipsum")?; let events = rx .recv_timeout(Duration::from_secs(10)) .expect("no events received") .expect("received an error"); assert!(!events.is_empty(), "received empty event list"); Ok(()) } } notify-debouncer-full-0.5.0/src/testing.rs000064400000000000000000000250161046102023000166600ustar 00000000000000use std::{ collections::{HashMap, VecDeque}, path::{Path, PathBuf}, time::{Duration, Instant}, }; use file_id::FileId; use notify::{ event::{ AccessKind, AccessMode, CreateKind, DataChange, Flag, MetadataKind, ModifyKind, RemoveKind, RenameMode, }, Error, ErrorKind, Event, EventKind, RecursiveMode, }; use crate::{DebounceDataInner, DebouncedEvent, FileIdCache, Queue}; pub(crate) use schema::TestCase; mod schema { use std::collections::HashMap; use serde::Deserialize; #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub(crate) struct Error { /// The error kind is parsed by `into_notify_error` pub kind: String, /// The error paths #[serde(default)] pub paths: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub(crate) struct Event { /// The timestamp the event occurred #[serde(default)] pub time: u64, /// The event kind is parsed by `into_notify_event` pub kind: String, /// The event paths #[serde(default)] pub paths: Vec, /// The event flags #[serde(default)] pub flags: Vec, /// The event tracker pub tracker: Option, /// The event info pub info: Option, /// The file id for the file associated with the event /// /// Only used for the rename event. pub file_id: Option, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub(crate) struct Queue { pub events: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub(crate) struct State { /// Timeout for the debouncer /// /// Only used for the initial state. pub timeout: Option, /// The event queues for each file #[serde(default)] pub queues: HashMap, /// Cached file ids #[serde(default)] pub cache: HashMap, /// A map of file ids, used instead of accessing the file system #[serde(default)] pub file_system: HashMap, /// Current rename event pub rename_event: Option, /// Current rescan event pub rescan_event: Option, /// Debounced events /// /// Only used for the expected state. #[serde(default)] pub events: HashMap>, /// Errors #[serde(default)] pub errors: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub(crate) struct TestCase { /// Initial state pub state: State, /// Events that are added during the test #[serde(default)] pub events: Vec, /// Errors that are added during the test #[serde(default)] pub errors: Vec, /// Expected state after the test pub expected: State, } } impl schema::Error { pub fn into_notify_error(self) -> Error { let kind = match &*self.kind { "path-not-found" => ErrorKind::PathNotFound, "watch-not-found" => ErrorKind::WatchNotFound, "max-files-watch" => ErrorKind::MaxFilesWatch, _ => panic!("unknown error type `{}`", self.kind), }; let mut error = Error::new(kind); for p in self.paths { error = error.add_path(PathBuf::from(p)); } error } } impl schema::Event { #[rustfmt::skip] pub fn into_debounced_event(self, time: Instant, path: Option<&str>) -> DebouncedEvent { let kind = match &*self.kind { "any" => EventKind::Any, "other" => EventKind::Other, "access-any" => EventKind::Access(AccessKind::Any), "access-read" => EventKind::Access(AccessKind::Read), "access-open-any" => EventKind::Access(AccessKind::Open(AccessMode::Any)), "access-open-execute" => EventKind::Access(AccessKind::Open(AccessMode::Execute)), "access-open-read" => EventKind::Access(AccessKind::Open(AccessMode::Read)), "access-open-write" => EventKind::Access(AccessKind::Open(AccessMode::Write)), "access-open-other" => EventKind::Access(AccessKind::Open(AccessMode::Other)), "access-close-any" => EventKind::Access(AccessKind::Close(AccessMode::Any)), "access-close-execute" => EventKind::Access(AccessKind::Close(AccessMode::Execute)), "access-close-read" => EventKind::Access(AccessKind::Close(AccessMode::Read)), "access-close-write" => EventKind::Access(AccessKind::Close(AccessMode::Write)), "access-close-other" => EventKind::Access(AccessKind::Close(AccessMode::Other)), "access-other" => EventKind::Access(AccessKind::Other), "create-any" => EventKind::Create(CreateKind::Any), "create-file" => EventKind::Create(CreateKind::File), "create-folder" => EventKind::Create(CreateKind::Folder), "create-other" => EventKind::Create(CreateKind::Other), "modify-any" => EventKind::Modify(ModifyKind::Any), "modify-other" => EventKind::Modify(ModifyKind::Other), "modify-data-any" => EventKind::Modify(ModifyKind::Data(DataChange::Any)), "modify-data-size" => EventKind::Modify(ModifyKind::Data(DataChange::Size)), "modify-data-content" => EventKind::Modify(ModifyKind::Data(DataChange::Content)), "modify-data-other" => EventKind::Modify(ModifyKind::Data(DataChange::Other)), "modify-metadata-any" => EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)), "modify-metadata-access-time" => EventKind::Modify(ModifyKind::Metadata(MetadataKind::AccessTime)), "modify-metadata-write-time" => EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)), "modify-metadata-permissions" => EventKind::Modify(ModifyKind::Metadata(MetadataKind::Permissions)), "modify-metadata-ownership" => EventKind::Modify(ModifyKind::Metadata(MetadataKind::Ownership)), "modify-metadata-extended" => EventKind::Modify(ModifyKind::Metadata(MetadataKind::Extended)), "modify-metadata-other" => EventKind::Modify(ModifyKind::Metadata(MetadataKind::Other)), "rename-any" => EventKind::Modify(ModifyKind::Name(RenameMode::Any)), "rename-from" => EventKind::Modify(ModifyKind::Name(RenameMode::From)), "rename-to" => EventKind::Modify(ModifyKind::Name(RenameMode::To)), "rename-both" => EventKind::Modify(ModifyKind::Name(RenameMode::Both)), "rename-other" => EventKind::Modify(ModifyKind::Name(RenameMode::Other)), "remove-any" => EventKind::Remove(RemoveKind::Any), "remove-file" => EventKind::Remove(RemoveKind::File), "remove-folder" => EventKind::Remove(RemoveKind::Folder), "remove-other" => EventKind::Remove(RemoveKind::Other), _ => panic!("unknown event type `{}`", self.kind), }; let mut event = Event::new(kind); for p in self.paths { event = event.add_path(if p == "*" { PathBuf::from(path.expect("cannot replace `*`")) } else { PathBuf::from(p) }); if let Some(tracker) = self.tracker { event = event.set_tracker(tracker); } if let Some(info) = &self.info { event = event.set_info(info.as_str()); } } for f in self.flags { let flag = match &*f { "rescan" => Flag::Rescan, _ => panic!("unknown event flag `{f}`"), }; event = event.set_flag(flag); } DebouncedEvent { event, time: time + Duration::from_millis(self.time) } } } impl schema::State { pub(crate) fn into_debounce_data_inner(self, time: Instant) -> DebounceDataInner { let queues = self .queues .into_iter() .map(|(path, queue)| { let queue = Queue { events: queue .events .into_iter() .map(|event| event.into_debounced_event(time, Some(&path))) .collect::>(), }; (path.into(), queue) }) .collect(); let cache = self .cache .into_iter() .map(|(path, id)| { let path = PathBuf::from(path); let id = FileId::new_inode(id, id); (path, id) }) .collect::>(); let file_system = self .file_system .into_iter() .map(|(path, id)| { let path = PathBuf::from(path); let id = FileId::new_inode(id, id); (path, id) }) .collect::>(); let cache = TestCache::new(cache, file_system); let rename_event = self.rename_event.map(|e| { let file_id = e.file_id.map(|id| FileId::new_inode(id, id)); let event = e.into_debounced_event(time, None); (event, file_id) }); let rescan_event = self .rescan_event .map(|e| e.into_debounced_event(time, None)); DebounceDataInner { queues, roots: Vec::new(), cache, rename_event, rescan_event, errors: Vec::new(), timeout: Duration::from_millis(self.timeout.unwrap_or(50)), } } } #[derive(Debug, Clone)] pub struct TestCache { pub paths: HashMap, pub file_system: HashMap, } impl TestCache { pub fn new(paths: HashMap, file_system: HashMap) -> Self { Self { paths, file_system } } } impl FileIdCache for TestCache { fn cached_file_id(&self, path: &Path) -> Option<&FileId> { self.paths.get(path) } fn add_path(&mut self, path: &Path, recursive_mode: RecursiveMode) { for (file_path, file_id) in &self.file_system { if file_path == path || (file_path.starts_with(path) && recursive_mode == RecursiveMode::Recursive) { self.paths.insert(file_path.clone(), *file_id); } } } fn remove_path(&mut self, path: &Path) { self.paths.remove(path); } } notify-debouncer-full-0.5.0/src/time.rs000064400000000000000000000016121046102023000161350ustar 00000000000000#[cfg(not(test))] pub use build::*; #[cfg(not(test))] mod build { use std::time::Instant; pub fn now() -> Instant { Instant::now() } } #[cfg(test)] pub use test::*; #[cfg(test)] mod test { use std::{ sync::Mutex, time::{Duration, Instant}, }; thread_local! { static NOW: Mutex> = const { Mutex::new(None) }; } pub fn now() -> Instant { let time = NOW.with(|now| *now.lock().unwrap()); time.unwrap_or_else(Instant::now) } pub struct MockTime; impl MockTime { pub fn set_time(time: Instant) { NOW.with(|now| *now.lock().unwrap() = Some(time)); } pub fn advance(delta: Duration) { NOW.with(|now| { if let Some(n) = &mut *now.lock().unwrap() { *n += delta; } }); } } } notify-debouncer-full-0.5.0/test_cases/add_create_dir_event_twice.hjson000064400000000000000000000011731046102023000245510ustar 00000000000000// https://github.com/spacedriveapp/spacedrive/blob/90a350946914be7f91ba692887ca03db659d530a/core/src/location/manager/watcher/macos.rs // // This is a MacOS specific event that happens when a folder is created trough Finder. // It creates a folder but 2 events are triggered in FSEvents. { state: {} events: [ { kind: "create-folder", paths: ["/watch/dir"] } { kind: "create-folder", paths: ["/watch/dir"] } ] expected: { queues: { /watch/dir: { events: [ { kind: "create-folder", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_create_event.hjson000064400000000000000000000010741046102023000225200ustar 00000000000000{ state: { file_system: { /watch/file: 1 } } events: [ { kind: "create-any", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } ] } } cache: { /watch/file: 1 } events: { none: [] short: [] long: [ { kind: "create-any", paths: ["/watch/file"] } ] } } } notify-debouncer-full-0.5.0/test_cases/add_create_event_after_remove_event.hjson000064400000000000000000000010051046102023000264510ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "remove-any", paths: ["*"] } ] } } } events: [ { kind: "create-any", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "remove-any", paths: ["*"] } { kind: "create-any", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_errors.hjson000064400000000000000000000004361046102023000213710ustar 00000000000000{ state: {} errors: [ { kind: "max-files-watch" } { kind: "path-not-found", paths: ["/watch/file"] } ] expected: { errors: [ { kind: "max-files-watch" } { kind: "path-not-found", paths: ["/watch/file"] } ] } } notify-debouncer-full-0.5.0/test_cases/add_modify_content_event_after_create_event.hjson000064400000000000000000000012661046102023000302060ustar 00000000000000// https://github.com/spacedriveapp/spacedrive/blob/90a350946914be7f91ba692887ca03db659d530a/core/src/location/manager/watcher/macos.rs // MacOS emits a Create File and then an Update Content event when a file is created. { state: { queues: { /watch/file: { events: [ { kind: "create-file", paths: ["*"] } ] } } } events: [ { kind: "modify-data-content", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "create-file", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_remove_event.hjson000064400000000000000000000004351046102023000225520ustar 00000000000000{ state: {} events: [ { kind: "remove-any", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "remove-any", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_remove_event_after_create_and_modify_event.hjson000064400000000000000000000005331046102023000306470ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } { kind: "modify-data-any", paths: ["*"] } ] } } } events: [ { kind: "remove-any", paths: ["/watch/file"] } ] expected: {} } notify-debouncer-full-0.5.0/test_cases/add_remove_event_after_create_event.hjson000064400000000000000000000004351046102023000264570ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } ] } } } events: [ { kind: "remove-any", paths: ["/watch/file"] } ] expected: {} } notify-debouncer-full-0.5.0/test_cases/add_remove_event_after_modify_event.hjson000064400000000000000000000007211046102023000265010ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "modify-data-any", paths: ["*"] } ] } } } events: [ { kind: "remove-any", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "remove-any", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_remove_parent_event_after_remove_child_event.hjson000064400000000000000000000010071046102023000312210ustar 00000000000000{ state: { cache: { /watch: 1 /watch/parent: 2 /watch/parent/child: 3 } } events: [ { kind: "remove-any", paths: ["/watch/parent/child"] } { kind: "remove-any", paths: ["/watch/parent"] } ] expected: { queues: { /watch/parent: { events: [ { kind: "remove-any", paths: ["*"] } ] } } cache: { /watch: 1 } } } notify-debouncer-full-0.5.0/test_cases/add_rename_both_event.hjson000064400000000000000000000002021046102023000235300ustar 00000000000000{ state: {} events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"] } ] expected: {} } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event.hjson000064400000000000000000000006341046102023000250740ustar 00000000000000{ state: {} events: [ { kind: "rename-from", paths: ["/watch/source"], tracker: 1 } { kind: "rename-to", paths: ["/watch/target"], tracker: 1 } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1 } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_after_create.hjson000064400000000000000000000010431046102023000275730ustar 00000000000000{ state: { queues: { /watch/source: { events: [ { kind: "create-any", paths: ["*"] } ] } } } events: [ { kind: "rename-from", paths: ["/watch/source"], tracker: 1 } { kind: "rename-to", paths: ["/watch/target"], tracker: 1 } ] expected: { queues: { /watch/target: { events: [ { kind: "create-any", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_after_modify_content.hjson000064400000000000000000000012301046102023000313470ustar 00000000000000{ state: { queues: { /watch/source: { events: [ { kind: "modify-data-content", paths: ["*"] } ] } } } events: [ { kind: "rename-from", paths: ["/watch/source"], tracker: 1 } { kind: "rename-to", paths: ["/watch/target"], tracker: 1 } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1 } { kind: "modify-data-content", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_after_rename.hjson000064400000000000000000000012251046102023000276010ustar 00000000000000{ state: { queues: { /watch/temp: { events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/temp"], tracker: 1, time: 1 } ] } } } events: [ { kind: "rename-from", paths: ["/watch/temp"], tracker: 2, time: 2 } { kind: "rename-to", paths: ["/watch/target"], tracker: 2, time: 3 } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 2, time: 1 } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_override_created.hjson000064400000000000000000000011151046102023000304550ustar 00000000000000{ state: { queues: { /watch/target: { events: [ { kind: "create-any", paths: ["*"] } ] } } } events: [ { kind: "rename-from", paths: ["/watch/source"], tracker: 1 } { kind: "rename-to", paths: ["/watch/target"], tracker: 1 } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1 } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_override_modified.hjson000064400000000000000000000015501046102023000306310ustar 00000000000000{ state: { queues: { /watch/target: { events: [ { kind: "modify-data-any", paths: ["*"] } ] } } cache: { /watch/target: 1 /watch/source: 2 } file_system: { /watch/target: 2 } } events: [ { kind: "rename-from", paths: ["/watch/source"], tracker: 1 } { kind: "rename-to", paths: ["/watch/target"], tracker: 1 } ] expected: { queues: { /watch/target: { events: [ { kind: "remove-any", paths: ["*"], info: "override" } { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1 } ] } } cache: { /watch/target: 2 } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_override_removed.hjson000064400000000000000000000012061046102023000305100ustar 00000000000000{ state: { queues: { /watch/target: { events: [ { kind: "remove-any", paths: ["*"] } ] } } } events: [ { kind: "rename-from", paths: ["/watch/source"], tracker: 1 } { kind: "rename-to", paths: ["/watch/target"], tracker: 1 } ] expected: { queues: { /watch/target: { events: [ { kind: "remove-any", paths: ["*"] } { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1 } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_with_different_file_ids.hjson000064400000000000000000000012351046102023000320110ustar 00000000000000{ state: { cache: { /watch/source: 1 } file_system: { /watch/target: 2 } } events: [ { kind: "rename-from", paths: ["/watch/source"] } { kind: "rename-to", paths: ["/watch/target"] } ] expected: { queues: { /watch/source: { events: [ { kind: "rename-from", paths: ["*"] } ] } /watch/target: { events: [ { kind: "rename-to", paths: ["*"] } ] } } cache: { /watch/target: 2 } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_with_different_tracker.hjson000064400000000000000000000010321046102023000316610ustar 00000000000000{ state: {} events: [ { kind: "rename-from", paths: ["/watch/source"], tracker: 1 } { kind: "rename-to", paths: ["/watch/target"], tracker: 2 } ] expected: { queues: { /watch/source: { events: [ { kind: "rename-from", paths: ["*"], tracker: 1 } ] } /watch/target: { events: [ { kind: "rename-to", paths: ["*"], tracker: 2 } ] } } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_and_to_event_with_file_ids.hjson000064400000000000000000000010531046102023000277610ustar 00000000000000{ state: { cache: { /watch/source: 1 } file_system: { /watch/target: 1 } } events: [ { kind: "rename-from", paths: ["/watch/source"] } { kind: "rename-to", paths: ["/watch/target"] } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"] } ] } } cache: { /watch/target: 1 } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_event.hjson000064400000000000000000000005531046102023000235500ustar 00000000000000{ state: {} events: [ { kind: "rename-from", paths: ["/watch/source"] } ] expected: { queues: { /watch/source: { events: [ { kind: "rename-from", paths: ["*"] } ] } } rename_event: { kind: "rename-from", paths: ["/watch/source"] } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_event_after_create_and_modify_event.hjson000064400000000000000000000013111046102023000316370ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } { kind: "modify-data-any", paths: ["*"] } ] } } } events: [ { kind: "rename-from", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } { kind: "modify-data-any", paths: ["*"] } { kind: "rename-from", paths: ["*"] } ] } } rename_event: { kind: "rename-from", paths: ["/watch/file"] } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_event_after_create_event.hjson000064400000000000000000000011151046102023000274500ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } ] } } } events: [ { kind: "rename-from", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } { kind: "rename-from", paths: ["*"] } ] } } rename_event: { kind: "rename-from", paths: ["/watch/file"] } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_event_after_modify_event.hjson000064400000000000000000000011271046102023000274770ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "modify-data-any", paths: ["*"] } ] } } } events: [ { kind: "rename-from", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "modify-data-any", paths: ["*"] } { kind: "rename-from", paths: ["*"] } ] } } rename_event: { kind: "rename-from", paths: ["/watch/file"] } } } notify-debouncer-full-0.5.0/test_cases/add_rename_from_event_after_rename_from_event.hjson000064400000000000000000000013661046102023000305070ustar 00000000000000{ state: { queues: { /watch/file-a: { events: [ { kind: "rename-from", paths: ["*"] } ] } } rename_event: { kind: "rename-from", paths: ["/watch/file-a"] } } events: [ { kind: "rename-from", paths: ["/watch/file-b"] } ] expected: { queues: { /watch/file-a: { events: [ { kind: "rename-from", paths: ["*"] } ] } /watch/file-b: { events: [ { kind: "rename-from", paths: ["*"] } ] } } rename_event: { kind: "rename-from", paths: ["/watch/file-b"] } } } notify-debouncer-full-0.5.0/test_cases/add_rename_to_dir_event.hjson000064400000000000000000000007401046102023000240630ustar 00000000000000{ state: { file_system: { /watch/parent: 1 /watch/parent/child: 2 } } events: [ { kind: "rename-to", paths: ["/watch/parent"] } ] expected: { queues: { /watch/parent: { events: [ { kind: "rename-to", paths: ["*"] } ] } } cache: { /watch/parent: 1 /watch/parent/child: 2 } } } notify-debouncer-full-0.5.0/test_cases/add_rename_to_event.hjson000064400000000000000000000004371046102023000232300ustar 00000000000000{ state: {} events: [ { kind: "rename-to", paths: ["/watch/target"] } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-to", paths: ["*"] } ] } } } } notify-debouncer-full-0.5.0/test_cases/emit_close_events_only_once.hjson000064400000000000000000000017321046102023000250210ustar 00000000000000{ state: {} events: [ { kind: "modify-data-any", paths: ["/watch/file"], time: 1 } { kind: "access-close-write", paths: ["/watch/file"], time: 2 } { kind: "modify-data-any", paths: ["/watch/file"], time: 3 } { kind: "access-close-write", paths: ["/watch/file"], time: 4 } ] expected: { queues: { /watch/file: { events: [ { kind: "modify-data-any", paths: ["*"], time: 1 } { kind: "access-close-write", paths: ["*"], time: 2 } { kind: "modify-data-any", paths: ["*"], time: 3 } { kind: "access-close-write", paths: ["*"], time: 4 } ] } } events: { short: [] long: [ { kind: "modify-data-any", paths: ["/watch/file"], time: 3 } { kind: "access-close-write", paths: ["/watch/file"], time: 4 } ] } } } notify-debouncer-full-0.5.0/test_cases/emit_continuous_modify_content_events.hjson000064400000000000000000000030151046102023000271520ustar 00000000000000{ state: { timeout: 5 } events: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 1 } { kind: "modify-data-content", paths: ["/watch/file"], time: 2 } { kind: "modify-data-content", paths: ["/watch/file"], time: 3 } ] expected: { queues: { /watch/file: { events: [ { kind: "modify-data-content", paths: ["*"], time: 1 } { kind: "modify-data-content", paths: ["*"], time: 2 } { kind: "modify-data-content", paths: ["*"], time: 3 } ] } } events: { 1: [] 2: [] 3: [] 4: [] 5: [] 6: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 1 } ] 7: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 2 } ] 8: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 3 } ] 9: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 3 } ] 10: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 3 } ] 100: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 3 } ] 1000: [ { kind: "modify-data-content", paths: ["/watch/file"], time: 3 } ] } } } notify-debouncer-full-0.5.0/test_cases/emit_events_in_chronological_order.hjson000064400000000000000000000035501046102023000263530ustar 00000000000000{ state: { timeout: 5 } events: [ { kind: "modify-data-content", paths: ["/watch/file-a"], time: 1 } { kind: "modify-data-content", paths: ["/watch/file-b"], time: 3 } { kind: "modify-data-content", paths: ["/watch/file-c"], time: 4 } { kind: "modify-metadata-write-time", paths: ["/watch/file-b"], time: 7 } { kind: "modify-metadata-write-time", paths: ["/watch/file-c"], time: 8 } { kind: "modify-metadata-write-time", paths: ["/watch/file-a"], time: 9 } ] expected: { queues: { /watch/file-a: { events: [ { kind: "modify-data-content", paths: ["*"], time: 1 } { kind: "modify-metadata-write-time", paths: ["*"], time: 9 } ] } /watch/file-b: { events: [ { kind: "modify-data-content", paths: ["*"], time: 3 } { kind: "modify-metadata-write-time", paths: ["*"], time: 7 } ] } /watch/file-c: { events: [ { kind: "modify-data-content", paths: ["*"], time: 4 } { kind: "modify-metadata-write-time", paths: ["*"], time: 8 } ] } } events: { long: [ { kind: "modify-data-content", paths: ["/watch/file-a"], time: 1 } { kind: "modify-data-content", paths: ["/watch/file-b"], time: 3 } { kind: "modify-data-content", paths: ["/watch/file-c"], time: 4 } { kind: "modify-metadata-write-time", paths: ["/watch/file-b"], time: 7 } { kind: "modify-metadata-write-time", paths: ["/watch/file-c"], time: 8 } { kind: "modify-metadata-write-time", paths: ["/watch/file-a"], time: 9 } ] } } } notify-debouncer-full-0.5.0/test_cases/emit_events_with_a_prepended_rename_event.hjson000064400000000000000000000027361046102023000277050ustar 00000000000000{ state: { timeout: 5 } events: [ { kind: "modify-data-content", paths: ["/watch/source"], time: 1 } { kind: "modify-data-content", paths: ["/watch/source"], time: 4 } { kind: "rename-from", paths: ["/watch/source"], tracker: 1, time: 7 } { kind: "rename-to", paths: ["/watch/target"], tracker: 1, time: 8 } { kind: "modify-metadata-write-time", paths: ["/watch/target"], time: 9 } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1, time: 7 } { kind: "modify-data-content", paths: ["*"], time: 1 } { kind: "modify-data-content", paths: ["*"], time: 4 } { kind: "modify-metadata-write-time", paths: ["*"], time: 9 } ] } } events: { 11: [] 12: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1, time: 7 } { kind: "modify-data-content", paths: ["/watch/target"], time: 4 } ] 14: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"], tracker: 1, time: 7 } { kind: "modify-data-content", paths: ["/watch/target"], time: 4 } { kind: "modify-metadata-write-time", paths: ["/watch/target"], time: 9 } ] } } } notify-debouncer-full-0.5.0/test_cases/emit_modify_event_after_close_event.hjson000064400000000000000000000021461046102023000265220ustar 00000000000000{ state: {} events: [ { kind: "modify-data-any", paths: ["/watch/file"], time: 1 } { kind: "access-close-write", paths: ["/watch/file"], time: 2 } { kind: "modify-data-any", paths: ["/watch/file"], time: 3 } { kind: "access-close-write", paths: ["/watch/file"], time: 4 } { kind: "modify-data-any", paths: ["/watch/file"], time: 5 } ] expected: { queues: { /watch/file: { events: [ { kind: "modify-data-any", paths: ["*"], time: 1 } { kind: "access-close-write", paths: ["*"], time: 2 } { kind: "modify-data-any", paths: ["*"], time: 3 } { kind: "access-close-write", paths: ["*"], time: 4 } { kind: "modify-data-any", paths: ["*"], time: 5 } ] } } events: { short: [] long: [ { kind: "access-close-write", paths: ["/watch/file"], time: 4 } { kind: "modify-data-any", paths: ["/watch/file"], time: 5 } ] } } } notify-debouncer-full-0.5.0/test_cases/emit_needs_rescan_event.hjson000064400000000000000000000026741046102023000241230ustar 00000000000000{ state: { queues: { /watch/file-a: { events: [ { kind: "create-any", paths: ["*"], time: 1 } ] } /watch/file-b: { events: [ { kind: "create-any", paths: ["*"], time: 2 } ] } } cache: { /watch/file-a: 1 /watch/file-b: 2 } file_system: { /watch/file-a: 1 /watch/file-b: 2 /watch/file-c: 3 } } events: [ { kind: "other", flags: ["rescan"], time: 3 } ] expected: { queues: { /watch/file-a: { events: [ { kind: "create-any", paths: ["*"], time: 1 } ] } /watch/file-b: { events: [ { kind: "create-any", paths: ["*"], time: 2 } ] } } rescan_event: { kind: "other", flags: ["rescan"], time: 3 } cache: { /watch/file-a: 1 /watch/file-b: 2 /watch/file-c: 3 } events: { short: [] long: [ { kind: "create-any", paths: ["/watch/file-a"], time: 1 } { kind: "create-any", paths: ["/watch/file-b"], time: 2 } { kind: "other", flags: ["rescan"], time: 3 } ] } } } notify-debouncer-full-0.5.0/test_cases/read_file_id_without_create_event.hjson000064400000000000000000000006361046102023000261440ustar 00000000000000{ state: { file_system: { /watch/file: 1 } } events: [ { kind: "modify-data-any", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "modify-data-any", paths: ["*"] } ] } } cache: { /watch/file: 1 } } } notify-debouncer-full-0.5.0/test_cases/sort_events_chronologically.hjson000064400000000000000000000024671046102023000250760ustar 00000000000000{ state: { queues: { /watch/file-1: { events: [ { kind: "create-any", paths: ["*"], time: 2 } { kind: "modify-any", paths: ["*"], time: 3 } ] } /watch/file-2: { events: [ { kind: "create-any", paths: ["*"], time: 1 } { kind: "modify-any", paths: ["*"], time: 4 } ] } } } expected: { queues: { /watch/file-1: { events: [ { kind: "create-any", paths: ["*"], time: 2 } { kind: "modify-any", paths: ["*"], time: 3 } ] } /watch/file-2: { events: [ { kind: "create-any", paths: ["*"], time: 1 } { kind: "modify-any", paths: ["*"], time: 4 } ] } } events: { long: [ { kind: "create-any", paths: ["/watch/file-2"], time: 1 } { kind: "create-any", paths: ["/watch/file-1"], time: 2 } { kind: "modify-any", paths: ["/watch/file-1"], time: 3 } { kind: "modify-any", paths: ["/watch/file-2"], time: 4 } ] } } } notify-debouncer-full-0.5.0/test_cases/sort_events_with_reordering.hjson000064400000000000000000000024641046102023000250760ustar 00000000000000{ state: { queues: { /watch/file-1: { events: [ { kind: "create-any", paths: ["*"], time: 2 } { kind: "modify-any", paths: ["*"], time: 3 } ] } /watch/file-2: { events: [ { kind: "rename-to", paths: ["*"], time: 4 } { kind: "modify-any", paths: ["*"], time: 1 } ] } } } expected: { queues: { /watch/file-1: { events: [ { kind: "create-any", paths: ["*"], time: 2 } { kind: "modify-any", paths: ["*"], time: 3 } ] } /watch/file-2: { events: [ { kind: "rename-to", paths: ["*"], time: 4 } { kind: "modify-any", paths: ["*"], time: 1 } ] } } events: { long: [ { kind: "create-any", paths: ["/watch/file-1"], time: 2 } { kind: "modify-any", paths: ["/watch/file-1"], time: 3 } { kind: "rename-to", paths: ["/watch/file-2"], time: 4 } { kind: "modify-any", paths: ["/watch/file-2"], time: 1 } ] } } }