1#ifndef FRAY_FILE_WATCHER_HPP
2#define FRAY_FILE_WATCHER_HPP
19#ifndef WIN32_LEAN_AND_MEAN
20#define WIN32_LEAN_AND_MEAN
64 const FileId& other)
const {
return !(*
this == other); }
84 const std::filesystem::path& path,
88 HANDLE handle = CreateFileW(path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
89 nullptr, OPEN_EXISTING,
90 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
nullptr);
91 if (handle == INVALID_HANDLE_VALUE)
93 BY_HANDLE_FILE_INFORMATION info;
94 const bool ok = GetFileInformationByHandle(handle, &info) != 0;
98 id.device = info.dwVolumeSerialNumber;
99 id.index = (
static_cast<std::uint64_t
>(info.nFileIndexHigh) << 32) | info.nFileIndexLow;
102 if (::lstat(path.c_str(), &status) != 0)
104 id.device =
static_cast<std::uint64_t
>(status.st_dev);
105 id.index =
static_cast<std::uint64_t
>(status.st_ino);
194 std::filesystem::file_time_type
time;
272 const std::filesystem::path& root)
275 std::error_code error;
276 std::filesystem::recursive_directory_iterator it(
277 root, std::filesystem::directory_options::skip_permission_denied, error), end;
278 for (; !error && it != end; it.increment(error))
280 std::error_code entryError;
281 const auto status = it->symlink_status(entryError);
285 entry.
directory = std::filesystem::is_directory(status);
290 entry.
size = it->is_regular_file(entryError) ? it->file_size(entryError) : 0;
291 entry.
time = std::filesystem::last_write_time(it->path(), entryError);
293 snapshot[it->path().lexically_relative(root).generic_string()] = entry;
305 const std::string& path,
306 const std::string& folder)
308 return path.size() > folder.size() && path.compare(0, folder.size(), folder) == 0 &&
309 path[folder.size()] ==
'/';
317 std::vector<Change>& changes)
322 for (
auto& change : changes)
323 _queue.push_back(std::move(change));
336 std::vector<Change>& changes)
const
338 std::map<FileId, std::string> added;
339 for (
const auto& entry : after)
340 if (before.find(entry.first) == before.end())
341 added[entry.second.id] = entry.first;
343 std::vector<std::pair<std::string, std::string>> folderRenames;
344 std::vector<Change> renames, removals, additions, modifications;
345 std::map<std::string, bool> matched;
346 for (
const auto& entry : before)
348 const auto now = after.find(entry.first);
349 if (now != after.end())
351 const Entry& was = entry.second;
352 const Entry& is = now->second;
360 modifications.push_back(std::move(change));
364 const auto moved = added.find(entry.second.id);
367 change.
directory = entry.second.directory;
368 if (moved == added.end())
371 removals.push_back(std::move(change));
377 change.
id = entry.second.id;
378 matched[moved->second] =
true;
381 renames.push_back(std::move(change));
383 for (
const auto& entry : after)
385 if (before.find(entry.first) != before.end() || matched.count(entry.first))
390 change.
directory = entry.second.directory;
391 change.
id = entry.second.id;
392 additions.push_back(std::move(change));
394 const std::size_t first = changes.size();
396 for (
auto& change : renames)
398 bool carried =
false;
399 for (
const auto& folder : folderRenames)
400 if (
inside(change.previousRelative, folder.first) &&
401 change.relative == folder.second + change.previousRelative.substr(folder.first.size()))
404 changes.push_back(std::move(change));
406 for (
auto* group : {&removals, &additions, &modifications})
407 for (
auto& change : *group)
408 changes.push_back(std::move(change));
409 for (std::size_t i = first; i < changes.size(); ++i)
411 Change& change = changes[i];
441 const std::filesystem::path& root)
443 std::lock_guard<std::recursive_mutex> lock(
_scan);
459 std::lock_guard<std::recursive_mutex> lock(
_scan);
468 std::unique_lock<std::recursive_mutex>
hold() {
return std::unique_lock<std::recursive_mutex>(
_scan); }
482 _subscribers.push_back({id, std::move(filter), std::move(handler)});
509 std::function<
void()> notify)
523 std::vector<Change> changes;
525 std::lock_guard<std::recursive_mutex> lock(
_scan);
532 std::filesystem::path moved;
533 std::error_code error;
534 std::filesystem::directory_iterator it(
_root.parent_path(), error), end;
535 for (; !error && it != end; it.increment(error))
554 changes.push_back(std::move(change));
561 changes.push_back(std::move(change));
568 return changes.size();
578 std::deque<Change> changes;
579 std::vector<Subscriber> subscribers;
585 for (
const auto& change : changes)
586 for (
const auto& subscriber : subscribers)
587 if (!subscriber.filter || subscriber.filter(change))
588 subscriber.handler(change);
589 return changes.size();
602 std::function<
void()> tick =
nullptr,
603 std::chrono::milliseconds interval = std::chrono::milliseconds(1000))
605 while (!token.
waitFor(interval))
607 const std::size_t changes =
poll();
612 std::function<void()> notify;
Cooperative cancellation shared by every copy of a token. Copies share one state guarded by an intern...
bool waitFor(const std::chrono::duration< Rep, Period > &duration) const
Sleeps for up to duration; returns true as soon as a stop is requested.
void unwatch()
Stops scanning and clears the snapshot under _scan; queued changes remain available.
void run(const threads::StopToken &token, std::function< void()> tick=nullptr, std::chrono::milliseconds interval=std::chrono::milliseconds(1000))
Polls repeatedly on the calling thread until the stop token signals. Intended for a ThreadManager thr...
FileWatcher & operator=(const FileWatcher &)=delete
Copy assignment is disabled for this synchronized watcher.
std::filesystem::path _root
Current watched root path, updated when the root is renamed.
std::unique_lock< std::recursive_mutex > hold()
Returns an owning _scan lock that blocks polling until released. Use around filesystem changes and a ...
std::vector< Subscriber > _subscribers
Registered subscribers, protected by _queueMutex.
void setNotify(std::function< void()> notify)
Replaces the run-loop notification callback under _queueMutex. run() copies and invokes it on the pol...
std::deque< Change > _queue
Pending changes awaiting dispatch, protected by _queueMutex.
std::mutex _queueMutex
Protects the change queue, subscribers, subscription counter and notify callback.
void diff(const Snapshot &before, const Snapshot &after, std::vector< Change > &changes) const
Appends changes between snapshots, suppressing child renames carried by a folder rename....
static bool inside(const std::string &path, const std::string &folder)
Tests whether a generic relative path is a strict descendant of a folder path.
std::map< std::string, Entry > Snapshot
Map of root-relative generic paths to scanned entry metadata.
std::size_t dispatch()
Drains queued changes and delivers them to a snapshot of subscribers on the calling thread....
Subscription subscribe(Filter filter, Handler handler)
Registers callbacks under _queueMutex for future dispatch snapshots.
std::function< bool(const Change &)> Filter
Predicate receiving a change and returning true to deliver it; an empty filter accepts all changes....
std::function< void()> _notify
Optional run-loop notification callback, protected by _queueMutex.
Subscription _nextSubscription
Next subscription identifier, protected by _queueMutex.
bool watch(const std::filesystem::path &root)
Starts or restarts watching with a silent baseline, also acknowledging owner-made changes....
std::function< void(const Change &)> Handler
Callback receiving a delivered change on the dispatch() caller’s thread. It runs without the queue mu...
FileWatcher()=default
Constructs an inactive watcher.
void unsubscribe(Subscription id)
Removes a subscription under _queueMutex, if present. A dispatch already holding a copied subscriber ...
void enqueue(std::vector< Change > &changes)
Moves changes into the pending queue while holding _queueMutex.
std::recursive_mutex _scan
Protects watch state and snapshots; hold() exposes a scoped lock for owner operations.
bool _watching
Whether polling has an active baseline.
std::uint64_t Subscription
Identifier used to unregister a subscriber.
static Snapshot scanFolder(const std::filesystem::path &root)
Scans a folder tree, skipping entries whose status or identity cannot be read. Iteration stops on an ...
std::size_t poll()
Compares the watched tree with its baseline and enqueues detected changes. Holds _scan during scannin...
Snapshot _snapshot
Most recent tree snapshot, protected by _scan.
FileWatcher(const FileWatcher &)=delete
Copy construction is disabled for this synchronized watcher.
FileId _rootId
Identity used to detect root removal or sibling rename.
ChangeKind
Identifies an added, removed, renamed or modified entry.
bool fileId(const std::filesystem::path &path, FileId &id)
Reads the entry identity without following a symbolic link.
Describes a detected change to the watched root or one of its entries.
std::filesystem::path previousPath
Previous path for a rename; root removals also record the old root here.
ChangeKind kind
Kind of change detected.
bool root
Whether the change describes the watched root itself.
std::filesystem::path path
Path of the changed entry when detected, based on the watched root.
FileId id
Entry identity when available; ordinary entry removals leave it unset.
std::string previousRelative
Previous root-relative entry path for a rename.
std::string relative
Entry path relative to the watched root, empty for root changes.
bool directory
Whether the changed entry is a directory.
Filesystem identity surviving renames: device and inode, or volume and file index.
std::uint64_t index
Inode number or file index.
bool operator!=(const FileId &other) const
Tests two identities for inequality.
bool operator<(const FileId &other) const
Orders identities by device and then index.
std::uint64_t device
Device number or volume serial number.
bool operator==(const FileId &other) const
Tests two identities for equality.
bool valid() const
Returns whether either identity component is nonzero.
Snapshot metadata for one filesystem entry.
std::filesystem::file_time_type time
Last-write time used for non-directory modification detection.
std::uintmax_t size
File size used for modification detection; zero for directories.
FileId id
Filesystem identity of the entry.
bool directory
Whether the entry is a directory.
Subscription identifier and callbacks copied for dispatch.
Filter filter
Optional predicate controlling delivery.
Subscription id
Identifier assigned at subscription.
Handler handler
Handler invoked for matching changes.