1 parent
c9a52b73ac
commit
2d1d03db1e
22 files changed
+2040
-102
No files matched your search
@@ -0,0 +1,98 @@
|
||||
#include "echoion/host/FileWatcher.hpp"
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
|
||||
namespace Echoion::Host
|
||||
{
|
||||
|
||||
FileWatcher::FileWatcher() = default;
|
||||
|
||||
FileWatcher::~FileWatcher() { stopWatching(); }
|
||||
|
||||
void FileWatcher::startWatching(const std::filesystem::path& filePath,
|
||||
ChangeCallback callback,
|
||||
std::chrono::milliseconds intervalMs)
|
||||
{
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (watching_.load()) {
|
||||
stopWatching();
|
||||
}
|
||||
|
||||
watchedPath_ = filePath;
|
||||
callback_ = std::move(callback);
|
||||
intervalMs_ = intervalMs;
|
||||
stopRequested_ = false;
|
||||
|
||||
// Get initial file state
|
||||
if (std::filesystem::exists(watchedPath_)) {
|
||||
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
|
||||
lastFileSize_ = std::filesystem::file_size(watchedPath_);
|
||||
}
|
||||
|
||||
watching_ = true;
|
||||
watchThread_ = std::thread(&FileWatcher::watchLoop, this);
|
||||
}
|
||||
|
||||
void FileWatcher::stopWatching()
|
||||
{
|
||||
stopRequested_ = true;
|
||||
|
||||
if (watchThread_.joinable()) {
|
||||
watchThread_.join();
|
||||
}
|
||||
|
||||
watching_ = false;
|
||||
}
|
||||
|
||||
bool FileWatcher::isWatching() const noexcept { return watching_.load(); }
|
||||
|
||||
void FileWatcher::watchLoop()
|
||||
{
|
||||
while (!stopRequested_.load()) {
|
||||
// Sleep first to avoid checking immediately
|
||||
std::this_thread::sleep_for(intervalMs_);
|
||||
|
||||
if (stopRequested_.load()) {
|
||||
break;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (!std::filesystem::exists(watchedPath_)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
auto currentWriteTime =
|
||||
std::filesystem::last_write_time(watchedPath_);
|
||||
auto currentFileSize = std::filesystem::file_size(watchedPath_);
|
||||
|
||||
// Check if file has changed (time or size)
|
||||
if (currentWriteTime != lastWriteTime_ ||
|
||||
currentFileSize != lastFileSize_) {
|
||||
// Update stored values
|
||||
lastWriteTime_ = currentWriteTime;
|
||||
lastFileSize_ = currentFileSize;
|
||||
|
||||
// Trigger callback
|
||||
if (callback_) {
|
||||
try {
|
||||
callback_();
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr
|
||||
<< std::format("FileWatcher callback error: {}",
|
||||
e.what())
|
||||
<< '\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
// Ignore errors (file might be locked during write)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Host
|
||||
Reference in new issue
Block a user