notify-debouncer-full-0.3.1/.cargo_vcs_info.json0000644000000001630000000000100152510ustar { "git": { "sha1": "4a001215b36d90585c555b0d0a01c9321b003b9e" }, "path_in_vcs": "notify-debouncer-full" }notify-debouncer-full-0.3.1/Cargo.toml0000644000000033110000000000100132450ustar # 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.60" name = "notify-debouncer-full" version = "0.3.1" 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" resolver = "1" [lib] name = "notify_debouncer_full" path = "src/lib.rs" [dependencies.crossbeam-channel] version = "0.5" optional = true [dependencies.file-id] version = "0.2.1" [dependencies.log] version = "0.4.17" [dependencies.notify] version = "6.1.1" [dependencies.parking_lot] version = "0.12.1" [dependencies.walkdir] version = "2.2.2" [dev-dependencies.deser-hjson] version = "1.1.1" [dev-dependencies.mock_instant] version = "0.3.0" [dev-dependencies.pretty_assertions] version = "1.3.0" [dev-dependencies.rand] version = "0.8.5" [dev-dependencies.rstest] version = "0.17.0" [dev-dependencies.serde] version = "1.0.89" features = ["derive"] [features] crossbeam = [ "crossbeam-channel", "notify/crossbeam-channel", ] default = ["crossbeam"] notify-debouncer-full-0.3.1/Cargo.toml.orig000064400000000000000000000023660072674642500167670ustar 00000000000000[package] name = "notify-debouncer-full" version = "0.3.1" edition = "2021" rust-version = "1.60" description = "notify event debouncer optimized for ease of use" documentation = "https://docs.rs/notify-debouncer-full" homepage = "https://github.com/notify-rs/notify" repository = "https://github.com/notify-rs/notify.git" authors = ["Daniel Faust "] keywords = ["events", "filesystem", "notify", "watch"] license = "MIT OR Apache-2.0" readme = "README.md" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] name = "notify_debouncer_full" path = "src/lib.rs" [features] default = ["crossbeam"] # can't use dep:crossbeam-channel and feature name crossbeam-channel below rust 1.60 crossbeam = ["crossbeam-channel","notify/crossbeam-channel"] [dependencies] notify = { version = "6.1.1", path = "../notify" } crossbeam-channel = { version = "0.5", optional = true } file-id = { version = "0.2.1", path = "../file-id" } walkdir = "2.2.2" parking_lot = "0.12.1" log = "0.4.17" [dev-dependencies] pretty_assertions = "1.3.0" mock_instant = "0.3.0" rstest = "0.17.0" serde = { version = "1.0.89", features = ["derive"] } deser-hjson = "1.1.1" rand = "0.8.5" notify-debouncer-full-0.3.1/LICENSE-APACHE000064400000000000000000000254400072674642500160220ustar 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.3.1/LICENSE-MIT000064400000000000000000000021000072674642500155160ustar 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.3.1/README.md000064400000000000000000000023030072674642500153460ustar 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 stiches 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` enabled by default, for crossbeam channel support. This may create problems used in tokio environments. See [#380](https://github.com/notify-rs/notify/issues/380). Use someting like the following to disable it. ```toml notify-debouncer-full = { version = "*", default-features = false } ``` This also passes through to notify as `crossbeam-channel` feature. [docs]: https://docs.rs/notify-debouncer-full [notify]: https://crates.io/crates/notify notify-debouncer-full-0.3.1/src/cache.rs000064400000000000000000000103100072674642500162640ustar 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); /// 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 paths. /// /// This will be called if the notification back-end has dropped events. fn rescan(&mut self); } /// 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, roots: Vec<(PathBuf, RecursiveMode)>, } impl FileIdMap { /// Construct an empty cache. pub fn new() -> Self { Default::default() } /// Add a path to the cache. /// /// If `recursive_mode` is `Recursive`, all children will be added to the cache as well /// and all paths will be kept up-to-date in case of changes like new files being added, /// files being removed or renamed. pub fn add_root(&mut self, path: impl Into, recursive_mode: RecursiveMode) { let path = path.into(); self.roots.push((path.clone(), recursive_mode)); self.add_path(&path); } /// Remove a path form the cache. /// /// If the path was added with `Recursive` mode, all children will also be removed from the cache. pub fn remove_root(&mut self, path: impl AsRef) { self.roots.retain(|(root, _)| !root.starts_with(&path)); self.remove_path(path.as_ref()); } fn dir_scan_depth(is_recursive: bool) -> usize { if is_recursive { usize::max_value() } 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) { let is_recursive = self .roots .iter() .find_map(|(root, recursive_mode)| { if path.starts_with(root) { Some(*recursive_mode == RecursiveMode::Recursive) } else { None } }) .unwrap_or_default(); 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)); } fn rescan(&mut self) { for (root, _) in self.roots.clone() { self.add_path(&root); } } } /// 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. pub struct NoCache; impl FileIdCache for NoCache { fn cached_file_id(&self, _path: &Path) -> Option<&FileId> { None } fn add_path(&mut self, _path: &Path) {} fn remove_path(&mut self, _path: &Path) {} fn rescan(&mut self) {} } notify-debouncer-full-0.3.1/src/debounced_event.rs000064400000000000000000000021460072674642500203620ustar 00000000000000use std::ops::{Deref, DerefMut}; #[cfg(test)] use mock_instant::Instant; #[cfg(not(test))] use std::time::Instant; use notify::Event; /// A debounced event is emitted after a short delay. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DebouncedEvent { /// The original event. pub event: Event, /// The time at which the event occurred. pub time: Instant, } impl DebouncedEvent { pub fn new(event: Event, time: Instant) -> Self { Self { event, time } } } impl Deref for DebouncedEvent { type Target = Event; fn deref(&self) -> &Self::Target { &self.event } } impl DerefMut for DebouncedEvent { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.event } } impl Default for DebouncedEvent { fn default() -> Self { Self { event: Default::default(), time: Instant::now(), } } } impl From for DebouncedEvent { fn from(event: Event) -> Self { Self { event, time: Instant::now(), } } } notify-debouncer-full-0.3.1/src/lib.rs000064400000000000000000000646110072674642500160040ustar 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 stiches 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 //! //! # Installation //! //! ```toml //! [dependencies] //! notify-debouncer-full = "0.3.1" //! ``` //! //! 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.3.1" //! 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.watcher().watch(Path::new("."), RecursiveMode::Recursive).unwrap(); //! //! // Add the same path to the file ID cache. The 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. //! debouncer.cache().add_root(Path::new("."), RecursiveMode::Recursive); //! ``` //! //! # Features //! //! The following crate features can be turned on or off in your cargo dependency config: //! //! - `crossbeam` enabled by default, adds [`DebounceEventHandler`](DebounceEventHandler) support for crossbeam channels. //! Also enables crossbeam-channel in the re-exported notify. You may want to disable this when using the tokio async runtime. //! - `serde` enables serde support for events. //! //! # 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 debounced_event; #[cfg(test)] mod testing; use std::{ collections::{HashMap, VecDeque}, path::PathBuf, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Duration, }; pub use cache::{FileIdCache, FileIdMap, NoCache}; pub use debounced_event::DebouncedEvent; pub use file_id; pub use notify; use file_id::FileId; use notify::{ event::{ModifyKind, RemoveKind, RenameMode}, Error, ErrorKind, Event, EventKind, RecommendedWatcher, Watcher, }; use parking_lot::{MappedMutexGuard, Mutex, MutexGuard}; #[cfg(test)] use mock_instant::Instant; #[cfg(not(test))] use std::time::Instant; /// 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")] 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, 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(), 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 = Instant::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); } } // 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; // order events for different files chronologically, but keep the order of events for the same file events_expired.sort_by(|event_a, event_b| { // use the last path because rename events are emitted for the target path if event_a.paths.last() == event_b.paths.last() { std::cmp::Ordering::Equal } else { event_a.time.cmp(&event_b.time) } }); events_expired } /// Returns all currently stored errors pub fn errors(&mut self) -> Vec { let mut v = Vec::new(); std::mem::swap(&mut v, &mut self.errors); v } /// Add an error entry to re-send later on pub fn add_error(&mut self, 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.rescan_event = Some(event.into()); return; } let path = &event.paths[0]; match &event.kind { EventKind::Create(_) => { self.cache.add_path(path); self.push_event(event, Instant::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, Instant::now()); } EventKind::Other => { // ignore meta events } _ => { if self.cache.cached_file_id(path).is_none() { self.cache.add_path(path); } self.push_event(event, Instant::now()); } } } fn handle_rename_from(&mut self, event: Event) { let time = Instant::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) { self.cache.add_path(&event.paths[0]); 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, Instant::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); } /// Access to the internally used notify Watcher backend pub fn watcher(&mut self) -> &mut T { &mut self.watcher } /// Access to the internally used notify Watcher backend pub fn cache(&mut self) -> MappedMutexGuard { MutexGuard::map(self.data.lock(), |data| &mut data.cache) } } 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(); 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(); 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, FileIdMap::new(), notify::Config::default(), ) } #[cfg(test)] mod tests { use std::{fs, path::Path}; use super::*; use mock_instant::MockClock; use pretty_assertions::assert_eq; use rstest::rstest; use testing::TestCase; #[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" )] 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(); MockClock::set_time(Duration::default()); let time = Instant::now(); let mut state = test_case.state.into_debounce_data_inner(time); for event in test_case.events { let event = event.into_debounced_event(time, None); MockClock::set_time(event.time - time); state.add_event(event.event); } for error in test_case.errors { let e = error.into_notify_error(); state.add_error(e); } 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 = Instant::now().duration_since(time); let backup_queues = state.queues.clone(); for (delay, events) in expected_events { MockClock::set_time(backup_time); state.queues = backup_queues.clone(); match delay.as_str() { "none" => {} "short" => MockClock::advance(Duration::from_millis(10)), "long" => MockClock::advance(Duration::from_millis(100)), _ => { if let Ok(ts) = delay.parse::() { let ts = time + Duration::from_millis(ts); MockClock::set_time(ts - time); } } } 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" ); } } } notify-debouncer-full-0.3.1/src/testing.rs000064400000000000000000000253400072674642500167070ustar 00000000000000use std::{ collections::{HashMap, VecDeque}, path::{Path, PathBuf}, time::Duration, }; use file_id::FileId; use mock_instant::Instant; use notify::{ event::{ AccessKind, AccessMode, CreateKind, DataChange, Flag, MetadataKind, ModifyKind, RemoveKind, RenameMode, }, Error, ErrorKind, Event, EventKind, }; 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, 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) { for (p, file_id) in &self.file_system { if p.starts_with(path) { self.paths.insert(p.clone(), file_id.clone()); } } } fn remove_path(&mut self, path: &Path) { self.paths.remove(path); } fn rescan(&mut self) { self.add_path(&Path::new("/")) } } notify-debouncer-full-0.3.1/test_cases/add_create_dir_event_twice.hjson000064400000000000000000000012170072674642500245770ustar 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.3.1/test_cases/add_create_event.hjson000064400000000000000000000011310072674642500225410ustar 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.3.1/test_cases/add_create_event_after_remove_event.hjson000064400000000000000000000010350072674642500265030ustar 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.3.1/test_cases/add_errors.hjson000064400000000000000000000004530072674642500214170ustar 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.3.1/test_cases/add_modify_content_event_after_create_event.hjson000064400000000000000000000013200072674642500302240ustar 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.3.1/test_cases/add_remove_event.hjson000064400000000000000000000004540072674642500226020ustar 00000000000000{ state: {} events: [ { kind: "remove-any", paths: ["/watch/file"] } ] expected: { queues: { /watch/file: { events: [ { kind: "remove-any", paths: ["*"] } ] } } } } notify-debouncer-full-0.3.1/test_cases/add_remove_event_after_create_and_modify_event.hjson000064400000000000000000000005530072674642500307000ustar 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.3.1/test_cases/add_remove_event_after_create_event.hjson000064400000000000000000000004540072674642500265070ustar 00000000000000{ state: { queues: { /watch/file: { events: [ { kind: "create-any", paths: ["*"] } ] } } } events: [ { kind: "remove-any", paths: ["/watch/file"] } ] expected: {} } notify-debouncer-full-0.3.1/test_cases/add_remove_event_after_modify_event.hjson000064400000000000000000000007500072674642500265320ustar 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.3.1/test_cases/add_remove_parent_event_after_remove_child_event.hjson000064400000000000000000000010400072674642500312450ustar 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.3.1/test_cases/add_rename_both_event.hjson000064400000000000000000000002110072674642500235570ustar 00000000000000{ state: {} events: [ { kind: "rename-both", paths: ["/watch/source", "/watch/target"] } ] expected: {} } notify-debouncer-full-0.3.1/test_cases/add_rename_from_and_to_event.hjson000064400000000000000000000006540072674642500251250ustar 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.3.1/test_cases/add_rename_from_and_to_event_after_create.hjson000064400000000000000000000010730072674642500276250ustar 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.3.1/test_cases/add_rename_from_and_to_event_after_modify_content.hjson000064400000000000000000000012610072674642500314020ustar 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.3.1/test_cases/add_rename_from_and_to_event_after_rename.hjson000064400000000000000000000012550072674642500276330ustar 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.3.1/test_cases/add_rename_from_and_to_event_override_created.hjson000064400000000000000000000011450072674642500305070ustar 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.3.1/test_cases/add_rename_from_and_to_event_override_modified.hjson000064400000000000000000000016130072674642500306600ustar 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.3.1/test_cases/add_rename_from_and_to_event_override_removed.hjson000064400000000000000000000012370072674642500305430ustar 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.3.1/test_cases/add_rename_from_and_to_event_with_different_file_ids.hjson000064400000000000000000000012740072674642500320430ustar 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.3.1/test_cases/add_rename_from_and_to_event_with_different_tracker.hjson000064400000000000000000000010570072674642500317170ustar 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.3.1/test_cases/add_rename_from_and_to_event_with_file_ids.hjson000064400000000000000000000011050072674642500300060ustar 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.3.1/test_cases/add_rename_from_event.hjson000064400000000000000000000005730072674642500236010ustar 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.3.1/test_cases/add_rename_from_event_after_create_and_modify_event.hjson000064400000000000000000000013440072674642500316740ustar 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.3.1/test_cases/add_rename_from_event_after_create_event.hjson000064400000000000000000000011460072674642500275030ustar 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.3.1/test_cases/add_rename_from_event_after_modify_event.hjson000064400000000000000000000011600072674642500275230ustar 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.3.1/test_cases/add_rename_from_event_after_rename_from_event.hjson000064400000000000000000000014240072674642500305310ustar 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.3.1/test_cases/add_rename_to_dir_event.hjson000064400000000000000000000007700072674642500241150ustar 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.3.1/test_cases/add_rename_to_event.hjson000064400000000000000000000004560072674642500232600ustar 00000000000000{ state: {} events: [ { kind: "rename-to", paths: ["/watch/target"] } ] expected: { queues: { /watch/target: { events: [ { kind: "rename-to", paths: ["*"] } ] } } } } notify-debouncer-full-0.3.1/test_cases/emit_close_events_only_once.hjson000064400000000000000000000017660072674642500250570ustar 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.3.1/test_cases/emit_continuous_modify_content_events.hjson000064400000000000000000000030760072674642500272100ustar 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.3.1/test_cases/emit_events_in_chronological_order.hjson000064400000000000000000000036250072674642500264050ustar 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.3.1/test_cases/emit_events_with_a_prepended_rename_event.hjson000064400000000000000000000030020072674642500277170ustar 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.3.1/test_cases/emit_modify_event_after_close_event.hjson000064400000000000000000000022040072674642500265440ustar 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.3.1/test_cases/emit_needs_rescan_event.hjson000064400000000000000000000027640072674642500241520ustar 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.3.1/test_cases/read_file_id_without_create_event.hjson000064400000000000000000000006640072674642500261740ustar 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 } } }